From timr at probo.com Sat May 1 00:29:05 2010 From: timr at probo.com (Tim Roberts) Date: Fri, 30 Apr 2010 21:29:05 -0700 Subject: winreg - access mask References: Message-ID: Richard Lamboj wrote: > >if i want to read, write a key and set a value, does i only need to set >KEY_WRITE, or does i need to set KEY_READ, KEY_WRITE and KEY_SET_VALUE? > >This questions is related to the OpenKey Function. You need KEY_READ|KEY_WRITE|KEY_SET_VALUE. Those constants are straight from the Windows API. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From pmaupin at gmail.com Sat May 1 01:08:14 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 30 Apr 2010 22:08:14 -0700 (PDT) Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: On Apr 30, 11:04?am, Jabapyth wrote: > At least a few times a day I wish python had the following shortcut > syntax: > > vbl.=func(args) > > this would be equivalent to > > vbl = vbl.func(args) > > example: > > foo = "Hello world" > foo.=split(" ") > print foo > # ['Hello', 'world'] > > and I guess you could generalize this to > > vbl.=[some text] > # > vbl = vbl.[some text] > > e.g. > > temp.=children[0] > # temp = temp.children[0] > > thoughts? First thought: good luck getting something like this through. Probably not going to happen, although I do find the idea very intriguing. Second thought: I don't like the proposed syntax at all. +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- place operator methods, actually) *modify* the lhs object. Your proposed .= syntax conceptually *replaces* the lhs object (actually, rebinds the lhs symbol to the new object). If this were to be deemed worthy of the language, I would think a better syntax would be something like: mystring = .upper() mystring = .replace('a', 'b') etc. The '=' shows clearly that mystring is being rebound to a new object. As Steven has shown, '.' functions as an operator, so if this change were accepted, in reality you would probably be able to write: mystring = . upper() mystring=.upper() or whatever. But the canonical form would probably be with a space before the period but not after. Regards, Pat From simonluijk at googlemail.com Sat May 1 02:03:30 2010 From: simonluijk at googlemail.com (Simon) Date: Sat, 1 May 2010 08:03:30 +0200 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: Hay I got a better idea. If you put two dots (..) on a line by itself it means execute the previous line again! On 1 May 2010 07:08, Patrick Maupin wrote: > On Apr 30, 11:04 am, Jabapyth wrote: > > At least a few times a day I wish python had the following shortcut > > syntax: > > > > vbl.=func(args) > > > > this would be equivalent to > > > > vbl = vbl.func(args) > > > > example: > > > > foo = "Hello world" > > foo.=split(" ") > > print foo > > # ['Hello', 'world'] > > > > and I guess you could generalize this to > > > > vbl.=[some text] > > # > > vbl = vbl.[some text] > > > > e.g. > > > > temp.=children[0] > > # temp = temp.children[0] > > > > thoughts? > > First thought: good luck getting something like this through. > Probably not going to happen, although I do find the idea very > intriguing. > > Second thought: I don't like the proposed syntax at all. > > +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- > place operator methods, actually) *modify* the lhs object. > > Your proposed .= syntax conceptually *replaces* the lhs object > (actually, rebinds the lhs symbol to the new object). > > If this were to be deemed worthy of the language, I would think a > better syntax would be something like: > > mystring = .upper() > mystring = .replace('a', 'b') > > etc. > > The '=' shows clearly that mystring is being rebound to a new object. > > As Steven has shown, '.' functions as an operator, so if this change > were accepted, in reality you would probably be able to write: > > mystring = . upper() > mystring=.upper() > > or whatever. But the canonical form would probably be with a space > before the period but not after. > > Regards, > Pat > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Sat May 1 02:27:46 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 01 May 2010 08:27:46 +0200 Subject: Ignoring XML Namespaces with cElementTree In-Reply-To: References: <9527079b-92bf-4c59-af2b-ab2c84029f55@h37g2000pra.googlegroups.com> Message-ID: dmtr, 30.04.2010 23:59: >> I think that's your main mistake: don't remove them. Instead, use the fully >> qualified names when comparing. > > Yes. That's what I'm forced to do. Pre-calculating tags like tagChild > = "{%s}child" % uri and using them instead of "child". Exactly. Keeps you from introducing typos in your code. And keeps you from having to deal with namespace-prefix mappings. Big features. > As a result the > code looks ugly and there is extra overhead concatenating/comparing > these repeating and redundant prefixes. The overhead is really small, though. In many cases, a pointer comparison will do. > I don't understand why > cElementTree forces users to do that. So far I couldn't find any way > around that without rebuilding cElementTree from source. Then don't do it. > Apparently somebody hard-coded the namespace_separator parameter in > the cElementTree.c (what a dumb thing to do!!!, it should have been a > parameter in the cElementTree.XMLParser() arguments): > =========== > self->parser = EXPAT(ParserCreate_MM)(encoding,&memory_handler, "}"); > =========== > > Simply replacing "}" with NULL gives me desired tags without stinking > URIs. You should try to calm down and embrace this feature. Stefan From shashank.sunny.singh at gmail.com Sat May 1 02:31:56 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Sat, 1 May 2010 12:01:56 +0530 Subject: No subject In-Reply-To: <20100501033354.30222.qmail@f4mail-234-119.rediffmail.com> References: <20100501033354.30222.qmail@f4mail-234-119.rediffmail.com> Message-ID: Here is my quick take on it using re import re strings = ["1 ALA Helix Sheet Helix Coil", "2 ALA Coil Coil Coil Sheet", "3 ALA Helix Sheet Coil Turn", "4 ALA Helix Sheet Helix Sheet"] regex = re.compile(r" (.+?\b)(?=.*\1)") for s in strings: moreThanOnce = list(set(regex.findall(s))) count = len(moreThanOnce) if count == 1: print moreThanOnce[0] elif count == 2: print "doubtful" else: print "error" Although this is short, its probably not the most efficient. A more verbose and efficient version would be for s in strings: l = s.split()[2:] counts = {} for ss in l: if counts.has_key(ss): counts[ss] += 1 else: counts[ss] = 1 filtered = [ss for ss in counts if counts[ss] >= 2] filteredCount = len(filtered) if filteredCount == 1: print filtered[0] elif filteredCount > 1: print "doubtful" else: print "error" HTH On Sat, May 1, 2010 at 9:03 AM, mannu jha wrote: > Dear all, > > I am trying my problem in this way: > > import re > expr = re.compile("Helix Helix| Sheet Sheet| Turn Turn| Coil Coil") > f = open("CalcSecondary4.txt") > for line in f: > if expr.search(line): > print line > > but with this it is printing only those line in which helix, sheet, turn > and coil are coming twice. Kindly suggest how should I modify it so that > whatever secondary structure is coming more than or equal to two times it > should write that as final secondary structure and if two seconday structure > are coming two-two times in one line itself like: > > 4 ALA Helix Sheet Helix Sheet > > then it should write that as doubtful and rest it should write as error. > > Thanks, > > > Dear all, > > I have a file like: > > 1 ALA Helix Sheet Helix Coil > 2 ALA Coil Coil Coil Sheet > 3 ALA Helix Sheet Coil Turn > > now what I want is that write a python program in which I will put the > condition that in each line whatever secondary structure is coming more than > or equal to two times it should write that as final secondary structure and > if two seconday structure are coming two-two times in one line itself like: > > 4 ALA Helix Sheet Helix Sheet > > then it should write that as doubtful and rest it should write as error. > > Thanks, > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From bestomegawatch at yahoo.com Sat May 1 03:18:33 2010 From: bestomegawatch at yahoo.com (Jack) Date: Sat, 1 May 2010 15:18:33 +0800 Subject: External Hashing [was Re: matching strings in a large set of strings] References: <840jkoFaibU1@mid.dfncis.de> Message-ID: http://www.swizwatch.com/ All Cartier replica watches sold at Hotwristwatch.com are brand-new and high quality. Each Cartier Replica Watch produced is examined carefully by our quality test department and each watch is inspected again before being sent to our customer. It is our desire that you do experience the joy of shopping when buying one of our Cartier Replica Watches at our site. Some Cartier Watches may need to be special ordered, please call for availability on Cartier watches. Best service you will receive from us. "Helmut Jarausch" ??????:840jkoFaibU1 at mid.dfncis.de... >I think one could apply an external hashing technique which would require >only > very few disk accesses per lookup. > Unfortunately, I'm now aware of an implementation in Python. > Does anybody know about a Python implementation of external hashing? > > Thanks, > Helmut. > > -- > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany From onlinejobsatfreetime at gmail.com Sat May 1 04:10:27 2010 From: onlinejobsatfreetime at gmail.com (online jobs) Date: Sat, 1 May 2010 01:10:27 -0700 (PDT) Subject: Online survey jobs & data entry jobs Message-ID: <8ff9c401-815f-4abb-b573-3ddae2f858de@n37g2000prc.googlegroups.com> http://teluguscope.com/job.html http://teluguscope.com/links/onlinedataentryjobs.html http://teluguscope.com/links/Copy%20Past%20jobs.html http://teluguscope.com/links/Work%20from%20Home.html http://teluguscope.com/links/Formfilling%20jobs.html http://teluguscope.com/links/Survey%20Jobs.html From mkmax2 at gmail.com Sat May 1 04:33:04 2010 From: mkmax2 at gmail.com (Andrew) Date: Sat, 1 May 2010 01:33:04 -0700 (PDT) Subject: Cheap Software Offers! Message-ID: We have best software prices, visit us at http://cheaphsoft4u.com/?rid=107 From pavlovevidence at gmail.com Sat May 1 06:17:32 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 1 May 2010 03:17:32 -0700 (PDT) Subject: Ignoring XML Namespaces with cElementTree References: <9527079b-92bf-4c59-af2b-ab2c84029f55@h37g2000pra.googlegroups.com> Message-ID: <7305286c-cc77-48cb-bd9b-22b2eb35ae5d@y18g2000prn.googlegroups.com> On Apr 27, 6:42?pm, dmtr wrote: > Is there any way to configure cElementTree to ignore the XML root > namespace? ?Default cElementTree (Python 2.6.4) appears to add the XML > root namespace URI to _every_ single tag. ?I know that I can strip > URIs manually, from every tag, but it is a rather idiotic thing to do > (performance wise). Perhaps upgrade to lxml. Not sure if gives you control over namespace expansion but if it doesn't it should at least be faster. For this and some other reasons, I find ElementTree not quite as handy when processing files from another source as when I'm saving and retrieving my own data. Carl Banks From pavlovevidence at gmail.com Sat May 1 06:33:57 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 1 May 2010 03:33:57 -0700 (PDT) Subject: Ignoring XML Namespaces with cElementTree References: <9527079b-92bf-4c59-af2b-ab2c84029f55@h37g2000pra.googlegroups.com> Message-ID: <7a4f1818-e77a-4238-b021-3e2c6da836ae@a18g2000prd.googlegroups.com> On Apr 29, 10:12?pm, Stefan Behnel wrote: > dmtr, 30.04.2010 04:57: > > > > > I'm referring to xmlns/URI prefixes. Here's a code example: > > ? from xml.etree.cElementTree import iterparse > > ? from cStringIO import StringIO > > ? xml = """ > root>""" > > ? for event, elem in iterparse(StringIO(xml)): print event, elem > > > The output is: > > ? end > > ? end > > > I don't want these "{http://www.very_long_url.com}" in front of my > > tags. > > > They create performance disaster on large files > > I seriously doubt that they do. I don't know what kind of XML files you deal with, but for me a large XML file is gigabyte-sized (obviously I don't use Element Tree for those). Even for files tens-of-megabyte files string ops to expand tags with namespaces is going to be a pretty decent penalty--remember ElementTree does nothing lazily. > > (first cElementTree > > adds them, then I have to remove them in python). > > I think that's your main mistake: don't remove them. Instead, use the fully > qualified names when comparing. Unless you have multiple namespaces or are working with defined schema or something, it's useless boilerplate. It'd be a nice feature if ElementTree could let users optionally ignore a namespace, unfortunately it doesn't have it. Carl Banks From dodo_do_not_wake_up at yahoo.Fr Sat May 1 06:52:01 2010 From: dodo_do_not_wake_up at yahoo.Fr (Dodo) Date: Sat, 01 May 2010 12:52:01 +0200 Subject: CGI python 3 write RAW BINARY In-Reply-To: References: <4bd8ae7e$0$27615$ba4acef3@reader.news.orange.fr> <4bd96540$0$27597$ba4acef3@reader.news.orange.fr> <4bd9b4c2$0$27606$ba4acef3@reader.news.orange.fr> <4bd9fc1a$0$2980$ba4acef3@reader.news.orange.fr> Message-ID: <4bdc07d4$0$2980$ba4acef3@reader.news.orange.fr> Le 30/04/2010 17:52, Antoine Pitrou a ?crit : > Le Thu, 29 Apr 2010 23:37:32 +0200, Dodo a ?crit : >> ....I don't get a thing. >> Now with the fix : >> All browsers shows a different thing, but not the image! >> http://ddclermont.homeip.net/misc/python/ >> >> If I save it to computer : >> * Windows image viewer won't read it >> * Irfanview can read it without problems > > Did you set the content-type and content-length in the HTTP headers? > Can you post your code? > > I didn't know about content-lenght Here's the new code (I used a fixed image patch to make sure this is not the source of the problem) #!/usr/bin/python3 import cgi, sys, cgitb cgitb.enable() f = open("/home/dodo/54.jpg", "rb") data = f.read() l = len(data) f.close() print("Content-type:image/jpg\nContent-length:%d\n\n" % l) sys.stdout.flush() sys.stdout.buffer.write( data ) Dorian From ben+python at benfinney.id.au Sat May 1 06:55:24 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 May 2010 20:55:24 +1000 Subject: Python daemonisation with python-daemon References: <7ed4c441-78b2-4452-a814-ba2306152236@k29g2000yqh.googlegroups.com> Message-ID: <87ljc3howz.fsf@benfinney.id.au> Thomas Courbon writes: > I would like to turn my server script into a Linux/Unix daemon > (launched at boot time by init, dunno if that matter) using the nice > python-daemon package by Ben Finley et al I resemble that name :-) > This package comes with a class DaemonRunner that seems to fit almost > exactly my need but I still have some interrogation. Yes, that class is unlikely to grow much beyond a simple example of how to use ?DaemonContext?. You should feel free to take ?DaemonRunner? under the granted license and adapt it to be closer to what you want. > The DaemonRunner class expects my class to have stdin_path, > stdout_path, stderr_path attributes and after reading the code it > seems they have to be valid paths. Is that ok for a Daemon to redirect > those stream to /dev/null for example ? I would prefer to alter the > DaemonRunner class to accept None as value since DaemonContext, the > underlying class, seems to accept None for those parameters. This is a godd idea, allowing a more minimal use of ?DaemonRunner?. I'll take this as a feature request for a future revision of the class. > Also, the DaemonRunner use os.kill(pid, signal.SIGTERM) to stop the > daemon. I wonder if with my signal handling I'll be able to terminate > correctly the daemon (joining children, flushing buffers, closing > connections...). If that's relevant, the connection I use is a > Listener/Client connection from the standard multiprocessing module. I'll be interested to know too :-) > I'm quite neophyte in Unix daemon programming so please forgive me if > my question are obvious. Thank you for your feedback, and I hope the ?python-daemon? library continues to meet your needs. -- \ ?In the long run, the utility of all non-Free software | `\ approaches zero. All non-Free software is a dead end.? ?Mark | _o__) Pilgrim, 2006 | Ben Finney From jason.heeris at gmail.com Sat May 1 07:04:09 2010 From: jason.heeris at gmail.com (Jason) Date: Sat, 1 May 2010 04:04:09 -0700 (PDT) Subject: PyObject_SetAttrString - doesn't set instance attribute Message-ID: <82ae0f7b-e5f4-4b85-a9fb-aef16de10af2@a39g2000prb.googlegroups.com> I'm having a bit of trouble with C/Python bindings. Particularly, trying to set an instance variable from C when the object is initialised using PyObject_SetAttrString, but nothing seems to happen. The C initialisation code is: static void nautilus_python_object_instance_init (NautilusPythonObject *object) { fprintf(stderr, "nautilus_python_object_instance_init called\n"); NautilusPythonObjectClass *class; debug_enter(); class = (NautilusPythonObjectClass*)(((GTypeInstance*)object)- >g_class); object->instance = PyObject_CallObject(class->type, NULL); PyObject* test_int = PyInt_FromLong(42); if (object->instance == NULL) { PyErr_Print(); } else { fprintf(stderr, "Setting magic parameter\n"); fprintf(stderr, "From C: "); PyObject_Print(object->instance, stderr, 0); fprintf(stderr, "\n"); int retval = PyObject_SetAttrString(object->instance, "super_happy_magic", test_int); fprintf(stderr, "Result: %i\n", retval); } Py_DECREF(test_int); } ...and the Python module contains: class MenuProviderTest(nautilus.MenuProvider): def __init__(self): print "From Python: %s" % self try: print getattr(self, "super_happy_magic") except AttributeError: print "Didn't work!" When the MenuProviderTest is created, the output is: nautilus_python_object_instance_init called Setting magic parameter >From C: Result: 0 >From Python: Didn't work! (I've tried getattr and self.super_happy_magic, with the same effect.) Where am I going wrong? ? Jason From news1234 at free.fr Sat May 1 07:48:02 2010 From: news1234 at free.fr (News123) Date: Sat, 01 May 2010 13:48:02 +0200 Subject: matching strings in a large set of strings In-Reply-To: References: Message-ID: <4BDC14F2.2050603@free.fr> Dennis Lee Bieber wrote: > On Thu, 29 Apr 2010 11:38:28 +0200, "Karin Lagesen" > declaimed the following in comp.lang.python: > >> Hello. >> >> I have approx 83 million strings, all 14 characters long. I need to be >> able to take another string and find out whether this one is present >> within the 83 million strings. >> >> > So don't load them into memory... First use a file-based (not memory > > > That lets you do a binary search on the file. Much faster than a > linear search (linear search will average out to 41.5M read operations; > binary should be around 10000 reads) Don't you meant 27 reads instead of 41.5 M reads? >>> from math import log >>> log(83e6)/log(2) 26.306608000671101 >>> N From walter.overby at gmail.com Sat May 1 07:59:17 2010 From: walter.overby at gmail.com (Walter Overby) Date: Sat, 1 May 2010 04:59:17 -0700 (PDT) Subject: Use Regular Expressions to extract URL's References: <0760f79c-aa63-43c7-a845-339c6abcc702@g39g2000pri.googlegroups.com> <4bda9ce2$0$8757$c3e8da3@news.astraweb.com> Message-ID: A John Gruber post from November seems relevant. I have not tried his regex in any language. http://daringfireball.net/2009/11/liberal_regex_for_matching_urls Regards, Walter. From tim at thechases.com Sat May 1 08:13:42 2010 From: tim at thechases.com (Tim Chase) Date: Sat, 01 May 2010 07:13:42 -0500 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: <4BDC1AF6.3070505@thechases.com> On 05/01/2010 12:08 AM, Patrick Maupin wrote: > +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- > place operator methods, actually) *modify* the lhs object. > > Your proposed .= syntax conceptually *replaces* the lhs object > (actually, rebinds the lhs symbol to the new object). The += family of operators really do rebind the symbol, not modify the object. >>> from decimal import Decimal >>> d = Decimal(42) >>> e = Decimal(18) >>> orig = d >>> d += e >>> d Decimal("60") >>> e Decimal("18") >>> orig Decimal("42") >>> d is orig False If your suggestion that += *modifies* the object, then orig would now unintuitively contain 60 and "d is orig" would return True. This doesn't preclude you from implementing a self-mutating += style __add__ method and returning "self", but it's usually a bad idea unless it's dire for performance (and even then, think it over a couple times). -tkc From martin at v.loewis.de Sat May 1 08:16:29 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 01 May 2010 14:16:29 +0200 Subject: http://pypi.python.org/pypi In-Reply-To: <5587c2ea-567d-4a20-9e60-70c4ee18b24b@e39g2000yqf.googlegroups.com> References: <5587c2ea-567d-4a20-9e60-70c4ee18b24b@e39g2000yqf.googlegroups.com> Message-ID: <4BDC1B9D.70505@v.loewis.de> > I have only access to the webpage form too upload my one file. > pkginfo is ok, just want to at a single .py file instead of a complete > site-package tar directory, because it is not a site-package, its more > like a single exe file. Uploading individual .py files is not supported. If it's not a Python package, it shouldn't be in the Python Package Index. Regards, Martin From stefan_ml at behnel.de Sat May 1 08:34:39 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 01 May 2010 14:34:39 +0200 Subject: Ignoring XML Namespaces with cElementTree In-Reply-To: <7a4f1818-e77a-4238-b021-3e2c6da836ae@a18g2000prd.googlegroups.com> References: <9527079b-92bf-4c59-af2b-ab2c84029f55@h37g2000pra.googlegroups.com> <7a4f1818-e77a-4238-b021-3e2c6da836ae@a18g2000prd.googlegroups.com> Message-ID: Carl Banks, 01.05.2010 12:33: > On Apr 29, 10:12 pm, Stefan Behnel wrote: >> dmtr, 30.04.2010 04:57: >>> I don't want these "{http://www.very_long_url.com}" in front of my >>> tags. They create performance disaster on large files >> >> I seriously doubt that they do. > > I don't know what kind of XML files you deal with, but for me a large > XML file is gigabyte-sized (obviously I don't use Element Tree for > those). Why not? I used cElementTree for files of that size (1-1.5GB unpacked) a couple of times, and it was never a problem. > Even for files tens-of-megabyte files string ops to expand tags with > namespaces is going to be a pretty decent penalty--remember > ElementTree does nothing lazily. So? Did you run a profiler on it to know that there is a penalty due to the string concatenation? cElementTree's parser (expat) and its tree builder are blazingly fast, especially the iterparse() implementation. http://codespeak.net/lxml/performance.html#parsing-and-serialising http://codespeak.net/lxml/performance.html#a-longer-example http://effbot.org/zone/celementtree.htm#benchmarks >>> (first cElementTree adds them, then I have to remove them in python). >> >> I think that's your main mistake: don't remove them. Instead, use the fully >> qualified names when comparing. > > Unless you have multiple namespaces or are working with defined schema > or something, it's useless boilerplate. > > It'd be a nice feature if ElementTree could let users optionally > ignore a namespace, unfortunately it doesn't have it. I agree that that would make for a nice parser option, e.g. when dealing with HTML and XHTML in the same code. Stefan From stefan_ml at behnel.de Sat May 1 09:05:05 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 01 May 2010 15:05:05 +0200 Subject: matching strings in a large set of strings In-Reply-To: References: <877hnpjtdw.fsf@rudin.co.uk> Message-ID: Duncan Booth, 30.04.2010 10:20: > So more than 3GB just for the strings (and that's for Python 2.x on > Python 3.x you'll need nearly 5GB). > > Running on a 64 bit version of Python should be fine, but for a 32 bit > system a naive approach just isn't going to work. > > Option 1: use a trie. That should reduce storage, maybe it will reduce > it enough, maybe not. It depends on the data. Depending on the implementation and the data, a trie can also use a lot /more/ space than the set of strings that it contains. The 83 million 14 character strings can well include a relatively large subset of the possible permutations (imagine purely numeric, hex-numeric or lower-case alpha-numeric strings, for example), so the trie will likely need to branch very often with very low intermediate run length. If you use pointers for trie branches, that's at least 8 bytes per branch on a 64bit system, versus 1 byte per character in a byte string list. Depending on the ratio of branches to characters, one or the other may win. So a "naive approach" likely won't work for tries either. Stefan From stefan_ml at behnel.de Sat May 1 09:17:25 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 01 May 2010 15:17:25 +0200 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4BDC1AF6.3070505@thechases.com> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4BDC1AF6.3070505@thechases.com> Message-ID: Tim Chase, 01.05.2010 14:13: > On 05/01/2010 12:08 AM, Patrick Maupin wrote: >> +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- >> place operator methods, actually) *modify* the lhs object. >> >> Your proposed .= syntax conceptually *replaces* the lhs object >> (actually, rebinds the lhs symbol to the new object). > > The += family of operators really do rebind the symbol, not modify the > object. > > >>> from decimal import Decimal > >>> d = Decimal(42) > >>> e = Decimal(18) > >>> orig = d > >>> d += e > >>> d > Decimal("60") > >>> e > Decimal("18") > >>> orig > Decimal("42") > >>> d is orig > False > > If your suggestion that += *modifies* the object, then orig would now > unintuitively contain 60 and "d is orig" would return True. > > This doesn't preclude you from implementing a self-mutating += style > __add__ method and returning "self", but it's usually a bad idea unless > it's dire for performance (and even then, think it over a couple times). It's not like this was unprecedented in Python, though: Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> l = [1,2,3] >>> a = l >>> l += [4,5,6] >>> l [1, 2, 3, 4, 5, 6] >>> a [1, 2, 3, 4, 5, 6] And I'm pretty sure this wasn't just done for performance reasons. Mutable data types behave that way. Stefan From python.list at tim.thechases.com Sat May 1 09:19:00 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 01 May 2010 08:19:00 -0500 Subject: Fast Efficient way to transfer an object to another list In-Reply-To: <4bdba195$0$8757$c3e8da3@news.astraweb.com> References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> Message-ID: <4BDC2A44.5080301@tim.thechases.com> On 04/30/2010 10:35 PM, Steven D'Aprano wrote: > If you know there is one, and only one, item with that stock code: > > def transfer_stock(stock_code, old_list, new_list): > """ Transfer a stock from one list to another """ > i = old_list.index(stock_code) # search > new_list.append(old_list[i]) # copy > del old_list[i] # delete > return new_list This could be written as def move(code, source, dest): dest.append(source.pop(source.index(code))) return dest depending on how one thinks. I tend to prefer lst.pop(idx) over tmp = lst[idx] del lst[idx] only using the latter if "idx" is a range/slice. Though since the function mutates the arguments, I'd be tempted to return None like list.sort() does for the same rationale. If more than one item is in the source, it will move/remove the first leaving the remainder; if no matching item is in the source it will appropriately raise a ValueError. -tkc From kaleem.adil at gmail.com Sat May 1 09:28:33 2010 From: kaleem.adil at gmail.com (Adil Kaleem) Date: Sat, 1 May 2010 06:28:33 -0700 (PDT) Subject: Help needed in downloading Brown corpus Message-ID: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> Hi all I'm a masters student in NLP. I needed to download the Brown corpus. I'm unable to download from nltk.org with the python CLI. My network connection is behind a proxy server so it's creating a problem. Since I don't know a bit of python, so unable to figure a way out. Can someone help me in this regard either how to solve my downloading problem or how to get Brown Corpus from some other link. Thanks in advance. From shashank.sunny.singh at gmail.com Sat May 1 09:37:28 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Sat, 1 May 2010 19:07:28 +0530 Subject: Help needed in downloading Brown corpus In-Reply-To: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> References: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> Message-ID: try this: run this in your terminal before you hit nltk.download(). Don't forget to set username, password and proxy info for your own system.(in PROXY_INFO) import urllib2 PROXY_INFO = { 'user' : username, 'pass' : password, 'host' : proxy_server, 'port' : proxy_port } proxy_support = urllib2.ProxyHandler({"http" : \ "http://%(user)s:%(pass)s@%(host)s:%(port)d" % PROXY_INFO}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) urllib2.install_opener(opener) HTH On Sat, May 1, 2010 at 6:58 PM, Adil Kaleem wrote: > Hi all > I'm a masters student in NLP. I needed to download the Brown corpus. > I'm unable to download from nltk.org with the python CLI. My network > connection is behind a proxy server so it's creating a problem. Since > I don't know a bit of python, so unable to figure a way out. Can > someone help me in this regard either how to solve my downloading > problem or how to get Brown Corpus from some other link. > Thanks in advance. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From news1234 at free.fr Sat May 1 10:44:48 2010 From: news1234 at free.fr (News123) Date: Sat, 01 May 2010 16:44:48 +0200 Subject: Windows7 run python script / sub process with elevated privileges Message-ID: <4bdc3e60$0$12096$426a74cc@news.free.fr> Hi, I have a small python script, which has been started as normal non privileged user. At a later point in time it would like to start another python script with elevated privileges. How can I write my code such, that I will get the privilege elevation prompt and I can start a sub process / python function with elevated privileges. thanks for any hints. Under Linux Ubuntu I would use sudo/gksu Under Windows 7 I'm a little lost. A Python only solution is of course prefered, but any .bat .c .C# .cmd wrapper would be fine. N From alfps at start.no Sat May 1 10:45:51 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 01 May 2010 16:45:51 +0200 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: On 01.05.2010 14:13, * Tim Chase: > On 05/01/2010 12:08 AM, Patrick Maupin wrote: >> +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- >> place operator methods, actually) *modify* the lhs object. >> >> Your proposed .= syntax conceptually *replaces* the lhs object >> (actually, rebinds the lhs symbol to the new object). > > The += family of operators really do rebind the symbol, not modify the > object. > > >>> from decimal import Decimal > >>> d = Decimal(42) > >>> e = Decimal(18) > >>> orig = d > >>> d += e > >>> d > Decimal("60") > >>> e > Decimal("18") > >>> orig > Decimal("42") > >>> d is orig > False > > If your suggestion that += *modifies* the object, then orig would now > unintuitively contain 60 and "d is orig" would return True. In some cases += modifies the object. For CPython this is an optimization for the 'str' type, reducing to O(n) time the common newbie O(n^2) loops. The criterion for doing it is that there is exactly 1 reference (as is the case after a first append, subsequent appends can just modify). > This doesn't preclude you from implementing a self-mutating += style > __add__ method and returning "self", but it's usually a bad idea unless > it's dire for performance (and even then, think it over a couple times). Agreed, at the Python level one doesn't in general have the necessary information to do it safely. Nothwithstanding the current CPython and Jython documentation error of sys.getrefcount (or whatever the name was) that indicates that it's available in any implementation. Cheers, - Alf From python at mrabarnett.plus.com Sat May 1 11:08:22 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 01 May 2010 16:08:22 +0100 Subject: Fast Efficient way to transfer an object to another list In-Reply-To: <4BDC2A44.5080301@tim.thechases.com> References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> <4BDC2A44.5080301@tim.thechases.com> Message-ID: <4BDC43E6.1090508@mrabarnett.plus.com> Tim Chase wrote: > On 04/30/2010 10:35 PM, Steven D'Aprano wrote: >> If you know there is one, and only one, item with that stock code: >> >> def transfer_stock(stock_code, old_list, new_list): >> """ Transfer a stock from one list to another """ >> i = old_list.index(stock_code) # search >> new_list.append(old_list[i]) # copy >> del old_list[i] # delete >> return new_list > > This could be written as > > def move(code, source, dest): > dest.append(source.pop(source.index(code))) > return dest > > depending on how one thinks. I tend to prefer > > lst.pop(idx) > > over > > tmp = lst[idx] > del lst[idx] > > only using the latter if "idx" is a range/slice. > > Though since the function mutates the arguments, I'd be tempted to > return None like list.sort() does for the same rationale. > > If more than one item is in the source, it will move/remove the first > leaving the remainder; if no matching item is in the source it will > appropriately raise a ValueError. > It would be more efficient if instead of deleting or popping the item you moved the last one into its place: if idx == len(source) - 1: item = source.pop() else: item = source[idx] source[idx] = source.pop() assuming that the order of the items in the list doesn't matter. From bieffe62 at gmail.com Sat May 1 11:11:45 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sat, 1 May 2010 08:11:45 -0700 (PDT) Subject: Fast Efficient way to transfer an object to another list References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> Message-ID: <06366a6d-e3db-4963-bcc0-0bc03d035a94@e2g2000yqn.googlegroups.com> On 1 Mag, 05:35, Steven D'Aprano wrote: > > def transfer_stock(stock_code, old_list, new_list): > ? ? """ Transfer a stock from one list to another """ > ? ? while True: ?# loop forever > ? ? ? ? try: > ? ? ? ? ? ? i = old_list.index(stock_code) > ? ? ? ? except ValueError: > ? ? ? ? ? ? # not found, so we're done > ? ? ? ? ? ? break > ? ? ? ? new_list.append(old_list[i]) > ? ? ? ? del old_list[i] > ? ? return new_list > > -- > Steven I think this could be slower than doing like the OP, since 'index' rescan the whole list every time while doing an explicit loop you only scan the list once. Anyway i think that list.extract( old_list, predicate ) -> new_list would be a nice addition to the standard library (possibly a C faster version of what one could implement in python) ... and since the library is not under moratorium maybe we will have it ... the semantic could be like th OP asked: --- code begins class ListE(list): def extract(self, predicate): res = [] for idx, el in enumerate(self): if predicate(el): res.append( self.pop(idx) ) return res class Stock(object): def __init__(self, code): self.code = code def __repr__(self): return "Stock: code=%d" % self.code l = ListE( Stock(n) for n in range(19) ) subl = l.extract( lambda x: x.code in (1,4, 9) ) print " l = ", l print "subl = ", subl --- code ends --- results l = [Stock: code=0, Stock: code=2, Stock: code=3, Stock: code=5, Stock: code=6, Stock: code=7, Stock: code=8, Stock: code=10, Stock: code=11, Stock: code=12, Stock: code=13, Stock: code=14, Stock: code=15, Stock: code=16, Stock: code=17, Stock: code=18] subl = [Stock: code=1, Stock: code=4, Stock: code=9] Ciao --- FB From news1234 at free.fr Sat May 1 11:57:56 2010 From: news1234 at free.fr (News123) Date: Sat, 01 May 2010 17:57:56 +0200 Subject: Windows7 run python script / sub process with elevated privileges In-Reply-To: <4bdc3e60$0$12096$426a74cc@news.free.fr> References: <4bdc3e60$0$12096$426a74cc@news.free.fr> Message-ID: <4bdc4f84$0$18399$426a74cc@news.free.fr> I Found a first solution, though not very satisfying: News123 wrote: > Hi, > > I have a small python script, which has been started as normal non > privileged user. > > At a later point in time it would like to start another python script > with elevated privileges. > > How can I write my code such, that I will get the privilege elevation > prompt and I can start a sub process / python function with elevated > privileges. > > thanks for any hints. > > Under Linux Ubuntu I would use sudo/gksu > > Under Windows 7 I'm a little lost. > > A Python only solution is of course prefered, but any .bat .c .C# .cmd > wrapper would be fine. > I could call following command: PowerShell -Command (New-Object -com 'Shell.Application').ShellExecute('Cmd.exe', '/c c:\abs_path_to_my_app\pyscript.pyw', ' ', 'runas') So I might do something like: # ########### script starts import subprocess cmd_wrap = "PowerShell -Command (New-Object -com "\ "'Shell.Application').ShellExecute('Cmd.exe', "\ "'/c %s', '', 'runas')" args = r"c:\abspathtommyapp\myapp.pyw" cmd = cmd_wrap % args # create KW args to hide console kwargs = { } su = subprocess.STARTUPINFO() su.dwFlags |= subprocess.STARTF_USESHOWWINDOW su.wShowWindow = subprocess.SW_HIDE kwargs['startupinfo'] = su p = subprocess.Popen( cmd.split() , **kwargs ) # script ends here However my issue is, that I have one annoying console window popping up when PowerShell starts cmd.exe Is there anything better? From daniel at stutzbachenterprises.com Sat May 1 11:57:56 2010 From: daniel at stutzbachenterprises.com (Daniel Stutzbach) Date: Sat, 1 May 2010 10:57:56 -0500 Subject: Fast Efficient way to transfer an object to another list In-Reply-To: References: Message-ID: On Fri, Apr 30, 2010 at 9:16 PM, Jimbo wrote: > Hello I have a relatively simple thing to do; move an object from one > to list into another. But I think my solution maybe inefficient & > slow. > Removing an item from a list is O(n) on average, so it's going to be a bit slow any way you slice it (unless you only remove from the end of the list which is O(1)). Can you tell us more about why you're using a list? If the order of the items doesn't matter, you may be able to use a set(). If the order matters, how is the list ordered? If we know how the list is ordered, we may be able to help you come up with a clever way to remove an item cheaply. -- Daniel Stutzbach, Ph.D. President, Stutzbach Enterprises, LLC -------------- next part -------------- An HTML attachment was scrubbed... URL: From WolfgangMeiners01 at web.de Sat May 1 12:04:43 2010 From: WolfgangMeiners01 at web.de (Wolfgang Meiners) Date: Sat, 01 May 2010 18:04:43 +0200 Subject: recommended way to insert data into a one to many relationship using python Message-ID: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Hi, one to many relationships are fairly common, i think. So there should be a recommended way to insert data into such a relation using python. Given the following programm, what is the recommended way to insert the list of NewEmployees to the database? ======================================================================== # !python # -*- coding: utf-8 -*- import sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() cur.execute("""create table employees( eid integer primary key autoincrement, name text not null, rid integer references rooms(rid))""") cur.execute("""create table rooms( rid integer primary key autoincrement, number integer, fid integer references floors(fid))""") cur.execute("""create table floors( fid integer primary key autoincrement, floor text not null)""") cur.execute("""insert into floors(floor) values ('first floor')""") cur.execute("""insert into floors(floor) values ('second floor')""") cur.execute("""insert into rooms(number,fid) values (21, 1)""") cur.execute("""insert into rooms(number,fid) values (22, 2)""") cur.execute("""insert into employees(name,rid) values ('Joe', 1)""") cur.execute("""insert into employees(name,rid) values ('Nancy', 2)""") cur.execute("""create view emplist as select name, number, floor from employees natural inner join rooms natural inner join floors""") print cur.execute("""select * from emplist order by name""").fetchall() NewEmployees =[] NewEmployees.append({'name': 'George', 'room': 89, 'floor': 'third floor'}) NewEmployees.append({'name': 'Ellen', 'room': 21, 'floor': 'first floor'}) print NewEmployees con.close() =========================================================================== Thank you for any hint Wolfgang From ppearson at nowhere.invalid Sat May 1 13:54:40 2010 From: ppearson at nowhere.invalid (Peter Pearson) Date: 1 May 2010 17:54:40 GMT Subject: Help needed in downloading Brown corpus References: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> Message-ID: <843870Fj4oU1@mid.individual.net> On Sat, 1 May 2010 06:28:33 -0700 (PDT), Adil Kaleem wrote: > Hi all > I'm a masters student in NLP. I needed to download the Brown corpus. > I'm unable to download from nltk.org with the python CLI. My network > connection is behind a proxy server so it's creating a problem. Since > I don't know a bit of python, so unable to figure a way out. Can > someone help me in this regard either how to solve my downloading > problem or how to get Brown Corpus from some other link. > Thanks in advance. As I understand it (from Wikipedia), the Brown Corpus is a collection of samples of modern American English text, and nltk.org provides a Python toolkit for exploring said Corpus. I'm trying to figure out whether you're trying to get the Corpus or the toolkit. Neither interpretation looks plausible: if you're after the Corpus itself and you don't know a bit of Python, why are you struggling with Python? On the other hand, if you're after the toolkit, what's the problem? People download Python modules all the time. And besides, why would you be after the toolkit if you don't know a bit of Python? If your goal is to learn enough Python to use the toolkit, you'll find this newsgroup full of smart and helpful people. But you'll have to be a little more explicit about what you're trying to do and more specific about what obstacles you encounter. As you might see by looking at other threads on this newsgroup, the queries that get the most prompt and useful responses usually include blocks of quoted text of the form "I type this [cut-and-pasted block] and get this response [another cut-and-pasted block]." -- To email me, substitute nowhere->spamcop, invalid->net. From lie.1296 at gmail.com Sat May 1 15:08:53 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 02 May 2010 05:08:53 +1000 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> Message-ID: <4bdc7ca3$1@dnews.tpgi.com.au> On 05/01/10 11:16, Steven D'Aprano wrote: > On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote: > > In practice though, I think that's a difference that makes no difference. > It walks like an operator, it swims like an operator, and it quacks like > an operator. > Nope it's not. A full-time operator in python have a reflected version (e.g. __radd__), which dot does not have. And Python's object system makes it that the argument to __getattr__ is always a string even though there might be a valid variable that corresponds to it: a = MyClass() b = MyClass() print a . b I've often wanted to figure out a way to (ab)use python's dot operator for function composition (i.e. f.g(x) ==> f(g(x)) ). There's no way to do it, not without being way too hackish. OTOH, doing so is quite trivial with regular operators. In short, unless there's __rgetattr__ and unless you can refer to the right-hand operand as an object[1], dot doesn't quack like an operator. [1] well, technically string is an object, but you get what I mean From __peter__ at web.de Sat May 1 15:20:33 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 May 2010 21:20:33 +0200 Subject: recommended way to insert data into a one to many relationship using python References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Wolfgang Meiners wrote: > Hi, > > one to many relationships are fairly common, i think. So there should be > a recommended way to insert data into such a relation using python. > > > Given the following programm, what is the recommended way to insert the > list of NewEmployees to the database? > > ======================================================================== > # !python > # -*- coding: utf-8 -*- > > import sqlite3 > > con = sqlite3.connect(":memory:") > cur = con.cursor() > > cur.execute("""create table employees( > eid integer primary key autoincrement, > name text not null, > rid integer references rooms(rid))""") > > cur.execute("""create table rooms( > rid integer primary key autoincrement, > number integer, > fid integer references floors(fid))""") > > cur.execute("""create table floors( > fid integer primary key autoincrement, > floor text not null)""") > > cur.execute("""insert into floors(floor) values ('first floor')""") > cur.execute("""insert into floors(floor) values ('second floor')""") > > cur.execute("""insert into rooms(number,fid) values (21, 1)""") > cur.execute("""insert into rooms(number,fid) values (22, 2)""") > > cur.execute("""insert into employees(name,rid) values ('Joe', 1)""") > cur.execute("""insert into employees(name,rid) values ('Nancy', 2)""") > > cur.execute("""create view emplist as select name, number, floor > from employees natural inner join rooms natural inner join > floors""") > > print cur.execute("""select * from emplist order by name""").fetchall() > > NewEmployees =[] > NewEmployees.append({'name': 'George', 'room': 89, 'floor': 'third > floor'}) NewEmployees.append({'name': 'Ellen', 'room': 21, 'floor': 'first > floor'}) > > print NewEmployees > con.close() > =========================================================================== > > Thank you for any hint > Wolfgang There are probably some opportunities for generalization lurking in the following mess, but it would take me more time than I'm willing to invest. cur.execute("create table new_employees (name, room, floor, fid);") cur.executemany("""insert into new_employees (name, room, floor) values (:name, :room, :floor)""", NewEmployees) c2 = con.cursor() missing = c2.execute(""" select distinct n.floor from new_employees n left outer join floors f on n.floor = f.floor where f.floor is null """) cur.executemany("insert into floors (floor) values (?)", missing) cur.execute(""" update new_employees set fid = (select fid from floors where floors.floor = new_employees.floor)""") missing = c2.execute(""" select distinct n.fid, n.room from new_employees n left outer join rooms r on n.fid = r.fid and n.room = r.number where r.fid is null""") cur.executemany("insert into rooms (fid, number) values (?, ?)", missing) new = c2.execute(""" select n.name, r.rid from new_employees n, rooms r where n.room = r.number and n.fid == r.fid """) cur.executemany("insert into employees (name, rid) values (?, ?)", new) If your data is small enough you may try to do the heavy lifting in Python instead of SQL; if not, maybe you'd better ask in a SQL forum. Peter Afterthought: Can SQLAlchemy do these kind of things cleanly? From pmaupin at gmail.com Sat May 1 15:22:06 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 1 May 2010 12:22:06 -0700 (PDT) Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: <54dfd378-f519-4a43-96ba-df8de28c45c6@k29g2000yqh.googlegroups.com> On May 1, 7:13?am, Tim Chase wrote: > On 05/01/2010 12:08 AM, Patrick Maupin wrote: > > > +=, -=, /=, *=, etc. ?conceptually (and, if lhs object supports in- > > place operator methods, actually) *modify* the lhs object. > > > Your proposed .= syntax conceptually *replaces* the lhs object > > (actually, rebinds the lhs symbol to the new object). > > The += family of operators really do rebind the symbol, not > modify the object. > > ? ?>>> from decimal import Decimal > ? ?>>> d = Decimal(42) > ? ?>>> e = Decimal(18) > ? ?>>> orig = d > ? ?>>> d += e > ? ?>>> d > ? ?Decimal("60") > ? ?>>> e > ? ?Decimal("18") > ? ?>>> orig > ? ?Decimal("42") > ? ?>>> d is orig > ? ?False > > If your suggestion that += *modifies* the object, then orig would > now unintuitively contain 60 and "d is orig" would return True. Well, I wrote "conceptually" (which I believe is true; it's certainly true for me) and "sometimes actually" (which I know is true): >>> x = [1,2,3,4,5] >>> y = x >>> x += [6] >>> y [1, 2, 3, 4, 5, 6] >>> >>> x = set() >>> y = x >>> x |= set([1]) >>> y set([1]) SO, if you find those results "unintuitive", perhaps you should upgrade your understanding of python. Personally, I don't find any of the results I gave, or the results you gave, surprising, so I'm not saying my "conceptually and sometimes actually modifies the result" is right for *you* but it works great for me. :-) > This doesn't preclude you from implementing a self-mutating += > style __add__ method and returning "self", but it's usually a bad > idea unless it's dire for performance (and even then, think it > over a couple times). Well, you should submit a bug report to fix the operation of lists and sets for a starter. But first, you might want to read PEP 203 -- augmented assignments. I particularly like the section which says: "The idea behind augmented assignment in Python is that it isn't just an easier way to write the common practice of storing the result of a binary operation in its left-hand operand, but also a way for the left- hand operand in question to know that it should operate `on itself', rather than creating a modified copy of itself." There are a lot of sections which have a similar flavor. If (which I doubt), the "augmented dot" is accepted, it won't necessarily have the same meaning. x = x.foo could replace x with any other kind of object, and I view it as a replacement, while I view x += foo as a modification. Regards, Pat From darcy at druid.net Sat May 1 15:24:46 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 1 May 2010 15:24:46 -0400 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4bdc7ca3$1@dnews.tpgi.com.au> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> Message-ID: <20100501152446.2fd017bd.darcy@druid.net> On Sun, 02 May 2010 05:08:53 +1000 Lie Ryan wrote: > On 05/01/10 11:16, Steven D'Aprano wrote: > > On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote: > > > > In practice though, I think that's a difference that makes no difference. > > It walks like an operator, it swims like an operator, and it quacks like > > an operator. > > > > Nope it's not. A full-time operator in python have a reflected version Hi. Please watch the attributions. I didn't write that. I was the one who said that '.' was not an operator. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From paul.paj at gmail.com Sat May 1 16:16:04 2010 From: paul.paj at gmail.com (Paul Johnston) Date: Sat, 1 May 2010 13:16:04 -0700 (PDT) Subject: jpeg package Message-ID: Hi, I've used the jpeg library on PyPI in the past and it's been great: http://pypi.python.org/pypi/jpeg/0.1.4 However, the library home page is now unaccessible. I can't even find the library on archive.org. Any idea how I can get it? http://www.emilas.com/jpeg/ Thanks, Paul From Jack.Jansen at cwi.nl Sat May 1 17:40:13 2010 From: Jack.Jansen at cwi.nl (Jack Jansen) Date: Sat, 1 May 2010 23:40:13 +0200 Subject: [capi-sig] SWIG + expy In-Reply-To: <272522.69975.qm@web54204.mail.re2.yahoo.com> References: <272522.69975.qm@web54204.mail.re2.yahoo.com> Message-ID: <652256E5-5D3A-41DE-A7C5-6BED41F5944E@cwi.nl> On 27-Apr-2010, at 08:30 , Yingjie Lan wrote: > Hi, > > Is it possible to use SWIG to parse C/C++, and provide an interface for me to generate some code? I thought it might be good to have SWIG help generate expy (see http://expy.sourceforge.net) files, then generate the python extension via expy. I would be very interested in a universal intermediate format for all the interface generators. I'm still using a version of Guido's old bgen, now grudgingly extended to handle C++ and do bidirectional bridging between Python and C++, and while I love and cherish the code generator the C++ parser is, uhm... challenging. Parsing C++ with per-line regular expressions is no fun:-) I looked at gccxml at some point, as well as at some of the competing Python interface generators, but it went nowhere. gccxml output is far too detailed, and the output is too much of a simple parse tree to be of any use. The intermediate formats of the other interface generators I looked at were all too inaccessible. Maybe we can come up with something decent in this group? If there is enough interest: I can start by describing bgen's intermediate format, and if other people do the same for theirs we may be able to get to common ground... -- Jack Jansen, , http://www.cwi.nl/~jack If I can't dance I don't want to be part of your revolution -- Emma Goldman From news1234 at free.fr Sat May 1 17:46:33 2010 From: news1234 at free.fr (News123) Date: Sat, 01 May 2010 23:46:33 +0200 Subject: matching strings in a large set of strings In-Reply-To: References: <4BDC14F2.2050603@free.fr> Message-ID: <4BDCA139.2010303@free.fr> Dennis Lee Bieber wrote: > On Sat, 01 May 2010 13:48:02 +0200, News123 declaimed > the following in gmane.comp.python.general: > >> Dennis Lee Bieber wrote: >>> That lets you do a binary search on the file. Much faster than a >>> linear search (linear search will average out to 41.5M read operations; >>> binary should be around 10000 reads) >> Don't you meant 27 reads instead of 41.5 M reads? >> > Don't you mean my 10000 reads? The 41.5M is the average for the > linear search. > Indeed, this is what I meant. or phrased differently: "about 27 reads with a binary search instead of 41.5M reads average with a linear search." >>>>> from math import log >>>>> log(83e6)/log(2) >> 26.306608000671101 > Probably -- it was late at night and I was working things out in my > head... I know about late nights. I just wondered whether I overlooked something. From news1234 at free.fr Sat May 1 17:46:33 2010 From: news1234 at free.fr (News123) Date: Sat, 01 May 2010 23:46:33 +0200 Subject: matching strings in a large set of strings In-Reply-To: References: <4BDC14F2.2050603@free.fr> Message-ID: <4BDCA139.2010303@free.fr> Dennis Lee Bieber wrote: > On Sat, 01 May 2010 13:48:02 +0200, News123 declaimed > the following in gmane.comp.python.general: > >> Dennis Lee Bieber wrote: >>> That lets you do a binary search on the file. Much faster than a >>> linear search (linear search will average out to 41.5M read operations; >>> binary should be around 10000 reads) >> Don't you meant 27 reads instead of 41.5 M reads? >> > Don't you mean my 10000 reads? The 41.5M is the average for the > linear search. > Indeed, this is what I meant. or phrased differently: "about 27 reads with a binary search instead of 41.5M reads average with a linear search." >>>>> from math import log >>>>> log(83e6)/log(2) >> 26.306608000671101 > Probably -- it was late at night and I was working things out in my > head... I know about late nights. I just wondered whether I overlooked something. From vincent at vincentdavis.net Sat May 1 18:22:57 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Sat, 1 May 2010 16:22:57 -0600 Subject: jpeg package In-Reply-To: References: Message-ID: This gets you the cached page link I also fond some of the source pages in googles cache *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn On Sat, May 1, 2010 at 2:16 PM, Paul Johnston wrote: > Hi, > > I've used the jpeg library on PyPI in the past and it's been great: > http://pypi.python.org/pypi/jpeg/0.1.4 > > However, the library home page is now unaccessible. I can't even find > the library on archive.org. Any idea how I can get it? > http://www.emilas.com/jpeg/ > > Thanks, > > Paul > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregory.j.baker at gmail.com Sat May 1 18:57:06 2010 From: gregory.j.baker at gmail.com (Novocastrian_Nomad) Date: Sat, 1 May 2010 15:57:06 -0700 (PDT) Subject: Need direction on mass find/replacement in HTML files References: Message-ID: One single line regex solution would be: re.sub(r'http\://www.mysite.org/\?page=([^"]+)',r'pages/\1.htm',html) From evil.hackerz.999 at gmail.com Sat May 1 19:54:21 2010 From: evil.hackerz.999 at gmail.com (EVIL-HaCkErZ) Date: Sat, 1 May 2010 16:54:21 -0700 (PDT) Subject: TEAM EVILHACKERZ Message-ID: TEAM EVILHACKERZ http://handyzon.com/ [Amazon social network & discount center] http://fullversionddl.com [cracked software & etc] http://realhacks.com [learn hacking/tutorials] http://desktopmp3.com [mucic album & wallpaper] http://dvdripdownload.com [latest movies download ] From steve at REMOVE-THIS-cybersource.com.au Sat May 1 20:58:10 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 00:58:10 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> Message-ID: <4bdcce21$0$27782$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 05:08:53 +1000, Lie Ryan wrote: > On 05/01/10 11:16, Steven D'Aprano wrote: >> On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote: >> >> In practice though, I think that's a difference that makes no >> difference. It walks like an operator, it swims like an operator, and >> it quacks like an operator. >> >> > Nope it's not. A full-time operator in python have a reflected version > (e.g. __radd__), which dot does not have. What are the reflected versions of __eq__ and __ne__ (binary == and != operators)? And __neg__, __pos__ and __inv__ (for the unary - + and ~ operators)? And the three-argument form of __pow__ for power(1, 2, x)? > And Python's object system > makes it that the argument to __getattr__ is always a string even though > there might be a valid variable that corresponds to it: That is nothing to do with the object system, it is related to the semantics of Python syntax. a.b doesn't mean "apply the binary dot operator to arguments a and b". It is syntactic sugar for "look for an attribute named 'b' on object a". As such, the operands that __getattr__ receives are the object a and the *name* b (implemented as a string). Also, the implementation of attribute lookup is quite complex, with all sorts of special cases and optimizations. > a = MyClass() > b = MyClass() > print a . b > > I've often wanted to figure out a way to (ab)use python's dot operator > for function composition (i.e. f.g(x) ==> f(g(x)) ). There's no way to > do it, not without being way too hackish. That's a good example of where the difference does make a difference. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 1 20:59:36 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 00:59:36 GMT Subject: Fast Efficient way to transfer an object to another list References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> <06366a6d-e3db-4963-bcc0-0bc03d035a94@e2g2000yqn.googlegroups.com> Message-ID: <4bdcce77$0$27782$c3e8da3@news.astraweb.com> On Sat, 01 May 2010 08:11:45 -0700, Francesco Bochicchio wrote: > On 1 Mag, 05:35, Steven D'Aprano > wrote: > > >> def transfer_stock(stock_code, old_list, new_list): >> ? ? """ Transfer a stock from one list to another """ while True: ?# >> ? ? loop forever >> ? ? ? ? try: >> ? ? ? ? ? ? i = old_list.index(stock_code) >> ? ? ? ? except ValueError: >> ? ? ? ? ? ? # not found, so we're done >> ? ? ? ? ? ? break >> ? ? ? ? new_list.append(old_list[i]) >> ? ? ? ? del old_list[i] >> ? ? return new_list >> >> -- >> Steven > > I think this could be slower than doing like the OP, since 'index' > rescan the whole list every time > while doing an explicit loop you only scan the list once. If the list is sufficiently big enough, yes, you are correct. But since list.index is fast C code, and a while loop is slow Python code, it would need to be fairly big, and probably much bigger than you think! The simplest way to speed the above code up is not to start from the beginning each time. That requires two very small changes. And since deletions from the front of the list are slow, MRAB's suggestion is also a good idea. This requires another very small change. Putting them together: # Untested. def transfer_stock(stock_code, old_list, new_list): ? ? """ Transfer a stock from one list to another """ i = 0 while True: ?# loop forever ? ? ? ?try: ? ? ? ? ? i = old_list.index(stock_code, i) ? ? ? except ValueError: ? ? ? ? ? ? # not found, so we're done ? ? ? ? ? ? break ? ? ? ? new_list.append(old_list[i]) ? ? ? ? old_list[i] = old_list[-1] del old_list[-1] ? ? return new_list This should be very much faster, for hardly any extra complexity. > Anyway i think that list.extract( old_list, predicate ) -> new_list > would be a nice addition to the standard library (possibly a C faster > version of what one could implement in python) ... and since the library > is not under moratorium maybe we will have it ... But since it is a method on a built-in (list), and not a library function, it does fall under the moratorium. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 1 21:30:26 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 01:30:26 GMT Subject: Help needed in downloading Brown corpus References: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> Message-ID: <4bdcd5b2$0$27782$c3e8da3@news.astraweb.com> On Sat, 01 May 2010 06:28:33 -0700, Adil Kaleem wrote: > Hi all > I'm a masters student in NLP. I needed to download the Brown corpus. I'm > unable to download from nltk.org with the python CLI. My network > connection is behind a proxy server so it's creating a problem. Since I > don't know a bit of python, so unable to figure a way out. This has nothing to do with Python, it is a network issue. Talk to your network administrator and get him to fix the proxy, or give you a way to bypass it. Or if you have an internet connection at home, download it from there. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 1 21:32:34 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 01:32:34 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: <4bdcd631$0$27782$c3e8da3@news.astraweb.com> On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: > On 05/01/2010 12:08 AM, Patrick Maupin wrote: >> +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- >> place operator methods, actually) *modify* the lhs object. >> >> Your proposed .= syntax conceptually *replaces* the lhs object >> (actually, rebinds the lhs symbol to the new object). > > The += family of operators really do rebind the symbol, not modify the > object. They potentially do both, depending on the object, even for built-ins. > >>> from decimal import Decimal [...] I'm not sure why you took the trouble to import Decimal for this example, when you could have shown the same thing with built-ins int or float. All three types are immutable. A counter example with a mutable type: >>> a = [] >>> b = a >>> a += [2] >>> a [2] >>> b [2] thus demonstrating that __iadd__ modifies in place as well as rebinds for at least one mutable type. > This doesn't preclude you from implementing a self-mutating += style > __add__ method and returning "self", but it's usually a bad idea Obviously the Python dev team don't agree with that :) Just to prove that += for lists is not an accident: >>> a = set() >>> b = a >>> a |= set([1]) >>> a set([1]) >>> b set([1]) -- Steven From clp2 at rebertia.com Sat May 1 22:03:04 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 1 May 2010 19:03:04 -0700 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4bdcd631$0$27782$c3e8da3@news.astraweb.com> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On Sat, May 1, 2010 at 6:32 PM, Steven D'Aprano wrote: > On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: >> This doesn't preclude you from implementing a self-mutating += style >> __add__ method and returning "self", but it's usually a bad idea > > Obviously the Python dev team don't agree with that :) > > Just to prove that += for lists is not an accident: > >>>> a = set() >>>> b = a >>>> a |= set([1]) >>>> a > set([1]) >>>> b > set([1]) In both cases, __iOP__ operator methods are being used, not vanilla __OP__ methods, so neither of your examples are relevant to Mr. Chase's point. Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sat May 1 22:24:16 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 02:24:16 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: <4bdce250$0$27782$c3e8da3@news.astraweb.com> On Sat, 01 May 2010 19:03:04 -0700, Chris Rebert wrote: > On Sat, May 1, 2010 at 6:32 PM, Steven D'Aprano > wrote: >> On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: >>> This doesn't preclude you from implementing a self-mutating += style >>> __add__ method and returning "self", but it's usually a bad idea >> >> Obviously the Python dev team don't agree with that :) >> >> Just to prove that += for lists is not an accident: [...] > In both cases, __iOP__ operator methods are being used, not vanilla > __OP__ methods, so neither of your examples are relevant to Mr. Chase's > point. I'm sorry, I read Tim's reference to __add__ (instead of __iadd__) as a typo. Having __add__ mutate self would be a strange thing to do. -- Steven From pmaupin at gmail.com Sat May 1 23:03:14 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 1 May 2010 20:03:14 -0700 (PDT) Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: <3c3d61cc-c714-4bea-91bc-b423a5dbdf99@g21g2000yqk.googlegroups.com> On May 1, 9:03?pm, Chris Rebert wrote: > In both cases, __iOP__ operator methods are being used, not vanilla > __OP__ methods, so neither of your examples are relevant to Mr. > Chase's point. Well, Tim's main assertion was: "The += family of operators really do rebind the symbol, not modify the object." So, using __iadd__ to disprove this blanket assertion is certainly relevant. Regards, Pat From dchichkov at gmail.com Sat May 1 23:06:24 2010 From: dchichkov at gmail.com (dmtr) Date: Sat, 1 May 2010 20:06:24 -0700 (PDT) Subject: Ignoring XML Namespaces with cElementTree References: <9527079b-92bf-4c59-af2b-ab2c84029f55@h37g2000pra.googlegroups.com> <7a4f1818-e77a-4238-b021-3e2c6da836ae@a18g2000prd.googlegroups.com> Message-ID: <74e6f0f1-1665-4902-9d1a-ccf9cfc2e2f7@u3g2000prl.googlegroups.com> > Unless you have multiple namespaces or are working with defined schema > or something, it's useless boilerplate. > > It'd be a nice feature if ElementTree could let users optionally > ignore a namespace, unfortunately it doesn't have it. Yep. Exactly my point. Here's a link to the patch addressing this: http://bugs.python.org/issue8583 From aahz at pythoncraft.com Sun May 2 00:06:48 2010 From: aahz at pythoncraft.com (Aahz) Date: 1 May 2010 21:06:48 -0700 Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: In article <4bdcd631$0$27782$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: >> >> The += family of operators really do rebind the symbol, not modify the >> object. > >They potentially do both, depending on the object, even for built-ins. No, they always rebind; sometimes they modify the object and sometimes they rebind the original target to the same object. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From stefan_ml at behnel.de Sun May 2 00:44:11 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 02 May 2010 06:44:11 +0200 Subject: [capi-sig] SWIG + expy In-Reply-To: <652256E5-5D3A-41DE-A7C5-6BED41F5944E@cwi.nl> References: <272522.69975.qm@web54204.mail.re2.yahoo.com> <652256E5-5D3A-41DE-A7C5-6BED41F5944E@cwi.nl> Message-ID: Jack Jansen, 01.05.2010 23:40: > I would be very interested in a universal intermediate format for all > the interface generators. I'm still using a version of Guido's old bgen, > now grudgingly extended to handle C++ and do bidirectional bridging > between Python and C++, and while I love and cherish the code generator > the C++ parser is, uhm... challenging. Parsing C++ with per-line regular > expressions is no fun:-) > > I looked at gccxml at some point, as well as at some of the competing > Python interface generators, but it went nowhere. gccxml output is far > too detailed, and the output is too much of a simple parse tree to be of > any use. The intermediate formats of the other interface generators I > looked at were all too inaccessible. > > Maybe we can come up with something decent in this group? This sounds like a good topic for the CAPI-sig group, rather than for c.l.py. I suggest keeping subsequent discussion there. Stefan From alfps at start.no Sun May 2 01:05:26 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 02 May 2010 07:05:26 +0200 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On 02.05.2010 06:06, * Aahz: > In article<4bdcd631$0$27782$c3e8da3 at news.astraweb.com>, > Steven D'Aprano wrote: >> On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: >>> >>> The += family of operators really do rebind the symbol, not modify the >>> object. >> >> They potentially do both, depending on the object, even for built-ins. > > No, they always rebind; sometimes they modify the object If they always rebind and sometimes modify object then they "potentially do both", and so the "No" at the start of the sentence contradicts this later part. > and sometimes > they rebind the original target to the same object. At the Python level that seems to be an undetectable null-operation. Granted one could see something going on in a machine code or byte code debugger. But making that distinction (doing nothing versus self-assignment) at the Python level seems, to me, to be meaningless. Cheers, - Alf From clp2 at rebertia.com Sun May 2 01:19:23 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 1 May 2010 22:19:23 -0700 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On Sat, May 1, 2010 at 10:05 PM, Alf P. Steinbach wrote: > On 02.05.2010 06:06, * Aahz: >> In article<4bdcd631$0$27782$c3e8da3 at news.astraweb.com>, >> Steven D'Aprano ?wrote: >>> >>> On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: >>>> >>>> The += family of operators really do rebind the symbol, not modify the >>>> object. >>> >>> They potentially do both, depending on the object, even for built-ins. >> >> No, they always rebind; sometimes they modify the object > > If they always rebind and sometimes modify object then they "potentially do > both", and so the "No" at the start of the sentence contradicts this later > part. > > >> and sometimes >> they rebind the original target to the same object. > > At the Python level that seems to be an undetectable null-operation. Granted > one could see something going on in a machine code or byte code debugger. > But making that distinction (doing nothing versus self-assignment) at the > Python level seems, to me, to be meaningless. There are some circumstances where the subtle distinction matters. Consider x.y += z where x is an instance of a class that overrides __setattr__ and __getattribute__ and x.y results in a mutable object. Not doing the assignment can result in a noticeable difference in behavior since __setattr__ won't get called. Yes, this is a slightly obscure case, but it does come up. Cheers, Chris -- http://blog.rebertia.com From porterj at alum.rit.edu Sun May 2 02:03:19 2010 From: porterj at alum.rit.edu (James Porter) Date: Sun, 02 May 2010 01:03:19 -0500 Subject: sometype.__new__ and C subclasses Message-ID: I've been trying to write a Python C extension module that uses NumPy and has a subtype of numpy.ndarray written in C. However, I've run into a snag: calling numpy.ndarray.__new__(mysubtype, ...) triggers an exception in the bowels of Python (this is necessary for a handful of NumPy features). I'm posting to this list to try to figure out why this exception exists in the first place, and what (if anything) I can do to work around it. The exception in question happens in Objects/typeobject.c in tp_new_wrapper. Here's the comment for the block: /* Check that the use doesn't do something silly and unsafe like object.__new__(dict). To do this, we check that the most derived base that's not a heap type is this type. */ The code has the end effect that basetype.__new__(subtype, ...) fails whenever subtype is a statically-defined type (i.e. a normal C extension type object). Why is this necessary in general? I can see why it might be bad for a limited number of core Python types, but it seems unnecessarily limiting for Python C extensions. On a more practical note, is there a way (short of rewriting the subtype in Python) to work around this? It seems that I could call the type metaclass to create a heap type in C, but I'm not sure of all the implications of that. Thanks in advance, Jim From kaleem.adil at gmail.com Sun May 2 02:03:22 2010 From: kaleem.adil at gmail.com (Adil Kaleem) Date: Sat, 1 May 2010 23:03:22 -0700 (PDT) Subject: Help needed in downloading Brown corpus References: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> <843870Fj4oU1@mid.individual.net> Message-ID: <3a537cd0-4716-420a-b271-0e9904566133@u20g2000pru.googlegroups.com> On May 1, 10:54?pm, Peter Pearson wrote: > > As I understand it (from Wikipedia), the Brown Corpus is a > collection of samples of modern American English text, and > nltk.org provides a Python toolkit for exploring said Corpus. > > I'm trying to figure out whether you're trying to get the > Corpus or the toolkit. ?Neither interpretation looks > plausible: if you're after the Corpus itself and you don't > know a bit of Python, why are you struggling with Python? > On the other hand, if you're after the toolkit, what's the > problem? People download Python modules all the time. ?And > besides, why would you be after the toolkit if you don't > know a bit of Python? > > If your goal is to learn enough Python to use the toolkit, > you'll find this newsgroup full of smart and helpful people. > > But you'll have to be a little more explicit about what > you're trying to do and more specific about what obstacles > you encounter. ?As you might see by looking at other threads > on this newsgroup, the queries that get the most prompt and > useful responses usually include blocks of quoted text of > the form "I type this [cut-and-pasted block] and get > this response [another cut-and-pasted block]." > > -- > To email me, substitute nowhere->spamcop, invalid->net. Hi Peter, Thanks for replying. Appreciate your pain in writing. I'm sorry I wasn't proper in my question. I downloaded the toolkit and from it I wanted to download the corpora. But since my system is behind the proxy (no direct connection), I couldn't download the corpora as was the process told for downloading using Python IDLE. The exact steps/ codes to write were given on the website for downloading but was only for a direct connection. I didn't knew the process of configuring IDLE for a proxy network for the download. And lastly since I'm unaware of Python programming, I faced the problem. This was my total essence of the problem and in this regard, I sought to take help from the very best of this language knowers i.e, you all. But nonetheless, I got my problem solved. One amongst you, Shashank Singh, in this group helped me in solving the problem. I thank him again for taking all the pain in making the system work for me. Thanks Shashank, I owe you man. Thank you Peter for giving your precious time in reading and replying to my problem. From kaleem.adil at gmail.com Sun May 2 02:09:24 2010 From: kaleem.adil at gmail.com (Adil Kaleem) Date: Sat, 1 May 2010 23:09:24 -0700 (PDT) Subject: Help needed in downloading Brown corpus References: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> <4bdcd5b2$0$27782$c3e8da3@news.astraweb.com> Message-ID: <867f8d34-64c0-4ce1-90e0-de8c9c30bf9a@n37g2000prc.googlegroups.com> On May 2, 6:30?am, Steven D'Aprano wrote: > On Sat, 01 May 2010 06:28:33 -0700, Adil Kaleem wrote: > > Hi all > > I'm a masters student in NLP. I needed to download the Brown corpus. I'm > > unable to download from nltk.org with the python CLI. My network > > connection is behind a proxy server so it's creating a problem. Since I > > don't know a bit of python, so unable to figure a way out. > > This has nothing to do with Python, it is a network issue. Talk to your > network administrator and get him to fix the proxy, or give you a way to > bypass it. Or if you have an internet connection at home, download it > from there. > > -- > Steven Hi Steven, It all had to do with configuring the network from Python IDLE, aliter: It all had to do with Python. I could have done it, the bypasssing. But I couldn't have learned anything if I hadn't fought with the problem, of course it was Shashank Singh from this group who helped me through. Bypassing is always not good, atleast for me and therefore I came to seek the help of you all. Thanks Steven in reading and replying to my problem. -- Adil From lie.1296 at gmail.com Sun May 2 02:28:28 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 02 May 2010 16:28:28 +1000 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4bdcce21$0$27782$c3e8da3@news.astraweb.com> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> <4bdcce21$0$27782$c3e8da3@news.astraweb.com> Message-ID: <4bdd1bea$1@dnews.tpgi.com.au> On 05/02/10 10:58, Steven D'Aprano wrote: >> > And Python's object system >> > makes it that the argument to __getattr__ is always a string even though >> > there might be a valid variable that corresponds to it: > That is nothing to do with the object system, it is related to the > semantics of Python syntax. a.b doesn't mean "apply the binary dot > operator to arguments a and b". It is syntactic sugar for "look for an > attribute named 'b' on object a". As such, the operands that __getattr__ > receives are the object a and the *name* b (implemented as a string). You just described *exactly* the reason why dot is not, and cannot be an operator. From lie.1296 at gmail.com Sun May 2 03:09:36 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 02 May 2010 17:09:36 +1000 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4bdcce21$0$27782$c3e8da3@news.astraweb.com> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> <4bdcce21$0$27782$c3e8da3@news.astraweb.com> Message-ID: <4bdd258e$1@dnews.tpgi.com.au> On 05/02/10 10:58, Steven D'Aprano wrote: > On Sun, 02 May 2010 05:08:53 +1000, Lie Ryan wrote: > >> > On 05/01/10 11:16, Steven D'Aprano wrote: >>> >> On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote: >>> >> >>> >> In practice though, I think that's a difference that makes no >>> >> difference. It walks like an operator, it swims like an operator, and >>> >> it quacks like an operator. >>> >> >>> >> >> > Nope it's not. A full-time operator in python have a reflected version >> > (e.g. __radd__), which dot does not have. > What are the reflected versions of __eq__ and __ne__ (binary == and != > operators)? Python do not have them now, but it does make sense if python have them[1]. OTOH, given current python's language semantic, __rgetattr__ doesn't make any sense; adding __rgetattr__ would require a quite fundamental change to the language's semantic, primarily how attribute resolution works. [1] though they'd probably be dismissed as bad idea since equality and inequality are supposed to be a symmetric relation; reflected (in)equality makes it way too easy to break that premise > And __neg__, __pos__ and __inv__ (for the unary - + and ~ operators)? > > And the three-argument form of __pow__ for power(1, 2, x)? I know you're a famed nitpicker, but don't be silly, reflected operator, by definition, only makes sense for binary operator. From news3 at mystrobl.de Sun May 2 03:16:10 2010 From: news3 at mystrobl.de (Wolfgang Strobl) Date: Sun, 02 May 2010 09:16:10 +0200 Subject: pyjamas 0.7 released References: <5cf8017c-d2e1-4ee4-b5d4-48e0cda19396@i37g2000yqn.googlegroups.com> <823f6745-c63a-45c5-a11e-860b7f344262@o11g2000yqj.googlegroups.com> <518it5t6hpvv4pdlue6cljmb09mse7ctov@4ax.com> <80d02ac5-b6ed-43fa-9508-67996cbedfde@b18g2000yqb.googlegroups.com> Message-ID: lkcl : > at least _some_ input would be good! the knowledge doesn't have to >be there: just the bugreports saying "there's a problem and here's >exactly how you reproduce it" would be a start! >> So please make it simpler for more people to help. > ... how?? there's a bugtracker, wiki, svn repository, over 30 >examples and a developer list. the code really _is_ very very small >(the UI widget set, with around 75 widgets, minus the license header >text is only around 4,000 lines _total_, making it very very simple >and very very easy for people to get used to). suggestions welcome! Well, the bunch of programming languages and APIs I collected over the years is large enough already. These days I prefer to stay with python and c, spiced with an occasional domain specific language. That's why I was attracted by pyjamas, to begin with!. If I'd like to program using Eclipse and Java or fool around with JavaScript, I'd do just that. But I don't. IMHO, that ist a general problem of translation tools - they attract the wrong people, from the point of view a developer who looks for people sharing some of the workload. :-) So, Luke, I can only answer your question from the point of view of somebody who is mostly a potentional consumer of your work, and most problably not another developer. If you want to delegate some work you'd like not to do yourself (for example because you prefer designing and coding to testing and reorganizing and polishing the docs), than you have at least to _define_ those pieces and to monitor progress. > >> Other people have >> other projects, where they invest some of their own time and money in. > > yes. been there. didn't receive any return on investment. did some >projects. received about 25% of required money to pay bills. need >?15k pa; receiving approximately ?7-8k. > >> >> ?I didn't look at >> >> every example again, but AFAIK, this didn't change with 0.7. (Tried with >> >> Python 2.6.4/5 on WinXP/7 with Firefox and Chrome, if that matters). >> >> > then please issue bugreports for as many as you feel comfortable >> >with / have time for. ? Well, ok. I put my notes in a Google chart, see http://spreadsheets.google.com/pub?key=0Au5LhqNQyrfCdGpDbTVjZFJwSERzVUFXVlg5bWl2enc I had to write a short patch against compile.py (see issue 397) in order to make it compile the showcase examples on Windows. In addition, I've tried to create Selenium tests for automating the time consuming job of checking all those examples, using Selenium IDE in Firefox. I was my first experience using this against Ajax apps. The results are somewhat mixed. Playing a round of "lightout" was a breeze, but so far I hadn't much luck in driving the showcase example(s). I didn't try very hard, though, because I ran out of time, as I do now. -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From tjreedy at udel.edu Sun May 2 04:04:11 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 May 2010 04:04:11 -0400 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On 5/2/2010 1:05 AM, Alf P. Steinbach wrote: > On 02.05.2010 06:06, * Aahz: >> and sometimes >> they rebind the original target to the same object. > > At the Python level that seems to be an undetectable null-operation. If you try t=(1,2,3); t[1]+=3, if very much matters that a rebind occurs. > Granted one could see something going on in a machine code or byte code > debugger. But making that distinction (doing nothing versus > self-assignment) at the Python level seems, to me, to be meaningless. Please do not confuse things. Augmented *assignment* must be understood as assignment. Failure to do so leads (and has lead) newbies into confusion, and puzzled posts on this list. Terry Jan Reedy From steve at REMOVE-THIS-cybersource.com.au Sun May 2 05:21:16 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 09:21:16 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> <4bdcce21$0$27782$c3e8da3@news.astraweb.com> <4bdd1bea$1@dnews.tpgi.com.au> Message-ID: <4bdd440b$0$27782$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 16:28:28 +1000, Lie Ryan wrote: > On 05/02/10 10:58, Steven D'Aprano wrote: >>> > And Python's object system >>> > makes it that the argument to __getattr__ is always a string even >>> > though there might be a valid variable that corresponds to it: >> That is nothing to do with the object system, it is related to the >> semantics of Python syntax. a.b doesn't mean "apply the binary dot >> operator to arguments a and b". It is syntactic sugar for "look for an >> attribute named 'b' on object a". As such, the operands that >> __getattr__ receives are the object a and the *name* b (implemented as >> a string). > > You just described *exactly* the reason why dot is not, and cannot be an > operator. This would be relevant if I said it was an operator. I did not. I said it was a de facto operator that behaves similarly enough to operators as to make it reasonable to talk about "dot operator". I still stand by that. That doesn't imply that Python's implementation of a.b has to be identical in every last detail to Python's implementation of a+b, because it clearly isn't. But there are sufficient similarities to justify saying that it duck-types as an operator. This isn't meant to be a vigorous statement of fact in the same manner than "CPython implements lists as arrays of pointers" is a statement of fact. It's meant to be a hand-wavy "dot act kinda-sorta like an operator" manner. I'm sorry if I failed to make that clear enough. I thought that explicitly stating that it wasn't a real operator would be sufficient. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun May 2 05:24:23 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 09:24:23 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> <4bdcce21$0$27782$c3e8da3@news.astraweb.com> <4bdd258e$1@dnews.tpgi.com.au> Message-ID: <4bdd44c7$0$27782$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 17:09:36 +1000, Lie Ryan wrote: > On 05/02/10 10:58, Steven D'Aprano wrote: >> On Sun, 02 May 2010 05:08:53 +1000, Lie Ryan wrote: >> >>> > On 05/01/10 11:16, Steven D'Aprano wrote: >>>> >> On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote: >>>> >> >>>> >> In practice though, I think that's a difference that makes no >>>> >> difference. It walks like an operator, it swims like an operator, >>>> >> and it quacks like an operator. >>>> >> >>>> >> >>> > Nope it's not. A full-time operator in python have a reflected >>> > version (e.g. __radd__), which dot does not have. >> What are the reflected versions of __eq__ and __ne__ (binary == and != >> operators)? > > Python do not have them now, but it does make sense if python have > them[1]. OTOH, given current python's language semantic, __rgetattr__ > doesn't make any sense; adding __rgetattr__ would require a quite > fundamental change to the language's semantic, primarily how attribute > resolution works. > > [1] though they'd probably be dismissed as bad idea since equality and > inequality are supposed to be a symmetric relation; reflected > (in)equality makes it way too easy to break that premise > >> And __neg__, __pos__ and __inv__ (for the unary - + and ~ operators)? >> >> And the three-argument form of __pow__ for power(1, 2, x)? > > I know you're a famed nitpicker, but don't be silly, reflected operator, > by definition, only makes sense for binary operator. Binary operators aren't the only kind of operator, and you claimed that: "A full-time operator in python have a reflected version". But there are full-time operators that don't have reflected versions, so your claim is just *wrong*. It would still be wrong even if you had limited yourself to binary operators. I have agreed with you that there are useful things people might want to do (e.g. function composition) that you can't do because the "dot operator" isn't a *real* operator with exactly the same semantics as "plus operator", "multiply operator" and friends. I think we're in violent agreement, and merely disagreeing over semantics. There's no need to continue arguing against a position I haven't actually taken :) -- Steven From pavlovevidence at gmail.com Sun May 2 05:34:54 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 02:34:54 -0700 (PDT) Subject: sometype.__new__ and C subclasses References: Message-ID: On May 1, 11:03?pm, James Porter wrote: > I've been trying to write a Python C extension module that uses NumPy > and has a subtype of numpy.ndarray written in C. However, I've run into > a snag: calling numpy.ndarray.__new__(mysubtype, ...) triggers an > exception in the bowels of Python (this is necessary for a handful of > NumPy features). I'm posting to this list to try to figure out why this > exception exists in the first place, and what (if anything) I can do to > work around it. > > The exception in question happens in Objects/typeobject.c in > tp_new_wrapper. Here's the comment for the block: > > ? ? ? ? /* Check that the use doesn't do something silly and unsafe like > ? ? ? ? ? ?object.__new__(dict). ?To do this, we check that the > ? ? ? ? ? ?most derived base that's not a heap type is this type. */ > > The code has the end effect that basetype.__new__(subtype, ...) fails > whenever subtype is a statically-defined type (i.e. a normal C extension > type object). Why is this necessary in general? I can see why it might > be bad for a limited number of core Python types, but it seems > unnecessarily limiting for Python C extensions. Why don't you use mysubtype.__new__(mysubtype,...)? If you wrote mysubtype in C, and defined a different tp_new than ndarray, then this exception will trigger. And it ought to; you don't want to use ndarray's tp_new to create an object of your subclass, if you've defined a different tp_new. > On a more practical note, is there a way (short of rewriting the subtype > in Python) to work around this? It seems that I could call the type > metaclass to create a heap type in C, but I'm not sure of all the > implications of that. It should work if you use mysubtype.__new__(mysubtype,...). If it doesn't do what you want, then there's probably something wrong with the way you subclassed ndarray. Carl Banks From pavlovevidence at gmail.com Sun May 2 05:52:13 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 02:52:13 -0700 (PDT) Subject: PyObject_SetAttrString - doesn't set instance attribute References: <82ae0f7b-e5f4-4b85-a9fb-aef16de10af2@a39g2000prb.googlegroups.com> Message-ID: <1579c863-c7e2-47ba-ae45-b3ba74eff40c@a39g2000prb.googlegroups.com> On May 1, 4:04?am, Jason wrote: > I'm having a bit of trouble with C/Python bindings. Particularly, > trying to set an instance variable from C when the object is > initialised using PyObject_SetAttrString, but nothing seems to happen. > The C initialisation code is: > > static void > nautilus_python_object_instance_init (NautilusPythonObject *object) > { > > ? ? ? ? fprintf(stderr, "nautilus_python_object_instance_init called\n"); > > ? ? ? ? NautilusPythonObjectClass *class; > ? ? ? ? debug_enter(); > > ? ? ? ? class = (NautilusPythonObjectClass*)(((GTypeInstance*)object)- > > >g_class); > > ? ? ? ? object->instance = PyObject_CallObject(class->type, NULL); > > ? ? ? ? PyObject* test_int = PyInt_FromLong(42); > > ? ? ? ? if (object->instance == NULL) > ? ? ? ? { > ? ? ? ? ? ? ? ? PyErr_Print(); > ? ? ? ? } > ? ? ? ? else > ? ? ? ? { > ? ? ? ? ? ? ? ? fprintf(stderr, "Setting magic parameter\n"); > ? ? ? ? ? ? ? ? fprintf(stderr, "From C: "); > ? ? ? ? ? ? ? ? PyObject_Print(object->instance, stderr, 0); > ? ? ? ? ? ? ? ? fprintf(stderr, "\n"); > ? ? ? ? ? ? ? ? int retval = PyObject_SetAttrString(object->instance, > "super_happy_magic", test_int); > ? ? ? ? ? ? ? ? fprintf(stderr, "Result: %i\n", retval); > ? ? ? ? } > > ? ? ? ? Py_DECREF(test_int); > > } Not sure what you're doing here. It looks like you are being passed an object of a given type, then you get the type object, call it to create another object of that type, and assign it to object->instance. > ...and the Python module contains: > > class MenuProviderTest(nautilus.MenuProvider): > > ? ? def __init__(self): > ? ? ? ? print "From Python: %s" % self > > ? ? ? ? try: > ? ? ? ? ? ? print getattr(self, "super_happy_magic") > ? ? ? ? except AttributeError: > ? ? ? ? ? ? print "Didn't work!" > > When the MenuProviderTest is created, the output is: > > nautilus_python_object_instance_init called > Setting magic parameter > From C: > Result: 0 > From Python: > Didn't work! > > (I've tried getattr and self.super_happy_magic, with the same effect.) > > Where am I going wrong? You are assigning the attirbute the the object that the C code refers to as "object->instance", but it seems that in the Python snippet you are calling getattr on the object that the C code refers to as "object". Carl Banks From michelparker at live.com Sun May 2 06:00:14 2010 From: michelparker at live.com (michel parker) Date: Sun, 2 May 2010 11:00:14 +0100 Subject: help error : Failed to build these modules: _dbm Message-ID: Hi, When i make python 3.1 on my ubuntu 9.10 i get following error : Failed to build these modules: _dbm Please help me. I have done : apt-get build-dep python2.5 but to no avail. Cheers _________________________________________________________________ Hotmail: Free, trusted and rich email service. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun May 2 06:08:55 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 10:08:55 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: <4bdd4f37$0$27782$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 04:04:11 -0400, Terry Reedy wrote: > On 5/2/2010 1:05 AM, Alf P. Steinbach wrote: >> On 02.05.2010 06:06, * Aahz: > >>> and sometimes >>> they rebind the original target to the same object. >> >> At the Python level that seems to be an undetectable null-operation. > > If you try t=(1,2,3); t[1]+=3, if very much matters that a rebind > occurs. > >> Granted one could see something going on in a machine code or byte code >> debugger. But making that distinction (doing nothing versus >> self-assignment) at the Python level seems, to me, to be meaningless. > > Please do not confuse things. Augmented *assignment* must be understood > as assignment. Failure to do so leads (and has lead) newbies into > confusion, and puzzled posts on this list. I think that if you think *only* about Python's standard namespaces, self- assignment is more or less a no-op. I can't think of any way that x = x could do anything other than use CPU cycles, *if* you limit yourself to the standard global or function local namespaces. But if you think about custom namespace types, and item assignment (e.g. the example you gave with a tuple), the situation becomes different. Here's a nice example, using Python 3.1: >>> class B(A): # class A defined elsewhere -- see below. ... x = 1 ... x = x ... Traceback (most recent call last): File "", line 1, in File "", line 3, in B File "", line 4, in __setitem__ TypeError: can't rebind constants Thus proving that self-assignment is not necessarily a no-op. How did I make that work? It takes a custom dict and a bit of metaclass magic: class ConstantNamespace(dict): def __setitem__(self, key, value): if key in self: raise TypeError("can't rebind constants") super(ConstantNamespace, self).__setitem__(key, value) class WriteOnceClass(type): @classmethod def __prepare__(metacls, name, bases): return ConstantNamespace() def __new__(cls, name, bases, classdict): return type.__new__(cls, name, bases, classdict) class A(metaclass=WriteOnceClass): pass -- Steven From jason.heeris at gmail.com Sun May 2 06:26:46 2010 From: jason.heeris at gmail.com (Jason) Date: Sun, 2 May 2010 03:26:46 -0700 (PDT) Subject: PyObject_SetAttrString - doesn't set instance attribute References: <82ae0f7b-e5f4-4b85-a9fb-aef16de10af2@a39g2000prb.googlegroups.com> <1579c863-c7e2-47ba-ae45-b3ba74eff40c@a39g2000prb.googlegroups.com> Message-ID: <751257bd-5d92-4ec9-bec9-41369b5d31e5@y18g2000prn.googlegroups.com> On May 2, 5:52?pm, Carl Banks wrote: > Not sure what you're doing here. ?It looks like you are being passed > an object of a given type, then you get the type object, call it to > create another object of that type, and assign it to object->instance. Sorry, I should have noted that the "NautilusPythonObject" type in the code is a struct defined as: struct _NautilusPythonObject { GObject parent_slot; PyObject *instance; }; > You are assigning the attirbute the the object that the C code refers > to as "object->instance", but it seems that in the Python snippet you > are calling getattr on the object that the C code refers to as > "object". object->instance is the PyObject, and I gathered that it was the correct thing to assign to from the fact that the address is identical as seen from C and Python. ? Jason From kushal.kumaran+python at gmail.com Sun May 2 07:08:28 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sun, 2 May 2010 16:38:28 +0530 Subject: help error : Failed to build these modules: _dbm In-Reply-To: References: Message-ID: On Sun, May 2, 2010 at 3:30 PM, michel parker wrote: > Hi, > When i make python 3.1 on my ubuntu 9.10 i get following error : > > Failed to build these modules: > _dbm > Please help me. > I have done : > > apt-get build-dep python2.5 > > but to no avail. > Cheers > > Probably the packages libdb4.7-dev (if you want berkeley db) or libgdbm-dev (if you want gnu dbm). ISTR there was a thread about this just a couple of days ago. -- regards, kushal From michelparker at live.com Sun May 2 07:56:57 2010 From: michelparker at live.com (michel parker) Date: Sun, 2 May 2010 12:56:57 +0100 Subject: help error : Failed to build these modules: _dbm In-Reply-To: References: , Message-ID: hi, yup problem solved module was missing libgdbm-dev > From: kushal.kumaran+python at gmail.com > Date: Sun, 2 May 2010 16:38:28 +0530 > Subject: Re: help error : Failed to build these modules: _dbm > To: michelparker at live.com > CC: python-list at python.org > > On Sun, May 2, 2010 at 3:30 PM, michel parker wrote: > > Hi, > > When i make python 3.1 on my ubuntu 9.10 i get following error : > > > > Failed to build these modules: > > _dbm > > Please help me. > > I have done : > > > > apt-get build-dep python2.5 > > > > but to no avail. > > Cheers > > > > > > Probably the packages libdb4.7-dev (if you want berkeley db) or > libgdbm-dev (if you want gnu dbm). > > ISTR there was a thread about this just a couple of days ago. > > -- > regards, > kushal _________________________________________________________________ Hotmail: Trusted email with powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From michelparker at live.com Sun May 2 07:59:35 2010 From: michelparker at live.com (michel parker) Date: Sun, 2 May 2010 12:59:35 +0100 Subject: help req setting python executable Message-ID: hi, i have just installed python3.1 with opt=g option. but when i set python executable in wingide to usr/local/bin/python3.1 it says : Some values are invalid: - Python executable 'usr/local/bin/python3.1' is not in path Please correct the values and try again. Please help. What is going to be correct pythonpath for me. i have installed python using standard sudo make install method. Cheers _________________________________________________________________ Hotmail: Powerful Free email with security by Microsoft. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmitrey.kroshko at scipy.org Sun May 2 08:11:40 2010 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 2 May 2010 05:11:40 -0700 (PDT) Subject: Bug in Python set Message-ID: <0bd314a8-db65-43f1-a999-521e2ed71cad@n15g2000yqf.googlegroups.com> Python 2.6.5 r265:79063 >>>set().update(set()) is None True while I expect result of update to be set. Also, result of set().add(None) is None while I expect it to be set with element None (or, maybe, it should be empty set?) Regards, D. From albert at spenarnc.xs4all.nl Sun May 2 08:12:23 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 02 May 2010 12:12:23 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: In article , Jean-Michel Pichavant wrote: >Jabapyth wrote: >> At least a few times a day I wish python had the following shortcut >> syntax: >> >> vbl.=func(args) >> >> this would be equivalent to >> >> vbl = vbl.func(args) >> >> example: >> >> foo = "Hello world" >> foo.=split(" ") >> print foo >> # ['Hello', 'world'] >> >> and I guess you could generalize this to >> >> vbl.=[some text] >> # >> vbl = vbl.[some text] >> >> e.g. >> >> temp.=children[0] >> # temp = temp.children[0] >> >> thoughts? >> >Useless if you use meaningful names for your variables & attributes. > >It may happen that one object attribute refer to an object of the same >type, but it is quite rare that both can share the same name anyway. > >Possible use cases: > >1/ >car = Car() >car = car.wheel # ??? > >2/ >wheel = Car() # ??? >wheel = wheel.wheel # ??? > >3/ >currentCar = Car() >currentCar = currentCar.nextCar > >The syntax you prose will be applicable on very little assignements (use >case 3). I'm not sure it's worth it. Note how related it is to the requirement to have a _radd_ operator. It amounts to the argument that a op= b requires that a and b have somewhat "similar" "type", or that the "type" of a doesn't really change as a result from the operation. This is IMHO an argument against the .= pseudo-operator. > >JM Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From __peter__ at web.de Sun May 2 08:13:02 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2010 14:13:02 +0200 Subject: recommended way to insert data into a one to many relationship using python References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Peter Otten wrote: If you create indices for floors (and rooms) cur.execute("""create unique index room_index on rooms (fid, number);""") cur.execute("""create unique index floor_index on floors (floor);""") the addition of missing rows can be simplified to missing = c2.execute("""select distinct floor from new_employees;""") cur.executemany("insert or ignore into floors (floor) values (?)", missing) etc. Peter From aahz at pythoncraft.com Sun May 2 08:23:23 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 May 2010 05:23:23 -0700 Subject: Bug in Python set References: <0bd314a8-db65-43f1-a999-521e2ed71cad@n15g2000yqf.googlegroups.com> Message-ID: In article <0bd314a8-db65-43f1-a999-521e2ed71cad at n15g2000yqf.googlegroups.com>, dmitrey wrote: > >Python 2.6.5 r265:79063 >>>>set().update(set()) is None >True >while I expect result of update to be set. >Also, result of >set().add(None) >is None while I expect it to be set with element None (or, maybe, it >should be empty set?) Why are you assuming that your expectations are correct? Generally speaking, Python methods that mutate do *not* return the original object, precisely to make sure you don't make stupid mistakes. You should probably read this: http://www.catb.org/~esr/faqs/smart-questions.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From albert at spenarnc.xs4all.nl Sun May 2 08:23:45 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 02 May 2010 12:23:45 GMT Subject: matching strings in a large set of strings References: <877hnpjtdw.fsf@rudin.co.uk> Message-ID: In article <877hnpjtdw.fsf at rudin.co.uk>, Paul Rudin wrote: >"Karin Lagesen" writes: > >> Hello. >> >> I have approx 83 million strings, all 14 characters long. I need to be >> able to take another string and find out whether this one is present >> within the 83 million strings. >> >> Now, I have tried storing these strings as a list, a set and a dictionary. >> I know that finding things in a set and a dictionary is very much faster >> than working with a list, so I tried those first. However, I run out of >> memory building both the set and the dictionary, so what I seem to be left >> with is the list, and using the in method. >> >> I imagine that there should be a faster/better way than this? >> > >Shouldn't a set with 83 million 14 character strings be fine in memory >on a stock PC these days? I suppose if it's low on ram you might start >swapping which will kill performance. Perhaps the method you're using to >build the data structures creates lots of garbage? How much ram do you >have and how much memory does the python process use as it builds your >data structures? And if this is practical there should be no swapping problems, as the working set will be a small fraction of the data used. > >There are other algorithms you can use that have better theoretical >performance than using bisect for this particular problem, but you get >into trade offs between executing things in python as opposed to C if >you start to hand code things in python. There are a lot of possibility, but they depend a great deal on secondary conditions, like how often the 83 M dataset changes. Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From steve at REMOVE-THIS-cybersource.com.au Sun May 2 09:12:10 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 13:12:10 GMT Subject: Bug in Python set References: <0bd314a8-db65-43f1-a999-521e2ed71cad@n15g2000yqf.googlegroups.com> Message-ID: <4bdd7a2a$0$27857$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 05:11:40 -0700, dmitrey wrote: > Python 2.6.5 r265:79063 >>>>set().update(set()) is None > True > while I expect result of update to be set. Change your expectations. Generally, methods which modify the object rather than creating a new one return None. >>> s = set([1,2,3]) >>> s.update(set([3, 4, 5])) >>> s {1, 2, 3, 4, 5} > Also, result of set().add(None) is None while I expect it to be set > with element None (or, maybe, it should be empty set?) >>> s = set() >>> s.add(None) >>> s {None} Python sets have been used by tens of thousands of programmers for many years now. Which do you think is more likely? (1) Not one person before you noticed that something as fundamental as adding an item to a set is buggy; or (2) You have misunderstood what is happening? -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun May 2 10:57:30 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 14:57:30 GMT Subject: List size versus list allocation Message-ID: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> Python lists are over-allocated: whenever they need to be resized, they are made a little bit larger than necessary so that appends will be fast. See: http://code.python.org/hg/trunk/file/e9d930f8b8ff/Objects/listobject.c I'm interested in gathering some statistics on this, and to do so I need a way of measuring the list's logical size versus its actual size. The first is easy: it's just len(list). Is there some way of getting the allocated size of the list? -- Steven From hansmu at xs4all.nl Sun May 2 11:07:29 2010 From: hansmu at xs4all.nl (Hans Mulder) Date: Sun, 02 May 2010 17:07:29 +0200 Subject: Fast Efficient way to transfer an object to another list In-Reply-To: <06366a6d-e3db-4963-bcc0-0bc03d035a94@e2g2000yqn.googlegroups.com> References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> <06366a6d-e3db-4963-bcc0-0bc03d035a94@e2g2000yqn.googlegroups.com> Message-ID: <4bdd953c$0$22933$e4fe514c@news.xs4all.nl> Francesco Bochicchio wrote: > Anyway i think that list.extract( old_list, predicate ) -> new_list > would be a nice addition to the standard library You could use filter( predicate, old_list ) -> new_list -- HansM From darcy at druid.net Sun May 2 11:10:10 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 2 May 2010 11:10:10 -0400 Subject: help req setting python executable In-Reply-To: References: Message-ID: <20100502111010.5ef5748d.darcy@druid.net> On Sun, 2 May 2010 12:59:35 +0100 michel parker wrote: > > hi, > i have just installed python3.1 with opt=g option. > but when i set python executable in wingide to usr/local/bin/python3.1 it says : I don't know anything about wingide but I think your problem is simply a missing slash. /usr/local/bin/python3.1 -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From __peter__ at web.de Sun May 2 11:52:05 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2010 17:52:05 +0200 Subject: List size versus list allocation References: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Python lists are over-allocated: whenever they need to be resized, they > are made a little bit larger than necessary so that appends will be fast. > > See: > > http://code.python.org/hg/trunk/file/e9d930f8b8ff/Objects/listobject.c > > I'm interested in gathering some statistics on this, and to do so I need > a way of measuring the list's logical size versus its actual size. The > first is easy: it's just len(list). Is there some way of getting the > allocated size of the list? With some brute force guesswork... >>> a = [None] * 42 >>> for i in range(10): ... print i, ctypes.c_ulong.from_address(id(a)+i*8) ... 0 c_ulong(1L) 1 c_ulong(8488896L) 2 c_ulong(42L) 3 c_ulong(37432768L) 4 c_ulong(42L) 5 c_ulong(1L) 6 c_ulong(8510496L) 7 c_ulong(32L) 8 c_ulong(18446744073709551615L) 9 c_ulong(8935143189711421440L) >>> a = [] >>> for i in range(42): a.append(None) ... >>> for i in range(10): ... print i, ctypes.c_ulong.from_address(id(a)+i*8) ... 0 c_ulong(1L) 1 c_ulong(8488896L) 2 c_ulong(42L) 3 c_ulong(40136160L) 4 c_ulong(46L) 5 c_ulong(0L) 6 c_ulong(0L) 7 c_ulong(0L) 8 c_ulong(0L) 9 c_ulong(0L) ... you can see that the size sits at offset 4*sizeof(long) on my 64-bit Python. With that information we can take a look at a list's overallocation strategy: >>> a = [] >>> for i in range(20): ... print i, ctypes.c_ulong.from_address(id(a)+4*8) ... a.append(None) ... 0 c_ulong(0L) 1 c_ulong(4L) 2 c_ulong(4L) 3 c_ulong(4L) 4 c_ulong(4L) 5 c_ulong(8L) 6 c_ulong(8L) 7 c_ulong(8L) 8 c_ulong(8L) 9 c_ulong(16L) 10 c_ulong(16L) 11 c_ulong(16L) 12 c_ulong(16L) 13 c_ulong(16L) 14 c_ulong(16L) 15 c_ulong(16L) 16 c_ulong(16L) 17 c_ulong(25L) 18 c_ulong(25L) 19 c_ulong(25L) Peter From lists at cheimes.de Sun May 2 12:07:31 2010 From: lists at cheimes.de (Christian Heimes) Date: Sun, 02 May 2010 18:07:31 +0200 Subject: List size versus list allocation In-Reply-To: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> References: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> Message-ID: > I'm interested in gathering some statistics on this, and to do so I need > a way of measuring the list's logical size versus its actual size. The > first is easy: it's just len(list). Is there some way of getting the > allocated size of the list? With Python 2.6 and newer you can use sys.getsizeof() to get the actual size of the list object: >>> import sys, struct >>> sys.getsizeof([]) 72 >>> a = [1,2,3] >>> b = [] >>> b.append(1) >>> b.append(2) >>> b.append(3) >>> sys.getsizeof(a) 96 >>> sys.getsizeof(b) 104 >>> def slots(lst): ... return (sys.getsizeof(lst) - sys.getsizeof([])) / struct.calcsize("P") ... >>> slots(b) 4 >>> slots(a) 3 Christian From __peter__ at web.de Sun May 2 12:24:37 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2010 18:24:37 +0200 Subject: List size versus list allocation References: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> Message-ID: Christian Heimes wrote: >>>> def slots(lst): > ... return (sys.getsizeof(lst) - sys.getsizeof([])) / D'oh! Peter From ptmcg at austin.rr.com Sun May 2 13:14:44 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 2 May 2010 10:14:44 -0700 (PDT) Subject: condition and True or False Message-ID: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> While sifting through some code looking for old "x and y or z" code that might better be coded using "y if x else z", I came across this puzzler: x = and True or False What is "and True or False" adding to this picture? The boolean expression part is already evaluating to a boolean, so I don't understand why a code author would feel compelled to beat this one over the head with the additional "and True or False". I did a little code Googling and found a few other Python instances of this, but also many Lua instances. I'm not that familiar with Lua, is this a practice that one who uses Lua frequently might carry over to Python, not realizing that the added "and True or False" is redundant? Other theories? -- Paul From porterj at alum.rit.edu Sun May 2 13:48:01 2010 From: porterj at alum.rit.edu (James Porter) Date: Sun, 02 May 2010 12:48:01 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 5/2/2010 4:34 AM, Carl Banks wrote: > Why don't you use mysubtype.__new__(mysubtype,...)? > > If you wrote mysubtype in C, and defined a different tp_new than > ndarray, then this exception will trigger. And it ought to; you don't > want to use ndarray's tp_new to create an object of your subclass, if > you've defined a different tp_new. Unfortunately, I can't do that, since that call is in NumPy itself and it's part of their "standard" way of making instances of subclasses of ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, ...) to create new arrays based on the shape of other arrays. The Python version of the subclass is shown here: , and I'm trying to write something pretty similar in C. I'm trying to stay in C since everything else is in C, so it's easier to stay in C then to jump back and forth all the time. Maybe the real answer to this question is "NumPy is doing it wrong" and I should be on their list; still, it seems strange that the behavior is different between Python and C. - Jim From mount.sarah at gmail.com Sun May 2 14:06:52 2010 From: mount.sarah at gmail.com (Sarah Mount) Date: Sun, 2 May 2010 19:06:52 +0100 Subject: Python debuggers with sys.settrace() Message-ID: This is a bit of an odd question, but is there any way for a Python debugger to suppress I/O generated by the program which is being debugged? I guess an "obvious" thing to do would be to replace core parts of the standard library and change any relevant imports in the locals and globals dicts to fake ones which don't generate I/O, but this seems brittle as the standard library will change over time. Is it possible to modify the byte-compiled code in each stack frame? Or is there a simpler way to do this? Many thanks, Sarah -- Sarah Mount, Senior Lecturer, University of Wolverhampton website: http://www.snim2.org/ twitter: @snim2 From __peter__ at web.de Sun May 2 14:13:42 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2010 20:13:42 +0200 Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > x = and True or False > > What is "and True or False" adding to this picture? The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one > over the head with the additional "and True or False". > > I did a little code Googling and found a few other Python instances of > this, but also many Lua instances. I'm not that familiar with Lua, is > this a practice that one who uses Lua frequently might carry over to > Python, not realizing that the added "and True or False" is redundant? > > Other theories? If it were e. g. def f(): big_beast = list(range(10**100)) return big_beast and True or False x = f() it would prevent that a big_beast reference becomes visible outside the function and allow for immediate release of its memory. Peter From nulla.epistola at web.de Sun May 2 14:28:54 2010 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 02 May 2010 20:28:54 +0200 Subject: assigning multi-line strings to variables In-Reply-To: <34ec4b50-7a05-46af-aeed-a123e62a9267@z30g2000yqz.googlegroups.com> References: <7d91e94e-88fe-43e3-817e-b9a8f5cdb16a@u34g2000yqu.googlegroups.com> <4e25733e-eafa-477b-a84d-a64d139f7134@u34g2000yqu.googlegroups.com> <4bd868bd$1@dnews.tpgi.com.au> <4bd89846$1@dnews.tpgi.com.au> <83t5esFbnhU1@mid.individual.net> <34ec4b50-7a05-46af-aeed-a123e62a9267@z30g2000yqz.googlegroups.com> Message-ID: goldtech schrieb: > Thank you to posters for help to my question. Seems I had trouble with > triple quotes strings in the PythonWin shell. But using the Idle shell > things work as expected. But this is probably another issue...any way, > w/Idle's shell I got the "action" regarding multiline strings I > expected. What PythonWin version? I remember having had such trouble years ago, probably Python 1.something. Greetings Sibylle From zak.mc.kraken at libero.it Sun May 2 14:35:29 2010 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Sun, 02 May 2010 20:35:29 +0200 Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: Peter Otten wrote: > def f(): > big_beast = list(range(10**100)) > return big_beast and True or False > x = f() > > it would prevent that a big_beast reference becomes visible outside the > function and allow for immediate release of its memory. what's wrong in bool(big_beast)? -- By ZeD From robert.kern at gmail.com Sun May 2 14:43:08 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 02 May 2010 13:43:08 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 2010-05-02 12:48 , James Porter wrote: > On 5/2/2010 4:34 AM, Carl Banks wrote: >> Why don't you use mysubtype.__new__(mysubtype,...)? >> >> If you wrote mysubtype in C, and defined a different tp_new than >> ndarray, then this exception will trigger. And it ought to; you don't >> want to use ndarray's tp_new to create an object of your subclass, if >> you've defined a different tp_new. > > Unfortunately, I can't do that, since that call is in NumPy itself and > it's part of their "standard" way of making instances of subclasses of > ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, > ...) to create new arrays based on the shape of other arrays. > > The Python version of the subclass is shown here: > , > and I'm trying to write something pretty similar in C. I'm trying to > stay in C since everything else is in C, so it's easier to stay in C > then to jump back and forth all the time. > > Maybe the real answer to this question is "NumPy is doing it wrong" and > I should be on their list; still, it seems strange that the behavior is > different between Python and C. Perhaps things would be clearer if you could post the C code that you've written that fails. So far, you've only alluded at what you are doing using Python-syntax examples. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bryanjugglercryptographer at yahoo.com Sun May 2 15:05:32 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sun, 2 May 2010 12:05:32 -0700 (PDT) Subject: recommended way to insert data into a one to many relationship using python References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <16f716de-8a0c-455c-8eb5-dbed332a81fe@h20g2000prn.googlegroups.com> Wolfgang Meiners wrote: > one to many relationships are fairly common, i think. So there should be > a recommended way to insert data into such a relation using python. > > Given the following programm, what is the recommended way to insert the > list of NewEmployees to the database? > > ======================================================================== > # !python > # -*- coding: utf-8 -*- > > import sqlite3 > > con = sqlite3.connect(":memory:") > cur = con.cursor() > > cur.execute("""create table employees( > ? ? eid integer primary key autoincrement, > ? ? name text not null, > ? ? rid integer references rooms(rid))""") > > cur.execute("""create table rooms( > ? ? rid integer primary key autoincrement, > ? ? number integer, > ? ? fid integer references floors(fid))""") > > cur.execute("""create table floors( > ? ? fid integer primary key autoincrement, > ? ? floor text not null)""") > [...] > > NewEmployees ?=[] > NewEmployees.append({'name': 'George', 'room': 89, 'floor': 'third floor'}) > NewEmployees.append({'name': 'Ellen', 'room': 21, 'floor': 'first floor'}) > For that kind of insert to be well-defined, the pair (floor, room_number) must uniquely identify a room. When natural keys like that are availabe, they're the obvious choice for primary keys in the database schema. I suggested getting rid of fid and rid, as in: schema = """ CREATE TABLE floors ( floor TEXT PRIMARY KEY ); CREATE TABLE rooms ( floor TEXT REFERENCES floors, number INTEGER, PRIMARY KEY (floor, number) ); CREATE TABLE employees ( eid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, floor TEXT, room_number INTEGER, FOREIGN KEY (floor, room_number) REFERENCES rooms ) """ con = sqlite3.connect(":memory:") for cmd in schema.split(';'): con.execute(cmd) con.close() -- --Bryan From tjreedy at udel.edu Sun May 2 15:23:05 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 May 2010 15:23:05 -0400 Subject: Bug in Python set In-Reply-To: <0bd314a8-db65-43f1-a999-521e2ed71cad@n15g2000yqf.googlegroups.com> References: <0bd314a8-db65-43f1-a999-521e2ed71cad@n15g2000yqf.googlegroups.com> Message-ID: On 5/2/2010 8:11 AM, dmitrey wrote: > Python 2.6.5 r265:79063 >>>> set().update(set()) is None > True > while I expect result of update to be set. > Also, result of > set().add(None) > is None while I expect it to be set with element None (or, maybe, it > should be empty set?) 'Expect' has two different meanings in this context. 1. The empirical behavior surprised me (because I did not bother to read the manual, which clearly says what the returns are). 2. The documented behavior, which I read, surprises me, because I would have designed things differently, perhaps because I have used other languages designed differently. I am not sure which you meant. From andreas.loescher at s2005.tu-chemnitz.de Sun May 2 15:54:03 2010 From: andreas.loescher at s2005.tu-chemnitz.de (Andreas =?ISO-8859-1?Q?L=F6scher?=) Date: Sun, 02 May 2010 21:54:03 +0200 Subject: Parser Message-ID: <1272830042.14469.1.camel@laptop> Hi, I am looking for an easy to use parser. I am want to get an overview over parsing and want to try to get some information out of a C-Header file. Which parser would you recommend? Best, Andreas From porterj at alum.rit.edu Sun May 2 16:03:45 2010 From: porterj at alum.rit.edu (James Porter) Date: Sun, 02 May 2010 15:03:45 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 5/2/2010 1:43 PM, Robert Kern wrote: > Perhaps things would be clearer if you could post the C code that you've > written that fails. So far, you've only alluded at what you are doing > using Python-syntax examples. I'm not sure how much this will help, but here you go. The actual C code probably doesn't matter except for where I set tp_flags, tp_new, and register the type, but I included it for completeness. The full C source is available here if you need it, but be warned that other strangeness abounds in the code: . Obviously, this is kind of a bizarre case, so I'm not entirely sure what the best route is here. Thanks, Jim static PyObject* iMeshArrObj_new(PyTypeObject *cls,PyObject *args,PyObject *kw) { static char *kwlist[] = {"object","instance",0}; PyObject *obj; iMesh_Object *instance = NULL; PyObject *arr = NULL; iMeshArr_Object *self; if(!PyArg_ParseTupleAndKeywords(args,kw,"O|O!",kwlist,&obj, &iMesh_Type,&instance)) return NULL; arr = PyArray_FROM_O(obj); if(arr == NULL) return NULL; self = (iMeshArr_Object*)PyObject_CallMethod(arr,"view","O",cls); Py_DECREF(arr); if(self == NULL) return NULL; /* some boring stuff to set |instance| */ return self; } static void iMeshArrObj_dealloc(iMeshArr_Object *self) { Py_XDECREF(self->instance); self->array.ob_type->tp_free((PyObject*)self); } static PyObject* iMeshArrObj_finalize(iMeshArr_Object *self,PyObject *args) { iMeshArr_Object *context; if(PyArg_ParseTuple(args,"O!",&iMeshArr_Type,&context)) { self->instance = context->instance; Py_XINCREF(self->instance); } PyErr_Clear(); Py_RETURN_NONE; } static PyMethodDef iMeshArrObj_methods[] = { { "__array_finalize__", (PyCFunction)iMeshArrObj_finalize, METH_VARARGS, "" }, {0} }; static PyMemberDef iMeshArrObj_members[] = { {"instance", T_OBJECT_EX, offsetof(iMeshArr_Object, instance), READONLY, "base iMesh instance"}, {0} }; static PyTypeObject iMeshArr_Type = { PyObject_HEAD_INIT(NULL) /* ... */ (destructor)iMeshArrObj_dealloc, /* tp_dealloc */ /* ... */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "iMesh array objects", /* tp_doc */ /* ... */ iMeshArrObj_methods, /* tp_methods */ iMeshArrObj_members, /* tp_members */ /* ... */ iMeshArrObj_new, /* tp_new */ }; PyMODINITFUNC initiMesh(void) { PyObject *m; m = Py_InitModule("iMesh",module_methods); import_array(); iMeshArr_Type.tp_base = &PyArray_Type; if(PyType_Ready(&iMeshArr_Type) < 0) return; Py_INCREF(&iMeshArr_Type); PyModule_AddObject(m,"Array",(PyObject *)&iMeshArr_Type); } /***** End C code *****/ And then in Python: A = iMesh.Array(numpy.array([1,2,3,4,5]), instance=mesh) numpy.zeros_like(A) # fails here Inside NumPy, zeros_like looks like this (there's a bit more than this, but it's irrelevant to this problem): def zeros_like(a): if isinstance(a, ndarray): res = ndarray.__new__(type(a), a.shape, a.dtype, order=a.flags.fnc) res.fill(0) return res From drobinow at gmail.com Sun May 2 16:16:21 2010 From: drobinow at gmail.com (David Robinow) Date: Sun, 2 May 2010 16:16:21 -0400 Subject: condition and True or False In-Reply-To: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: On Sun, May 2, 2010 at 1:14 PM, Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > ? ?x = and True or False > > What is "and True or False" adding to this picture? ?The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one > over the head with the additional "and True or False". > > I did a little code Googling and found a few other Python instances of > this, but also many Lua instances. ?I'm not that familiar with Lua, is > this a practice that one who uses Lua frequently might carry over to > Python, not realizing that the added "and True or False" is redundant? > > Other theories? > > -- Paul > -- > http://mail.python.org/mailman/listinfo/python-list > True and False were added in Python 2.2.1 (PEP 285) Perhaps this was a silly way to ensure that the user wouldn't try to run it in earlier versions. From jason.scheirer at gmail.com Sun May 2 16:28:03 2010 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Sun, 2 May 2010 13:28:03 -0700 (PDT) Subject: Parser References: <1272830042.14469.1.camel@laptop> Message-ID: On May 2, 12:54?pm, Andreas L?scher wrote: > Hi, > I am looking for an easy to use parser. I am want to get an overview > over parsing and want to try to get some information out of a C-Header > file. Which parser would you recommend? > > Best, > Andreas Pyparsing: http://pyparsing.wikispaces.com/ I've abused the lexers built in to Pygments ( http://pygments.org/ ) a few times to decent effect too. From pavlovevidence at gmail.com Sun May 2 16:28:05 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 13:28:05 -0700 (PDT) Subject: sometype.__new__ and C subclasses References: Message-ID: On May 2, 10:48?am, James Porter wrote: > On 5/2/2010 4:34 AM, Carl Banks wrote: > > > Why don't you use mysubtype.__new__(mysubtype,...)? > > > If you wrote mysubtype in C, and defined a different tp_new than > > ndarray, then this exception will trigger. ?And it ought to; you don't > > want to use ndarray's tp_new to create an object of your subclass, if > > you've defined a different tp_new. > > Unfortunately, I can't do that, since that call is in NumPy itself and > it's part of their "standard" way of making instances of subclasses of > ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, > ...) to create new arrays based on the shape of other arrays. > > The Python version of the subclass is shown here: > , > and I'm trying to write something pretty similar in C. I'm trying to > stay in C since everything else is in C, so it's easier to stay in C > then to jump back and forth all the time. > > Maybe the real answer to this question is "NumPy is doing it wrong" and > I should be on their list; still, it seems strange that the behavior is > different between Python and C. I would say numpy is wrong here, so I suggest filing a bug report. In fact I can't think of any benefit to EVER calling X.__new__(Y) where X is not Y. Maybe old-style classes? Someone who wants to ensure they're getting an instance of a certain type can check issubclass(Y,X) then call Y.__new__(Y). Unfortunately, you just can't get rid of the test in tp_new_wrapper. Carl Banks From robert.kern at gmail.com Sun May 2 16:51:19 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 02 May 2010 15:51:19 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 2010-05-02 15:28 , Carl Banks wrote: > On May 2, 10:48 am, James Porter wrote: >> On 5/2/2010 4:34 AM, Carl Banks wrote: >> >>> Why don't you use mysubtype.__new__(mysubtype,...)? >> >>> If you wrote mysubtype in C, and defined a different tp_new than >>> ndarray, then this exception will trigger. And it ought to; you don't >>> want to use ndarray's tp_new to create an object of your subclass, if >>> you've defined a different tp_new. >> >> Unfortunately, I can't do that, since that call is in NumPy itself and >> it's part of their "standard" way of making instances of subclasses of >> ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, >> ...) to create new arrays based on the shape of other arrays. >> >> The Python version of the subclass is shown here: >> , >> and I'm trying to write something pretty similar in C. I'm trying to >> stay in C since everything else is in C, so it's easier to stay in C >> then to jump back and forth all the time. >> >> Maybe the real answer to this question is "NumPy is doing it wrong" and >> I should be on their list; still, it seems strange that the behavior is >> different between Python and C. > > I would say numpy is wrong here, so I suggest filing a bug report. > > In fact I can't think of any benefit to EVER calling X.__new__(Y) > where X is not Y. Maybe old-style classes? Someone who wants to > ensure they're getting an instance of a certain type can check > issubclass(Y,X) then call Y.__new__(Y). Well, the Y.__new__(Y) may call X.__new__(Y) (and we certainly do this successfully in other Python subclasses of ndarray; this also appears in the Python regression tests). I'm not sure why this would be permitted there and not in a regular function (numpy.zeros_like() seems to be the function that does this and fails for the OP). The reason we do it there instead of calling the subclass's constructor is because the subclass's constructor may have different arguments. I'm happy to concede that this might be a bug in numpy, but I don't understand why this is allowed for Python subclasses but not C subtypes. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Sun May 2 16:58:27 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 02 May 2010 15:58:27 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 2010-05-02 15:03 , James Porter wrote: > And then in Python: > > A = iMesh.Array(numpy.array([1,2,3,4,5]), instance=mesh) > numpy.zeros_like(A) # fails here > > Inside NumPy, zeros_like looks like this (there's a bit more than this, > but it's irrelevant to this problem): > > def zeros_like(a): > if isinstance(a, ndarray): > res = ndarray.__new__(type(a), a.shape, a.dtype, > order=a.flags.fnc) > res.fill(0) > return res Well, I think we can change zeros_like() and the rest to work around this issue. Can you bring it up on the numpy mailing list? def zeros_like(a): if isinstance(a, ndarray): res = numpy.empty(a.shape, a.dtype, order=a.flags.fnc) res.fill(0) res = res.view(type(a)) return res ... -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From pavlovevidence at gmail.com Sun May 2 17:19:08 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 14:19:08 -0700 (PDT) Subject: PyObject_SetAttrString - doesn't set instance attribute References: <82ae0f7b-e5f4-4b85-a9fb-aef16de10af2@a39g2000prb.googlegroups.com> <1579c863-c7e2-47ba-ae45-b3ba74eff40c@a39g2000prb.googlegroups.com> <751257bd-5d92-4ec9-bec9-41369b5d31e5@y18g2000prn.googlegroups.com> Message-ID: <0c809eb9-6e97-4b23-93bd-79b875daf09d@n37g2000prc.googlegroups.com> On May 2, 3:26?am, Jason wrote: > On May 2, 5:52?pm, Carl Banks wrote: > > > Not sure what you're doing here. ?It looks like you are being passed > > an object of a given type, then you get the type object, call it to > > create another object of that type, and assign it to object->instance. > > Sorry, I should have noted that the "NautilusPythonObject" type in the > code is a struct defined as: > > struct _NautilusPythonObject { > ? GObject parent_slot; > ? PyObject *instance; > > }; > > You are assigning the attirbute the the object that the C code refers > > to as "object->instance", but it seems that in the Python snippet you > > are calling getattr on the object that the C code refers to as > > "object". > > object->instance is the PyObject, and I gathered that it was the > correct thing to assign to from the fact that the address is identical > as seen from C and Python. We'd have to see more code, I'd think. What you posted needs more context. For instance, what type, exactly, is class->type? This would help us understand better. I don't understand how object->instance and self could be the same object. If they have the same address it's possible (and, I'm inclined to think, likely) that you're creating an object, it's getting destroyed, then you are creating another one. Here's what's really odd. You are calling getattr(self, "super_happy_magic") inside __init__, which is the class's initializer. How could you have had occasion to call PyObject_SetAttrString on that same object at that point? The only possible way it could have happened is if nautilus_python_object_instance_init is invoked by MenuProviderTest.__new__ somehow, but that doesn't make sense either. You run PyObject_CallObject(class->type,NULL) to create object- >instance, but calling a type also calls the type's __init__ method. So how is it that later the __init__ method is being called again on the same object? Unless you're doing something very weird, it could only mean it's a different object. I doubt it'll fix all your problems, but one thing to try is to replace "PyObject_CallObject(class->type, NULL);" with "class->type- >tp_new(class->type);". But you probably have to go back to the drawing board and rethink the whole thing. What you've posted is quite unusual. You should choose more descriptive variable names, too. Carl Banks From pavlovevidence at gmail.com Sun May 2 17:39:27 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 14:39:27 -0700 (PDT) Subject: sometype.__new__ and C subclasses References: Message-ID: <6fb5fa23-f484-4fba-9b73-5e0517dc374d@34g2000prs.googlegroups.com> On May 2, 1:51?pm, Robert Kern wrote: > On 2010-05-02 15:28 , Carl Banks wrote: > > > > > On May 2, 10:48 am, James Porter ?wrote: > >> On 5/2/2010 4:34 AM, Carl Banks wrote: > > >>> Why don't you use mysubtype.__new__(mysubtype,...)? > > >>> If you wrote mysubtype in C, and defined a different tp_new than > >>> ndarray, then this exception will trigger. ?And it ought to; you don't > >>> want to use ndarray's tp_new to create an object of your subclass, if > >>> you've defined a different tp_new. > > >> Unfortunately, I can't do that, since that call is in NumPy itself and > >> it's part of their "standard" way of making instances of subclasses of > >> ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, > >> ...) to create new arrays based on the shape of other arrays. > > >> The Python version of the subclass is shown here: > >> , > >> and I'm trying to write something pretty similar in C. I'm trying to > >> stay in C since everything else is in C, so it's easier to stay in C > >> then to jump back and forth all the time. > > >> Maybe the real answer to this question is "NumPy is doing it wrong" and > >> I should be on their list; still, it seems strange that the behavior is > >> different between Python and C. > > > I would say numpy is wrong here, so I suggest filing a bug report. > > > In fact I can't think of any benefit to EVER calling X.__new__(Y) > > where X is not Y. ?Maybe old-style classes? ?Someone who wants to > > ensure they're getting an instance of a certain type can check > > issubclass(Y,X) then call Y.__new__(Y). > > Well, the Y.__new__(Y) may call X.__new__(Y) (and we certainly do this > successfully in other Python subclasses of ndarray; this also appears in the > Python regression tests). I'm not sure why this would be permitted there and not > in a regular function (numpy.zeros_like() seems to be the function that does > this and fails for the OP). The reason we do it there instead of calling the > subclass's constructor is because the subclass's constructor may have different > arguments. > > I'm happy to concede that this might be a bug in numpy, but I don't understand > why this is allowed for Python subclasses but not C subtypes. Because Python subclasses (i.e., "heap types") all invoke tp_new_wrapper, which is guaranteed to call the tp_new of the most derived base. C subtypes can, and often have to, replace tp_new with their own version. Calling a base type's tp_new when you've defined your own tp_new at the C level is dangerous. As for the issue with a subclass's arguments being different, I'm shocked that anyone at numpy could possibly think bypassing the subtype's constructor is good idea. Carl Banks From pavlovevidence at gmail.com Sun May 2 17:49:16 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 14:49:16 -0700 (PDT) Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: <5ac89a1b-1646-4196-8805-e50a19230490@j36g2000prj.googlegroups.com> On May 2, 10:14?am, Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > ? ? x = and True or False > > What is "and True or False" adding to this picture? ?The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one > over the head with the additional "and True or False". > > I did a little code Googling and found a few other Python instances of > this, but also many Lua instances. ?I'm not that familiar with Lua, is > this a practice that one who uses Lua frequently might carry over to > Python, not realizing that the added "and True or False" is redundant? > > Other theories? The person who wrote it was a programmer who fancied himself to be more clever than he really was. Convenient though they may be, people always abuse (and often misuse) these boolean shortcuts, a big reason why I don't like them. You never see crap like this in Java. Carl Banks From martin at v.loewis.de Sun May 2 18:02:07 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 03 May 2010 00:02:07 +0200 Subject: Parser In-Reply-To: <1272830042.14469.1.camel@laptop> References: <1272830042.14469.1.camel@laptop> Message-ID: <4BDDF65F.7080302@v.loewis.de> Andreas L?scher wrote: > Hi, > I am looking for an easy to use parser. I am want to get an overview > over parsing and want to try to get some information out of a C-Header > file. To get information from a header file, try Tools/scripts/h2py.py Regards, Martin From porterj at alum.rit.edu Sun May 2 18:06:34 2010 From: porterj at alum.rit.edu (James Porter) Date: Sun, 02 May 2010 17:06:34 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 5/2/2010 3:58 PM, Robert Kern wrote: > Well, I think we can change zeros_like() and the rest to work around > this issue. Can you bring it up on the numpy mailing list? > > def zeros_like(a): > if isinstance(a, ndarray): > res = numpy.empty(a.shape, a.dtype, order=a.flags.fnc) > res.fill(0) > res = res.view(type(a)) > return res > ... I'm having difficulty posting to the NumPy list (both via gmane and email) so I'm just going to put this here so it doesn't get lost. zeros_like probably needs to call __array_finalize__ for this to work properly (it'll cause a segfault for me otherwise): def zeros_like(a): if isinstance(a, ndarray): res = numpy.zeros(a.shape, a.dtype, order=a.flags.fnc) res = res.view(type(a)) res.__array_finalize__(a) return res ... - Jim From steve at REMOVE-THIS-cybersource.com.au Sun May 2 19:14:22 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 23:14:22 GMT Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: <4bde074e$0$27857$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 10:14:44 -0700, Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code that > might better be coded using "y if x else z", I came across this puzzler: > > x = and True or False > > What is "and True or False" adding to this picture? The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one over > the head with the additional "and True or False". If is already an actual bool, then I can only imagine that the author is simply struggling with the concept, in the same way that some people write: if == True: ... If it is any arbitrary object, then "x and True or False" is just an obfuscated way of writing "bool(x)". Perhaps their code predates the introduction of bools, and they have defined global constants True and False but not bool. Then they removed the True and False bindings as no longer necessary, but neglected to replace the obfuscated conversion. -- Steven From lanyjie at yahoo.com Sun May 2 19:24:11 2010 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sun, 2 May 2010 16:24:11 -0700 (PDT) Subject: ANN: expy 0.6.6 released! Message-ID: <196302.50328.qm@web54202.mail.re2.yahoo.com> EXPY is an express way to extend Python! EXPY provides a way to extend python in an elegant way. For more information and a tutorial, see: http://expy.sourceforge.net/ What's new: 1. Special methods can now take @throws decorators. 2. Added convenience macros _NEW and _CheckExact for extension types. 3. Give warnings of missing Py_INCREF on all methods/functions returning an object. 4. And the responsibility of Py_INCREF is left for the developer. 5. Documentation update. Cheers, Yingjie From steve at REMOVE-THIS-cybersource.com.au Sun May 2 19:26:46 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 23:26:46 GMT Subject: List size versus list allocation References: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> Message-ID: <4bde0a36$0$27857$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 18:07:31 +0200, Christian Heimes wrote: >> I'm interested in gathering some statistics on this, and to do so I >> need a way of measuring the list's logical size versus its actual size. >> The first is easy: it's just len(list). Is there some way of getting >> the allocated size of the list? > > With Python 2.6 and newer you can use sys.getsizeof() to get the actual > size of the list object: Thanks Christian and Peter for your answers. That's very helpful. -- Steven From pmaupin at gmail.com Sun May 2 19:37:43 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 2 May 2010 16:37:43 -0700 (PDT) Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: <5e5a0005-1c44-4d47-bd3e-8ebbd66eea1e@k19g2000yqm.googlegroups.com> On May 2, 12:14?pm, Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > ? ? x = and True or False > > What is "and True or False" adding to this picture? ?The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one > over the head with the additional "and True or False". > > I did a little code Googling and found a few other Python instances of > this, but also many Lua instances. ?I'm not that familiar with Lua, is > this a practice that one who uses Lua frequently might carry over to > Python, not realizing that the added "and True or False" is redundant? > > Other theories? > > -- Paul I think it's idiomatic -- that it was written by someone who was deep in thought about actually getting something accomplished, and not thinking at the level of the details. As you're actively *looking* for "x and y or z" I'm sure you'll agree that we've probably all written lots of stuff like: x = and 'some_prefix' or '' x = and 42 or 0 x = and ['Hi, mom!'] or [] When you're in this mode of expression, the only thing that would really trip you up and make it "wrong" is if 'some_prefix' or 42 or ['Hi, mom!'] evaluated to False, and then you get the '', 0, or [] you didn't really want. So I know that, to the extent I was thinking deeply about the low level of what I was writing, my mental energy would be going towards making sure that the second sub-expression evaluated to true. So, if you're mentally operating in this mode, and you want True or False, and you forget, don't think about, or are not cognizant of the fact that bool() is available, it's pretty obvious what the result is going to be. I've probably done it myself a few times, although I would probably have to be *really* lost in thought in order to do it when the underlying sub-expression was boolean to start with. Regards, Pat From greg.ewing at canterbury.ac.nz Sun May 2 20:41:29 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 May 2010 12:41:29 +1200 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: <846jr7Fl1cU1@mid.individual.net> James Porter wrote: > Functions like numpy.zeros_like use ndarray.__new__(subtype, > ...) to create new arrays based on the shape of other arrays. > > Maybe the real answer to this question is "NumPy is doing it wrong" Yes, I think NumPy is doing it wrong, even for subclasses written in Python. If the subtype has overridden ndarray's __new__ method, the way NumPy is doing it will skip the subclass's version of the method. -- Greg From sjmachin at lexicon.net Sun May 2 20:42:27 2010 From: sjmachin at lexicon.net (John Machin) Date: Sun, 2 May 2010 17:42:27 -0700 (PDT) Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> <4bde074e$0$27857$c3e8da3@news.astraweb.com> Message-ID: On May 3, 9:14?am, Steven D'Aprano wrote: > If it is any arbitrary object, then "x and True or False" is just an > obfuscated way of writing "bool(x)". Perhaps their code predates the > introduction of bools, and they have defined global constants True and > False but not bool. Then they removed the True and False bindings as no > longer necessary, but neglected to replace the obfuscated conversion. Or perhaps they are maintaining code that must run on any 2.X. True and False would be set up conditional on Python version. Writing "expression and True or False" avoids a function call. From lanyjie at yahoo.com Sun May 2 21:40:30 2010 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sun, 2 May 2010 18:40:30 -0700 (PDT) Subject: ANN: expy 0.6.6 released! In-Reply-To: <196302.50328.qm@web54202.mail.re2.yahoo.com> Message-ID: <74508.23739.qm@web54204.mail.re2.yahoo.com> > Subject: ANN: expy 0.6.6 released! > To: "python list" > Cc: "CAPI Python" > Date: Monday, May 3, 2010, 3:24 AM > EXPY is an express way to extend Python! > > EXPY provides a way to extend python in an elegant way. For > more information and a tutorial, see: http://expy.sourceforge.net/ > I'm using expy in a serious project to wrap an old project written in C and deliver it up via www with django. That is why expy is getting improved quickly these days. So far, both the project and expy are making good progress hand in hand. Cheers, Yingjie From bryanjugglercryptographer at yahoo.com Sun May 2 21:52:06 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sun, 2 May 2010 18:52:06 -0700 (PDT) Subject: Fast Efficient way to transfer an object to another list References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> <06366a6d-e3db-4963-bcc0-0bc03d035a94@e2g2000yqn.googlegroups.com> <4bdcce77$0$27782$c3e8da3@news.astraweb.com> Message-ID: <01862ff6-f0a9-436c-b836-a73fbfdd1439@a39g2000prb.googlegroups.com> Steven D'Aprano wrote: > The simplest way to speed the above code up is not to start from the > beginning each time. That requires two very small changes. And since > deletions from the front of the list are slow, MRAB's suggestion is also > a good idea. Those two speed-ups provide worst-case linear run-time, but as MRAB astutely noted, his optimization assumes that order is unimportant. That's a bad assumption for a general extract-from-list function. Where order does not matter, I'd suspect 'list' was a poor choice of data type. Here's a general, order-preserving, linear-time version: def extract(lst, predicate): """ Return items of lst satisfying predicate, deleting them from lst. """ result = [] j = 0 for i in range(len(lst)): if predicate(lst[i]): result.append(lst[i]) else: lst[j] = lst[i] j += 1 del lst[j:] return result # some testing: for nitems in range(10): for pred in [lambda x: True, lambda x: False, lambda x: x % 2 == 0, lambda x: x % 2 == 1, lambda x: x < nitems // 2, lambda x: x >= nitems // 2]: original = list(range(nitems)) source = original[:] extracted = extract(source, pred) assert len(source) + len(extracted) == nitems assert sorted(source) == source for n in source: assert not pred(n) assert n in original assert sorted(extracted) == extracted for n in extracted: assert pred(n) assert n in original -- --Bryan From alfps at start.no Mon May 3 00:37:49 2010 From: alfps at start.no (Alf P. Steinbach) Date: Mon, 03 May 2010 06:37:49 +0200 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: * Terry Reedy: > * Alf P. Steinbach: >> * Aahz: > >>> and sometimes >>> they rebind the original target to the same object. >> >> At the Python level that seems to be an undetectable null-operation. > > If you try t=(1,2,3); t[1]+=3, if very much matters that a rebind occurs. Testing: >>> t = ([], [], []) >>> t ([], [], []) >>> t[0] += ["blah"] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> t (['blah'], [], []) >>> _ Yep, it matters. Is this change-but-raise-exception a bug? I seem to have a knack for running into bugs. :-) >> Granted one could see something going on in a machine code or byte code >> debugger. But making that distinction (doing nothing versus >> self-assignment) at the Python level seems, to me, to be meaningless. > > Please do not confuse things. Augmented *assignment* must be understood > as assignment. Failure to do so leads (and has lead) newbies into > confusion, and puzzled posts on this list. OK. But I think it would be less confusing, less breaking of expectations, if, for the example above, += reduced to the functionality of extend(), with no x. Cheers, & thanks, - Alf From dchichkov at gmail.com Mon May 3 01:10:00 2010 From: dchichkov at gmail.com (dmtr) Date: Sun, 2 May 2010 22:10:00 -0700 (PDT) Subject: Parser References: <1272830042.14469.1.camel@laptop> Message-ID: <2121ba34-89e2-430f-bc99-5b6a2388f3dd@g1g2000pro.googlegroups.com> On May 2, 12:54?pm, Andreas L?scher wrote: > Hi, > I am looking for an easy to use parser. I am want to get an overview > over parsing and want to try to get some information out of a C-Header > file. Which parser would you recommend? ANTLR From clp2 at rebertia.com Mon May 3 01:18:39 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 May 2010 22:18:39 -0700 Subject: Parser In-Reply-To: <2121ba34-89e2-430f-bc99-5b6a2388f3dd@g1g2000pro.googlegroups.com> References: <1272830042.14469.1.camel@laptop> <2121ba34-89e2-430f-bc99-5b6a2388f3dd@g1g2000pro.googlegroups.com> Message-ID: On Sun, May 2, 2010 at 10:10 PM, dmtr wrote: > On May 2, 12:54?pm, Andreas L?scher chemnitz.de> wrote: >> Hi, >> I am looking for an easy to use parser. I am want to get an overview >> over parsing and want to try to get some information out of a C-Header >> file. Which parser would you recommend? > > ANTLR I don't know if it's that easy to get started with though. The companion for-pay book is *most excellent*, but it seems to have been written to the detriment of the normal online docs. Cheers, Chris -- http://blog.rebertia.com From dchichkov at gmail.com Mon May 3 01:39:43 2010 From: dchichkov at gmail.com (dmtr) Date: Sun, 2 May 2010 22:39:43 -0700 (PDT) Subject: Parser References: <1272830042.14469.1.camel@laptop> <2121ba34-89e2-430f-bc99-5b6a2388f3dd@g1g2000pro.googlegroups.com> Message-ID: <6d42a22e-ed67-4e8e-bcdb-ceed85f6c6d2@r21g2000prr.googlegroups.com> > > > ANTLR > > I don't know if it's that easy to get started with though. The > companion for-pay book is *most excellent*, but it seems to have been > written to the detriment of the normal online docs. > > Cheers, > Chris > --http://blog.rebertia.com IMO ANTLR is much easier to use compared to any other tool simply because it has excellent GUI (the quality of which is amazing). From stefan_ml at behnel.de Mon May 3 01:56:50 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 03 May 2010 07:56:50 +0200 Subject: Parser In-Reply-To: <6d42a22e-ed67-4e8e-bcdb-ceed85f6c6d2@r21g2000prr.googlegroups.com> References: <1272830042.14469.1.camel@laptop> <2121ba34-89e2-430f-bc99-5b6a2388f3dd@g1g2000pro.googlegroups.com> <6d42a22e-ed67-4e8e-bcdb-ceed85f6c6d2@r21g2000prr.googlegroups.com> Message-ID: dmtr, 03.05.2010 07:39: >>> ANTLR >> >> I don't know if it's that easy to get started with though. The >> companion for-pay book is *most excellent*, but it seems to have been >> written to the detriment of the normal online docs. > > IMO ANTLR is much easier to use compared to any other tool simply > because it has excellent GUI (the quality of which is amazing). See? Explanations help more than bold statements. Stefan From parul.pandey85 at gmail.com Mon May 3 02:24:51 2010 From: parul.pandey85 at gmail.com (pp) Date: Sun, 2 May 2010 23:24:51 -0700 (PDT) Subject: Problems with 'scipy.sparse.linalg.dsolve.umfpack' Message-ID: <2bed17f4-0fa1-4561-b7ec-32002e38b690@32g2000prq.googlegroups.com> Hello all, I have this equation to solve where variable LHS is a sparse matrix and RHS is an array . c = linsolve.spsolve(LHS, RHS) i get this error warn( 'scipy.sparse.linalg.dsolve.umfpack will be removed,'\ ' install scikits.umfpack instead' what is the reason for this and do I do next Please help I am very new to scipy. Thanks a lot From clp2 at rebertia.com Mon May 3 02:48:03 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 May 2010 23:48:03 -0700 Subject: Problems with 'scipy.sparse.linalg.dsolve.umfpack' In-Reply-To: <2bed17f4-0fa1-4561-b7ec-32002e38b690@32g2000prq.googlegroups.com> References: <2bed17f4-0fa1-4561-b7ec-32002e38b690@32g2000prq.googlegroups.com> Message-ID: On Sun, May 2, 2010 at 11:24 PM, pp wrote: > Hello all, > > I have this equation to solve where variable > LHS is a sparse matrix and RHS is an array . > c = linsolve.spsolve(LHS, RHS) > > > i get this error > warn( 'scipy.sparse.linalg.dsolve.umfpack will be removed,'\ > ? ? ? ? ? ? ? ? ?' install scikits.umfpack instead' > what is the reason for this and do I do next > > Please help > I am very new to scipy. This is the general Python mailinglist. You'd be more likely to get an answer on the SciPy mailinglist: http://mail.scipy.org/mailman/listinfo/scipy-user Cheers, Chris -- http://blog.rebertia.com From WolfgangMeiners01 at web.de Mon May 3 02:51:13 2010 From: WolfgangMeiners01 at web.de (Wolfgang Meiners) Date: Mon, 03 May 2010 08:51:13 +0200 Subject: recommended way to insert data into a one to many relationship using python In-Reply-To: References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4bde7262$0$6776$9b4e6d93@newsspool3.arcor-online.net> Peter Otten schrieb: > Peter Otten wrote: > > If you create indices for floors (and rooms) > > cur.execute("""create unique index room_index on rooms (fid, number);""") > cur.execute("""create unique index floor_index on floors (floor);""") > > the addition of missing rows can be simplified to > > missing = c2.execute("""select distinct floor from new_employees;""") > cur.executemany("insert or ignore into floors (floor) values (?)", missing) > > etc. > > Peter Hi Peter, thank you for your response. What i have got from it, is to have a (temporary) table to do the work inside sql and not from python. I thought of a second method to do it inside sql by an trigger sql = """create trigger insert_new_employee instead of insert on emplist begin # insert floor if not exists floor # insert (room, floor) if not exists (room, floor) # insert (person, rid) end""" but i would have to learn how to write triggers. Your idea gives me a more direct solution. Wolfgang From WolfgangMeiners01 at web.de Mon May 3 03:03:57 2010 From: WolfgangMeiners01 at web.de (Wolfgang Meiners) Date: Mon, 03 May 2010 09:03:57 +0200 Subject: recommended way to insert data into a one to many relationship using python In-Reply-To: <16f716de-8a0c-455c-8eb5-dbed332a81fe@h20g2000prn.googlegroups.com> References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> <16f716de-8a0c-455c-8eb5-dbed332a81fe@h20g2000prn.googlegroups.com> Message-ID: <4bde755d$0$6762$9b4e6d93@newsspool3.arcor-online.net> Bryan schrieb: > Wolfgang Meiners wrote: >> one to many relationships are fairly common, i think. So there should be >> a recommended way to insert data into such a relation using python. >> >> Given the following programm, what is the recommended way to insert the >> list of NewEmployees to the database? >> >> ======================================================================== >> # !python >> # -*- coding: utf-8 -*- >> >> import sqlite3 >> >> con = sqlite3.connect(":memory:") >> cur = con.cursor() >> >> cur.execute("""create table employees( >> eid integer primary key autoincrement, >> name text not null, >> rid integer references rooms(rid))""") >> >> cur.execute("""create table rooms( >> rid integer primary key autoincrement, >> number integer, >> fid integer references floors(fid))""") >> >> cur.execute("""create table floors( >> fid integer primary key autoincrement, >> floor text not null)""") >> > [...] >> NewEmployees =[] >> NewEmployees.append({'name': 'George', 'room': 89, 'floor': 'third floor'}) >> NewEmployees.append({'name': 'Ellen', 'room': 21, 'floor': 'first floor'}) >> > > For that kind of insert to be well-defined, the pair (floor, > room_number) must uniquely identify a room. When natural keys like > that are availabe, they're the obvious choice for primary keys in the > database schema. I suggested getting rid of fid and rid, as in: > > > schema = """ > CREATE TABLE floors ( > floor TEXT PRIMARY KEY > ); > > CREATE TABLE rooms ( > floor TEXT REFERENCES floors, > number INTEGER, > PRIMARY KEY (floor, number) > ); > > CREATE TABLE employees ( > eid INTEGER PRIMARY KEY AUTOINCREMENT, > name TEXT, > floor TEXT, > room_number INTEGER, > FOREIGN KEY (floor, room_number) REFERENCES rooms > ) > """ > > con = sqlite3.connect(":memory:") > for cmd in schema.split(';'): > con.execute(cmd) > con.close() > > > > -- > --Bryan This looks interesting to me. I would have all necessary information in table employees. But i think the additional tables for rooms and floors are necessary too, to have a normalized database. I thougth of a function like try_insert_and_return_key(x,y) for the tables but i had difficulties to write such a function. In this function x should be the key and y the depended data that can be compound. Nevertheless, with a given y there might be more then one x and i think, this is exactly what you stated above. Thank you for this hint Wolfgang From steven at REMOVE.THIS.cybersource.com.au Mon May 3 03:29:05 2010 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 03 May 2010 07:29:05 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On Mon, 03 May 2010 06:37:49 +0200, Alf P. Steinbach wrote: > * Terry Reedy: >> * Alf P. Steinbach: >>> * Aahz: >> >>>> and sometimes >>>> they rebind the original target to the same object. >>> >>> At the Python level that seems to be an undetectable null-operation. >> >> If you try t=(1,2,3); t[1]+=3, if very much matters that a rebind >> occurs. > > Testing: > > > >>> t = ([], [], []) > >>> t > ([], [], []) > >>> t[0] += ["blah"] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > >>> t > (['blah'], [], []) > >>> _ > > > Yep, it matters. > > Is this change-but-raise-exception a bug? > > I seem to have a knack for running into bugs. :-) No, I don't believe so -- I believe that it is behaving exactly as advertised. But it is absolutely a gotcha. Consider: >>> class K(object): ... def __init__(self, value=0): ... self.value = value ... def __add__(self, other): ... self.value = self.value + other ... return self ... def __str__(self): ... return "%s" % self.value ... __repr__ = __str__ ... >>> x = K(42) >>> x + 5 47 >>> t = (None, x) >>> t (None, 47) >>> >>> t[1] + 3 50 >>> t (None, 50) >>> t[1] += 1 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> t (None, 51) Unintuitive, yes. Possibly a bad design, maybe. Surprising, absolutely. But not a bug, as it's working exactly as promised. += is conceptually two steps: perform an addition, and perform an assignment afterward. That addition is sometimes performed in-place, but regardless of whether it is or not, the assignment is always attempted. -- Steven From nospam at nospam.com Mon May 3 03:46:05 2010 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 03 May 2010 09:46:05 +0200 Subject: HTTP server + SQLite? Message-ID: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Hello I'd like to build a prototype that will combine a web server as front-end (it must support GZIPping data to the remote client when there are a lot of data to return), and SQLite as back-end, call the server from a VB.Net application, and see how well this works. I want to see if performance is significantly lower than using a server that uses a binary protocol. I'm no Python expert, so would appreciate any information on how to combine a web server and SQLite into a single Python application. This is just for a proof-of-concept, so it doesn't need to be shipping-quality. Thank you for any hint. From wuwei23 at gmail.com Mon May 3 04:32:07 2010 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 May 2010 01:32:07 -0700 (PDT) Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Message-ID: <77d7a0ba-4141-4c05-aef1-96f64ee38ed8@s4g2000prh.googlegroups.com> Gilles Ganault wrote: > I'm no Python expert, so would appreciate any information on how to > combine a web server and SQLite into a single Python application. Hey Gilles, I'm a fan of the http framework, CherryPy[1]. Very quick and easy to get something up and running. The site also has some ideas on interoperating with a database[2], although this might be a better starting point[3]. SQLite is included in the Python standard library past 2.5, but if you're stuck with either 2.3 or 2.4, the 3rd party library pysqlite[4] provides support for them. For a higher level web framework, I find Turbogears 2.x[5] really straightforward. It's based around SQLAlchemy, which supports SQLite, but sounds like it's probably overkill for your situation. 1: http://www.cherrypy.org/ 2: http://tools.cherrypy.org/wiki/Databases 3: http://code.activestate.com/recipes/496799/ 4: http://code.google.com/p/pysqlite 5: http://turbogears.org/2.0/ From clp2 at rebertia.com Mon May 3 04:48:38 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 01:48:38 -0700 Subject: HTTP server + SQLite? In-Reply-To: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Message-ID: On Mon, May 3, 2010 at 12:46 AM, Gilles Ganault wrote: > I'd like to build a prototype that will combine a web server as > front-end (it must support GZIPping data to the remote client when > there are a lot of data to return), and SQLite as back-end, call the > server from a VB.Net application, and see how well this works. I want > to see if performance is significantly lower than using a server that > uses a binary protocol. > > I'm no Python expert, so would appreciate any information on how to > combine a web server and SQLite into a single Python application. This > is just for a proof-of-concept, so it doesn't need to be > shipping-quality. If your want to write a basic/low-level HTTP server: http://docs.python.org/library/basehttpserver.html Looks like you'd use HTTPServer and a custom subclass of BaseHTTPRequestHandler. If you want to write at the slightly higher WSGI (http://www.python.org/dev/peps/pep-0333/) level of abstraction, you can have your WSGI application run by a simple Python HTTP server such as: http://pythonpaste.org/modules/httpserver.html As Alex said, SQLite is in the std lib: http://docs.python.org/library/sqlite3 Cheers, Chris -- http://blog.rebertia.com From __peter__ at web.de Mon May 3 05:34:19 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2010 11:34:19 +0200 Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: Alf P. Steinbach wrote: > > >>> t = ([], [], []) > >>> t > ([], [], []) > >>> t[0] += ["blah"] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > >>> t > (['blah'], [], []) > >>> _ > > > Yep, it matters. > > Is this change-but-raise-exception a bug? No. a[0] += b translates to a.__setitem__(0, a.__getitem__(0).__iadd__(b)) assuming a[0] has an __iadd__() method. It should be obvious that only the the last operation, the outer a.__setitem__(...), will fail here. A possible fix might be a changed order of evaluation: _internal_set = a.__setitem__ _internal_set(0, a.__getitem__(0).__iadd__(b)) I don't know if there are arguments against this other than increased compiler complexity. Or one could argue that a += b should have been implemented as a = a + b or a = a.__add__(b) which is currently used as the fallback when there is no __iadd__() method and which gives a more intuitive behaviour at the cost of a greater overhead. But it's a little late for that discussion, for that language. Peter From jarausch at igpm.rwth-aachen.de Mon May 3 05:51:41 2010 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 03 May 2010 11:51:41 +0200 Subject: HTTP server + SQLite? In-Reply-To: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Message-ID: <847klaFrjnU1@mid.dfncis.de> On 05/03/10 09:46, Gilles Ganault wrote: > Hello > > I'd like to build a prototype that will combine a web server as > front-end (it must support GZIPping data to the remote client when > there are a lot of data to return), and SQLite as back-end, call the > server from a VB.Net application, and see how well this works. I want > to see if performance is significantly lower than using a server that > uses a binary protocol. > > I'm no Python expert, so would appreciate any information on how to > combine a web server and SQLite into a single Python application. This > is just for a proof-of-concept, so it doesn't need to be > shipping-quality. > You might have a look at http://www.karrigell.fr/doc/ Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From natalie5348 at gmail.com Mon May 3 06:23:44 2010 From: natalie5348 at gmail.com (Nat) Date: Mon, 3 May 2010 03:23:44 -0700 (PDT) Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> <847klaFrjnU1@mid.dfncis.de> Message-ID: <4d6a5330-0dec-4b4a-b56a-2d512c123afc@11g2000prv.googlegroups.com> interesting natalie5348 at hotmail.co.jp natalie5348s at yahoo.co.jp natalie5348 at gmail.com wlipgftth at jupiter.ocn.ne.jp natalie5348 at mbr.nifty.com natalie5348 at xqg.biglobe.ne.jp natalie5348 at zpost.plala.or.jp From nospam at nospam.com Mon May 3 06:57:49 2010 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 03 May 2010 12:57:49 +0200 Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> <847klaFrjnU1@mid.dfncis.de> Message-ID: On Mon, 03 May 2010 11:51:41 +0200, Helmut Jarausch wrote: >http://www.karrigell.fr/doc/ Thanks for the tip. From richard.lamboj at bilcom.at Mon May 3 07:02:31 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Mon, 3 May 2010 13:02:31 +0200 Subject: win32 - catch events(wmi?) Message-ID: <201005031302.31772.richard.lamboj@bilcom.at> Hello, i want catch the following events: - registry has chanced - file has chanced - outgoing network connection - programm start and i want to be able to allow, or deny this "requests". Kind Regards Richi From space.ship.traveller at gmail.com Mon May 3 08:05:26 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 4 May 2010 00:05:26 +1200 Subject: Teaching Programming Message-ID: Dear Friends, I'm looking for some help from the Python community. I hope this is the right place to ask for information. I'm putting together a website aimed at high school students and teachers, and would like to make sure the following page is as good as possible: http://programming.dojo.net.nz/languages/python/index In particular, "Why would I learn this language?" section needs to have a few paragraphs. I don't use Python predominantly so I hoped that you could provide the main reasons why Python is a language someone would want to learn about. Any other suggestions or ideas for the Python page would be fantastic, and any suggestions to other pages in general is also very helpful. http://programming.dojo.net.nz/ Kind regards, Samuel -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew at acooke.org Mon May 3 08:21:43 2010 From: andrew at acooke.org (andrew cooke) Date: Mon, 3 May 2010 05:21:43 -0700 (PDT) Subject: Parser References: <1272830042.14469.1.camel@laptop> Message-ID: <71942dbb-a772-4fcb-9746-282cc216eb70@q32g2000yqb.googlegroups.com> On May 2, 3:54?pm, Andreas L?scher wrote: > Hi, > I am looking for an easy to use parser. I am want to get an overview > over parsing and want to try to get some information out of a C-Header > file. Which parser would you recommend? > > Best, > Andreas I develop Lepl - http://www.acooke.org/lepl/ I think it's easy to use, and other people have said the documentation is fairly good. It doesn't have a GUI like Antlr, but it is recursive descent rather and completely implemented in Python, which (I think) makes it easier to understand and extend. Cheers, Andrew From clp2 at rebertia.com Mon May 3 08:29:57 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 05:29:57 -0700 Subject: Teaching Programming In-Reply-To: References: Message-ID: On Mon, May 3, 2010 at 5:05 AM, Samuel Williams wrote: > Dear Friends, > > I'm looking for some help from the Python community. I hope this is the > right place to ask for information. > > I'm putting together a website aimed at high school students and teachers, > and would like to make sure the following page is as good as possible: > http://programming.dojo.net.nz/languages/python/index > In particular, "Why would I learn this language?" section needs to have a > few paragraphs. I don't use Python predominantly so I hoped that you could > provide the main reasons why Python is a language someone would want to > learn about. - Significant use in certain applications areas: * Web programming (common frameworks include Django & TurboGears) * Scientific and numerical computing (see SciPy and Numeric) - Large "batteries-included" standard library, with a large number of third-party libraries also available - Used by Industrial Light and Magic, Google/YouTube, and other big names (http://www.python.org/about/success/) - A very clean syntax and elegant design, compared to other languages Cheers, Chris -- http://blog.rebertia.com From bazwal at ftml.net Mon May 3 08:42:13 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 13:42:13 +0100 Subject: strange interaction between open and cwd Message-ID: <4BDEC4A5.5070801@ftml.net> Python 2.6.4 (r264:75706, Mar 7 2010, 02:18:40) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.mkdir('/home/baz/tmp/xxx') >>> f = open('/home/baz/tmp/abc.txt', 'w') >>> f.write('abc') >>> f.close() >>> os.chdir('/home/baz/tmp/xxx') >>> os.getcwd() '/home/baz/tmp/xxx' >>> os.rmdir(os.getcwd()) >>> os.getcwd() Traceback (most recent call last): File "", line 1, in OSError: [Errno 2] No such file or directory >>> open('../abc.txt').read() 'abc' >>> can anybody explain how python is able to read the file at the end of this session? i'm guessing it's a platform specific thing as i'm pretty sure the above sequence of commands wouldn't work on windows (i.e. attempting to remove the cwd would produce an error). but how can python determine the parent directory of a directory that no longer exists? this actually caused a bug for me. i was trying to ensure that my program always resolved any file-names given on the command line by using os.path.realpath(). i had assumed that if realpath failed, then open would also fail - but not so! From lanyjie at yahoo.com Mon May 3 08:43:55 2010 From: lanyjie at yahoo.com (Yingjie Lan) Date: Mon, 3 May 2010 05:43:55 -0700 (PDT) Subject: ANN: expy 0.6.7 released! In-Reply-To: <74508.23739.qm@web54204.mail.re2.yahoo.com> Message-ID: <741400.49245.qm@web54202.mail.re2.yahoo.com> EXPY is an express way to extend Python! EXPY provides a way to extend python in an elegant way. For more information and a tutorial, see: http://expy.sourceforge.net/ I'm glad to announce a new release again today. ^_^ What's new: Version 0.6.7 1. Now functions can have 'value on failure' via rawtype. 2. Now property getters/setters can have @throws 3. Bug fix: if __init__ wrapper fails, it must return -1. Cheers, Yingjie From clp2 at rebertia.com Mon May 3 09:06:09 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 06:06:09 -0700 Subject: Teaching Programming In-Reply-To: References: Message-ID: On Mon, May 3, 2010 at 5:29 AM, Chris Rebert wrote: > On Mon, May 3, 2010 at 5:05 AM, Samuel Williams > wrote: >> Dear Friends, >> >> I'm looking for some help from the Python community. I hope this is the >> right place to ask for information. >> >> I'm putting together a website aimed at high school students and teachers, >> and would like to make sure the following page is as good as possible: >> http://programming.dojo.net.nz/languages/python/index >> In particular, "Why would I learn this language?" section needs to have a >> few paragraphs. I don't use Python predominantly so I hoped that you could >> provide the main reasons why Python is a language someone would want to >> learn about. > - A very clean syntax and elegant design, compared to other languages Also, I take issue with your classifying Python as orange with regard to "Is the general syntax simple and concise?" on http://programming.dojo.net.nz/resources/programming-language-comparison/index Python's syntax is at least as simple, if not simpler, than Ruby's, which you rate as green. Ruby may be /slightly/ more concise than Python in certain cases due to its Perl influences, but those instances of specialized syntax also make it more complex. To wit, I refer you to http://webcache.googleusercontent.com/search?q=cache:dyugd_KlqvcJ:blog.nicksieger.com/articles/2006/10/27/visualization-of-rubys-grammar+ruby+grammar+visualization&cd=1&hl=en&ct=clnk&gl=us Note the complexity of the graph for Ruby's grammar. By comparison, here is the same graph for Python (generated from a file linked to in the post's comment thread): http://rebertia.com/images/python_grammar_graph.png (Disclaimer: Neither of the graphs are current.) Additionally, you rate Python orange but Perl green for "Does the language provide a useful and consistent set of object oriented constructs?". Could you explain your reasoning for this? While neither Python nor Perl have the level of object-oriented purity of Ruby or Smalltalk, my understanding is that short of using CPAN libraries for Perl or dealing in Perl 6, Perl and Python have a substantially similar object model, so I don't how Python could rate below Perl in this area. Cheers, Chris -- http://blog.rebertia.com From andrew at acooke.org Mon May 3 09:06:59 2010 From: andrew at acooke.org (andrew cooke) Date: Mon, 3 May 2010 06:06:59 -0700 (PDT) Subject: Ann: Validating Emails and HTTP URLs in Python Message-ID: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> Hi, The latest Lepl release includes an implementation of RFC 3696 - the RFC that describes how best to validate email addresses and HTTP URLs. For more information please see http://www.acooke.org/lepl/rfc3696.html Lepl's main page is http://www.acooke.org/lepl Because Lepl compiles to regular expressions wherever possible, the library is quite fast - in testing I was seeing about 1ms needed to validate a URL. Please bear in mind that this is the very first release of this module, so it may have some bugs... If you find any problems contact me and I'll fix them ASAP. Thanks, Andrew From clp2 at rebertia.com Mon May 3 09:18:55 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 06:18:55 -0700 Subject: strange interaction between open and cwd In-Reply-To: <4BDEC4A5.5070801@ftml.net> References: <4BDEC4A5.5070801@ftml.net> Message-ID: On Mon, May 3, 2010 at 5:42 AM, Baz Walter wrote: > Python 2.6.4 (r264:75706, Mar ?7 2010, 02:18:40) > [GCC 4.4.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os >>>> os.mkdir('/home/baz/tmp/xxx') >>>> f = open('/home/baz/tmp/abc.txt', 'w') >>>> f.write('abc') >>>> f.close() >>>> os.chdir('/home/baz/tmp/xxx') >>>> os.getcwd() > '/home/baz/tmp/xxx' >>>> os.rmdir(os.getcwd()) >>>> os.getcwd() > Traceback (most recent call last): > ?File "", line 1, in > OSError: [Errno 2] No such file or directory >>>> open('../abc.txt').read() > 'abc' >>>> > > can anybody explain how python is able to read the file at the end of this > session? > but how can python determine the > parent directory of a directory that no longer exists? Whether or not /home/baz/tmp/xxx/ exists, we know from the very structure and properties of directory paths that its parent directory is, *by definition*, /home/baz/tmp/ (just chop off everything after the second-to-last slash). I would assume this is what happens internally. How exactly this interacts with, say, moving the directory to a new location rather than deleting it, I don't know; again, it would quite likely be platform-specific. Cheers, Chris -- http://blog.rebertia.com From philip at semanchuk.com Mon May 3 09:24:49 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 3 May 2010 09:24:49 -0400 Subject: Ann: Validating Emails and HTTP URLs in Python In-Reply-To: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> References: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> Message-ID: On May 3, 2010, at 9:06 AM, andrew cooke wrote: > > Hi, > > The latest Lepl release includes an implementation of RFC 3696 - the > RFC that describes how best to validate email addresses and HTTP > URLs. For more information please see http://www.acooke.org/lepl/rfc3696.html > > Lepl's main page is http://www.acooke.org/lepl > > Because Lepl compiles to regular expressions wherever possible, the > library is quite fast - in testing I was seeing about 1ms needed to > validate a URL. > > Please bear in mind that this is the very first release of this > module, so it may have some bugs... If you find any problems contact > me and I'll fix them ASAP. Thanks, Andrew, for contributing that to the open source community. FYI, Fourthought's PyXML has a module called uri.py that contains regexes for URL validation. I've over a million URLs (harvested from the Internet) through their code. I can't say I checked each and every result, but I never saw anything that would lead me to believe it was misbehaving. It might be interesting to compare the results of running a large list of URLs through your code and theirs. Good luck Philip From vithya.69 at gmail.com Mon May 3 09:33:49 2010 From: vithya.69 at gmail.com (vithya subramani) Date: Mon, 3 May 2010 19:03:49 +0530 Subject: Python code for outlook automation. Message-ID: hi, i need python source code for - Adding Contacts into Outlook. - Adding Blocked list,Safe sender list to junk Email folder in outlook - Counting total no of contacts in Blocked list,Safe sender list please provide help on these... Thanks, Vidu.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From space.ship.traveller at gmail.com Mon May 3 09:38:53 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 4 May 2010 01:38:53 +1200 Subject: Teaching Programming In-Reply-To: References: Message-ID: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> Dear Chris, Thanks for reading further into the site. Yes, it is complicated to provide a good comparison. It isn't always accurate and I welcome feedback. Please be aware that orange does not mean problem - it simply means take note that there may be potential issues that you need to consider. It is highly subjective, so I appreciate your feedback. The red dot is when there is definitely an issue that needs to be taken into consideration. It isn't "Okay, Warning, Error" because it isn't possible to make this kind of judgement without being omnipotent. There are several reason why I decided to rate the syntax as not being simple. 1) Indentation model is not appreciated by everyone - I think its a good model, but feedback from some other people has been that they don't like it. Also, I've had perfectly good Python code fall to bits after editing in a different editor. I'm not saying that this was the fault of Python, but in an educational context it might be a problem, since people are fairly limited and don't understand these issues. 2) I don't think that the list comprehension integrates well with the rest of the language. It is an additional syntactic construct which seems to be separate from the rest of the language. It would be nice if list comprehension was implemented in a way that was more general, using a general closure syntax for example. This is just my opinion, and it might not be valid (I don't research this point very heavily). I appreciate that in general the Python syntax is good and concise. It is hard. Some teacher might want to consider these issues more carefully. Do you think I should change that spot to green? I don't have a problem with doing that, as long as it makes sense. Thanks for providing the syntax images, they are very interesting. With regards to Perl, yes, this is probably something I need to investigate further. It is not always easy to do a comparison of this nature. From my experience, Perl generally seems to have a robust object model that is consistently implemented (even if the syntax is pretty wonky at times). However, in a sense, it is no better or worse than Python implementation... so why is it green dot? Do you think I should change Perl to orange or Python to green. The main criteria is whether it is going to be an issue in an educational context - this means, for new programmers, or those who might make error easily (syntax, semantic), etc. Also, I wonder if Visual Basic needs to be reevaluated on this criteria too. I guess what is important is the relative importance. I will bring this issue up on the Perl mailing list in order to get advice. Would you recommend changing Perl to orange? Thanks for your well thought out response, it is very helpful. Kind regards, Samuel On 4/05/2010, at 1:06 AM, Chris Rebert wrote: > On Mon, May 3, 2010 at 5:29 AM, Chris Rebert wrote: >> On Mon, May 3, 2010 at 5:05 AM, Samuel Williams >> wrote: >>> Dear Friends, >>> >>> I'm looking for some help from the Python community. I hope this is the >>> right place to ask for information. >>> >>> I'm putting together a website aimed at high school students and teachers, >>> and would like to make sure the following page is as good as possible: >>> http://programming.dojo.net.nz/languages/python/index >>> In particular, "Why would I learn this language?" section needs to have a >>> few paragraphs. I don't use Python predominantly so I hoped that you could >>> provide the main reasons why Python is a language someone would want to >>> learn about. > >> - A very clean syntax and elegant design, compared to other languages > > Also, I take issue with your classifying Python as orange with regard > to "Is the general syntax simple and concise?" on > http://programming.dojo.net.nz/resources/programming-language-comparison/index > Python's syntax is at least as simple, if not simpler, than Ruby's, > which you rate as green. Ruby may be /slightly/ more concise than > Python in certain cases due to its Perl influences, but those > instances of specialized syntax also make it more complex. > To wit, I refer you to > http://webcache.googleusercontent.com/search?q=cache:dyugd_KlqvcJ:blog.nicksieger.com/articles/2006/10/27/visualization-of-rubys-grammar+ruby+grammar+visualization&cd=1&hl=en&ct=clnk&gl=us > Note the complexity of the graph for Ruby's grammar. By comparison, > here is the same graph for Python (generated from a file linked to in > the post's comment thread): > http://rebertia.com/images/python_grammar_graph.png > (Disclaimer: Neither of the graphs are current.) > > Additionally, you rate Python orange but Perl green for "Does the > language provide a useful and consistent set of object oriented > constructs?". Could you explain your reasoning for this? While neither > Python nor Perl have the level of object-oriented purity of Ruby or > Smalltalk, my understanding is that short of using CPAN libraries for > Perl or dealing in Perl 6, Perl and Python have a substantially > similar object model, so I don't how Python could rate below Perl in > this area. > > Cheers, > Chris > -- > http://blog.rebertia.com From __peter__ at web.de Mon May 3 09:46:35 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2010 15:46:35 +0200 Subject: strange interaction between open and cwd References: Message-ID: Baz Walter wrote: > attempting to remove the cwd would produce an error). but how can python > determine the parent directory of a directory that no longer exists? My tentative explanation would be that the directory, namely the inode, still exists -- only the entry for it in its parent directory is gone. So "one level up from here" is still a valid operation, but there is no longer a path in the file system associated with "here". Peter From bazwal at ftml.net Mon May 3 09:49:46 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 14:49:46 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> Message-ID: <4BDED47A.7050106@ftml.net> On 03/05/10 14:18, Chris Rebert wrote: > Whether or not /home/baz/tmp/xxx/ exists, we know from the very > structure and properties of directory paths that its parent directory > is, *by definition*, /home/baz/tmp/ (just chop off everything after > the second-to-last slash). I would assume this is what happens > internally. > How exactly this interacts with, say, moving the directory to a new > location rather than deleting it, I don't know; again, it would quite > likely be platform-specific. but how does '..' get resolved in the relative path '../abc.txt'? i'm assuming python must initially use getcwd() internally to do this, and then if that fails it falls back on something else. but what is that something else? is it something that is reproducible in pure python? From clp2 at rebertia.com Mon May 3 09:56:42 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 06:56:42 -0700 Subject: strange interaction between open and cwd In-Reply-To: <4BDED47A.7050106@ftml.net> References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: On Mon, May 3, 2010 at 6:49 AM, Baz Walter wrote: > On 03/05/10 14:18, Chris Rebert wrote: >> Whether or not /home/baz/tmp/xxx/ exists, we know from the very >> structure and properties of directory paths that its parent directory >> is, *by definition*, /home/baz/tmp/ (just chop off everything after >> the second-to-last slash). I would assume this is what happens >> internally. >> How exactly this interacts with, say, moving the directory to a new >> location rather than deleting it, I don't know; again, it would quite >> likely be platform-specific. > > but how does '..' get resolved in the relative path '../abc.txt'? i'm > assuming python must initially use getcwd() internally to do this, and then > if that fails it falls back on something else. but what is that something > else? is it something that is reproducible in pure python? I would think that the OS system call, not Python itself, does the relative->absolute conversion. Cheers, Chris -- Fsck MMW. From clp2 at rebertia.com Mon May 3 09:58:39 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 06:58:39 -0700 Subject: Teaching Programming In-Reply-To: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> References: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> Message-ID: > On 4/05/2010, at 1:06 AM, Chris Rebert wrote: >> On Mon, May 3, 2010 at 5:29 AM, Chris Rebert wrote: >>> On Mon, May 3, 2010 at 5:05 AM, Samuel Williams >>> wrote: >>>> In particular, "Why would I learn this language?" section needs to have a >>>> few paragraphs. I don't use Python predominantly so I hoped that you could >>>> provide the main reasons why Python is a language someone would want to >>>> learn about. >> >>> - A very clean syntax and elegant design, compared to other languages >> >> Also, I take issue with your classifying Python as orange with regard >> to "Is the general syntax simple and concise?" on >> http://programming.dojo.net.nz/resources/programming-language-comparison/index >> Python's syntax is at least as simple, if not simpler, than Ruby's, >> which you rate as green. Ruby may be /slightly/ more concise than >> Python in certain cases due to its Perl influences, but those >> instances of specialized syntax also make it more complex. >> To wit, I refer you to >> http://webcache.googleusercontent.com/search?q=cache:dyugd_KlqvcJ:blog.nicksieger.com/articles/2006/10/27/visualization-of-rubys-grammar+ruby+grammar+visualization&cd=1&hl=en&ct=clnk&gl=us >> Note the complexity of the graph for Ruby's grammar. By comparison, >> here is the same graph for Python (generated from a file linked to in >> the post's comment thread): >> http://rebertia.com/images/python_grammar_graph.png >> (Disclaimer: Neither of the graphs are current.) >> >> Additionally, you rate Python orange but Perl green for "Does the >> language provide a useful and consistent set of object oriented >> constructs?". Could you explain your reasoning for this? While neither >> Python nor Perl have the level of object-oriented purity of Ruby or >> Smalltalk, my understanding is that short of using CPAN libraries for >> Perl or dealing in Perl 6, Perl and Python have a substantially >> similar object model, so I don't how Python could rate below Perl in >> this area. On Mon, May 3, 2010 at 6:38 AM, Samuel Williams wrote: > Dear Chris, > > Thanks for reading further into the site. > > Yes, it is complicated to provide a good comparison. It isn't always accurate and I welcome feedback. > > Please be aware that orange does not mean problem - it simply means take note that there may be potential issues that you need to consider. It is highly subjective, so I appreciate your feedback. The red dot is when there is definitely an issue that needs to be taken into consideration. It isn't "Okay, Warning, Error" because it isn't possible to make this kind of judgement without being omnipotent. > > There are several reason why I decided to rate the syntax as not being simple. > 1) Indentation model is not appreciated by everyone - I think its a good model, but feedback from some other people has been that they don't like it. Also, I've had perfectly good Python code fall to bits after editing in a different editor. I'm not saying that this was the fault of Python, but in an educational context it might be a problem, since people are fairly limited and don't understand these issues. > 2) I don't think that the list comprehension integrates well with the rest of the language. It is an additional syntactic construct which seems to be separate from the rest of the language. It would be nice if list comprehension was implemented in a way that was more general, using a general closure syntax for example. This is just my opinion, and it might not be valid (I don't research this point very heavily). > > I appreciate that in general the Python syntax is good and concise. It is hard. Some teacher might want to consider these issues more carefully. Do you think I should change that spot to green? I don't have a problem with doing that, as long as it makes sense. Yes, I do think it ought to be green, though I admit I'm not unbiased on this. I will point out that (1) does not seem related to "simplicity and conciseness", which is what that row in the comparison claims to be about. > With regards to Perl, yes, this is probably something I need to investigate further. It is not always easy to do a comparison of this nature. From my experience, Perl generally seems to have a robust object model that is consistently implemented (even if the syntax is pretty wonky at times). However, in a sense, it is no better or worse than Python implementation... so why is it green dot? Do you think I should change Perl to orange or Python to green. I'm unsure, but in either case, at least based on my limited knowledge of Perl 5, it again seems rather strange for Python & Perl to not be rated approximately the same in this area (if anything, I'd think Perl might be slightly worse off due to its syntax; but again, I'm not unbiased and my Perl knowledge is limited). Cheers, Chris -- Avoid "top-posting" (google it) http://blog.rebertia.com From space.ship.traveller at gmail.com Mon May 3 10:05:04 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 4 May 2010 02:05:04 +1200 Subject: Teaching Programming In-Reply-To: References: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> Message-ID: <678305F9-CE2F-4467-9E1D-FBF8235A4A7D@gmail.com> Dear Chris, I will take your feedback into consideration and let you know the outcome when I have time to think about it. Again, I appreciate your thoughts. Thanks for taking the time to think about the comparison chart. Kind regards, Samuel On 4/05/2010, at 1:58 AM, Chris Rebert wrote: >> I appreciate that in general the Python syntax is good and concise. It is hard. Some teacher might want to consider these issues more carefully. Do you think I should change that spot to green? I don't have a problem with doing that, as long as it makes sense. > > Yes, I do think it ought to be green, though I admit I'm not unbiased > on this. I will point out that (1) does not seem related to > "simplicity and conciseness", which is what that row in the comparison > claims to be about. > >> With regards to Perl, yes, this is probably something I need to investigate further. It is not always easy to do a comparison of this nature. From my experience, Perl generally seems to have a robust object model that is consistently implemented (even if the syntax is pretty wonky at times). However, in a sense, it is no better or worse than Python implementation... so why is it green dot? Do you think I should change Perl to orange or Python to green. > > I'm unsure, but in either case, at least based on my limited knowledge > of Perl 5, it again seems rather strange for Python & Perl to not be > rated approximately the same in this area (if anything, I'd think Perl > might be slightly worse off due to its syntax; but again, I'm not > unbiased and my Perl knowledge is limited). From bazwal at ftml.net Mon May 3 10:10:21 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 15:10:21 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BDED94D.20209@ftml.net> On 03/05/10 14:56, Chris Rebert wrote: >> but how does '..' get resolved in the relative path '../abc.txt'? i'm >> assuming python must initially use getcwd() internally to do this, and then >> if that fails it falls back on something else. but what is that something >> else? is it something that is reproducible in pure python? > > I would think that the OS system call, not Python itself, does the > relative->absolute conversion. so there is a discrepancy between some of the std library path functions (like realpath, getcwd, abspath) and the built-in open function. there are files which can be opened for which it is impossible to resolve their full paths (on some platforms). From andrew at acooke.org Mon May 3 10:13:58 2010 From: andrew at acooke.org (andrew cooke) Date: Mon, 3 May 2010 07:13:58 -0700 (PDT) Subject: Ann: Validating Emails and HTTP URLs in Python References: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> Message-ID: > FYI, Fourthought's PyXML has a module called uri.py that contains ? > regexes for URL validation. I've over a million URLs (harvested from ? > the Internet) through their code. I can't say I checked each and every ? > result, but I never saw anything that would lead me to believe it was ? > misbehaving. > > It might be interesting to compare the results of running a large list ? > of URLs through your code and theirs. > > Good luck > Philip It's getting a set of URLs that's the main problem. I've tested it with URL examples in RFC 3696, and with a few extra ones that test particular issues, but when I looked around I couldn't find any public, obvious list of URLs for general testing. Could I use your list? Also, same for emails... Cheers, Andrew Cheers, Andrew From invalid at invalid.invalid Mon May 3 10:22:26 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 14:22:26 +0000 (UTC) Subject: strange interaction between open and cwd References: Message-ID: On 2010-05-03, Peter Otten <__peter__ at web.de> wrote: > Baz Walter wrote: > >> attempting to remove the cwd would produce an error). but how can >> python determine the parent directory of a directory that no longer >> exists? Python doesn't determine the parent directory. The Unix system call and filesystem code do. The same thing happens in bash. IOW, you can do this: $ rm -rf $PWD; cd .. > My tentative explanation would be that the directory, namely the > inode, still exists -- only the entry for it in its parent directory > is gone. That sounds right. > So "one level up from here" is still a valid operation, but there is > no longer a path in the file system associated with "here". I believe that is the case. -- Grant Edwards grant.b.edwards Yow! -- I have seen the at FUN -- gmail.com From bazwal at ftml.net Mon May 3 10:23:47 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 15:23:47 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: Message-ID: <4BDEDC73.1020301@ftml.net> On 03/05/10 14:46, Peter Otten wrote: > Baz Walter wrote: > >> attempting to remove the cwd would produce an error). but how can python >> determine the parent directory of a directory that no longer exists? > > My tentative explanation would be that the directory, namely the inode, > still exists -- only the entry for it in its parent directory is gone. > > So "one level up from here" is still a valid operation, but there is no > longer a path in the file system associated with "here". so "here" must always be available somehow, even if getcwd() fails (something like the environment variable $PWD). shame that os.getenv('PWD') isn't reliable, as it would solve my issue :( From invalid at invalid.invalid Mon May 3 10:24:20 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 14:24:20 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: > On 03/05/10 14:18, Chris Rebert wrote: >> Whether or not /home/baz/tmp/xxx/ exists, we know from the very >> structure and properties of directory paths that its parent directory >> is, *by definition*, /home/baz/tmp/ (just chop off everything after >> the second-to-last slash). I would assume this is what happens >> internally. >> How exactly this interacts with, say, moving the directory to a new >> location rather than deleting it, I don't know; again, it would quite >> likely be platform-specific. > > but how does '..' get resolved in the relative path '../abc.txt'? The current directory has an entry named '..' that points to the parent directory. > i'm assuming python must initially use getcwd() internally to do > this, Nope. Python just passes the string '../abc.txt' to libc's open() function, and that in turn passes it on to the Unix/Linux open() syscall, when follows the link in the current working directory named '..'. > and then if that fails it falls back on something else. but what is > that something else? is it something that is reproducible in pure > python? None of this has anything at all to do with Python. -- Grant Edwards grant.b.edwards Yow! I didn't order any at WOO-WOO ... Maybe a YUBBA gmail.com ... But no WOO-WOO! From philip at semanchuk.com Mon May 3 10:28:54 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 3 May 2010 10:28:54 -0400 Subject: Ann: Validating Emails and HTTP URLs in Python In-Reply-To: References: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> Message-ID: <25608F6F-DF17-4E32-A693-4B96B3DBD624@semanchuk.com> On May 3, 2010, at 10:13 AM, andrew cooke wrote: >> FYI, Fourthought's PyXML has a module called uri.py that contains >> regexes for URL validation. I've over a million URLs (harvested from >> the Internet) through their code. I can't say I checked each and >> every >> result, but I never saw anything that would lead me to believe it was >> misbehaving. >> >> It might be interesting to compare the results of running a large >> list >> of URLs through your code and theirs. >> >> Good luck >> Philip > > It's getting a set of URLs that's the main problem. I've tested it > with URL examples in RFC 3696, and with a few extra ones that test > particular issues, but when I looked around I couldn't find any > public, obvious list of URLs for general testing. Could I use your > list? > > Also, same for emails... If I still had a list of URLs you'd be welcome to it. The list was generated as part of a spidering project that's long gone. If all you want to do is generate a list of URLs and email addresses, you could cobble a robots.txt-respectful spider without too much trouble. As with so many things, it's just an SMOP [1]. =) [1] - http://en.wikipedia.org/wiki/Small_matter_of_programming bye Philip From davea at ieee.org Mon May 3 10:49:16 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 03 May 2010 10:49:16 -0400 Subject: strange interaction between open and cwd In-Reply-To: <4BDED47A.7050106@ftml.net> References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BDEE26C.1050608@ieee.org> Baz Walter wrote: > On 03/05/10 14:18, Chris Rebert wrote: >> Whether or not /home/baz/tmp/xxx/ exists, we know from the very >> structure and properties of directory paths that its parent directory >> is, *by definition*, /home/baz/tmp/ (just chop off everything after >> the second-to-last slash). I would assume this is what happens >> internally. >> How exactly this interacts with, say, moving the directory to a new >> location rather than deleting it, I don't know; again, it would quite >> likely be platform-specific. > > but how does '..' get resolved in the relative path '../abc.txt'? i'm > assuming python must initially use getcwd() internally to do this, and > then if that fails it falls back on something else. but what is that > something else? is it something that is reproducible in pure python? > > os.path.dirname() doesn't care about whether a path actually represents a location on disk. It just parses the string. If I were processing the .., that's what I'd use to normalize it. DaveA From invalid at invalid.invalid Mon May 3 10:55:16 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 14:55:16 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: > On 03/05/10 14:56, Chris Rebert wrote: >>> but how does '..' get resolved in the relative path '../abc.txt'? i'm >>> assuming python must initially use getcwd() internally to do this, and then >>> if that fails it falls back on something else. but what is that something >>> else? is it something that is reproducible in pure python? >> >> I would think that the OS system call, not Python itself, does the >> relative->absolute conversion. > > so there is a discrepancy between some of the std library path functions > (like realpath, getcwd, abspath) and the built-in open function. Not really. There is a discrepancy between your perception and expectations and the way the Unix filesystem works. > there are files which can be opened for which it is impossible to > resolve their full paths (on some platforms). Sort of. The file in question _has_ a full path, you just can't tell what it is based on the path you used to open it. -- Grant Edwards grant.b.edwards Yow! I smell a RANCID at CORN DOG! gmail.com From invalid at invalid.invalid Mon May 3 10:56:42 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 14:56:42 +0000 (UTC) Subject: strange interaction between open and cwd References: Message-ID: On 2010-05-03, Baz Walter wrote: > On 03/05/10 14:46, Peter Otten wrote: >> Baz Walter wrote: >> >>> attempting to remove the cwd would produce an error). but how can python >>> determine the parent directory of a directory that no longer exists? >> >> My tentative explanation would be that the directory, namely the inode, >> still exists -- only the entry for it in its parent directory is gone. >> >> So "one level up from here" is still a valid operation, but there is no >> longer a path in the file system associated with "here". > > so "here" must always be available somehow, Yes. > even if getcwd() fails If the current working directory doesn't _have_ a path within a filesystem, what do you expect it to do? > (something like the environment variable $PWD). shame that > os.getenv('PWD') isn't reliable, as it would solve my issue :( I don't understand what you mean by that. -- Grant Edwards grant.b.edwards Yow! I'm wet! I'm wild! at gmail.com From see at sig.for.address Mon May 3 11:17:47 2010 From: see at sig.for.address (Victor Eijkhout) Date: Mon, 3 May 2010 10:17:47 -0500 Subject: long int computations Message-ID: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> I have two long ints, both too long to convert to float, but their ratio is something reasonable. How can I compute that? The obvious "(1.*x)/y" does not work. Victor. -- Victor Eijkhout -- eijkhout at tacc utexas edu From lists at nanl.de Mon May 3 11:22:58 2010 From: lists at nanl.de (Mirko Vogt) Date: Mon, 03 May 2010 17:22:58 +0200 Subject: using python2.6 on windows without installation In-Reply-To: References: <1272554759.3626.52.camel@mia> Message-ID: <1272900178.3769.3.camel@mia> Thanks a lot for all your solutions! Tried installing it "just for the current user" as suggested by Christian and it works like a charme, so there seems to be no need for another python distribution in this case. Thanks a lot once again! mirko On Fri, 2010-04-30 at 01:34 +0200, Christian Heimes wrote: > Mirko Vogt wrote: > > Hey, > > > > is there a way to use python2.6 without having used the installation > > routine? > > > > When I install python2.6 and copy over the python-directory (C:\programs > > \python2.6) to another windows host and trying to execute python.exe > > there, I get an error that python26.dll could not be found. > > > > On the host where I used the installation routine, python26.dll is > > stored in C:\windows\system32 which (obviously) isn't on the host where > > I just copied the python directory to. > > > > Is it possible to include python26.dll in the application folder or tell > > python not to look in C:\windows\system32 for its library? > > You need to include more than just python26.dll. The correct MSVCRT > version must be shipped with your package or it has to be installed by > your users. > > Fear not, my friend! The solution for your quest is easy to come by. > Install Python 2.6 again but this time chose "install only for me" > instead of "for all users". With this option all necessary files land > into one directory. As long as you have no need for fancy stuff like COM > and Windows services you have to worry about python26.dll in Windows' > system32 directory. > > At work we run our entire application stack including Python2.6, tons of > Python packages with extensions, a complete Java runtime environment and > a pile of DLLs from svn. Works like a charm. > > Christian > -- This email address is used for mailinglist purposes only. Non-mailinglist emails will be dropped automatically. If you want to get in contact with me personally, please mail to: mirko.vogt nanl de From jarausch at igpm.rwth-aachen.de Mon May 3 11:25:07 2010 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 03 May 2010 17:25:07 +0200 Subject: Teaching Programming In-Reply-To: References: Message-ID: <84886fFomtU1@mid.dfncis.de> On 05/03/10 14:29, Chris Rebert wrote: > On Mon, May 3, 2010 at 5:05 AM, Samuel Williams > wrote: >> Dear Friends, >> >> I'm looking for some help from the Python community. I hope this is the >> right place to ask for information. >> >> I'm putting together a website aimed at high school students and teachers, >> and would like to make sure the following page is as good as possible: >> http://programming.dojo.net.nz/languages/python/index >> In particular, "Why would I learn this language?" section needs to have a >> few paragraphs. I don't use Python predominantly so I hoped that you could >> provide the main reasons why Python is a language someone would want to >> learn about. > > - Significant use in certain applications areas: > * Web programming (common frameworks include Django & TurboGears) > * Scientific and numerical computing (see SciPy and Numeric) > - Large "batteries-included" standard library, with a large number of > third-party libraries also available > - Used by Industrial Light and Magic, Google/YouTube, and other big > names (http://www.python.org/about/success/) > - A very clean syntax and elegant design, compared to other languages > I've used Perl for quite some years before I switched to Python. I've been burnt by Perl. There so many hidden variables and states which influence the outcome of nearly each statement in Perl, that it is hard to understand and debug unless you're using it several hours a day (each day). What convinced me is clearly written in http://www.linuxjournal.com/article/3882 Please have a look at it, Helmut. (I'm teaching programming for more than 15 years) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From __peter__ at web.de Mon May 3 11:30:03 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2010 17:30:03 +0200 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: Victor Eijkhout wrote: > I have two long ints, both too long to convert to float, but their ratio > is something reasonable. How can I compute that? The obvious "(1.*x)/y" > does not work. >>> import fractions >>> x = 12345 * 10**1000 >>> y = 765 * 10**1000 >>> float(x) Traceback (most recent call last): File "", line 1, in OverflowError: long int too large to convert to float >>> fractions.Fraction(x, y) Fraction(823, 51) >>> float(_) 16.137254901960784 Peter From malaclypse2 at gmail.com Mon May 3 11:41:31 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 3 May 2010 11:41:31 -0400 Subject: long int computations In-Reply-To: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: On Mon, May 3, 2010 at 11:17 AM, Victor Eijkhout wrote: > I have two long ints, both too long to convert to float, but their ratio > is something reasonable. How can I compute that? The obvious "(1.*x)/y" > does not work. You didn't say what version of python you were using, but this seems to work for me in 2.6.4: >>> long1 = 10**1000 >>> long2 = long1 * 2 >>> float(long1) Traceback (most recent call last): File "", line 1, in float(long1) OverflowError: long int too large to convert to float >>> long1/long2 0L >>> from __future__ import division >>> long1/long2 0.5 The "from __future__ import division" line gets python to return a float as the result of dividing two integers (or longs), instead of returning an integer. If I recall correctly, this has been available for quite a few python versions (since 2.2 maybe?), and has become the default in python 3. If you need to do integer division, you would use the // operator: >>> long1 // long2 0L Hope that helps. -- Jerry From varnikat22 at gmail.com Mon May 3 11:44:48 2010 From: varnikat22 at gmail.com (varnikat t) Date: Mon, 3 May 2010 21:14:48 +0530 Subject: How to check when OCRing is finished Message-ID: Hi, How to check if OCR engine like cuneiform,ocropus,ocrad OCRing an image has completed the job if running it from a python program? I am using a progress bar on the front end to show the OCRing progress happening in background but how to stop progress bar automatically when OCRing is done. As of now, I am just running the timer for a few seconds (considering the maximum time taken by ocropus and for high resolution image) but then the OCRing time varies for different engines and different images.Some take less and some take more. Any solutions? Regards Varnika Tewari (UMIT,SNDT University) -------------- next part -------------- An HTML attachment was scrubbed... URL: From bryanjugglercryptographer at yahoo.com Mon May 3 11:53:18 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Mon, 3 May 2010 08:53:18 -0700 (PDT) Subject: matching strings in a large set of strings References: Message-ID: Karin Lagesen wrote: > I have approx 83 million strings, all 14 characters long. I need to be > able to take another string and find out whether this one is present > within the 83 million strings. [...] > I run out of memory building both the set and the dictionary, so > what I seem to be left with is the list I agree with the recommendations to try modules that maintain the set on disk (sqlite, dbm, shelve), but here's an in-memory solution: Hash to about 8 million buckets, and use a compact representation for the several strings in each bucket. That gives you most of the speed and avoids most of the memory overhead. Python makes it easy: class ConstLenStrSet: """ Keep a set of strings all of the same length. Support set.add() and Python's 'in' test. """ def __init__(self, strlen=14, nbuckets=8000000): assert strlen > 0 and nbuckets > 0 self.strlen = strlen self.nbuckets = nbuckets | 1 self.table = [''] * self.nbuckets def _hashstr(self, s): return hash(s) % self.nbuckets def add(self, s): assert len(s) == self.strlen if s not in self: self.table[self._hashstr(s)] += s def __contains__(self, s): data = self.table[self._hashstr(s)] for i in range(0, len(data), self.strlen): if data[i : i + self.strlen] == s: return True return False # Rudimentary demo-test: from random import choice from string import letters def rnd_str(slen=14): return ''.join(choice(letters) for _ in range(slen)) # Test against Python's built-in set sref = set() for i in range(830000): sref.add(rnd_str()) print('Strings generated.') sset = sset = ConstLenStrSet(14, 80000) for s in sref: sset.add(s) print 'ConstLenStrSet loaded.' for s in sref: assert s in sset for i in range(1000): s = rnd_str() if s in sref: print 'That was unlucky.' else: assert s not in sset If building the set is too slow, and you know you don't have a lot of duplicate strings, you can use a faster insert method that doesn't check whether the string is already in the set: def add_quick(self, s): assert len(s) == self.strlen self.table[self._hashstr(s)] += s -- --Bryan From davea at ieee.org Mon May 3 12:10:36 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 03 May 2010 12:10:36 -0400 Subject: long int computations In-Reply-To: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: <4BDEF57C.1070409@ieee.org> Victor Eijkhout wrote: > I have two long ints, both too long to convert to float, but their ratio > is something reasonable. How can I compute that? The obvious "(1.*x)/y" > does not work. > > Victor. > > You don't make clear what you mean by "too long to convert to float." Do you mean can't convert exactly, or that they're more than 400 digits or whatever the exponent limit of float is (I'm too lazy to look it up right now) ? Assuming the latter, you could divide each by the same constant, then use your formula above to make a float version of the ratio. How to pick the constant? How about the smaller of your numbers, divided by 1e18 ? You'd have to build that number using longs as well. Alternatively, you could build your own floating point library, using longs as the mantissa. DaveA From ppearson at nowhere.invalid Mon May 3 12:16:24 2010 From: ppearson at nowhere.invalid (Peter Pearson) Date: 3 May 2010 16:16:24 GMT Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: <848b6oFvnkU1@mid.individual.net> On Mon, 03 May 2010 17:30:03 +0200, Peter Otten <__peter__ at web.de> wrote: > Victor Eijkhout wrote: > >> I have two long ints, both too long to convert to float, but their ratio >> is something reasonable. How can I compute that? The obvious "(1.*x)/y" >> does not work. > >>>> import fractions >>>> x = 12345 * 10**1000 >>>> y = 765 * 10**1000 >>>> float(x) > Traceback (most recent call last): > File "", line 1, in > OverflowError: long int too large to convert to float >>>> fractions.Fraction(x, y) > Fraction(823, 51) >>>> float(_) > 16.137254901960784 Does this still work if y = 765 * 10**1000 + 1 ? It looks as if it might rely on x and y having a large common divisor. (I blush to confess that my Python has no fractions module, and it's too early in the morning to risk trying to update anything.) -- To email me, substitute nowhere->spamcop, invalid->net. From jpiitula at ling.helsinki.fi Mon May 3 12:23:40 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 03 May 2010 19:23:40 +0300 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: Peter Otten writes: > Victor Eijkhout wrote: > > > I have two long ints, both too long to convert to float, but their > > ratio is something reasonable. How can I compute that? The obvious > > "(1.*x)/y" does not work. > > >>> import fractions > >>> x = 12345 * 10**1000 > >>> y = 765 * 10**1000 > >>> float(x) > Traceback (most recent call last): > File "", line 1, in > OverflowError: long int too large to convert to float > >>> fractions.Fraction(x, y) > Fraction(823, 51) > >>> float(_) > 16.137254901960784 Logarithms agree to 13 decimal digits or so: >>> math.exp(math.log(x) - math.log(y)) 16.13725490196353 From bazwal at ftml.net Mon May 3 12:27:05 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 17:27:05 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: Message-ID: <4BDEF959.7070104@ftml.net> On 03/05/10 15:56, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: >> On 03/05/10 14:46, Peter Otten wrote: >>> Baz Walter wrote: >>> >>>> attempting to remove the cwd would produce an error). but how can python >>>> determine the parent directory of a directory that no longer exists? >>> >>> My tentative explanation would be that the directory, namely the inode, >>> still exists -- only the entry for it in its parent directory is gone. >>> >>> So "one level up from here" is still a valid operation, but there is no >>> longer a path in the file system associated with "here". >> >> so "here" must always be available somehow, > > Yes. > >> even if getcwd() fails > > If the current working directory doesn't _have_ a path within a > filesystem, what do you expect it to do? well, i expect it to fail, like i said :) >> (something like the environment variable $PWD). shame that >> os.getenv('PWD') isn't reliable, as it would solve my issue :( > > I don't understand what you mean by that. i'm trying to understand how the path of the cwd can be known if there is no entry for it in the filesytem - but this is starting to get a little OT, so i won't pursue it here any longer. From invalid at invalid.invalid Mon May 3 12:34:12 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 16:34:12 +0000 (UTC) Subject: strange interaction between open and cwd References: Message-ID: On 2010-05-03, Baz Walter wrote: >>> (something like the environment variable $PWD). shame that >>> os.getenv('PWD') isn't reliable, as it would solve my issue :( >> >> I don't understand what you mean by that. > > i'm trying to understand how the path of the cwd can be known if there > is no entry for it in the filesytem It can't. That's why cwd() failed. > - but this is starting to get a little OT, so i won't pursue it here > any longer. OK. -- Grant Edwards grant.b.edwards Yow! Should I do my BOBBIE at VINTON medley? gmail.com From __peter__ at web.de Mon May 3 12:39:33 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2010 18:39:33 +0200 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> <848b6oFvnkU1@mid.individual.net> Message-ID: Peter Pearson wrote: > On Mon, 03 May 2010 17:30:03 +0200, Peter Otten <__peter__ at web.de> wrote: >> Victor Eijkhout wrote: >> >>> I have two long ints, both too long to convert to float, but their ratio >>> is something reasonable. How can I compute that? The obvious "(1.*x)/y" >>> does not work. >> >>>>> import fractions >>>>> x = 12345 * 10**1000 >>>>> y = 765 * 10**1000 >>>>> float(x) >> Traceback (most recent call last): >> File "", line 1, in >> OverflowError: long int too large to convert to float >>>>> fractions.Fraction(x, y) >> Fraction(823, 51) >>>>> float(_) >> 16.137254901960784 > > Does this still work if y = 765 * 10**1000 + 1 ? It looks > as if it might rely on x and y having a large common divisor. You mean something like this? >>> import fractions >>> x = 765 * 10**1000 >>> fractions.gcd(x, x+1) 1L >>> float(fractions.Fraction(x, x+1)) 1.0 But my D'oh!* moment really was seeing Jerry Hill doing it with >>> from __future__ import division >>> x/(x+1) 1.0 Peter (*) I'm having a lot of these lately. Looks like I need a new brain. From lbolla at gmail.com Mon May 3 12:51:26 2010 From: lbolla at gmail.com (lbolla) Date: Mon, 3 May 2010 09:51:26 -0700 (PDT) Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Message-ID: <3d78b115-9fa2-4b2b-bd0d-ff21f1c9509d@e2g2000yqn.googlegroups.com> On May 3, 8:46?am, Gilles Ganault wrote: > Hello > > I'd like to build a prototype that will combine a web server as > front-end (it must support GZIPping data to the remote client when > there are a lot of data to return), and SQLite as back-end, call the > server from a VB.Net application, and see how well this works. I want > to see if performance is significantly lower than using a server that > uses a binary protocol. > > I'm no Python expert, so would appreciate any information on how to > combine a web server and SQLite into a single Python application. This > is just for a proof-of-concept, so it doesn't need to be > shipping-quality. > > Thank you for any hint. I quite like web.py: http://webpy.org/ L. From bazwal at ftml.net Mon May 3 12:59:25 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 17:59:25 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BDF00ED.8090604@ftml.net> On 03/05/10 15:55, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: >> On 03/05/10 14:56, Chris Rebert wrote: >>>> but how does '..' get resolved in the relative path '../abc.txt'? i'm >>>> assuming python must initially use getcwd() internally to do this, and then >>>> if that fails it falls back on something else. but what is that something >>>> else? is it something that is reproducible in pure python? >>> >>> I would think that the OS system call, not Python itself, does the >>> relative->absolute conversion. >> >> so there is a discrepancy between some of the std library path functions >> (like realpath, getcwd, abspath) and the built-in open function. > > Not really. There is a discrepancy between your perception and > expectations and the way the Unix filesystem works. it's a fact that realpath/abspath/normpath etc can fail for paths that don't when used with os.stat or the builtin open function. i think it's reasonable to expect that a path that can be used to successfully open a file wont then produce "No such file or directory" errors when used with an os.path function like realpath. it shouldn't be necessary to have detailed knowledge of the underlying filesytem to be able to use os.path - it's supposed to be generic. >> there are files which can be opened for which it is impossible to >> resolve their full paths (on some platforms). > > Sort of. The file in question _has_ a full path, you just can't tell > what it is based on the path you used to open it. yes, that's exactly what i was trying to demonstrate in my OP. i can use python to open a file; but under certain circumstances, there seems to be no guarantee that i can then use python to locate that file in the filesystem. From invalid at invalid.invalid Mon May 3 13:12:09 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 17:12:09 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: > it's a fact that realpath/abspath/normpath etc can fail for paths > that don't when used with os.stat or the builtin open function. True. > i think it's reasonable to expect that a path that can be used to > successfully open a file wont then produce "No such file or > directory" errors when used with an os.path function like realpath. Yes, I understand that's what you think. That's not, however, a reasonable expectation in some cases. > it shouldn't be necessary to have detailed knowledge of the > underlying filesytem to be able to use os.path - it's supposed to be > generic. If you ask for the path of a file that has no path (or for which the path can't be determined from the provided information), what do you propose should happen? >>> there are files which can be opened for which it is impossible to >>> resolve their full paths (on some platforms). >> >> Sort of. The file in question _has_ a full path, you just can't tell >> what it is based on the path you used to open it. > > yes, that's exactly what i was trying to demonstrate in my OP. i can > use python to open a file; but under certain circumstances, there > seems to be no guarantee that i can then use python to locate that > file in the filesystem. Exactly. In your example, it's simply not possible to determine the file's absolute path within the filesystem given the relative path you provided. You requested something that wasn't possible. It failed. What do you think should have happened? -- Grant Edwards grant.b.edwards Yow! There's enough money at here to buy 5000 cans of gmail.com Noodle-Roni! From tjreedy at udel.edu Mon May 3 13:15:31 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 May 2010 13:15:31 -0400 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On 5/3/2010 12:37 AM, Alf P. Steinbach wrote: > * Terry Reedy: >> * Alf P. Steinbach: >>> * Aahz: >> >>>> and sometimes >>>> they rebind the original target to the same object. >>> >>> At the Python level that seems to be an undetectable null-operation. >> >> If you try t=(1,2,3); t[1]+=3, if very much matters that a rebind occurs. > > Testing: > > > >>> t = ([], [], []) > >>> t > ([], [], []) > >>> t[0] += ["blah"] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > >>> t > (['blah'], [], []) > >>> _ > > > Yep, it matters. So one should instead write t[0].extend('blah') to the same effect, but without the exception raising assignment attempt, when that is what one really means ;-). Terry Jan Reedy From tjreedy at udel.edu Mon May 3 13:32:14 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 May 2010 13:32:14 -0400 Subject: Teaching Programming In-Reply-To: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> References: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> Message-ID: On 5/3/2010 9:38 AM, Samuel Williams wrote: > Dear Chris, > > Thanks for reading further into the site. > > Yes, it is complicated to provide a good comparison. It isn't always > accurate and I welcome feedback. > > Please be aware that orange does not mean problem - it simply means > take note that there may be potential issues that you need to > consider. It is highly subjective, so I appreciate your feedback. The > red dot is when there is definitely an issue that needs to be taken > into consideration. It isn't "Okay, Warning, Error" because it isn't > possible to make this kind of judgement without being omnipotent. > > There are several reason why I decided to rate the syntax as not > being simple. 1) Indentation model is not appreciated by everyone - I Appreciation is orthogonal to simplicity. > think its a good model, but feedback from some other people has been > that they don't like it. Also, I've had perfectly good Python code > fall to bits after editing in a different editor. I'm not saying that I view this is a consequence of simplicity. Python does not have the complexity of usually redundant (but possibly contradictory) backup indication of structure. So to me, you are rating Python as not simple because it is too simple for some people for some purposes ;-). > this was the fault of Python, but in an educational context it might > be a problem, since people are fairly limited and don't understand > these issues. 2) I don't think that the list comprehension integrates > well with the rest of the language. It is an additional syntactic > construct which seems to be separate from the rest of the language. > It would be nice if list comprehension was implemented in a way that > was more general, using a general closure syntax for example. This is List comprehensions have been generalized in Python 3 to generator expressions and list/set/dict comprehensions. I do not know whether you rate Py2 or Py3 at your site, but for 'should I learn this language' comparision, Py3 would be fairest. > just my opinion, and it might not be valid (I don't research this > point very heavily). > > I appreciate that in general the Python syntax is good and concise. > It is hard. Some teacher might want to consider these issues more > carefully. Do you think I should change that spot to green? I don't > have a problem with doing that, as long as it makes sense. > > Thanks for providing the syntax images, they are very interesting. I chose Python over Perl (over a decade ago) partly because it seemed to me them to have a simpler, more consistent object model and system. Since then, the user class system has been integrated with the builtin type system, and the older separate class system eliminated in Python3, which, again, simplifies things. It is perhaps worth noting that Python's object model, and consequent function calling protocol, dates back at least to Barbara Liskov's CLU language. Terry Jan Reedy From bazwal at ftml.net Mon May 3 13:37:09 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 18:37:09 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> Message-ID: <4BDF09C5.7050107@ftml.net> On 03/05/10 15:24, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: >> On 03/05/10 14:18, Chris Rebert wrote: >>> Whether or not /home/baz/tmp/xxx/ exists, we know from the very >>> structure and properties of directory paths that its parent directory >>> is, *by definition*, /home/baz/tmp/ (just chop off everything after >>> the second-to-last slash). I would assume this is what happens >>> internally. >>> How exactly this interacts with, say, moving the directory to a new >>> location rather than deleting it, I don't know; again, it would quite >>> likely be platform-specific. >> >> but how does '..' get resolved in the relative path '../abc.txt'? > > The current directory has an entry named '..' that points to the > parent directory. > >> i'm assuming python must initially use getcwd() internally to do >> this, > > Nope. Python just passes the string '../abc.txt' to libc's open() > function, and that in turn passes it on to the Unix/Linux open() > syscall, when follows the link in the current working directory named > '..'. > >> and then if that fails it falls back on something else. but what is >> that something else? is it something that is reproducible in pure >> python? > > None of this has anything at all to do with Python. i think what i'm asking for is a python function that, given, say, a valid file descriptor, can return the file's full path. would such a thing even be possible? From invalid at invalid.invalid Mon May 3 13:41:42 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 17:41:42 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: > i think what i'm asking for is a python function that, given, say, a > valid file descriptor, can return the file's full path. Firstly, a file may have any number of paths (including 0). > would such a thing even be possible? Yes. You have to search the filesystem and compare the descirptor's inode number to that of every file in the filesystem. It will match 0 or more of them. However, that will probably take a long time (many minutes) for a typical "single partition" Unix filesystem. If you have a dedicated filesystem with a small number of files, it may be feasible. -- Grant Edwards grant.b.edwards Yow! !! I am having fun!!! at gmail.com From bazwal at ftml.net Mon May 3 13:45:31 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 18:45:31 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BDF0BBB.1080009@ftml.net> On 03/05/10 18:12, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: >>> Sort of. The file in question _has_ a full path, you just can't tell >>> what it is based on the path you used to open it. >> >> yes, that's exactly what i was trying to demonstrate in my OP. i can >> use python to open a file; but under certain circumstances, there >> seems to be no guarantee that i can then use python to locate that >> file in the filesystem. > > Exactly. > > In your example, it's simply not possible to determine the file's > absolute path within the filesystem given the relative path you > provided. > > You requested something that wasn't possible. It failed. What do you > think should have happened? path = '../abc.txt' os.path.realpath(path) -> "OSError: [Errno 2] No such file or directory" therefore: open(path) -> "IOError: [Errno 2] No such file or directory" i think that if the first of these seemingly "impossible" requests fails, it is reasonable to expect that the second one also fails. but the second one (sometimes) doesn't. i think they should always either both succeed, or both fail. From WolfgangMeiners01 at web.de Mon May 3 13:46:19 2010 From: WolfgangMeiners01 at web.de (Wolfgang Meiners) Date: Mon, 03 May 2010 19:46:19 +0200 Subject: recommended way to insert data into a one to many relationship using python In-Reply-To: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4bdf0bec$0$6770$9b4e6d93@newsspool3.arcor-online.net> Wolfgang Meiners schrieb: [... example of a simple sql-database and relating questions ...] so after reading the hints of Peter Otten and Bryan i played around a bit and got the following solution. Of course it would be much simpler following Bryans idea of natural keys but i think, i will go step by step. Any useful comments appreacheated. Wolfgang ================================================================================ # !python # -*- coding: utf-8 -*- import sqlite3 schema = """ create table floors ( fid integer primary key autoincrement, floor text not null); create table rooms ( rid integer primary key autoincrement, number integer, fid integer references floors(fid)); create table employees ( eid integer primary key autoincrement, name text not null, rid integer references rooms(rid)); create view emplist as select name, number, floor from employees natural inner join rooms natural inner join floors; """ #con = sqlite3.connect("test.db") con = sqlite3.connect(":memory:") cur = con.cursor() for cmd in schema.split(';'): cur.execute(cmd) def insert_new_value(d): sql = """insert or ignore into floors(floor) select :floor where not exists (select * from floors where floor = :floor)""" cur.execute(sql,d) sql = """insert or ignore into rooms (number, fid) select :number, fid from floors where floor = :floor and not exists (select * from rooms natural inner join floors where number = :number and floor = :floor)""" cur.execute(sql,d) sql = """insert or ignore into employees(name,rid) select :name, rid from rooms natural inner join floors where number = :number and floor = :floor and not exists (select * from employees natural inner join rooms natural inner join floors where name = :name and number = :number and floor = :floor) """ cur.execute(sql,d) NewEmployees =[] NewEmployees.append({'name': 'Joe', 'number': 21, 'floor': 'first floor'}) NewEmployees.append({'name': 'Nancy', 'number': 22, 'floor': 'second floor'}) NewEmployees.append({'name': 'George', 'number': 89, 'floor': 'third floor'}) NewEmployees.append({'name': 'Ellen', 'number': 21, 'floor': 'first floor'}) NewEmployees.append({'name': 'Joe', 'number': 21, 'floor': 'first floor'}) print "Old Values:" print cur.execute("""select * from emplist order by name """).fetchall() for d in NewEmployees: insert_new_value(d) print "New Values:" print cur.execute("""select * from emplist order by name """).fetchall() con.close() ================================================================================ From crebert at ucsd.edu Mon May 3 13:53:31 2010 From: crebert at ucsd.edu (Chris Rebert) Date: Mon, 3 May 2010 10:53:31 -0700 Subject: How to check when OCRing is finished In-Reply-To: References: Message-ID: On Mon, May 3, 2010 at 8:44 AM, varnikat t wrote: > Hi, > How to check if OCR engine? like cuneiform,ocropus,ocrad OCRing an image has > completed the job if running it from a? python program? > > I am using a progress bar on the front end to show the OCRing progress > happening in background but how to stop progress bar automatically when > OCRing is done. > > As of now, I am just running the timer for a few seconds (considering the > maximum time taken by ocropus and for high resolution image) but then the > OCRing time varies for different engines and different images.Some take less > and some take more. > > Any solutions? I believe one generally uses an "indeterminate progress bar", throbber (http://en.wikipedia.org/wiki/Throbber), or other similar widget rather than a normal progress bar when the time an operation will take is indeterminate or can't be accurately estimated (in this case, due to invoking an external program which apparently does not report its intermediate progress). I presume such widgets have a way to be easily notified, and thus in turn indicate to the user, when an operation has indeed been completed. Cheers, Chris -- http://blog.rebertia.com From bazwal at ftml.net Mon May 3 13:56:59 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 18:56:59 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> Message-ID: <4BDF0E6B.2010600@ftml.net> On 03/05/10 18:41, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: > >> i think what i'm asking for is a python function that, given, say, a >> valid file descriptor, can return the file's full path. > > Firstly, a file may have any number of paths (including 0). yes, of course. i forgot about hard links - that pretty much kills that idea. oh well. From clp2 at rebertia.com Mon May 3 14:05:00 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 11:05:00 -0700 Subject: strange interaction between open and cwd In-Reply-To: <4BDF0BBB.1080009@ftml.net> References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> Message-ID: On Mon, May 3, 2010 at 10:45 AM, Baz Walter wrote: > On 03/05/10 18:12, Grant Edwards wrote: >> On 2010-05-03, Baz Walter ?wrote: >>>> Sort of. ?The file in question _has_ a full path, you just can't tell >>>> what it is based on the path you used to open it. >>> >>> yes, that's exactly what i was trying to demonstrate in my OP. i can >>> use python to open a file; but under certain circumstances, there >>> seems to be no guarantee that i can then use python to locate that >>> file in the filesystem. >> >> Exactly. >> >> In your example, it's simply not possible to determine the file's >> absolute path within the filesystem given the relative path you >> provided. >> >> You requested something that wasn't possible. ?It failed. ?What do you >> think should have happened? > > path = '../abc.txt' > > os.path.realpath(path) -> "OSError: [Errno 2] No such file or directory" > > therefore: > > open(path) -> "IOError: [Errno 2] No such file or directory" > > i think that if the first of these seemingly "impossible" requests fails, it > is reasonable to expect that the second one also fails. but the second one > (sometimes) doesn't. > > i think they should always either both succeed, or both fail. Well, that's Unix and Worse-is-Better[1] for ya. Inelegant theoretically, but probably makes some bit of the OS's job slightly easier and is usually good enough in practice. Pragmatism is a bitch sometimes. :-) Cheers, Chris -- [1]: http://en.wikipedia.org/wiki/Worse_is_better http://blog.rebertia.com From bazwal at ftml.net Mon May 3 14:10:53 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 19:10:53 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> Message-ID: <4BDF11AD.2060009@ftml.net> On 03/05/10 19:05, Chris Rebert wrote: > On Mon, May 3, 2010 at 10:45 AM, Baz Walter wrote: >> On 03/05/10 18:12, Grant Edwards wrote: >>> On 2010-05-03, Baz Walter wrote: >>>>> Sort of. The file in question _has_ a full path, you just can't tell >>>>> what it is based on the path you used to open it. >>>> >>>> yes, that's exactly what i was trying to demonstrate in my OP. i can >>>> use python to open a file; but under certain circumstances, there >>>> seems to be no guarantee that i can then use python to locate that >>>> file in the filesystem. >>> >>> Exactly. >>> >>> In your example, it's simply not possible to determine the file's >>> absolute path within the filesystem given the relative path you >>> provided. >>> >>> You requested something that wasn't possible. It failed. What do you >>> think should have happened? >> >> path = '../abc.txt' >> >> os.path.realpath(path) -> "OSError: [Errno 2] No such file or directory" >> >> therefore: >> >> open(path) -> "IOError: [Errno 2] No such file or directory" >> >> i think that if the first of these seemingly "impossible" requests fails, it >> is reasonable to expect that the second one also fails. but the second one >> (sometimes) doesn't. >> >> i think they should always either both succeed, or both fail. > > Well, that's Unix and Worse-is-Better[1] for ya. Inelegant > theoretically, but probably makes some bit of the OS's job slightly > easier and is usually good enough in practice. Pragmatism is a bitch > sometimes. :-) yeah, i probably should have added "in an ideal world" or something :) From invalid at invalid.invalid Mon May 3 14:12:10 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 18:12:10 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: >> You requested something that wasn't possible. It failed. What do >> you think should have happened? > > path = '../abc.txt' > > os.path.realpath(path) -> "OSError: [Errno 2] No such file or directory" > > therefore: > > open(path) -> "IOError: [Errno 2] No such file or directory" > > i think that if the first of these seemingly "impossible" requests > fails, it is reasonable to expect that the second one also fails. but > the second one (sometimes) doesn't. Because the second one isn't impossible in the case you posted. > i think they should always either both succeed, or both fail. That's not how Unix filesystems work. Are you saying that Python should add code to it's open() builtin which calls realpath() and then refuses to open files for which realpath() fails? Even though the user provided a legal and openable path? -- Grant Edwards grant.b.edwards Yow! Did I say I was at a sardine? Or a bus??? gmail.com From invalid at invalid.invalid Mon May 3 14:14:47 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 18:14:47 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> Message-ID: On 2010-05-03, Chris Rebert wrote: >> open(path) -> "IOError: [Errno 2] No such file or directory" >> >> i think that if the first of these seemingly "impossible" requests fails, it >> is reasonable to expect that the second one also fails. but the second one >> (sometimes) doesn't. >> >> i think they should always either both succeed, or both fail. > > Well, that's Unix and Worse-is-Better[1] for ya. Inelegant > theoretically, I don't see how it's inelegant at all. Perhaps it's counter-intuitive if you don't understand how a Unix filesystem works, but the underlying filesystem model is very simple, regular, and elegant. > but probably makes some bit of the OS's job slightly easier and is > usually good enough in practice. Pragmatism is a bitch sometimes. :-) -- Grant Edwards grant.b.edwards Yow! ... I'm IMAGINING a at sensuous GIRAFFE, CAVORTING gmail.com in the BACK ROOM of a KOSHER DELI -- From andre.roberge at gmail.com Mon May 3 14:23:00 2010 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 3 May 2010 11:23:00 -0700 (PDT) Subject: Teaching Programming References: Message-ID: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> To Samuel Williams: (and other interested ;-) If you want to consider Python in education, I would encourage you have a look at http://www.python.org/community/sigs/current/edu-sig/ I think you will find that there are quite a few resources available - perhaps more than you are aware of. And, I don't think that because "some people do not like the indentation strategy" is a valid reason not to consider that Python's syntax is concise and simple. Actually, I would almost argue for the contrary. Indentation indicate programming structure/logic very clearly, without the need for arbitrary keywords and other punctuation symbols. There are very few keywords in the language. You indicate that Python programs are readable. They are also known to be short (much shorter than some other languages). Andr? From a_jtim at bellsouth.net Mon May 3 15:09:28 2010 From: a_jtim at bellsouth.net (Tim Arnold) Date: Mon, 3 May 2010 12:09:28 -0700 (PDT) Subject: design question Message-ID: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> This is a question about system design I guess. I have a django website that allows users to change/view configuration details for documentation builds. The database is very small. The reason I'm using a database in the first place is to make it easy for users to change the configuration of their builds. Django makes that easy and I can go on to other problems, like actually building the documentation. During a build, I query the configuration database at different times to get the configuration I need, which results in several calls to the database at different points of the build process. It doesn't feel right that I'm making these calls at different times. I *could* make a single big call at the beginning of the build, basically serializing all the config data I could need into a dictionary or maybe a json structure. And just pass that structure around as needed during the build, with no more database calls needed. These builds take from a few minutes to an hour or so, with the time spent making db calls almost insignificant. So if time isn't a problem, am I wringing my hands over something that really doesn't matter much? I guess it just doesn't feel like the right thing to me. thanks, --Tim From tomf.sessile at gmail.com Mon May 3 15:24:33 2010 From: tomf.sessile at gmail.com (TomF) Date: Mon, 3 May 2010 12:24:33 -0700 Subject: Django as exemplary design Message-ID: <2010050312243328275-tomfsessile@gmailcom> I'm interested in improving my python design by studying a large, well-designed codebase. Someone (not a python programmer) suggested Django. I realize that Django is popular, but can someone comment on whether its code is well-designed and worth studying? Thanks, -Tom From gandalf at shopzeus.com Mon May 3 15:28:39 2010 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 03 May 2010 21:28:39 +0200 Subject: duplicate temporary file? Message-ID: <4BDF23E7.8090505@shopzeus.com> I try to write an iterator class: class FileIterator(object): def __init__(self,file_object): self.fin = file_object # other initialization code here ... def __iter__(self): return self def next(self): # special code that reads from the file and converts to Pythonic data... This iterator I want to use with regular binary file objects. My requirement is to be able to create many iterators for the same file object, and use them from many threads - which is not straightforward. Of course I do not want to save file positions in the iterators, use locking on the file, and call seek() every time I need to read from the file. Instead of that, I try to re-open the file for each iteator. The trivial way to do it is: class FileIterator(object): def __init__(self,file_object): self.fin = open(file_object.name,"rb") self.fin.seek(file_object.tell()) ... However, it won't work for temporary files. Temporary files are just file-like objects, and their name is ''. I guess I could open a temporary file with os.open, and then use os.dup, but that is low level stuff. Then I have to use os.* methods, and the file object won't be iterable. tempfile.NamedTempFile is not better, because it cannot be reopened under Windows. So the question is, how do I create my iterator so that: * under Windows and Unix * many iterators can be used for the same underlying file, from many threads * with a normal binary file * and also with temporary files A workaround would be to create a temporary directory, and then create real files inside the temporary directory. If there is no better way to do it, I'll do that. Thanks Laszlo -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Mon May 3 15:43:00 2010 From: lists at cheimes.de (Christian Heimes) Date: Mon, 03 May 2010 21:43:00 +0200 Subject: duplicate temporary file? In-Reply-To: <4BDF23E7.8090505@shopzeus.com> References: <4BDF23E7.8090505@shopzeus.com> Message-ID: Laszlo Nagy wrote: > However, it won't work for temporary files. Temporary files are just > file-like objects, and their name is ''. I guess I could open a > temporary file with os.open, and then use os.dup, but that is low level > stuff. Then I have to use os.* methods, and the file object won't be > iterable. tempfile.NamedTempFile is not better, because it cannot be > reopened under Windows. On POSIX OSes like Linux a temporary file *is* a real file. It just doesn't have a name on the file system anymore. The concept is called an anonymous file. Python creates the file in the tmp directory and unlinks the name. The file still needs resources on the file system but you can "see" it. The /proc/PID/fd/ directory will show the temporary files. In order to copy the file handler you have to os.dup() the file descriptor (file_object.fileno()) and os.fdopen() it to get a file object. The Python documentation and the man pages dup(2), fileno(3) and fopen(3) will give you more information. Christian From mail at timgolden.me.uk Mon May 3 16:02:36 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 03 May 2010 21:02:36 +0100 Subject: win32 - catch events(wmi?) In-Reply-To: <201005031302.31772.richard.lamboj@bilcom.at> References: <201005031302.31772.richard.lamboj@bilcom.at> Message-ID: <4BDF2BDC.7020805@timgolden.me.uk> On 03/05/2010 12:02 PM, Richard Lamboj wrote: > i want catch the following events: > - registry has chanced > - file has chanced > - outgoing network connection > - programm start > > and i want to be able to allow, or deny this "requests". Wow. That's quite a list. To do what you want in general terms, you're into driver-level code which you're really not going to be able to do with Python. Windows does provide certain hooks and events but they're relatively limited. And the final requirement of being able to allow or deny requests is basically what the OS does via security, so to do it yourself would be quite a large task, methinks. In principle, you can use WMI events to track some of the things you've listed. The only one I'd really recommend is "program[m] start" for which you can see an related example here: http://timgolden.me.uk/python/wmi/cookbook.html#run-notepad-wait-until-it-s-closed-and-then-show-its-text Even there, WMI is polling on your behalf and if programs are spawning fast enough you'll miss one or more events. File monitoring *can* be done with the same sort of technique from within WMI, but don't: it will bring your disk to its knees. Instead, use the file monitoring APIs, such as: http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges I'm not aware of any technique for monitoring registry use, altho' a scan of sysinternals (or its ms-owned replacement) might yield something. And I'm not sure exactly what you mean by "outgoing network connection": that's really what the Windows firewall is there for. The firewall does have a WMI interface, although at this moment I can't remember where it is, which would enable you to set some things up, but I don't believe it provides an event/callback mechanism. Might be worth Googling to see if I'm wrong. And in all these cases, I'm really only talking about monitoring usage: you can terminate a process once it's open; you can delete a file once it's created; you can (possibly) nobble a socket connection once it's been made, but anything else and you're doing the Operating System's job for it. TJG From pavlovevidence at gmail.com Mon May 3 16:13:42 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 May 2010 13:13:42 -0700 (PDT) Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <5e748866-3ff5-43f7-bdca-08de1a0a534f@e35g2000yqm.googlegroups.com> On May 3, 12:24?pm, TomF wrote: > I'm interested in improving my python design by studying a large, > well-designed codebase. ?Someone (not a python programmer) suggested > Django. ?I realize that Django is popular, but can someone comment on > whether its code is well-designed and worth studying? I once delved into django because I wanted to use a couple of the administrative tools for non-web tasks, and found it to be disappointingly ad hoc. It it makes some assumptions about file locations and module names (unnecessarily, IMO). It works well as long as someone sticks to the rigid conventions, but can't cope well with deviances. Therefore I'd call its codebase less than exemplary. As a tool it's quite good (as long as you can stick to the prescribed layout) but that's a different question. Carl Banks From rouslank at msn.com Mon May 3 16:44:02 2010 From: rouslank at msn.com (Rouslan Korneychuk) Date: Mon, 03 May 2010 16:44:02 -0400 Subject: new extension generator for C++ Message-ID: Hi, I'm new here. I'm working on a program that exposes C++ declarations to Python and I was wondering if there is any interest in it. It's a hobby project. I was originally using Boost.Python on another project but found a couple of things I didn't like. Eg: you can't really have private constructors. If you want a Python object created, you either have to expose the constructor in Python, or create an instance of the object somewhere else in memory, and have it either copied to the PyObject or have the PyObject hold a reference to it. I was working on a rudimentary 3D game engine that was a Python extension. It was important to avoid copying potentially huge amounts of data, but to have almost every PyObject just be a pointer to another object (and the object already is just a few or even one pointer) seemed like an pointless compromise, considering that I was writing code that was specifically designed to be a Python extension (There was also another issue I came across but don't remember now). So I looked for other solutions and noticed that Py++ (which simply generates Boost.Python code for you) was based on a seperate program called GCCXML. I figured I could use GCCXML and generate code however I wanted. So I did. My program generates human-readable code (it even uses proper indentation). The program still has a lot of work to be done on it, but it can already generate working Python extensions. It takes an input file like this: module doc string class doc string You can probably figure out what the resulting code does. The goal is to generate code that is as close to hand-written code as possible. It even forgoes using PyArg_ParseTupleAndKeywords and has the argument checks hard-wired. It also generates a header file that contains a PyObject implementation of MyClass called obj_AClass, with every constructor fowarded and with the new and delete operators overloaded to play nice with Python's memory handler: ... extern PyTypeObject obj_AClassType; struct obj_AClass { PyObject_HEAD MyClass base; bool initialized; void *operator new(size_t s) { void *ptr = PyMem_Malloc(s); if(!ptr) throw std::bad_alloc(); return ptr; } void operator delete(void *ptr) { PyMem_Free(ptr); } obj_AClass(MyClass const & _0) : base(_0) { PyObject_Init(reinterpret_cast(this),&obj_AClassType); initialized = true; } obj_AClass(unsigned int _0) : base(_0) { PyObject_Init(reinterpret_cast(this),&obj_AClassType); initialized = true; } }; ... If you want to expose one overload of a constructor or function but not the others, you can add overload="list,of,args" to or . Default values for arguments are handled automatically. When handling overloaded functions, it checks the types of the arguments to pick the best overload, taking into consideration polymorphism and the fact that basic types like ints can be converted from one-another. It will automatically detect if two overloads match to the same set of Python arguments (eg: void func(float) vs void func(double)). The only issue is it will not use keyword arguments for overloaded functions (I don't know if that can even be done reliably *and* efficiently. I would need to give it more thought). If there is enough interest I can put this project up on SourceForge or Google Code. From see at sig.for.address Mon May 3 16:49:02 2010 From: see at sig.for.address (Victor Eijkhout) Date: Mon, 3 May 2010 15:49:02 -0500 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: <1jhxakp.1xj5u9nd6k7x7N%see@sig.for.address> Jerry Hill wrote: > >>> from __future__ import division > >>> long1/long2 > 0.5 Beautiful. Thanks so much guys. Victor. -- Victor Eijkhout -- eijkhout at tacc utexas edu From realvrz at aol.com Mon May 3 16:49:14 2010 From: realvrz at aol.com (Country Boy) Date: Mon, 3 May 2010 13:49:14 -0700 (PDT) Subject: PyQt Ram Usage Message-ID: <023dd1f9-7a9c-4f46-a6a6-9821bc7e6de0@b7g2000yqk.googlegroups.com> Hi, I am new to Python (and programming so pardon my ignorance) I have a small PyQt program that lives in windows system tray. I am using Suds & ElemetTree to do webservices call and parse XML. I have a QTimer that runs every 30 seconds and fetches the updated data from the server. Finally, the python script is "frozen" into exe using CX_FREEZE. When I run the exe, it starts with 18MB (which i think i high for an app that just fetches info from webserver and creates a menu full of web url shortcuts, but thats besides the point). After every 30 seconds (as my QTimer timeout()), my RAM usage goes up by 400KB. So after an hour or two of running the application almost uses ~60MB or more, which is ridiculous. I think my application has some memory leaks and I think every time I create an instance of the WebService class (its a QThread that fetches information using WSDL) the RAM goes up but doesn't get released once Class's work is done. Can somebody pls direct me into the things that I should be looking into to troubleshooting this issue... I am running my application on Windows Embedded thin clients so its really important that my application's memory footprint is low. Update: I tried del and it decreased the amount of RAM overall, but the application still starts with 20MB and then goes unto 40MB. From david at boddie.org.uk Mon May 3 17:53:08 2010 From: david at boddie.org.uk (David Boddie) Date: Mon, 03 May 2010 23:53:08 +0200 Subject: PyQt Ram Usage References: <023dd1f9-7a9c-4f46-a6a6-9821bc7e6de0@b7g2000yqk.googlegroups.com> Message-ID: On Monday 03 May 2010 22:49, Country Boy wrote: > I am new to Python (and programming so pardon my ignorance) > I have a small PyQt program that lives in windows system tray. I am > using Suds & ElemetTree to do webservices call and parse XML. > I have a QTimer that runs every 30 seconds and fetches the updated > data from the server. > Finally, the python script is "frozen" into exe using CX_FREEZE. > When I run the exe, it starts with 18MB (which i think i high for an > app that just fetches info from webserver and creates a menu full of > web url shortcuts, but thats besides the point). It's the price you pay for features. There are ways to cut out features you don't want if you're prepared to use a specialised version of Qt. > After every 30 seconds (as my QTimer timeout()), my RAM usage goes up > by 400KB. So after an hour or two of running the application almost > uses ~60MB or more, which is ridiculous. > I think my application has some memory leaks and I think every time I > create an instance of the WebService class (its a QThread that fetches > information using WSDL) the RAM goes up but doesn't get released once > Class's work is done. Can somebody pls direct me into the things that > I should be looking into to troubleshooting this issue... Qt has its own way of managing memory that usually plays well with Python's own memory management, but there are ways to accidentally create objects that will stay alive until the application exits. In particular, beware of creating objects with a parent QObject if you really want to manage them from Python because Qt will keep the underlying C++ object around, even if you delete the object in Python. This might not be the reason for the memory usage you see, but it's one thing to look at. You might also need to show us some code if the problem turns out to be more complicated than this. David From bazwal at ftml.net Mon May 3 17:57:41 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 22:57:41 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BDF46D5.1040501@ftml.net> On 03/05/10 19:12, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: > >>> You requested something that wasn't possible. It failed. What do >>> you think should have happened? >> >> path = '../abc.txt' >> >> os.path.realpath(path) -> "OSError: [Errno 2] No such file or directory" >> >> therefore: >> >> open(path) -> "IOError: [Errno 2] No such file or directory" >> >> i think that if the first of these seemingly "impossible" requests >> fails, it is reasonable to expect that the second one also fails. but >> the second one (sometimes) doesn't. > > Because the second one isn't impossible in the case you posted. > >> i think they should always either both succeed, or both fail. > > That's not how Unix filesystems work. > > Are you saying that Python should add code to it's open() builtin > which calls realpath() and then refuses to open files for which > realpath() fails? my original question was really about *how* python does the "seemingly impossible". i had hoped there might be a way to augment realpath so that it would always work for any path which is openable. but apparently that is not possible for unix filesystems. > Even though the user provided a legal and openable path? that sounds like an operational definition to me: what's the difference between "legal" and "openable"? From g.rodola at gmail.com Mon May 3 18:53:59 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Tue, 4 May 2010 00:53:59 +0200 Subject: win32 - catch events(wmi?) In-Reply-To: <4BDF2BDC.7020805@timgolden.me.uk> References: <201005031302.31772.richard.lamboj@bilcom.at> <4BDF2BDC.7020805@timgolden.me.uk> Message-ID: Just out of curiosity, is WMI able to list the TCP and UDP connections opened by a process or by the OS? We'll have to do this for psutil (http://code.google.com/p/psutil) and we guess it's not gonna be easy. --- Giampaolo http://code.google.com/p/psutil http://code.google.com/p/pyftpdlib 2010/5/3 Tim Golden : > On 03/05/2010 12:02 PM, Richard Lamboj wrote: >> >> i want catch the following events: >> ?- registry has chanced >> ?- file has chanced >> ?- outgoing network connection >> ?- programm start >> >> and i want to be able to allow, or deny this "requests". > > Wow. That's quite a list. To do what you want in general > terms, you're into driver-level code which you're really > not going to be able to do with Python. Windows does > provide certain hooks and events but they're relatively > limited. And the final requirement of being able to allow > or deny requests is basically what the OS does via security, > so to do it yourself would be quite a large task, methinks. > > In principle, you can use WMI events to track some of > the things you've listed. The only one I'd really recommend > is "program[m] start" for which you can see an related example > here: > > ?http://timgolden.me.uk/python/wmi/cookbook.html#run-notepad-wait-until-it-s-closed-and-then-show-its-text > > Even there, WMI is polling on your behalf and if programs are > spawning fast enough you'll miss one or more events. > > File monitoring *can* be done with the same sort of technique > from within WMI, but don't: it will bring your disk to its > knees. Instead, use the file monitoring APIs, such as: > > ?http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges > > I'm not aware of any technique for monitoring registry use, > altho' a scan of sysinternals (or its ms-owned replacement) > might yield something. And I'm not sure exactly what you > mean by "outgoing network connection": that's really what the > Windows firewall is there for. The firewall does have a WMI > interface, although at this moment I can't remember where it > is, which would enable you to set some things up, but I don't > believe it provides an event/callback mechanism. Might be worth > Googling to see if I'm wrong. > > And in all these cases, I'm really only talking about monitoring > usage: you can terminate a process once it's open; you can delete > a file once it's created; you can (possibly) nobble a socket > connection once it's been made, but anything else and you're > doing the Operating System's job for it. > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > From kevin.p.dwyer at gmail.com Mon May 3 19:29:18 2010 From: kevin.p.dwyer at gmail.com (Kev) Date: Mon, 3 May 2010 23:29:18 +0000 (UTC) Subject: design question References: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> Message-ID: Tim Arnold wrote: > This is a question about system design I guess. I have a django > website that allows users to change/view configuration details for > documentation builds. The database is very small. The reason I'm using > a database in the first place is to make it easy for users to change > the configuration of their builds. Django makes that easy and I can go > on to other problems, like actually building the documentation. > > During a build, I query the configuration database at different times > to get the configuration I need, which results in several calls to the > database at different points of the build process. > > It doesn't feel right that I'm making these calls at different times. > I *could* make a single big call at the beginning of the build, > basically serializing all the config data I could need into a > dictionary or maybe a json structure. And just pass that structure > around as needed during the build, with no more database calls needed. > > These builds take from a few minutes to an hour or so, with the time > spent making db calls almost insignificant. So if time isn't a > problem, am I wringing my hands over something that really doesn't > matter much? I guess it just doesn't feel like the right thing to me. > > thanks, > --Tim Hello Tim, Given the times that you've quoted for the documentation builds, a few microseconds here and there for database queries doesn't really matter. The Django docs, as it happens, look favourably on doing one query up front, (http://docs.djangoproject.com/en/1.1/topics/db/optimization/#topics-db-optimization), but they also recommend profiling first, which would presumably highlight the insignificance of your queries compared with the duration of the builds. So I think the upshot is don't worry about it, or if you must, accept that you're worrying more about aesthetics than anything else (not that aesthetics aren't important). Cheers, Kev From lie.1296 at gmail.com Mon May 3 19:39:20 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 04 May 2010 09:39:20 +1000 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4bdf5f09$1@dnews.tpgi.com.au> On 05/04/10 07:57, Baz Walter wrote: > On 03/05/10 19:12, Grant Edwards wrote: >> On 2010-05-03, Baz Walter wrote: >> >>>> You requested something that wasn't possible. It failed. What do >>>> you think should have happened? >>> >>> path = '../abc.txt' >>> >>> os.path.realpath(path) -> "OSError: [Errno 2] No such file or >>> directory" >>> >>> therefore: >>> >>> open(path) -> "IOError: [Errno 2] No such file or directory" >>> >>> i think that if the first of these seemingly "impossible" requests >>> fails, it is reasonable to expect that the second one also fails. but >>> the second one (sometimes) doesn't. >> >> Because the second one isn't impossible in the case you posted. >> >>> i think they should always either both succeed, or both fail. >> >> That's not how Unix filesystems work. >> >> Are you saying that Python should add code to it's open() builtin >> which calls realpath() and then refuses to open files for which >> realpath() fails? > > my original question was really about *how* python does the "seemingly > impossible". i had hoped there might be a way to augment realpath so > that it would always work for any path which is openable. but apparently > that is not possible for unix filesystems. It's the OS that does the "seemingly impossible" things. Python only makes the relevant system call with the string you've given, and leaves the rest of the magic of resolving the real file to open, opening the filename, moving the harddrive head, etc to OS kernel. If OS kernel dictates that you can open a file that have no actual path; then Python will do so. >> Even though the user provided a legal and openable path? > > that sounds like an operational definition to me: what's the difference > between "legal" and "openable"? From cjw at ncf.ca Mon May 3 19:46:19 2010 From: cjw at ncf.ca (cjw) Date: Mon, 03 May 2010 19:46:19 -0400 Subject: Teaching Programming In-Reply-To: References: Message-ID: On 03-May-10 09:38 AM, Samuel Williams wrote: > Dear Chris, > > Thanks for reading further into the site. > > Yes, it is complicated to provide a good comparison. It isn't always accurate and I welcome feedback. > > Please be aware that orange does not mean problem - it simply means take note that there may be potential issues that you need to consider. It is highly subjective, so I appreciate your feedback. The red dot is when there is definitely an issue that needs to be taken into consideration. It isn't "Okay, Warning, Error" because it isn't possible to make this kind of judgement without being omnipotent. > > There are several reason why I decided to rate the syntax as not being simple. > 1) Indentation model is not appreciated by everyone - I think its a good model, but feedback from some other people has been that they don't like it. Also, I've had perfectly good Python code fall to bits after editing in a different editor. I'm not saying that this was the fault of Python, but in an educational context it might be a problem, since people are fairly limited and don't understand these issues. Nobody likes indentation at first, it is different. There is no begin/end and not {}. That feeling might last for an hour. People welcome the absence of clutter. Indentation makes it easier to read and understand the code. Coding errors are easily found with a good IDE, such as PyScripter Colin W. > 2) I don't think that the list comprehension integrates well with the rest of the language. It is an additional syntactic construct which seems to be separate from the rest of the language. It would be nice if list comprehension was implemented in a way that was more general, using a general closure syntax for example. This is just my opinion, and it might not be valid (I don't research this point very heavily). > > I appreciate that in general the Python syntax is good and concise. It is hard. Some teacher might want to consider these issues more carefully. Do you think I should change that spot to green? I don't have a problem with doing that, as long as it makes sense. > > Thanks for providing the syntax images, they are very interesting. > > With regards to Perl, yes, this is probably something I need to investigate further. It is not always easy to do a comparison of this nature. From my experience, Perl generally seems to have a robust object model that is consistently implemented (even if the syntax is pretty wonky at times). However, in a sense, it is no better or worse than Python implementation... so why is it green dot? Do you think I should change Perl to orange or Python to green. > > The main criteria is whether it is going to be an issue in an educational context - this means, for new programmers, or those who might make error easily (syntax, semantic), etc. > > Also, I wonder if Visual Basic needs to be reevaluated on this criteria too. I guess what is important is the relative importance. > > I will bring this issue up on the Perl mailing list in order to get advice. > > Would you recommend changing Perl to orange? > > Thanks for your well thought out response, it is very helpful. > > Kind regards, > Samuel > > On 4/05/2010, at 1:06 AM, Chris Rebert wrote: > >> On Mon, May 3, 2010 at 5:29 AM, Chris Rebert wrote: >>> On Mon, May 3, 2010 at 5:05 AM, Samuel Williams >>> wrote: >>>> Dear Friends, >>>> >>>> I'm looking for some help from the Python community. I hope this is the >>>> right place to ask for information. >>>> >>>> I'm putting together a website aimed at high school students and teachers, >>>> and would like to make sure the following page is as good as possible: >>>> http://programming.dojo.net.nz/languages/python/index >>>> In particular, "Why would I learn this language?" section needs to have a >>>> few paragraphs. I don't use Python predominantly so I hoped that you could >>>> provide the main reasons why Python is a language someone would want to >>>> learn about. >> >>> - A very clean syntax and elegant design, compared to other languages >> >> Also, I take issue with your classifying Python as orange with regard >> to "Is the general syntax simple and concise?" on >> http://programming.dojo.net.nz/resources/programming-language-comparison/index >> Python's syntax is at least as simple, if not simpler, than Ruby's, >> which you rate as green. Ruby may be /slightly/ more concise than >> Python in certain cases due to its Perl influences, but those >> instances of specialized syntax also make it more complex. >> To wit, I refer you to >> http://webcache.googleusercontent.com/search?q=cache:dyugd_KlqvcJ:blog.nicksieger.com/articles/2006/10/27/visualization-of-rubys-grammar+ruby+grammar+visualization&cd=1&hl=en&ct=clnk&gl=us >> Note the complexity of the graph for Ruby's grammar. By comparison, >> here is the same graph for Python (generated from a file linked to in >> the post's comment thread): >> http://rebertia.com/images/python_grammar_graph.png >> (Disclaimer: Neither of the graphs are current.) >> >> Additionally, you rate Python orange but Perl green for "Does the >> language provide a useful and consistent set of object oriented >> constructs?". Could you explain your reasoning for this? While neither >> Python nor Perl have the level of object-oriented purity of Ruby or >> Smalltalk, my understanding is that short of using CPAN libraries for >> Perl or dealing in Perl 6, Perl and Python have a substantially >> similar object model, so I don't how Python could rate below Perl in >> this area. >> >> Cheers, >> Chris >> -- >> http://blog.rebertia.com > From kalin at el.net Mon May 3 19:53:11 2010 From: kalin at el.net (kalin m) Date: Mon, 03 May 2010 19:53:11 -0400 Subject: msg_footer Message-ID: <4BDF61E7.2030808@el.net> is there a variable for the member's email address in the msg_footer? the one the message is being sent to? thanks.... From C.Sanders at DeleteThis.Bom.GOV.AU Mon May 3 20:16:39 2010 From: C.Sanders at DeleteThis.Bom.GOV.AU (Charles) Date: Tue, 4 May 2010 10:16:39 +1000 Subject: [OT] strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> Message-ID: <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> "Grant Edwards" wrote in message news:hrn3qn$nh0$2 at reader1.panix.com... > On 2010-05-03, Chris Rebert wrote: > >>> open(path) -> "IOError: [Errno 2] No such file or directory" >>> >>> i think that if the first of these seemingly "impossible" requests >>> fails, it >>> is reasonable to expect that the second one also fails. but the second >>> one >>> (sometimes) doesn't. >>> >>> i think they should always either both succeed, or both fail. >> >> Well, that's Unix and Worse-is-Better[1] for ya. Inelegant >> theoretically, > > I don't see how it's inelegant at all. Perhaps it's counter-intuitive > if you don't understand how a Unix filesystem works, but the > underlying filesystem model is very simple, regular, and elegant. > >> but probably makes some bit of the OS's job slightly easier and is >> usually good enough in practice. Pragmatism is a bitch sometimes. :-) > I agree that the Unix file system is quite elegant, but can be counter-intuitive for people who are used to the "one file, one name" paradigm. Simplifying, if I recall correctly from Unix courses in the early 1980's, Unix knows a file by the triple (device major number, device minor number, inode number). Ignoring mount points, directories are simply files that contain a map from names (components of a path) to inode numbers, assumed to be on the same device as the directory. There can be many references to the same inode ("hard" links). The OS keeps track of how many references there are to a file and deletes files when they no longer have any references. Opening a file, or using a directory as the current working directory, count as references. Removing a file or directory removes the reference in the file system, but leaves the in memory references for open files or current directories. Thus, removing a file (or directory) while one or more processes have an open file descriptor referring to it (or have it as their current directory) does not result in it being deleted. The in-memory references keep it alive, but it is no longer accessible to other processes as it no longer has a name in the file system. It is (or used to be) a common unix idiom to create and open a temporary file (or create a temporary directory and cd to it), and then delete it. This ensured that no other processes could then access the file/directory (it no longer had a name in the file system), and that the file (directory) will usually be deleted by the OS when the process exits, as the only reference to the file/directory is the open file descriptor/current directory in the process, which disappears when the process exits. This applies even if the normal end of process cleanup does not happen because of a (Unix) kill -9 or other major problem, and usually applies even in case of a system crash. In the OP's case, references to the directory have been removed from the file system, but his process still has the current working directory reference to it, so it has not actually been deleted. When he opens "../abc.txt", the OS searches the current directory for ".." and finds the inode for /home/baz/tmp, then searches that directory (/home/baz/tmp) for abc.txt and finds it. Note that, on unix, hard links and possible duplicate NFS mounts make it impossible to guarantee a unique "name" for a file. Even on windows, multiple CIFS mounts can result in in being impossible to guarantee a unique name. Charles From alfps at start.no Mon May 3 20:21:36 2010 From: alfps at start.no (Alf P. Steinbach) Date: Tue, 04 May 2010 02:21:36 +0200 Subject: design question In-Reply-To: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> References: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> Message-ID: * Tim Arnold: > This is a question about system design I guess. I have a django > website that allows users to change/view configuration details for > documentation builds. The database is very small. The reason I'm using > a database in the first place is to make it easy for users to change > the configuration of their builds. Django makes that easy and I can go > on to other problems, like actually building the documentation. > > During a build, I query the configuration database at different times > to get the configuration I need, which results in several calls to the > database at different points of the build process. > > It doesn't feel right that I'm making these calls at different times. > I *could* make a single big call at the beginning of the build, > basically serializing all the config data I could need into a > dictionary or maybe a json structure. And just pass that structure > around as needed during the build, with no more database calls needed. > > These builds take from a few minutes to an hour or so, with the time > spent making db calls almost insignificant. So if time isn't a > problem, am I wringing my hands over something that really doesn't > matter much? I guess it just doesn't feel like the right thing to me. Re efficiency it seems to be a complete non-issue, but correctness is much more important: is there any way that the config details can be (inadvertently) changed while the build is going on? If so then it might be a good idea to read all relevant info up front (holding a lock for hours seems ungood to me). Cheers & hth., - Alf From ben+python at benfinney.id.au Mon May 3 21:12:49 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 04 May 2010 11:12:49 +1000 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> Message-ID: <87d3xch3la.fsf@benfinney.id.au> Baz Walter writes: > On 03/05/10 18:41, Grant Edwards wrote: > > Firstly, a file may have any number of paths (including 0). > > yes, of course. i forgot about hard links Rather, you forgot that *every* entry that references a file is a hard link. To ask for a filesystem entry referencing the file contents *is* to ask for a hard link; and there can be zero or more of those. The case where there is exactly one of those for a given file is the special case, and should not be assumed. -- \ ?[Freedom of speech] isn't something somebody else gives you. | `\ That's something you give to yourself.? ?_Hocus Pocus_, Kurt | _o__) Vonnegut | Ben Finney From kalin at el.net Mon May 3 21:16:48 2010 From: kalin at el.net (kalin m) Date: Mon, 03 May 2010 21:16:48 -0400 Subject: msg_footer In-Reply-To: <4BDF61E7.2030808@el.net> References: <4BDF61E7.2030808@el.net> Message-ID: <4BDF7580.5060009@el.net> nevermind... i found it... kalin m wrote: > > is there a variable for the member's email address in the msg_footer? > the one the message is being sent to? > > thanks.... From cs at zip.com.au Mon May 3 21:36:58 2010 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 4 May 2010 11:36:58 +1000 Subject: strange interaction between open and cwd In-Reply-To: <4BDEDC73.1020301@ftml.net> References: <4BDEDC73.1020301@ftml.net> Message-ID: <20100504013658.GA25409@cskk.homeip.net> On 03May2010 15:23, Baz Walter wrote: | On 03/05/10 14:46, Peter Otten wrote: | >Baz Walter wrote: | > | >>attempting to remove the cwd would produce an error). but how can python | >>determine the parent directory of a directory that no longer exists? | > | >My tentative explanation would be that the directory, namely the inode, | >still exists -- only the entry for it in its parent directory is gone. | > | >So "one level up from here" is still a valid operation, but there is no | >longer a path in the file system associated with "here". | | so "here" must always be available somehow, even if getcwd() fails Well, yeah. Just like an open file handle on a file you have subsequently removed still exists. Remember that the directory tree is a digraph, and (historically at least, and probably for real in many filesystems) '.' and '..' are just pointers to "here" and "up". Your rmdir has detached the current directory from the one that was "up", but the "up" pointer still references the old parent. There's just no filesystem path that refers to your current directory any more (except '.'). Just like a detached object in python really. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Everything that can be invented has been invented. - Charles H. Duell, Commissioner, U.S. Office of Patents, 1899. From invalid at invalid.invalid Mon May 3 22:19:04 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 4 May 2010 02:19:04 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: > On 03/05/10 19:12, Grant Edwards wrote: >>> i think they should always either both succeed, or both fail. >> >> That's not how Unix filesystems work. >> >> Are you saying that Python should add code to it's open() builtin >> which calls realpath() and then refuses to open files for which >> realpath() fails? > > my original question was really about *how* python does the > "seemingly impossible". i had hoped there might be a way to augment > realpath so that it would always work for any path which is openable. > but apparently that is not possible for unix filesystems. Exactly >> Even though the user provided a legal and openable path? > > that sounds like an operational definition to me: what's the > difference between "legal" and "openable"? Legal as in meets the syntactic requirements for a path (not sure if there really are any requirements other than it being a null-terminated string). Openable meaning that it denotes a path file that exists and for which the caller has read permissions on the file and execute premissions on the directories within the path. -- Grant From invalid at invalid.invalid Mon May 3 22:25:54 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 4 May 2010 02:25:54 +0000 (UTC) Subject: [OT] strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> Message-ID: On 2010-05-04, Charles wrote: >> I don't see how it's inelegant at all. Perhaps it's >> counter-intuitive if you don't understand how a Unix filesystem >> works, but the underlying filesystem model is very simple, regular, >> and elegant. >> >>> but probably makes some bit of the OS's job slightly easier and is >>> usually good enough in practice. Pragmatism is a bitch sometimes. :-) >> > > I agree that the Unix file system is quite elegant, but can be > counter-intuitive for people who are used to the "one file, one name" > paradigm. I guess I've been using Unix for too long (almost 30 years). I don't think I was consciously aware of a "one file, one name" paradigm. Is that a characteristic of Dos, Windows or Mac filesystems? > [...] > In the OP's case, references to the directory have been removed from > the file system, but his process still has the current working > directory reference to it, so it has not actually been deleted. When > he opens "../abc.txt", the OS searches the current directory for ".." > and finds the inode for /home/baz/tmp, then searches that directory > (/home/baz/tmp) for abc.txt and finds it. Exactly. I probably should have taken the time to explain that as well as you did. One forgets that there are a log of new Unix users who've never been taught how the filesystem works. -- Grant From invalid at invalid.invalid Mon May 3 22:36:47 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 4 May 2010 02:36:47 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEDC73.1020301@ftml.net> Message-ID: On 2010-05-04, Cameron Simpson wrote: > On 03May2010 15:23, Baz Walter wrote: >| so "here" must always be available somehow, even if getcwd() fails > > Well, yeah. Just like an open file handle on a file you have > subsequently removed still exists. Remember that the directory tree > is a digraph, and (historically at least, and probably for real in > many filesystems) '.' and '..' are just pointers to "here" and "up". > > Your rmdir has detached the current directory from the one that was > "up", but the "up" pointer still references the old parent. > > There's just no filesystem path that refers to your current directory > any more (except '.'). Just like a detached object in python really. Indeed. In fact, CPython uses a pointer/link and reference counting scheme that's pretty much identical to that used by Unix filesystems except that Python objects can form a generalized graph, and Unix filesystems are constrained to be a tree. Though once upon a time SunOS allowed you to create arbitrary graphs within a filesystem by allowing you to create hard links to directories. You had to be root, and you had to use some sort of override option on the command line (probably -f). If you knew enough to gracefully extract yourself from the situation, you probably wouldn't have done it in the first place. IOW, it wasn't something one did a second time. Still, at the time, it _seemed_ like a good way to share a directory of source code amongst multiple projects. I don't remember why symlinks wouldn't accomplish the task -- something to do with RCS... -- Grant From mwilson at the-wire.com Mon May 3 23:34:21 2010 From: mwilson at the-wire.com (Mel) Date: Mon, 03 May 2010 23:34:21 -0400 Subject: [OT] strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> Message-ID: Grant Edwards wrote: > I guess I've been using Unix for too long (almost 30 years). I don't > think I was consciously aware of a "one file, one name" paradigm. Is > that a characteristic of Dos, Windows or Mac filesystems? Older and simpler filesystems used to combine the naming with the space allocation. CP/M, and (IIRC) the GE/Honeywell mainframe systems I used to work with. MS-DOS FAT filesystems might have supported multi-names but refused to administer them before long filenames were implemented as special cases. I first ran into multi-names on Multics, where the Volume Table of Contents controlled disk space allocation and directories provided name- keyed access to the VTOC entries. Pretty much as Linux does now with directories and inodes. Mel. From cmpython at gmail.com Tue May 4 00:03:32 2010 From: cmpython at gmail.com (CM) Date: Mon, 3 May 2010 21:03:32 -0700 (PDT) Subject: Teaching Programming References: Message-ID: > Nobody likes indentation at first, it is different. ? For what it's worth, I didn't have a programming background, and I liked Python's indentation right from the start. I was used to thinking in terms of indentation from writing and word processing documents with subordinate sections, so I found it very natural (and already had a well-developed tab finger). On the other hand, curly braces always have struck me as visual "clutter". From nagle at animats.com Tue May 4 00:12:19 2010 From: nagle at animats.com (John Nagle) Date: Mon, 03 May 2010 21:12:19 -0700 Subject: HTTP server + SQLite? In-Reply-To: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Message-ID: <4bdf993e$0$1669$742ec2ed@news.sonic.net> Gilles Ganault wrote: > Hello > > I'd like to build a prototype that will combine a web server as > front-end (it must support GZIPping data to the remote client when > there are a lot of data to return), and SQLite as back-end, call the > server from a VB.Net application, and see how well this works. I want > to see if performance is significantly lower than using a server that > uses a binary protocol. > > I'm no Python expert, so would appreciate any information on how to > combine a web server and SQLite into a single Python application. This > is just for a proof-of-concept, so it doesn't need to be > shipping-quality. > > Thank you for any hint. There's no reason you can't do that. Whether you want to is another issue. There are, after all, plenty of web servers out there. Also, SQLite really is a "lite" database. Although there's good read concurrency, multiple updates from multiple processes tend to result in sizable delays, since the locking is via file locks and wait/retry logic. John Nagle From robin1 at cnsp.com Tue May 4 01:00:08 2010 From: robin1 at cnsp.com (Robin) Date: Mon, 3 May 2010 22:00:08 -0700 (PDT) Subject: repeat tkinter Message-ID: <8739b635-18c6-40e6-82ac-7b0ca673774b@o11g2000yqj.googlegroups.com> How can I make a command within a tkinter application repeat itself over and over in intervals of a certain time. Thanks, -Robin From fred at bsdhost.net Tue May 4 01:01:49 2010 From: fred at bsdhost.net (Fred C) Date: Mon, 3 May 2010 22:01:49 -0700 Subject: print executed query In-Reply-To: <8E05B556-DB67-4B4C-B4B4-C34E12BE6E35@semanchuk.com> References: <9b2a7e6f-003d-474a-968f-0cdcede9ce5c@k41g2000yqb.googlegroups.com> <8E05B556-DB67-4B4C-B4B4-C34E12BE6E35@semanchuk.com> Message-ID: On Apr 29, 2010, at 9:49 AM, Philip Semanchuk wrote: > > On Apr 29, 2010, at 12:01 PM, someone wrote: > >> Hello! >> >> Is there a way to print a query for logging purpose as it was or will >> be sent to database, if I don't escape values of query by myself? >> >> cursor.execute(query, [id, somestring]) >> >> I could print query and values separate, but it would be great, if I >> could see how query is constructed and can the also copy it and >> execute in console. >> >> Im using psycopg2, btw > > > If you can fiddle with the Postgres server settings, the server has options for logging lots of things, including the queries it executes. > > > Hope this helps > Philip > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3676 bytes Desc: not available URL: From rickhg12hs at gmail.com Tue May 4 01:02:45 2010 From: rickhg12hs at gmail.com (rickhg12hs) Date: Mon, 3 May 2010 22:02:45 -0700 (PDT) Subject: Recursive functions not returning lists as expected Message-ID: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Would a kind soul explain something basic to a python noob? Why doesn't this function always return a list? def recur_trace(x,y): print x,y if not x: return y recur_trace(x[1:], y + [x[0]]) Here are a couple sample runs. >>> print(recur_trace([],[1,2,3])) [] [1,2,3] [1,2,3] So that worked okay and returned the list [1,2,3]. >>> print(recur_trace([9,8],[1,2,3])) [9,8] [1,2,3] [8] [1,2,3,9] [] [1,2,3,9,8] None No list is returned here. Why? [Using Python 2.6.2] From fred at bsdhost.net Tue May 4 01:02:47 2010 From: fred at bsdhost.net (Fred C) Date: Mon, 3 May 2010 22:02:47 -0700 Subject: print executed query In-Reply-To: <8E05B556-DB67-4B4C-B4B4-C34E12BE6E35@semanchuk.com> References: <9b2a7e6f-003d-474a-968f-0cdcede9ce5c@k41g2000yqb.googlegroups.com> <8E05B556-DB67-4B4C-B4B4-C34E12BE6E35@semanchuk.com> Message-ID: <5B1BDBA5-CB8B-4238-ADB4-506914DEB706@bsdhost.net> On Apr 29, 2010, at 9:49 AM, Philip Semanchuk wrote: > > On Apr 29, 2010, at 12:01 PM, someone wrote: > >> Hello! >> >> Is there a way to print a query for logging purpose as it was or will >> be sent to database, if I don't escape values of query by myself? >> >> cursor.execute(query, [id, somestring]) >> >> I could print query and values separate, but it would be great, if I >> could see how query is constructed and can the also copy it and >> execute in console. >> >> Im using psycopg2, btw > > > If you can fiddle with the Postgres server settings, the server has options for logging lots of things, including the queries it executes. > Yes you can fiddle like that: >>> cur.mogrify("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar')) "INSERT INTO test (num, data) VALUES (42, E'bar')" -fred- -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3676 bytes Desc: not available URL: From ideamonk at gmail.com Tue May 4 01:30:34 2010 From: ideamonk at gmail.com (Abhishek Mishra) Date: Tue, 4 May 2010 11:00:34 +0530 Subject: Recursive functions not returning lists as expected In-Reply-To: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: Perhaps you forgot a return, thats fundamental to recursion right - funciton returning itself to itself :) Here's a bit modification needed - def recur_trace(x,y): print x,y if not x: return y return recur_trace(x[1:], y + x[:1]) print ( recur_trace([],[1,2,3]) ) print print ( recur_trace([9,8],[1,2,3]) ) print print ( recur_trace([0],[1,2,3]) ) $ python poo.py [] [1, 2, 3] [1, 2, 3] [9, 8] [1, 2, 3] [8] [1, 2, 3, 9] [] [1, 2, 3, 9, 8] [1, 2, 3, 9, 8] [0] [1, 2, 3] [] [1, 2, 3, 0] [1, 2, 3, 0] On Tue, May 4, 2010 at 10:32 AM, rickhg12hs wrote: > Would a kind soul explain something basic to a python noob? > > Why doesn't this function always return a list? > > def recur_trace(x,y): > print x,y > if not x: > return y > recur_trace(x[1:], y + [x[0]]) > > Here are a couple sample runs. > > >>> print(recur_trace([],[1,2,3])) > [] [1,2,3] > [1,2,3] > > So that worked okay and returned the list [1,2,3]. > > >>> print(recur_trace([9,8],[1,2,3])) > [9,8] [1,2,3] > [8] [1,2,3,9] > [] [1,2,3,9,8] > None > > No list is returned here. Why? > [Using Python 2.6.2] > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From C.Sanders at DeleteThis.Bom.GOV.AU Tue May 4 01:32:18 2010 From: C.Sanders at DeleteThis.Bom.GOV.AU (Charles) Date: Tue, 4 May 2010 15:32:18 +1000 Subject: Recursive functions not returning lists as expected References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: <4bdfb164$0$45290$c30e37c6@exi-reader.telstra.net> "rickhg12hs" wrote in message news:2ff16113-4f79-4dcf-8310-35d2b91e89dc at o11g2000yqj.googlegroups.com... > Would a kind soul explain something basic to a python noob? > > Why doesn't this function always return a list? > > def recur_trace(x,y): > print x,y > if not x: > return y > recur_trace(x[1:], y + [x[0]]) > shouldn't it be return recur_trace(x[1:], y + [x[0]]) otherwise the recursive call returns nothing Charles From cs at zip.com.au Tue May 4 01:34:12 2010 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 4 May 2010 15:34:12 +1000 Subject: Recursive functions not returning lists as expected In-Reply-To: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: <20100504053412.GA27108@cskk.homeip.net> On 03May2010 22:02, rickhg12hs wrote: | Would a kind soul explain something basic to a python noob? | | Why doesn't this function always return a list? | | def recur_trace(x,y): | print x,y | if not x: | return y | recur_trace(x[1:], y + [x[0]]) You need: return recur_trace(x[1:], y + [x[0]]) Otherwise the function returns None. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ [...] every time you touch something, if your security systems rely on biometric ID, then you're essentially leaving your pin number on a post-it note. - Ben Goldacre, http://www.badscience.net//?p=585 From rickhg12hs at gmail.com Tue May 4 01:45:16 2010 From: rickhg12hs at gmail.com (rickhg12hs) Date: Mon, 3 May 2010 22:45:16 -0700 (PDT) Subject: Recursive functions not returning lists as expected References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: On May 4, 1:34?am, Cameron Simpson wrote: > On 03May2010 22:02, rickhg12hs wrote: > | Would a kind soul explain something basic to a python noob? > | > | Why doesn't this function always return a list? > | > | def recur_trace(x,y): > | ? print x,y > | ? if not x: > | ? ? return y > | ? recur_trace(x[1:], y + [x[0]]) > > You need: > ? ? return recur_trace(x[1:], y + [x[0]]) > > Otherwise the function returns None. Ah, an explicit "return" is required. Thanks! [To bad there's no tail recursion optimization.] 8-( From stefan_ml at behnel.de Tue May 4 01:51:07 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 07:51:07 +0200 Subject: new extension generator for C++ In-Reply-To: References: Message-ID: Rouslan Korneychuk, 03.05.2010 22:44: > So I looked for other solutions and noticed that Py++ (which simply > generates Boost.Python code for you) was based on a seperate program > called GCCXML. I figured I could use GCCXML and generate code however I > wanted. So I did. > > My program generates human-readable code (it even uses proper > indentation). The program still has a lot of work to be done on it, but > it can already generate working Python extensions. Last I heard, that was basically what PyBindGen does (and probably some other existing binding generators). You should take a look at them before investing too much time into a duplicated effort. Also, if you're interested in performance, you should take a look at Cython, which is an optimising compiler for (basically) Python code that can talk to C, C++ and Fortran code. It's been used a lot for writing performance critical library wrappers. Stefan From michele.simionato at gmail.com Tue May 4 01:57:07 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 3 May 2010 22:57:07 -0700 (PDT) Subject: Sphinx hosting Message-ID: Say you have a project with a lot of documentation in the form of Sphinx pages (for instance a book project). What is the the easiest way to publish it on the Web? I see that GitHub Pages allows you to publish static pages, but I would need to check in both the .rst sources and the .html output: it is not that annoying, but perhaps there is already some services out there publishing Sphinx pages directly. Do you know of any? Currently I am hosting my stuff on Google Code but I do not see an easy way to publish the documentation there. Any hint is appreciated. Michele Simionato From kse.listed.co1 at gmail.com Tue May 4 02:02:42 2010 From: kse.listed.co1 at gmail.com (Naeem) Date: Mon, 3 May 2010 23:02:42 -0700 (PDT) Subject: "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ Message-ID: <2b150fa6-3a2b-4693-b54f-80429166a25e@o14g2000yqb.googlegroups.com> "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments From paul.nospam at rudin.co.uk Tue May 4 02:04:24 2010 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Tue, 04 May 2010 07:04:24 +0100 Subject: Recursive functions not returning lists as expected References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: <874oio19uf.fsf@rudin.co.uk> rickhg12hs writes: > Would a kind soul explain something basic to a python noob? > > Why doesn't this function always return a list? > > def recur_trace(x,y): > print x,y > if not x: > return y > recur_trace(x[1:], y + [x[0]]) > > Here are a couple sample runs. > >>>> print(recur_trace([],[1,2,3])) > [] [1,2,3] > [1,2,3] > > So that worked okay and returned the list [1,2,3]. > >>>> print(recur_trace([9,8],[1,2,3])) > [9,8] [1,2,3] > [8] [1,2,3,9] > [] [1,2,3,9,8] > None > > No list is returned here. Why? > [Using Python 2.6.2] Without trying it out I'd guess you want a "return" in your last line. (If python falls out of a function without hitting an explicit return then None is returned by default.) From bryanjugglercryptographer at yahoo.com Tue May 4 02:07:08 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Mon, 3 May 2010 23:07:08 -0700 (PDT) Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> <4bdf993e$0$1669$742ec2ed@news.sonic.net> Message-ID: <11247616-b5da-4494-bf83-1d7416c8dbef@g5g2000pre.googlegroups.com> John Nagle wrote: > [...] SQLite really > is a "lite" database. ?Although there's good read concurrency, multiple > updates from multiple processes tend to result in sizable delays, since > the locking is via file locks and wait/retry logic. True, and I have other gripes about SQLite, but I've fallen in love with it. SQLite rocks. SQLite rocks like Python rocks. Hard as Python had rocked before, Python started rockin' a whole bunch harder when 2.5 included SQLite3 in the standard library. I love SQLite because it solves problems I actually have. For the vast majority of code I write, "lite" is a good thing, and lite as it is, SQLite can handle several transactions per second. I give SQLite a file path and in a split second I have a relational, transactional database. Great. I did not want to configure a server and I sure did not want to inflict complexity upon my users. If you are smart and/or lucky enough to write a web app so popular that it outgrows SQLite, you can switch over to a big-time SQL server DBMS. At worst, you'll have to tweak some of the code. Imagine how much harder the scaling problem would be if the persistent data were stored via pickle. The SQLite developers state the situation brilliantly at http://www.sqlite.org/whentouse.html: "SQLite is not designed to replace Oracle. It is designed to replace fopen()." -- --Bryan From martin at v.loewis.de Tue May 4 02:07:48 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 04 May 2010 08:07:48 +0200 Subject: Sphinx hosting In-Reply-To: References: Message-ID: <4BDFB9B4.1040400@v.loewis.de> Michele Simionato wrote: > Say you have a project with a lot of documentation in the form of > Sphinx pages (for instance a book project). What is the the easiest > way to publish it on the Web? I see that GitHub Pages allows you to > publish static pages, but I would need to check in both the .rst > sources and the .html output: it is not that annoying, but perhaps > there is already some services out there publishing Sphinx pages > directly. Do you know of any? Currently I am hosting my stuff on > Google Code but I do not see an easy way to publish the documentation > there. Any hint is appreciated. If it's a Python package that this documentation is about, you can host it on PyPI. Regards, Martin From michele.simionato at gmail.com Tue May 4 02:19:12 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 3 May 2010 23:19:12 -0700 (PDT) Subject: Sphinx hosting References: <4BDFB9B4.1040400@v.loewis.de> Message-ID: <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> On May 4, 8:07?am, "Martin v. Loewis" wrote: > If it's a Python package that this documentation is about, you can host > it on PyPI. It must not be Python, but let's consider this case first. How does it work? When I published my decorator module (http://pypi.python.org/pypi/decorator) the support was not very good. At the end I decided to put the generated .html inside the long_description field instead of the .rst source to get the look and feel I wanted. Moreover the long_description hack works for a single page documentation, but I am talking here of a book-sized document with many pages and hyperlinks. Do you know of recent improvements on the PyPI side about docs hosting? The CheeseShopTutorial http://wiki.python.org/moin/CheeseShopTutorial seems to give the same info of the last time I checked. From rony.masc at gmail.com Tue May 4 02:21:23 2010 From: rony.masc at gmail.com (Rony Mascreen) Date: Mon, 3 May 2010 23:21:23 -0700 (PDT) Subject: Rockin phone u r rit Message-ID: I wasnt intend to buy any of the samsung phones. but i was fascinated of its new corby series and buy this phone. really amazing phone with lots social networking programs. i have written more on http://hubpages.com/hub/Samsung-Corby-TxT-B3210 This phone is worth to buy. From rony.masc at gmail.com Tue May 4 02:21:45 2010 From: rony.masc at gmail.com (Rony Mascreen) Date: Mon, 3 May 2010 23:21:45 -0700 (PDT) Subject: Buy Samsung Corby TXT B3210 Mobile References: <6606ee63-9e0d-4a5d-97eb-4b88133345c7@30g2000yqi.googlegroups.com> Message-ID: <0647c288-17b2-45c6-a566-3af18dc16e9b@z13g2000prh.googlegroups.com> On Apr 12, 3:05?pm, "mohanti.si... at yahoo.in" wrote: > Samsung Corby TXT is a GSM phone. Samsung Corby TXT, a SmartPhone > mobile comes with a great list of features. > > ?Samsung Corby TXT B3210 is a mobile with a user memory of 38 MB and > MicroSD support up to 8 GB of external memory. This simple statement > of specifications is sufficient for mobile buffs to gauge the power of > Samsung Corby TXT B3210. > > The Samsung Corby TxT is approximately priced at Rs 7,000 in India. > > Samsung Corby Txt Specification > ? Network: GSM, Band 850/900/1800/1900 > ? Dimension: 59?110x12.9 > ? Display: TFT LCD 2.2 inch > ? Battery: 800mAh > ? Talk Time: up to 10 hrs > ? Standby: up to 316H > ? Camera: 2MP, 2x digital zoom > ? Video player > ? Video recording > ? Video messaging > ? Video streaming > ? Music Player > ? MP3 Ringtones > ? 3D sound technology ? Music Recognition > ? FM Radio > ? Bluetooth > ? WAP > ? USB > ? PC Sync Application > ? User Memory: 38 MB > ? SMS Memory: 500 > ? Phone Book Entries upto 1000 > ? External Memory: Upto MicroSD(Upto 8GB) > ? Speakerphone > For more information:http://www.khojle.in/classifieds/mobile/ I wasnt intend to buy any of the samsung phones. but i was fascinated of its new corby series and buy this phone. really amazing phone with lots social networking programs. i have written more on http://hubpages.com/hub/Samsung-Corby-TxT-B3210 This phone is worth to buy. From martin at v.loewis.de Tue May 4 02:37:32 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 04 May 2010 08:37:32 +0200 Subject: Sphinx hosting In-Reply-To: <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> Message-ID: <4BDFC0AC.40609@v.loewis.de> > Do you know of recent improvements on the PyPI side about docs > hosting? Yes; go to your package's pkg_edit page, i.e. http://pypi.python.org/pypi?%3Aaction=pkg_edit&name=decorator and provide a zip file at Upload Documentation. Regards, Martin From __peter__ at web.de Tue May 4 02:45:57 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 May 2010 08:45:57 +0200 Subject: repeat tkinter References: <8739b635-18c6-40e6-82ac-7b0ca673774b@o11g2000yqj.googlegroups.com> Message-ID: Robin wrote: > How can I make a command within a tkinter application repeat itself > over and over in intervals of a certain time. >>> import Tkinter as tk >>> root = tk.Tk() >>> color = "blue" >>> def switch_color(): ... global color ... if color == "blue": ... color = "red" ... else: ... color = "blue" ... root["background"] = color ... root.after(500, switch_color) ... >>> switch_color() From Ron.Barak at lsi.com Tue May 4 03:01:35 2010 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 4 May 2010 08:01:35 +0100 Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> Hi, I'm parsing XML files using ElementTree from xml.etree (see code below (and attached xml_parse_example.py)). However, I'm coming across input XML files (attached an example: tmp.xml) which include invalid characters, that produce the following traceback: $ python xml_parse_example.py Traceback (most recent call last): File "xml_parse_example.py", line 63, in tree = xml2dict.open_and_parse_xml_file() File "xml_parse_example.py", line 14, in open_and_parse_xml_file tree = ElementTree.parse(f) File "c:\Python26\lib\xml\etree\ElementTree.py", line 862, in parse tree.parse(source, parser) File "c:\Python26\lib\xml\etree\ElementTree.py", line 586, in parse parser.feed(data) File "c:\Python26\lib\xml\etree\ElementTree.py", line 1245, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 6, column 34 I read the documentation for xml.etree.ElementTree and see that it may take an optional parser parameter, but I don't know what this parser should be - to ignore the invalid characters. Could you suggest a way to call ElementTree, so it won't bomb on these invalid characters ? Thanks, Ron. ________________________________ #!/usr/bin/env python from xml.etree import ElementTree import pprint compute_tail = False class XmlFileToDict(): def __init__(self, xml_file_path): self.xml_file_path = xml_file_path def open_and_parse_xml_file(self): with open(self.xml_file_path, 'rt') as f: tree = ElementTree.parse(f) return tree def dict_list(self, node): res = {} res[node.tag] = [] self.xml_to_dict(node,res[node.tag]) reply = {} if compute_tail: reply[node.tag] = {'value':res[node.tag],'attribs':node.attrib,'tail':node.tail} else: reply[node.tag] = {'value':res[node.tag],'attribs':node.attrib} return reply def xml_to_dict(self, node, res): rep = {} if len(node): #n = 0 for n in list(node): rep[node.tag] = [] value = self.xml_to_dict(n,rep[node.tag]) if len(n): if compute_tail: value = {'value':rep[node.tag],'attributes':n.attrib,'tail':n.tail} else: value = {'value':rep[node.tag],'attributes':n.attrib} res.append({n.tag:value}) else : res.append(rep[node.tag][0]) else: value = {} if compute_tail: value = {'value':node.text,'attributes':node.attrib,'tail':node.tail} else: value = {'value':node.text,'attributes':node.attrib} res.append({node.tag:value}) return if __name__ == '__main__' : xml_file_path ='tmp.xml' xml2dict = XmlFileToDict(xml_file_path) tree = xml2dict.open_and_parse_xml_file() xml_dict = xml2dict.dict_list(tree.getroot()) pprint.pprint(xml_dict) ________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: tmp.xml Type: application/xml Size: 637 bytes Desc: tmp.xml URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: xml_parse_example.py Type: application/octet-stream Size: 2294 bytes Desc: xml_parse_example.py URL: From stefan_ml at behnel.de Tue May 4 03:01:40 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 09:01:40 +0200 Subject: new extension generator for C++ In-Reply-To: References: Message-ID: Rouslan Korneychuk, 03.05.2010 22:44: > The only issue is > it will not use keyword arguments for overloaded functions (I don't know > if that can even be done reliably *and* efficiently. I would need to > give it more thought). You should look at the argument unpacking code that Cython generates. It has been subject to serious benchmarking and optimisations. Stefan From space.ship.traveller at gmail.com Tue May 4 03:06:17 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 4 May 2010 19:06:17 +1200 Subject: new extension generator for C++ In-Reply-To: References: Message-ID: <9F9978CE-B1DD-4BBF-AEAF-25B8515E4932@gmail.com> Dear Rouslan, It looks interesting. I say go for it. You will learn something and might make some improvements on existing ideas. I recommend putting the code on www.github.com Kind regards, Samuel On 4/05/2010, at 8:44 AM, Rouslan Korneychuk wrote: > Hi, I'm new here. I'm working on a program that exposes C++ declarations to Python and I was wondering if there is any interest in it. > > It's a hobby project. I was originally using Boost.Python on another project but found a couple of things I didn't like. Eg: you can't really have private constructors. If you want a Python object created, you either have to expose the constructor in Python, or create an instance of the object somewhere else in memory, and have it either copied to the PyObject or have the PyObject hold a reference to it. I was working on a rudimentary 3D game engine that was a Python extension. It was important to avoid copying potentially huge amounts of data, but to have almost every PyObject just be a pointer to another object (and the object already is just a few or even one pointer) seemed like an pointless compromise, considering that I was writing code that was specifically designed to be a Python extension (There was also another issue I came across but don't remember now). > > So I looked for other solutions and noticed that Py++ (which simply generates Boost.Python code for you) was based on a seperate program called GCCXML. I figured I could use GCCXML and generate code however I wanted. So I did. > > My program generates human-readable code (it even uses proper indentation). The program still has a lot of work to be done on it, but it can already generate working Python extensions. > > It takes an input file like this: > > > module doc string > > > class doc string > > > > > > > > You can probably figure out what the resulting code does. The goal is to generate code that is as close to hand-written code as possible. It even forgoes using PyArg_ParseTupleAndKeywords and has the argument checks hard-wired. It also generates a header file that contains a PyObject implementation of MyClass called obj_AClass, with every constructor fowarded and with the new and delete operators overloaded to play nice with Python's memory handler: > ... > extern PyTypeObject obj_AClassType; > > struct obj_AClass { > PyObject_HEAD > MyClass base; > bool initialized; > > void *operator new(size_t s) { > void *ptr = PyMem_Malloc(s); > if(!ptr) throw std::bad_alloc(); > return ptr; > } > > void operator delete(void *ptr) { > PyMem_Free(ptr); > } > > obj_AClass(MyClass const & _0) : base(_0) { > PyObject_Init(reinterpret_cast(this),&obj_AClassType); > initialized = true; > } > > obj_AClass(unsigned int _0) : base(_0) { > PyObject_Init(reinterpret_cast(this),&obj_AClassType); > initialized = true; > } > > }; > ... > > If you want to expose one overload of a constructor or function but not the others, you can add overload="list,of,args" to or . Default values for arguments are handled automatically. When handling overloaded functions, it checks the types of the arguments to pick the best overload, taking into consideration polymorphism and the fact that basic types like ints can be converted from one-another. It will automatically detect if two overloads match to the same set of Python arguments (eg: void func(float) vs void func(double)). The only issue is it will not use keyword arguments for overloaded functions (I don't know if that can even be done reliably *and* efficiently. I would need to give it more thought). > > If there is enough interest I can put this project up on SourceForge or Google Code. > -- > http://mail.python.org/mailman/listinfo/python-list From r1chardj0n3s at gmail.com Tue May 4 03:07:21 2010 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Tue, 4 May 2010 17:07:21 +1000 Subject: Next Melbourne PUG meeting 6:30pm Monday 10th of May @ Horse Bazaar Message-ID: Meeting details, location and talks list are at: http://wiki.python.org/moin/MelbournePUG It looks like we've got a few cool talks lined up: 15 minute talks - None yet... suggest one! 5 minute talks - Load-balancing xmlrpclib/jsonrpclib for robust distributed applications (Andreux Fort) ... please feel free to suggest a topic - anything cool you've discovered lately. And I'm sure there'll be some talk about PyCon Australia as well! Richard From stefan_ml at behnel.de Tue May 4 03:23:56 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 09:23:56 +0200 Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> Message-ID: Barak, Ron, 04.05.2010 09:01: > I'm parsing XML files using ElementTree from xml.etree (see code below > (and attached xml_parse_example.py)). > > However, I'm coming across input XML files (attached an example: > tmp.xml) which include invalid characters, that produce the following > traceback: > > $ python xml_parse_example.py > Traceback (most recent call last): > xml.parsers.expat.ExpatError: not well-formed (invalid token): line 6, column 34 I hope you are aware that this means that the input you are parsing is not XML. It's best to reject the file and tell the producers that they are writing broken output files. You should always fix the source, instead of trying to make sense out of broken input in fragile ways. > I read the documentation for xml.etree.ElementTree and see that it may > take an optional parser parameter, but I don't know what this parser > should be - to ignore the invalid characters. > > Could you suggest a way to call ElementTree, so it won't bomb on these > invalid characters ? No. The parser in lxml.etree has a 'recover' option that lets it try to recover from input errors, but in general, XML parsers are required to reject non well-formed input. Stefan From michele.simionato at gmail.com Tue May 4 03:27:30 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 4 May 2010 00:27:30 -0700 (PDT) Subject: Sphinx hosting References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> Message-ID: <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> On May 4, 8:37?am, "Martin v. Loewis" wrote: > > Do you know of recent improvements on the PyPI side about docs > > hosting? > > Yes; go to your package's pkg_edit page, i.e. > > http://pypi.python.org/pypi?%3Aaction=pkg_edit&name=decorator > > and provide a zip file at Upload Documentation. > > Regards, > Martin Cool, that's good to know. I am still accepting recommendations for non-Python projects ;) From bruno.42.desthuilliers at websiteburo.invalid Tue May 4 03:37:03 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 04 May 2010 09:37:03 +0200 Subject: Django as exemplary design In-Reply-To: <2010050312243328275-tomfsessile@gmailcom> References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <4bdfce42$0$9110$426a34cc@news.free.fr> TomF a ?crit : > I'm interested in improving my python design by studying a large, > well-designed codebase. Someone (not a python programmer) suggested > Django. I realize that Django is popular, but can someone comment on > whether its code is well-designed and worth studying? > Carl makes some valid points in his answer, and there are indeed a couple dark corners in this area - bit it's just a part of the whole framework. There are still things worth studying in Django IHMO, specially if you're interested in seeing metaclasses and descriptors at work. From bruno.42.desthuilliers at websiteburo.invalid Tue May 4 03:39:03 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 04 May 2010 09:39:03 +0200 Subject: design question In-Reply-To: References: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> Message-ID: <4bdfceba$0$9110$426a34cc@news.free.fr> Alf P. Steinbach a ?crit : (snip) > Re efficiency it seems to be a complete non-issue, but correctness is > much more important: is there any way that the config details can be > (inadvertently) changed while the build is going on? +1 From prologic at shortcircuit.net.au Tue May 4 03:48:22 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 4 May 2010 17:48:22 +1000 Subject: Sphinx hosting In-Reply-To: <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> Message-ID: On Tue, May 4, 2010 at 5:27 PM, Michele Simionato wrote: > Cool, that's good to know. I am still accepting recommendations for > non-Python projects ;) bitbucket (1) also provide static file hosting through the wiki. From what I understand (tested) you simply clone the wiki repository (which is it's own repository) and commit a bunch of .html files. cheers James 1. http://bitbucket.org/ From greg.ewing at canterbury.ac.nz Tue May 4 03:56:13 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 May 2010 19:56:13 +1200 Subject: [OT] strange interaction between open and cwd In-Reply-To: <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> Message-ID: <84a1mcFfnpU1@mid.individual.net> Charles wrote: > In the OP's case, references to the directory have been removed from the > file > system, but his process still has the current working directory reference to > it, > so it has not actually been deleted. When he opens "../abc.txt", the OS > searches > the current directory for ".." and finds the inode for /home/baz/tmp, This doesn't seem to be quite correct. An experiment I just did reveals that the link count on the parent directory goes down by one when the current directory is deleted, suggesting that the .. link has actually been removed... yet it still works! I think what must be happening is that the kernel is maintaining an in-memory reference to the parent directory, and treating ".." as a special case when looking up a name. (This probably shouldn't be too surprising, because ".." is special in another way as well -- at the root of a mounted file system, it leads to the parent of the mount point, even though the actual ".." link on disk just points back to the same directory. Probably it simplifies the name lookup logic to always treat it specially.) -- Greg From greg.ewing at canterbury.ac.nz Tue May 4 04:08:36 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 May 2010 20:08:36 +1200 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEDC73.1020301@ftml.net> Message-ID: <84a2djFjqrU1@mid.individual.net> Grant Edwards wrote: > except that Python objects can form a generalized graph, and Unix > filesystems are constrained to be a tree. Actually I believe that root is allowed to create arbitrary hard links to directories in Unix, so it's possible to turn the file system in to a general graph. It's highly unrecommended, though, because it confuses the heck out of programs that recursively traverse directories (which is why only root is allowed to do it). -- Greg From ldo at geek-central.gen.new_zealand Tue May 4 04:15:43 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 04 May 2010 20:15:43 +1200 Subject: [PATCH] add functional matrix-returning methods to Pycairo Message-ID: I find the matrix methods in Pycairo to be an annoying hodge-podge of ones that overwrite the Matrix object in-place (init_rotate, invert) versus ones that concatenate additional transformations (rotate, scale, translate) versus ones that return new matrices without modifying the originals (multiply). Myself, I prefer methods that always return new matrices. This allows for a more functional style of programming, e.g. given m = cairo.Matrix() then m2 = m.translation(-10, -10) * m.rotation(math.pi / 4) * m.translation(10, 10) concisely expresses rotation by 90? about the centre (10, 10). Herewith a patch to add such methods to the cairo.Matrix class. Note that the names (inverse, rotation, scaling, translation) are nouns, to reflect the fact that they don't perform the actions, but they return Matrix objects that do. --- src/matrix.c | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 75 insertions(+), 0 deletions(-) diff --git a/src/matrix.c b/src/matrix.c index eefeab9..d1709b9 100644 --- a/src/matrix.c +++ b/src/matrix.c @@ -206,6 +206,76 @@ matrix_translate (PycairoMatrix *o, PyObject *args) { } static PyObject * +matrix_translation(PycairoMatrix *unused, PyObject *args) + { + PyObject * result = NULL; + double tx, ty; + cairo_matrix_t result_matrix; + do /*once*/ + { + if (!PyArg_ParseTuple(args, "dd:Matrix.translation", &tx, &ty)) + break; + cairo_matrix_init_identity(&result_matrix); + cairo_matrix_translate(&result_matrix, tx, ty); + result = PycairoMatrix_FromMatrix(&result_matrix); + } + while (0); + return result; + } /*matrix_translation*/ + +static PyObject * +matrix_scaling(PycairoMatrix *unused, PyObject *args) + { + PyObject * result = NULL; + double sx, sy; + cairo_matrix_t result_matrix; + do /*once*/ + { + if (!PyArg_ParseTuple(args, "dd:Matrix.scaling", &sx, &sy)) + break; + cairo_matrix_init_identity(&result_matrix); + cairo_matrix_scale(&result_matrix, sx, sy); + result = PycairoMatrix_FromMatrix(&result_matrix); + } + while (0); + return result; + } /*matrix_scaling*/ + +static PyObject * +matrix_rotation(PycairoMatrix *unused, PyObject *args) + { + PyObject * result = NULL; + double radians; + cairo_matrix_t result_matrix; + do /*once*/ + { + if (!PyArg_ParseTuple(args, "d:Matrix.rotation", &radians)) + break; + cairo_matrix_init_identity(&result_matrix); + cairo_matrix_rotate(&result_matrix, radians); + result = PycairoMatrix_FromMatrix(&result_matrix); + } + while (0); + return result; + } /*matrix_rotation*/ + +static PyObject * +matrix_inverse(PycairoMatrix *self, PyObject *args_unused) + { + PyObject * result = NULL; + cairo_matrix_t result_matrix; + do /*once*/ + { + result_matrix = self->matrix; + if (Pycairo_Check_Status(cairo_matrix_invert(&result_matrix))) + break; + result = PycairoMatrix_FromMatrix(&result_matrix); + } + while (0); + return result; + } /*matrix_inverse*/ + +static PyObject * matrix_item (PycairoMatrix *o, Py_ssize_t i) { switch (i) { case 0: @@ -297,6 +367,11 @@ static PyMethodDef matrix_methods[] = { {"transform_distance",(PyCFunction)matrix_transform_distance, METH_VARARGS }, {"transform_point", (PyCFunction)matrix_transform_point, METH_VARARGS }, {"translate", (PyCFunction)matrix_translate, METH_VARARGS }, + /* functional methods: */ + {"translation", (PyCFunction)matrix_translation, METH_VARARGS | METH_STATIC }, + {"scaling", (PyCFunction)matrix_scaling, METH_VARARGS | METH_STATIC }, + {"rotation", (PyCFunction)matrix_rotation, METH_VARARGS | METH_STATIC }, + {"inverse", (PyCFunction)matrix_inverse, METH_VARARGS }, {NULL, NULL, 0, NULL}, }; -- 1.7.0 From greg.ewing at canterbury.ac.nz Tue May 4 04:23:50 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 May 2010 20:23:50 +1200 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <84a3a5Fp5nU1@mid.individual.net> Grant Edwards wrote: > In your example, it's simply not possible to determine the file's > absolute path within the filesystem given the relative path you > provided. Actually, I think it *is* theoretically possible to find an absolute path for the file in this case. I suspect that what realpath() is doing for a relative path is something like: 1. Use getcwd() to find an absolute path for the current directory. 2. Chop off a trailing pathname component for each ".." on the front of the original path. 3. Tack the filename on the end of what's left. Step 1 fails because the current directory no longer has an absolute pathname -- specifically, it has no name in what used to be its parent directory. What realpath() is failing to realise is that it doesn't actually need to know the full path of the current directory, only of its parent directory, which is still reachable via ".." (if it weren't, the file wouldn't be reachable either, and we wouldn't be having this discussion). A smarter version of realpath() wouldn't try to find the path of the *current* directory, but would follow the ".." links until it got to a directory that it did need to know an absolute path for, and start with that. Unfortunately, there is no C stdlib routine that does the equivalent of getcwd() for an arbitrary directory, so this would require realpath() to duplicate much of getcwd()'s functionality, which is probably why it's done the way it is. -- Greg From mail at timgolden.me.uk Tue May 4 05:19:31 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 04 May 2010 10:19:31 +0100 Subject: win32 - catch events(wmi?) In-Reply-To: References: <201005031302.31772.richard.lamboj@bilcom.at> <4BDF2BDC.7020805@timgolden.me.uk> Message-ID: <4BDFE6A3.5010002@timgolden.me.uk> On 03/05/2010 23:53, Giampaolo Rodol? wrote: > Just out of curiosity, is WMI able to list the TCP and UDP connections > opened by a process or by the OS? > We'll have to do this for psutil (http://code.google.com/p/psutil) and > we guess it's not gonna be easy. Not as far as I know. WMI doesn't tend to deal with things at a process level. (Altho' I'm always being surprised at just what *is* out there in WMI-land). TJG From jeanmichel at sequans.com Tue May 4 05:22:09 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 04 May 2010 11:22:09 +0200 Subject: Teaching Programming In-Reply-To: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> Message-ID: <4BDFE741.40305@sequans.com> Andr? wrote: > To Samuel Williams: (and other interested ;-) > > If you want to consider Python in education, I would encourage you > have a look at http://www.python.org/community/sigs/current/edu-sig/ > > I think you will find that there are quite a few resources available - > perhaps more than you are aware of. > > And, I don't think that because "some people do not like the > indentation strategy" is a valid reason not to consider that Python's > syntax is concise and simple. Actually, I would almost argue for the > contrary. Indentation indicate programming structure/logic very > clearly, without the need for arbitrary keywords and other punctuation > symbols. There are very few keywords in the language. > > You indicate that Python programs are readable. They are also known > to be short (much shorter than some other languages). > Andr? > Python indentation has been already discussed many times around, I remember someone saying something like "How is it possible not to like indentation while any decent programmer will use it no matter the language, including all those which feature statements/keywords for blocks". JM From space.ship.traveller at gmail.com Tue May 4 05:33:32 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 4 May 2010 21:33:32 +1200 Subject: Teaching Programming In-Reply-To: <4BDFE741.40305@sequans.com> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> Message-ID: I personally like indentation. I just wonder whether it is an issue that some people will dislike. But anyway, I updated the language comparison to remove this critique. Kind regards, Samuel On 4/05/2010, at 9:22 PM, Jean-Michel Pichavant wrote: > Andr? wrote: >> To Samuel Williams: (and other interested ;-) >> >> If you want to consider Python in education, I would encourage you >> have a look at http://www.python.org/community/sigs/current/edu-sig/ >> >> I think you will find that there are quite a few resources available - >> perhaps more than you are aware of. >> >> And, I don't think that because "some people do not like the >> indentation strategy" is a valid reason not to consider that Python's >> syntax is concise and simple. Actually, I would almost argue for the >> contrary. Indentation indicate programming structure/logic very >> clearly, without the need for arbitrary keywords and other punctuation >> symbols. There are very few keywords in the language. >> >> You indicate that Python programs are readable. They are also known >> to be short (much shorter than some other languages). >> Andr? >> > Python indentation has been already discussed many times around, I remember someone saying something like "How is it possible not to like indentation while any decent programmer will use it no matter the language, including all those which feature statements/keywords for blocks". > > JM > -- > http://mail.python.org/mailman/listinfo/python-list From nico.schloemer at gmail.com Tue May 4 06:10:36 2010 From: nico.schloemer at gmail.com (=?ISO-8859-1?Q?Nico_Schl=F6mer?=) Date: Tue, 4 May 2010 12:10:36 +0200 Subject: itertools: problem with nested groupby, list() Message-ID: Hi, I ran into a bit of an unexpected issue here with itertools, and I need to say that I discovered itertools only recently, so maybe my way of approaching the problem is "not what I want to do". Anyway, the problem is the following: I have a list of dictionaries, something like [ { "a": 1, "b": 1, "c": 3 }, { "a": 1, "b": 1, "c": 4 }, ... ] and I'd like to iterate through all items with, e.g., "a":1. What I do is sort and then groupby, my_list.sort( key=operator.itemgetter('a') ) my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) and then just very simply iterate over my_list_grouped, for my_item in my_list_grouped: # do something with my_item[0], my_item[1] Now, inside this loop I'd like to again iterate over all items with the same 'b'-value -- no problem, just do the above inside the loop: for my_item in my_list_grouped: # group by keyword "b" my_list2 = list( my_item[1] ) my_list2.sort( key=operator.itemgetter('b') ) my_list_grouped = itertools.groupby( my_list2, operator.itemgetter('b') ) for e in my_list_grouped: # do something with e[0], e[1] That seems to work all right. Now, the problem occurs when this all is wrapped into an outer loop, such as for k in [ 'first pass', 'second pass' ]: for my_item in my_list_grouped: # bla, the above To be able to iterate more than once through my_list_grouped, I have to convert it into a list first, so outside all loops, I go like my_list.sort( key=operator.itemgetter('a') ) my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) my_list_grouped = list( my_list_grouped ) This, however, makes it impossible to do the inner sort and groupby-operation; you just get the very first element, and that's it. An example file is attached. Hints, anyone? Cheers, Nico -------------- next part -------------- A non-text attachment was scrubbed... Name: iterator-test.py Type: text/x-python Size: 1146 bytes Desc: not available URL: From petshmidt at googlemail.com Tue May 4 06:17:10 2010 From: petshmidt at googlemail.com (someone) Date: Tue, 4 May 2010 03:17:10 -0700 (PDT) Subject: print executed query References: <9b2a7e6f-003d-474a-968f-0cdcede9ce5c@k41g2000yqb.googlegroups.com> <8E05B556-DB67-4B4C-B4B4-C34E12BE6E35@semanchuk.com> Message-ID: On 4 Mai, 07:01, Fred C wrote: > On Apr 29, 2010, at 9:49 AM, Philip Semanchuk wrote: > > > > > > > On Apr 29, 2010, at 12:01 PM, someone wrote: > > >> Hello! > > >> Is there a way to print a query for logging purpose as it was or will > >> be sent to database, if I don't escape values of query by myself? > > >> cursor.execute(query, [id, somestring]) > > >> I could print query and values separate, but it would be great, if I > >> could see how query is constructed and can the also copy it and > >> execute in console. > > >> Im using psycopg2, btw > > > If you can fiddle with the Postgres server settings, the server has options for logging lots of things, including the queries it executes. > > > Hope this helps > > Philip > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ?smime.p7s > 4KAnzeigenHerunterladen Hello! Thanks for help! I've found much more simpler solution ;) http://initd.org/psycopg/docs/cursor.html query Read-only attribute containing the body of the last query sent to the backend (including bound arguments). None if no query has been executed yet: >>> cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar')) >>> cur.query "INSERT INTO test (num, data) VALUES (42, E'bar')" DB API extension The query attribute is a Psycopg extension to the DB API 2.0. From utente at esempio.net Tue May 4 06:28:51 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 12:28:51 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> Message-ID: <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> Samuel Williams ha scritto: > I personally like indentation. > > I just wonder whether it is an issue that some people will dislike. i think there is an issue if you -- say -- produce python code, from within another programming environment, to be executed on the fly, at least in some instances. there might be problems if for example you generate code from a one-line template. i use a special template system for my job, which goes like this: ... %%SCHEMA: ... $A, $B, $C being "loop" control variables reserved to the template system. upon parsing, the system generates the corresponding code (say "print 12*2**3") and stores the output for further use. due to design restrictions, i cannot write a code-template which spans multiple template-lines, and that is a problem with python, because for instance i cannot use conditionals or for loops. if it was C or java there wuold be no problem since the source is free-form, so an entire program can "live" on a single source line. bye From eckhardt at satorlaser.com Tue May 4 06:46:20 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 04 May 2010 12:46:20 +0200 Subject: itertools: problem with nested groupby, list() References: Message-ID: Nico Schl?mer wrote: > I ran into a bit of an unexpected issue here with itertools, and I > need to say that I discovered itertools only recently, so maybe my way > of approaching the problem is "not what I want to do". > > Anyway, the problem is the following: > I have a list of dictionaries, something like > > [ { "a": 1, "b": 1, "c": 3 }, > { "a": 1, "b": 1, "c": 4 }, > ... > ] > > and I'd like to iterate through all items with, e.g., "a":1. What I do > is sort and then groupby, > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > > and then just very simply iterate over my_list_grouped, > > for my_item in my_list_grouped: > # do something with my_item[0], my_item[1] I'd try to avoid copying the list and instead just iterate over it: def iterate_by_key(l, key): for d in l: try: yield l[key] except: continue Note that you could also ask the dictionary first if it has the key, but I'm told this way is even faster since it only requires a single lookup attempt. > Now, inside this loop I'd like to again iterate over all items with > the same 'b'-value -- no problem, just do the above inside the loop: > > for my_item in my_list_grouped: > # group by keyword "b" > my_list2 = list( my_item[1] ) > my_list2.sort( key=operator.itemgetter('b') ) > my_list_grouped = itertools.groupby( my_list2, > operator.itemgetter('b') ) > for e in my_list_grouped: > # do something with e[0], e[1] > > That seems to work all right. Since your operation not only iterates over a list but first sorts it, it requires a modification which must not happen while iterating. You work around this by copying the list first. > Now, the problem occurs when this all is wrapped into an outer loop, such > as > > for k in [ 'first pass', 'second pass' ]: > for my_item in my_list_grouped: > # bla, the above > > To be able to iterate more than once through my_list_grouped, I have > to convert it into a list first, so outside all loops, I go like > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > my_list_grouped = list( my_list_grouped ) > > This, however, makes it impossible to do the inner sort and > groupby-operation; you just get the very first element, and that's it. I believe that you are doing a modifying operation inside the the iteration, which is a no-no. Create a custom iterator function (IIRC they are called "generators") and you should be fine. Note that this should also perform better since copying and sorting are not exactly for free, though you may not notice that with small numbers of objects. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From stefan_ml at behnel.de Tue May 4 06:50:46 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 12:50:46 +0200 Subject: Teaching Programming In-Reply-To: <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> Message-ID: superpollo, 04.05.2010 12:28: > i think there is an issue if you -- say -- produce python code, from > within another programming environment, to be executed on the fly, at > least in some instances. there might be problems if for example you > generate code from a one-line template. There are a couple of code generation tools available that you can find on PyPI. However, the main reason why this problem doesn't hurt much in Python is that Python is a dynamic language that can get you extremely far without generating code. It's simply not necessary in most cases, so people don't run into problems with it. Stefan From joncle at googlemail.com Tue May 4 07:08:14 2010 From: joncle at googlemail.com (Jon Clements) Date: Tue, 4 May 2010 04:08:14 -0700 (PDT) Subject: itertools: problem with nested groupby, list() References: Message-ID: <76fc5fab-9c3b-4aeb-b38d-8ae913822d3a@q32g2000yqb.googlegroups.com> On 4 May, 11:10, Nico Schl?mer wrote: > Hi, > > I ran into a bit of an unexpected issue here with itertools, and I > need to say that I discovered itertools only recently, so maybe my way > of approaching the problem is "not what I want to do". > > Anyway, the problem is the following: > I have a list of dictionaries, something like > > [ { "a": 1, "b": 1, "c": 3 }, > ? { "a": 1, "b": 1, "c": 4 }, > ? ... > ] > > and I'd like to iterate through all items with, e.g., "a":1. What I do > is sort and then groupby, > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > > and then just very simply iterate over my_list_grouped, > > for my_item in my_list_grouped: > ? ? # do something with my_item[0], my_item[1] > > Now, inside this loop I'd like to again iterate over all items with > the same 'b'-value -- no problem, just do the above inside the loop: > > for my_item in my_list_grouped: > ? ? ? ? # group by keyword "b" > ? ? ? ? my_list2 = list( my_item[1] ) > ? ? ? ? my_list2.sort( key=operator.itemgetter('b') ) > ? ? ? ? my_list_grouped = itertools.groupby( my_list2, > operator.itemgetter('b') ) > ? ? ? ? for e in my_list_grouped: > ? ? ? ? ? ? # do something with e[0], e[1] > > That seems to work all right. > > Now, the problem occurs when this all is wrapped into an outer loop, such as > > for k in [ 'first pass', 'second pass' ]: > ? ? for my_item in my_list_grouped: > ? ? # bla, the above > > To be able to iterate more than once through my_list_grouped, I have > to convert it into a list first, so outside all loops, I go like > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > my_list_grouped = list( my_list_grouped ) > > This, however, makes it impossible to do the inner sort and > groupby-operation; you just get the very first element, and that's it. > > An example file is attached. > > Hints, anyone? > > Cheers, > Nico Does this example help at all? my_list.sort( key=itemgetter('a','b','c') ) for a, a_iter in groupby(my_list, itemgetter('a')): print 'New A', a for b, b_iter in groupby(a_iter, itemgetter('b')): print '\t', 'New B', b for c, c_iter in groupby(b_iter, itemgetter('c')): print '\t'*2, 'New C', c for c_data in c_iter: print '\t'*3, a, b, c, c_data print '\t'*2, 'End C', c print '\t', 'End B', b print 'End A', a Jon. From chris at simplistix.co.uk Tue May 4 07:22:02 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 04 May 2010 12:22:02 +0100 Subject: modifying open office spreadsheet (with OO installed) In-Reply-To: <4BD9FB33.90208@comcast.net> References: <4bd8aa92$0$2118$426a34cc@news.free.fr> <4bd9ec94$0$24904$426a74cc@news.free.fr> <4BD9FB33.90208@comcast.net> Message-ID: <4BE0035A.4080001@simplistix.co.uk> Jim Byrnes wrote: > News123 wrote: >> Mumbling to myself, perhaps somebody else is interested. > > Yes I am. > >> News123 wrote: >>> Hi, >>> >>> >>> I wanted to know who can recommend a good module/library, that allows to >>> modify an Open Office spreadsheet. >>> >>> One can assume, that Open Office is installed on the host. >>> >>> >> Following url gives a small introduction about using the PyUno-bridge to >> open-read-modify-save a spread sheet >> http://stuvel.eu/ooo-python If .xls files are an option for you, xlutils.copy is your friend: https://secure.simplistix.co.uk/svn/xlutils/trunk/xlutils/docs/copy.txt cheers, Chris From chris at simplistix.co.uk Tue May 4 07:23:26 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 04 May 2010 12:23:26 +0100 Subject: ooolib, reading writing a spread sheet and keep formatting In-Reply-To: <4BD94090.8060005@free.fr> References: <4bd8cfc3$0$667$426a74cc@news.free.fr> <4BD94090.8060005@free.fr> Message-ID: <4BE003AE.4080406@simplistix.co.uk> News123 wrote: > > from xlrd import open_workbook > from xlutils.copy import copy > > rb = open_workbook('doc1.xls') open_workbook('doc1.xls',formatting_info=True) > print "WB with %d sheets" % rb.nsheets > wb = copy(rb) > wb.save("doc2.xls") # file is created, but ALL formattng is lost and > formulas are now diplayed as text cheers, Chris From utente at esempio.net Tue May 4 07:23:56 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 13:23:56 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> Message-ID: <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> Stefan Behnel ha scritto: > superpollo, 04.05.2010 12:28: >> i think there is an issue if you -- say -- produce python code, from >> within another programming environment, to be executed on the fly, at >> least in some instances. there might be problems if for example you >> generate code from a one-line template. > > There are a couple of code generation tools available that you can find > on PyPI. > > However, the main reason why this problem doesn't hurt much in Python is > that Python is a dynamic language that can get you extremely far without > generating code. It's simply not necessary in most cases, so people > don't run into problems with it. > > Stefan > Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> A,B=2,3 >>> if A>B: ... print A+B ... else: ... print A**B-B**2 ... -1 >>> A,B=3,2 >>> if A>B: ... print A+B ... else: ... print A**B-B**2 ... 5 >>> tell me please: how can generate the same output (depending on A and B) without control structure? i mean in a natural "pythonic" way... bye From martin.hellwig at dcuktec.org Tue May 4 07:25:57 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 04 May 2010 12:25:57 +0100 Subject: Teaching Programming In-Reply-To: <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> Message-ID: On 05/04/10 11:28, superpollo wrote: > Samuel Williams ha scritto: >> I personally like indentation. >> >> I just wonder whether it is an issue that some people will dislike. > there might be problems if for example you > generate code from a one-line template. Well a one-line template code generator are great and such, but if the output should be human readable it is necessary to have at least some form of mark-up control on it. Like newlines and indentations. On the other hand if it is only meant to generate executable code, generating an interpreted code might not be the best solution for the actual problem. For the corner cases (I can think of a couple) it is good to know you can use ';' most of the time. -- mph From oxfordenergyservices at googlemail.com Tue May 4 07:26:53 2010 From: oxfordenergyservices at googlemail.com (a) Date: Tue, 4 May 2010 04:26:53 -0700 (PDT) Subject: python gui Message-ID: <2f187732-ae4d-4cfc-8c43-3e4a5cd0166f@b18g2000yqb.googlegroups.com> where's the best online resource for teaching about GUI building? Thanks Paul C From nico.schloemer at gmail.com Tue May 4 07:36:06 2010 From: nico.schloemer at gmail.com (=?ISO-8859-1?Q?Nico_Schl=F6mer?=) Date: Tue, 4 May 2010 13:36:06 +0200 Subject: itertools: problem with nested groupby, list() In-Reply-To: <76fc5fab-9c3b-4aeb-b38d-8ae913822d3a@q32g2000yqb.googlegroups.com> References: <76fc5fab-9c3b-4aeb-b38d-8ae913822d3a@q32g2000yqb.googlegroups.com> Message-ID: > Does this example help at all? Thanks, that clarified things a lot! To make it easier, let's just look at 'a' and 'b': > my_list.sort( key=itemgetter('a','b','c') ) > for a, a_iter in groupby(my_list, itemgetter('a')): > print 'New A', a > for b, b_iter in groupby(a_iter, itemgetter('b')): > print '\t', 'New B', b > for b_data in b_iter: > print '\t'*3, a, b, b_data > print '\t', 'End B', b > print 'End A', a That works well, and I can wrap the outer loop in another loop without problems. What's *not* working, though, is having more than one pass on the inner loop, as in =============================== *snip* =============================== my_list.sort( key=itemgetter('a','b','c') ) for a, a_iter in groupby(my_list, itemgetter('a')): print 'New A', a for pass in ['first pass', 'second pass']: for b, b_iter in groupby(a_iter, itemgetter('b')): print '\t', 'New B', b for b_data in b_iter: print '\t'*3, a, b, b_data print '\t', 'End B', b print 'End A', a =============================== *snap* =============================== I tried working around this by =============================== *snip* =============================== my_list.sort( key=itemgetter('a','b','c') ) for a, a_iter in groupby(my_list, itemgetter('a')): print 'New A', a inner_list = list( groupby(a_iter, itemgetter('b')) ) for pass in ['first pass', 'second pass']: for b, b_iter in inner_list: print '\t', 'New B', b for b_data in b_iter: print '\t'*3, a, b, b_data print '\t', 'End B', b print 'End A', a =============================== *snap* =============================== which don't work either, and I don't understand why. -- I'll look at Uli's comments. Cheers, Nico On Tue, May 4, 2010 at 1:08 PM, Jon Clements wrote: > On 4 May, 11:10, Nico Schl?mer wrote: >> Hi, >> >> I ran into a bit of an unexpected issue here with itertools, and I >> need to say that I discovered itertools only recently, so maybe my way >> of approaching the problem is "not what I want to do". >> >> Anyway, the problem is the following: >> I have a list of dictionaries, something like >> >> [ { "a": 1, "b": 1, "c": 3 }, >> ? { "a": 1, "b": 1, "c": 4 }, >> ? ... >> ] >> >> and I'd like to iterate through all items with, e.g., "a":1. What I do >> is sort and then groupby, >> >> my_list.sort( key=operator.itemgetter('a') ) >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> >> and then just very simply iterate over my_list_grouped, >> >> for my_item in my_list_grouped: >> ? ? # do something with my_item[0], my_item[1] >> >> Now, inside this loop I'd like to again iterate over all items with >> the same 'b'-value -- no problem, just do the above inside the loop: >> >> for my_item in my_list_grouped: >> ? ? ? ? # group by keyword "b" >> ? ? ? ? my_list2 = list( my_item[1] ) >> ? ? ? ? my_list2.sort( key=operator.itemgetter('b') ) >> ? ? ? ? my_list_grouped = itertools.groupby( my_list2, >> operator.itemgetter('b') ) >> ? ? ? ? for e in my_list_grouped: >> ? ? ? ? ? ? # do something with e[0], e[1] >> >> That seems to work all right. >> >> Now, the problem occurs when this all is wrapped into an outer loop, such as >> >> for k in [ 'first pass', 'second pass' ]: >> ? ? for my_item in my_list_grouped: >> ? ? # bla, the above >> >> To be able to iterate more than once through my_list_grouped, I have >> to convert it into a list first, so outside all loops, I go like >> >> my_list.sort( key=operator.itemgetter('a') ) >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> my_list_grouped = list( my_list_grouped ) >> >> This, however, makes it impossible to do the inner sort and >> groupby-operation; you just get the very first element, and that's it. >> >> An example file is attached. >> >> Hints, anyone? >> >> Cheers, >> Nico > > Does this example help at all? > > my_list.sort( key=itemgetter('a','b','c') ) > for a, a_iter in groupby(my_list, itemgetter('a')): > ? ?print 'New A', a > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): > ? ? ? ?print '\t', 'New B', b > ? ? ? ?for c, c_iter in groupby(b_iter, itemgetter('c')): > ? ? ? ? ? ?print '\t'*2, 'New C', c > ? ? ? ? ? ?for c_data in c_iter: > ? ? ? ? ? ? ? ?print '\t'*3, a, b, c, c_data > ? ? ? ? ? ?print '\t'*2, 'End C', c > ? ? ? ?print '\t', 'End B', b > ? ?print 'End A', a > > Jon. > -- > http://mail.python.org/mailman/listinfo/python-list > From nico.schloemer at gmail.com Tue May 4 07:43:18 2010 From: nico.schloemer at gmail.com (=?ISO-8859-1?Q?Nico_Schl=F6mer?=) Date: Tue, 4 May 2010 13:43:18 +0200 Subject: itertools: problem with nested groupby, list() In-Reply-To: References: Message-ID: > I'd try to avoid copying the list and instead just iterate over it: > > > def iterate_by_key(l, key): > for d in l: > try: > yield l[key] > except: > continue Hm, that won't work for me b/c I don't know all the keys beforehand. I could certainly do a unique(list.keys()) or something like that beforehand, but I guess this does away with the speed advantage. > Since your operation not only iterates over a list but first sorts it, it > requires a modification which must not happen while iterating. You work > around this by copying the list first. So when I go like for item in list: item[1].sort() I actually modify *list*? I didn't realize that; I thought it'd just be a copy of it. Anyway, I could just try for item in list: newitem = sorted( item[1] ) in that case. > which is a no-no. Create a custom iterator function (IIRC they are > called "generators") and you should be fine. I'll look into this, thanks for the hint. Cheers, Nico On Tue, May 4, 2010 at 12:46 PM, Ulrich Eckhardt wrote: > Nico Schl?mer wrote: >> I ran into a bit of an unexpected issue here with itertools, and I >> need to say that I discovered itertools only recently, so maybe my way >> of approaching the problem is "not what I want to do". >> >> Anyway, the problem is the following: >> I have a list of dictionaries, something like >> >> [ { "a": 1, "b": 1, "c": 3 }, >> ? { "a": 1, "b": 1, "c": 4 }, >> ? ... >> ] >> >> and I'd like to iterate through all items with, e.g., "a":1. What I do >> is sort and then groupby, >> >> my_list.sort( key=operator.itemgetter('a') ) >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> >> and then just very simply iterate over my_list_grouped, >> >> for my_item in my_list_grouped: >> ? ? # do something with my_item[0], my_item[1] > > I'd try to avoid copying the list and instead just iterate over it: > > > ? ?def iterate_by_key(l, key): > ? ? ? ?for d in l: > ? ? ? ? ? ?try: > ? ? ? ? ? ? ? ?yield l[key] > ? ? ? ? ? ?except: > ? ? ? ? ? ? ? ?continue > > Note that you could also ask the dictionary first if it has the key, but I'm > told this way is even faster since it only requires a single lookup > attempt. > > >> Now, inside this loop I'd like to again iterate over all items with >> the same 'b'-value -- no problem, just do the above inside the loop: >> >> for my_item in my_list_grouped: >> ? ? ? ? # group by keyword "b" >> ? ? ? ? my_list2 = list( my_item[1] ) >> ? ? ? ? my_list2.sort( key=operator.itemgetter('b') ) >> ? ? ? ? my_list_grouped = itertools.groupby( my_list2, >> operator.itemgetter('b') ) >> ? ? ? ? for e in my_list_grouped: >> ? ? ? ? ? ? # do something with e[0], e[1] >> >> That seems to work all right. > > Since your operation not only iterates over a list but first sorts it, it > requires a modification which must not happen while iterating. You work > around this by copying the list first. > >> Now, the problem occurs when this all is wrapped into an outer loop, such >> as >> >> for k in [ 'first pass', 'second pass' ]: >> ? ? for my_item in my_list_grouped: >> ? ? # bla, the above >> >> To be able to iterate more than once through my_list_grouped, I have >> to convert it into a list first, so outside all loops, I go like >> >> my_list.sort( key=operator.itemgetter('a') ) >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> my_list_grouped = list( my_list_grouped ) >> >> This, however, makes it impossible to do the inner sort and >> groupby-operation; you just get the very first element, and that's it. > > I believe that you are doing a modifying operation inside the the iteration, > which is a no-no. Create a custom iterator function (IIRC they are > called "generators") and you should be fine. Note that this should also > perform better since copying and sorting are not exactly for free, though > you may not notice that with small numbers of objects. > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 > > -- > http://mail.python.org/mailman/listinfo/python-list > From stefan_ml at behnel.de Tue May 4 07:43:43 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 13:43:43 +0200 Subject: Teaching Programming In-Reply-To: <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> Message-ID: superpollo, 04.05.2010 13:23: > Stefan Behnel ha scritto: >> the main reason why this problem doesn't hurt much in Python >> is that Python is a dynamic language that can get you extremely far >> without generating code. It's simply not necessary in most cases, so >> people don't run into problems with it. > > Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> A,B=2,3 > >>> if A>B: > ... print A+B > ... else: > ... print A**B-B**2 > ... > -1 > >>> A,B=3,2 > >>> if A>B: > ... print A+B > ... else: > ... print A**B-B**2 > ... > 5 > > tell me please: how can generate the same output (depending on A and B) > without control structure? i mean in a natural "pythonic" way... The question is: why do you have to generate the above code in the first place? Isn't a function enough that does the above? Stefan From joncle at googlemail.com Tue May 4 07:52:34 2010 From: joncle at googlemail.com (Jon Clements) Date: Tue, 4 May 2010 04:52:34 -0700 (PDT) Subject: itertools: problem with nested groupby, list() References: <76fc5fab-9c3b-4aeb-b38d-8ae913822d3a@q32g2000yqb.googlegroups.com> Message-ID: <22a806f2-03a0-4cfa-a73f-b4d4ff582937@g21g2000yqk.googlegroups.com> On 4 May, 12:36, Nico Schl?mer wrote: > > Does this example help at all? > > Thanks, that clarified things a lot! > > To make it easier, let's just look at 'a' and 'b': > > > my_list.sort( key=itemgetter('a','b','c') ) > > for a, a_iter in groupby(my_list, itemgetter('a')): > > ? ?print 'New A', a > > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): > > ? ? ? ?print '\t', 'New B', b > > ? ? ? ?for b_data in b_iter: > > ? ? ? ? ? ?print '\t'*3, a, b, b_data > > ? ? ? ?print '\t', 'End B', b > > ? ?print 'End A', a > > That works well, and I can wrap the outer loop in another loop without > problems. What's *not* working, though, is having more than one pass > on the inner loop, as in > > =============================== *snip* =============================== > my_list.sort( key=itemgetter('a','b','c') ) > for a, a_iter in groupby(my_list, itemgetter('a')): > ? ?print 'New A', a > ? ?for pass in ['first pass', 'second pass']: > ? ? ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): > ? ? ? ? ? ?print '\t', 'New B', b > ? ? ? ? ? ?for b_data in b_iter: > ? ? ? ? ? ? ? ?print '\t'*3, a, b, b_data > ? ? ? ? ? ?print '\t', 'End B', b > ? ? ? ?print 'End A', a > =============================== *snap* =============================== > > I tried working around this by > > =============================== *snip* =============================== > my_list.sort( key=itemgetter('a','b','c') ) > for a, a_iter in groupby(my_list, itemgetter('a')): > ? ?print 'New A', a > ? ?inner_list = ?list( groupby(a_iter, itemgetter('b')) ) > ? ?for pass in ['first pass', 'second pass']: > ? ? ? ?for b, b_iter in inner_list: > ? ? ? ? ? ?print '\t', 'New B', b > ? ? ? ? ? ?for b_data in b_iter: > ? ? ? ? ? ? ? ?print '\t'*3, a, b, b_data > ? ? ? ? ? ?print '\t', 'End B', b > ? ? ? ?print 'End A', a > =============================== *snap* =============================== > > which don't work either, and I don't understand why. -- I'll look at > Uli's comments. > > Cheers, > Nico > > On Tue, May 4, 2010 at 1:08 PM, Jon Clements wrote: > > On 4 May, 11:10, Nico Schl?mer wrote: > >> Hi, > > >> I ran into a bit of an unexpected issue here with itertools, and I > >> need to say that I discovered itertools only recently, so maybe my way > >> of approaching the problem is "not what I want to do". > > >> Anyway, the problem is the following: > >> I have a list of dictionaries, something like > > >> [ { "a": 1, "b": 1, "c": 3 }, > >> ? { "a": 1, "b": 1, "c": 4 }, > >> ? ... > >> ] > > >> and I'd like to iterate through all items with, e.g., "a":1. What I do > >> is sort and then groupby, > > >> my_list.sort( key=operator.itemgetter('a') ) > >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > > >> and then just very simply iterate over my_list_grouped, > > >> for my_item in my_list_grouped: > >> ? ? # do something with my_item[0], my_item[1] > > >> Now, inside this loop I'd like to again iterate over all items with > >> the same 'b'-value -- no problem, just do the above inside the loop: > > >> for my_item in my_list_grouped: > >> ? ? ? ? # group by keyword "b" > >> ? ? ? ? my_list2 = list( my_item[1] ) > >> ? ? ? ? my_list2.sort( key=operator.itemgetter('b') ) > >> ? ? ? ? my_list_grouped = itertools.groupby( my_list2, > >> operator.itemgetter('b') ) > >> ? ? ? ? for e in my_list_grouped: > >> ? ? ? ? ? ? # do something with e[0], e[1] > > >> That seems to work all right. > > >> Now, the problem occurs when this all is wrapped into an outer loop, such as > > >> for k in [ 'first pass', 'second pass' ]: > >> ? ? for my_item in my_list_grouped: > >> ? ? # bla, the above > > >> To be able to iterate more than once through my_list_grouped, I have > >> to convert it into a list first, so outside all loops, I go like > > >> my_list.sort( key=operator.itemgetter('a') ) > >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > >> my_list_grouped = list( my_list_grouped ) > > >> This, however, makes it impossible to do the inner sort and > >> groupby-operation; you just get the very first element, and that's it. > > >> An example file is attached. > > >> Hints, anyone? > > >> Cheers, > >> Nico > > > Does this example help at all? > > > my_list.sort( key=itemgetter('a','b','c') ) > > for a, a_iter in groupby(my_list, itemgetter('a')): > > ? ?print 'New A', a > > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): > > ? ? ? ?print '\t', 'New B', b > > ? ? ? ?for c, c_iter in groupby(b_iter, itemgetter('c')): > > ? ? ? ? ? ?print '\t'*2, 'New C', c > > ? ? ? ? ? ?for c_data in c_iter: > > ? ? ? ? ? ? ? ?print '\t'*3, a, b, c, c_data > > ? ? ? ? ? ?print '\t'*2, 'End C', c > > ? ? ? ?print '\t', 'End B', b > > ? ?print 'End A', a > > > Jon. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Are you basically after this, then? for a, a_iter in groupby(my_list, itemgetter('a')): print 'New A', a for b, b_iter in groupby(a_iter, itemgetter('b')): b_list = list(b_iter) for p in ['first', 'second']: for b_data in b_list: #whatever... Cos that looks like it could be simplified to (untested) for (a, b), data_iter in groupby(my_list, itemgetter('a','b')): data = list(data) # take copy for pass_ in ['first', 'second']: # do something with data But from my POV, it's almost looking like a 2-tuple key in a defaultdict jobby. Jon. From utente at esempio.net Tue May 4 07:56:43 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 13:56:43 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> Message-ID: <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Stefan Behnel ha scritto: > superpollo, 04.05.2010 13:23: >> Stefan Behnel ha scritto: >>> the main reason why this problem doesn't hurt much in Python >>> is that Python is a dynamic language that can get you extremely far >>> without generating code. It's simply not necessary in most cases, so >>> people don't run into problems with it. >> >> Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) >> [GCC 4.3.3] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> A,B=2,3 >> >>> if A>B: >> ... print A+B >> ... else: >> ... print A**B-B**2 >> ... >> -1 >> >>> A,B=3,2 >> >>> if A>B: >> ... print A+B >> ... else: >> ... print A**B-B**2 >> ... >> 5 >> >> tell me please: how can generate the same output (depending on A and B) >> without control structure? i mean in a natural "pythonic" way... > > The question is: why do you have to generate the above code in the first > place? Isn't a function enough that does the above? of course! *but* if i must generate on-the-fly python code that defines a function i am back again to the problem: def fun(): .... ecc... how can i put *that* on a oneliner? From utente at esempio.net Tue May 4 07:59:46 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 13:59:46 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> Message-ID: <4be00c33$0$1134$4fafbaef@reader3.news.tin.it> Martin P. Hellwig ha scritto: > On 05/04/10 11:28, superpollo wrote: >> Samuel Williams ha scritto: >>> I personally like indentation. >>> >>> I just wonder whether it is an issue that some people will dislike. > >> there might be problems if for example you >> generate code from a one-line template. > > Well a one-line template code generator are great and such, but if the > output should be human readable it is necessary to have at least some > form of mark-up control on it. Like newlines and indentations. or latex markup, in my case... > On the other hand if it is only meant to generate executable code, > generating an interpreted code might not be the best solution for the > actual problem. yes, maybe generating code for a *compiler* might be faster but you must consider overhead due to compilation time, especially if code snippets are sprinkled by the dozen all over the template file. > For the corner cases (I can think of a couple) it is good to know you > can use ';' most of the time. > most but not always as i noted (think about loops or function definition) bye From livibetter at gmail.com Tue May 4 08:02:51 2010 From: livibetter at gmail.com (livibetter) Date: Tue, 4 May 2010 05:02:51 -0700 (PDT) Subject: Ann: Validating Emails and HTTP URLs in Python References: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> Message-ID: First, it's good to see a library has URL and email validator. But I found there might be a problem in your validator, the problems I found are these URLs: http://example.com/path http://example.com/path) http://example.com/path] http://example.com/path} By my understanding from RFCs, only first two are valid. >>> from lepl.apps.rfc3696 import * >>> v = HttpUrl() >>> v('http://example.com/') True >>> v('http://example.com/path') True >>> v('http://example.com/path)') True >>> v('http://example.com/path]') True >>> v('http://example.com/path}') True You use RFC 3969 [1] to write your code (I read your source code, lepl.apps.rfc3696._HttpUrl()), I think your code should only return True for first case, but all return True. Maybe I use it incorrectly? And I think that has a slight issue because RFC 3969 was written based on RFC 2396 [2], which is obsoleted by RFC 3986 [3]. I never really read RFC 3969, I am not sure if there is problem. But in RFC 3969, it writes The following characters are reserved in many URIs -- they must be used for either their URI-intended purpose or must be encoded. Some particular schemes may either broaden or relax these restrictions (see the following sections for URLs applicable to "web pages" and electronic mail), or apply them only to particular URI component parts. ; / ? : @ & = + $ , ? However in RFC 2396 (the obsoleted RFC), "3.3. Path Component," The path component contains data, specific to the authority (or the scheme if there is no authority component), identifying the resource within the scope of that scheme and authority. path = [ abs_path | opaque_part ] path_segments = segment *( "/" segment ) segment = *pchar *( ";" param ) param = *pchar pchar = unreserved | escaped | ":" | "@" | "&" | "=" | "+" | "$" | "," Here is unreserved of pchar: unreserved = alphanum | mark mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" In RFC 3986, they are a bit different, but my point here is "(" and ")". The Uri from 4Suite return the results I expect: >>> import Ft.Lib.Uri as U >>> U.MatchesUriSyntax('http://example.com/path') True >>> U.MatchesUriSyntax('http://example.com/path)') True >>> U.MatchesUriSyntax('http://example.com/path}') False >>> U.MatchesUriSyntax('http://example.com/path]') False I think you should use (read) RFC 3986 not RFC 3696 for URL validation. One more thing, HttpUrl()'s docstring should s/email/url/. [1]: http://tools.ietf.org/html/rfc3696 [2]: http://tools.ietf.org/html/rfc2396 [3]: http://tools.ietf.org/html/rfc3986 From prologic at shortcircuit.net.au Tue May 4 08:04:19 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 4 May 2010 22:04:19 +1000 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> Message-ID: On Tue, May 4, 2010 at 9:43 PM, Stefan Behnel wrote: >> Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) >> [GCC 4.3.3] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> ?>>> A,B=2,3 >> ?>>> if A>B: >> ... print A+B >> ... else: >> ... print A**B-B**2 >> ... >> -1 >> ?>>> A,B=3,2 >> ?>>> if A>B: >> ... print A+B >> ... else: >> ... print A**B-B**2 >> ... >> 5 >> >> tell me please: how can generate the same output (depending on A and B) >> without control structure? i mean in a natural "pythonic" way... >>> def quadratic(a, b): ... return a + b if a > b else a**b - b**2 ... >>> a, b = 2, 3 >>> print quadratic(a, b) -1 >>> a, b = 3, 2 >>> print quadratic(a, b) 5 >>> --james From prologic at shortcircuit.net.au Tue May 4 08:06:38 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 4 May 2010 22:06:38 +1000 Subject: Teaching Programming In-Reply-To: <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: > of course! *but* if i must generate on-the-fly python code that defines a > function i am back again to the problem: One-liner: $ python Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) [GCC 4.4.1 (CRUX)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a, b = 2, 3 >>> print a + b if a > b else a**b - b**2 -1 >>> a, b = 3, 2 >>> print a + b if a > b else a**b - b**2 5 >>> --James From eckhardt at satorlaser.com Tue May 4 08:09:41 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 04 May 2010 14:09:41 +0200 Subject: itertools: problem with nested groupby, list() References: Message-ID: <5df5b7-g8u.ln1@satorlaser.homedns.org> Nico Schl?mer wrote: > So when I go like > > for item in list: > item[1].sort() > > I actually modify *list*? I didn't realize that; I thought it'd just > be a copy of it. No, I misunderstood your code there. Modifying the objects inside the list is fine, but I don't thing you do that, provided the items in the list don't contain references to the list itself. Good luck! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From e_d_k at yahoo.com Tue May 4 08:15:31 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 05:15:31 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <163888.67952.qm@web58706.mail.re1.yahoo.com> --- On Tue, 5/4/10, Stefan Behnel wrote: > From: Stefan Behnel > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 7:43 AM > superpollo, 04.05.2010 13:23: > > Stefan Behnel ha scritto: > >> the main reason why this problem doesn't hurt much > in Python > >> is that Python is a dynamic language that can get > you extremely far > >> without generating code. It's simply not necessary > in most cases, so > >> people don't run into problems with it. > > > > Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) > > [GCC 4.3.3] on linux2 > > Type "help", "copyright", "credits" or "license" for > more information. > >? >>> A,B=2,3 > >? >>> if A>B: > > ... print A+B > > ... else: > > ... print A**B-B**2 > > ... > > -1 > >? >>> A,B=3,2 > >? >>> if A>B: > > ... print A+B > > ... else: > > ... print A**B-B**2 > > ... > > 5 > > > > tell me please: how can generate the same output > (depending on A and B) > > without control structure? i mean in a natural > "pythonic" way... > > The question is: why do you have to generate the above code > in the first > place? Isn't a function enough that does the above? > > Stefan > > -- > http://mail.python.org/mailman/listinfo/python-list > Just thought I'd add my $0.02 here. I wrote AsciiLitProg (http://asciilitprog.berlios.de/) in Python. It is a literate programming tool. It generates code from a document. It can generate code in any language the author wants. It would have been a LOT easier to write if it did not generate Python code. Python is a great language to write in (although I do wish it did a better job with closures). But it is a PITA to generate code for! -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From benjamin.kaplan at case.edu Tue May 4 08:17:33 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 4 May 2010 08:17:33 -0400 Subject: Teaching Programming In-Reply-To: <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> Message-ID: On Tue, May 4, 2010 at 7:23 AM, superpollo wrote: > Stefan Behnel ha scritto: >> >> superpollo, 04.05.2010 12:28: >>> >>> i think there is an issue if you -- say -- produce python code, from >>> within another programming environment, to be executed on the fly, at >>> least in some instances. there might be problems if for example you >>> generate code from a one-line template. >> >> There are a couple of code generation tools available that you can find on >> PyPI. >> >> However, the main reason why this problem doesn't hurt much in Python is >> that Python is a dynamic language that can get you extremely far without >> generating code. It's simply not necessary in most cases, so people don't >> run into problems with it. >> >> Stefan >> > > Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> A,B=2,3 >>>> if A>B: > ... ? ? print A+B > ... else: > ... ? ? print A**B-B**2 > ... > -1 >>>> A,B=3,2 >>>> if A>B: > ... ? ? print A+B > ... else: > ... ? ? print A**B-B**2 > ... > 5 >>>> > > tell me please: how can generate the same output (depending on A and B) > without control structure? i mean in a natural "pythonic" way... > > bye Well, it requires 2.6 or 3 Python 2.6.5 (r265:79063, Mar 21 2010, 22:38:52) [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import print_function >>> A,B=2,3;print(A+B if A > B else A**B - B**2) -1 >>> A,B=3,2;print(A+B if A > B else A**B - B**2) 5 > > -- > http://mail.python.org/mailman/listinfo/python-list > From utente at esempio.net Tue May 4 08:23:00 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 14:23:00 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4be011a4$0$1121$4fafbaef@reader3.news.tin.it> James Mills ha scritto: > On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: >> of course! *but* if i must generate on-the-fly python code that defines a >> function i am back again to the problem: > > One-liner: > > $ python > Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) > [GCC 4.4.1 (CRUX)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a, b = 2, 3 >>>> print a + b if a > b else a**b - b**2 > -1 >>>> a, b = 3, 2 >>>> print a + b if a > b else a**b - b**2 > 5 > > --James much obliged. From prologic at shortcircuit.net.au Tue May 4 08:24:16 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 4 May 2010 22:24:16 +1000 Subject: python gui In-Reply-To: <2f187732-ae4d-4cfc-8c43-3e4a5cd0166f@b18g2000yqb.googlegroups.com> References: <2f187732-ae4d-4cfc-8c43-3e4a5cd0166f@b18g2000yqb.googlegroups.com> Message-ID: On Tue, May 4, 2010 at 9:26 PM, a wrote: > where's the best online resource for teaching about GUI building? There are many many resources available on the topic. If you simply Google (tm) some of the keywords in your post you'll be presented with a whole smorgasbord of useful resources. --james From stefan_ml at behnel.de Tue May 4 08:33:58 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 14:33:58 +0200 Subject: Teaching Programming In-Reply-To: <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: superpollo, 04.05.2010 13:56: > Stefan Behnel ha scritto: >> The question is: why do you have to generate the above code in the >> first place? Isn't a function enough that does the above? > > of course! *but* if i must generate on-the-fly python code that defines > a function [...] Well, could you provide a use case where you have to generate Python code, and where normally written code with some kind of parametrisation won't work? The only thing that currently comes to my mind is a template compiler that translates a user provided template into an executable Python program. But that should be pretty trivial to do as well. I just remembered this little thing on Fredrik's effbot site, which should help here: http://effbot.org/zone/python-code-generator.htm Stefan From nico.schloemer at gmail.com Tue May 4 08:37:17 2010 From: nico.schloemer at gmail.com (=?ISO-8859-1?Q?Nico_Schl=F6mer?=) Date: Tue, 4 May 2010 14:37:17 +0200 Subject: itertools: problem with nested groupby, list() In-Reply-To: <22a806f2-03a0-4cfa-a73f-b4d4ff582937@g21g2000yqk.googlegroups.com> References: <76fc5fab-9c3b-4aeb-b38d-8ae913822d3a@q32g2000yqb.googlegroups.com> <22a806f2-03a0-4cfa-a73f-b4d4ff582937@g21g2000yqk.googlegroups.com> Message-ID: > Are you basically after this, then? > > for a, a_iter in groupby(my_list, itemgetter('a')): > print 'New A', a > for b, b_iter in groupby(a_iter, itemgetter('b')): > b_list = list(b_iter) > for p in ['first', 'second']: > for b_data in b_list: > #whatever... Yes. Moving the 'first', 'second' operation to the innermost loop works all right, and I guess that's what I'll do. > Cos that looks like it could be simplified to (untested) > for (a, b), data_iter in groupby(my_list, itemgetter('a','b')): > data = list(data) # take copy > for pass_ in ['first', 'second']: > # do something with data Potentially yes, but for now I actually need to do something at "print 'New A', a", so I can't just skip this. Anyway, the above suggestion works well for now. Thanks! --Nico On Tue, May 4, 2010 at 1:52 PM, Jon Clements wrote: > On 4 May, 12:36, Nico Schl?mer wrote: >> > Does this example help at all? >> >> Thanks, that clarified things a lot! >> >> To make it easier, let's just look at 'a' and 'b': >> >> > my_list.sort( key=itemgetter('a','b','c') ) >> > for a, a_iter in groupby(my_list, itemgetter('a')): >> > ? ?print 'New A', a >> > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): >> > ? ? ? ?print '\t', 'New B', b >> > ? ? ? ?for b_data in b_iter: >> > ? ? ? ? ? ?print '\t'*3, a, b, b_data >> > ? ? ? ?print '\t', 'End B', b >> > ? ?print 'End A', a >> >> That works well, and I can wrap the outer loop in another loop without >> problems. What's *not* working, though, is having more than one pass >> on the inner loop, as in >> >> =============================== *snip* =============================== >> my_list.sort( key=itemgetter('a','b','c') ) >> for a, a_iter in groupby(my_list, itemgetter('a')): >> ? ?print 'New A', a >> ? ?for pass in ['first pass', 'second pass']: >> ? ? ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): >> ? ? ? ? ? ?print '\t', 'New B', b >> ? ? ? ? ? ?for b_data in b_iter: >> ? ? ? ? ? ? ? ?print '\t'*3, a, b, b_data >> ? ? ? ? ? ?print '\t', 'End B', b >> ? ? ? ?print 'End A', a >> =============================== *snap* =============================== >> >> I tried working around this by >> >> =============================== *snip* =============================== >> my_list.sort( key=itemgetter('a','b','c') ) >> for a, a_iter in groupby(my_list, itemgetter('a')): >> ? ?print 'New A', a >> ? ?inner_list = ?list( groupby(a_iter, itemgetter('b')) ) >> ? ?for pass in ['first pass', 'second pass']: >> ? ? ? ?for b, b_iter in inner_list: >> ? ? ? ? ? ?print '\t', 'New B', b >> ? ? ? ? ? ?for b_data in b_iter: >> ? ? ? ? ? ? ? ?print '\t'*3, a, b, b_data >> ? ? ? ? ? ?print '\t', 'End B', b >> ? ? ? ?print 'End A', a >> =============================== *snap* =============================== >> >> which don't work either, and I don't understand why. -- I'll look at >> Uli's comments. >> >> Cheers, >> Nico >> >> On Tue, May 4, 2010 at 1:08 PM, Jon Clements wrote: >> > On 4 May, 11:10, Nico Schl?mer wrote: >> >> Hi, >> >> >> I ran into a bit of an unexpected issue here with itertools, and I >> >> need to say that I discovered itertools only recently, so maybe my way >> >> of approaching the problem is "not what I want to do". >> >> >> Anyway, the problem is the following: >> >> I have a list of dictionaries, something like >> >> >> [ { "a": 1, "b": 1, "c": 3 }, >> >> ? { "a": 1, "b": 1, "c": 4 }, >> >> ? ... >> >> ] >> >> >> and I'd like to iterate through all items with, e.g., "a":1. What I do >> >> is sort and then groupby, >> >> >> my_list.sort( key=operator.itemgetter('a') ) >> >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> >> >> and then just very simply iterate over my_list_grouped, >> >> >> for my_item in my_list_grouped: >> >> ? ? # do something with my_item[0], my_item[1] >> >> >> Now, inside this loop I'd like to again iterate over all items with >> >> the same 'b'-value -- no problem, just do the above inside the loop: >> >> >> for my_item in my_list_grouped: >> >> ? ? ? ? # group by keyword "b" >> >> ? ? ? ? my_list2 = list( my_item[1] ) >> >> ? ? ? ? my_list2.sort( key=operator.itemgetter('b') ) >> >> ? ? ? ? my_list_grouped = itertools.groupby( my_list2, >> >> operator.itemgetter('b') ) >> >> ? ? ? ? for e in my_list_grouped: >> >> ? ? ? ? ? ? # do something with e[0], e[1] >> >> >> That seems to work all right. >> >> >> Now, the problem occurs when this all is wrapped into an outer loop, such as >> >> >> for k in [ 'first pass', 'second pass' ]: >> >> ? ? for my_item in my_list_grouped: >> >> ? ? # bla, the above >> >> >> To be able to iterate more than once through my_list_grouped, I have >> >> to convert it into a list first, so outside all loops, I go like >> >> >> my_list.sort( key=operator.itemgetter('a') ) >> >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> >> my_list_grouped = list( my_list_grouped ) >> >> >> This, however, makes it impossible to do the inner sort and >> >> groupby-operation; you just get the very first element, and that's it. >> >> >> An example file is attached. >> >> >> Hints, anyone? >> >> >> Cheers, >> >> Nico >> >> > Does this example help at all? >> >> > my_list.sort( key=itemgetter('a','b','c') ) >> > for a, a_iter in groupby(my_list, itemgetter('a')): >> > ? ?print 'New A', a >> > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): >> > ? ? ? ?print '\t', 'New B', b >> > ? ? ? ?for c, c_iter in groupby(b_iter, itemgetter('c')): >> > ? ? ? ? ? ?print '\t'*2, 'New C', c >> > ? ? ? ? ? ?for c_data in c_iter: >> > ? ? ? ? ? ? ? ?print '\t'*3, a, b, c, c_data >> > ? ? ? ? ? ?print '\t'*2, 'End C', c >> > ? ? ? ?print '\t', 'End B', b >> > ? ?print 'End A', a >> >> > Jon. >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> > > Are you basically after this, then? > > for a, a_iter in groupby(my_list, itemgetter('a')): > ? ?print 'New A', a > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): > ? ? ? ?b_list = list(b_iter) > ? ? ? ?for p in ['first', 'second']: > ? ? ? ? ? ?for b_data in b_list: > ? ? ? ? ? ? ? ?#whatever... > > Cos that looks like it could be simplified to (untested) > > for (a, b), data_iter in groupby(my_list, itemgetter('a','b')): > ? data = list(data) # take copy > ? for pass_ in ['first', 'second']: > ? ? ?# do something with data > > But from my POV, it's almost looking like a 2-tuple key in a > defaultdict jobby. > > Jon. > -- > http://mail.python.org/mailman/listinfo/python-list > From stefan_ml at behnel.de Tue May 4 08:40:07 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 14:40:07 +0200 Subject: Teaching Programming In-Reply-To: <163888.67952.qm@web58706.mail.re1.yahoo.com> References: <163888.67952.qm@web58706.mail.re1.yahoo.com> Message-ID: Ed Keith, 04.05.2010 14:15: > I wrote AsciiLitProg (http://asciilitprog.berlios.de/) in Python. It is > a literate programming tool. It generates code from a document. It can > generate code in any language the author wants. It would have been a LOT > easier to write if it did not generate Python code. > > Python is a great language to write in (although I do wish it did a > better job with closures). But it is a PITA to generate code for! Interesting. Could you elaborate a bit? Could you give a short example of what kind of document text you translate into what kind of Python code, and what the problems were that you faced in doing so? Stefan From utente at esempio.net Tue May 4 08:46:52 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 14:46:52 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> Stefan Behnel ha scritto: > superpollo, 04.05.2010 13:56: >> Stefan Behnel ha scritto: >>> The question is: why do you have to generate the above code in the >>> first place? Isn't a function enough that does the above? >> >> of course! *but* if i must generate on-the-fly python code that defines >> a function [...] > > Well, could you provide a use case where you have to generate Python > code, and where normally written code with some kind of parametrisation > won't work? i see your point, and mr mills gave me hints as to how to attack some of my problems in such a fashion. > The only thing that currently comes to my mind is a template compiler > that translates a user provided template into an executable Python > program. But that should be pretty trivial to do as well. I just > remembered this little thing on Fredrik's effbot site, which should help > here: > > http://effbot.org/zone/python-code-generator.htm very good. i will most certainly give it a try. but i do not think i can use it myself, since my template system wants the input to generate the code to stay on a single line ( don't ask :-( ) bye From bazwal at ftml.net Tue May 4 08:53:40 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 04 May 2010 13:53:40 +0100 Subject: strange interaction between open and cwd In-Reply-To: <87d3xch3la.fsf@benfinney.id.au> References: <4BDEC4A5.5070801@ftml.net> <87d3xch3la.fsf@benfinney.id.au> Message-ID: <4BE018D4.8060808@ftml.net> On 04/05/10 02:12, Ben Finney wrote: > Baz Walter writes: > >> On 03/05/10 18:41, Grant Edwards wrote: >>> Firstly, a file may have any number of paths (including 0). >> >> yes, of course. i forgot about hard links > > Rather, you forgot that *every* entry that references a file is a hard > link. i'm not a frequent poster on this list, but i'm aware of it's reputation for pointless pedantry ;-) but what the heck, when in rome... note that i said hard links (plural) - i think a more generous reader would assume i was referring to additional hard links. From C.Sanders at DeleteThis.Bom.GOV.AU Tue May 4 09:02:29 2010 From: C.Sanders at DeleteThis.Bom.GOV.AU (Charles) Date: Tue, 4 May 2010 23:02:29 +1000 Subject: [OT] strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> <84a1mcFfnpU1@mid.individual.net> Message-ID: <4be01ae8$0$45294$c30e37c6@exi-reader.telstra.net> "Gregory Ewing" wrote in message news:84a1mcFfnpU1 at mid.individual.net... > Charles wrote: > >> In the OP's case, references to the directory have been removed >> from the file system, but his process still has the current working >> directory reference to it, so it has not actually been deleted. >> When he opens "../abc.txt", the OS searches the current directory >> for ".." and finds the inode for /home/baz/tmp, > > This doesn't seem to be quite correct. An experiment I just did > reveals that the link count on the parent directory goes down by > one when the current directory is deleted, suggesting that the .. > link has actually been removed... yet it still works! > > I think what must be happening is that the kernel is maintaining > an in-memory reference to the parent directory, and treating ".." > as a special case when looking up a name. > > (This probably shouldn't be too surprising, because ".." is special > in another way as well -- at the root of a mounted file system, it > leads to the parent of the mount point, even though the actual ".." > link on disk just points back to the same directory. Probably it > simplifies the name lookup logic to always treat it specially.) I am by no means an expert in this area, but what I think happens (and I may well be wrong) is that the directory is deleted on the file system. The link from the parent is removed, and the parent's link count is decremented, as you observed, but the directory itself is still intact with it's original contents, including the "." and ".." names and associated inode numbers. Unix does not normally zero out files on deletion - the file's blocks usually retain their contents, and I would not expect directories to be a special case. The blocks from the directory will be re-cycled when the memory reference (the process's current working directory) disappears, but until then the directory and its contents are still accessible via the process's current directory. This is all supposition, and based on distant memories form the mid 1980s, I could very well be wrong. Charles From bazwal at ftml.net Tue May 4 09:03:55 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 04 May 2010 14:03:55 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BE01B3B.7010901@ftml.net> On 04/05/10 03:19, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: >> On 03/05/10 19:12, Grant Edwards wrote: >>> Even though the user provided a legal and openable path? >> >> that sounds like an operational definition to me: what's the >> difference between "legal" and "openable"? > > Legal as in meets the syntactic requirements for a path (not sure if > there really are any requirements other than it being a > null-terminated string). Openable meaning that it denotes a path file > that exists and for which the caller has read permissions on the file > and execute premissions on the directories within the path. openable is not the same as accessible. a file can still openable, even though a user may not have permission to access it. a better definition of "legal path" might be whether any useful information can be gained from a stat() call on it. From stefan_ml at behnel.de Tue May 4 09:09:29 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 15:09:29 +0200 Subject: Teaching Programming In-Reply-To: <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> Message-ID: superpollo, 04.05.2010 14:46: > my template system wants > the input to generate the code to stay on a single line ( don't ask :-( ) I hope you don't mind if I still ask. What are you generating and for what templating system? Stefan From utente at esempio.net Tue May 4 09:15:31 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 15:15:31 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> Message-ID: <4be01df4$0$1134$4fafbaef@reader3.news.tin.it> Stefan Behnel ha scritto: > superpollo, 04.05.2010 14:46: >> my template system wants >> the input to generate the code to stay on a single line ( don't ask :-( ) > > I hope you don't mind if I still ask. What are you generating and for > what templating system? ok, since you asked for it, prepare yourself for a bit of a horror story ;-) i will answer in my next post bye From e_d_k at yahoo.com Tue May 4 09:19:38 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 06:19:38 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <121607.77893.qm@web58702.mail.re1.yahoo.com> --- On Tue, 5/4/10, Stefan Behnel wrote: > From: Stefan Behnel > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 8:40 AM > Ed Keith, 04.05.2010 14:15: > > I wrote AsciiLitProg (http://asciilitprog.berlios.de/) in Python. It is > > a literate programming tool. It generates code from a > document. It can > > generate code in any language the author wants. It > would have been a LOT > > easier to write if it did not generate Python code. > > > > Python is a great language to write in (although I do > wish it did a > > better job with closures). But it is a PITA to > generate code for! > > Interesting. Could you elaborate a bit? Could you give a > short example of what kind of document text you translate > into what kind of Python code, and what the problems were > that you faced in doing so? > > Stefan > > -- http://mail.python.org/mailman/listinfo/python-list > The program is written using itself. If you click on the link above you will see an HTML file that fully describes the program. That HTML is generated from an AcsiiDoc (http://www.methods.co.nz/asciidoc/) document. The same document is used to generate the python code that it describes. The source document, and the generated HTML and Python code are all avalable at BerliOS (http://developer.berlios.de/projects/asciilitprog/). For more information on Literate Programming in general see the following links. http://www.literateprogramming.com/ http://en.wikipedia.org/wiki/Literate_programming http://en.literateprograms.org/LiteratePrograms:Welcome -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From ben+python at benfinney.id.au Tue May 4 09:23:16 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 04 May 2010 23:23:16 +1000 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <87d3xch3la.fsf@benfinney.id.au> Message-ID: <87vdb3g5rv.fsf@benfinney.id.au> Baz Walter writes: > On 04/05/10 02:12, Ben Finney wrote: > > Baz Walter writes: > >> yes, of course. i forgot about hard links > > > > Rather, you forgot that *every* entry that references a file is a > > hard link. > > i'm not a frequent poster on this list, but i'm aware of it's > reputation for pointless pedantry ;-) Only pointless if you view this as a conversation entirely for the benefit of you and I. I, on the other hand, am trying to make this useful to whoever may read it now and in the future. > note that i said hard links (plural) - i think a more generous reader > would assume i was referring to additional hard links. The point, though, was that this is normal operation, rather than exceptional. Files have zero or more hard links, and ?this file has exactly one hard link? is merely a common case among that spectrum. I'm glad you already knew this, and hope you can appreciate that it's better explicit than implicit. -- \ ?The difference between religions and cults is determined by | `\ how much real estate is owned.? ?Frank Zappa | _o__) | Ben Finney From nobody at nowhere.com Tue May 4 09:29:20 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 04 May 2010 14:29:20 +0100 Subject: [OT] strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> <84a1mcFfnpU1@mid.individual.net> <4be01ae8$0$45294$c30e37c6@exi-reader.telstra.net> Message-ID: On Tue, 04 May 2010 23:02:29 +1000, Charles wrote: > I am by no means an expert in this area, but what I think happens (and I > may well be wrong) is that the directory is deleted on the file system. > The link from the parent is removed, and the parent's link count is > decremented, as you observed, but the directory itself is still intact > with it's original contents, including the "." and ".." names and > associated inode numbers. Unix does not normally zero out files on > deletion - the file's blocks usually retain their contents, and I would > not expect directories to be a special case. You are correct. System calls don't "delete" inodes (files, directories, etc), they "unlink" them. Deletion occurs when the inode's link count reaches zero and no process holds a reference to the inode (a reference could be a descriptor, or the process' cwd, chroot directory, or an mmap()d file, etc). IOW, reference-counted garbage collection. From bazwal at ftml.net Tue May 4 09:36:06 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 04 May 2010 14:36:06 +0100 Subject: strange interaction between open and cwd In-Reply-To: <84a3a5Fp5nU1@mid.individual.net> References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: <4BE022C6.8070600@ftml.net> On 04/05/10 09:23, Gregory Ewing wrote: > Grant Edwards wrote: > >> In your example, it's simply not possible to determine the file's >> absolute path within the filesystem given the relative path you >> provided. > > Actually, I think it *is* theoretically possible to find an > absolute path for the file in this case. > > I suspect that what realpath() is doing for a relative path is > something like: > > 1. Use getcwd() to find an absolute path for the current > directory. > 2. Chop off a trailing pathname component for each ".." > on the front of the original path. > 3. Tack the filename on the end of what's left. > > Step 1 fails because the current directory no longer has > an absolute pathname -- specifically, it has no name in > what used to be its parent directory. > > What realpath() is failing to realise is that it doesn't > actually need to know the full path of the current directory, > only of its parent directory, which is still reachable via > ".." (if it weren't, the file wouldn't be reachable either, > and we wouldn't be having this discussion). > > A smarter version of realpath() wouldn't try to find the > path of the *current* directory, but would follow the > ".." links until it got to a directory that it did need to > know an absolute path for, and start with that. > > Unfortunately, there is no C stdlib routine that does the > equivalent of getcwd() for an arbitrary directory, so > this would require realpath() to duplicate much of > getcwd()'s functionality, which is probably why it's > done the way it is. actually, this part of the problem can be achieved using pure python. given the basename of a file, all you have to do is use os.stat and os.listdir to recursively climb up the tree and build a dirpath for it. start by doing os.stat(basename) to make sure you have a legal file in the current directory; then use os.stat('..') to get the parent directory inode, and stat each of the items in os.listdir('../..') to find a name matching that inode etc. (note that the possibility of hard-linked directories doesn't really spoil this - for relative paths, we don't care exactly which absolute path is found). this will work so long as the file is in a part of the filesystem that can be traversed from the current directory to the root. what i'm not sure about is whether it's possible to cross filesystem boundaries using this kind of technique. From nobody at nowhere.com Tue May 4 09:39:04 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 04 May 2010 14:39:04 +0100 Subject: strange interaction between open and cwd References: <4BDEDC73.1020301@ftml.net> <84a2djFjqrU1@mid.individual.net> Message-ID: On Tue, 04 May 2010 20:08:36 +1200, Gregory Ewing wrote: >> except that Python objects can form a generalized graph, and Unix >> filesystems are constrained to be a tree. > > Actually I believe that root is allowed to create arbitrary hard links to > directories in Unix, so it's possible to turn the file system in to a > general graph. It's highly unrecommended, though, because it confuses the > heck out of programs that recursively traverse directories (which is why > only root is allowed to do it). The 1980s are over already ;) I don't know of any modern Unix which allows creating additional hard links to directories (even for root). It creates too many problems, and isn't necessary if you have symlinks. If you want to turn the filesystem into a cyclic graph, you typically need to bypass the kernel's filesystem interface and modify the block device directly (e.g. with debugfs). If fsck finds out, it's likely to fix it. From a_jtim at bellsouth.net Tue May 4 09:43:32 2010 From: a_jtim at bellsouth.net (Tim Arnold) Date: Tue, 4 May 2010 06:43:32 -0700 (PDT) Subject: design question References: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> <4bdfceba$0$9110$426a34cc@news.free.fr> Message-ID: <259ba42e-471c-4801-9f1d-28f869c60dee@r6g2000vbh.googlegroups.com> On May 4, 3:39?am, Bruno Desthuilliers wrote: > Alf P. Steinbach a ?crit : > (snip) > > > Re efficiency it seems to be a complete non-issue, but correctness is > > much more important: is there any way that the config details can be > > (inadvertently) changed while the build is going on? > > +1 Thanks everyone, I'm new at this type of development so it helps to get input from folks who know what they're talking about. I'm just been coding and doing what is right in my own eyes... There is almost no way for the configuration to change during a build, so it looks like I was just worrying about something that doesn't need worry. Now on to the things that do! thanks again, --Tim From bazwal at ftml.net Tue May 4 09:48:28 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 04 May 2010 14:48:28 +0100 Subject: strange interaction between open and cwd In-Reply-To: <84a2djFjqrU1@mid.individual.net> References: <4BDEDC73.1020301@ftml.net> <84a2djFjqrU1@mid.individual.net> Message-ID: <4BE025AC.7070309@ftml.net> On 04/05/10 09:08, Gregory Ewing wrote: > Grant Edwards wrote: > >> except that Python objects can form a generalized graph, and Unix >> filesystems are constrained to be a tree. > > Actually I believe that root is allowed to create arbitrary > hard links to directories in Unix, so it's possible to turn > the file system in to a general graph. It's highly > unrecommended, though, because it confuses the heck out of > programs that recursively traverse directories (which is > why only root is allowed to do it). i think there are versions of mac osx that use hard-linked directories in their backup systems. From nobody at nowhere.com Tue May 4 09:48:34 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 04 May 2010 14:48:34 +0100 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> Message-ID: On Mon, 03 May 2010 06:18:55 -0700, Chris Rebert wrote: >> but how can python determine the >> parent directory of a directory that no longer exists? > > Whether or not /home/baz/tmp/xxx/ exists, we know from the very structure > and properties of directory paths that its parent directory is, *by > definition*, /home/baz/tmp/ (just chop off everything after the > second-to-last slash). Not necessarily. There are two common interpretations for the concept of a "parent directory". One is the directory referenced by removing the last component from the (normalised) path, the other is the directory referenced by appending ".." to the path. The two don't necessarily refer to the same directory if the last component is a symlink (or an additional hard link, on platforms which allow creating additional hard links to directories). For the current directory[1], or a directory referenced by a descriptor rather than a path, the latter definition has to be used, as there is no path to manipulate. [1] And also for e.g. "./../..". From wuwei23 at gmail.com Tue May 4 10:06:08 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 May 2010 07:06:08 -0700 (PDT) Subject: Teaching Programming References: Message-ID: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> Ed Keith wrote: > For more information on Literate Programming in general see the following links. None of which address the question of what you found problematic about generating Python code. Was it issues with indentation? From __peter__ at web.de Tue May 4 10:10:55 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 May 2010 16:10:55 +0200 Subject: itertools: problem with nested groupby, list() References: Message-ID: Nico Schl?mer wrote: > Hi, > > I ran into a bit of an unexpected issue here with itertools, and I > need to say that I discovered itertools only recently, so maybe my way > of approaching the problem is "not what I want to do". > > Anyway, the problem is the following: > I have a list of dictionaries, something like > > [ { "a": 1, "b": 1, "c": 3 }, > { "a": 1, "b": 1, "c": 4 }, > ... > ] > > and I'd like to iterate through all items with, e.g., "a":1. What I do > is sort and then groupby, > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > > and then just very simply iterate over my_list_grouped, > > for my_item in my_list_grouped: > # do something with my_item[0], my_item[1] > > Now, inside this loop I'd like to again iterate over all items with > the same 'b'-value -- no problem, just do the above inside the loop: > > for my_item in my_list_grouped: > # group by keyword "b" > my_list2 = list( my_item[1] ) > my_list2.sort( key=operator.itemgetter('b') ) > my_list_grouped = itertools.groupby( my_list2, > operator.itemgetter('b') ) > for e in my_list_grouped: > # do something with e[0], e[1] > > That seems to work all right. > > Now, the problem occurs when this all is wrapped into an outer loop, such > as > > for k in [ 'first pass', 'second pass' ]: > for my_item in my_list_grouped: > # bla, the above > > To be able to iterate more than once through my_list_grouped, I have > to convert it into a list first, so outside all loops, I go like > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > my_list_grouped = list( my_list_grouped ) > > This, however, makes it impossible to do the inner sort and > groupby-operation; you just get the very first element, and that's it. > > An example file is attached. > > Hints, anyone? If you want a reusable copy of a groupby(...) it is not enough to convert it to a list as a whole: >>> from itertools import groupby >>> from operator import itemgetter >>> items = [(1,1), (1,2), (1,3), (2,1), (2,2)] >>> grouped_items = list(groupby(items, key=itemgetter(0))) # WRONG >>> for run in 1, 2: ... print "run", run ... for k, g in grouped_items: ... print k, list(g) ... run 1 1 [] 2 [(2, 2)] run 2 1 [] 2 [] Instead, you have to process the groups, too: >>> grouped_items = [(k, list(g)) for k, g in groupby(items, key=itemgetter(0))] >>> for run in 1, 2: ... print "run", run ... for k, g in grouped_items: ... print k, list(g) ... run 1 1 [(1, 1), (1, 2), (1, 3)] 2 [(2, 1), (2, 2)] run 2 1 [(1, 1), (1, 2), (1, 3)] 2 [(2, 1), (2, 2)] But usually you don't bother and just run groupby() twice: >>> for run in 1, 2: ... print "run", run ... for k, g in groupby(items, key=itemgetter(0)): ... print k, list(g) ... run 1 1 [(1, 1), (1, 2), (1, 3)] 2 [(2, 1), (2, 2)] run 2 1 [(1, 1), (1, 2), (1, 3)] 2 [(2, 1), (2, 2)] The only caveat then is that list(items) == list(items) must hold. Peter From wuwei23 at gmail.com Tue May 4 10:11:08 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 May 2010 07:11:08 -0700 (PDT) Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: TomF wrote: > I'm interested in improving my python design by studying a large, > well-designed codebase. ?Someone (not a python programmer) suggested > Django. ?I realize that Django is popular, but can someone comment on > whether its code is well-designed and worth studying? Here's a viewpoint that says no: http://mockit.blogspot.com/2010/04/mess-djangos-in.html There's a lot of good counterpoint in the comments too. (I also think there's value to be gained in studying _bad_ code, too...) From Ron.Barak at lsi.com Tue May 4 10:11:17 2010 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 4 May 2010 15:11:17 +0100 Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? In-Reply-To: References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6A3B87357@enbmail01.lsi.com> > -----Original Message----- > From: Stefan Behnel [mailto:stefan_ml at behnel.de] > Sent: Tuesday, May 04, 2010 10:24 AM > To: python-list at python.org > Subject: Re: How to get xml.etree.ElementTree not bomb on > invalid characters in XML file ? > > Barak, Ron, 04.05.2010 09:01: > > I'm parsing XML files using ElementTree from xml.etree (see code > > below (and attached xml_parse_example.py)). > > > > However, I'm coming across input XML files (attached an example: > > tmp.xml) which include invalid characters, that produce the > following > > traceback: > > > > $ python xml_parse_example.py > > Traceback (most recent call last): > > xml.parsers.expat.ExpatError: not well-formed (invalid > token): line 6, > > column 34 > > I hope you are aware that this means that the input you are > parsing is not XML. It's best to reject the file and tell the > producers that they are writing broken output files. You > should always fix the source, instead of trying to make sense > out of broken input in fragile ways. > > > > I read the documentation for xml.etree.ElementTree and see > that it may > > take an optional parser parameter, but I don't know what > this parser > > should be - to ignore the invalid characters. > > > > Could you suggest a way to call ElementTree, so it won't > bomb on these > > invalid characters ? > > No. The parser in lxml.etree has a 'recover' option that lets > it try to recover from input errors, but in general, XML > parsers are required to reject non well-formed input. > > Stefan > > > Hi Stefan, The XML file seems to be valid XML (all XML viewers I tried were able to read it). You can verify this by trying to read the XML example I attached to the original message (attached again here). Actually, when trying to view the file with an XML viewer, these offensive characters are not shown. It's just that some of the fields include characters that the parser used by ElementTree seems to chock on. Bye, Ron. -------------- next part -------------- A non-text attachment was scrubbed... Name: tmp_small.xml Type: application/xml Size: 637 bytes Desc: tmp_small.xml URL: From mkiever at Pirx.sirius.org Tue May 4 10:17:06 2010 From: mkiever at Pirx.sirius.org (Matthias Kievernagel) Date: Tue, 4 May 2010 14:17:06 +0000 (UTC) Subject: py3 tkinter acceps bytes. why? Message-ID: From: Matthias Kievernagel Subject: py3 tkinter acceps bytes. why? Newsgroups: comp.lang.python Summary: Keywords: In a recent thread named "py3 tkinter Text accepts what bytes?" (google groups link: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b75ed69f4e81b202/e2aff9ddd62d210c?lnk=raot) I asked what kinds of bytes are accepted as tkinter parameters. I still wonder why they are accepted at all. Does anyone know a reason for this or has a link to some relevant discussion? Thanks for any hint, Matthias Kievernagel From e_d_k at yahoo.com Tue May 4 10:21:29 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 07:21:29 -0700 (PDT) Subject: Teaching Programming In-Reply-To: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> Message-ID: <952067.92151.qm@web58703.mail.re1.yahoo.com> --- On Tue, 5/4/10, alex23 wrote: > From: alex23 > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 10:06 AM > Ed Keith > wrote: > > For more information on Literate Programming in > general see the following links. > > None of which address the question of what you found > problematic about > generating Python code. Was it issues with indentation? > > > -- > http://mail.python.org/mailman/listinfo/python-list > Yes, the problem was indentation. To deal with indentation I had to 1) keep track of indentation of all chunks of code embedded in the document and indent inserted chunks to the sum of all the indentation of the enclosing chunks. and 2) expand all tabls to spaces and allow the user to set the tab expansion size from the command line. Fortunately Python provides good support for this. Neither of these problems exist in languages that are not indention sensitive. Tabs are always a problem when writing Python. I get around this problem by setting my text editor to expand all tabs with spaces when editing Python, but I have had problems when coworkers have not done this. Don't get me wrong, I love working in Python. It is one of my favorite languages, but it, like all other languages, is not perfect. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From Michael.Coll-Barth at VerizonWireless.com Tue May 4 10:23:53 2010 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Tue, 4 May 2010 10:23:53 -0400 Subject: Django as exemplary design In-Reply-To: References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <20100504143508.07C19C70A@mail.python.org> > From: alex23 > (I also think there's value to be gained in studying _bad_ code, > too...) Oh, very true. And not just true for python. But, only if an 'expoert' points out why it is bad and provides an alternative. And saying things like, "it isn't pyhonic" or that such and such is a more "pythonic way" is NOT helpful. From prologic at shortcircuit.net.au Tue May 4 10:35:18 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 5 May 2010 00:35:18 +1000 Subject: Teaching Programming In-Reply-To: <952067.92151.qm@web58703.mail.re1.yahoo.com> References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> Message-ID: On Wed, May 5, 2010 at 12:21 AM, Ed Keith wrote: > To deal with indentation I had to > > ? 1) keep track of indentation of all chunks of code embedded in the > ? ? ?document and indent inserted chunks to the sum of all the > ? ? ?indentation of the enclosing chunks. In my experience of non-indentation sensitive languages such as C-class (curly braces) it's just as hard to keep track of opening and closing braces. --James From bazwal at ftml.net Tue May 4 10:38:23 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 04 May 2010 15:38:23 +0100 Subject: [OT] strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> Message-ID: <4BE0315F.6090607@ftml.net> On 04/05/10 03:25, Grant Edwards wrote: > On 2010-05-04, Charles wrote: > >>> I don't see how it's inelegant at all. Perhaps it's >>> counter-intuitive if you don't understand how a Unix filesystem >>> works, but the underlying filesystem model is very simple, regular, >>> and elegant. >>> >>>> but probably makes some bit of the OS's job slightly easier and is >>>> usually good enough in practice. Pragmatism is a bitch sometimes. :-) >>> >> >> I agree that the Unix file system is quite elegant, but can be >> counter-intuitive for people who are used to the "one file, one name" >> paradigm. > > I guess I've been using Unix for too long (almost 30 years). I don't > think I was consciously aware of a "one file, one name" paradigm. Is > that a characteristic of Dos, Windows or Mac filesystems? > >> [...] > >> In the OP's case, references to the directory have been removed from >> the file system, but his process still has the current working >> directory reference to it, so it has not actually been deleted. When >> he opens "../abc.txt", the OS searches the current directory for ".." >> and finds the inode for /home/baz/tmp, then searches that directory >> (/home/baz/tmp) for abc.txt and finds it. > > Exactly. I probably should have taken the time to explain that as > well as you did. One forgets that there are a log of new Unix users > who've never been taught how the filesystem works. actually, what i failed to grok is that whatever '..' refers to is all that is needed to find the file 'abc.txt' *even if the current directory has been deleted*. an absolute path just isn't needed. this has really got nothing to do with how unix filesystems work per se or "one file, one name", but more to do with simple reference counting. when i mentioned in my original post how windows handles attempts to delete the cwd differently, i should have put two and two together and figured this all out for myself. but i don't think it's immediately obvious what the consequences of (re)moving the cwd are, even if you've been using unix filesystems for a while. in know for a fact that i have used several linux programs in the past that didn't handle this possiblity gracefully, so it's not just new users that can be caught out by this. From invalid at invalid.invalid Tue May 4 10:55:52 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 4 May 2010 14:55:52 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEDC73.1020301@ftml.net> <84a2djFjqrU1@mid.individual.net> Message-ID: On 2010-05-04, Gregory Ewing wrote: > Grant Edwards wrote: > >> except that Python objects can form a generalized graph, and Unix >> filesystems are constrained to be a tree. > > Actually I believe that root is allowed to create arbitrary > hard links to directories in Unix, I know that used to be the case in SunOS (as I found out the hard way), but I've been told by Solaris experts that it is no longer allowed. I was also under the impression that it wasn't allowed in Linux, but I've never tried it. According the the Linux ln (1) man page: -d, -F, --directory allow the superuser to attempt to hard link directories (note: will probably fail due to system restrictions, even for the superuser) > so it's possible to turn the file system in to a general graph. It's > highly unrecommended, though, because it confuses the heck out of > programs that recursively traverse directories (which is why only > root is allowed to do it). It sure caused trouble when I did it on a SunOS system back in the day (1990 or thereabouts). -- Grant Edwards grant.b.edwards Yow! I feel like I'm at in a Toilet Bowl with a gmail.com thumbtack in my forehead!! From andreengels at gmail.com Tue May 4 11:00:11 2010 From: andreengels at gmail.com (Andre Engels) Date: Tue, 4 May 2010 17:00:11 +0200 Subject: Teaching Programming In-Reply-To: References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> Message-ID: On Tue, May 4, 2010 at 4:35 PM, James Mills wrote: > On Wed, May 5, 2010 at 12:21 AM, Ed Keith wrote: >> To deal with indentation I had to >> >> ? 1) keep track of indentation of all chunks of code embedded in the >> ? ? ?document and indent inserted chunks to the sum of all the >> ? ? ?indentation of the enclosing chunks. > > In my experience of non-indentation sensitive languages > such as C-class (curly braces) it's just as hard to keep track > of opening and closing braces. Although I have little or no experience with this, I still dare to say that I don't agree. The difference is that in C you do not _need_ to know where in the braces-defined hierarchy you are. You just embed or change a piece of code at the right location. In Python however you _do_ need to know how far your code is to be indented. -- Andr? Engels, andreengels at gmail.com From e_d_k at yahoo.com Tue May 4 11:11:20 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 08:11:20 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <915747.23422.qm@web58705.mail.re1.yahoo.com> --- On Tue, 5/4/10, James Mills wrote: > From: James Mills > Subject: Re: Teaching Programming > To: "python list" > Date: Tuesday, May 4, 2010, 10:35 AM > On Wed, May 5, 2010 at 12:21 AM, Ed > Keith > wrote: > > To deal with indentation I had to > > > > ? 1) keep track of indentation of all chunks of code > embedded in the > > ? ? ?document and indent inserted chunks to the sum > of all the > > ? ? ?indentation of the enclosing chunks. > > In my experience of non-indentation sensitive languages > such as C-class (curly braces) it's just as hard to keep > track > of opening and closing braces. > > --James > -- > http://mail.python.org/mailman/listinfo/python-list > Not in this case, because the user is required to include all text of the program in the chunks, the tools does not generate any text, It only needs to generate white space if the language is white space sensitive. I can see how it could be a problem in other cases. In the interest of completeness, I should mention that I had to take care not to introduce extraneous line breaks for languages that are sensitive to them. It is much easier to generate code for languages that are completely white space agnostic. I actually find the fact that I need to think about where I can, and where I can not, break a line to be a bigger problem when write code, than keeping track of indentation level. And Python is not the only language that has this problem. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From e_d_k at yahoo.com Tue May 4 11:14:57 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 08:14:57 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <472414.98152.qm@web58708.mail.re1.yahoo.com> --- On Tue, 5/4/10, Andre Engels wrote: > From: Andre Engels > Subject: Re: Teaching Programming > To: "James Mills" > Cc: "python list" > Date: Tuesday, May 4, 2010, 11:00 AM > On Tue, May 4, 2010 at 4:35 PM, James > Mills > > wrote: > > On Wed, May 5, 2010 at 12:21 AM, Ed Keith > wrote: > >> To deal with indentation I had to > >> > >> ? 1) keep track of indentation of all chunks of > code embedded in the > >> ? ? ?document and indent inserted chunks to the > sum of all the > >> ? ? ?indentation of the enclosing chunks. > > > > In my experience of non-indentation sensitive > languages > > such as C-class (curly braces) it's just as hard to > keep track > > of opening and closing braces. > > Although I have little or no experience with this, I still > dare to say > that I don't agree. The difference is that in C you do not > _need_ to > know where in the braces-defined hierarchy you are. You > just embed or > change a piece of code at the right location. In Python > however you > _do_ need to know how far your code is to be indented. > > For a programmer, it is harder to keep track of braced. For a code generator, it is harder to keep track of indentation. It is a matter of which you are more interested in catering to. Python is easier to write, C is easier to generate. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From ethan at stoneleaf.us Tue May 4 11:28:08 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 04 May 2010 08:28:08 -0700 Subject: Teaching Programming In-Reply-To: References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> Message-ID: <4BE03D08.1080108@stoneleaf.us> Andre Engels wrote: > On Tue, May 4, 2010 at 4:35 PM, James Mills > wrote: >> On Wed, May 5, 2010 at 12:21 AM, Ed Keith wrote: >>> To deal with indentation I had to >>> >>> 1) keep track of indentation of all chunks of code embedded in the >>> document and indent inserted chunks to the sum of all the >>> indentation of the enclosing chunks. >> In my experience of non-indentation sensitive languages >> such as C-class (curly braces) it's just as hard to keep track >> of opening and closing braces. > > Although I have little or no experience with this, I still dare to say > that I don't agree. The difference is that in C you do not _need_ to > know where in the braces-defined hierarchy you are. You just embed or > change a piece of code at the right location. In Python however you > _do_ need to know how far your code is to be indented. And how do you know where the right location is? You have to figure it out from the different (nested) braces at the 'right' location. For me, at least, it's much easier to get that information from the already indented Python code, as opposed to indenting (and double-checking the indents) on the braces language. ~Ethan~ From nospam at nospam.com Tue May 4 11:28:26 2010 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 04 May 2010 17:28:26 +0200 Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> <4bdf993e$0$1669$742ec2ed@news.sonic.net> <11247616-b5da-4494-bf83-1d7416c8dbef@g5g2000pre.googlegroups.com> Message-ID: On Mon, 3 May 2010 23:07:08 -0700 (PDT), Bryan wrote: >I love SQLite because it solves problems I actually have. For the vast >majority of code I write, "lite" is a good thing, and lite as it is, >SQLite can handle several transactions per second. I give SQLite a >file path and in a split second I have a relational, transactional >database. Great. I did not want to configure a server and I sure did >not want to inflict complexity upon my users. Exactly. I need a safe way to share an SQLite database among a few years, but sharing a drive isn't safe but I also don't need a full-fledged DBMS like MySQL. At this point, as an alternative to a Python-based solution, it seems like Mongoose + Lua + SQLite could do the trick. From stefan_ml at behnel.de Tue May 4 11:33:33 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 17:33:33 +0200 Subject: Teaching Programming In-Reply-To: <121607.77893.qm@web58702.mail.re1.yahoo.com> References: <121607.77893.qm@web58702.mail.re1.yahoo.com> Message-ID: Ed Keith, 04.05.2010 15:19: > --- On Tue, 5/4/10, Stefan Behnel wrote: >> Ed Keith, 04.05.2010 14:15: >>> Python is a great language to write in (although I do >>> wish it did a better job with closures). But it is a PITA to >>> generate code for! >> >> Interesting. Could you elaborate a bit? Could you give a >> short example of what kind of document text you translate >> into what kind of Python code, and what the problems were >> that you faced in doing so? > > The program is written using itself. If you click on the link above you > will see an HTML file that fully describes the program. I did. I find it a bit hard to read due to the block splitting (basically like 'include' based spaghetti programming), but so far, the actual code that does the code merging looks pretty simple and I can't figure out where the "PITA" bit is on that page. That's why I asked. Stefan From stefan_ml at behnel.de Tue May 4 11:37:50 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 17:37:50 +0200 Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6A3B87357@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> <7F0503CD69378F49BE0DC30661C6CCF6A3B87357@enbmail01.lsi.com> Message-ID: Barak, Ron, 04.05.2010 16:11: >>> I'm parsing XML files using ElementTree from xml.etree (see code >>> below (and attached xml_parse_example.py)). >>> >>> However, I'm coming across input XML files (attached an example: >>> tmp.xml) which include invalid characters, that produce the >>> following traceback: >>> >>> $ python xml_parse_example.py >>> Traceback (most recent call last): >>> xml.parsers.expat.ExpatError: not well-formed (invalid >>> token): line 6, column 34 >> >> I hope you are aware that this means that the input you are >> parsing is not XML. It's best to reject the file and tell the >> producers that they are writing broken output files. You >> should always fix the source, instead of trying to make sense >> out of broken input in fragile ways. >> > The XML file seems to be valid XML (all XML viewers I tried were able to read it). This is what xmllint gives me: ----------------------- $ xmllint /home/sbehnel/tmp.xml tmp.xml:6: parser error : Char 0x0 out of allowed range "MainStorage_snap ^ tmp.xml:6: parser error : Premature end of data in tag m_sanApiName1 line 6 "MainStorage_snap ^ tmp.xml:6: parser error : Premature end of data in tag DbHbaGroup line 5 "MainStorage_snap ^ tmp.xml:6: parser error : Premature end of data in tag database line 4 "MainStorage_snap ^ ----------------------- The file contains 0-bytes - clearly not XML. Stefan From e_d_k at yahoo.com Tue May 4 11:43:22 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 08:43:22 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <304036.63124.qm@web58706.mail.re1.yahoo.com> --- On Tue, 5/4/10, Stefan Behnel wrote: > From: Stefan Behnel > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 11:33 AM > Ed Keith, 04.05.2010 15:19: > > --- On Tue, 5/4/10, Stefan Behnel wrote: > >> Ed Keith, 04.05.2010 14:15: > >>> Python is a great language to write in > (although I do > >>> wish it did a better job with closures). But > it is a PITA to > >>> generate code for! > >> > >> Interesting. Could you elaborate a bit? Could you > give a > >> short example of what kind of document text you > translate > >> into what kind of Python code, and what the > problems were > >> that you faced in doing so? > > > > The program is written using itself. If you click on > the link above you > > will see an HTML file that fully describes the > program. > > I did. I find it a bit hard to read due to the block > splitting (basically like 'include' based spaghetti > programming), but so far, the actual code that does the code > merging looks pretty simple and I can't figure out where the > "PITA" bit is on that page. That's why I asked. > > Stefan > > -- http://mail.python.org/mailman/listinfo/python-list > The PITA is having to keep track of the indentation of each embedded chunk and summing it for each level of indentation. This requires a fair amount of bookkeeping that would not otherwise be necessary. The original prototype simply replaced each embedded chunk with the text from the chunk definition, all indenting information was lost. It worked for most languages, but not Python. In testing the program I used two languages, Python and J. I figured if I could make both of them work I would not have any problem with anything else. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From wuwei23 at gmail.com Tue May 4 11:45:32 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 May 2010 08:45:32 -0700 (PDT) Subject: Teaching Programming References: Message-ID: <5512eb07-b589-4f18-9ccf-634efc7c6f70@u3g2000prl.googlegroups.com> Ed Keith wrote: > Tabs are always a problem when writing Python. I get > around this problem by setting my text editor to expand > all tabs with spaces when editing Python, but I have had > problems when coworkers have not done this. It's best not to trust others to do the right thing. I do trust Tools/ scripts/reindent.py more though :) > Don't get me wrong, I love working in Python. It is one > of my favorite languages, but it, like all other languages, > is not perfect. I was genuinely interested in the problems you hit as I have some hazy projects in mind that I was planning on trying to handle via code generation. Context managers seem the best place to first try dealing with it. If you're interested I can keep you posted when I finally have some working code. Cheers for the clarification. From darcy at druid.net Tue May 4 11:49:25 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 May 2010 11:49:25 -0400 Subject: Teaching Programming In-Reply-To: References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> Message-ID: <20100504114925.af9e3224.darcy@druid.net> On Wed, 5 May 2010 00:35:18 +1000 James Mills wrote: > In my experience of non-indentation sensitive languages > such as C-class (curly braces) it's just as hard to keep track > of opening and closing braces. Harder. That was the big "Aha!" for me with Python. My first programming language was Fortran in 1969 so when I saw indentation as syntax I also recoiled in horror for about 0.5 seconds. However, I immediately realized that from now on I could be sure that if it looked right then it was right. for (x = 0; x++; x < 10); printf("Current number is %d\n", x); Or... for (x = 0; x++; x < 10); { printf("Current number is %d\n", x); } Oops. Looks right but isn't. Try to make that mistake in Python. Note untested - I wasn't about to fire up an editor, create a C program, add the includes, compile and run the a.out just to test this. Another way that Python excels. However, I am pretty sure that the above would compile. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From stefan_ml at behnel.de Tue May 4 11:52:30 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 17:52:30 +0200 Subject: Teaching Programming In-Reply-To: <304036.63124.qm@web58706.mail.re1.yahoo.com> References: <304036.63124.qm@web58706.mail.re1.yahoo.com> Message-ID: Ed Keith, 04.05.2010 17:43: > The PITA is having to keep track of the indentation of each embedded > chunk and summing it for each level of indentation. This requires a fair > amount of bookkeeping that would not otherwise be necessary. > > The original prototype simply replaced each embedded chunk with the text > from the chunk definition, all indenting information was lost. It worked > for most languages, but not Python. > > In testing the program I used two languages, Python and J. Well, then both of the language generators have benefited from your effort because the generated complete code is properly indented and therefore much more readable during debugging. I'd say it was worth it. Stefan From utente at esempio.net Tue May 4 11:55:20 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 17:55:20 +0200 Subject: Teaching Programming In-Reply-To: <4be01df4$0$1134$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> <4be01df4$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4be0436a$0$1125$4fafbaef@reader3.news.tin.it> superpollo ha scritto: > Stefan Behnel ha scritto: >> superpollo, 04.05.2010 14:46: >>> my template system wants >>> the input to generate the code to stay on a single line ( don't ask >>> :-( ) >> >> I hope you don't mind if I still ask. What are you generating and for >> what templating system? > > ok, since you asked for it, prepare yourself for a bit of a horror story > ;-) > > i will answer in my next post ok here it is. i am not a programmer or it-guy in the first place; my job is as a high school teacher in a field only remotely connected with computers (math and physics). since i have some kind of computer literacy (as opposed to most of my colleagues), some years ago i was kindly asked to try and solve a "simple" particular problem, that is to write a program that generates math exercises (q+a) from an example taken from the textbook. for instance, this: %%TITLE:Sample worksheet %% %%SCHEMA:\lim_{x \to } %%SCHEMA:\frac %%SCHEMA:{x^3-x^2-x} %%SCHEMA:{x^3-x^2+x-}\\ %% %%ANS:FRAC %%ANSNUM: %%ANSDEN: %% %%AMIN:1 %%AINC:1 %%AMAX:2 %%BMIN:3 %%BINC:1 %%BMAX:4 %%CMIN:2 %%CINC:1 %%CMAX:3 should generate this latex source document: \documentclass[a4paper,10pt,twocolumn,fleqn]{article} \title{Sample worksheet} \pagestyle{empty} \usepackage[italian]{babel} \usepackage{amsmath} \usepackage{amssymb} \usepackage{cancel} \usepackage{mathrsfs} \usepackage[dvips]{graphicx} \usepackage{eurosym} \usepackage{pstricks} \usepackage{pst-eucl} \usepackage{pst-poly} \usepackage{pst-plot} \frenchspacing \begin{document} \section*{\center{\framebox{Sample worksheet}}} \noindent \begin{enumerate} \item \begin{multline*} \lim_{x \to 1} \frac {x^3+3x^2-4x} {x^3-x^2+2x-2}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 2} \frac {x^3+x^2-6x} {x^3-2x^2+2x-4}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 2} \frac {x^3+2x^2-8x} {x^3-2x^2+2x-4}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 1} \frac {x^3+2x^2-3x} {x^3-x^2+2x-2}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 1} \frac {x^3+2x^2-3x} {x^3-x^2+3x-3}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 1} \frac {x^3+3x^2-4x} {x^3-x^2+3x-3}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 2} \frac {x^3+x^2-6x} {x^3-2x^2+3x-6}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 2} \frac {x^3+2x^2-8x} {x^3-2x^2+3x-6}\\ \end{multline*} \end{enumerate} \subsection*{\center{Answers}} \begin{enumerate} \item \begin{displaymath} \frac{5}{3} \end{displaymath} \item \begin{displaymath} \frac{5}{3} \end{displaymath} \item \begin{displaymath} 2 \end{displaymath} \item \begin{displaymath} \frac{4}{3} \end{displaymath} \item \begin{displaymath} 1 \end{displaymath} \item \begin{displaymath} \frac{5}{4} \end{displaymath} \item \begin{displaymath} \frac{10}{7} \end{displaymath} \item \begin{displaymath} \frac{12}{7} \end{displaymath} \end{enumerate} \end{document} which in turn can be used to generate the following pdf file: http://www.datafilehost.com/download-cc88a19e.html fine huh? now, for the horror part. when i began putting down some code i thought that maybe it would take a couple of evenings to put up a working prototype, and i was w-r-o-n-g: 1) as i said i am not a professional 2) i decided to use bash shell as a core language for the parser/generator ( *sigh* ) 3) feautiritis soon crept in if some of you knows a bit about math and especially algebra, you will understand that some of the biggest problems in generating standard math notation in to cope with the various layers of traditions and innuendos: for example i could generate the string "2x" which is fine; but what about "1x" or "-1x" or "0x"? and what about plus signs at the start of an expression (normally omitted)? when does a subexpression start? etc ... there are plenty of icompatible rules and as much as exceptions ... as you can see i had many problems to solve and i am not trained to cope with such issues from a programmatic standpoint. another thing is that for some features i intended to include i found convenient to use python (since it's the language i feel i am more at ease with), so i had to cope with template lines like this: %%SCHEMA: or even worse: %%ANSFRCEMBPYC:\\ to make a long story short: the whole program is now 4775 lines of bash code, written by an unqualified amateur under time pressure; sometimes i have to hand-modify it to get certain outputs as i expect them to be; this in turn breaks other subsystems. i am ashamed to post the code, and it is a true design nightmare. also it is offtopic (being bash). *but* it was and it is a wonderful experience to learn to program, to acknowledge weaknesses end strongnesses of various approaches, to better understand the structure of math notation, problem solving end teaching techniques. it is still work in progress though, and i hope i will never see the day i have to refurbish it. i hope -- instead -- that the next time i try to attack the task i will have a better knowledge thanks to errors committed, to avoid many of the pitfalls i stumbled upon. for now, it works. *whew* i hope i was not boring, and i sincerely hope that some of you could see the depth of the problem i tried to solve (perhaps usuccesfully), end give me some professional advice as what to do for the next incarnation of my awful program. any concrete suggestion will be *very* appreciated. thank to all bye From tjreedy at udel.edu Tue May 4 12:06:10 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 12:06:10 -0400 Subject: Teaching Programming In-Reply-To: References: Message-ID: On 5/3/2010 7:46 PM, cjw wrote: > Nobody likes indentation at first, Speak for yourself, please. For two decades before I met Python, I indented code nicely whenever it was allowed. That option was one of the great advancements of Fortran77 over FortranIV. Coming from C, I was immediately glad to be done with those darn braces. tjr From darcy at druid.net Tue May 4 12:07:25 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 May 2010 12:07:25 -0400 Subject: Teaching Programming In-Reply-To: References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> Message-ID: <20100504120725.1dfdf513.darcy@druid.net> On Tue, 4 May 2010 17:00:11 +0200 Andre Engels wrote: > Although I have little or no experience with this, I still dare to say > that I don't agree. The difference is that in C you do not _need_ to > know where in the braces-defined hierarchy you are. You just embed or > change a piece of code at the right location. In Python however you > _do_ need to know how far your code is to be indented. Well, I'm afraid your lack of experience shows. Experienced C coders will tell you that one of the most annoying things is counting braces to make sure that you have the right number in the right places. In fact, they add indentation so that they can use the visual layout to check the brace layout. Braces are the added step. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From clp2 at rebertia.com Tue May 4 12:11:44 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 May 2010 09:11:44 -0700 Subject: Teaching Programming In-Reply-To: <20100504114925.af9e3224.darcy@druid.net> References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> <20100504114925.af9e3224.darcy@druid.net> Message-ID: On Tue, May 4, 2010 at 8:49 AM, D'Arcy J.M. Cain wrote: > On Wed, 5 May 2010 00:35:18 +1000 > James Mills wrote: >> In my experience of non-indentation sensitive languages >> such as C-class (curly braces) it's just as hard to keep track >> of opening and closing braces. > > Harder. ?That was the big "Aha!" for me with Python. ?My first > programming language was Fortran in 1969 so when I saw indentation as > syntax I also recoiled in horror for about 0.5 seconds. The amount of mental scaring that Fortran has caused regarding indentation is astounding. Maybe the PSF should run re-education camps for Fortran programmers... :P > However, I > immediately realized that from now on I could be sure that if it looked > right then it was right. > > ? ?for (x = 0; x++; x < 10); > ? ? ? ?printf("Current number is %d\n", x); > > Or... > > ? ?for (x = 0; x++; x < 10); > ? ?{ > ? ? ? ?printf("Current number is %d\n", x); > ? ?} > > Oops. ?Looks right but isn't. ?Try to make that mistake in Python. Technically, that pitfall /could/ be eliminated if curly-braces languages simply always required the curly-braces for bodies and stopped special-casing the null body case, in which case both your examples would be syntax errors. Removing the special-casing of single-line bodies too would remove a further class of errors. However, I've yet to encounter a language that takes such an approach. Quite a pity. Cheers, Chris -- I've thought a lot about this. http://blog.rebertia.com/2010/01/24/of-braces-and-semicolons/ From clp2 at rebertia.com Tue May 4 12:13:38 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 May 2010 09:13:38 -0700 Subject: Teaching Programming In-Reply-To: References: <304036.63124.qm@web58706.mail.re1.yahoo.com> Message-ID: On Tue, May 4, 2010 at 8:52 AM, Stefan Behnel wrote: > Ed Keith, 04.05.2010 17:43: >> The PITA is having to keep track of the indentation of each embedded >> chunk and summing it for each level of indentation. This requires a fair >> amount of bookkeeping that would not otherwise be necessary. >> >> The original prototype simply replaced each embedded chunk with the text >> from the chunk definition, all indenting information was lost. It worked >> for most languages, but not Python. >> >> In testing the program I used two languages, Python and J. > > Well, then both of the language generators have benefited from your effort > because the generated complete code is properly indented and therefore much > more readable during debugging. I'd say it was worth it. Though there are auto-re-indenting programs for curly-brace languages you know. Cheers, Chris -- http://blog.rebertia.com From tjreedy at udel.edu Tue May 4 12:15:17 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 12:15:17 -0400 Subject: Teaching Programming In-Reply-To: <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> Message-ID: On 5/4/2010 8:46 AM, superpollo wrote: > but i do not think i can use it myself, since my template system wants > the input to generate the code to stay on a single line ( don't ask :-( ) I think we can agree that Python (unlike C, for instance) is not good for writing non-humanly-readable one-unbounded-length-line code. That is contrary to its design goal. But I would think that you would have similar problems with other manditorily multiline languages, like Fortran and Basic. Terry Jan Reedy From davea at ieee.org Tue May 4 12:22:08 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 04 May 2010 12:22:08 -0400 Subject: Teaching Programming In-Reply-To: <4BE03D08.1080108@stoneleaf.us> References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> <4BE03D08.1080108@stoneleaf.us> Message-ID: <4BE049B0.1060805@ieee.org> Ethan Furman wrote: >
Andre > Engels wrote: >> On Tue, May 4, 2010 at 4:35 PM, James Mills >> wrote: >>> On Wed, May 5, 2010 at 12:21 AM, Ed Keith wrote: >>>> To deal with indentation I had to >>>> >>>> 1) keep track of indentation of all chunks of code embedded in the >>>> document and indent inserted chunks to the sum of all the >>>> indentation of the enclosing chunks. >>> In my experience of non-indentation sensitive languages >>> such as C-class (curly braces) it's just as hard to keep track >>> of opening and closing braces. >> >> Although I have little or no experience with this, I still dare to say >> that I don't agree. The difference is that in C you do not _need_ to >> know where in the braces-defined hierarchy you are. You just embed or >> change a piece of code at the right location. In Python however you >> _do_ need to know how far your code is to be indented. > > And how do you know where the right location is? You have to figure > it out from the different (nested) braces at the 'right' location. > For me, at least, it's much easier to get that information from the > already indented Python code, as opposed to indenting (and > double-checking the indents) on the braces language. > > ~Ethan~ > > Much more important to be able to read code reliably than write it quickly. When I was heavily doing C++ I found myself wishing that incorrect indentation would be an error or at least a warning. And I hadn't ever heard of Python. When I did, I said "About time!" Of course, I was surrounded by many programmers who ignored any warning that the compiler produced, while I cranked up warnings to max, with pedantic. On one project I generated C++ code, about 20k lines. And it was all indented and commented. Most of that code went through the code generator twice. The "source" was a header file from outside my organization. The generator used that to create a new header, more detailed. Then the generator used that to create source & headers that were actually used by the project. DaveA From gherron at islandtraining.com Tue May 4 12:23:58 2010 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 04 May 2010 09:23:58 -0700 Subject: Teaching Programming In-Reply-To: References: Message-ID: <4BE04A1E.7040903@islandtraining.com> Terry Reedy wrote: > On 5/3/2010 7:46 PM, cjw wrote: > >> Nobody likes indentation at first, > > Speak for yourself, please. For two decades before I met Python, I > indented code nicely whenever it was allowed. That option was one of > the great advancements of Fortran77 over FortranIV. Coming from C, I > was immediately glad to be done with those darn braces. > > tjr > Right. Somewhere in the 80's I read a paper in sigplan which demonstrated that indentation-only was sufficient to communicate the structure of a program. I immediately *knew* that was the right way to go. Sadly, I had to wait a decade or so before discovering Python in the mid 90's, but I never forgot that paper nor lost my eager anticipation waiting for language design to catch up with that idea. Gary Herron From stefan_ml at behnel.de Tue May 4 12:30:46 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 18:30:46 +0200 Subject: Teaching Programming In-Reply-To: <4be0436a$0$1125$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> <4be01df4$0$1134$4fafbaef@reader3.news.tin.it> <4be0436a$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: superpollo, 04.05.2010 17:55: > since i have some kind of computer literacy (as opposed to most of my > colleagues), some years ago i was kindly asked to try and solve a > "simple" particular problem, that is to write a program that generates > math exercises (q+a) from an example taken from the textbook. for > instance, this: > > %%TITLE:Sample worksheet > %% > %%SCHEMA:\lim_{x \to } > %%SCHEMA:\frac > %%SCHEMA:{x^3-x^2-x} > %%SCHEMA:{x^3-x^2+x-}\\ > %% > %%ANS:FRAC > %%ANSNUM: > %%ANSDEN: > %% > %%AMIN:1 > %%AINC:1 > %%AMAX:2 > %%BMIN:3 > %%BINC:1 > %%BMAX:4 > %%CMIN:2 > %%CINC:1 > %%CMAX:3 > > should generate this latex source document: > > \documentclass[a4paper,10pt,twocolumn,fleqn]{article} > \title{Sample worksheet} > \pagestyle{empty} > \usepackage[italian]{babel} > \usepackage{amsmath} > \usepackage{amssymb} > \usepackage{cancel} > \usepackage{mathrsfs} > \usepackage[dvips]{graphicx} > \usepackage{eurosym} > \usepackage{pstricks} > \usepackage{pst-eucl} > \usepackage{pst-poly} > \usepackage{pst-plot} > \frenchspacing > \begin{document} > \section*{\center{\framebox{Sample worksheet}}} > \noindent > \begin{enumerate} > \item > \begin{multline*} > \lim_{x \to 1} > \frac > {x^3+3x^2-4x} > {x^3-x^2+2x-2}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 2} > \frac > {x^3+x^2-6x} > {x^3-2x^2+2x-4}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 2} > \frac > {x^3+2x^2-8x} > {x^3-2x^2+2x-4}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 1} > \frac > {x^3+2x^2-3x} > {x^3-x^2+2x-2}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 1} > \frac > {x^3+2x^2-3x} > {x^3-x^2+3x-3}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 1} > \frac > {x^3+3x^2-4x} > {x^3-x^2+3x-3}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 2} > \frac > {x^3+x^2-6x} > {x^3-2x^2+3x-6}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 2} > \frac > {x^3+2x^2-8x} > {x^3-2x^2+3x-6}\\ > \end{multline*} > \end{enumerate} > \subsection*{\center{Answers}} > \begin{enumerate} > \item > \begin{displaymath} > \frac{5}{3} > \end{displaymath} > \item > \begin{displaymath} > \frac{5}{3} > [...] I'm not exactly sure I understand the mapping between the two formats, but it seems to me that you'll need a proper math expression parser (with a strong emphasis on *parser*) for this. Math expressions are not exactly trivial (recursion, prefix/infix/postfix notations, functions), which is why 'real' programmers don't write parsers for them but download tested, working code for that from somewhere. > another thing is that for some features i intended to include i found > convenient to use python (since it's the language i feel i am more at > ease with), so i had to cope with template lines like this: > > %%SCHEMA: You should assure that the math module is always imported, and otherwise restrict the expressiveness to expressions (terms that result in a value), not arbitrary statements (executable commands that do things without returning anything). > to make a long story short: the whole program is now 4775 lines of bash > code, Argh! > *but* it was and it is a wonderful experience to learn to program It does sound like you almost completely skipped over two very important programming lessons, though: reading code is harder than writing it (i.e. maintenance cost matters), and the best code is the code that you don't need to write (and debug and maintain). Stefan From tjreedy at udel.edu Tue May 4 12:31:06 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 12:31:06 -0400 Subject: HTTP server + SQLite? In-Reply-To: <11247616-b5da-4494-bf83-1d7416c8dbef@g5g2000pre.googlegroups.com> References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> <4bdf993e$0$1669$742ec2ed@news.sonic.net> <11247616-b5da-4494-bf83-1d7416c8dbef@g5g2000pre.googlegroups.com> Message-ID: On 5/4/2010 2:07 AM, Bryan wrote: > The SQLite developers state the situation brilliantly at > http://www.sqlite.org/whentouse.html: For future reference, that link does not work with Thunderbird. This one does. http://www.sqlite.org/whentouse.html When posting links, best to put them on a line by themselves, with NO punctuation, even if 'proper' English seems to require it. A space before the colon probably would have worked too, if its complete absence bothers one too much ;=). Terry Jan Reedy From mensanator at aol.com Tue May 4 12:50:47 2010 From: mensanator at aol.com (Mensanator) Date: Tue, 4 May 2010 09:50:47 -0700 (PDT) Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: <11022b40-3360-4725-aac4-24b0d07df16c@i9g2000yqi.googlegroups.com> On May 3, 10:17?am, s... at sig.for.address (Victor Eijkhout) wrote: > I have two long ints, both too long to convert to float, but their ratio > is something reasonable. How can I compute that? The obvious "(1.*x)/y" > does not work. You could try using the gmpy module. It supports arbitrary precision floats, so converting long to float is no problem. YY = 3**10684 float(YY) Traceback (most recent call last) File "pyshell#78>", line 1, in float(YY) OverflowError: Python int too large to convert to C double import gmpy gmpy.mpf(YY) mpf('3.6600365709...0197681e5097',16936) > > Victor. > > -- > Victor Eijkhout -- eijkhout at tacc utexas edu From robin1 at cnsp.com Tue May 4 13:32:26 2010 From: robin1 at cnsp.com (Robin) Date: Tue, 4 May 2010 10:32:26 -0700 (PDT) Subject: scrolledtext download location Message-ID: Does anyone know where I can download the ScrolledText tkintewr widget, looked all over for it and had no luck, Thanks, -Robin From tjreedy at udel.edu Tue May 4 13:32:39 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 13:32:39 -0400 Subject: Recursive functions not returning lists as expected In-Reply-To: References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: On 5/4/2010 1:45 AM, rickhg12hs wrote: > On May 4, 1:34 am, Cameron Simpson wrote: >> On 03May2010 22:02, rickhg12hs wrote: >> | Would a kind soul explain something basic to a python noob? >> | >> | Why doesn't this function always return a list? >> | >> | def recur_trace(x,y): >> | print x,y >> | if not x: >> | return y >> | recur_trace(x[1:], y + [x[0]]) >> >> You need: >> return recur_trace(x[1:], y + [x[0]]) >> >> Otherwise the function returns None. > > Ah, an explicit "return" is required. Thanks! > [To bad there's no tail recursion optimization.] 8-( That issue is much more complicated than you probably imagine. Here is part of it, using your toy example of computing y +x. [Code snippets below are untested and might have typos.] Write your tail recursive function with the recursive branch first: def t_r(x,y): if x: return t_r(x[1:], y+[x[0]]) else: return y and the conversion ('optimization') to while form is trivial: def t_w(x,y): while x: x,y = x[1:], y+[x[0]] else: return y Of course, most would omit the 'else:', which I left to emphasize the paralellism. More importantly, 'while' loops are relatively rare in Python because scanning an iterable (a typical use of tail recursion) can be and usually is done (generically) with for loops instead: def t_f(x,y): for o in x: y = y + [o] return y Of course, this, like your original code, wastefully creates numerous temporary lists (two per iteration) when only one new list is needed for the entire process. This is easily fixed in the loop version: def t_f2(x,y): r = y[:] for o in x: r.append(o) return r Making that important fix in the recursive version is harder since the copying should be done exactly once, and not with every recursive call. I leave it to you to try either of the two main approaches. Terry Jan Reedy From see at sig.for.address Tue May 4 13:35:29 2010 From: see at sig.for.address (Victor Eijkhout) Date: Tue, 4 May 2010 12:35:29 -0500 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> <11022b40-3360-4725-aac4-24b0d07df16c@i9g2000yqi.googlegroups.com> Message-ID: <1jhyw5q.1jzuq46ob9mwgN%see@sig.for.address> Mensanator wrote: > You could try using the gmpy module. It supports arbitrary precision > floats, so converting long to float is no problem. I fear I may actually have to go symbolic. I'm now having to use the 12th root of 2, and I would like the twelfth power of that to be exactly 2. Victor. -- Victor Eijkhout -- eijkhout at tacc utexas edu From tjreedy at udel.edu Tue May 4 13:43:16 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 13:43:16 -0400 Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? In-Reply-To: References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> <7F0503CD69378F49BE0DC30661C6CCF6A3B87357@enbmail01.lsi.com> Message-ID: On 5/4/2010 11:37 AM, Stefan Behnel wrote: > Barak, Ron, 04.05.2010 16:11: >> The XML file seems to be valid XML (all XML viewers I tried were able >> to read it). From Internet Explorer: The XML page cannot be displayed Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later. -------------------------------------------------------------------------------- An invalid character was found in text content. Error processing resource 'file:///C:/Documents and Settings... "BROLB21 > This is what xmllint gives me: > > ----------------------- > $ xmllint /home/sbehnel/tmp.xml > tmp.xml:6: parser error : Char 0x0 out of allowed range > "MainStorage_snap > ^ > tmp.xml:6: parser error : Premature end of data in tag m_sanApiName1 line 6 > "MainStorage_snap > ^ > tmp.xml:6: parser error : Premature end of data in tag DbHbaGroup line 5 > "MainStorage_snap > ^ > tmp.xml:6: parser error : Premature end of data in tag database line 4 > "MainStorage_snap > ^ > ----------------------- > > The file contains 0-bytes - clearly not XML. IE agrees. From rouslank at msn.com Tue May 4 13:46:29 2010 From: rouslank at msn.com (Rouslan Korneychuk) Date: Tue, 04 May 2010 13:46:29 -0400 Subject: new extension generator for C++ In-Reply-To: References: Message-ID: <4BE05D75.7030301@msn.com> On 05/04/2010 03:06 AM, Samuel Williams wrote: > Dear Rouslan, > > It looks interesting. I say go for it. You will learn something and might make some improvements on existing ideas. > > I recommend putting the code on www.github.com > > Kind regards, > Samuel > > Thanks for the suggestion. I think I'll do just that. The "social" aspect sounds interesting, since up until now, this project has been a solitary exercise. On 05/04/2010 01:51 AM, Stefan Behnel wrote: > Last I heard, that was basically what PyBindGen does (and probably some > other existing binding generators). You should take a look at them > before investing too much time into a duplicated effort. > > Also, if you're interested in performance, you should take a look at > Cython, which is an optimising compiler for (basically) Python code that > can talk to C, C++ and Fortran code. It's been used a lot for writing > performance critical library wrappers. > > Stefan > I took a brief look at PyBindGen. I noticed a couple of things in the generated code of a test module. The PyObject definitions held a pointer to the contained datatype, which is one of the things I was trying to steer away from. It would generate a std::map for each new type, apparently to allow the contained type to be matched back to the PyObject when needed. I intend to use the same method that Boost.Python uses, sneak the pointer into the destruct functor of a shared_ptr. And when parsing arguments from an overloaded set, PyBindGen appears to generate complete separate functions for each overload and then try one after the other. The reason mine doesn't support overloaded named arguments is because it instead uses a bunch of nested if-statements to match the overload with as few checks as possible. Mine also orders the checks so that a base-class is never checked before a derived-class and that numeric types and string types are matched to their best fit (given func(double x) and func(int x), a python float value will always call func(double)). I'm not certain that PyBindGen doesn't generate code that takes this into consideration I haven't studied its code. I'll definitely take a look at how Cython handles arguments some time. It's also interesting to note that while PyBindGen will parse C++ types itself, to interpret arguments and return types, mine uses gccxml to do all the work. When given a specific overload, it will generate a dummy function with the same set of arguments in the file given to gccxml, along with typedefs for all built-in types. That way, you can specify types either explicitly, or with typedefs regardless of how the interface you want to expose does it, and my code doesn't have to do any extra work. The only question I have now is what about licensing? Is that something I need to worry about? Should I go with LGPL, MIT, or something else? And should the license be mentioned in the code or be in a single separate file at the top-level directory? From tjreedy at udel.edu Tue May 4 13:54:20 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 13:54:20 -0400 Subject: scrolledtext download location In-Reply-To: References: Message-ID: On 5/4/2010 1:32 PM, Robin wrote: > Does anyone know where I can download the ScrolledText tkintewr > widget, looked all over for it and had no luck, Since this is a module included with tkinter which is included with Python, (at least on Windows) I am puzzled. Perhaps you need to supply more info as to your problem. (3.1) Lib ref 24.4: "tkinter.scrolledtext module provides a class of the same name which implements a basic text widget which has a vertical scroll ..." From utente at esempio.net Tue May 4 13:56:56 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 19:56:56 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4be05fe9$0$1133$4fafbaef@reader3.news.tin.it> James Mills ha scritto: > On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: >> of course! *but* if i must generate on-the-fly python code that defines a >> function i am back again to the problem: > > One-liner: > > $ python > Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) > [GCC 4.4.1 (CRUX)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a, b = 2, 3 >>>> print a + b if a > b else a**b - b**2 > -1 >>>> a, b = 3, 2 >>>> print a + b if a > b else a**b - b**2 > 5 > > --James what if i want an elif clause? From tjreedy at udel.edu Tue May 4 14:13:19 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 14:13:19 -0400 Subject: py3 tkinter acceps bytes. why? In-Reply-To: References: Message-ID: On 5/4/2010 10:17 AM, Matthias Kievernagel wrote: > From: Matthias Kievernagel > Subject: py3 tkinter acceps bytes. why? > Newsgroups: comp.lang.python > Summary: > Keywords: > > In a recent thread named "py3 tkinter Text accepts what bytes?" > (google groups link: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/b75ed69f4e81b202/e2aff9ddd62d210c?lnk=raot) > I asked what kinds of bytes are accepted as tkinter parameters. > I still wonder why they are accepted at all. > Does anyone know a reason for this > or has a link to some relevant discussion? I do not remember any particular public discussion of tkinter on the dev lists. I suspect the reason is a) avoid breaking old code and b) tkinter (tk inter-face) passes params on to tk which expects byte strings. I would not be surprised if tkinter has to encode py3 (unicode) strings before passing them on. The Py3 changes were greatly complicated by the need to interface with the older bytes world. Terry Jan Reedy From utente at esempio.net Tue May 4 14:16:48 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 20:16:48 +0200 Subject: Teaching Programming In-Reply-To: <4be05fe9$0$1133$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be05fe9$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: <4be06491$0$1133$4fafbaef@reader3.news.tin.it> superpollo ha scritto: > James Mills ha scritto: >> On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: >>> of course! *but* if i must generate on-the-fly python code that >>> defines a >>> function i am back again to the problem: >> >> One-liner: >> >> $ python >> Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) >> [GCC 4.4.1 (CRUX)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> a, b = 2, 3 >>>>> print a + b if a > b else a**b - b**2 >> -1 >>>>> a, b = 3, 2 >>>>> print a + b if a > b else a**b - b**2 >> 5 >> >> --James > > what if i want an elif clause? > my first try obviously falied: >>> print a + b if a > b elif a=b "WOW" else a**b - b**2 File "", line 1 print a + b if a > b elif a=b "WOW" else a**b - b**2 ^ SyntaxError: invalid syntax From tjreedy at udel.edu Tue May 4 14:35:10 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 14:35:10 -0400 Subject: Teaching Programming In-Reply-To: References: Message-ID: On 5/4/2010 1:44 PM, Dennis Lee Bieber wrote: > On Tue, 04 May 2010 12:06:10 -0400, Terry Reedy > declaimed the following in gmane.comp.python.general: > >> Speak for yourself, please. For two decades before I met Python, I >> indented code nicely whenever it was allowed. That option was one of the >> great advancements of Fortran77 over FortranIV. Coming from C, I was >> immediately glad to be done with those darn braces. >> > What kept you from indenting FORTRAN-IV? There was a several year gap with learning of 'structured programming' in between. Perhaps ignorance of both the possibility (no one did it, that I know of) and desirability. Glass screens made consistent indentation a lot easier that with cards and teletypes. The new structured block constructs made indentation more useful, too. From utente at esempio.net Tue May 4 14:35:48 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 20:35:48 +0200 Subject: Teaching Programming In-Reply-To: <4be06491$0$1133$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be05fe9$0$1133$4fafbaef@reader3.news.tin.it> <4be06491$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: <4be06906$0$1122$4fafbaef@reader3.news.tin.it> superpollo ha scritto: > superpollo ha scritto: >> James Mills ha scritto: >>> On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: >>>> of course! *but* if i must generate on-the-fly python code that >>>> defines a >>>> function i am back again to the problem: >>> >>> One-liner: >>> >>> $ python >>> Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) >>> [GCC 4.4.1 (CRUX)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>>>>> a, b = 2, 3 >>>>>> print a + b if a > b else a**b - b**2 >>> -1 >>>>>> a, b = 3, 2 >>>>>> print a + b if a > b else a**b - b**2 >>> 5 >>> >>> --James >> >> what if i want an elif clause? >> > > my first try obviously falied: > > >>> print a + b if a > b elif a=b "WOW" else a**b - b**2 > File "", line 1 > print a + b if a > b elif a=b "WOW" else a**b - b**2 > ^ > SyntaxError: invalid syntax > ok i got it: >>> a,b=2,3 >>> print a + b if a > b else "WOW" if a < b else a**b - b**2 WOW >>> From benjamin.kaplan at case.edu Tue May 4 14:44:05 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 4 May 2010 14:44:05 -0400 Subject: Teaching Programming In-Reply-To: <4be06491$0$1133$4fafbaef@reader3.news.tin.it> References: <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be05fe9$0$1133$4fafbaef@reader3.news.tin.it> <4be06491$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: On Tue, May 4, 2010 at 2:16 PM, superpollo wrote: > superpollo ha scritto: >> >> James Mills ha scritto: >>> >>> On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: >>>> >>>> of course! *but* if i must generate on-the-fly python code that defines >>>> a >>>> function i am back again to the problem: >>> >>> One-liner: >>> >>> $ python >>> Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) >>> [GCC 4.4.1 (CRUX)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>>>>> >>>>>> a, b = 2, 3 >>>>>> print a + b if a > b else a**b - b**2 >>> >>> -1 >>>>>> >>>>>> a, b = 3, 2 >>>>>> print a + b if a > b else a**b - b**2 >>> >>> 5 >>> >>> --James >> >> what if i want an elif clause? >> > > my first try obviously falied: > >>>> print a + b if a > b elif a=b "WOW" else a**b - b**2 > ?File "", line 1 > ? ?print a + b if a > b elif a=b "WOW" else a**b - b**2 > ? ? ? ? ? ? ? ? ? ? ? ? ? ?^ > SyntaxError: invalid syntax That's because this technically isn't an if statement. It's the ternary conditional expression. If you want multiple conditions, you have to repeat the expression print a+b if a > b else "WOW" if a==b else a**b - b**2 > > -- > http://mail.python.org/mailman/listinfo/python-list > From e_d_k at yahoo.com Tue May 4 14:45:15 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 11:45:15 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <949627.90429.qm@web58701.mail.re1.yahoo.com> --- On Tue, 5/4/10, Stefan Behnel wrote: > From: Stefan Behnel > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 11:52 AM > Ed Keith, 04.05.2010 17:43: > > The PITA is having to keep track of the indentation of > each embedded > > chunk and summing it for each level of indentation. > This requires a fair > > amount of bookkeeping that would not otherwise be > necessary. > > > > The original prototype simply replaced each embedded > chunk with the text > > from the chunk definition, all indenting information > was lost. It worked > > for most languages, but not Python. > > > > In testing the program I used two languages, Python > and J. > > Well, then both of the language generators have benefited > from your effort because the generated complete code is > properly indented and therefore much more readable during > debugging. I'd say it was worth it. > > Stefan > > -- http://mail.python.org/mailman/listinfo/python-list > I agree, but some propellants of literate programming would not. Knuth wanted the generated source to be unreadable, so people would not be tempted to edit the generated code. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From dalamartr at gmail.com Tue May 4 15:12:38 2010 From: dalamartr at gmail.com (Hellnar) Date: Tue, 4 May 2010 12:12:38 -0700 (PDT) Subject: str.count algorithm Message-ID: Hello, I am trying to find what algorithm Python uses for the built-in str.count function, if it has a name. Thanks From python at rcn.com Tue May 4 15:25:30 2010 From: python at rcn.com (Raymond Hettinger) Date: Tue, 4 May 2010 12:25:30 -0700 (PDT) Subject: str.count algorithm References: Message-ID: <79750194-ec0d-4043-811d-c284cb2e011d@h20g2000prn.googlegroups.com> On May 4, 12:12?pm, Hellnar wrote: > Hello, > I am trying to find what algorithm Python uses for the built-in > str.count function, if it has a name. Roughly the same as: sum(1 for c in s if c == tgt) Raymond From __peter__ at web.de Tue May 4 15:54:58 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 May 2010 21:54:58 +0200 Subject: str.count algorithm References: <79750194-ec0d-4043-811d-c284cb2e011d@h20g2000prn.googlegroups.com> Message-ID: Raymond Hettinger wrote: > On May 4, 12:12 pm, Hellnar wrote: >> Hello, >> I am trying to find what algorithm Python uses for the built-in >> str.count function, if it has a name. > > Roughly the same as: > > sum(1 for c in s if c == tgt) That would be list.count(), I think. OP, the source http://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch.h?revision=77470&view=markup has a reference to http://effbot.org/zone/stringlib.htm Peter From rickhg12hs at gmail.com Tue May 4 16:10:16 2010 From: rickhg12hs at gmail.com (rickhg12hs) Date: Tue, 4 May 2010 13:10:16 -0700 (PDT) Subject: Recursive functions not returning lists as expected References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: On May 4, 1:32?pm, Terry Reedy wrote: > On 5/4/2010 1:45 AM, rickhg12hs wrote: [snip] > > [To bad there's no tail recursion optimization.] ?8-( > > That issue is much more complicated than you probably imagine. [snip] No imagination is necessary - functional languages (e.g., Erlang) do it quite well. From tjreedy at udel.edu Tue May 4 16:36:32 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 16:36:32 -0400 Subject: Generating nested code with context managers Message-ID: In a current thread, people have claimed that generating properly indented nested blocks is a pain because of the need to keep track of indent levels. Someone countered with the now rather ancient http://effbot.org/zone/python-code-generator.htm The usage example c = CodeGeneratorBackend() c.begin(tab=" ") c.write("for i in range(1000):\n") c.indent() c.write("print 'code generation is trivial'") c.dedent() illustrates three problems with the CodeGeneratorBackend class. 1) it requires explicit \n on all lines (which the second omits, though it is non-fatal since it is also the last) 2) the user still has to manually match indents and dedents, and 3) the user *cannot* indent lines that produce indented code. The relatively new with statement and associated context managers are designed, among other things, for this situation, where one needs to alter and restore a global context. So here is my updated (3.1) proof-of-concept version. class PyCodeGen: def __init__(self, tab=" "): self.code = [] self.tab = tab self.level = 0 # all attributes should be treated as read-only def end(self): return '\n'.join(self.code) def line(self, string): # new line self.code.append(self.tab * self.level + string) class For: def __init__(self, target, in_expression): target.line('for ' + in_expression + ':') self.target = target def __enter__(self): self.target.level += 1 def __exit__(self, t, v, tb): self.target.level -= 1 c = PyCodeGen() with For(c, 'i in range(1000)'): c.line('print("Code gen is easy")') c.line('# done') print(c.end()) # prints for i in range(1000): print("Code gen is easy") # done Note that the absence of .indent and .dedent is intentional. In a fleshed out system, there would be a context manager for each compound statement and these would handle all indents and dedents. If one really preferred to write, for instance, 'c.For(s); instead of 'For(c,s)' in the with statement, one could add a wrapper method like def For(self, s): return For(self, s) for each context manager. I left that out. Similar methods can be used to auto-match C braces and other open/close pairs. Terry Jan Reedy From tjreedy at udel.edu Tue May 4 17:23:20 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 17:23:20 -0400 Subject: Recursive functions not returning lists as expected In-Reply-To: References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: On 5/4/2010 4:10 PM, rickhg12hs wrote: > On May 4, 1:32 pm, Terry Reedy wrote: >> On 5/4/2010 1:45 AM, rickhg12hs wrote: > [snip] >>> [To bad there's no tail recursion optimization.] 8-( This is prinarily a space optimization to conserve stack frame space. The speedup would be minimal. Using while or for loops has the same space saving with better speedup (slow function are also gone) and easier optimization in other ways, as I showed. >> That issue is much more complicated than you probably imagine. > [snip] > > No imagination is necessary - functional languages (e.g., Erlang) do > it quite well. More complicated in the Python context. Does Erlang use static or dynamic name binding, or early versus late local name resolution? Python, by design, resolves global names within a function each time the function is called. So whether a call is recursive cannot be determined until the call is made. It is not difficult for CPython to space-optimize *all* tail calls, recursive or not. But this would have the bad effect of leaving gaps in error tracebacks and is not done for that reason. To only space-optimize simple recursive tail calls would take more time, and one would still lose traceback information. If you imagined all of the above, then indeed I underestimated you ;-). Terry Jan Reedy From pavlovevidence at gmail.com Tue May 4 17:27:58 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 4 May 2010 14:27:58 -0700 (PDT) Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> <4bdfce42$0$9110$426a34cc@news.free.fr> Message-ID: <4f8219ec-dd67-4889-bdf1-063ea5bad20c@o8g2000yqo.googlegroups.com> On May 4, 12:37?am, Bruno Desthuilliers wrote: > TomF a ?crit : > > > I'm interested in improving my python design by studying a large, > > well-designed codebase. ?Someone (not a python programmer) suggested > > Django. ?I realize that Django is popular, but can someone comment on > > whether its code is well-designed and worth studying? > > Carl makes some valid points in his answer, and there are indeed a > couple dark corners in this area - bit it's just a part of the whole > framework. There are still things worth studying in Django IHMO, > specially if you're interested in seeing metaclasses and descriptors at > work. Absolutely. I said it was "less than exemplary", i.e., still pretty good. Carl Banks From martin at v.loewis.de Tue May 4 17:29:06 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 04 May 2010 23:29:06 +0200 Subject: py3 tkinter acceps bytes. why? In-Reply-To: References: Message-ID: <4BE091A2.2010104@v.loewis.de> > In a recent thread named "py3 tkinter Text accepts what bytes?" > (google groups link: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/b75ed69f4e81b202/e2aff9ddd62d210c?lnk=raot) > I asked what kinds of bytes are accepted as tkinter parameters. > I still wonder why they are accepted at all. That's basically because the port from 2.x was shallow: it supports the exact same feature set that 2.x supports, with just the type names swapped. Tkinter in 2.x will already use Unicode strings in most situations. However, 2.x code would often also provide byte strings for text properties, and Tcl supports that "nicely" (*) Regards, Martin (*) I think you also asked how Tcl interprets things. IIUC, it first assumes that a byte string is UTF-8 (starting from 8.1 or so); if it's not, it then assumes that it's in the locale's encoding. If that turns out incorrect also, it just tries to pass it as-is to the operating system GUI API. Or something like that. From python at bdurham.com Tue May 4 17:37:51 2010 From: python at bdurham.com (python at bdurham.com) Date: Tue, 04 May 2010 17:37:51 -0400 Subject: Exclusively lock a file to prevent other processes from reading it? Message-ID: <1273009071.19963.1373400243@webmail.messagingengine.com> Is there a way to exclusively lock a file to prevent other processes from reading it while we have it open? I need to cache some overflow data to disk in a temp file and I want to make sure no other processes can read the contents of this file while I'm using it. I tried the following using an 'append binary' mode, but I can use NotePad to read the file while I'm using it: fd = open( r'a-temp-file.dat', 'ab' ) My environment is Python 2.6.4 (32-bit) under Windows, but I'm looking for a cross-platform solution if that's possible. Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From scott.freemire at gmail.com Tue May 4 17:40:20 2010 From: scott.freemire at gmail.com (Scott) Date: Tue, 4 May 2010 14:40:20 -0700 (PDT) Subject: Sharing a program I wrote Message-ID: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> I'm looking for suggestions on what to do (and how to do it) if I want to share a program that I wrote in Python. There seem to be quite a few places to post code and I don't know how to choose. I wrote a program (script?) that takes a text file containing the output of the "show access-list" command on a Cisco PIX/ASA/FWSM firewall and any number of text files containing syslog output from the same firewall and creates a report showing which access-list rules allowed which actual connections. It is written in Python 2.6 and runs on Windows. Since this is obviously something mankind has long been waiting for I am thinking about sharing it - but since I am new to Python and programming in general I am not at all familiar with dealing with source code. I'm sure that improvements and additions could be made if it was reviewed by "actual programmers" but I wouldn't exactly call it a "project" either. Of course I'd love to add a gui interface... I've seen pypi. It seems to index code that is posted on all sorts of sites - including pypi itself? And what is a "package" anyway? I've seen sourceforge. It looks like a good home for big applications or multi-developer projects. Freshmeat? Google code? My own website? Your blog? Another detail is that my program uses a library that was written by someone else. It is the most excellent netaddr written by David P. D. Moss and it lives at code.google.com. It uses the New BSD License. Since this library is required would I simply provide a link to it? Would I post the actual library? Do I have to post a copy of his copyright info anywhere? Please don't tell me I have to write some kind of installer that takes care of providing that. I really just want anyone who might need a little networking/security tool like this to be able to find it. Any advice? Thanks, Scott From python at bdurham.com Tue May 4 17:43:15 2010 From: python at bdurham.com (python at bdurham.com) Date: Tue, 04 May 2010 17:43:15 -0400 Subject: Generating nested code with context managers In-Reply-To: References: Message-ID: <1273009395.20712.1373401615@webmail.messagingengine.com> Terry, > So here is my updated (3.1) proof-of-concept version. Very clever! An excellent example of how to use the 'with' statement with something besides the traditional file open example. Not the original OP, but thank you anyway. Malcolm From philip at semanchuk.com Tue May 4 17:46:29 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 May 2010 17:46:29 -0400 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: <1273009071.19963.1373400243@webmail.messagingengine.com> References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: <647AB9C0-B8F3-4711-92D9-39799F248728@semanchuk.com> On May 4, 2010, at 5:37 PM, python at bdurham.com wrote: > Is there a way to exclusively lock a file to prevent other > processes from reading it while we have it open? > > I need to cache some overflow data to disk in a temp file and I > want to make sure no other processes can read the contents of > this file while I'm using it. > > I tried the following using an 'append binary' mode, but I can > use NotePad to read the file while I'm using it: > > fd = open( r'a-temp-file.dat', 'ab' ) > > My environment is Python 2.6.4 (32-bit) under Windows, but I'm > looking for a cross-platform solution if that's possible. Have a look at tempfile.mkstemp() in the standard library. From clp2 at rebertia.com Tue May 4 17:48:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 May 2010 14:48:59 -0700 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: <1273009071.19963.1373400243@webmail.messagingengine.com> References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: On Tue, May 4, 2010 at 2:37 PM, wrote: > Is there a way to exclusively lock a file to prevent other processes from > reading it while we have it open? > > I need to cache some overflow data to disk in a temp file and I want to make > sure no other processes can read the contents of this file while I'm using > it. > > I tried the following using an 'append binary' mode, but I can use NotePad > to read the file while I'm using it: > > fd = open( r'a-temp-file.dat', 'ab' ) > > My environment is Python 2.6.4 (32-bit) under Windows, but I'm looking for a > cross-platform solution if that's possible. I remember this recipe (or a variant) from the dead-tree Python Cookbook: http://code.activestate.com/recipes/65203-portalocker-cross-platform-posixnt-api-for-flock-s/ Cheers, Chris -- http://blog.rebertia.com From chris at simplistix.co.uk Tue May 4 18:07:11 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 04 May 2010 23:07:11 +0100 Subject: ooolib, reading writing a spread sheet and keep formatting In-Reply-To: <4BE09A9B.60404@free.fr> References: <4bd8cfc3$0$667$426a74cc@news.free.fr> <4BD94090.8060005@free.fr> <4BE09A9B.60404@free.fr> Message-ID: <4BE09A8F.5050803@simplistix.co.uk> News123 wrote: > Hi Chris, > > > Chris Withers wrote: >> News123 wrote: >>> from xlrd import open_workbook >>> from xlutils.copy import copy >>> >>> rb = open_workbook('doc1.xls') >> open_workbook('doc1.xls',formatting_info=True) > > I'll try, but the doc mentioned explicitely, that formulas will be lost. > I'll keep you updated. Yup, for them to be preserved, someone needs to either provide the patches or stump up the cash to get the features implemented. cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From news1234 at free.fr Tue May 4 18:07:23 2010 From: news1234 at free.fr (News123) Date: Wed, 05 May 2010 00:07:23 +0200 Subject: ooolib, reading writing a spread sheet and keep formatting In-Reply-To: References: <4bd8cfc3$0$667$426a74cc@news.free.fr> <4BD94090.8060005@free.fr> Message-ID: <4BE09A9B.60404@free.fr> Hi Chris, Chris Withers wrote: > News123 wrote: >> >> from xlrd import open_workbook >> from xlutils.copy import copy >> >> rb = open_workbook('doc1.xls') > > open_workbook('doc1.xls',formatting_info=True) I'll try, but the doc mentioned explicitely, that formulas will be lost. I'll keep you updated. > >> print "WB with %d sheets" % rb.nsheets >> wb = copy(rb) >> wb.save("doc2.xls") # file is created, but ALL formattng is lost and >> formulas are now diplayed as text > > From news1234 at free.fr Tue May 4 18:07:23 2010 From: news1234 at free.fr (News123) Date: Wed, 05 May 2010 00:07:23 +0200 Subject: ooolib, reading writing a spread sheet and keep formatting In-Reply-To: References: <4bd8cfc3$0$667$426a74cc@news.free.fr> <4BD94090.8060005@free.fr> Message-ID: <4BE09A9B.60404@free.fr> Hi Chris, Chris Withers wrote: > News123 wrote: >> >> from xlrd import open_workbook >> from xlutils.copy import copy >> >> rb = open_workbook('doc1.xls') > > open_workbook('doc1.xls',formatting_info=True) I'll try, but the doc mentioned explicitely, that formulas will be lost. I'll keep you updated. > >> print "WB with %d sheets" % rb.nsheets >> wb = copy(rb) >> wb.save("doc2.xls") # file is created, but ALL formattng is lost and >> formulas are now diplayed as text > > From tomf.sessile at gmail.com Tue May 4 18:34:23 2010 From: tomf.sessile at gmail.com (TomF) Date: Tue, 4 May 2010 15:34:23 -0700 Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <2010050415342385304-tomfsessile@gmailcom> Thanks to everyone for their comments. On 2010-05-04 07:11:08 -0700, alex23 said: > TomF wrote: >> I'm interested in improving my python design by studying a large, >> well-designed codebase. ?Someone (not a python programmer) suggested >> Django. ?I realize that Django is popular, but can someone comment on >> whether its code is well-designed and worth studying? > > Here's a viewpoint that says no: > http://mockit.blogspot.com/2010/04/mess-djangos-in.html > > There's a lot of good counterpoint in the comments too. I read most of the discussion. Yep, there is a LOT of disagreement about the code quality. I guess I'll dig in and see whether I can learn anything. > > (I also think there's value to be gained in studying _bad_ code, > too...) True, although whether that's time well spent is another question. Regards, -Tom From lists at cheimes.de Tue May 4 18:38:29 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 May 2010 00:38:29 +0200 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: <1273009071.19963.1373400243@webmail.messagingengine.com> References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: python at bdurham.com wrote: > Is there a way to exclusively lock a file to prevent other > processes from reading it while we have it open? > > I need to cache some overflow data to disk in a temp file and I > want to make sure no other processes can read the contents of > this file while I'm using it. > > I tried the following using an 'append binary' mode, but I can > use NotePad to read the file while I'm using it: > > fd = open( r'a-temp-file.dat', 'ab' ) > > My environment is Python 2.6.4 (32-bit) under Windows, but I'm > looking for a cross-platform solution if that's possible. I know of now mandatory file lock solution that works cross platform. On Unix file locks (flock(2)) are advisory locks. All applications must check the file lock and act accordantly. Your best choice is other a temporary file or a temporary directory owned by your application. Python's tempfile module contains several solutions to securely work with temporary files and directories. Please don't try to come up with your own solution. Your app can easily become vulnerable by symlink attacks. Christian From e_d_k at yahoo.com Tue May 4 18:51:28 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 15:51:28 -0700 (PDT) Subject: Sharing a program I wrote In-Reply-To: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: <32883.64444.qm@web58708.mail.re1.yahoo.com> --- On Tue, 5/4/10, Scott wrote: > From: Scott > Subject: Sharing a program I wrote > To: python-list at python.org > Date: Tuesday, May 4, 2010, 5:40 PM > I'm looking for suggestions on what > to do (and how to do it) if I want > to share a program that I wrote in Python. There seem to be > quite a > few places to post code and I don't know how to choose. > > I wrote a program (script?) that takes a text file > containing the > output of? the "show access-list" command on a Cisco > PIX/ASA/FWSM > firewall and any number of text files containing syslog > output from > the same firewall and creates a report showing which > access-list rules > allowed which actual connections. It is written in Python > 2.6 and runs > on Windows. > > Since this is obviously something mankind has long been > waiting for I > am thinking about sharing it - but since I am new to Python > and > programming in general I am not at all familiar with > dealing with > source code. > > I'm sure that improvements and additions could be made if > it was > reviewed by "actual programmers" but I wouldn't exactly > call it a > "project" either. Of course I'd love to add a gui > interface... > > I've seen pypi. It seems to index code that is posted on > all sorts of > sites - including pypi itself? And what is a "package" > anyway? I've > seen sourceforge. It looks like a good home for big > applications or > multi-developer projects. Freshmeat? Google code? My own > website? Your > blog? > > Another detail is that my program uses a library that was > written by > someone else. It is the most excellent netaddr written by > David P. D. > Moss and it lives at code.google.com. It uses the New BSD > License. > Since this library is required would I simply provide a > link to it? > Would I post the actual library? Do I have to post a copy > of his > copyright info anywhere? Please don't tell me I have to > write some > kind of installer that takes care of providing that. > > I really just want anyone who might need a little > networking/security > tool like this to be able to find it. Any advice? > > Thanks, > Scott > -- > http://mail.python.org/mailman/listinfo/python-list > It depends on exactly what you want to do. I'd suggest you look at the following sites: http://developer.berlios.de/ http://codepad.org/ http://pastebin.com/ http://ideone.com/ One of them might be what your looking for. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From nobody at nowhere.com Tue May 4 19:44:14 2010 From: nobody at nowhere.com (Nobody) Date: Wed, 05 May 2010 00:44:14 +0100 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: On Tue, 04 May 2010 14:36:06 +0100, Baz Walter wrote: > this will work so long as the file is in a part of the filesystem that can > be traversed from the current directory to the root. what i'm not sure > about is whether it's possible to cross filesystem boundaries using this > kind of technique. At least on Linux, the kernel "fixes" the links at mount points, i.e. within the root directory of a mounted filesystem, ".." refers to the directory containing the mount point on the parent filesystem, while the mount point refers to the root directory of the mounted filesystem. This also appears to work correctly for bind mounts (mounting an arbitrary directory to another directory, which results in a directory hierarchy appearing at multiple locations within the filesystem), i.e. ".." refers to the appropriate directory for each "instance". OTOH, the algorithm can fail if a directory is moved (whether by rename() or remounting) between the stat("..") and the listdir(). From nobody at nowhere.com Tue May 4 20:03:17 2010 From: nobody at nowhere.com (Nobody) Date: Wed, 05 May 2010 01:03:17 +0100 Subject: Exclusively lock a file to prevent other processes from reading it? References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: On May 4, 2010, at 5:37 PM, python at bdurham.com wrote: > Is there a way to exclusively lock a file to prevent other processes > from reading it while we have it open? > My environment is Python 2.6.4 (32-bit) under Windows, but I'm looking > for a cross-platform solution if that's possible. Some Unix systems support mandatory locking; Linux used to, but the option appears to have been removed (and was seldom enabled). On Unix systems which support mandatory locking, it is enabled for a particular file by setting the setgid bit on a file which lacks group-execute permission. This causes fcntl() locks to be mandatory, i.e. they cause read()/write() operations to block rather than merely preventing conflicting locks from being obtained. But in general, you can't rely upon mandatory locking being available. From cs at zip.com.au Tue May 4 20:10:01 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 5 May 2010 10:10:01 +1000 Subject: strange interaction between open and cwd In-Reply-To: <4BE025AC.7070309@ftml.net> References: <4BE025AC.7070309@ftml.net> Message-ID: <20100505001000.GA8666@cskk.homeip.net> On 04May2010 14:48, Baz Walter wrote: | On 04/05/10 09:08, Gregory Ewing wrote: | >Grant Edwards wrote: | >>except that Python objects can form a generalized graph, and Unix | >>filesystems are constrained to be a tree. | > | >Actually I believe that root is allowed to create arbitrary | >hard links to directories in Unix, so it's possible to turn | >the file system in to a general graph. It's highly | >unrecommended, though, because it confuses the heck out of | >programs that recursively traverse directories (which is | >why only root is allowed to do it). | | i think there are versions of mac osx that use hard-linked | directories in their backup systems. I believe TimeMachine exploits that. I think one can make loops with recursive mounts. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ You can't go around hoping that most people have sterling moral characters. The most you can hope for is that people will pretend that they do. - Fran Lebowitz From james.harris.1 at googlemail.com Tue May 4 20:27:27 2010 From: james.harris.1 at googlemail.com (James Harris) Date: Tue, 4 May 2010 17:27:27 -0700 (PDT) Subject: Sharing a program I wrote References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: On 4 May, 22:40, Scott wrote: > I'm looking for suggestions on what to do (and how to do it) if I want > to share a program that I wrote in Python. There seem to be quite a > few places to post code and I don't know how to choose. Perhaps look at the options and then select whichever suits your needs best. > I wrote a program (script?) that takes a text file containing the > output of ?the "show access-list" command on a Cisco PIX/ASA/FWSM > firewall and any number of text files containing syslog output from > the same firewall and creates a report showing which access-list rules > allowed which actual connections. It is written in Python 2.6 and runs > on Windows. > > Since this is obviously something mankind has long been waiting for I > am thinking about sharing it - but since I am new to Python and > programming in general I am not at all familiar with dealing with > source code. > > I'm sure that improvements and additions could be made if it was > reviewed by "actual programmers" but I wouldn't exactly call it a > "project" either. Of course I'd love to add a gui interface... An option if you want reviews - and your code is short - is to post it here to comp.lang.python. > I've seen pypi. It seems to index code that is posted on all sorts of > sites - including pypi itself? And what is a "package" anyway? I've > seen sourceforge. It looks like a good home for big applications or > multi-developer projects. Freshmeat? Google code? My own website? Your > blog? Yes, many of these are well suited for significant projects. I set up http://codewiki.wikispaces.com/ Its focus is not on code size per se but on promoting sharing and updates. However, *smaller* pieces of code are preferred, i.e. code that can be viewed online and learned from. For example, see the Python programs at http://codewiki.wikispaces.com/index_by_language#x-Portable%20Python > > Another detail is that my program uses a library that was written by > someone else. It is the most excellent netaddr written by David P. D. > Moss and it lives at code.google.com. It uses the New BSD License. > Since this library is required would I simply provide a link to it? > Would I post the actual library? Do I have to post a copy of his > copyright info anywhere? Please don't tell me I have to write some > kind of installer that takes care of providing that. Unless you are worried that the original copy of the library may be deleted or lost it should be enough to post a link. Then the web site that contains the code would be responsible for explaining its licence and will include other relevant documentation. For my own code on codewiki I include installation instructions as text, where necessary. > I really just want anyone who might need a little networking/security > tool like this to be able to find it. Any advice? That was similar to my motive. Interestingly the highest number of page hits on the site is for a networking utility. James From sjmachin at lexicon.net Tue May 4 20:37:15 2010 From: sjmachin at lexicon.net (John Machin) Date: Tue, 4 May 2010 17:37:15 -0700 (PDT) Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> Message-ID: <5e4a1284-774c-4318-89a0-096f1434e942@a16g2000prg.googlegroups.com> On May 5, 12:11?am, "Barak, Ron" wrote: > > -----Original Message----- > > From: Stefan Behnel [mailto:stefan... at behnel.de] > > Sent: Tuesday, May 04, 2010 10:24 AM > > To: python-l... at python.org > > Subject: Re: How to get xml.etree.ElementTree not bomb on > > invalid characters in XML file ? > > > Barak, Ron, 04.05.2010 09:01: > > > ?I'm parsing XML files using ElementTree from xml.etree (see code > > > below (and attached xml_parse_example.py)). > > > > However, I'm coming across input XML files (attached an example: > > > tmp.xml) which include invalid characters, that produce the > > following > > > traceback: > > > > $ python xml_parse_example.py > > > Traceback (most recent call last): > > > xml.parsers.expat.ExpatError: not well-formed (invalid > > token): line 6, > > > column 34 > > > I hope you are aware that this means that the input you are > > parsing is not XML. It's best to reject the file and tell the > > producers that they are writing broken output files. You > > should always fix the source, instead of trying to make sense > > out of broken input in fragile ways. > > > > I read the documentation for xml.etree.ElementTree and see > > that it may > > > take an optional parser parameter, but I don't know what > > this parser > > > should be - to ignore the invalid characters. > > > > Could you suggest a way to call ElementTree, so it won't > > bomb on these > > > invalid characters ? > > > No. The parser in lxml.etree has a 'recover' option that lets > > it try to recover from input errors, but in general, XML > > parsers are required to reject non well-formed input. > > > Stefan > > Hi Stefan, > The XML file seems to be valid XML (all XML viewers I tried were able to read it). > You can verify this by trying to read the XML example I attached to the original message (attached again here). > Actually, when trying to view the file with an XML viewer, these offensive characters are not shown. > It's just that some of the fields include characters that the parser used by ElementTree seems to chock on. > Bye, > Ron. > > ?tmp_small.xml > < 1KViewDownload Have a look at your file with e.g. a hex editor or just Python repr() -- see below. You will see that there are four cases of good_data\x00garbage where "garbage" is repeated \x00 or just random line noise or uninitialised memory. "MainStorage_snap\x00\x00*SNIP*\x00\x00" "BROLB21\x00\xee"\x00\x00\x00\x90,\x02G\xdc\xfb\x04P\xdc \xfb\x04\x01a\xfc>(\xe8\xfb\x04" It's a toss-up whether the > in there is accidental or a deliberate attempt to sanitise the garbage !-) "Alstom\x00\x00o\x00m\x00\x00*SNIP*\x00\x00" "V5R1.28.1 [R - LA]\x00\x00*SNIP*\x00\x00" The garbage in the 2nd case is such as to make the initial declaration encoding="UTF-8" an outright lie and I'm curious as to how the XML parser managed to get as far as it did -- it must decode a line at a time. As already advised: it's much better to reject that rubbish outright than to attempt to repair it. Repair should be contemplated only if it's a one-off exercise AND you can't get a fixed copy from the source. And while we're on the subject of rubbish: """The XML file seems to be valid XML (all XML viewers I tried were able to read it).""" The conclusion from that is that all XML viewers that you tried are rubbish. From wuwei23 at gmail.com Tue May 4 20:38:27 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 May 2010 17:38:27 -0700 (PDT) Subject: Generating nested code with context managers References: Message-ID: On May 5, 6:36?am, Terry Reedy wrote: > The relatively new with statement and associated context managers are > designed, among other things, for this situation, where one needs to > alter and restore a global context. So here is my updated (3.1) > proof-of-concept version. This is what I love about c.l.p, you wait 10 mins and someone proves your point with working code :) I had a more generic 'with indentation:' context manager in mind, but I really like your approach. Cheers. From wuwei23 at gmail.com Tue May 4 20:47:07 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 May 2010 17:47:07 -0700 (PDT) Subject: Teaching Programming References: Message-ID: Ed Keith wrote: > Knuth wanted the generated source to be unreadable, so people would not be tempted to edit the generated code. This is my biggest issue with Knuth's view of literate programming. If the generated source isn't readable, am I just supposed to trust it? How can I tell if an error lies in my expression of the algorithm or in the code generation itself? From sjmachin at lexicon.net Tue May 4 21:21:23 2010 From: sjmachin at lexicon.net (John Machin) Date: Tue, 4 May 2010 18:21:23 -0700 (PDT) Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> <7F0503CD69378F49BE0DC30661C6CCF6A3B87357@enbmail01.lsi.com> Message-ID: On May 5, 3:43?am, Terry Reedy wrote: > On 5/4/2010 11:37 AM, Stefan Behnel wrote: > > > Barak, Ron, 04.05.2010 16:11: > >> The XML file seems to be valid XML (all XML viewers I tried were able > >> to read it). > > ?From Internet Explorer: > > The XML page cannot be displayed > Cannot view XML input using XSL style sheet. Please correct the error > and then click the Refresh button, or try again later. > > -------------------------------------------------------------------------------- > > An invalid character was found in text content. Error processing > resource 'file:///C:/Documents and Settings... > > ? ? ? "BROLB21 > > > > > This is what xmllint gives me: > > > ----------------------- > > $ xmllint /home/sbehnel/tmp.xml > > tmp.xml:6: parser error : Char 0x0 out of allowed range > > "MainStorage_snap > > ^ > > tmp.xml:6: parser error : Premature end of data in tag m_sanApiName1 line 6 > > "MainStorage_snap > > ^ > > tmp.xml:6: parser error : Premature end of data in tag DbHbaGroup line 5 > > "MainStorage_snap > > ^ > > tmp.xml:6: parser error : Premature end of data in tag database line 4 > > "MainStorage_snap > > ^ > > ----------------------- > > > The file contains 0-bytes - clearly not XML. > > IE agrees. Look closer. IE *DOESN'T* agree. It has ignored the problem on line 6 and lurched on to the next problem (in line 11). If you edit that file to remove the line noise in line 11, leaving the 3 cases of multiple \x00 bytes, IE doesn't complain at all about the (invalid) \x00 bytes. From bazwal at ftml.net Tue May 4 21:41:09 2010 From: bazwal at ftml.net (Baz Walter) Date: Wed, 05 May 2010 02:41:09 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: <4BE0CCB5.7050307@ftml.net> On 05/05/10 00:44, Nobody wrote: > On Tue, 04 May 2010 14:36:06 +0100, Baz Walter wrote: > >> this will work so long as the file is in a part of the filesystem that can >> be traversed from the current directory to the root. what i'm not sure >> about is whether it's possible to cross filesystem boundaries using this >> kind of technique. > > At least on Linux, the kernel "fixes" the links at mount points, i.e. > within the root directory of a mounted filesystem, ".." refers to > the directory containing the mount point on the parent filesystem, while > the mount point refers to the root directory of the mounted filesystem. > > This also appears to work correctly for bind mounts (mounting an arbitrary > directory to another directory, which results in a directory hierarchy > appearing at multiple locations within the filesystem), i.e. ".." refers > to the appropriate directory for each "instance". > > OTOH, the algorithm can fail if a directory is moved (whether by rename() > or remounting) between the stat("..") and the listdir(). i think the algorithm also can't guarantee the intended result when crossing filesystem boundaries. IIUC, a stat() call on the root directory of a mounted filesystem will give the same inode number as its parent. so if several filesystems are mounted in the same parent directory, there is no way to tell which of them is the "right" one. From dchichkov at gmail.com Tue May 4 21:55:41 2010 From: dchichkov at gmail.com (dmtr) Date: Tue, 4 May 2010 18:55:41 -0700 (PDT) Subject: A python interface to google-sparsehash? Message-ID: <44f814e1-a24e-4ee6-bbd1-b28f4355af44@y6g2000pra.googlegroups.com> Anybody knows if a python sparsehash module is there in the wild? From scott.freemire at gmail.com Tue May 4 23:25:35 2010 From: scott.freemire at gmail.com (Scott) Date: Tue, 4 May 2010 20:25:35 -0700 (PDT) Subject: Sharing a program I wrote References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: James, Thanks for the comprehensive reply. I would like to post it to comp.lang.python but the main file is 169 lines long and the file for functions is 316 lines long. I'm thinking that is a little long for this format. Maybe I can put them up on a basic web page or file sharing site and just post a link. Is that well received on this forum? Thanks, Scott From michele.simionato at gmail.com Wed May 5 00:08:28 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 4 May 2010 21:08:28 -0700 (PDT) Subject: Sphinx hosting References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> Message-ID: <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> On May 4, 9:48?am, James Mills wrote: > On Tue, May 4, 2010 at 5:27 PM, Michele Simionato > > wrote: > > Cool, that's good to know. I am still accepting recommendations for > > non-Python projects ;) > > bitbucket (1) also provide static file hosting through the wiki. From > what I understand (tested) > you simply clone the wiki repository (which is it's own repository) > and commit a bunch of .html > files. > > cheers > James > > 1.http://bitbucket.org/ Interesting. I tried to see if the same was true for the Wiki in Google code but apparently it does not work. Does anybody here know if it is possible to publish raw html in the Google Code wiki and how does it work? From lie.1296 at gmail.com Wed May 5 00:16:56 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 05 May 2010 14:16:56 +1000 Subject: Sharing a program I wrote In-Reply-To: References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: <4be0f197$1@dnews.tpgi.com.au> On 05/05/10 13:25, Scott wrote: > James, > > Thanks for the comprehensive reply. I would like to post it to > comp.lang.python but the main file is 169 lines long and the file for > functions is 316 lines long. I'm thinking that is a little long for > this format. Maybe I can put them up on a basic web page or file > sharing site and just post a link. Is that well received on this > forum? > > Thanks, > Scott Make it as easy as possible for people to get to your code; file sharing site isn't very good for this (especially those that have wait time and download limits and if you have to zip your file). If you're setting up a webpage you need to take care not to mess up special characters. Using pastebin is fairly well-received as people won't have to save the file to their harddrive to see the content and their page is specifically set up for displaying code (syntax highlighting and stuffs). If your code is specifically reusable or if it illustrates a certain concept, posting it as Activestate recipe is great as well. From nagle at animats.com Wed May 5 00:19:35 2010 From: nagle at animats.com (John Nagle) Date: Tue, 04 May 2010 21:19:35 -0700 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: <4be0ec73$0$1661$742ec2ed@news.sonic.net> Philip Semanchuk wrote: > > On May 4, 2010, at 5:37 PM, python at bdurham.com wrote: > >> Is there a way to exclusively lock a file to prevent other >> processes from reading it while we have it open? If you can use SQLite to store the data, it will deal with your locking problems. The pain of getting locking right has already been dealt with by others. Classic lock files are iffy. They're not race condition free on NTFS, and all the junk needed to clean up lock files properly after a crash is a headache. John Nagle From clp2 at rebertia.com Wed May 5 00:23:10 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 May 2010 21:23:10 -0700 Subject: Sharing a program I wrote In-Reply-To: <4be0f197$1@dnews.tpgi.com.au> References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> <4be0f197$1@dnews.tpgi.com.au> Message-ID: On Tue, May 4, 2010 at 9:16 PM, Lie Ryan wrote: > On 05/05/10 13:25, Scott wrote: >> I would like to post it to >> comp.lang.python but the main file is 169 lines long and the file for >> functions is 316 lines long. I'm thinking that is a little long for >> this format. Maybe I can put them up on a basic web page or file >> sharing site and just post a link. Is that well received on this >> forum? >> > Make it as easy as possible for people to get to your code; file sharing > site isn't very good for this (especially those that have wait time and > download limits and if you have to zip your file). If you're setting up > a webpage you need to take care not to mess up special characters. Using > pastebin is fairly well-received as people won't have to save the file > to their harddrive to see the content and their page is specifically set > up for displaying code (syntax highlighting and stuffs). > > If your code is specifically reusable or if it illustrates a certain > concept, posting it as Activestate recipe is great as well. In case Scott's not familiar, obligatory link: http://code.activestate.com/recipes/langs/python/ Cheers, Chris -- http://blog.rebertia.com From prologic at shortcircuit.net.au Wed May 5 00:39:11 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 5 May 2010 14:39:11 +1000 Subject: Sphinx hosting In-Reply-To: <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> Message-ID: On Wed, May 5, 2010 at 2:08 PM, Michele Simionato wrote: > Interesting. I tried to see if the same was true for the Wiki in > Google code but apparently it does not work. Does anybody here know if > it is possible to publish raw html in the Google Code wiki and how > does it work? I may be wrong, but I recall that Google Code Hosting's Wiki Engine has a macro that will allow you to render raw HTML. cheers James From gagsl-py2 at yahoo.com.ar Wed May 5 01:09:01 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 May 2010 02:09:01 -0300 Subject: CGI python 3 write RAW BINARY References: <4bd8ae7e$0$27615$ba4acef3@reader.news.orange.fr> <4bd96540$0$27597$ba4acef3@reader.news.orange.fr> <4bd9b4c2$0$27606$ba4acef3@reader.news.orange.fr> <4bd9fc1a$0$2980$ba4acef3@reader.news.orange.fr> <4bdc07d4$0$2980$ba4acef3@reader.news.orange.fr> Message-ID: En Sat, 01 May 2010 07:52:01 -0300, Dodo escribi?: > Le 30/04/2010 17:52, Antoine Pitrou a ?crit : >> Le Thu, 29 Apr 2010 23:37:32 +0200, Dodo a ?crit : >>> ....I don't get a thing. >>> Now with the fix : >>> All browsers shows a different thing, but not the image! >>> http://ddclermont.homeip.net/misc/python/ >>> >>> If I save it to computer : >>> * Windows image viewer won't read it >>> * Irfanview can read it without problems >> >> Did you set the content-type and content-length in the HTTP headers? >> Can you post your code? >> >> > I didn't know about content-lenght > Here's the new code (I used a fixed image patch to make sure this is not > the source of the problem) > > > #!/usr/bin/python3 > import cgi, sys, cgitb > cgitb.enable() > > f = open("/home/dodo/54.jpg", "rb") > data = f.read() > l = len(data) > f.close() > > print("Content-type:image/jpg\nContent-length:%d\n\n" % l) > > sys.stdout.flush() > sys.stdout.buffer.write( data ) Computers are dumb. You have to speak to them very slow and clearly in order to be understood :) You need a space after those ':'. The correct media type for JPEG images is image/jpeg. And (the important thing) you have one more \n than necessary. Each header field finishes with \n; an empty line (just \n) marks the end of all headers; the body [your image] must follow immediately. #!/usr/bin/python3 import cgi, sys, cgitb cgitb.enable() f = open("/home/dodo/54.jpg", "rb") data = f.read() l = len(data) f.close() print("Content-Type: image/jpeg\nContent-Length: %d\n" % l) sys.stdout.flush() sys.stdout.buffer.write( data ) (Probably, a better way would be to replace all those \n with \r\n, and not use print at all, but the above code is good enough). -- Gabriel Genellina From michele.simionato at gmail.com Wed May 5 01:35:55 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 4 May 2010 22:35:55 -0700 (PDT) Subject: Sphinx hosting References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> Message-ID: <1aeaac06-ff0e-4ec1-8f7d-fc71891228c0@b18g2000yqb.googlegroups.com> On May 5, 6:39?am, James Mills wrote: > On Wed, May 5, 2010 at 2:08 PM, Michele Simionato > > wrote: > > Interesting. I tried to see if the same was true for the Wiki in > > Google code but apparently it does not work. Does anybody here know if > > it is possible to publish raw html in the Google Code wiki and how > > does it work? > > I may be wrong, but I recall that Google Code Hosting's Wiki Engine > has a macro that will allow you to render raw HTML. > > cheers > James I am sure it has, but I was talking about just putting in the repository an index.html file and have it published, the wayI hear it works in BitBucket and GitHub. From prologic at shortcircuit.net.au Wed May 5 02:00:31 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 5 May 2010 16:00:31 +1000 Subject: Sphinx hosting In-Reply-To: <1aeaac06-ff0e-4ec1-8f7d-fc71891228c0@b18g2000yqb.googlegroups.com> References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> <1aeaac06-ff0e-4ec1-8f7d-fc71891228c0@b18g2000yqb.googlegroups.com> Message-ID: On Wed, May 5, 2010 at 3:35 PM, Michele Simionato wrote: > I am sure it has, but I was talking about just putting in the > repository an index.html file and have it published, the wayI hear ?it > works in BitBucket and GitHub. I'm pretty sure Google Code Hosting doesn't support rendering text/html mime-type files in the repository (like Trac can). On a side-note, not sure if you're interested in this at all... I wrote (for the hell/fun of it) a "Sphinx Server", here's the code: http://codepad.org/ywo8pscb This uses the latest development version of circuits (1) cheers James 1. http://bitbucket.org/prologic/circuits/ From gagsl-py2 at yahoo.com.ar Wed May 5 02:05:37 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 May 2010 03:05:37 -0300 Subject: Fast Efficient way to transfer an object to another list References: Message-ID: En Fri, 30 Apr 2010 23:16:04 -0300, Jimbo escribi?: > Hello I have a relatively simple thing to do; move an object from one > to list into another. But I think my solution maybe inefficient & > slow. Is there a faster better way to move my stock object from one > list to another? (IE, without having to use a dictionary instead of a > list or is that my only solution?) > > [code] > class stock: > > code = "NULL" > price = 0 > > > stock_list1 = [] > stock_list2 = [] > > def transfer_stock(stock_code, old_list, new_list): > """ Transfer a stock from one list to another """ > # is there a more efficient & faster way to > > index = 0 > > for stock in old_list: > > temp_stock = stock > > if temp_stock.code == stock_code: > new_list.append(temp_stock) > del old_list[index] > index += 1 > > return new_list[/code] I'd do that in two steps: def transfer_stock(stock_code, old_list, new_list): # find the indexes to transfer indexes = [i for i,stock in enumerate(old_list) if stock.code==stock_code] # actually transfer them for index in reversed(indexes): stock = old_list[index] new_list.append(stock) del old_list[index] # I would not return anything -- Gabriel Genellina From nobody at nowhere.com Wed May 5 02:24:02 2010 From: nobody at nowhere.com (Nobody) Date: Wed, 05 May 2010 07:24:02 +0100 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: On Wed, 05 May 2010 02:41:09 +0100, Baz Walter wrote: > i think the algorithm also can't guarantee the intended result when > crossing filesystem boundaries. IIUC, a stat() call on the root directory > of a mounted filesystem will give the same inode number as its parent. Nope; it will have the same dev/inode pair as if it wasn't mounted, i.e. the device will refer to the mounted device, not the device it's mounted on, and the inode will be the mounted filesystem's root inode (typically #2 for Linux ext2/ext3 filesystems). And stat()ing the appropriate entry in the parent directory will return the same information, i.e. the root inode of the mounted device, not the subdirectory of the parent device (as you would see if the filesystem was unmounted). IOW, if stat("foo") reports a different device to stat("."), "foo" is a mount point, while if stat("..") reports a different device to stat("."), the current directory is the root of a mounted filesystem. > so > if several filesystems are mounted in the same parent directory, there is > no way to tell which of them is the "right" one. The only case which would cause a problem here is if you mount the same device on two different subdirectories of a common directory. But in that case, it doesn't really matter which answer you get, as they're both equivalent in any sense that matters. From davea at ieee.org Wed May 5 04:50:11 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 05 May 2010 04:50:11 -0400 Subject: Teaching Programming In-Reply-To: References: Message-ID: <4BE13143.6040904@ieee.org> alex23 wrote: > Ed Keith wrote: > >> Knuth wanted the generated source to be unreadable, so people would not be tempted to edit the generated code. >> > > This is my biggest issue with Knuth's view of literate programming. If > the generated source isn't readable, am I just supposed to trust it? > How can I tell if an error lies in my expression of the algorithm or > in the code generation itself? > > Do you think a compiler is required to make its object file conveniently readable? Do you regularly read the machine code generated by your C compiler? I admit I've frequently studied compiler output over the years, but I think I'm very unusual in that respect. I've never disassembled a python byte code file, though I wrote tools to display and manipulate both java byte code files and dot-net (before it was called that). I think the question really boils down to whether you trust the compiler. DaveA From bruno.42.desthuilliers at websiteburo.invalid Wed May 5 04:59:01 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 05 May 2010 10:59:01 +0200 Subject: Django as exemplary design In-Reply-To: <2010050415342385304-tomfsessile@gmailcom> References: <2010050312243328275-tomfsessile@gmailcom> <2010050415342385304-tomfsessile@gmailcom> Message-ID: <4be132f1$0$20639$426a74cc@news.free.fr> TomF a ?crit : > > On 2010-05-04 07:11:08 -0700, alex23 said: (snip) >> (I also think there's value to be gained in studying _bad_ code, >> too...) > > True, although whether that's time well spent is another question. The more bad code (mine or not) I have to maintain (or even just read and understand), the more I pay attention to my own design and code quality. Sometimes you only understand why something is bad, why it is bad and how bad it is when you have to deal with it :( From pavlovevidence at gmail.com Wed May 5 05:17:12 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 5 May 2010 02:17:12 -0700 (PDT) Subject: Python debuggers with sys.settrace() References: Message-ID: <1f8f2c8e-3ee1-4fc1-95e8-aae3e54ba1b4@n37g2000prc.googlegroups.com> On May 2, 11:06?am, Sarah Mount wrote: > This is a bit of an odd question, but is there any way for a Python > debugger to suppress I/O generated by the program which is being > debugged? I guess an "obvious" thing to do would be to replace core > parts of the standard library and change any relevant imports in the > locals and globals dicts to fake ones which don't generate I/O, but > this seems brittle as the standard library will change over time. Is > it possible to modify the byte-compiled code in each stack frame? Or > is there a simpler way to do this? It's not foolproof but you could try to reassign sys.stdout and sys.stderr to a bit bucket ("sys.stdout = open(os.devull)"), then invoke the debugger with stdout set to sys._stdout (the actual stdout). You'll have to create the Pdb() by hand since the built-in convience functions don't do it. Check the file pdb.py for details. Carl Banks From robin1 at cnsp.com Wed May 5 05:44:57 2010 From: robin1 at cnsp.com (Robin) Date: Wed, 5 May 2010 02:44:57 -0700 (PDT) Subject: the solution to your current problems........join this: http://www.thevoid1.net/para Message-ID: <76cf627c-3212-48ba-9fa4-37e766d4c9a1@37g2000yqm.googlegroups.com> the solution to your current problems........join this: http://www.thevoid1.net/para From e_d_k at yahoo.com Wed May 5 06:32:24 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Wed, 5 May 2010 03:32:24 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <472926.69200.qm@web58701.mail.re1.yahoo.com> --- On Tue, 5/4/10, alex23 wrote: > From: alex23 > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 8:47 PM > Ed Keith > wrote: > > Knuth wanted the generated source to be unreadable, so > people would not be tempted to edit the generated code. > > This is my biggest issue with Knuth's view of literate > programming. If > the generated source isn't readable, am I just supposed to > trust it? > How can I tell if an error lies in my expression of the > algorithm or > in the code generation itself? > > -- > http://mail.python.org/mailman/listinfo/python-list > My feelings exactly. I can see an argument for an option to emit obstructed code, but the default should be readable. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From hiralsmaillist at gmail.com Wed May 5 06:34:06 2010 From: hiralsmaillist at gmail.com (hiral) Date: Wed, 5 May 2010 03:34:06 -0700 (PDT) Subject: how to import subprocess into my 'subprocess.py' file Message-ID: <7a0a477e-1473-4001-b167-a9f96ff3a1d8@y18g2000prn.googlegroups.com> Hi, I am doing following in my 'subprocess.py' file... 1 from __future__ import absolute_import 2 from subprocess import * 3 from subprocess import call as myCall 4 from subprocess import Popen as myPopen 5 6 def getProperCmd(cmd): 7 cmd += 'time' # this is just an example; in fact I am doing lots of processing on cmd 8 return cmd 9 10 11 def call(cmd, **kwargs): 12 return myCall(getProperCmd(cmd), **kwargs) 13 14 def Popen(cmd, **kwargs): 15 return myPopen(getProperCmd(cmd), **kwargs) When running this it gives following error... Traceback (most recent call last): File "subprocess.py", line 2, in from subprocess import * File "subprocess.py", line 3, in from subprocess import call as myCall ImportError: cannot import name call So how can I create a python file (with the same name as standard module name) with custom methods? Thank you in advance. -Hiral From googler.1.webmaster at spamgourmet.com Wed May 5 08:04:06 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Wed, 5 May 2010 05:04:06 -0700 (PDT) Subject: Python Embedding, no correct lib Message-ID: <5d90e51f-133f-4b01-9074-9fdc3eb37d59@e35g2000yqm.googlegroups.com> Hi, I have a serious problem with Python. I am currently trying to implement Python into my app. Well this works fine, but get this: I have my own Python interpreter in a subfolder of my app. When I start my app, PYTHONHOME is set, and an environment variable is set to it can find the python DLL on startup. When Python is not installed on the system everything works fine as expected. When I now install Python on my system (so I have two python libs now) the system installation is the preferred one. print sys.path prints out ['', 'C:\Windows \system32\python26.zip', ...] and I cant explain whats going wrong here. I expected that it just uses the System lib when it cannot find it in the subfolder which I set in the environment variables before.. :-( Any ideas? Thanks a lot for help. Bye, moerchendiser2k3 From nospam at news.eternal-september.org Wed May 5 08:14:11 2010 From: nospam at news.eternal-september.org (balzer) Date: Wed, 5 May 2010 15:14:11 +0300 Subject: Portable Python Message-ID: Is there any difference in functionality between standard Python pack and portable Python? Why standard Python pack installation requires reboot after installation? Can portable Python used from hard drive folder? From bazwal at ftml.net Wed May 5 08:23:03 2010 From: bazwal at ftml.net (Baz Walter) Date: Wed, 05 May 2010 13:23:03 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: <4BE16327.5050209@ftml.net> On 05/05/10 07:24, Nobody wrote: > On Wed, 05 May 2010 02:41:09 +0100, Baz Walter wrote: > >> i think the algorithm also can't guarantee the intended result when >> crossing filesystem boundaries. IIUC, a stat() call on the root directory >> of a mounted filesystem will give the same inode number as its parent. > > Nope; it will have the same dev/inode pair as if it wasn't mounted, i.e. > the device will refer to the mounted device, not the device it's mounted > on, and the inode will be the mounted filesystem's root inode (typically > #2 for Linux ext2/ext3 filesystems). > > And stat()ing the appropriate entry in the parent directory will return > the same information, i.e. the root inode of the mounted device, not the > subdirectory of the parent device (as you would see if the filesystem was > unmounted). yes, that's actually what i meant (but probably put badly as usual). > IOW, if stat("foo") reports a different device to stat("."), "foo" > is a mount point, while if stat("..") reports a different device to > stat("."), the current directory is the root of a mounted filesystem. > >> so >> if several filesystems are mounted in the same parent directory, there is >> no way to tell which of them is the "right" one. > > The only case which would cause a problem here is if you mount the same > device on two different subdirectories of a common directory. But in that > case, it doesn't really matter which answer you get, as they're both > equivalent in any sense that matters. nope! just to be clear: here's what i get on my system, where '/dev/sda1' and '/dev/sda6' are mounted at '/boot' and '/home' respectively: >>> os.stat('/').st_ino 2L >>> os.stat('/usr').st_ino 212993L >>> os.stat('/boot').st_ino 2L >>> os.stat('/home').st_ino 2L >>> if the algorithm is climbing up from '/home/baz/tmp/xxx', what does it do when it searches os.listdir('../../../..')? how can it tell whether 'boot' or 'home' is the correct next parent if it only checks the inode number? i think the algorithm would at least need to take account of changes in the current device id. not sure whether that would be enough to cover all cases, though. From steve at REMOVE-THIS-cybersource.com.au Wed May 5 08:32:48 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 May 2010 12:32:48 GMT Subject: how to import subprocess into my 'subprocess.py' file References: <7a0a477e-1473-4001-b167-a9f96ff3a1d8@y18g2000prn.googlegroups.com> Message-ID: <4be16570$0$27823$c3e8da3@news.astraweb.com> On Wed, 05 May 2010 03:34:06 -0700, hiral wrote: > So how can I create a python file (with the same name as standard module > name) with custom methods? Don't do this. It will lead to nothing but trouble. Python doesn't support multiple modules with the same name. Unless you create a custom importer, a module called subprocess will shadow (hide) the original subprocess module. -- Steven From nospam at news.eternal-september.org Wed May 5 08:47:33 2010 From: nospam at news.eternal-september.org (balzer) Date: Wed, 5 May 2010 15:47:33 +0300 Subject: Movable Python or ActivePython Message-ID: I want Python pack that can run without being installed, mostly for testing programs. As I read, Movable Python can run without being installed. It needs no registry entries and knows the path to all the dlls (system or otherwise) that it uses. Whats about ActivePython http://www.activestate.com/activepython/downloads? Does it requires installation? From massi_srb at msn.com Wed May 5 08:56:03 2010 From: massi_srb at msn.com (Massi) Date: Wed, 5 May 2010 05:56:03 -0700 (PDT) Subject: Create a new process to run python function Message-ID: Hi everyone, in my script (python 2.5 on windows xp) I need to run a simple function in a separate process. In other words I need something similar to the fork function under UNIX. I tried with threads: import os, threading def func(s) : print "I'm thread number "+s, os.getpid() threading.Thread(target=func, args=("1",)).start() threading.Thread(target=func, args=("2",)).start() but this does not work, since the two threads share the same pid. Can anyone give me a suggestion? Thanks in advance. From jeanmichel at sequans.com Wed May 5 08:56:29 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 05 May 2010 14:56:29 +0200 Subject: how to import subprocess into my 'subprocess.py' file In-Reply-To: <7a0a477e-1473-4001-b167-a9f96ff3a1d8@y18g2000prn.googlegroups.com> References: <7a0a477e-1473-4001-b167-a9f96ff3a1d8@y18g2000prn.googlegroups.com> Message-ID: <4BE16AFD.9000805@sequans.com> hiral wrote: > Hi, > > I am doing following in my 'subprocess.py' file... > > 1 from __future__ import absolute_import > 2 from subprocess import * > 3 from subprocess import call as myCall > 4 from subprocess import Popen as myPopen > 5 > 6 def getProperCmd(cmd): > 7 cmd += 'time' # this is just an example; in fact I am doing > lots of processing on cmd > 8 return cmd > 9 > 10 > 11 def call(cmd, **kwargs): > 12 return myCall(getProperCmd(cmd), **kwargs) > 13 > 14 def Popen(cmd, **kwargs): > 15 return myPopen(getProperCmd(cmd), **kwargs) > > When running this it gives following error... > > Traceback (most recent call last): > File "subprocess.py", line 2, in > from subprocess import * > File "subprocess.py", line 3, in > from subprocess import call as myCall > ImportError: cannot import name call > > > So how can I create a python file (with the same name as standard > module name) with custom methods? > > Thank you in advance. > -Hiral > Just don't do that, find another name. Dont use * in import statement: "Namespaces are one honking great idea -- let's do more of those!" ("import this" in a shell for more rules) Using * in import statements removes namespaces. JM From python at bdurham.com Wed May 5 09:20:19 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 09:20:19 -0400 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: <1273009071.19963.1373400243@webmail.messagingengine.com> References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: <1273065619.18441.1373515393@webmail.messagingengine.com> Chris, Philip, Christian, John and others, Thank you all for your replies. Regards, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Wed May 5 09:20:19 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 09:20:19 -0400 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: <1273009071.19963.1373400243@webmail.messagingengine.com> References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: <1273065619.18441.1373515393@webmail.messagingengine.com> Chris, Philip, Christian, John and others, Thank you all for your replies. Regards, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From goon12 at gmail.com Wed May 5 09:20:32 2010 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 5 May 2010 09:20:32 -0400 Subject: Create a new process to run python function In-Reply-To: References: Message-ID: On Wed, May 5, 2010 at 8:56 AM, Massi wrote: > but this does not work, since the two threads share the same pid. Can > anyone give me a suggestion? Have you looked at os.fork ? http://docs.python.org/library/os.html#os.fork From lists at cheimes.de Wed May 5 09:29:25 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 May 2010 15:29:25 +0200 Subject: Create a new process to run python function In-Reply-To: References: Message-ID: Joe Riopel wrote: > On Wed, May 5, 2010 at 8:56 AM, Massi wrote: >> but this does not work, since the two threads share the same pid. Can >> anyone give me a suggestion? > > Have you looked at os.fork ? > http://docs.python.org/library/os.html#os.fork Fork on Windows XP? Have a lot of fun ... The NT Kernel has support for forking but neither the Win32 API nor Python supports it. Christian From gelonida at gmail.com Wed May 5 09:34:34 2010 From: gelonida at gmail.com (gelonida) Date: Wed, 5 May 2010 06:34:34 -0700 (PDT) Subject: find out whther byte two .pyc files contain the same byte code. Message-ID: <8d53dbc5-9ad0-44ed-881f-fa2b6fc82e96@i9g2000yqi.googlegroups.com> Hi, I'd like to know whether the byte code of two .pyc files is identical. I thought, I could just compare the md5sums of thw .pyc files. However this does not work. It seems, that .pyc ontains the time stamp of the source file. the .pyc file changes its contents when I don't change the file's contents but just save it again. Is there any way to compare two .pyc files or to just strip the timestiam or set it to a fixed value? Example: ##### I create a python file $ echo 'print 1' > tst.py ##### I compile it and display the md5sum of the .pyc file $ rm -f tst.pyc ; python -c 'import tst' ; md5sum tst.pyc 1 0d67af4c2c233dbbe89bd2dab6b12088 *tst.pyc ##### now I recompile and will get the same md5sum $ rm -f tst.pyc ; python -c 'import tst' ; md5sum tst.pyc 1 0d67af4c2c233dbbe89bd2dab6b12088 *tst.pyc #### now I change the time stamp of the python source touch tst.py #### now the md5sum will be different $ rm -f tst.pyc ; python -c 'import tst' ; md5sum tst.pyc 1 f6faf2048b6f967c73e68951558f954c *tst.pyc thanks for any suggestions / ideas From james.harris.1 at googlemail.com Wed May 5 10:29:16 2010 From: james.harris.1 at googlemail.com (James Harris) Date: Wed, 5 May 2010 07:29:16 -0700 (PDT) Subject: Sharing a program I wrote References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: <9c80c3f4-004c-4b80-9a3f-6d48abc97822@q32g2000yqb.googlegroups.com> On 5 May, 04:25, Scott wrote: > James, > > Thanks for the comprehensive reply. I would like to post it to > comp.lang.python but the main file is 169 lines long and the file for > functions is 316 lines long. I'm thinking that is a little long for > this format. You're welcome. Yes, it sounds a bit long for a direct post. In general, comments are more forthcoming on smaller pithier code fragments. > Maybe I can put them up on a basic web page or file > sharing site and just post a link. Is that well received on this > forum? I can't answer for how it would be received here but once you have addressed any Python issues you may want to let folks on either or both of comp.dcom.sys.cisco comp.dcom.net-management know about your utility. James From prologic at shortcircuit.net.au Wed May 5 10:33:29 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 6 May 2010 00:33:29 +1000 Subject: Create a new process to run python function In-Reply-To: References: Message-ID: On Wed, May 5, 2010 at 10:56 PM, Massi wrote: > in my script (python 2.5 on windows xp) I need to run a simple > function in a separate process. In other words I need something > similar to the fork function under UNIX. I tried with threads: Use the new multiprocesing package. > import os, threading > > def func(s) : > ? ?print "I'm thread number "+s, os.getpid() > > threading.Thread(target=func, args=("1",)).start() > threading.Thread(target=func, args=("2",)).start() Like this: import multiprocessing multiprocessing.Process(target=func, args=("1",)).start() multiprocessing.Process(target=func, args=("2",)).start() ... Surprise surprise it has almost the same API as the threading module :) --James From mouadino at gmail.com Wed May 5 10:36:44 2010 From: mouadino at gmail.com (mouadino) Date: Wed, 5 May 2010 07:36:44 -0700 (PDT) Subject: abc don't play well with private method Message-ID: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com> i have a problem here : i want to make a plugin architecture using abstract base class , this is my base class : # -*- coding: utf-8 -*- import abc class BASE_Connector: """ Mount point for plugins which refer to actions that can be performed. Plugins implementing this reference should provide the following methods: ======== ======================================================== connect the connection method that will initialize a transport layer __login the login method to use to login in to the server this one should be called from connect directly get this method is use for getting the files from the remote server close this method is called for closing the connection suddenly quit this method is more polite to close the connection ======== ======================================================== """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def connect(self, host, user="", passwd="", port="", private_key_file="", timeout=100): """ connect to a remote server this function call the __login function after the connection is established -- host : remote server name -- user : the user name in the remote server Default : empty string for server that don't need authentication or use private key instead -- passwd : password of the user given Default : empty string for server that don't need authentication or use private key instead -- port : the connection port Default : it's known from the protocol -- private_key_file : the file containing the private key used special for ssh connection Default : empty string -- timeout : the timeout of the connection Default : empty string """ pass @abc.abstractmethod def __login(self): """ private method to login to the remote server . it use the user name and the password or the private key for that """ @abc.abstractmethod def get(self, remote_file_path, local_path="/tmp/ housead_matcher"): """ method to download the file from the remote server -- remote_file_path : the path of the file in the remote server -- local_path : the local path where the file will be save """ pass @abc.abstractmethod def close(self): """ Close the connection unilaterally(from this host) """ @abc.abstractmethod def quit(self): """ close the connection. This is the ?polite? way to close a connection """ and i define my plugins in a differents module like this : class FTP_Connector(FTP, Base_Connector) : """ this class is for the connection to a ftp server """ def __init__(self): FTP.__init__() def connect(self, host, port, user, passwd, timeout=""): self.connect(host, port, timeout) self.___login(user, passwd) def ___login(self, username="", password=""): self.login(username, password) def get(self, remote_file_path, local_path): remote_file_path = os.path.expanduser(remote_file_path) local_path = os.path.expanduser(local_path) remote_directory, remote_file_name = os.path.split(remote_file_path) local_file = os.path.join(local_path, remote_file_name) self.cwd(remote_directory) self.retrlines("RETR " + remote_file_name, lambda s, w=local_file.write: w(s+"\n")) def close(self): self.close() def quit(self): self.quit() and when i test my code i get this error : Can't instantiate abstract class FTP_Connector with abstract methods _BASE_Connector__login i can understand why. but my problem is why why ? i can't put "private" method in the ABC class ??? From gandalf at shopzeus.com Wed May 5 10:42:21 2010 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 05 May 2010 16:42:21 +0200 Subject: Portable Python In-Reply-To: References: Message-ID: <4BE183CD.3040708@shopzeus.com> > Is there any difference in functionality between standard Python pack > and portable Python? It is not so easy to install third party modules for portable Python... > Why standard Python pack installation requires reboot after installation? It is not true for all operating systems. At least under Unbuntu Linux, BSD, Windows XP and Windows 7, you don't need to restart the OS after installation. What others have you tried? > Can portable Python used from hard drive folder? Did you read its very front page? http://www.portablepython.com/ "Just download it, extract to your portable storage device ***or hard drive*** and in 10 minutes you are ready to create your next Python application." Laszlo From bruno.42.desthuilliers at websiteburo.invalid Wed May 5 11:24:18 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 05 May 2010 17:24:18 +0200 Subject: abc don't play well with private method In-Reply-To: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com> References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com> Message-ID: <4be18d3d$0$19014$426a34cc@news.free.fr> mouadino a ?crit : > i have a problem here : > > i want to make a plugin architecture using abstract base class , this > is my base class : > > # -*- coding: utf-8 -*- > > import abc > > > class BASE_Connector: > """ > Mount point for plugins which refer to actions that can be > performed. > > Plugins implementing this reference should provide the following > methods: > > connect the connection method that will initialize a transport > layer > > __login the login method to use to login in to the server > this one should be called from connect directly Removing one of the leading underscores would solve your problem. > """ > __metaclass__ = abc.ABCMeta > > > > @abc.abstractmethod > def __login(self): > """ private method to login to the remote server . > it use the user name and the password or the private key > for that > > """ > and when i test my code i get this error : > Can't instantiate abstract class FTP_Connector with abstract methods > _BASE_Connector__login > > i can understand why. but my problem is why why ? i can't put > "private" method in the ABC class ??? There's no such thing as a "private" attribute in Python. The name-mangling mechanism invoked by "__name" is really meant to avoid accidental redefinition of the attribute in a derived class. In this case, your attribute is expected to be redefined, so you definitly don't want any name mangling here. Also and FWIW, the naming convention for "implementation attributes" is a single leading underscore. Also and FWIW: > > class FTP_Connector(FTP, Base_Connector) : > """ this class is for the connection to a ftp server > > """ > def close(self): > > self.close() > > def quit(self): > > self.quit() > Don't you see kind of a problem here ? Something like, say, an infinite recursion ? HTH From dg.gmane at thesamovar.net Wed May 5 11:51:48 2010 From: dg.gmane at thesamovar.net (Dan Goodman) Date: Wed, 05 May 2010 17:51:48 +0200 Subject: Generating nested code with context managers In-Reply-To: References: Message-ID: I tried a very similar thing, but not using with statements: http://mail.python.org/pipermail/python-list/2010-March/1239577.html Dan On 04/05/2010 22:36, Terry Reedy wrote: > In a current thread, people have claimed that generating properly > indented nested blocks is a pain because of the need to keep track of > indent levels. Someone countered with the now rather ancient > > http://effbot.org/zone/python-code-generator.htm > > The usage example > > c = CodeGeneratorBackend() > c.begin(tab=" ") > c.write("for i in range(1000):\n") > c.indent() > c.write("print 'code generation is trivial'") > c.dedent() > > illustrates three problems with the CodeGeneratorBackend class. 1) it > requires explicit \n on all lines (which the second omits, though it is > non-fatal since it is also the last) 2) the user still has to manually > match indents and dedents, and 3) the user *cannot* indent lines that > produce indented code. > > The relatively new with statement and associated context managers are > designed, among other things, for this situation, where one needs to > alter and restore a global context. So here is my updated (3.1) > proof-of-concept version. > > class PyCodeGen: > def __init__(self, tab=" "): > self.code = [] > self.tab = tab > self.level = 0 > # all attributes should be treated as read-only > def end(self): > return '\n'.join(self.code) > def line(self, string): # new line > self.code.append(self.tab * self.level + string) > > class For: > def __init__(self, target, in_expression): > target.line('for ' + in_expression + ':') > self.target = target > def __enter__(self): > self.target.level += 1 > def __exit__(self, t, v, tb): > self.target.level -= 1 > > c = PyCodeGen() > > with For(c, 'i in range(1000)'): > c.line('print("Code gen is easy")') > c.line('# done') > > print(c.end()) > > # prints > > for i in range(1000): > print("Code gen is easy") > # done > > Note that the absence of .indent and .dedent is intentional. In a > fleshed out system, there would be a context manager for each compound > statement and these would handle all indents and dedents. > > If one really preferred to write, for instance, 'c.For(s); instead of > 'For(c,s)' in the with statement, one could add a wrapper method like > def For(self, s): return For(self, s) > for each context manager. I left that out. > > Similar methods can be used to auto-match C braces and other open/close > pairs. > > Terry Jan Reedy > > > From benjamin.kaplan at case.edu Wed May 5 11:59:44 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 5 May 2010 11:59:44 -0400 Subject: Create a new process to run python function In-Reply-To: References: Message-ID: On Wed, May 5, 2010 at 10:33 AM, James Mills wrote: > On Wed, May 5, 2010 at 10:56 PM, Massi wrote: >> in my script (python 2.5 on windows xp) I need to run a simple >> function in a separate process. In other words I need something >> similar to the fork function under UNIX. I tried with threads: > > Use the new multiprocesing package. > >> import os, threading >> >> def func(s) : >> ? ?print "I'm thread number "+s, os.getpid() >> >> threading.Thread(target=func, args=("1",)).start() >> threading.Thread(target=func, args=("2",)).start() > > Like this: > > import multiprocessing > > multiprocessing.Process(target=func, args=("1",)).start() > multiprocessing.Process(target=func, args=("2",)).start() > > ... > > Surprise surprise it has almost the same API > as the threading module :) > > --James Multiprocessing wasn't added until Python 2.6. http://www.python.org/dev/peps/pep-0371/ In Python 2.5, it was still a 3rd party package. http://pypi.python.org/pypi/processing The project's website appears to be down right now though. http://developer.berlios.de/projects/pyprocessing > -- > http://mail.python.org/mailman/listinfo/python-list > From lists at cheimes.de Wed May 5 12:34:09 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 May 2010 18:34:09 +0200 Subject: Create a new process to run python function In-Reply-To: References: Message-ID: Am 05.05.2010 17:59, schrieb Benjamin Kaplan: > Multiprocessing wasn't added until Python 2.6. > http://www.python.org/dev/peps/pep-0371/ > > In Python 2.5, it was still a 3rd party package. > http://pypi.python.org/pypi/processing > > The project's website appears to be down right now though. > http://developer.berlios.de/projects/pyprocessing Why don't you try out our backport: http://pypi.python.org/pypi/multiprocessing/2.6.2.1 :) From pietro.campe at gmail.com Wed May 5 13:26:18 2010 From: pietro.campe at gmail.com (Pietro Campesato) Date: Wed, 5 May 2010 10:26:18 -0700 (PDT) Subject: Where is python31.dll? Message-ID: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> Hi, recently I've been wondering how to roll my own portable python 3.1 (since there seems to be no portable app specifically for this version). Thinking you can just copy your install folder (+ python's dll), I've noticed that there seems to be no python31.dll in my systems folder (c:\windows\system32\). I cannot find the dll inside the python installation folder either. Another reason I'm asking is because what I've found on the net so far tells you to look for this dll specifically. Am I missing something? Thanks, Alex PS: my setup is version 3.1.2 on windows vista From tjreedy at udel.edu Wed May 5 14:03:26 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 May 2010 14:03:26 -0400 Subject: Teaching Programming In-Reply-To: <4BE13143.6040904@ieee.org> References: <4BE13143.6040904@ieee.org> Message-ID: On 5/5/2010 4:50 AM, Dave Angel wrote: > alex23 wrote: >> Ed Keith wrote: >>> Knuth wanted the generated source to be unreadable, so people would >>> not be tempted to edit the generated code. >> >> This is my biggest issue with Knuth's view of literate programming. If >> the generated source isn't readable, am I just supposed to trust it? >> How can I tell if an error lies in my expression of the algorithm or >> in the code generation itself? >> > Do you think a compiler is required to make its object file conveniently > readable? Do you regularly read the machine code generated by your C > compiler? I admit I've frequently studied compiler output over the > years, but I think I'm very unusual in that respect. I've never > disassembled a python byte code file, The output from dis.dis() is quite readable, and people (developers and others) have used it to check on what the compiler is doing. From tjreedy at udel.edu Wed May 5 14:07:06 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 May 2010 14:07:06 -0400 Subject: Movable Python or ActivePython In-Reply-To: References: Message-ID: On 5/5/2010 8:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for > testing programs. As I read, Movable Python can run without being > installed. It needs no registry entries and knows the path to all the > dlls (system or otherwise) that it uses. > Whats about ActivePython > http://www.activestate.com/activepython/downloads? Does it requires > installation? Yes. It is the standard distribution with extra stuff added and installed. From sridharr at activestate.com Wed May 5 14:19:35 2010 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Wed, 5 May 2010 11:19:35 -0700 Subject: Movable Python or ActivePython In-Reply-To: References: Message-ID: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> On 2010-05-05, at 5:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for testing programs. As I read, Movable Python can run without being installed. It needs no registry entries and knows the path to all the dlls (system or otherwise) that it uses. > Whats about ActivePython http://www.activestate.com/activepython/downloads? Does it requires installation? The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ (substitute with latest version) When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 x64 machine - by extracting and running python.exe (from INSTALLDIR/) without installing - it just worked. -srid From tjreedy at udel.edu Wed May 5 14:20:15 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 May 2010 14:20:15 -0400 Subject: Where is python31.dll? In-Reply-To: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> References: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> Message-ID: On 5/5/2010 1:26 PM, Pietro Campesato wrote: > Hi, > recently I've been wondering how to roll my own portable python 3.1 > (since there seems to be no portable app specifically for this > version). Thinking you can just copy your install folder (+ python's > dll), I've noticed that there seems to be no python31.dll in my > systems folder (c:\windows\system32\). That is where it is on my WinXP system, installed for all users. > I cannot find the dll inside the python installation folder either. > Another reason I'm asking is because what I've found on the net so far > tells you to look for this dll specifically. Am I missing something? Your windows search command? Which is how I verified the above. From lists at cheimes.de Wed May 5 14:40:16 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 May 2010 20:40:16 +0200 Subject: Where is python31.dll? In-Reply-To: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> References: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> Message-ID: Am 05.05.2010 19:26, schrieb Pietro Campesato: > Hi, > recently I've been wondering how to roll my own portable python 3.1 > (since there seems to be no portable app specifically for this > version). Thinking you can just copy your install folder (+ python's > dll), I've noticed that there seems to be no python31.dll in my > systems folder (c:\windows\system32\). > > I cannot find the dll inside the python installation folder either. > Another reason I'm asking is because what I've found on the net so far > tells you to look for this dll specifically. Am I missing something? It's trivial to roll your own portable bundle of Python that doesn't installation. All you need is an installation "for me" instead of an installation for all users. When you install Python just for the current user all necessary files land in the installation directory -- including the main dll and msvcrt stuff. Note that some features like COM and Windows Services require some dependencies in the system32 directory. Christian From python at bdurham.com Wed May 5 15:04:55 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 15:04:55 -0400 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> Message-ID: <1273086295.15686.1373577021@webmail.messagingengine.com> In a recent thread ("Movable Python or ActivePython), Sridhar Ratnakumar pointed out that the ActiveState Python releases can be downloaded as ZIP files vs. MSI files. (Great idea - thank you ActiveState!) > The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: > > http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ I just took a look at the ActiveStatre 2.6.5.12 release (zip file version) and noticed that this file does not include the MSVCR90.DLL run time file - it includes MFC*.DLL files instead (and a different manifest file as well). Can anyone explain why the ActiveState release uses different MS Visual C runtime files than the official Python Foundation's release of Python? Thanks, Malcolm ----- Original message ----- From: "Sridhar Ratnakumar" To: "balzer" Cc: python-list at python.org Date: Wed, 5 May 2010 11:19:35 -0700 Subject: Re: Movable Python or ActivePython On 2010-05-05, at 5:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for testing programs. As I read, Movable Python can run without being installed. It needs no registry entries and knows the path to all the dlls (system or otherwise) that it uses. > Whats about ActivePython http://www.activestate.com/activepython/downloads? Does it requires installation? The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ (substitute with latest version) When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 x64 machine - by extracting and running python.exe (from INSTALLDIR/) without installing - it just worked. -srid From python at bdurham.com Wed May 5 15:04:55 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 15:04:55 -0400 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> Message-ID: <1273086295.15686.1373577021@webmail.messagingengine.com> In a recent thread ("Movable Python or ActivePython), Sridhar Ratnakumar pointed out that the ActiveState Python releases can be downloaded as ZIP files vs. MSI files. (Great idea - thank you ActiveState!) > The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: > > http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ I just took a look at the ActiveStatre 2.6.5.12 release (zip file version) and noticed that this file does not include the MSVCR90.DLL run time file - it includes MFC*.DLL files instead (and a different manifest file as well). Can anyone explain why the ActiveState release uses different MS Visual C runtime files than the official Python Foundation's release of Python? Thanks, Malcolm ----- Original message ----- From: "Sridhar Ratnakumar" To: "balzer" Cc: python-list at python.org Date: Wed, 5 May 2010 11:19:35 -0700 Subject: Re: Movable Python or ActivePython On 2010-05-05, at 5:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for testing programs. As I read, Movable Python can run without being installed. It needs no registry entries and knows the path to all the dlls (system or otherwise) that it uses. > Whats about ActivePython http://www.activestate.com/activepython/downloads? Does it requires installation? The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ (substitute with latest version) When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 x64 machine - by extracting and running python.exe (from INSTALLDIR/) without installing - it just worked. -srid From phd at phd.pp.ru Wed May 5 15:09:39 2010 From: phd at phd.pp.ru (Oleg Broytman) Date: Wed, 5 May 2010 23:09:39 +0400 Subject: SQLObject 0.11.6 Message-ID: <20100505190939.GC23337@phd.pp.ru> Hello! I'm pleased to announce version 0.11.6, a minor bugfix release of 0.11 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.11.6 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.11.5 ----------------- * A bug was fixed in SQLiteConnection.columnsFromSchema(): pass None as size/precision to DecimalCol; DecimalCol doesn't allow default values (to force user to pass meaningful values); but columnsFromSchema() doesn't implement proper parsing of column details. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytman http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From phd at phd.pp.ru Wed May 5 15:11:07 2010 From: phd at phd.pp.ru (Oleg Broytman) Date: Wed, 5 May 2010 23:11:07 +0400 Subject: SQLObject 0.12.4 Message-ID: <20100505191107.GG23337@phd.pp.ru> Hello! I'm pleased to announce version 0.12.4, a minor bugfix release of branch 0.12 of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.12.4 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.12.3 ----------------- * Bugs were fixed in calling from_python(). * A bug was fixed in SQLiteConnection.columnsFromSchema(): pass None as size/precision to DecimalCol; DecimalCol doesn't allow default values (to force user to pass meaningful values); but columnsFromSchema() doesn't implement proper parsing of column details. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytman http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From mgedmin at gmail.com Wed May 5 15:46:25 2010 From: mgedmin at gmail.com (Marius Gedminas) Date: Wed, 5 May 2010 12:46:25 -0700 (PDT) Subject: How to check what is holding reference to object References: <37bce451-4877-44a5-be28-6d4341f9704e@x3g2000yqd.googlegroups.com> Message-ID: <553796db-3c71-41e7-bf35-b89384fda4f2@e2g2000yqn.googlegroups.com> On Apr 28, 3:59?pm, Christian Heimes wrote: > The trick works only for objects that are tracked by CPython's garbage > collector. Simple and non-containerish objects like str, int, unicode > and some other types aren't tracked by the gc. Yes they are -- have you ever tried >>> import gc >>> gc.get_referrers(42) ? Marius Gedminas From mgedmin at gmail.com Wed May 5 15:47:35 2010 From: mgedmin at gmail.com (Marius Gedminas) Date: Wed, 5 May 2010 12:47:35 -0700 (PDT) Subject: How to check what is holding reference to object References: <37bce451-4877-44a5-be28-6d4341f9704e@x3g2000yqd.googlegroups.com> Message-ID: On Apr 27, 11:45?pm, Michal M wrote: > I've just found out that one of objects is not destroyed when it > should be. This means that something was holding reference to this > object or part of it (i.e. method). Is there any way to check what > holds that reference? I am unable to do that just looking to the code > or debugging it because it is pretty complicated, but I am able to > invoke this situation again. I wrote http://pypi.python.org/pypi/objgraph for this purpose. -- Marius Gedminas From saimapk81 at gmail.com Wed May 5 16:09:42 2010 From: saimapk81 at gmail.com (saima81) Date: Wed, 5 May 2010 13:09:42 -0700 (PDT) Subject: "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ Message-ID: <67c321d0-9061-40b3-8680-2e7dc1322da6@s4g2000prh.googlegroups.com> "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD" From martin.hellwig at dcuktec.org Wed May 5 18:01:08 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 May 2010 23:01:08 +0100 Subject: Teaching Programming In-Reply-To: <4be00c33$0$1134$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be00c33$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: On 05/04/10 12:59, superpollo wrote: > Martin P. Hellwig ha scritto: >> For the corner cases (I can think of a couple) it is good to know you >> can use ';' most of the time. >> > > most but not always as i noted (think about loops or function definition) > Well through in some exec magic then, for example: for number in [1,2,3,4]: def nprint(number): print(number) number += 1 nprint(number translates to: >>> exec('for number in [1,2,3,4]:\n\tdef nprint(number):\n\t\tprint(number)\n\tnumber += 1\n\tnprint(number)') 2 3 4 5 But if you have an example why indentation is still a problem please give it :-) -- mph From utente at esempio.net Wed May 5 18:10:52 2010 From: utente at esempio.net (superpollo) Date: Thu, 06 May 2010 00:10:52 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be00c33$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4be1eced$0$816$4fafbaef@reader5.news.tin.it> Martin P. Hellwig ha scritto: > On 05/04/10 12:59, superpollo wrote: >> Martin P. Hellwig ha scritto: > >>> For the corner cases (I can think of a couple) it is good to know you >>> can use ';' most of the time. >>> >> >> most but not always as i noted (think about loops or function definition) >> > Well through in some exec magic then, for example: > for number in [1,2,3,4]: > def nprint(number): > print(number) > number += 1 > nprint(number > > translates to: > > >>> exec('for number in [1,2,3,4]:\n\tdef > nprint(number):\n\t\tprint(number)\n\tnumber += 1\n\tnprint(number)') > 2 > 3 > 4 > 5 > > But if you have an example why indentation is still a problem please > give it :-) > i think your exec example solved most of my problems. thanks a lot. bye From trentm at activestate.com Wed May 5 19:02:53 2010 From: trentm at activestate.com (Trent Mick) Date: Wed, 05 May 2010 16:02:53 -0700 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <1273086295.15686.1373577021@webmail.messagingengine.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> <1273086295.15686.1373577021@webmail.messagingengine.com> Message-ID: <4BE1F91D.8050201@activestate.com> On 10-05-05 12:04 PM, python at bdurham.com wrote: > I just took a look at the ActiveStatre 2.6.5.12 release (zip file > version) and noticed that this file does not include the MSVCR90.DLL run > time file - it includes MFC*.DLL files instead (and a different manifest > file as well). > > Can anyone explain why the ActiveState release uses different MS Visual > C runtime files than the official Python Foundation's release of Python? It doesn't. We use the same MSVC version as the python.org builds. Note that "MFC*.dll" files (IIRC, it has been a while) are redistributable DLLs used by the included PyWin32 extensions that have Python bindings for the Microsoft Foundation Classes GUI APIs. Trent -- Trent Mick trentm at activestate.com http://trentm.com/blog/ From gagsl-py2 at yahoo.com.ar Wed May 5 19:04:23 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 May 2010 20:04:23 -0300 Subject: find out whther byte two .pyc files contain the same byte code. References: <8d53dbc5-9ad0-44ed-881f-fa2b6fc82e96@i9g2000yqi.googlegroups.com> Message-ID: En Wed, 05 May 2010 10:34:34 -0300, gelonida escribi?: > I'd like to know whether the byte code of two .pyc files is identical. > > I thought, I could just compare the md5sums of thw .pyc files. > However this does not work. > > It seems, that .pyc ontains the time stamp of the source file. > the .pyc file changes its contents when I don't change the file's > contents but just > save it again. Yes, that's what happens. First 4 bytes in a .pyc file contain a "magic" number identifying the Python version used to create it. Next 4 bytes contain the timestamp of the source file. Just ignore the first 8 bytes when computing the checksum: tail -c +8 tst.pyc | md5sum (untested) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed May 5 19:30:44 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 May 2010 20:30:44 -0300 Subject: Python Embedding, no correct lib References: <5d90e51f-133f-4b01-9074-9fdc3eb37d59@e35g2000yqm.googlegroups.com> Message-ID: En Wed, 05 May 2010 09:04:06 -0300, moerchendiser2k3 escribi?: > I have a serious problem with Python. I am currently trying to > implement Python into my app. > Well this works fine, but get this: > > I have my own Python interpreter in a subfolder of my app. When I > start my app, PYTHONHOME is set, and an environment variable is set to > it can find the python DLL on startup. You should not define any environment variables. You are embedding Python into your application, aren't you? That is, you call Py_Initialize and all that stuff - you don't invoke a separate python.exe, true? Python tries to find its standard library looking for [the directory containing the executable]\Lib\os.py and a few other places. Once it finds the "Lib" directory, all other are derived from it. > When Python is not installed on the system everything works fine as > expected. > > When I now install Python on my system (so I have two python libs now) > the system installation is the preferred one. > > print sys.path prints out ['', 'C:\Windows > \system32\python26.zip', ...] and I cant explain whats going wrong > here. Such zip file doesn't even exist in a standard Python installation; but it means that your program loaded python26.dll from the system32 directory, not your own copy. You may want to use a .local file or a manifest; see http://msdn.microsoft.com/en-us/library/ms811694.aspx > I expected that it just uses the System lib when it cannot find > it in the subfolder which I set in the environment variables > before.. :-( Note that this is a Windows issue, not a Python one. You have to ensure the Python DLL is loaded from your own directory, not the system one. (BTW, don't set any environment variables. There is no need to do so, and it may conflict with an existing installation. The reverse is true too: a PYTHONPATH variable set for the "system" Python will interfere with your private copy too. Global state is always a bad idea.) -- Gabriel Genellina From googler.1.webmaster at spamgourmet.com Wed May 5 19:51:56 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Wed, 5 May 2010 16:51:56 -0700 (PDT) Subject: Python Embedding, no correct lib References: <5d90e51f-133f-4b01-9074-9fdc3eb37d59@e35g2000yqm.googlegroups.com> Message-ID: <7d400ac1-d3dc-4212-ad98-1bd9d0a51fca@l28g2000yqd.googlegroups.com> On 6 Mai, 01:30, "Gabriel Genellina" wrote: > En Wed, 05 May 2010 09:04:06 -0300, moerchendiser2k3 ? > escribi?: > > > I have a serious problem with Python. I am currently trying to > > implement Python into my app. > > Well this works fine, but get this: > > > I have my own Python interpreter in a subfolder of my app. When I > > start my app, PYTHONHOME is set, and an environment variable is set to > > it can find the python DLL on startup. > > You should not define any environment variables. > > You are embedding Python into your application, aren't you? That is, you ? > call Py_Initialize and all that stuff - you don't invoke a separate ? > python.exe, true? > > Python tries to find its standard library looking for > [the directory containing the executable]\Lib\os.py > and a few other places. Once it finds the "Lib" directory, all other are ? > derived from it. > > > When Python is not installed on the system everything works fine as > > expected. > > > When I now install Python on my system (so I have two python libs now) > > the system installation is the preferred one. > > > print sys.path prints out ['', 'C:\Windows > > \system32\python26.zip', ...] and I cant explain whats going wrong > > here. > > Such zip file doesn't even exist in a standard Python installation; but it ? > means that your program loaded python26.dll from the system32 directory, ? > not your own copy. You may want to use a .local file or a manifest; seehttp://msdn.microsoft.com/en-us/library/ms811694.aspx > > > I expected that it just uses the System lib when it cannot find > > it in the subfolder which I set in the environment variables > > before.. :-( > > Note that this is a Windows issue, not a Python one. You have to ensure ? > the Python DLL is loaded from your own directory, not the system one. > > (BTW, don't set any environment variables. There is no need to do so, and ? > it may conflict with an existing installation. The reverse is true too: a ? > PYTHONPATH variable set for the "system" Python will interfere with your ? > private copy too. Global state is always a bad idea.) > > -- > Gabriel Genellina Hi Gabriel, thanks very much for your information. I found the solution. This is related to this one. The order of the search path is the explanation why the system one is used: http://msdn.microsoft.com/en-us/library/ms682586(VS.85).aspx So 'Alternate Search Order' is the solution. :) Bye, moerchendiser2k3 From cs at zip.com.au Wed May 5 20:21:45 2010 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 6 May 2010 10:21:45 +1000 Subject: strange interaction between open and cwd In-Reply-To: <4BE16327.5050209@ftml.net> References: <4BE16327.5050209@ftml.net> Message-ID: <20100506002144.GA26948@cskk.homeip.net> On 05May2010 13:23, Baz Walter wrote: | here's what i get on my system, where '/dev/sda1' and '/dev/sda6' | are mounted at '/boot' and '/home' respectively: | | >>> os.stat('/').st_ino | 2L | >>> os.stat('/usr').st_ino | 212993L | >>> os.stat('/boot').st_ino | 2L | >>> os.stat('/home').st_ino | 2L | >>> | | if the algorithm is climbing up from '/home/baz/tmp/xxx', what does | it do when it searches os.listdir('../../../..')? how can it tell | whether 'boot' or 'home' is the correct next parent if it only | checks the inode number? i think the algorithm would at least need | to take account of changes in the current device id. not sure | whether that would be enough to cover all cases, though. Look at the st_rdev field (== the device holding this inode). When that changes, you've crossed a mount mount point. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Usenet is essentially a HUGE group of people passing notes in class. --R. Kadel From python at bdurham.com Wed May 5 20:30:47 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 20:30:47 -0400 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <4BE1F91D.8050201@activestate.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> <1273086295.15686.1373577021@webmail.messagingengine.com> <4BE1F91D.8050201@activestate.com> Message-ID: <1273105847.779.1373624397@webmail.messagingengine.com> Hi Trent, On 10-05-05 12:04 PM, python at bdurham.com wrote: >> I just took a look at the ActiveStatre 2.6.5.12 release (zip file >> version) and noticed that this file does not include the MSVCR90.DLL run >> time file - it includes MFC*.DLL files instead (and a different manifest >> file as well). >> >> Can anyone explain why the ActiveState release uses different MS Visual >> C runtime files than the official Python Foundation's release of Python? > It doesn't. We use the same MSVC version as the python.org builds. > > Note that "MFC*.dll" files (IIRC, it has been a while) are > redistributable DLLs used by the included PyWin32 extensions that have > Python bindings for the Microsoft Foundation Classes GUI APIs. Yes, you are correct about the MFC*.dll's being shipped as part of the Py2Win32 extensions. But I don't see the MSVCR90.DLL in your ZIP release. I do see a MSVCR71.DLL. Malcolm From vincent at vincentdavis.net Wed May 5 21:12:35 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Wed, 5 May 2010 19:12:35 -0600 Subject: Encrypt password within source code. Message-ID: I can't think of a way to do this, not sure it is possible but I feel as though I might not know what I don't know. I want to share and example of a python script, to run it needs a google username and password. Is there a way for me to encrypt my username and password in the source code? I though about openID but don't really know anything about it. *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed May 5 21:44:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 May 2010 18:44:59 -0700 Subject: Encrypt password within source code. In-Reply-To: References: Message-ID: On Wed, May 5, 2010 at 6:12 PM, Vincent Davis wrote: > I can't think of a way to do this, not sure it is possible but I feel as though I might not know what I don't know. > I want to share and example of a python script, to run it needs a google username and password. Is there a way for me to encrypt my username and password in the source code? I though about openID but don't really know anything about it. Nope. What you're asking for is essentially a form of DRM by including the information in a way the program can use it but the user can't extract it; DRM schemes have been broken many times and the idea is flawed even in theory, for if a person has control of their computer (or in the limit case, at least physical access to its innards), they can just watch the computation (e.g. memory snoop) until the data gets converted to its plain form so the program can actually utilize it, and then bada-bing, they have your valuable data. Think of it this way. If you encrypted the information in your program, the program would need to be able to decrypt it later so it could actually use the login info. For it to be able to do that, you'd have to include the encryption key in plaintext somewhere in the program so it could pass it into the decryption algorithm. But then someone can put 2 and 2 together, see that "there's his key!", and decrypt your info using the key. So, to prevent this, the key *itself* would then have to be encrypted...by another key, which again would be stored in plaintext in your program somewhere, where someone could then find it and use it to decrypt the first key and then your data, so you use yet another key to encrypt that key...(as you can see, this goes on ad infinitum, and thus the whole scheme is doomed). See also section 1, "DRM Systems Don't Work", of http://changethis.com/manifesto/show/4.DRM You can alternatively just try to obfuscate it, but that's obviously not truly secure and is likewise easily circumvented. Just let the user input their own Google Account info. If you're trying to show an example that depends on your own exact account, just include a transcript of your terminal session (omitting your Google Account info obviously). Cheers, Chris -- DRM is http://defectiveByDesign.org http://blog.rebertia.com From python.list at tim.thechases.com Wed May 5 21:48:22 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 05 May 2010 20:48:22 -0500 Subject: Encrypt password within source code. In-Reply-To: References: Message-ID: <4BE21FE6.9060506@tim.thechases.com> On 05/05/2010 08:12 PM, Vincent Davis wrote: > I can't think of a way to do this, not sure it is possible but I feel as > though I might not know what I don't know. > > I want to share and example of a python script, to run it needs a google > username and password. Is there a way for me to encrypt my username and > password in the source code? No-ish. You can encrypt it, but if you encrypt it, you need to include the keys or algorithm for decrypting it, and all it takes is a pdb.set_trace() before the decrypted uname/pwd get sent to Google to get it, and poof all your encryption/decryption has been in vain: uname = SUPER_ENCRYPTED_USER pwd = SUPER_ENCRYPTED_PASSWORD u = secret_decrypt(uname) p = secret_decrypt(pwd) # regardless of how good the stuff above is # you're vulnerable right here: # print "%r %r" % (u, p) do_google_stuff(u, p) Unless the Google API you're using allows for chain-of-authority creation of sub-credentials (so your account creates secondary accounts that are then distributed in your code/config files and managed via your dev login), two possibilities that come to mind: 1) put in a bogus uname/password and make them get their own Google login to put in (which can be done in a config file if they're squeamish about editing source code) This assumes that any arbitrary Google login can grant access to what you want (sometimes this is a developer key, in which case the user would need to get their own dev key). 2) create a web-service on a server somewhere that has your credentials, but your distributed code merely hits this web service instead of having your actual credentials in the source (plain-text or encrypted). The server would have them (I'd just put them in plain-text -- no need to be fancy. If you can't trust your hosting service, don't use them) but you wouldn't expose the credentials outside the application. -tkc From dreadpiratejeff at gmail.com Wed May 5 22:47:25 2010 From: dreadpiratejeff at gmail.com (J) Date: Wed, 5 May 2010 22:47:25 -0400 Subject: Is there a better way to set a system clock in Python (on a Linux system) Message-ID: Is there a better way to do this? def SkewTime(): ''' Optional function. We can skew time by 1 hour if we'd like to see real sync changes being enforced ''' TIME_SKEW=1 logging.info('Time Skewing has been selected. Setting clock ahead 1 hour') # Let's get our current time t = TimeCheck() logging.info('Current time is: %s' % time.asctime(t)) # Now create new time string in the form MMDDhhmmYYYY for the date program hr = t.tm_hour + TIME_SKEW date_string = time.strftime('%m%d%H%M%Y',(t.tm_year, t.tm_mon, t.tm_mday, hr, t.tm_min, t.tm_sec, t.tm_wday, t.tm_yday, t.tm_isdst)) logging.debug('New date string is: %s' % date_string) logging.debug('Setting new system time/date') status = SilentCall('/bin/date %s' % date_string) logging.info('Pre-sync time is: %s' % time.asctime()) TimeCheck() as referenced above is a simple function that just returns the time.time_struct object from time.localtime(). I pull time a few times and it was a little cleaner to put that into a function and just call the function whenever I needed to. SilentCall() is a modification of subprocess.call() (which in reality just calls Popen(*popenargs,**kwargs).wait()) but it defaults to redirecting stdin and stdout to /dev/null to suppress shell output from the command being called. Anyway, what I'm wondering, is, while this works, is there a better way to do it than using part of the originally returned time_struct and injecting my own new hour argument (hr). The goal of this function is to just set the system clock one hour ahead, so when I call the Linux command 'ntpdate' I can get a real time change when it syncs the local clock to an NTP server. This just looks... well, big to me. I tried passing only the things I really needed to time.strftime(), but apparently, that requires the full 9-tuple from time_struct, not just individual parts of it. Like I said, it works well, I just wonder if there is a cleaner way of setting the local clock to a different time in python without having to do all this. The reason most of that exists, is because the linux date command expects to see the new date/time like this: MMDDhhmmYYYY.ss. Or am I just looking at this too hard and really did work it out nicely? Cheers Jeff From clp2 at rebertia.com Wed May 5 23:01:44 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 May 2010 20:01:44 -0700 Subject: Is there a better way to set a system clock in Python (on a Linux system) In-Reply-To: References: Message-ID: On Wed, May 5, 2010 at 7:47 PM, J wrote: > Is there a better way to do this? Yes: from datetime import datetime, timedelta > def SkewTime(): > ? ?''' > ? ?Optional function. We can skew time by 1 hour if we'd like to see real sync > ? ?changes being enforced > ? ?''' > ? ?TIME_SKEW=1 > ? ?logging.info('Time Skewing has been selected. Setting clock ahead 1 hour') > ? ?# Let's get our current time skewed = datetime.now() + timedelta(hours=TIME_SKEW) > ? ?# Now create new time string in the form MMDDhhmmYYYY for the date program date_time_str = skewed.strftime('%m%d%H%M%Y') ? ?logging.debug('New date string is: %s' % date_time_str) > ? ?logging.debug('Setting new system time/date') ? ?status = SilentCall('/bin/date %s' % date_time_str) > ? ?logging.info('Pre-sync time is: %s' % time.asctime()) > > Anyway, what I'm wondering, is, while this works, is there a better > way to do it than using part of the originally returned time_struct > and injecting my own new hour argument (hr). Use the datetime module roughly as shown. (Disclaimer: Code is untested). Also, I'm not sure if your original code worked properly after 11PM; my code definitely should. > This just looks... well, big to me. ?I tried passing only the things I > really needed to time.strftime(), but apparently, that requires the > full 9-tuple from time_struct, not just individual parts of it. Cheers, Chris -- http://blog.rebertia.com From killy.draw at gmail.com Wed May 5 23:01:54 2010 From: killy.draw at gmail.com (KDr2) Date: Thu, 6 May 2010 11:01:54 +0800 Subject: Is there a better way to set a system clock in Python (on a Linux system) In-Reply-To: References: Message-ID: man 2 clock_settime call it with ctypes -- Best Regards, -- KDr2 http://kdr2.net On Thu, May 6, 2010 at 10:47 AM, J wrote: > Is there a better way to do this? > > def SkewTime(): > ''' > Optional function. We can skew time by 1 hour if we'd like to see real > sync > changes being enforced > ''' > TIME_SKEW=1 > logging.info('Time Skewing has been selected. Setting clock ahead 1 > hour') > # Let's get our current time > t = TimeCheck() > logging.info('Current time is: %s' % time.asctime(t)) > # Now create new time string in the form MMDDhhmmYYYY for the date > program > hr = t.tm_hour + TIME_SKEW > date_string = time.strftime('%m%d%H%M%Y',(t.tm_year, > t.tm_mon, > t.tm_mday, > hr, > t.tm_min, > t.tm_sec, > t.tm_wday, > t.tm_yday, > t.tm_isdst)) > logging.debug('New date string is: %s' % date_string) > logging.debug('Setting new system time/date') > status = SilentCall('/bin/date %s' % date_string) > logging.info('Pre-sync time is: %s' % time.asctime()) > > TimeCheck() as referenced above is a simple function that just returns > the time.time_struct object from time.localtime(). I pull time a few > times and it was a little cleaner to put that into a function and just > call the function whenever I needed to. > > SilentCall() is a modification of subprocess.call() (which in reality > just calls Popen(*popenargs,**kwargs).wait()) but it defaults to > redirecting stdin and stdout to /dev/null to suppress shell output > from the command being called. > > Anyway, what I'm wondering, is, while this works, is there a better > way to do it than using part of the originally returned time_struct > and injecting my own new hour argument (hr). > > The goal of this function is to just set the system clock one hour > ahead, so when I call the Linux command 'ntpdate' I can get a real > time change when it syncs the local clock to an NTP server. > > This just looks... well, big to me. I tried passing only the things I > really needed to time.strftime(), but apparently, that requires the > full 9-tuple from time_struct, not just individual parts of it. > > Like I said, it works well, I just wonder if there is a cleaner way of > setting the local clock to a different time in python without having > to do all this. The reason most of that exists, is because the linux > date command expects to see the new date/time like this: > MMDDhhmmYYYY.ss. > > Or am I just looking at this too hard and really did work it out nicely? > > Cheers > Jeff > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at vincentdavis.net Wed May 5 23:10:56 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Wed, 5 May 2010 21:10:56 -0600 Subject: Encrypt password within source code. In-Reply-To: <4BE21FE6.9060506@tim.thechases.com> References: <4BE21FE6.9060506@tim.thechases.com> Message-ID: Thanks for the replies I though the answer was no. Vincent On Wed, May 5, 2010 at 7:48 PM, Tim Chase wrote: > On 05/05/2010 08:12 PM, Vincent Davis wrote: > >> I can't think of a way to do this, not sure it is possible but I feel as >> though I might not know what I don't know. >> >> I want to share and example of a python script, to run it needs a google >> username and password. Is there a way for me to encrypt my username and >> password in the source code? >> > > No-ish. You can encrypt it, but if you encrypt it, you need to include the > keys or algorithm for decrypting it, and all it takes is a pdb.set_trace() > before the decrypted uname/pwd get sent to Google to get it, and poof all > your encryption/decryption has been in vain: > > uname = SUPER_ENCRYPTED_USER > pwd = SUPER_ENCRYPTED_PASSWORD > u = secret_decrypt(uname) > p = secret_decrypt(pwd) > # regardless of how good the stuff above is > # you're vulnerable right here: > # print "%r %r" % (u, p) > do_google_stuff(u, p) > > Unless the Google API you're using allows for chain-of-authority creation > of sub-credentials (so your account creates secondary accounts that are then > distributed in your code/config files and managed via your dev login), two > possibilities that come to mind: > > 1) put in a bogus uname/password and make them get their own Google login > to put in (which can be done in a config file if they're squeamish about > editing source code) This assumes that any arbitrary Google login can grant > access to what you want (sometimes this is a developer key, in which case > the user would need to get their own dev key). > > 2) create a web-service on a server somewhere that has your credentials, > but your distributed code merely hits this web service instead of having > your actual credentials in the source (plain-text or encrypted). The server > would have them (I'd just put them in plain-text -- no need to be fancy. If > you can't trust your hosting service, don't use them) but you wouldn't > expose the credentials outside the application. > > -tkc > > > > > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Wed May 5 23:20:10 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 23:20:10 -0400 Subject: Looking for a gettext and/or Babel tutorial for Windows Message-ID: <1273116010.24126.1373643559@webmail.messagingengine.com> I'm looking for a gettext and/or Babel tutorial for Windows. Any suggestions? Specific topics I'm interested in: 1. Understanding the full life cycle of PO/POT and MO files from their initial creation to their ongoing maintenance (under Windows) 2. Automating the use of pygettext and msgfmt.py (or their GNU gettext equivalents) to update PO and MO files (under Windows) 3. Where to store my MO files (under Windows) - is there a best practice location for these files? In the absence of a tutorial, I'm open to looking at source code and/or batch/command/script/make files. Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From r1chardj0n3s at gmail.com Wed May 5 23:35:30 2010 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Thu, 6 May 2010 13:35:30 +1000 Subject: PyCon Australia Early-Bird running out! Message-ID: Registration is open and the Early Bird tickets are running out. Register here: http://pycon-au.org/reg We offer two levels of registration for PyCon Australia 2010: Full (Early Bird) - $165 This is the registration rate for regular attendees. We're offering a limited Early Bird rate for the first 50 to registration. Once the Early Bird slots are filled registration will increase to $198. Full registration includes one seat at the conference dinner on Saturday night. Student - $44 For students able to present a valid student card we're offering this reduced rate. Student registrations do not include a seat at the conference dinner. Additional seats at the conference dinner may be purchased for $77 each. All prices include GST. Information about the registration process is on the PyCon Australia website. Register here: http://pycon-au.org/reg From pietro.campe at gmail.com Wed May 5 23:52:39 2010 From: pietro.campe at gmail.com (Pietro Campesato) Date: Wed, 5 May 2010 20:52:39 -0700 (PDT) Subject: Where is python31.dll? References: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> Message-ID: <78087231-bdd2-4ebc-91b0-ade65af18f9d@k19g2000yqm.googlegroups.com> > Your windows search command? > Which is how I verified the above. I looked at the folder visually. Simply using os.listdir shows there is in fact a python31.dll there: somehow it was an invisible file. This is strange since I've never touched any system folder. Thanks and forgive me if I have asked the group a silly question. From nobody at nowhere.com Thu May 6 00:16:40 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 06 May 2010 05:16:40 +0100 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: On Wed, 05 May 2010 13:23:03 +0100, Baz Walter wrote: >>> so >>> if several filesystems are mounted in the same parent directory, there is >>> no way to tell which of them is the "right" one. >> >> The only case which would cause a problem here is if you mount the same >> device on two different subdirectories of a common directory. But in that >> case, it doesn't really matter which answer you get, as they're both >> equivalent in any sense that matters. > > nope! just to be clear: > > here's what i get on my system, where '/dev/sda1' and '/dev/sda6' are > mounted at '/boot' and '/home' respectively: > > >>> os.stat('/').st_ino > 2L > >>> os.stat('/usr').st_ino > 212993L > >>> os.stat('/boot').st_ino > 2L > >>> os.stat('/home').st_ino > 2L > >>> Right. /, /boot and /home are separate filesystems; ext2/ext3 filesystems normally use inode #2 as the root directory. If you look at the st_dev field, all three will be different (for /boot and /home, they'll correspond to sda1 and sda6 respectively). > if the algorithm is climbing up from '/home/baz/tmp/xxx', what does it > do when it searches os.listdir('../../../..')? how can it tell whether > 'boot' or 'home' is the correct next parent if it only checks the inode > number? It doesn't. Inode numbers are only unique within a single device; you need to use both st_dev and st_ino to uniquely identify an inode within a complete filesystem. > i think the algorithm would at least need to take account of > changes in the current device id. not sure whether that would be enough > to cover all cases, though. st_dev+st_ino is sufficient. From nobody at nowhere.com Thu May 6 00:24:33 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 06 May 2010 05:24:33 +0100 Subject: strange interaction between open and cwd References: <4BE16327.5050209@ftml.net> Message-ID: On Thu, 06 May 2010 10:21:45 +1000, Cameron Simpson wrote: > Look at the st_rdev field (== the device holding this inode). > When that changes, you've crossed a mount mount point. st_dev reports the device on which the inode resides. st_rdev is only meaningul if the inode type is block device (S_IFBLK) or character device (S_IFCHR), in which case it identifies the device to which the inode refers, e.g.: > os.stat("/").st_dev 2049L > os.stat("/").st_rdev 0 > os.stat("/dev/sda1").st_dev 2049L > os.stat("/dev/sda1").st_rdev 2049 > os.stat("/dev/sda2").st_dev 2049L > os.stat("/dev/sda2").st_rdev 2050 (/dev/sda1 is mounted as the root filesystem). From cs at zip.com.au Thu May 6 02:00:27 2010 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 6 May 2010 16:00:27 +1000 Subject: strange interaction between open and cwd In-Reply-To: References: Message-ID: <20100506060026.GA6171@cskk.homeip.net> On 06May2010 05:24, Nobody wrote: | On Thu, 06 May 2010 10:21:45 +1000, Cameron Simpson wrote: | | > Look at the st_rdev field (== the device holding this inode). | > When that changes, you've crossed a mount mount point. | | st_dev reports the device on which the inode resides. | | st_rdev is only meaningul if the inode type is block device (S_IFBLK) or | character device (S_IFCHR), in which case it identifies the device to | which the inode refers, e.g.: Gah. Yes, you're quite right. st_dev is what I should have been citing. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ It's better, when you're riding with someone you don't know so well, to stick to the inside line - it's easier to avoid the bits... - Barry Sheene From no.email at nospam.invalid Thu May 6 02:55:23 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 05 May 2010 23:55:23 -0700 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: <7x7hnhjz8k.fsf@ruckus.brouhaha.com> see at sig.for.address (Victor Eijkhout) writes: > I have two long ints, both too long to convert to float, but their ratio > is something reasonable. How can I compute that? The obvious "(1.*x)/y" > does not work. The math.log function has a special hack for long ints, that might help: Python 2.6.2 (r262:71600, Jan 25 2010, 18:46:47) >>> from math import * >>> a = log(3**100000) >>> a 109861.22886681097 >>> b = log(3**100001) >>> exp(b-a) 2.9999999999994813 From no.email at nospam.invalid Thu May 6 02:59:23 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 05 May 2010 23:59:23 -0700 Subject: Sharing a program I wrote References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: <7x39y5jz1w.fsf@ruckus.brouhaha.com> Scott writes: > I've seen pypi. It seems to index code that is posted on all sorts of > sites - including pypi itself? And what is a "package" anyway? I've > seen sourceforge. It looks like a good home for big applications or > multi-developer projects. Freshmeat? Google code? My own website? Your > blog? My friends like github.com for code hosting. There is an xkcd about it: http://xkcd.com/624/ If it's just a one-off script that you want comments on, you can post it here on clpy. Or if you want to chat with other programmers about it, download an irc client and visit #python on irc.freenode.net. From ldo at geek-central.gen.new_zealand Thu May 6 03:14:23 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 06 May 2010 19:14:23 +1200 Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: In message <685761fe-b052-4d89-92d3-17d1f2a39e34 at p2g2000yqh.googlegroups.com>, Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > x = and True or False I suspect the ?boolean expression? isn?t actually evaluating to a Boolean at all, this is simply a long-winded way of converting values that Python treats as ?false? (e.g. None, 0, what else?) to actual False, and everything else to True. From news1234 at free.fr Thu May 6 03:34:50 2010 From: news1234 at free.fr (News123) Date: Thu, 06 May 2010 09:34:50 +0200 Subject: modifying open office spreadsheet (with OO installed) In-Reply-To: References: <4bd8aa92$0$2118$426a34cc@news.free.fr> <4bd9ec94$0$24904$426a74cc@news.free.fr> <4BD9FB33.90208@comcast.net> Message-ID: <4be2711a$0$12973$426a74cc@news.free.fr> Hi CHris, Chris Withers wrote: > Jim Byrnes wrote: >> News123 wrote: >>> Mumbling to myself, perhaps somebody else is interested. >> >> Yes I am. >> >>> News123 wrote: >>>> Hi, >>>> >>>> >>>> I wanted to know who can recommend a good module/library, that >>>> allows to >>>> modify an Open Office spreadsheet. >>>> >>>> One can assume, that Open Office is installed on the host. >>>> >>>> >>> Following url gives a small introduction about using the PyUno-bridge to >>> open-read-modify-save a spread sheet >>> http://stuvel.eu/ooo-python > > If .xls files are an option for you, xlutils.copy is your friend: > > https://secure.simplistix.co.uk/svn/xlutils/trunk/xlutils/docs/copy.txt > In fact I like this library and for some things I intend to do it's a rather nice option. However for changing a few fields and keeping all the rest exactly as it is it doesn't seem to be the most apropriate solution (without some hacking) as formulas might get lost. > cheers, > > Chris > From news1234 at free.fr Thu May 6 03:38:31 2010 From: news1234 at free.fr (News123) Date: Thu, 06 May 2010 09:38:31 +0200 Subject: ooolib, reading writing a spread sheet and keep formatting In-Reply-To: References: <4bd8cfc3$0$667$426a74cc@news.free.fr> <4BD94090.8060005@free.fr> <4BE09A9B.60404@free.fr> Message-ID: <4be271f7$0$12973$426a74cc@news.free.fr> Hi Chris, Chris Withers wrote: > News123 wrote: >> Hi Chris, >> >> >> Chris Withers wrote: >>> News123 wrote: >>>> from xlrd import open_workbook >>>> from xlutils.copy import copy >>>> >>>> rb = open_workbook('doc1.xls') >>> open_workbook('doc1.xls',formatting_info=True) >> >> I'll try, but the doc mentioned explicitely, that formulas will be lost. >> I'll keep you updated. > > Yup, for them to be preserved, someone needs to either provide the > patches or stump up the cash to get the features implemented. Thanks for your clarification. You want to say, that there is a newer version or patches, which will treat formulas? Might be interestng. Currently Iswitched to the uno module, which is a little bulky, but generates for my case the correct docs on any system with OO installed. N From lucaberto at libero.it Thu May 6 03:40:50 2010 From: lucaberto at libero.it (luca72) Date: Thu, 6 May 2010 00:40:50 -0700 (PDT) Subject: pysms Message-ID: Hello Has anyone used pysms can you tell me with wich gsm module it works? Thanks Luca From andreas.loescher at s2005.tu-chemnitz.de Thu May 6 03:56:41 2010 From: andreas.loescher at s2005.tu-chemnitz.de (Andreas =?ISO-8859-1?Q?L=F6scher?=) Date: Thu, 06 May 2010 09:56:41 +0200 Subject: Parser In-Reply-To: <1272830042.14469.1.camel@laptop> References: <1272830042.14469.1.camel@laptop> Message-ID: <1273132601.4785.0.camel@laptop> Am Sonntag, den 02.05.2010, 21:54 +0200 schrieb Andreas L?scher: > Hi, > I am looking for an easy to use parser. I am want to get an overview > over parsing and want to try to get some information out of a C-Header > file. Which parser would you recommend? > > Best, > Andreas > Thanks for your answers. I think I will have a look at ANTLR to do some parsing. Best, Andreas From mkiever at Pirx.sirius.org Thu May 6 04:00:30 2010 From: mkiever at Pirx.sirius.org (Matthias Kievernagel) Date: Thu, 6 May 2010 08:00:30 +0000 (UTC) Subject: py3 tkinter acceps bytes. why? References: >>Me: >> I asked what kinds of bytes are accepted as tkinter parameters. >> I still wonder why they are accepted at all. >> Does anyone know a reason for this >> or has a link to some relevant discussion? >Terry Reedy: > I do not remember any particular public discussion of tkinter on the dev > lists. I suspect the reason is a) avoid breaking old code and b) tkinter > (tk inter-face) passes params on to tk which expects byte strings. I > would not be surprised if tkinter has to encode py3 (unicode) strings > before passing them on. If I interpret the code in _tkinter.c correctly Python bytes are converted to a String Tcl_Obj and Python str to a Unicode Tcl_Obj: AsObj(PyObject *value) { ... if (PyBytes_Check(value)) return Tcl_NewStringObj(PyBytes_AS_STRING(value), PyBytes_GET_SIZE(value)); ... else if (PyUnicode_Check(value)) { ... return Tcl_NewUnicodeObj(inbuf, size); ... } And as Martin pointed out: >That's basically because the port from 2.x was shallow: it supports the >exact same feature set that 2.x supports, with just the type names >swapped. If I don't want bytes to get passed to tkinter I just have to raise an exception in AsObj, no? Or is it even sufficient to just remove the bytes case? Regards and thanks for your answers. Matthias Kievernagel. From dickinsm at gmail.com Thu May 6 04:22:09 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 6 May 2010 01:22:09 -0700 (PDT) Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> <1jhxakp.1xj5u9nd6k7x7N%see@sig.for.address> Message-ID: On May 3, 9:49?pm, s... at sig.for.address (Victor Eijkhout) wrote: > Jerry Hill wrote: > > >>> from __future__ import division > > >>> long1/long2 > > 0.5 > > Beautiful. Thanks so much guys. And if for some reason you don't want to use the 'from __future__' import, then you can do long1.__truediv__(long2): >>> n = 765*10**1000 + 1 >>> n.__truediv__(n+1) 1.0 If you care about speed at all, I'd avoid the Fractions solution; it does an expensive and slow gcd computation. -- Mark From mannu_0523 at rediffmail.com Thu May 6 04:22:53 2010 From: mannu_0523 at rediffmail.com (mannu jha) Date: 6 May 2010 08:22:53 -0000 Subject: =?utf-8?B?Y29sdW1uIHNlbGVjdGlvbg==?= Message-ID: <20100506082253.25882.qmail@f4mail-235-130.rediffmail.com> Hi, I have few files like this: 24 ALA helix (helix_alpha, helix2) 27 ALA helix (helix_alpha, helix2) 51 ALA helix (helix_alpha, helix4) 58 ALA helix (helix_alpha, helix5) 63 ALA helix (helix_alpha, helix5) now with this program: for line in open('1.txt'): columns = line.split() print columns[0], columns[2] I am trying to print only 1st and third column but it showing error like: mruser at caf:~> python split.py 24 helix Traceback (most recent call last): File "split.py", line 3, in print columns[0], columns[2] IndexError: list index out of range nmruser at caf:~> how to rectify it. Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From massi_srb at msn.com Thu May 6 04:22:54 2010 From: massi_srb at msn.com (Massi) Date: Thu, 6 May 2010 01:22:54 -0700 (PDT) Subject: ctypes:Multiple library access problem Message-ID: <87a9ce5a-aa16-44f2-bcd7-7b790fe75466@b7g2000yqk.googlegroups.com> Hi everyone, in my script I need to execute multiple separated loading of the same dll library, in order to handle the internal variables with different threads. Consider the followin piece of code: lib1 = cdll.LoadLibrary("MyLib.dll")) lib2 = cdll.LoadLibrary("MyLib.dll")) lib1.var1 = 0 lib2.var1 = 1 Now, if I print the value of lib1.var1 I get 1, that is lib1 and lib2 point to the same memory space. Is there a way to create "different instances" of the same library? Or, alternatively, does it exist any workaround to avoid lib1 and lib2 share the same memory space? Thanks in advance. From kurianmthayil at gmail.com Thu May 6 04:47:40 2010 From: kurianmthayil at gmail.com (Kurian Thayil) Date: Thu, 6 May 2010 14:17:40 +0530 Subject: Python - MySQL fetching values Message-ID: Hi All, I am pretty new to python, and I have an issue with fetching values in python using MySQLdb module. The query executed is *SELECT TIME(DATE_ADD(info_last_calltime, INTERVAL %s MINUTE)) FROM rem_call_info WHERE info_ctrlid=%s""", (retryinterval,controlid1,)* where retryinterval=30 and controlid=2, the expected output is *05:35:05*. Now, here is code snippet, cursor1=getconnect1.cursor() getrows=cursor1.execute("""SELECT TIME(DATE_ADD(info_last_calltime, INTERVAL %s MINUTE)) FROM rem_call_info WHERE info_ctrlid=%s""", (retryinterval,controlid1,)) rawstatus20result=cursor1.fetchone() print "Raw result is",rawstatus20result status20result=rawstatus20result[0] print "The query result for Status 20:",status20result,";Time now is",timeformat The output is: Raw result is (datetime.timedelta(0, 20105),) The query result for Status 20: 5:35:05 ;Time now is 05:22:00 Match not found. New call to be made Getting next value if any... If you look closer, the time fetched by python module was 5:35:05 instead of 05:35:05. How can I get this time format? Thanks in advance. Regards, Kurian Thayil. -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Thu May 6 04:48:55 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 6 May 2010 18:48:55 +1000 Subject: column selection In-Reply-To: <20100506082253.25882.qmail@f4mail-235-130.rediffmail.com> References: <20100506082253.25882.qmail@f4mail-235-130.rediffmail.com> Message-ID: You need to ignore empty lines. for line in open('1.txt'): if len(line.strip()) == 0: continue columns = line.split() print columns[0], columns[2] Cheers, Xav On Thu, May 6, 2010 at 6:22 PM, mannu jha wrote: > Hi, > > I have few files like this: > > 24 ALA helix (helix_alpha, helix2) > > > 27 ALA helix (helix_alpha, helix2) > > > 51 ALA helix (helix_alpha, helix4) > > > 58 ALA helix (helix_alpha, helix5) > > > 63 ALA helix (helix_alpha, helix5) > > now with this program: > > for line in open('1.txt'): > columns = line.split() > print columns[0], columns[2] > > I am trying to print only 1st and third column but it showing error like: > mruser at caf:~> python split.py > 24 helix > Traceback (most recent call last): > File "split.py", line 3, in > print columns[0], columns[2] > IndexError: list index out of range > nmruser at caf:~> > how to rectify it. > > Thanks, > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu May 6 05:10:16 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 06 May 2010 05:10:16 -0400 Subject: Where is python31.dll? In-Reply-To: <78087231-bdd2-4ebc-91b0-ade65af18f9d@k19g2000yqm.googlegroups.com> References: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> <78087231-bdd2-4ebc-91b0-ade65af18f9d@k19g2000yqm.googlegroups.com> Message-ID: <4BE28778.7030809@ieee.org> Pietro Campesato wrote: >> Your windows search command? >> Which is how I verified the above. >> > > I looked at the folder visually. Simply using os.listdir shows there > is in fact a python31.dll there: somehow it was an invisible file. > This is strange since I've never touched any system folder. Thanks and > forgive me if I have asked the group a silly question. > > "visually"? Lots of possibilities there. And if you're not sure, you need to get familiar with Windows quirks. IF you're using Explorer, there are a few ways you could miss a single file out of thousands. Simplest is that the listing is not necessarily completely sorted. You need to do a View->ArrangeIconsBy->Name to really trust that they're sorted today. And you may have to repeat that menu again next time you launch Explorer, or even next time you look at some other directory. Next is that Explorer is initialized by Microsoft to mostly use the worst possible defaults. One is to hide system and hidden files . Another is to hide extensions of known types. Either of these could make you overlook the file. HTH DaveA From mail at timgolden.me.uk Thu May 6 05:11:22 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 06 May 2010 10:11:22 +0100 Subject: Windows7 run python script / sub process with elevated privileges In-Reply-To: <4bdc3e60$0$12096$426a74cc@news.free.fr> References: <4bdc3e60$0$12096$426a74cc@news.free.fr> Message-ID: <4BE287BA.8070708@timgolden.me.uk> On 01/05/2010 15:44, News123 wrote: > Hi, > > I have a small python script, which has been started as normal non > privileged user. > > At a later point in time it would like to start another python script > with elevated privileges. > > How can I write my code such, that I will get the privilege elevation > prompt and I can start a sub process / python function with elevated > privileges. The canonical way is to use the "runas" verb from within ShellExecuteEx, which is exposed by the win32api module. TJG From clp2 at rebertia.com Thu May 6 05:12:50 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 02:12:50 -0700 Subject: Python - MySQL fetching values In-Reply-To: References: Message-ID: On Thu, May 6, 2010 at 1:47 AM, Kurian Thayil wrote: > the expected output is 05:35:05. > > Now, here is code snippet, > > ??????????????? cursor1=getconnect1.cursor() > ??????????????? getrows=cursor1.execute("""SELECT > TIME(DATE_ADD(info_last_calltime, INTERVAL %s MINUTE)) FROM rem_call_info > WHERE info_ctrlid=%s""", (retryinterval,controlid1,)) > ??????????????? rawstatus20result=cursor1.fetchone() > ??????????????? print "Raw result is",rawstatus20result > ??????????????? status20result=rawstatus20result[0] > ??????????????? print "The query result for Status > 20:",status20result,";Time now is",timeformat > > The output is: > > Raw result is (datetime.timedelta(0, 20105),) > The query result for Status 20: 5:35:05 ;Time now is 05:22:00 > Match not found. > New call to be made > Getting next value if any... > > If you look closer, the time fetched by python module was 5:35:05 instead of > 05:35:05. How can I get this time format? Thanks in advance. You're getting back a time delta (i.e. quantity/duration of time, e.g. "3 hours") rather than an actual time (i.e. temporal coordinates for a particular instant of time, e.g. "5:15PM and 2 seconds"), and timedelta defines its stringification differently, hence your issue. I would guess that getting back a timedelta instead of a time is some quirk of MySQLdb; haven't used it though, so I'm just guessing. Anyway, you can work around this by converting the timedelta object to a time object yourself: #Untested Code! from datetime import time minutes, seconds = divmod(status20result.seconds, 60) hours, minutes = divmod(minutes, 60) time_result = time(hours, minutes, seconds, status20result.microseconds) print "The query result for Status 20:",time_result,";Time now is",timeformat Cheers, Chris -- http://blog.rebertia.com From davea at ieee.org Thu May 6 05:21:50 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 06 May 2010 05:21:50 -0400 Subject: ctypes:Multiple library access problem In-Reply-To: <87a9ce5a-aa16-44f2-bcd7-7b790fe75466@b7g2000yqk.googlegroups.com> References: <87a9ce5a-aa16-44f2-bcd7-7b790fe75466@b7g2000yqk.googlegroups.com> Message-ID: <4BE28A2E.1080509@ieee.org> Massi wrote: > Hi everyone, > > in my script I need to execute multiple separated loading of the same > dll library, in order to handle the internal variables with different > threads. > Consider the followin piece of code: > > lib1 = cdll.LoadLibrary("MyLib.dll")) > lib2 = cdll.LoadLibrary("MyLib.dll")) > > lib1.var1 = 0 > lib2.var1 = 1 > > Now, if I print the value of lib1.var1 I get 1, that is lib1 and lib2 > point to the same memory space. Is there a way to create "different > instances" of the same library? Or, alternatively, does it exist any > workaround to avoid lib1 and lib2 share the same memory space? > > Thanks in advance. > > Windows will not load the same DLL twice into the same process in two different places. When it detects that it's the same one, it simply returns the same handle as the earlier one, without any loading or initializing. With some DLL's, you might get away with copying it to a different filename, and then loading each as an independent item. But unless you wrote it yourself, or it has been documented for that behavior, you're taking a big risk. On the other hand, if the DLL was written with threading in mind, then it'll get notified for each new thread you create, and it can manage TLS (thread local storage) rather than using extern vars. I have no idea how to get at those from Python, however. DaveA From richard.lamboj at bilcom.at Thu May 6 05:24:49 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Thu, 6 May 2010 11:24:49 +0200 Subject: Classes: nested functions vs. private methodes Message-ID: <201005061124.50324.richard.lamboj@bilcom.at> Hello, what should i take: - nested functions: class MyClass(object) def blah(self): def blub(var1, var2): do something... blub(1, 5) or class MyClass(object) def blah(self): def _blub(var1, var2): do something... _blub(1, 5) - "private" functions: class MyClass(object) def blah(self): self._blub() def _blub(self): do something... What is more pythonic? It is just for splitting up long code in classes. Kind Regards, Richi From davea at ieee.org Thu May 6 05:26:07 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 06 May 2010 05:26:07 -0400 Subject: column selection In-Reply-To: <20100506082253.25882.qmail@f4mail-235-130.rediffmail.com> References: <20100506082253.25882.qmail@f4mail-235-130.rediffmail.com> Message-ID: <4BE28B2F.2050604@ieee.org> mannu jha wrote: > Hi, > > I have few files like this: > > 24 ALA helix (helix_alpha, helix2) > > > 27 ALA helix (helix_alpha, helix2) > > > 51 ALA helix (helix_alpha, helix4) > > > 58 ALA helix (helix_alpha, helix5) > > > 63 ALA helix (helix_alpha, helix5) > > now with this program: > > for line in open('1.txt'): > columns = line.split() > print columns[0], columns[2] > > I am trying to print only 1st and third column but it showing error like: > mruser at caf:~> python split.py > 24 helix > Traceback (most recent call last): > File "split.py", line 3, in > print columns[0], columns[2] > IndexError: list index out of range > nmruser at caf:~> > how to rectify it. > > Thanks, > > If your files have two blank lines between each useful line, you have to do something to avoid trying to print those items for the blank lines. Depending how sure you are about your formatting, you could either do a if not line: continue or a if columns < 3: continue DaveA From duncan.booth at invalid.invalid Thu May 6 05:26:50 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 May 2010 09:26:50 GMT Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: Peter Otten <__peter__ at web.de> wrote: > Victor Eijkhout wrote: > >> I have two long ints, both too long to convert to float, but their ratio >> is something reasonable. How can I compute that? The obvious "(1.*x)/y" >> does not work. > >>>> import fractions >>>> x = 12345 * 10**1000 >>>> y = 765 * 10**1000 >>>> float(x) > Traceback (most recent call last): > File "", line 1, in > OverflowError: long int too large to convert to float >>>> fractions.Fraction(x, y) > Fraction(823, 51) >>>> float(_) > 16.137254901960784 > Another way of doing this is simply to scale the values down until they do fit in a float: >>> x = 12345 * 10**1000 >>> y = 765 * 10**1000 >>> maxfloat = 1e308 # or whatever it actually is... >>> d = max(max(abs(x),abs(y))//long(maxfloat), 1) >>> float(x//d)/float(y//d) 16.137254901960784 I think that should work for any cases where the ratio fits in a float (if it doesn't then you might get a ZeroDivisionError or inf or -inf). -- Duncan Booth http://kupuguy.blogspot.com From hihighsky at gmail.com Thu May 6 05:49:29 2010 From: hihighsky at gmail.com (Tingting HAN) Date: Thu, 6 May 2010 11:49:29 +0200 Subject: running .py files on Linux Message-ID: Dear Officer, I want to run two .py files to generate .h5 files. hantingting at tityro:~$ python2.5 Python 2.5.4 (r254:67916, Jan 20 2010, 21:43:02) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. When ruuning gentest_sphere.py, the problem is as following: hantingting at tityro:~/Downloads/triMC3D/python$ python2.5 gentest_sphere.py gsphere.h5 Usage: gentest_sphere.pynEl Testfile.h5 options: n: number of elements hantingting at tityro:~/Downloads/triMC3D/python$ I guess I should write the command in the format of usage, but I don't know how to do it. When ruuning test_detector.py, the problem is as following: hantingting at tityro:~/Downloads/triMC3D/python$ python2.5 test_detector.py tdetector.h5 h5/Opaque_material/ext_Trabecular_Bone-int_Cartilage/Nonenm/SourceNone/ lamb = None Traceback (most recent call last): File "test_detector.py", line 600, in main() File "test_detector.py", line 567, in main hdf5.subs_lamb( materials, lamb ) File "/home/hantingting/Downloads/triMC3D/python/local_modules/hdf5.py", line 703, in subs_lamb m.mu_s = m.mu_s(l) File "/home/hantingting/Downloads/triMC3D/python/local_modules/matslib.py", line 71, in [1550.0,1460.0,1360.0,1300.0,1240.0,1220.0,1220.0,1200.0,1160.0], s=300 )) File "/usr/lib/python2.5/site-packages/scipy/interpolate/fitpack.py", line 485, in splev y,ier=_fitpack._spl_(x,der,t,c,k) TypeError: array cannot be safely cast to required type hantingting at tityro:~/Downloads/triMC3D/python$ python2.5 test_detector.py usage: test_detector.py outputfile.h5 [options] options: -c Cage Material -e External Material -i Internal Material -l Lambda -o Output String -s Source Number -h Shows this help hantingting at tityro:~/Downloads/triMC3D/python$ Could you please give me some advice to solve these two problems? I sincerely apologize that I am new for python. -- Best regards, HAN Tingting -------------- next part -------------- An HTML attachment was scrubbed... URL: From SSchukat at dspace.de Thu May 6 05:56:59 2010 From: SSchukat at dspace.de (Stefan Schukat) Date: Thu, 6 May 2010 11:56:59 +0200 Subject: ctypes:Multiple library access problem In-Reply-To: <4BE28A2E.1080509@ieee.org> References: <87a9ce5a-aa16-44f2-bcd7-7b790fe75466@b7g2000yqk.googlegroups.com> <4BE28A2E.1080509@ieee.org> Message-ID: <9015A9FD792E914DADD11DDEB075333843B925F15C@exchange2007.dspace.de> Massi wrote: > > Hi everyone, > > > > in my script I need to execute multiple separated loading of the same > > dll library, in order to handle the internal variables with different > > threads. > > Consider the followin piece of code: > > > > lib1 = cdll.LoadLibrary("MyLib.dll")) > > lib2 = cdll.LoadLibrary("MyLib.dll")) > > > > lib1.var1 = 0 > > lib2.var1 = 1 > > > > Now, if I print the value of lib1.var1 I get 1, that is lib1 and lib2 > > point to the same memory space. Is there a way to create "different > > instances" of the same library? Or, alternatively, does it exist any > > workaround to avoid lib1 and lib2 share the same memory space? > > > > Thanks in advance. > > > > > Windows will not load the same DLL twice into the same process in two > different places. When it detects that it's the same one, it simply > returns the same handle as the earlier one, without any loading or > initializing. > > With some DLL's, you might get away with copying it to a different > filename, and then loading each as an independent item. But unless you > wrote it yourself, or it has been documented for that behavior, you're > taking a big risk. > > On the other hand, if the DLL was written with threading in mind, then > it'll get notified for each new thread you create, and it can manage TLS > (thread local storage) rather than using extern vars. I have no idea > how to get at those from Python, however. > > DaveA > > -- > http://mail.python.org/mailman/listinfo/python-list > The statement from Dave is as far true as the library is loaded without a path. Hence windows searches the system path and always finds the same file. If you load a DLL with an absolute path window will place the dll multiple times into the process. e.g. lib1 = cdll.LoadLibrary(r"c:\temp\MyLib.dll") lib2 = cdll.LoadLibrary(r"d:\temp\MyLib.dll") This has the same effect as renaming the library on the disk. Stefan From steven at REMOVE.THIS.cybersource.com.au Thu May 6 06:02:47 2010 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 06 May 2010 10:02:47 GMT Subject: Classes: nested functions vs. private methodes References: Message-ID: On Thu, 06 May 2010 11:24:49 +0200, Richard Lamboj wrote: > Hello, > > what should i take: > - nested functions: > class MyClass(object) > def blah(self): > def blub(var1, var2): > do something... > blub(1, 5) The disadvantage of nested functions is that it is harder to test them in isolation. > or > > class MyClass(object) > def blah(self): > def _blub(var1, var2): > do something... > _blub(1, 5) There is no real point in marking a nested function as "private" with a leading underscore, as no other object can get access to it. > - "private" functions: > class MyClass(object) > def blah(self): > self._blub() > def _blub(self): > do something... This has the advantage of allowing you to test blah() and _blub() in isolation. It has the disadvantage of polluting the namespace of MyClass with an extra visible method, _blub. > What is more pythonic? Both are Pythonic. Private methods are more object oriented, nested functions are more procedural, but it is mostly a matter of taste which you use. You can use either, or a combination of both, or even do this: class _MyClass(object): """Private class blah blah blah...""" def blah(self, arg): do something... class MyClass(_MyClass): """Public interface to _MyClass""" def blah(self, arg): arg = preprocessing(arg) x = super(MyClass, self).blah(arg) x = postprocessing(x) return x -- Steven From jonvspython at gmail.com Thu May 6 06:38:18 2010 From: jonvspython at gmail.com (jon vs. python) Date: Thu, 6 May 2010 12:38:18 +0200 Subject: pysms In-Reply-To: References: Message-ID: Hi Luca, I've never used pysms, but I just downloaded the source code and it seems that SMS related functionallity is performed using standard GSM AT commands. So if you're accessing the gsm module through a serial port you shouldn't worry at all. Hope it helps, Jon. On Thu, May 6, 2010 at 9:40 AM, luca72 wrote: > Hello > Has anyone used pysms can you tell me with wich gsm module it works? > > Thanks > > Luca > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From richard.lamboj at bilcom.at Thu May 6 06:40:16 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Thu, 6 May 2010 12:40:16 +0200 Subject: Classes: nested functions vs. private methodes In-Reply-To: References: Message-ID: <201005061240.16391.richard.lamboj@bilcom.at> Am Thursday 06 May 2010 12:02:47 schrieb Steven D'Aprano: > On Thu, 06 May 2010 11:24:49 +0200, Richard Lamboj wrote: > > Hello, > > > > what should i take: > > - nested functions: > > class MyClass(object) > > def blah(self): > > def blub(var1, var2): > > do something... > > blub(1, 5) > > The disadvantage of nested functions is that it is harder to test them in > isolation. > > > or > > > > class MyClass(object) > > def blah(self): > > def _blub(var1, var2): > > do something... > > _blub(1, 5) > > There is no real point in marking a nested function as "private" with a > leading underscore, as no other object can get access to it. > > > - "private" functions: > > class MyClass(object) > > def blah(self): > > self._blub() > > def _blub(self): > > do something... > > This has the advantage of allowing you to test blah() and _blub() in > isolation. It has the disadvantage of polluting the namespace of MyClass > with an extra visible method, _blub. > > > What is more pythonic? > > Both are Pythonic. Private methods are more object oriented, nested > functions are more procedural, but it is mostly a matter of taste which > you use. You can use either, or a combination of both, or even do this: > > > class _MyClass(object): > """Private class blah blah blah...""" > def blah(self, arg): > do something... > > class MyClass(_MyClass): > """Public interface to _MyClass""" > def blah(self, arg): > arg = preprocessing(arg) > x = super(MyClass, self).blah(arg) > x = postprocessing(x) > return x > > > > -- > Steven Thank you for the nice sample, but what is with multiple inheritance in your sample? I mean the super call. Why not _MyClass.blah(self, arg). What is when i have more then one Class from which i inherite and in both are a methode called "blah", but i just want to call one of them and not both, becouse they do different things? Kind Regards, Richi From fw at deneb.enyo.de Thu May 6 07:09:04 2010 From: fw at deneb.enyo.de (Florian Weimer) Date: Thu, 06 May 2010 13:09:04 +0200 Subject: Compression module APIs Message-ID: <874oil8ey7.fsf@mid.deneb.enyo.de> As far as I can see, the compression-related APIs (gzip, zlib, bzip2) in Python 2.5 have three distinct APIs. Is there really no unified interface, or am I missing something? From clp2 at rebertia.com Thu May 6 07:37:21 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 04:37:21 -0700 Subject: Compression module APIs In-Reply-To: <874oil8ey7.fsf@mid.deneb.enyo.de> References: <874oil8ey7.fsf@mid.deneb.enyo.de> Message-ID: On Thu, May 6, 2010 at 4:09 AM, Florian Weimer wrote: > As far as I can see, the compression-related APIs (gzip, zlib, bzip2) > in Python 2.5 have three distinct APIs. ?Is there really no unified > interface, or am I missing something? bz2.BZ2File and gzip.GzipFile both offer a file-like interface for reading/writing compressed files in their respective formats. The gzip module is already built on top of the zlib module, so there's no ZlibFile. zlib and bz2 also both offer compatible one-shot compress() and decompress() functions. So, the interfaces are sorta "unified", although it is true they're not grouped into a single generic "compression" module. Cheers, Chris -- http://blog.rebertia.com From fw at deneb.enyo.de Thu May 6 07:41:56 2010 From: fw at deneb.enyo.de (Florian Weimer) Date: Thu, 06 May 2010 13:41:56 +0200 Subject: Compression module APIs In-Reply-To: (Chris Rebert's message of "Thu, 6 May 2010 04:37:21 -0700") References: <874oil8ey7.fsf@mid.deneb.enyo.de> Message-ID: <87tyql6yuz.fsf@mid.deneb.enyo.de> * Chris Rebert: > On Thu, May 6, 2010 at 4:09 AM, Florian Weimer wrote: >> As far as I can see, the compression-related APIs (gzip, zlib, bzip2) >> in Python 2.5 have three distinct APIs. ?Is there really no unified >> interface, or am I missing something? > > bz2.BZ2File and gzip.GzipFile both offer a file-like interface for > reading/writing compressed files in their respective formats. > The gzip module is already built on top of the zlib module, so there's > no ZlibFile. > zlib and bz2 also both offer compatible one-shot compress() and > decompress() functions. > So, the interfaces are sorta "unified", although it is true they're > not grouped into a single generic "compression" module. Some overlap is there. But but there does not appear to be a way to decompress a gzip stream on the fly (which is surprising, as this is a fairly common operation), and there are no counterparts to bz2.BZ2{Dec,C}ompressor. From clp2 at rebertia.com Thu May 6 07:52:30 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 04:52:30 -0700 Subject: Compression module APIs In-Reply-To: <87tyql6yuz.fsf@mid.deneb.enyo.de> References: <874oil8ey7.fsf@mid.deneb.enyo.de> <87tyql6yuz.fsf@mid.deneb.enyo.de> Message-ID: On Thu, May 6, 2010 at 4:41 AM, Florian Weimer wrote: > * Chris Rebert: >> On Thu, May 6, 2010 at 4:09 AM, Florian Weimer wrote: >>> As far as I can see, the compression-related APIs (gzip, zlib, bzip2) >>> in Python 2.5 have three distinct APIs. ?Is there really no unified >>> interface, or am I missing something? >> >> bz2.BZ2File and gzip.GzipFile both offer a file-like interface for >> reading/writing compressed files in their respective formats. >> The gzip module is already built on top of the zlib module, so there's >> no ZlibFile. >> zlib and bz2 also both offer compatible one-shot compress() and >> decompress() functions. >> So, the interfaces are sorta "unified", although it is true they're >> not grouped into a single generic "compression" module. > > Some overlap is there. ?But but there does not appear to be a way to > decompress a gzip stream on the fly (which is surprising, as this is a > fairly common operation), and there are no counterparts to > bz2.BZ2{Dec,C}ompressor. Well, there are zlib equivalents: http://docs.python.org/library/zlib.html#zlib.decompressobj http://docs.python.org/library/zlib.html#zlib.compressobj As for gzip, you might be able to pass a StringIO object as the `fileobj` argument to zip.GzipFile's constructor; that'd give you basically the same thing as a Gzip{Dec,C}ompressor. I haven't tried it, but there's a decent chance it might work. Cheers, Chris -- http://blog.rebertia.com From rjvbertin at gmail.com Thu May 6 08:16:14 2010 From: rjvbertin at gmail.com (=?ISO-8859-1?Q?Ren=E9_J=2EV=2E_Bertin?=) Date: Thu, 6 May 2010 14:16:14 +0200 Subject: crash in Py_EnterRecursiveCall In-Reply-To: References: Message-ID: Hello, I have embedded Python into and extended it with functionality from a graphical tool I use. One of the things it allows me to do is to export Python objects to a simple scripting language ("ascanf"), and call them as if they were native functions. I have the following situation in which I get a systematic segmentation violation in Py_EnterRecursiveCall(), in Python 2.4 2.5 and 2.6 (OS X) and on Cygwin with 2.5 and 2.6 . I enter an interactive Python 'console' from within my application, either the one from the interact package, or the IPython shell. My application has a callback defined for the readline routines that calls the graphical event handler, allowing for instance refresh/redraws to continue while working in the Python console. The crash occurs when during such events handled through the readline callback, I call an exported Python object. This does not appear to be related to recursion per se, but rather to "calling a python interpreter behind the back of the currently active console/interpreter". To be clearer, suppose I have some Python code def Py_travDistCalc(a,b,c): ... return x ascanf.ExportVariable("travDistCalc", Py_travDistCalc ) I can then issue a call 1) travDistCalc[a,b,c] from an ascanf script. 2) ascanf.Eval( 'travDistCalc[a,b,c]' ) from the Python console Call 1) provokes a crash in Py_EnterRecursiveCall() when invoked through the readline callback when the Python console is open, but call 2) succeeds normally. Note that this is a single-threaded application. My workaround is to keep track of the readline callback recursion level, and compare the current level with the level recorded when entering a Python console before doing the PyObject_CallObject() required in call 1) and 2) above. In Python 2.3, the Py_xxxRecursiveCall functions are missing, but I also get a crash, so I guess I'm doing something really nasty. I'm not sure if this is a bug in Python. It is the sort of crash situation I'd try to avoid, though. From mannu_0523 at rediffmail.com Thu May 6 08:24:34 2010 From: mannu_0523 at rediffmail.com (mannu jha) Date: 6 May 2010 12:24:34 -0000 Subject: =?utf-8?B?UmU6IFJlOiBjb2x1bW4gc2VsZWN0aW9u?= In-Reply-To: <4BE28B2F.2050604@ieee.org> Message-ID: <1273140847.S.2303.13864.f4mail-235-207.rediffmail.com.1273148674.35579@webmail.rediffmail.com> I tried with this: for line in open('1.txt'): columns = line.split() print columns[0], columns[1] if not line: continue but it is showing error: nmruser at caf:~> python split.py 24 ALA Traceback (most recent call last): File "split.py", line 3, in print columns[0], columns[1] IndexError: list index out of range nmruser at caf:~> Thanks, On Thu, 06 May 2010 15:44:07 +0530 wrote >mannu jha wrote: > Hi, > > I have few files like this: > > 24 ALA helix (helix_alpha, helix2) > > > 27 ALA helix (helix_alpha, helix2) > > > 51 ALA helix (helix_alpha, helix4) > > > 58 ALA helix (helix_alpha, helix5) > > > 63 ALA helix (helix_alpha, helix5) > > now with this program: > > for line in open('1.txt'): > columns = line.split() > print columns[0], columns[2] > > I am trying to print only 1st and third column but it showing error like: > mruser at caf:~> python split.py > 24 helix > Traceback (most recent call last): > File "split.py", line 3, in > print columns[0], columns[2] > IndexError: list index out of range > nmruser at caf:~> > how to rectify it. > > Thanks, > > If your files have two blank lines between each useful line, you have to do something to avoid trying to print those items for the blank lines. Depending how sure you are about your formatting, you could either do a if not line: continue or a if columns < 3: continue DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at shopzeus.com Thu May 6 08:58:55 2010 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 06 May 2010 14:58:55 +0200 Subject: running .py files on Linux In-Reply-To: References: Message-ID: <4BE2BD0F.7090103@shopzeus.com> Tingting HAN ?rta: > Dear Officer, > I want to run two .py files to generate .h5 files. > hantingting at tityro:~$ python2.5 > Python 2.5.4 (r254:67916, Jan 20 2010, 21:43:02) > [GCC 4.4.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > When ruuning gentest_sphere.py, the problem is as following: > hantingting at tityro:~/Downloads/triMC3D/python$ > python2.5 > gentest_sphere.py gsphere.h5 > Usage: gentest_sphere.pynEl Testfile.h5 > options: > n: number of elements > hantingting at tityro:~/Downloads/triMC3D/python$ > > I guess I should write the command in the format of usage, but I don't > know how to do it. > > When ruuning test_detector.py, the problem is as following: > hantingting at tityro:~/Downloads/triMC3D/python$ > python2.5 > test_detector.py tdetector.h5 > h5/Opaque_material/ext_Trabecular_Bone-int_Cartilage/Nonenm/SourceNone/ > lamb = None > Traceback (most recent call last): > File "test_detector.py", line 600, in > main() > File "test_detector.py", line 567, in main > hdf5.subs_lamb( materials, lamb ) > File > "/home/hantingting/Downloads/triMC3D/python/local_modules/hdf5.py", > line 703, in subs_lamb > m.mu_s = m.mu_s(l) > File > "/home/hantingting/Downloads/triMC3D/python/local_modules/matslib.py", > line 71, in > [1550.0,1460.0,1360.0,1300.0,1240.0,1220.0,1220.0,1200.0,1160.0], > s=300 )) > File > "/usr/lib/python2.5/site-packages/scipy/interpolate/fitpack.py", line > 485, in splev > y,ier=_fitpack._spl_(x,der,t,c,k) > TypeError: array cannot be safely cast to required type > hantingting at tityro:~/Downloads/triMC3D/python$ > python2.5 > test_detector.py > usage: test_detector.py outputfile.h5 [options] > options: > -c Cage Material > -e External Material > -i Internal Material > -l Lambda > -o Output String > -s Source Number > -h Shows this help > hantingting at tityro:~/Downloads/triMC3D/python$ > > Could you please give me some advice to solve these two problems? I > sincerely apologize that I am new for python. Did you try this: 1.) replace the first line of gentest_sphere.py to "#!/usr/bin/python2.5" (or your path to python2.5) 2.) "chmod +x gentest_sphere.py" 3.) run this: "./gentest_sphere.py gsphere.h5" (instead of "python2.5 ./gentest_sphere.py gsphere.h5" It may not help. But... suspicious. You used the advertised command line. The program may have a bug. E.g. it uses sys.argv the incorrect way. Best, Laszlo From mount.sarah at gmail.com Thu May 6 08:59:04 2010 From: mount.sarah at gmail.com (Sarah Mount) Date: Thu, 6 May 2010 13:59:04 +0100 Subject: Python debuggers with sys.settrace() In-Reply-To: <1f8f2c8e-3ee1-4fc1-95e8-aae3e54ba1b4@n37g2000prc.googlegroups.com> References: <1f8f2c8e-3ee1-4fc1-95e8-aae3e54ba1b4@n37g2000prc.googlegroups.com> Message-ID: On 5 May 2010 10:17, Carl Banks wrote: > On May 2, 11:06?am, Sarah Mount wrote: >> This is a bit of an odd question, but is there any way for a Python >> debugger to suppress I/O generated by the program which is being >> debugged? I guess an "obvious" thing to do would be to replace core >> parts of the standard library and change any relevant imports in the >> locals and globals dicts to fake ones which don't generate I/O, but >> this seems brittle as the standard library will change over time. Is >> it possible to modify the byte-compiled code in each stack frame? Or >> is there a simpler way to do this? > > It's not foolproof but you could try to reassign sys.stdout and > sys.stderr to a bit bucket ("sys.stdout = open(os.devull)"), then > invoke the debugger with stdout set to sys._stdout (the actual > stdout). ?You'll have to create the Pdb() by hand since the built-in > convience functions don't do it. ?Check the file pdb.py for details. > Thanks Carl. I had considered this, but it won't catch things like socket communication. Hmmm..... Cheers, Sarah -- Sarah Mount, Senior Lecturer, University of Wolverhampton website: http://www.snim2.org/ twitter: @snim2 From clp2 at rebertia.com Thu May 6 09:09:16 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 06:09:16 -0700 Subject: Python debuggers with sys.settrace() In-Reply-To: References: <1f8f2c8e-3ee1-4fc1-95e8-aae3e54ba1b4@n37g2000prc.googlegroups.com> Message-ID: On Thu, May 6, 2010 at 5:59 AM, Sarah Mount wrote: > On 5 May 2010 10:17, Carl Banks wrote: >> On May 2, 11:06?am, Sarah Mount wrote: >>> This is a bit of an odd question, but is there any way for a Python >>> debugger to suppress I/O generated by the program which is being >>> debugged? I guess an "obvious" thing to do would be to replace core >>> parts of the standard library and change any relevant imports in the >>> locals and globals dicts to fake ones which don't generate I/O, but >>> this seems brittle as the standard library will change over time. Is >>> it possible to modify the byte-compiled code in each stack frame? Or >>> is there a simpler way to do this? >> >> It's not foolproof but you could try to reassign sys.stdout and >> sys.stderr to a bit bucket ("sys.stdout = open(os.devull)"), then >> invoke the debugger with stdout set to sys._stdout (the actual >> stdout). ?You'll have to create the Pdb() by hand since the built-in >> convience functions don't do it. ?Check the file pdb.py for details. >> > > Thanks Carl. I had considered this, but it won't catch things like > socket communication. Hmmm..... You could monkeypatch the socket constructors in the `socket` module to return dummies. Cheers, Chris -- http://blog.rebertia.com From davea at ieee.org Thu May 6 09:12:18 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 06 May 2010 09:12:18 -0400 Subject: column selection In-Reply-To: <1273140847.S.2303.13864.f4mail-235-207.rediffmail.com.1273148674.35579@webmail.rediffmail.com> References: <1273140847.S.2303.13864.f4mail-235-207.rediffmail.com.1273148674.35579@webmail.rediffmail.com> Message-ID: <4BE2C032.9080605@ieee.org> mannu jha wrote: > I tried with this: > > for line in open('1.txt'): > columns = line.split() > print columns[0], columns[1] > if not line: continue > > but it is showing error: > > nmruser at caf:~> python split.py > 24 ALA > Traceback (most recent call last): > File "split.py", line 3, in > print columns[0], columns[1] > IndexError: list index out of range > nmruser at caf:~> > > Thanks, > > On Thu, 06 May 2010 15:44:07 +0530 wrote > > > > If your files have two blank lines between each useful line, you have to > > do something to avoid trying to print those items for the blank lines. > > Depending how sure you are about your formatting, you could either do a > > if not line: continue > > or a > > if columns < 3: continue > > > DaveA > > > (Don't top-post. It makes the message very confusing to someone else trying to follow it. Also, enable your mail program's quoting feature -- currently it's not adding the marks at the beginning of each line you quote.) If you're going to skip over blank lines, it'd be good to do it before trying to print from it. Move the test up by a line. DaveA From cai.haibin at gmail.com Thu May 6 10:52:49 2010 From: cai.haibin at gmail.com (james_027) Date: Thu, 6 May 2010 07:52:49 -0700 (PDT) Subject: fast regex Message-ID: hi, I was working with regex on a very large text, really large but I have time constrained. Does python has any other regex library or string manipulation library that works really fast? Thanks, James From javier.collado at gmail.com Thu May 6 11:31:46 2010 From: javier.collado at gmail.com (Javier Collado) Date: Thu, 6 May 2010 17:31:46 +0200 Subject: fast regex In-Reply-To: References: Message-ID: Hello, 2010/5/6 james_027 : > I was working with regex on a very large text, really large but I have > time constrained. Does python has any other regex library or string > manipulation library that works really fast? re2 (http://code.google.com/p/re2/) is suppossed to be faster than the standard library in python. Unfortunately, it's implemented in C++ and there isn't an official python wrapper for it. However, you can find a wrapper that can be useful for you here: http://github.com/facebook/pyre2 Best regards, Javier From john at castleamber.com Thu May 6 11:33:47 2010 From: john at castleamber.com (John Bokma) Date: Thu, 06 May 2010 10:33:47 -0500 Subject: fast regex References: Message-ID: <87eihp2gf8.fsf@castleamber.com> james_027 writes: > I was working with regex on a very large text, really large but I have > time constrained. Does python has any other regex library or string > manipulation library that works really fast? Hard to answer without seeing your regex and requirements first. Your question is like: I had a meal yesterday and it upset my stomach. Can you suggest a different meal for today? -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From vriolk at gmail.com Thu May 6 11:53:49 2010 From: vriolk at gmail.com (coldpizza) Date: Thu, 6 May 2010 08:53:49 -0700 (PDT) Subject: convert Unicode filenames to good-looking ASCII Message-ID: Hello, I need to convert accented unicode chars in some audio files to similarly-looking ascii chars. Looks like the following code seems to work on windows: import os import sys import glob EXT = '*.*' lst_uni = glob.glob(unicode(EXT)) os.system('chcp 437') lst_asci = glob.glob(EXT) print sys.stdout.encoding for i in range(len(lst_asci)): try: os.rename(lst_uni[i], lst_asci[i]) except Exception as e: print e On windows it converts most of the accented chars from the latin1 encoding. This does not work in Linux since it uses 'chcp'. The questions are (1) *why* does it work on windows, and (2) what is the proper and portable way to convert unicode characters to similarly looking plain ascii chars? That is how to properly do this kind of conversion? ? > u ? > e ? > a ? > a ? > a ? > a ? > c ? > e ? > e ? > e Is there any other way apart from creating my own char replacement table? From p.f.moore at gmail.com Thu May 6 11:59:21 2010 From: p.f.moore at gmail.com (Paul Moore) Date: Thu, 6 May 2010 08:59:21 -0700 (PDT) Subject: Windows - select.select, timeout and KeyboardInterrupt Message-ID: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> >From a quick experiment, it seems that select.select with a timeout doesn't react to a keyboard interrupt until the timeout expires. Specifically, if I do s = socket.socket() select.select([s], [], [], 30) and then press Ctrl-C, Python waits for the 30 seconds before raising KeyboardInterrupt. Is this a known limitation on Windows? I see no mention of it in the documentation. Assuming it is a known limitation, is there a way round it? (I'm writing a tiny server using asyncore/asynchat, and the delayed response to Ctrl-C is a mild nuisance. Solutions such as "use twisted", while probably the sensible option in a wider context, don't really apply here - I need something within the confines of the stdlib if it's to be worth doing). Thanks, Paul From u53730 at gmail.com Thu May 6 12:22:41 2010 From: u53730 at gmail.com (Iliya) Date: Thu, 6 May 2010 20:22:41 +0400 Subject: convert Unicode filenames to good-looking ASCII In-Reply-To: References: Message-ID: Try smth like this: import unicodedata def remove_accents(str): nkfd_form = unicodedata.normalize('NFKD', unicode(str)) return u''.join([c for c in nkfd_form if not unicodedata.combining(c)]) From mal at egenix.com Thu May 6 12:26:51 2010 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 06 May 2010 18:26:51 +0200 Subject: matching strings in a large set of strings In-Reply-To: References: Message-ID: <4BE2EDCB.9090807@egenix.com> Dennis Lee Bieber wrote: > On Thu, 29 Apr 2010 11:38:28 +0200, "Karin Lagesen" > declaimed the following in comp.lang.python: > >> Hello. >> >> I have approx 83 million strings, all 14 characters long. I need to be >> able to take another string and find out whether this one is present >> within the 83 million strings. >> > Is this "another string" also exactly 14 characters long? > >> Now, I have tried storing these strings as a list, a set and a dictionary. >> I know that finding things in a set and a dictionary is very much faster >> than working with a list, so I tried those first. However, I run out of >> memory building both the set and the dictionary, so what I seem to be left >> with is the list, and using the in method. >> > So don't load them into memory... First use a file-based (not memory > limited) sort routine on the 80M strings (if position in the file is > important, make a copy with the line number on the end of each line > before sorting -- but since you've tried using Sets which do not retain > order... probably not a matter). > > Then, since you know the length of the file, and the length of each > line is fixed, you can do direct access I/O (well, since the C-stream > style I/O doesn't do "record" access, you'll need to calculate offsets > from the start of the file as (record# - 1) * recordlen)... > > That lets you do a binary search on the file. Much faster than a > linear search (linear search will average out to 41.5M read operations; > binary should be around 10000 reads) > > Or load the data into some relational database and let the compiled > code do the searching -- probably faster than byte-code interpreted > Python for the same algorithm... ... or put the data into a simple on-disc dictionary such as what mxBeeBase implements: http://www.egenix.com/products/python/mxBase/mxBeeBase/ Once you have that dict set up, lookups are very fast. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 06 2010) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From trentm at activestate.com Thu May 6 12:33:05 2010 From: trentm at activestate.com (Trent Mick) Date: Thu, 06 May 2010 09:33:05 -0700 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <1273105847.779.1373624397@webmail.messagingengine.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> <1273086295.15686.1373577021@webmail.messagingengine.com> <4BE1F91D.8050201@activestate.com> <1273105847.779.1373624397@webmail.messagingengine.com> Message-ID: <4BE2EF41.1090308@activestate.com> On 10-05-05 5:30 PM, python at bdurham.com wrote: > Hi Trent, > > On 10-05-05 12:04 PM, python at bdurham.com wrote: >>> I just took a look at the ActiveStatre 2.6.5.12 release (zip file >>> version) and noticed that this file does not include the MSVCR90.DLL run >>> time file - it includes MFC*.DLL files instead (and a different manifest >>> file as well). >>> >>> Can anyone explain why the ActiveState release uses different MS Visual >>> C runtime files than the official Python Foundation's release of Python? > >> It doesn't. We use the same MSVC version as the python.org builds. >> >> Note that "MFC*.dll" files (IIRC, it has been a while) are >> redistributable DLLs used by the included PyWin32 extensions that have >> Python bindings for the Microsoft Foundation Classes GUI APIs. > > Yes, you are correct about the MFC*.dll's being shipped as part of the > Py2Win32 extensions. > > But I don't see the MSVCR90.DLL in your ZIP release. I do see a > MSVCR71.DLL. That is probably a bug in the ZIP package (the MSI is by far the primary package for Windows so gets more attention). I've started a bug for this: http://bugs.activestate.com/show_bug.cgi?id=86794 Thanks, Trent -- Trent Mick trentm at activestate.com http://trentm.com/blog/ From __peter__ at web.de Thu May 6 12:34:42 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 May 2010 18:34:42 +0200 Subject: convert Unicode filenames to good-looking ASCII References: Message-ID: coldpizza wrote: > Hello, > > I need to convert accented unicode chars in some audio files to > similarly-looking ascii chars. Looks like the following code seems to > work on windows: > > import os > import sys > import glob > > EXT = '*.*' > > lst_uni = glob.glob(unicode(EXT)) > > os.system('chcp 437') > lst_asci = glob.glob(EXT) > print sys.stdout.encoding > > for i in range(len(lst_asci)): > try: > os.rename(lst_uni[i], lst_asci[i]) > except Exception as e: > print e > > On windows it converts most of the accented chars from the latin1 > encoding. This does not work in Linux since it uses 'chcp'. > > The questions are (1) *why* does it work on windows, and (2) what is > the proper and portable way to convert unicode characters to similarly > looking plain ascii chars? > > That is how to properly do this kind of conversion? > ? > u > ? > e > ? > a > ? > a > ? > a > ? > a > ? > c > ? > e > ? > e > ? > e > > Is there any other way apart from creating my own char replacement > table? >>> from unicodedata import normalize >>> s = u"""? > u ... ? > e ... ? > a ... ? > a ... ? > a ... ? > a ... ? > c ... ? > e ... ? > e ... ? > e ... """ >>> from unicodedata import normalize >>> print normalize("NFD", s).encode("ascii", "ignore") u > u e > e a > a a > a a > a a > a c > c e > e e > e e > e From python at bdurham.com Thu May 6 12:53:52 2010 From: python at bdurham.com (python at bdurham.com) Date: Thu, 06 May 2010 12:53:52 -0400 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <4BE2EF41.1090308@activestate.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> <1273086295.15686.1373577021@webmail.messagingengine.com> <4BE1F91D.8050201@activestate.com> <1273105847.779.1373624397@webmail.messagingengine.com> <4BE2EF41.1090308@activestate.com> Message-ID: <1273164832.14062.1373752241@webmail.messagingengine.com> Hi Trent, > That is probably a bug in the ZIP package (the MSI is by far the primary package for Windows so gets more attention). > > I've started a bug for this: > http://bugs.activestate.com/show_bug.cgi?id=86794 Thank you, Malcolm ----- Original message ----- From: "Trent Mick" To: python at bdurham.com Cc: python-list at python.org Date: Thu, 06 May 2010 09:33:05 -0700 Subject: Re: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) On 10-05-05 5:30 PM, python at bdurham.com wrote: > Hi Trent, > > On 10-05-05 12:04 PM, python at bdurham.com wrote: >>> I just took a look at the ActiveStatre 2.6.5.12 release (zip file >>> version) and noticed that this file does not include the MSVCR90.DLL run >>> time file - it includes MFC*.DLL files instead (and a different manifest >>> file as well). >>> >>> Can anyone explain why the ActiveState release uses different MS Visual >>> C runtime files than the official Python Foundation's release of Python? > >> It doesn't. We use the same MSVC version as the python.org builds. >> >> Note that "MFC*.dll" files (IIRC, it has been a while) are >> redistributable DLLs used by the included PyWin32 extensions that have >> Python bindings for the Microsoft Foundation Classes GUI APIs. > > Yes, you are correct about the MFC*.dll's being shipped as part of the > Py2Win32 extensions. > > But I don't see the MSVCR90.DLL in your ZIP release. I do see a > MSVCR71.DLL. That is probably a bug in the ZIP package (the MSI is by far the primary package for Windows so gets more attention). I've started a bug for this: http://bugs.activestate.com/show_bug.cgi?id=86794 Thanks, Trent -- Trent Mick trentm at activestate.com http://trentm.com/blog/ From vriolk at gmail.com Thu May 6 12:55:16 2010 From: vriolk at gmail.com (coldpizza) Date: Thu, 6 May 2010 09:55:16 -0700 (PDT) Subject: convert Unicode filenames to good-looking ASCII References: Message-ID: Cool! Thanks to both Iliya and Peter! On May 6, 7:34?pm, Peter Otten <__pete... at web.de> wrote: > coldpizza wrote: > > Hello, > > > I need to convert accented unicode chars in some audio files to > > similarly-looking ascii chars. Looks like the following code seems to > > work on windows: > > > import os > > import sys > > import glob > > > EXT = '*.*' > > > lst_uni = glob.glob(unicode(EXT)) > > > os.system('chcp 437') > > lst_asci = glob.glob(EXT) > > print sys.stdout.encoding > > > for i in range(len(lst_asci)): > > ? ? try: > > ? ? ? ? os.rename(lst_uni[i], lst_asci[i]) > > ? ? except Exception as e: > > ? ? ? ? print e > > > On windows it converts most of the accented chars from the latin1 > > encoding. This does not work in Linux since it uses 'chcp'. > > > The questions are (1) *why* does it work on windows, and (2) what is > > the proper and portable way to convert unicode characters to similarly > > looking plain ascii chars? > > > That is how to properly do this kind of conversion? > > ?? ?> u > > ?? ?> e > > ?? ?> a > > ?? ?> a > > ?? ?> a > > ?? ?> a > > ?? ?> c > > ?? ?> e > > ?? ?> e > > ?? ?> e > > > Is there any other way apart from creating my own char replacement > > table? > >>> from unicodedata import normalize > >>> s = u"""? ?> u > > ... ?? ?> e > ... ?? ?> a > ... ?? ?> a > ... ?? ?> a > ... ?? ?> a > ... ?? ?> c > ... ?? ?> e > ... ?? ?> e > ... ?? ?> e > ... """>>> from unicodedata import normalize > >>> print normalize("NFD", s).encode("ascii", "ignore") > > u ?> u > ?e ?> e > ?a ?> a > ?a ?> a > ?a ?> a > ?a ?> a > ?c ?> c > ?e ?> e > ?e ?> e > ?e ?> e From stef.mientki at gmail.com Thu May 6 13:46:21 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 06 May 2010 19:46:21 +0200 Subject: how to make a piece of code lowercase, except strings / comment ? Message-ID: <4BE3006D.5070505@gmail.com> hello, I use Python with some simplifications and a few extensions, as a scripting language for non-programmers. One of the simplifications is that the language should be case-insensitive. This is done by making the code lowercase. But now the strings in the code are also converted to lowercase. Is there an easy way to make a piece of code lowercase, except all string items (single / double /triple quoted and comment) ? thanks, Stef Mientki -------------- next part -------------- An HTML attachment was scrubbed... URL: From rouslank at msn.com Thu May 6 14:35:25 2010 From: rouslank at msn.com (Rouslan Korneychuk) Date: Thu, 06 May 2010 14:35:25 -0400 Subject: new extension generator for C++ In-Reply-To: <4BE05D75.7030301@msn.com> References: <4BE05D75.7030301@msn.com> Message-ID: I have the code up at http://github.com/Rouslan/PyExpose now. Any comments are welcome. From claird271 at gmail.com Thu May 6 14:38:43 2010 From: claird271 at gmail.com (Cameron Laird) Date: Thu, 6 May 2010 11:38:43 -0700 (PDT) Subject: Python-URL! - weekly Python news and links (May 5) Message-ID: <11e042dd-e031-4f42-93d0-e81ec1616003@d39g2000yqa.googlegroups.com> [Authored by Gabriel Genellina.] QOTW: "Even on alt.haruspicy they cannot do much without a liver now and then..." - Peter Otten http://groups.google.com/group/comp.lang.python/msg/7852938d0b92bd7b Mixing bytes and unicode when writing data in Python 3.x: http://groups.google.com.ar/group/comp.lang.python/t/72614b3e49b2efe/ The best way to join two lists: a.extend(b) or a+=b? http://groups.google.com.ar/group/comp.lang.python/t/e56703a77aff9c67/ How to check who is still holding a reference to some object: http://groups.google.com.ar/group/comp.lang.python/t/ca9ca80d1f9b13da/ Using metaclasses to define class-level, inheritable computed attributes (properties): http://groups.google.com.ar/group/comp.lang.python/t/78394a73748c176f/ How to compute a/b (a float value) when both numbers are really big integers outside the float range? http://groups.google.com.ar/group/comp.lang.python/t/bdfe5287890e5776/ When creating millions of objects, disabling the garbage collector may enormously improve performance: http://groups.google.com.ar/group/comp.lang.python/t/4294c4c585e75a6d/ The right way to define __str__, __repr__ and __unicode__ in Python 2: http://groups.google.com.ar/group/comp.lang.python/t/e208e63e399ec52a/ rfind()'s 'start' argument is quite unintuitive: http://groups.google.com.ar/group/comp.lang.python/t/d03fbdcacfbf5794/ Generating nested code using a context manager: http://groups.google.com.ar/group/comp.lang.python/t/1200df3bd70afaa6/ How can open() succeed but os.path.realpath() fail with the same file name? (and later: how the Unix filesystems work) http://groups.google.com.ar/group/comp.lang.python/t/771f233167ac6d8e/ [Windows] It may be wise to download Visual Studio Express 2008 now, to still be able to recompile C extensions in the future: http://groups.google.com.ar/group/comp.lang.python/t/65e34924e7d42c90/ The available options for Web application development (and a comparison with PHP): http://groups.google.com.ar/group/comp.lang.python/t/7caab317a1d56d6e/ The dot in a.b is not an operator, and it's quite different from a +=b (started as a new syntax proposal, the .= operator): http://groups.google.com.ar/group/comp.lang.python/t/c6f9171c7659a999/ A proposal for engineering notation (like scientific format but exponent is always multiple of 3): http://groups.google.com.ar/group/comp.lang.python/t/421f611d0235b9f6/ How strong are statements like 'dict.keys() and dict.values() correspond to each other'? http://groups.google.com.ar/group/comp.lang.python/t/29915caa46255e21/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" site: http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date nullege is an interesting search Web application, with the intelligence to distinguish between Python code and comments. It provides what appear to be relevant results, and demands neither Java nor CSS be enabled: http://www.nullege.com Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python Enjoy the *Python Magazine*. http://pymag.phparch.com/ *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From artur.siekielski at gmail.com Thu May 6 15:34:53 2010 From: artur.siekielski at gmail.com (Artur Siekielski) Date: Thu, 6 May 2010 12:34:53 -0700 (PDT) Subject: List comprehension + lambdas - strange behaviour Message-ID: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Hello. I found this strange behaviour of lambdas, closures and list comprehensions: >>> funs = [lambda: x for x in range(5)] >>> [f() for f in funs] [4, 4, 4, 4, 4] Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The 'x' was bound to the final value of 'range(5)' expression for ALL defined functions. Can you explain this? Is this only counterintuitive example or an error in CPython? Regards, Artur From aahz at pythoncraft.com Thu May 6 15:37:12 2010 From: aahz at pythoncraft.com (Aahz) Date: 6 May 2010 12:37:12 -0700 Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> <2010050415342385304-tomfsessile@gmailcom> <4be132f1$0$20639$426a74cc@news.free.fr> Message-ID: In article <4be132f1$0$20639$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: > >The more bad code (mine or not) I have to maintain (or even just read >and understand), the more I pay attention to my own design and code >quality. Sometimes you only understand why something is bad, why it is >bad and how bad it is when you have to deal with it :( ...and sometimes it takes several months of living with bad code to really understand how to rewrite it. I'm currently rewriting a chunk of bad code that merges three datasources. If I had done the rewriting five months ago (when I first started feeling that I understood the codebase well enough to do the job), I would not be doing the complete rewrite that I'm currently doing, which would have led to suboptimal code lasting longer. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From theller at ctypes.org Thu May 6 15:58:15 2010 From: theller at ctypes.org (Thomas Heller) Date: Thu, 06 May 2010 21:58:15 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: Paul Moore schrieb: >>From a quick experiment, it seems that select.select with a timeout > doesn't react to a keyboard interrupt until the timeout expires. > Specifically, if I do > > s = socket.socket() > select.select([s], [], [], 30) > > and then press Ctrl-C, Python waits for the 30 seconds before raising > KeyboardInterrupt. > > Is this a known limitation on Windows? I see no mention of it in the > documentation. Assuming it is a known limitation, is there a way round > it? (I'm writing a tiny server using asyncore/asynchat, and the > delayed response to Ctrl-C is a mild nuisance. Solutions such as "use > twisted", while probably the sensible option in a wider context, don't > really apply here - I need something within the confines of the stdlib > if it's to be worth doing). If you look at the source code for time.sleep(), which CAN be interrupted by pressing Ctrl-C, you will find that it is carefully programmed to be interruptible (sp?). Which is not the case for select.select(), obviously. I guess the best way might be to split your select.select() call into several ones, using a smaller timeout like 1 second for example. BTW: I have experimented with calling the win32 function SetConsoleCtrlHandler() before the call to select.select(). This allows to install a python callback function which is called when Ctrl+C is pressed. However it seems this callback is not able to interrupt the select() call - but it can 'raise SystemExit()' which will terminate the script. Here is the code: """ import ctypes, select, socket @ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint) def HandlerRoutine(dwCtrlType): print "hoppla", dwCtrlType if dwCtrlType == 0: # CTRL+C raise SystemExit() return 1 s = socket.socket() print "Waiting." ctypes.windll.kernel32.SetConsoleCtrlHandler(HandlerRoutine, 1) select.select([s], [], [], 30) ctypes.windll.kernel32.SetConsoleCtrlHandler(HandlerRoutine, 0) print "Done." """ From aahz at pythoncraft.com Thu May 6 16:22:30 2010 From: aahz at pythoncraft.com (Aahz) Date: 6 May 2010 13:22:30 -0700 Subject: Picking a license (was Re: new extension generator for C++) References: <4BE05D75.7030301@msn.com> Message-ID: In article <4BE05D75.7030301 at msn.com>, Rouslan Korneychuk wrote: > >The only question I have now is what about licensing? Is that something >I need to worry about? Should I go with LGPL, MIT, or something else? Which license you use depends partly on your political philosophy. Unless you have an aggressively Stallmanesque attitude that people using your code should be forced to contribute back any changes, stick with MIT. (Generally speaking, the less encumbrance in your code, the more likely people are to use it, if your goal is to encourage users.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From python at rcn.com Thu May 6 16:25:23 2010 From: python at rcn.com (Raymond Hettinger) Date: Thu, 6 May 2010 13:25:23 -0700 (PDT) Subject: List comprehension + lambdas - strange behaviour References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Message-ID: On May 6, 9:34?pm, Artur Siekielski wrote: > Hello. > I found this strange behaviour of lambdas, closures and list > comprehensions: > > >>> funs = [lambda: x for x in range(5)] > >>> [f() for f in funs] > > [4, 4, 4, 4, 4] > > Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The > 'x' was bound to the final value of 'range(5)' expression for ALL > defined functions. Can you explain this? Is this only counterintuitive > example or an error in CPython? Try binding the value of x for each of the inner functions: >>> funs = [lambda x=x: x for x in range(5)] >>> [f() for f in funs] [0, 1, 2, 3, 4] Otherwise, the 'x' is just a global value and the lambdas look it up at when the function is invoked. Really, not surprising at all: >>> x = 10 >>> def f(): ... return x ... >>> x = 20 >>> f() 20 Raymond From emile at fenx.com Thu May 6 16:26:44 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 06 May 2010 13:26:44 -0700 Subject: List comprehension + lambdas - strange behaviour In-Reply-To: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Message-ID: On 5/6/2010 12:34 PM Artur Siekielski said... > Hello. > I found this strange behaviour of lambdas, closures and list > comprehensions: > >>>> funs = [lambda: x for x in range(5)] funs is now a list of lambda functions that return 'x' (whatever it currently is from whereever it's accessible when invoked) >>> [f() for f,x in zip(funs,range(5))] [0, 1, 2, 3, 4] >>> del x >>> [f() for f in funs] Traceback (most recent call last): File "", line 1, in ? File "", line 1, in NameError: global name 'x' is not defined >>> Emile From fabiofz at gmail.com Thu May 6 16:27:10 2010 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 6 May 2010 17:27:10 -0300 Subject: 2to3 issues with execfile on python 3.0 on files with encoding Message-ID: Right now, it seems that the default implementation of execfile in 2to3 is something as: exec(compile(open(file).read()+"\n", file, 'exec'), globals, locals) But it seems it won't deal with encodings properly... and also, in CPython just making an open without a close is OK, because of the reference counting, but in Jython it shouldn't be relied on (so, an explicit close should be done). The default replacement should be really providing a new execfile that gets the encoding in the first 2 lines and opens it with the proper encoding set (and properly closes the stream). So, below is what I think would be a correct replacement... Can it be made easier? Is there any utility to get the encoding already? Maybe an execfile should be created again in Python 3? (even if not in the __builtin__, but at least somewhere, as that seems really tricky to get right) Note that some 'with' statements could be used, but I chose not to because I wanted it to be at least syntax-compatible with earlier versions of python. def execfile(file): stream = open(file) try: encoding = None #Get encoding! for i in range(2): line = stream.readline() #Should not raise an exception even if there are no more contents #Must be a comment line if line.strip().startswith('#'): #Don't import re if there's no chance that there's an encoding in the line if 'coding' in line: import re p = re.search(r"coding[:=]\s*([-\w.]+)", line) if p: encoding = p.group(1) break finally: stream.close() if encoding is not None: stream = open(file, encoding=encoding) else: stream = open(file) try: contents = stream.read() finally: stream.close() exec(compile(contents+"\n", file, 'exec'), globals, locals) #execute the script Cheers, Fabio From benjamin at python.org Thu May 6 16:29:34 2010 From: benjamin at python.org (Benjamin Peterson) Date: Thu, 6 May 2010 20:29:34 +0000 (UTC) Subject: List comprehension + lambdas - strange behaviour References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Message-ID: Artur Siekielski gmail.com> writes: > > Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The > 'x' was bound to the final value of 'range(5)' expression for ALL > defined functions. Can you explain this? Is this only counterintuitive > example or an error in CPython? The former. Closures are rebound in a loop. From vincent at vincentdavis.net Thu May 6 17:21:00 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Thu, 6 May 2010 15:21:00 -0600 Subject: 2to3 as a unittest Message-ID: I have used 2to3 from the command line. is there a way to run it as a unittest. Actually I guess my question is; is there a built in utility for running py3 compatibility on source code as a unittest? *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From pietro.campe at gmail.com Thu May 6 18:26:15 2010 From: pietro.campe at gmail.com (Pietro Campesato) Date: Thu, 6 May 2010 15:26:15 -0700 (PDT) Subject: Where is python31.dll? References: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> <78087231-bdd2-4ebc-91b0-ade65af18f9d@k19g2000yqm.googlegroups.com> Message-ID: <9c1adb05-3954-4711-ab1e-a10530c575b5@11g2000prw.googlegroups.com> Dave Angel wrote: > "visually"? Lots of possibilities there. And if you're not sure, you > need to get familiar with Windows quirks. > > IF you're using Explorer, there are a few ways you could miss a single > file out of thousands. > > Simplest is that the listing is not necessarily completely sorted. You > need to do a View->ArrangeIconsBy->Name > to really trust that they're sorted today. And you may have to repeat > that menu again next time you launch Explorer, or even next time you > look at some other directory. > > Next is that Explorer is initialized by Microsoft to mostly use the > worst possible defaults. One is to hide system and hidden files > . Another is to hide extensions of known types. Either of these could > make you overlook the file. > > HTH > DaveA You are right, I guess I should rely on programmatic ways to find specific files. Thank you. From rouslank at msn.com Thu May 6 18:53:50 2010 From: rouslank at msn.com (Rouslan Korneychuk) Date: Thu, 06 May 2010 18:53:50 -0400 Subject: Picking a license (was Re: new extension generator for C++) In-Reply-To: References: <4BE05D75.7030301@msn.com> Message-ID: <4BE3487E.9000500@msn.com> On 05/06/2010 04:22 PM, Aahz wrote: > In article<4BE05D75.7030301 at msn.com>, > Rouslan Korneychuk wrote: >> >> The only question I have now is what about licensing? Is that something >> I need to worry about? Should I go with LGPL, MIT, or something else? > > Which license you use depends partly on your political philosophy. > Unless you have an aggressively Stallmanesque attitude that people using > your code should be forced to contribute back any changes, stick with > MIT. (Generally speaking, the less encumbrance in your code, the more > likely people are to use it, if your goal is to encourage users.) MIT it is, then. From fabio at aptana.com Thu May 6 19:12:53 2010 From: fabio at aptana.com (Fabio Zadrozny) Date: Thu, 6 May 2010 20:12:53 -0300 Subject: Pydev 1.5.7 Released Message-ID: Hi All, Pydev 1.5.7 has been released Details on Pydev: http://pydev.org Details on its development: http://pydev.blogspot.com Release Highlights: ------------------------------- * **Uniquely identifying editors:** * Names are never duplicated * Special treatment for __init__ * Special treatment for django on views, models and tests * See: http://pydev.blogspot.com/2010/04/identifying-your-editors.html for details * **Debugger:** * **CRITICAL**: Fixed issue which could make the debugger skip breakpoints * Properly dealing with varibles that have '<' or '>' * Debugging file in python 3 with an encoding works * Double-clicking breakpoint opens file from the workspace instead of always forcing an external file * Added '* any file' option for file selection during a debug where the file is not found * **Performance improvements for dealing with really large files:** * Code folding marks won't be shown on *really large files* for performance reasons * Performance improvements in the code-analysis (much faster for *really large files*) * Outline tree is also faster * **Interpreter configuration:** * Only restoring the needed interpreter info (so, it's much faster to add a new interpreter) * Using an asynchronous progress monitor (which makes it even faster) * Interpreter location may not be duplicated (for cases where the same interpreter is used with a different config, virtualenv should be used) * Properly refreshing internal caches (which made a ctrl+2+kill or a restart of eclipse needed sometimes after configuring the interpreter) * socket added to forced builtins * **Python 3 grammar:** * Code completion and code-analysis work when dealing with keyword only parameters * Properly reporting syntax error instead of throwing a NumberFormatException on "1.0L" * **Editor and forcing tabs:** * Option to toggle forcing tabs added to the editor context menu * Fixed tabs issue which could change the global setting on force tabs * **Indentation:** * Added rule so that indentation stops at the level of the next line def or @ (to indent to add a decorator) * Auto indent strategy may indent based on next line if the previous is empty * **General:** * Django configuration supporting version 1.2 (contribution by Kenneth Belitzky) * Fixed encoding problem when pasting encoded text with indentation * asthelper.completions no longer created on current directory when project is removed * __all__ semantics correct when a tuple is defined (and not only when a list is defined) * Fixed issue in extract method (was not creating tuple on caller function with multiple returns) * Improved heuristic for assist assign (ctrl+1) * On search open files (ctrl+2+s), dialog is opened if nothing is entered and there's no editor selection * Fixed issue where ctrl+2 would not work on linux What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python, Jython and IronPython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer Aptana http://aptana.com/ Pydev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com From martin at v.loewis.de Thu May 6 19:38:13 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Fri, 07 May 2010 01:38:13 +0200 Subject: py3 tkinter acceps bytes. why? In-Reply-To: References: Message-ID: <4BE352E5.4060004@v.loewis.de> > If I don't want bytes to get passed to tkinter > I just have to raise an exception in AsObj, no? > Or is it even sufficient to just remove the bytes case? But why would you want that? There are commands which legitimately return bytes, e.g. the file and network io libraries of Tcl (not that you would usually want to use them in Python, but Tkinter is actually Tclinter, and should support all Tcl commands). Regards, Martin From pmaupin at gmail.com Thu May 6 19:38:22 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 6 May 2010 16:38:22 -0700 (PDT) Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> <2010050415342385304-tomfsessile@gmailcom> Message-ID: <746e8b47-bb35-47a1-9832-2babe0fec044@o8g2000yqo.googlegroups.com> On May 4, 5:34?pm, TomF wrote: > On 2010-05-04 07:11:08 -0700, alex23 said: > > (I also think there's value to be gained in studying _bad_ code, > > too...) > > True, although whether that's time well spent is another question. I don't know how this applies to reading other peoples' code, but recent research shows we learn more from success than failure: http://web.mit.edu/newsoffice/2009/successes-0729.html Regards, Pat From ben+python at benfinney.id.au Thu May 6 19:56:29 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 07 May 2010 09:56:29 +1000 Subject: Picking a license References: <4BE05D75.7030301@msn.com> Message-ID: <87k4rgfutu.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > In article <4BE05D75.7030301 at msn.com>, > Rouslan Korneychuk wrote: > > > >The only question I have now is what about licensing? Is that > >something I need to worry about? Should I go with LGPL, MIT, or > >something else? > > Which license you use depends partly on your political philosophy. Yes. Unless you place such a low value the freedom of your users that you'd allow proprietary derivatives of your work to remove the freedoms you've taken care to grant, then you should choose a copyleft license like the GPL. > Unless you have an aggressively Stallmanesque attitude that people > using your code should be forced to contribute back any changes Er, no. Anyone who thinks that a copyleft license ?forces? anyone to do anything is mistaken about copyright law, or the GPL, or both. The GPL only grants permissions, like any other free software license. -- \ ?If sharing a thing in no way diminishes it, it is not rightly | `\ owned if it is not shared.? ?Augustine of Hippo (354?430 CE) | _o__) | Ben Finney From martin at v.loewis.de Thu May 6 19:57:53 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Fri, 07 May 2010 01:57:53 +0200 Subject: 2to3 issues with execfile on python 3.0 on files with encoding In-Reply-To: References: Message-ID: > The default replacement should be really providing a new execfile that > gets the encoding in the first 2 lines and opens it with the proper > encoding set (and properly closes the stream). No. The default replacement should really open the file in binary mode. Regards, Martin From marduk at letterboxes.org Thu May 6 20:18:49 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Fri, 07 May 2010 09:18:49 +0900 Subject: Django as exemplary design In-Reply-To: <746e8b47-bb35-47a1-9832-2babe0fec044@o8g2000yqo.googlegroups.com> References: <2010050312243328275-tomfsessile@gmailcom> <2010050415342385304-tomfsessile@gmailcom> <746e8b47-bb35-47a1-9832-2babe0fec044@o8g2000yqo.googlegroups.com> Message-ID: <1273191529.196773.7.camel@paska> On Thu, 2010-05-06 at 16:38 -0700, Patrick Maupin wrote: > I don't know how this applies to reading other peoples' code, but > recent research shows we learn more from success than failure That's good to learn, because for years I have been intentionally failing in order to learn from it and become successful, and it hasn't really worked out for me :| -a From mehgcap at gmail.com Thu May 6 20:33:47 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 6 May 2010 20:33:47 -0400 Subject: does this exception mean something else? Message-ID: Hi all, I have a file, pasted below for what good it will do, which makes a couple conditional calls to a function called writeDefaults. However, when I manually trigger a condition that causes the function to be called, Python gives me a name error and says that my writeDefaults does not exist. I am sure that it does, as I copied the text from the call and pasted it into the text search of my editor, and it found the line that defines the function, so the text in the call is obviously correct. Sometimes, especially in a language like Javascript, one error can mean something else or point to a problem other than the one it claims to be about, so I wondered if the same thing could be happening here? The error is on line 55, just after the if statement that uses os.path.exists to ensure my ini file is really there. TIA! BTW, speech is just a file that will output a given message through an active screen reader; changing all calls to print will work just as well. import os, sys import helpers from configobj import ConfigObj #for reading ini files from string import Template #for interpreting the template strings in the ini file from speech import speak #set up a default dict of options to be used general={ "useSpeech":"True", "printMessages":"False", "roundTo":1, "defaultStartMode":1 } enableModes={ "resourceMonitor":"True", "weather":"True", "network":"True" } weatherOptions={ "location":"04938" } armOptions={ "primaryDrive":"c:", "secondaryDrive":"j:", "currentIsPrimary":"True", "CIsSecondary":"True", "ramInfo":"used", "driveInfo":"Used" } templates={ "sayCorePercentage":"$percent% for core $core", "sayProcessorAverage":"$percent% average load", "sayRamFree":"$percent% ram free ($free of $total remaining)", "sayRamUsed":"$percent% ram used ($used of $total used)", "sayDriveFree":"$percent% free on $drive ($free of $total remaining)", "sayDriveUsed":"$percent% used on $drive ($used of $total used)", "currentWeather":"$condition, $temp degrees. $wind. $humidity.", "forecast":"$day: $condition, $low to $high." } #first, load the ini file setting #so where is the ini? script_path/config.ini, of course! iniLoc=helpers.progdir+'\\config.ini' iniLoc=r'c:\arm\config.ni' #set up the ini object to read and write settings if(os.path.exists(iniLoc)): ini=ConfigObj(iniLoc) else: speak("The i n i file was not found. Now generating a default file.") writeDefaults() #end except #now get the settings general=ini["general"] printMessages=general["printMessages"] speech=general["useSpeech"] rnd=int(general["roundTo"]) mode=int(general["defaultStartMode"]) enable=ini['enableModes'] rmOn=enable["resourceMonitor"] weatherOn=enable["weather"] networkOn=enable["network"] aop=ini["armOptions"] #the options section drive1=aop["primaryDrive"] drive2=aop["secondaryDrive"] ramInfo=aop["ramInfo"] driveInfo=aop["driveInfo"] useCurrentDrive=aop["currentIsPrimary"] CIsSecondary=aop["CIsSecondary"] wop=ini["weatherOptions"] zip=str(wop["location"]) subs=ini["templates"] #short for substitute corePercent=Template(subs["sayCorePercentage"]) avg=Template(subs["sayProcessorAverage"]) sayRamFree=Template(subs["sayRamFree"]) sayRamUsed=Template(subs["sayRamUsed"]) sayDriveFree=Template(subs["sayDriveFree"]) sayDriveUsed=Template(subs["sayDriveUsed"]) currentWeather=Template(subs["currentWeather"]) forecast=Template(subs["forecast"]) def setOptions(): global ini try: ini.reload() except: speak("The i n i file was not found. Now generating a default file.") writeDefaults() #end except #now just a few settings that depend on the options #if useCurrentDrive is true, get that drive and set drive1 to it if(useCurrentDrive=="True"): #get current drive and assign it to primary currentDrive=os.path.splitdrive(sys.argv[0])[0] drive1=currentDrive #furthermore, if CIsSecondary is true, set that here, #since useCurrentDrive must be true for this one to take effect if(CIsSecondary=="True"): drive2="c:" #endif #endif #end def def writeDefaults(): global ini global iniLoc ini.filename=iniLoc ini["general"]=general ini["enableModes"]=enableModes ini["weatherOptions"]=weatherOptions ini["armOptions"]=armOptions ini["templates"]=templates #create the new file ini.write() #end def def speakSetOptions(): #just calls setOptions, but I use this separate def so I can speak a "reloaded" msg setOptions() speak("Settings reloaded.") #end def -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From python at mrabarnett.plus.com Thu May 6 20:37:26 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 May 2010 01:37:26 +0100 Subject: Django as exemplary design In-Reply-To: <1273191529.196773.7.camel@paska> References: <2010050312243328275-tomfsessile@gmailcom> <2010050415342385304-tomfsessile@gmailcom> <746e8b47-bb35-47a1-9832-2babe0fec044@o8g2000yqo.googlegroups.com> <1273191529.196773.7.camel@paska> Message-ID: <4BE360C6.3040503@mrabarnett.plus.com> Albert Hopkins wrote: > On Thu, 2010-05-06 at 16:38 -0700, Patrick Maupin wrote: >> I don't know how this applies to reading other peoples' code, but >> recent research shows we learn more from success than failure > > That's good to learn, because for years I have been intentionally > failing in order to learn from it and become successful, and it hasn't > really worked out for me :| > Failure just teaches you what you shouldn't do, not what you should... From clp2 at rebertia.com Thu May 6 20:50:22 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 17:50:22 -0700 Subject: does this exception mean something else? In-Reply-To: References: Message-ID: On Thu, May 6, 2010 at 5:33 PM, Alex Hall wrote: > Hi all, > I have a file, pasted below for what good it will do, which makes a > couple conditional calls to a function called writeDefaults. However, > when I manually trigger a condition that causes the function to be > called, Python gives me a name error and says that my writeDefaults > does not exist. I am sure that it does, as I copied the text from the > call and pasted it into the text search of my editor, and it found the > line that defines the function, so the text in the call is obviously > correct. You're calling the function before you've defined it; that doesn't work in Python. `def`s are executable statements, not declarations like in statically-typed languages. Move the "def writeDefaults():" and its body so it comes before the "#first, load the ini file setting" code. Cheers, Chris -- http://blog.rebertia.com From darwin at nowhere.com Thu May 6 21:03:55 2010 From: darwin at nowhere.com (Paul Hemans) Date: Fri, 7 May 2010 11:03:55 +1000 Subject: Extract a bordered, skewed rectangle from an image Message-ID: We have a scanned document on which a label has been attached. The label has been designed to have a border that makes it easy to determine the correct orientation and area of the label. The label portion of the scanned image needs to be extracted and deskewed as an image. The contents of the label will change, but the border won't I originally posted this onto RentAcoder as a project, but I am not getting a lot of responses. It might be that I requested it be done in Python, its too hard or I am too stingy. You can see the project here: http://www.RentACoder.com/RentACoder/misc/BidRequests/ShowBidRequest.asp?lngBidRequestId=1402446 It may not be feasible to do this project without the use of an image processing engine such as openCV. There is a routine in openCV called cvMinAreaRect2() that may do the job of returning a matching rectangle that is inclined. There is a Python to openCV interface available. So I think all the pieces are there, but this is out of my league as I have had very little experience with image processing. I am wondering whether there are any people here that have experience with openCV and Python. If so, could you either give me some pointers on how to approach this, or if you feel so inclined, bid on the project. There are 2 problems: How do I get openCV to ignore the contents of the label and just focus on the border? How to do this through Python into openCV? I am a newbie to Python, not strong in Maths and ignorant of the usage of openCV. Thanks. From python at mrabarnett.plus.com Thu May 6 21:03:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 May 2010 02:03:59 +0100 Subject: does this exception mean something else? In-Reply-To: References: Message-ID: <4BE366FF.3050509@mrabarnett.plus.com> Alex Hall wrote: > Hi all, > I have a file, pasted below for what good it will do, which makes a > couple conditional calls to a function called writeDefaults. However, > when I manually trigger a condition that causes the function to be > called, Python gives me a name error and says that my writeDefaults > does not exist. I am sure that it does, as I copied the text from the > call and pasted it into the text search of my editor, and it found the > line that defines the function, so the text in the call is obviously > correct. Sometimes, especially in a language like Javascript, one > error can mean something else or point to a problem other than the one > it claims to be about, so I wondered if the same thing could be > happening here? The error is on line 55, just after the if statement > that uses os.path.exists to ensure my ini file is really there. TIA! > BTW, speech is just a file that will output a given message through an > active screen reader; changing all calls to print will work just as > well. > You need to remember that 'def' and 'class' are _statements_, not declarations; they have the side-effect of adding a name to the current namespace. A Python script is run from the first line. If/when Python reaches line 55 the 'def' statement that defines the function 'writeDefaults' hasn't been run yet. BTW, you should avoid 'bare excepts' (an except clause that doesn't say which exception to catch) because they catch _every_ exception, even KeyboardInterrupt and NameError. You might also want to look at PEP 8: http://www.python.org/dev/peps/pep-0008/ which is the Style Guide for Python code. From trent at snakebite.org Thu May 6 21:20:02 2010 From: trent at snakebite.org (Trent Nelson) Date: Fri, 7 May 2010 09:20:02 +0800 Subject: Django as exemplary design In-Reply-To: <2010050312243328275-tomfsessile@gmailcom> References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <000001caed83$71a68e80$54f3ab80$@snakebite.org> > I'm interested in improving my python design by studying a large, > well-designed codebase. I'll tell you one of the best ways to improve your Python code: attend one of Raymond Hettinger's Code Clinic workshops at a Python conference and put some up of your work up on the projector for 20+ developers to rip apart, line by line ;-) You'll pick up more in 30 minutes than you ever thought possible. Trent. From contact at xavierho.com Thu May 6 21:33:16 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 7 May 2010 11:33:16 +1000 Subject: [Python-ideas] division oddness In-Reply-To: References: <4BE3623E.5000900@gmx.net> Message-ID: On Fri, May 7, 2010 at 11:13 AM, Chris Rebert wrote: > On Thu, May 6, 2010 at 5:43 PM, Mathias Panzenb?ck > wrote: > > Shouldn't by mathematical definition -x // y be the same as -(x // y)? > > I think this rather odd. Is there any deeper reason to this behaviour? I > > guess changing this will break a lot of code, but why does it behave like > > this? > > I would suppose it's what programmers have found more > useful/intuitive. Most programmers aren't number theorists. > Yeah, I was stinged by that before, too. I really don't find it intuitive at all - to keep the modulos remainer equal, you lose on negations and possibly integer equality. Ah well, too bad I didn't invent Python. =]. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu May 6 21:49:07 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 06 May 2010 21:49:07 -0400 Subject: List comprehension + lambdas - strange behaviour In-Reply-To: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Message-ID: On 5/6/2010 3:34 PM, Artur Siekielski wrote: > Hello. > I found this strange behaviour of lambdas, closures and list > comprehensions: > >>>> funs = [lambda: x for x in range(5)] >>>> [f() for f in funs] > [4, 4, 4, 4, 4] You succumbed to lambda hypnosis, a common malady ;-). The above will not work in 3.x, which does not leak comprehension iteration variables. It is equivalent to funs = [lambda: x for y in range(5)] del y # only for 2.x. y is already gone in 3.x x = 4 [f() for f in funs] Now, I am sure, you would expect what you got. and nearly equivalent to def f(): return x x=8 funs = [f for x in range(5)] [f() for f in funs] # [8,8,8,8,8] in 3.x Ditto Terry Jan Reedy From tjreedy at udel.edu Thu May 6 22:01:07 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 06 May 2010 22:01:07 -0400 Subject: does this exception mean something else? In-Reply-To: References: Message-ID: On 5/6/2010 8:33 PM, Alex Hall wrote: > Hi all, > I have a file, pasted below for what good it will do, which makes a > couple conditional calls to a function called writeDefaults. However, > when I manually trigger a condition that causes the function to be > called, Python gives me a name error and says that my writeDefaults > does not exist. It does not, when you try to call it, because the call occurs before you define it. Python code is executed top to bottom and function defines are executable statements. I suspect that you have used some other language that operates differently. ... > #first, load the ini file setting > #so where is the ini? script_path/config.ini, of course! > iniLoc=helpers.progdir+'\\config.ini' > iniLoc=r'c:\arm\config.ni' > #set up the ini object to read and write settings > if(os.path.exists(iniLoc)): > ini=ConfigObj(iniLoc) > else: > speak("The i n i file was not found. Now generating a default file.") > writeDefaults() > #end except writeDefaults is not yet defined ... > def writeDefaults(): > global ini > global iniLoc > ini.filename=iniLoc > ini["general"]=general > ini["enableModes"]=enableModes > ini["weatherOptions"]=weatherOptions > ini["armOptions"]=armOptions > ini["templates"]=templates > #create the new file > ini.write() > #end def Now it is. Move you def statements up closer to the top of the file. Terry Jan Reedy From mehgcap at gmail.com Thu May 6 22:01:15 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 6 May 2010 22:01:15 -0400 Subject: does this exception mean something else? In-Reply-To: <4BE366FF.3050509@mrabarnett.plus.com> References: <4BE366FF.3050509@mrabarnett.plus.com> Message-ID: Changing the order so the function is first did it. Thanks. That is what I get for working with Java all semester... On 5/6/10, MRAB wrote: > Alex Hall wrote: >> Hi all, >> I have a file, pasted below for what good it will do, which makes a >> couple conditional calls to a function called writeDefaults. However, >> when I manually trigger a condition that causes the function to be >> called, Python gives me a name error and says that my writeDefaults >> does not exist. I am sure that it does, as I copied the text from the >> call and pasted it into the text search of my editor, and it found the >> line that defines the function, so the text in the call is obviously >> correct. Sometimes, especially in a language like Javascript, one >> error can mean something else or point to a problem other than the one >> it claims to be about, so I wondered if the same thing could be >> happening here? The error is on line 55, just after the if statement >> that uses os.path.exists to ensure my ini file is really there. TIA! >> BTW, speech is just a file that will output a given message through an >> active screen reader; changing all calls to print will work just as >> well. >> > You need to remember that 'def' and 'class' are _statements_, not > declarations; they have the side-effect of adding a name to the current > namespace. > > A Python script is run from the first line. If/when Python reaches line > 55 the 'def' statement that defines the function 'writeDefaults' hasn't > been run yet. > > BTW, you should avoid 'bare excepts' (an except clause that doesn't say > which exception to catch) because they catch _every_ exception, even > KeyboardInterrupt and NameError. > > You might also want to look at PEP 8: > > http://www.python.org/dev/peps/pep-0008/ > > which is the Style Guide for Python code. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From cai.haibin at gmail.com Thu May 6 22:11:11 2010 From: cai.haibin at gmail.com (james_027) Date: Thu, 6 May 2010 19:11:11 -0700 (PDT) Subject: fast regex References: <87eihp2gf8.fsf@castleamber.com> Message-ID: On May 6, 11:33?pm, John Bokma wrote: > james_027 writes: > > I was working with regex on a very large text, really large but I have > > time constrained. Does python has any other regex library or string > > manipulation library that works really fast? > > Hard to answer without seeing your regex and requirements first. > Your question is like: I had a meal yesterday and it upset my > stomach. Can you suggest a different meal for today? > > -- > John Bokma ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? j3b > > Hacking & Hiking in Mexico - ?http://johnbokma.com/http://castleamber.com/- Perl & Python Development I am doing something like this for key, value in words_list.items(): compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) search = compile.sub(value, content) where the content is a large text about 500,000 characters and the word list is about 5,000 Any optimization for the code above? From clp2 at rebertia.com Thu May 6 22:14:41 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 19:14:41 -0700 Subject: [Python-ideas] division oddness In-Reply-To: References: <4BE3623E.5000900@gmx.net> Message-ID: On Thu, May 6, 2010 at 6:33 PM, Xavier Ho wrote: > On Fri, May 7, 2010 at 11:13 AM, Chris Rebert wrote: >> On Thu, May 6, 2010 at 5:43 PM, Mathias Panzenb?ck >> wrote: >> > Shouldn't by mathematical definition -x // y be the same as -(x // y)? >> > I think this rather odd. Is there any deeper reason to this behaviour? I >> > guess changing this will break a lot of code, but why does it behave >> > like >> > this? >> >> I would suppose it's what programmers have found more >> useful/intuitive. Most programmers aren't number theorists. > > Yeah, I was stinged by that before, too. I really don't find it intuitive at > all - to keep the modulos remainer equal, you lose on negations and possibly > integer equality. Ah well, too bad I didn't invent Python. =]. Personally, I find the following the most unintuitive: divmod(-11, 3) == (-4, 1) So, we overshoot -11 and then add 1 to go back to the right place? That violates my intuitive thought that abs((n//d)*d) <= abs(n) ought to hold. Cheers, Chris -- This is why we don't rely on intuition alone. http://blog.rebertia.com From cai.haibin at gmail.com Thu May 6 22:44:33 2010 From: cai.haibin at gmail.com (james_027) Date: Thu, 6 May 2010 19:44:33 -0700 (PDT) Subject: fast regex References: <87eihp2gf8.fsf@castleamber.com> Message-ID: <35bb1a8a-6f63-428e-8b96-1dcc41c4cb76@h20g2000prn.googlegroups.com> On May 6, 11:33?pm, John Bokma wrote: > james_027 writes: > > I was working with regex on a very large text, really large but I have > > time constrained. Does python has any other regex library or string > > manipulation library that works really fast? > > Hard to answer without seeing your regex and requirements first. > Your question is like: I had a meal yesterday and it upset my > stomach. Can you suggest a different meal for today? > > -- > John Bokma ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? j3b > > Hacking & Hiking in Mexico - ?http://johnbokma.com/http://castleamber.com/- Perl & Python Development I am doing something like this for key, value in words_list.items(): compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) search = compile.sub(value, content) where the content is a large text about 500,000 characters and the word list is about 5,000 Any optimization for the code above? From python.list at tim.thechases.com Thu May 6 22:47:18 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 06 May 2010 21:47:18 -0500 Subject: fast regex In-Reply-To: References: <87eihp2gf8.fsf@castleamber.com> Message-ID: <4BE37F36.3090701@tim.thechases.com> On 05/06/2010 09:11 PM, james_027 wrote: > for key, value in words_list.items(): > compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) > search = compile.sub(value, content) > > where the content is a large text about 500,000 characters and the > word list is about 5,000 You don't specify what you want to do with "search" vs. "content"...are you then reassigning content = search so that subsequent replacements happen? (your current version creates "search", only to discard it) My first thought would be to make use of re.sub()'s ability to take a function and do something like # a regexp that finds all possible # matches/words of interest r = re.compile(r'\b[a-zA-Z]+\b') def replacer(match): text = match.group(0) # assuming your dict.keys() are all lowercase: return word_list.get(text.lower(), text) results = r.sub(replacer, content) This does a replacement for every word in the input corpus (possibly with itself), but only takes one pass through the source text. If you wanted to get really fancy (and didn't butt up against the max size for a regexp), I suppose you could do something like r = re.compile(r'\b(%s)\b' % ( '|'.join(re.escape(s) for s in words_list.keys())), re.IGNORECASE) def replacer(match): return word_list[match.group(0).lower()] # assume lower keys results = r.sub(replacer, content) which would only do replacements on your keys rather than every "word" in your input, but I'd start with the first version before abusing programmatic regexp generation. -tkc From tomf.sessile at gmail.com Thu May 6 22:48:12 2010 From: tomf.sessile at gmail.com (TomF) Date: Thu, 6 May 2010 19:48:12 -0700 Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <2010050619481239450-tomfsessile@gmailcom> On 2010-05-06 18:20:02 -0700, Trent Nelson said: >> I'm interested in improving my python design by studying a large, >> well-designed codebase. > > I'll tell you one of the best ways to improve your Python code: attend > one of Raymond Hettinger's Code Clinic workshops at a Python conference > and put some up of your work up on the projector for 20+ developers to > rip apart, line by line ;-) You'll pick up more in 30 minutes than you > ever thought possible. I don't doubt it. But I'm not really interested in line (micro) level code issues at the moment. Not that my code couldn't stand being improved, but I'm more interested in seeing how medium/large OO python systems are designed. If I could get this from a book I would, but I suspect I need to study real code. -Tom From apt.shansen at gmail.com Thu May 6 23:01:46 2010 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 6 May 2010 20:01:46 -0700 Subject: Picking a license In-Reply-To: <87k4rgfutu.fsf@benfinney.id.au> References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: On Thu, May 6, 2010 at 4:56 PM, Ben Finney > wrote: > aahz at pythoncraft.com (Aahz) writes: > > > In article <4BE05D75.7030301 at msn.com>, > > Rouslan Korneychuk wrote: > > > > > >The only question I have now is what about licensing? Is that > > >something I need to worry about? Should I go with LGPL, MIT, or > > >something else? > > > > Which license you use depends partly on your political philosophy. > > Yes. > > Unless you place such a low value the freedom of your users that you'd > allow proprietary derivatives of your work to remove the freedoms you've > taken care to grant, then you should choose a copyleft license like the > GPL. > > Unless you have an aggressively Stallmanesque attitude that people > > using your code should be forced to contribute back any changes > Meh, both of these responses are... tiring and full of political rhetoric instead of just giving the guy the facts and letting him pick what he wants and suits himself. So, to the OP: If you release the code under the GPL, then anyone is free to take and use it and do anything in the world they want with it. However, should they choose to distribute it to anyone else, then any changes they make to it must be provided to this "anyone else" according to the same terms. So, someone who takes your code and say, adds a module to it-- that module can't be in any license but the GPL (or rather, no license more restrictive then the GPL). Notably, this code can't end up in any closed or proprietary product. If you release the code under a "permissive" license, like MIT or the 3-clause BSD, you're basically giving everyone in the world free reign to do -- anything they want with it, without any sort of "but's". They just can't say you endorsed it generally, and can't sue you for it, and they can't claim it was theirs (though they aren't required to admit it was yours, either). Someone can take it, rename it, and re-release it as a closed-source program if they want. Or, someone could incorporate it into any number of projects that are open source and not GPL-- whereas GPL code can't ever be incorporated into non-GPL code, without the whole codebase becoming GPL. Notably, Python has a permissive license, albeit one which is very, very wordy. What you decide on is up to you. Me, I'm very strongly in the MIT camp. I consider what I may release as a sort of donation, and don't expect anything of anyone-- and don't even mind if someone makes money off of it without being a good sport. "Freedom" and software have nothing to do with anything to me. I do open source because I think its an excellent way to get technically excellent products. The decision of which camp you find yourself is up to you. :) (Then there's others, like Artistic, the Apache, and on and on) --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From cai.haibin at gmail.com Thu May 6 23:18:01 2010 From: cai.haibin at gmail.com (james_027) Date: Thu, 6 May 2010 20:18:01 -0700 (PDT) Subject: fast regex References: <87eihp2gf8.fsf@castleamber.com> Message-ID: On May 6, 11:33?pm, John Bokma wrote: > james_027 writes: > > I was working with regex on a very large text, really large but I have > > time constrained. Does python has any other regex library or string > > manipulation library that works really fast? > > Hard to answer without seeing your regex and requirements first. > Your question is like: I had a meal yesterday and it upset my > stomach. Can you suggest a different meal for today? > > -- > John Bokma ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? j3b > > Hacking & Hiking in Mexico - ?http://johnbokma.com/http://castleamber.com/- Perl & Python Development I am doing something like this for key, value in words_list.items(): compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) search = compile.sub(value, content) where the content is a large text about 500,000 characters and the word list is about 5,000 Any optimization for the code above? From ncohen at ucsd.edu Thu May 6 23:50:01 2010 From: ncohen at ucsd.edu (Ben Cohen) Date: Thu, 6 May 2010 21:50:01 -0600 Subject: idiomatic way to collect and report multiple exceptions? Message-ID: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> Is there a pythonic way to collect and display multiple exceptions at the same time? For example let's say you're trying to validate the elements of a list and you'd like to validate as many of the elements as possible in one run and still report exception's raised while validating a failed element. eg -- I'd like to do something like this: errors = [] for item in data: try: process(item) except ValidationError as e: errors.append(e) raise MultipleValidationErrors(*errors) where if the raised MultipleValidationErrors exception goes uncaught the interpreter will print a nice traceback that includes the tracebacks of each raised ValidationError. But I don't know how MultipleValidationErrors should be written ... I'm targeting python 2.6 at the moment -- googling around for advice I see some pep's relating to exception handling changes in python3 that might be relevant but I've ended up more confused. Thanks in advance, Ben From crebert at ucsd.edu Fri May 7 00:56:10 2010 From: crebert at ucsd.edu (Chris Rebert) Date: Thu, 6 May 2010 21:56:10 -0700 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> Message-ID: On Thu, May 6, 2010 at 8:50 PM, Ben Cohen wrote: > Is there a pythonic way to collect and display multiple exceptions at the same time? > > For example let's say you're trying to validate the elements of a list and you'd like to validate as many of the elements as possible in one run and still report exception's raised while validating a failed element. > > eg -- I'd like to do something like this: > > errors = [] > for item in data: > ? ? ? ?try: > ? ? ? ? ? ? ? ?process(item) > ? ? ? ?except ValidationError as e: > ? ? ? ? ? ? ? ?errors.append(e) > raise MultipleValidationErrors(*errors) > > where if the raised MultipleValidationErrors exception goes uncaught the interpreter will print a nice traceback that includes the tracebacks of each raised ValidationError. ?But I don't know how MultipleValidationErrors should be written ... import sys, traceback def _traceback_for(exc_info): return ''.join(traceback.format_exception(*exc_info)) # StandardError can obviously be replaced with # whatever exception superclass you want. class MultipleValidationErrors(StandardError): def __init__(self, errors=None): self.errors = errors or [] def __str__(self): tracebacks = "\n\n".join(_traceback_for(exc_info) for exc_info in \ self.errors) parts=("See the following exception tracebacks:", "="*78, tracebacks) msg = '\n'.join(parts) return msg def capture_current_exception(self): self.errors.append(sys.exc_info()) def do_raise(self): """Raises itself if it contains any errors""" if self.errors: raise self #Example usage: multiple_err = MultipleValidationErrors() for c in "hello": try: int(c) # obviously fails except ValueError: # whatever error type you care about multiple_err.capture_current_exception() multiple_err.do_raise() Output from example: Traceback (most recent call last): File "tmp.py", line 35, in multiple_err.do_raise() File "tmp.py", line 25, in do_raise raise self __main__.MultipleValidationErrors: See the following exception tracebacks: ============================================================================== Traceback (most recent call last): File "tmp.py", line 32, in int(c) # obviously fails ValueError: invalid literal for int() with base 10: 'h' Traceback (most recent call last): File "tmp.py", line 32, in int(c) # obviously fails ValueError: invalid literal for int() with base 10: 'e' Traceback (most recent call last): File "tmp.py", line 32, in int(c) # obviously fails ValueError: invalid literal for int() with base 10: 'l' Traceback (most recent call last): File "tmp.py", line 32, in int(c) # obviously fails ValueError: invalid literal for int() with base 10: 'l' Traceback (most recent call last): File "tmp.py", line 32, in int(c) # obviously fails ValueError: invalid literal for int() with base 10: 'o' Cheers, Chris -- Go Tritons! http://blog.rebertia.com From tjreedy at udel.edu Fri May 7 00:57:52 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 May 2010 00:57:52 -0400 Subject: [Python-ideas] division oddness In-Reply-To: References: <4BE3623E.5000900@gmx.net> Message-ID: > On Thu, May 6, 2010 at 5:43 PM, Mathias Panzenb?ck >> Shouldn't by mathematical definition -x // y be the same as -(x// y)? Tradeoffs, tradeoffs. Most everyone agrees on this rule for the relation between // and %: x == y*(x//y) + x%y If // is defined as above, then, for instance, x%2 has 3 possible values (-1, 0, 1) rather than just 2. Not so good. Since y is usually positive in practical applications (what does dividing by a negative number mean?), having the sign of x%y governed by the sign of y rather than the sign of x seems advantageous. Judging from the chart at http://en.wikipedia.org/wiki/Modulo_operation languages are pretty evenly split on which definitions to use. Terry Jan Reedy From tjreedy at udel.edu Fri May 7 01:06:07 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 May 2010 01:06:07 -0400 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> Message-ID: On 5/6/2010 11:50 PM, Ben Cohen wrote: > Is there a pythonic way to collect and display multiple exceptions at > the same time? > > For example let's say you're trying to validate the elements of a > list and you'd like to validate as many of the elements as possible > in one run and still report exception's raised while validating a > failed element. > > eg -- I'd like to do something like this: > > errors = [] for item in data: try: process(item) except ValidationError as e: errors.append(e) I believe each exception replaces the traceback message. So I would collect tracebacks rather than exceptions. Try the traceback module. Terry Jan Reedy From timr at probo.com Fri May 7 01:24:28 2010 From: timr at probo.com (Tim Roberts) Date: Thu, 06 May 2010 22:24:28 -0700 Subject: Classes: nested functions vs. private methodes References: Message-ID: <9m87u59fmhjp8hhmm9anbhggllhuudl6nk@4ax.com> Richard Lamboj wrote: > >Thank you for the nice sample, but what is with multiple inheritance in your >sample? I mean the super call. Why not _MyClass.blah(self, arg). Because then I have to remember to change the name if I should happen to change the base class, or copy this code into another class. >What is when >i have more then one Class from which i inherite and in both are a methode >called "blah", but i just want to call one of them and not both, becouse they >do different things? Then you'd need use the full class name, of course. The search order is well-defined, so super() is still meaningful. However, in that case, you are rapidly getting into a design that is too complicated to understand at a glance. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ron.eggler at gmail.com Fri May 7 01:27:28 2010 From: ron.eggler at gmail.com (cerr) Date: Thu, 6 May 2010 22:27:28 -0700 (PDT) Subject: Broken pipe Message-ID: Hi There, I'm very new to Python and i wanna write a script that sends a certain string to a server. The code I came up with looks like this: #!/usr/bin/python import sys import string from socket import * usage="USAGE: "+sys.argv[0]+" "; if len(sys.argv) != 3: print usage; sys.exit(0); host = sys.argv[1]; port = sys.argv[2]; buf = 1024; addr = (host,port); sock = socket(AF_INET, SOCK_STREAM); data = string.join("NovaxTest",'\n'); sock.send(data); sock.close(); and I'm calling this script like that: "./TestService.py 127.0.0.1 1514" but when I call it I get following back: sending data to 127.0.0.1:1514 data: NovaxTest Traceback (most recent call last): File "./TestService.py", line 18, in sock.send(data); socket.error: [Errno 32] Broken pipe I understand that UNIX sends an Errno32 if the server closes the connection. But if i telnet to localhost on 1514 and send NovaxTest by hand everything works just fine. So what might be wrong here? Thank you very much! Ron From contact at xavierho.com Fri May 7 01:32:18 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 7 May 2010 15:32:18 +1000 Subject: [Python-ideas] division oddness In-Reply-To: References: <4BE3623E.5000900@gmx.net> Message-ID: On Fri, May 7, 2010 at 12:14 PM, Chris Rebert wrote: > Personally, I find the following the most unintuitive: > divmod(-11, 3) == (-4, 1) > > So, we overshoot -11 and then add 1 to go back to the right place? > That violates my intuitive thought that abs((n//d)*d) <= abs(n) ought to > hold. > Haha, really? *gives it a try* Oh wow... Yeah. I don't like that either. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Fri May 7 01:37:14 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 22:37:14 -0700 Subject: Broken pipe In-Reply-To: References: Message-ID: On Thu, May 6, 2010 at 10:27 PM, cerr wrote: > Hi There, > > I'm very new to Python and i wanna write a script that sends a certain > string to a server. The code I came up with looks like this: > #!/usr/bin/python > > import sys > import string > > from socket import * > usage="USAGE: "+sys.argv[0]+" "; > if len(sys.argv) != 3: > ? ? ? ? ? ? ?print usage; > ? ? ? ? ? ? ?sys.exit(0); > host = sys.argv[1]; > port = sys.argv[2]; > buf = 1024; > addr = (host,port); > sock = socket(AF_INET, SOCK_STREAM); > data = string.join("NovaxTest",'\n'); > sock.send(data); > sock.close(); > and I'm calling this script like that: "./TestService.py 127.0.0.1 > 1514" but when I call it I get following back: > sending data to 127.0.0.1:1514 > data: NovaxTest > Traceback (most recent call last): > ?File "./TestService.py", line 18, in > ? ?sock.send(data); > socket.error: [Errno 32] Broken pipe > I understand that UNIX sends an Errno32 if the server closes the > connection. But if i telnet to localhost on 1514 and send NovaxTest by > hand everything works just fine. So what might be wrong here? You never called sock.connect(addr). Your code doesn't even use `addr` at all. Also, please don't use semicolons in your code. It's bad style. Cheers, Chris -- http://blog.rebertia.com From ron.eggler at gmail.com Fri May 7 02:11:22 2010 From: ron.eggler at gmail.com (Ron Eggler) Date: Thu, 6 May 2010 23:11:22 -0700 Subject: Broken pipe In-Reply-To: References: Message-ID: <201005062311.23076.ron.eggler@gmail.com> On May 6, 2010 10:37:14 pm Chris Rebert wrote: > On Thu, May 6, 2010 at 10:27 PM, cerr wrote: > > Hi There, > > > > I'm very new to Python and i wanna write a script that sends a certain > > string to a server. The code I came up with looks like this: > > #!/usr/bin/python > > > > import sys > > import string > > > > from socket import * > > usage="USAGE: "+sys.argv[0]+" "; > > if len(sys.argv) != 3: > > print usage; > > sys.exit(0); > > host = sys.argv[1]; > > port = sys.argv[2]; > > buf = 1024; > > addr = (host,port); > > sock = socket(AF_INET, SOCK_STREAM); > > data = string.join("NovaxTest",'\n'); > > sock.send(data); > > sock.close(); > > and I'm calling this script like that: "./TestService.py 127.0.0.1 > > 1514" but when I call it I get following back: > > sending data to 127.0.0.1:1514 > > data: NovaxTest > > Traceback (most recent call last): > > File "./TestService.py", line 18, in > > sock.send(data); > > socket.error: [Errno 32] Broken pipe > > I understand that UNIX sends an Errno32 if the server closes the > > connection. But if i telnet to localhost on 1514 and send NovaxTest by > > hand everything works just fine. So what might be wrong here? > > You never called sock.connect(addr). Your code doesn't even use `addr` at > all. Oh, yeah, hOOps :$ > Also, please don't use semicolons in your code. It's bad style. Is it, eh? Well, I'm from C, C++ and for me it just belongs there..:) but i'll try to change my habits... :) Hm weird now I get something like: Traceback (most recent call last): File "./TestService.py", line 14, in sock.connect((host,port)) File "", line 1, in connect TypeError: an integer is required with this code: #!/usr/bin/python import sys import string from socket import * usage="USAGE: "+sys.argv[0]+" " if len(sys.argv) != 3: print usage sys.exit(0) host = sys.argv[1] port = sys.argv[2] sock = socket(AF_INET, SOCK_STREAM) sock.connect((host,port)) data = string.join("NovaxTest",'\n') sock.send(data) sock.close() What does that mean? :( Thanks, Ron From clp2 at rebertia.com Fri May 7 02:13:56 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 23:13:56 -0700 Subject: Broken pipe In-Reply-To: <201005062311.23076.ron.eggler@gmail.com> References: <201005062311.23076.ron.eggler@gmail.com> Message-ID: On Thu, May 6, 2010 at 11:11 PM, Ron Eggler wrote: > On May 6, 2010 10:37:14 pm Chris Rebert wrote: >> On Thu, May 6, 2010 at 10:27 PM, cerr wrote: >> > Hi There, >> > >> > I'm very new to Python and i wanna write a script that sends a certain >> > string to a server. The code I came up with looks like this: >> > #!/usr/bin/python >> > >> > import sys >> > import string >> > >> > from socket import * >> > usage="USAGE: "+sys.argv[0]+" "; >> > if len(sys.argv) != 3: >> > ? ? ? ? ? ? ?print usage; >> > ? ? ? ? ? ? ?sys.exit(0); >> > host = sys.argv[1]; >> > port = sys.argv[2]; >> > buf = 1024; >> > addr = (host,port); >> > sock = socket(AF_INET, SOCK_STREAM); >> > data = string.join("NovaxTest",'\n'); >> > sock.send(data); >> > sock.close(); >> > and I'm calling this script like that: "./TestService.py 127.0.0.1 >> > 1514" but when I call it I get following back: >> > sending data to 127.0.0.1:1514 >> > data: NovaxTest >> > Traceback (most recent call last): >> > ?File "./TestService.py", line 18, in >> > ? ?sock.send(data); >> > socket.error: [Errno 32] Broken pipe >> > I understand that UNIX sends an Errno32 if the server closes the >> > connection. But if i telnet to localhost on 1514 and send NovaxTest by >> > hand everything works just fine. So what might be wrong here? >> >> You never called sock.connect(addr). Your code doesn't even use `addr` at >> all. > Oh, yeah, hOOps :$ > Hm weird now I get something like: > Traceback (most recent call last): > ?File "./TestService.py", line 14, in > ? ?sock.connect((host,port)) > ?File "", line 1, in connect > TypeError: an integer is required > What does that mean? :( You never converted `port` to an int, it's still a string. You might consider reading the socket module docs: http://docs.python.org/library/socket.html Cheers, Chris -- http://blog.rebertia.com From kurianmthayil at gmail.com Fri May 7 03:21:25 2010 From: kurianmthayil at gmail.com (Kurian Thayil) Date: Fri, 7 May 2010 12:51:25 +0530 Subject: Python - MySQL fetching values In-Reply-To: References: Message-ID: On Thu, May 6, 2010 at 2:42 PM, Chris Rebert wrote: > On Thu, May 6, 2010 at 1:47 AM, Kurian Thayil > wrote: > > > the expected output is 05:35:05. > > > > Now, here is code snippet, > > > > cursor1=getconnect1.cursor() > > getrows=cursor1.execute("""SELECT > > TIME(DATE_ADD(info_last_calltime, INTERVAL %s MINUTE)) FROM rem_call_info > > WHERE info_ctrlid=%s""", (retryinterval,controlid1,)) > > rawstatus20result=cursor1.fetchone() > > print "Raw result is",rawstatus20result > > status20result=rawstatus20result[0] > > print "The query result for Status > > 20:",status20result,";Time now is",timeformat > > > > The output is: > > > > Raw result is (datetime.timedelta(0, 20105),) > > The query result for Status 20: 5:35:05 ;Time now is 05:22:00 > > Match not found. > > New call to be made > > Getting next value if any... > > > > If you look closer, the time fetched by python module was 5:35:05 instead > of > > 05:35:05. How can I get this time format? Thanks in advance. > > You're getting back a time delta (i.e. quantity/duration of time, e.g. > "3 hours") rather than an actual time (i.e. temporal coordinates for a > particular instant of time, e.g. "5:15PM and 2 seconds"), and > timedelta defines its stringification differently, hence your issue. I > would guess that getting back a timedelta instead of a time is some > quirk of MySQLdb; haven't used it though, so I'm just guessing. > > Anyway, you can work around this by converting the timedelta object to > a time object yourself: > #Untested Code! > from datetime import time > minutes, seconds = divmod(status20result.seconds, 60) > hours, minutes = divmod(minutes, 60) > time_result = time(hours, minutes, seconds, status20result.microseconds) > print "The query result for Status 20:",time_result,";Time now > is",timeformat > > Cheers, > Chris > -- > http://blog.rebertia.com > That worked Chris. Thank you. Regards, Kurian Thayil. -------------- next part -------------- An HTML attachment was scrubbed... URL: From t.lehmann at rtsgroup.net Fri May 7 03:54:52 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Fri, 7 May 2010 00:54:52 -0700 (PDT) Subject: No module named server Message-ID: <16aa8195-bbd6-4b22-a9bf-35fd63edda7d@e1g2000yqe.googlegroups.com> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Script: from http.server import HTTPServer, CGIHTTPRequestHandler Result: Traceback (most recent call last): File "http.py", line 1, in from http.server import HTTPServer, CGIHTTPRequestHandler File "F:\Checkouts\projects\python\http.py", line 1, in from http.server import HTTPServer, CGIHTTPRequestHandler ImportError: No module named server From jarausch at igpm.rwth-aachen.de Fri May 7 04:00:46 2010 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Fri, 07 May 2010 10:00:46 +0200 Subject: fast regex In-Reply-To: References: Message-ID: <84hvleFm3U1@mid.dfncis.de> On 05/06/10 16:52, james_027 wrote: > hi, > > I was working with regex on a very large text, really large but I have > time constrained. Does python has any other regex library or string > manipulation library that works really fast? Have a look at http://www.egenix.com/products/python/mxBase/mxTextTools/doc/ it claims to be fast, Helmut. From t.lehmann at rtsgroup.net Fri May 7 04:02:48 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Fri, 7 May 2010 01:02:48 -0700 (PDT) Subject: No module named server References: <16aa8195-bbd6-4b22-a9bf-35fd63edda7d@e1g2000yqe.googlegroups.com> Message-ID: <32529ed8-5052-40f1-ba4e-339ba5c22d49@o11g2000yqj.googlegroups.com> > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit Also after installing Python 3.1.2 the problem is still there. From albrecht.andi at googlemail.com Fri May 7 04:05:11 2010 From: albrecht.andi at googlemail.com (Andi Albrecht) Date: Fri, 7 May 2010 08:05:11 +0000 (UTC) Subject: No module named server References: <16aa8195-bbd6-4b22-a9bf-35fd63edda7d@e1g2000yqe.googlegroups.com> Message-ID: Thomas Lehmann schrieb: > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit > (Intel)] on win32 > > Script: > from http.server import HTTPServer, CGIHTTPRequestHandler > > Result: > Traceback (most recent call last): > File "http.py", line 1, in > from http.server import HTTPServer, CGIHTTPRequestHandler > File "F:\Checkouts\projects\python\http.py", line 1, in > from http.server import HTTPServer, CGIHTTPRequestHandler > ImportError: No module named server You should rename http.py since it collides with the "http" module you're trying to import the server and request handler classes from. Andi From t.lehmann at rtsgroup.net Fri May 7 04:24:13 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Fri, 7 May 2010 01:24:13 -0700 (PDT) Subject: No module named server References: <16aa8195-bbd6-4b22-a9bf-35fd63edda7d@e1g2000yqe.googlegroups.com> <32529ed8-5052-40f1-ba4e-339ba5c22d49@o11g2000yqj.googlegroups.com> Message-ID: <6f98f802-b0db-44d6-90bd-71eee6605a40@37g2000yqm.googlegroups.com> On 7 Mai, 10:02, Thomas Lehmann wrote: > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit > > Also after installing Python 3.1.2 the problem is still there. I know the problem. Reading a book about a simple cgi web server the descriptions says to use httpd.py as name for the file and I forgot the 'd'. This leads to the wrong behaviour. From p.f.moore at gmail.com Fri May 7 04:48:01 2010 From: p.f.moore at gmail.com (Paul Moore) Date: Fri, 7 May 2010 01:48:01 -0700 (PDT) Subject: Windows - select.select, timeout and KeyboardInterrupt References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: On 6 May, 20:58, Thomas Heller wrote: > If you look at the source code for time.sleep(), which CAN be interrupted > by pressing Ctrl-C, you will find that it is carefully programmed to be > interruptible (sp?). ?Which is not the case for select.select(), obviously. Thanks - given this, would it be worth me submitting a documentation patch noting that select.select is not interruptible on Windows? > I guess the best way might be to split your select.select() call into several > ones, using a smaller timeout like 1 second for example. Yes, that's probably good enough for my case. > BTW: I have experimented with calling the win32 function SetConsoleCtrlHandler() > before the call to select.select(). ?This allows to install a python callback > function which is called when Ctrl+C is pressed. ?However it seems this callback > is not able to interrupt the select() call - but it can 'raise SystemExit()' > which will terminate the script. ?Here is the code: That's useful - I doubt I'll need it for this case, but I'll keep it in mind for the future. Thanks for the help. Paul. From nospam at news.eternal-september.org Fri May 7 06:24:27 2010 From: nospam at news.eternal-september.org (balzer) Date: Fri, 7 May 2010 13:24:27 +0300 Subject: ActivePython - how to configure portable framework? Message-ID: I downloaded ActivePython-2.6.5.12-win32-x86.zip, it contains two folders and 3 files: SystemFolder INSTALLDIR sh2.py install.bat _install.py Anyone know how to configure this Python environment as "portable application" to work with it without installation, to set a fully-functional Python environment that executes entirely from hard drive (or USB stick) without leaving no registry entries, no mess with windows system files, etc on machine it's run on. I created folder "Python", what files I should copy inside? thanks. From nagarazang at yahoo.co.in Fri May 7 06:51:29 2010 From: nagarazang at yahoo.co.in (Nathas) Date: Fri, 07 May 2010 10:51:29 -0000 Subject: Openings at Aspire Systems, Chennai. (Product Dev. Company) Message-ID: Hi All, Please find below the openings at Aspire Systems, Chennai (www.aspiresys.com) 1. Testing - Selenium, TestComplete, RFT, Manual - SSE and Engineers - 2 + years 2. Java, Swings - Project Leader Position ? 5+ years 3. Java, J2EE ? Enngineer, SSE, Tech Arch ? 2+ Yrs 4. .NET - SSE and Tech Architect ? 3+ years 5. Silverlight, Sharepoint - Engineer, SSE ? 2+ yrs 6. PHP, Python, RoR, Great Plains - Engineer, SSE ? 2+ yrs 7. UI Developer - 2+ years 8. Sales - Sr. Exe. ? 3+ yrs Kindly circulate with your friends and do forward your / your friend's resume to the below email id. nagarajan.ganesan at aspiresys.com Thanks, Nagarajan. From richard.lamboj at bilcom.at Fri May 7 06:55:48 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Fri, 7 May 2010 12:55:48 +0200 Subject: importing modules Message-ID: <201005071255.48902.richard.lamboj@bilcom.at> Hello, I have a question about importing python modules. I have modul package, with submodules. So how can a submodul access a modul that is on level upper? Is there something like "import ../../blah"? I don't mean something like this: "import bla.blub.moep" Kind Regards, Richi From mehgcap at gmail.com Fri May 7 07:02:41 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 7 May 2010 07:02:41 -0400 Subject: importing modules In-Reply-To: <201005071255.48902.richard.lamboj@bilcom.at> References: <201005071255.48902.richard.lamboj@bilcom.at> Message-ID: I have a main folder. Inside that I have a "modes" package (subfolder holding __init__.py) as well as a "misc" package. When modes has to import helpers.py from misc, I use this: from .misc import helpers The period makes Python look up one level for misc, then go into it to find helpers. On 5/7/10, Richard Lamboj wrote: > > Hello, > > I have a question about importing python modules. > > I have modul package, with submodules. So how can a submodul access a modul > that is on level upper? > > Is there something like "import ../../blah"? I don't mean something like > this: "import bla.blub.moep" > > Kind Regards, > > Richi > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From albrecht.andi at googlemail.com Fri May 7 07:19:03 2010 From: albrecht.andi at googlemail.com (Andi Albrecht) Date: Fri, 7 May 2010 11:19:03 +0000 (UTC) Subject: importing modules References: Message-ID: Richard Lamboj schrieb: > > Hello, > > I have a question about importing python modules. > > I have modul package, with submodules. So how can a submodul access a modul > that is on level upper? > > Is there something like "import ../../blah"? I don't mean something like > this: "import bla.blub.moep" > > Kind Regards, > > Richi Hi Richi, starting with 2.5 Python allows relative imports, e.g. import ..blah Andi From nick at granger-brown.net Fri May 7 07:48:15 2010 From: nick at granger-brown.net (NickGB) Date: Fri, 7 May 2010 04:48:15 -0700 (PDT) Subject: listing exported functions in a DLL Message-ID: <9fc62d78-3163-43f7-b815-3b5b6d370681@l31g2000yqm.googlegroups.com> is there a way using ctypes to list the exported functions of a DLL? This is what I was hoping to do... from ctypes import * myDLL = windll.some_dll # what is this method? does it exist? list_of_exported_functions = myDLL.list_exported_functions() From jeanmichel at sequans.com Fri May 7 07:50:15 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 07 May 2010 13:50:15 +0200 Subject: importing modules In-Reply-To: <201005071255.48902.richard.lamboj@bilcom.at> References: <201005071255.48902.richard.lamboj@bilcom.at> Message-ID: <4BE3FE77.10005@sequans.com> Richard Lamboj wrote: > Hello, > > I have a question about importing python modules. > > I have modul package, with submodules. So how can a submodul access a modul > that is on level upper? > > Is there something like "import ../../blah"? I don't mean something like > this: "import bla.blub.moep" > > Kind Regards, > > Richi > I would advise to use absolute imports whenever possible (always ?). If 'pkg' is your package, then module sub1 should import sub2 that way: file pkg/sub1.py: import pkg.sub2 see http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports " the python-dev community chose absolute imports as the default because they're the more common use case and because absolute imports can provide all the functionality of relative (intra-package) imports -- albeit at the cost of difficulty when renaming package pieces higher up in the hierarchy or when moving one package inside another." You can still use relative import if you want, they've been implemented for a purpose, but I woudl highly discourage the ambiguous relative imports of python 2.4. JM From aahz at pythoncraft.com Fri May 7 08:23:07 2010 From: aahz at pythoncraft.com (Aahz) Date: 7 May 2010 05:23:07 -0700 Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> <2010050619481239450-tomfsessile@gmailcom> Message-ID: In article <2010050619481239450-tomfsessile at gmailcom>, TomF wrote: > >I don't doubt it. But I'm not really interested in line (micro) level >code issues at the moment. Not that my code couldn't stand being >improved, but I'm more interested in seeing how medium/large OO python >systems are designed. If I could get this from a book I would, but I >suspect I need to study real code. My suspicion is that very very few medium/large systems are truly "well-designed". I've had occasion to dive into the CherryPy and Cheetah code, you might look there. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From richard.lamboj at bilcom.at Fri May 7 08:25:40 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Fri, 7 May 2010 14:25:40 +0200 Subject: importing modules In-Reply-To: <4BE3FE77.10005@sequans.com> References: <201005071255.48902.richard.lamboj@bilcom.at> <4BE3FE77.10005@sequans.com> Message-ID: <201005071425.40959.richard.lamboj@bilcom.at> Am Friday 07 May 2010 13:50:15 schrieb Jean-Michel Pichavant: > Richard Lamboj wrote: > > Hello, > > > > I have a question about importing python modules. > > > > I have modul package, with submodules. So how can a submodul access a > > modul that is on level upper? > > > > Is there something like "import ../../blah"? I don't mean something like > > this: "import bla.blub.moep" > > > > Kind Regards, > > > > Richi > > I would advise to use absolute imports whenever possible (always ?). > If 'pkg' is your package, then module sub1 should import sub2 that way: > > file pkg/sub1.py: > > import pkg.sub2 > > > see http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports > > " the python-dev community chose absolute imports as the default because > they're the more common use case and because absolute imports can > provide all the functionality of relative (intra-package) imports -- > albeit at the cost of difficulty when renaming package pieces higher up > in the hierarchy or when moving one package inside another." > > You can still use relative import if you want, they've been implemented > for a purpose, but I woudl highly discourage the ambiguous relative > imports of python 2.4. > > JM Hello, I always use absolute imports, but sometimes i does not work. I got: ImportError: No module named mail. When i import it from top of the module it works. If i import it from a level down, it works not always - strange? Kind Regards, Richi From nospam at news.eternal-september.org Fri May 7 08:31:32 2010 From: nospam at news.eternal-september.org (balzer) Date: Fri, 7 May 2010 15:31:32 +0300 Subject: Movable Python or ActivePython References: Message-ID: "Sridhar Ratnakumar" wrote in message news:mailman.2638.1273083585.23598.python-list at python.org... On 2010-05-05, at 5:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for > testing programs. As I read, Movable Python can run without being > installed. It needs no registry entries and knows the path to all the dlls > (system or otherwise) that it uses. > Whats about ActivePython > http://www.activestate.com/activepython/downloads? Does it requires > installation? The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ (substitute with latest version) When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 x64 machine - by extracting and running python.exe (from INSTALLDIR/) without installing - it just worked. -srid =========== Not works for me. I tried run python script from INSTALLDIR/ - not works for me. Looks, its extremely inconveniet, not user-friendly. There's a vaste quanity of various stuff inside pyhon folders. From neilc at norwich.edu Fri May 7 08:31:33 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 7 May 2010 12:31:33 GMT Subject: List comprehension + lambdas - strange behaviour References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Message-ID: <84ifh5Fj5aU5@mid.individual.net> On 2010-05-07, Terry Reedy wrote: > On 5/6/2010 3:34 PM, Artur Siekielski wrote: >> Hello. >> I found this strange behaviour of lambdas, closures and list >> comprehensions: >> >>>>> funs = [lambda: x for x in range(5)] >>>>> [f() for f in funs] >> [4, 4, 4, 4, 4] > > You succumbed to lambda hypnosis, a common malady ;-). The > above will not work in 3.x, which does not leak comprehension > iteration variables. It functions the same in 3.1. Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> funs = [lambda: x for x in range(5)] >>> [f() for f in funs] [4, 4, 4, 4, 4] -- Neil Cerutti *** Your child was bitten by a Bat-Lizard. *** From python.list at tim.thechases.com Fri May 7 08:32:33 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 May 2010 07:32:33 -0500 Subject: fast regex In-Reply-To: References: <87eihp2gf8.fsf@castleamber.com> <4BE37F36.3090701@tim.thechases.com> Message-ID: <4BE40861.8080801@tim.thechases.com> [your reply appears to have come only to me instead of the mailing list; CC'ing c.l.p in reply] On 05/06/2010 10:12 PM, James Cai wrote: > When you say "This does a replacement for every word in the input corpus > (possibly with itself), but only takes one pass through the source text. " > It sounds great, but I am kinda lost with your code, sorry I am a regex > newbie. > > calling statement > > results = r.sub(replacer, content) > > the replacer is a function that needs parameter. How does the replacer know > what parameter? The documentation on the .sub() method says that the replacement can either be some text (as you used) or something callable (in my case a function, but could be an object with a __call__ method too), and that this callable is passed the match-object that's found. > why is r = re.compile(r'\b[a-zA-Z]+\b') when the words i want to find should > be in the word_list? You don't detail what sorts of words are in your word_list.keys() but you'd want your pattern to match those. My first regexp (that you quote) matches single words, but rather loosely (thus my caveat about "replace[s] every word in the input"). The replacement function checks to see if the replacement is in your word-list, and does the replacement, otherwise, it just returns the input. To watch it in action, you can try this: d = { # keys are all lowercase 'hello': 'goodbye', 'world': 'Python', } def replacer(match): text = match.group(0) replacement = d.get(text.lower(), text) # see what we're doing for explanation purposes print "Replacing %r with %r" % (text, replacement) return replacement r = re.compile(r'\b[a-zA-Z]+\b') print r.sub(replacer, "Hello there world, this is a test") > Is the match here the match of regex or just a variable name? If the keys in your word_list are more than just words, then the regexp may not find them all, and thus not replace them all. In that case you may have to resort to my 2nd regexp which builds the 5k branch regexp from your actual dictionary keys: >> r = re.compile(r'\b(%s)\b' % ( >> '|'.join(re.escape(s) for s in words_list.keys()) >> ), >> re.IGNORECASE) This method on the above dictionary (modified) d = { 'hello': 'goodbye', 'world': 'python', 'stuff with spaces?': 'tadah!', } would create a regexp of \b(hello|world|stuff\ with\ spaces\?)\b This has considerable performance implications as len(word_list) grows, unless you can figure a way to determine that some replacements are more probable than others and push them to the front of this regexp, but that's more complex and requires knowledge of your word-list. However, if all your keys are simply alpha (or alphanumeric, or findable by a simple regexp; likely one that doesn't include whitespace), you'll likely get much better performance with a generic regexp that over-captures, tries to find a replacement in your dict, returning that as the replacement; or if it's not in the dict, returning the original text unchanged. My simple test would be: test_regex = r'\w+' r = re.compile(r'^\b%s\b$' % test_regex) # added the "^....$" to anchor for testing purposes for key in word_list: # keys by default if not r.match(key): print "Failed to match %r" % key break If this passes, then the regexp should likely be sufficient to capture everything needed to use my replacer() function above. -tkc From jeanmichel at sequans.com Fri May 7 08:43:36 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 07 May 2010 14:43:36 +0200 Subject: importing modules In-Reply-To: <201005071425.40959.richard.lamboj@bilcom.at> References: <201005071255.48902.richard.lamboj@bilcom.at> <4BE3FE77.10005@sequans.com> <201005071425.40959.richard.lamboj@bilcom.at> Message-ID: <4BE40AF8.7070907@sequans.com> Richard Lamboj wrote: > Am Friday 07 May 2010 13:50:15 schrieb Jean-Michel Pichavant: > >> Richard Lamboj wrote: >> >>> Hello, >>> >>> I have a question about importing python modules. >>> >>> I have modul package, with submodules. So how can a submodul access a >>> modul that is on level upper? >>> >>> Is there something like "import ../../blah"? I don't mean something like >>> this: "import bla.blub.moep" >>> >>> Kind Regards, >>> >>> Richi >>> >> I would advise to use absolute imports whenever possible (always ?). >> If 'pkg' is your package, then module sub1 should import sub2 that way: >> >> file pkg/sub1.py: >> >> import pkg.sub2 >> >> >> see http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports >> >> " the python-dev community chose absolute imports as the default because >> they're the more common use case and because absolute imports can >> provide all the functionality of relative (intra-package) imports -- >> albeit at the cost of difficulty when renaming package pieces higher up >> in the hierarchy or when moving one package inside another." >> >> You can still use relative import if you want, they've been implemented >> for a purpose, but I woudl highly discourage the ambiguous relative >> imports of python 2.4. >> >> JM >> > > Hello, > > I always use absolute imports, but sometimes i does not work. > > I got: ImportError: No module named mail. When i import it from top of the > module it works. If i import it from a level down, it works not always - > strange? > > Kind Regards, > > Richi > Absolute imports works, 100%. You're doing something wrong. "No module named mail" means you forgot to prefix your submodule mail by the package name. It should be something like import pkg.mail The rule is simple, if pkg is your package, any import of a submodule should start with import pkg. Also note that your package must be properly installed (i.e. import pkg should work, no matter the directory you're in). If you don't want to install your package (don't wanna mess your PYTHONPATH with dev package), then you have to run your scripts from pkg/.. JM From davea at ieee.org Fri May 7 08:45:33 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 07 May 2010 08:45:33 -0400 Subject: column selection In-Reply-To: <4BE2C032.9080605@ieee.org> References: <1273140847.S.2303.13864.f4mail-235-207.rediffmail.com.1273148674.35579@webmail.rediffmail.com> <4BE2C032.9080605@ieee.org> Message-ID: <4BE40B6D.80508@ieee.org> Dave Angel wrote: >
mannu jha > wrote: >> I tried with this: >> >> for line in open('1.txt'): >> columns = line.split() >> print columns[0], columns[1] >> if not line: continue >> >> but it is showing error: >> >> nmruser at caf:~> python split.py >> 24 ALA >> Traceback (most recent call last): >> File "split.py", line 3, in print columns[0], columns[1] >> IndexError: list index out of range >> nmruser at caf:~> >> >> Thanks, >> >> On Thu, 06 May 2010 15:44:07 +0530 wrote >> >> >> If your files have two blank lines between each useful line, you have to >> do something to avoid trying to print those items for the blank lines. >> Depending how sure you are about your formatting, you could either do a >> >> if not line: continue >> >> or a >> >> if columns < 3: continue >> >> >> DaveA >> >> >> > (Don't top-post. It makes the message very confusing to someone else > trying to follow it. Also, enable your mail program's quoting feature > -- currently it's not adding the marks at the beginning of each line > you quote.) > > If you're going to skip over blank lines, it'd be good to do it before > trying to print from it. Move the test up by a line. > > DaveA > for line in open('1.txt'): columns = line.split() if len(columns) < 2: continue #skip over lines that don't have at least 2 columns print columns[0], columns[1] DaveA From python at bdurham.com Fri May 7 09:01:06 2010 From: python at bdurham.com (python at bdurham.com) Date: Fri, 07 May 2010 09:01:06 -0400 Subject: Movable Python or ActivePython In-Reply-To: References: Message-ID: <1273237266.16860.1373896225@webmail.messagingengine.com> Balzer, I took a look at the zip version of ActiveState's Python. There's a related thread in on this mailing list where I asked if the zip files are missing the Microsoft VC runtime files required by the Python interpreter. According to Trent from ActiveState, this is indeed the case. I recommend taking a look at this thread and contacting ActiveState to see when they expect to have a fix. You might also try taking a look at Py2exe and building your own Python "run time" (minus Idle). Malcolm ----- Original message ----- From: "balzer" To: python-list at python.org Date: Fri, 7 May 2010 15:31:32 +0300 Subject: Re: Movable Python or ActivePython "Sridhar Ratnakumar" wrote in message news:mailman.2638.1273083585.23598.python-list at python.org... On 2010-05-05, at 5:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for > testing programs. As I read, Movable Python can run without being > installed. It needs no registry entries and knows the path to all the dlls > (system or otherwise) that it uses. > Whats about ActivePython > http://www.activestate.com/activepython/downloads? Does it requires > installation? The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ (substitute with latest version) When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 x64 machine - by extracting and running python.exe (from INSTALLDIR/) without installing - it just worked. -srid =========== Not works for me. I tried run python script from INSTALLDIR/ - not works for me. Looks, its extremely inconveniet, not user-friendly. There's a vaste quanity of various stuff inside pyhon folders. -- http://mail.python.org/mailman/listinfo/python-list From nospam at news.eternal-september.org Fri May 7 09:48:55 2010 From: nospam at news.eternal-september.org (balzer) Date: Fri, 7 May 2010 16:48:55 +0300 Subject: Movable Python or ActivePython References: Message-ID: wrote in message news:mailman.2732.1273237281.23598.python-list at python.org... > Balzer, > > I took a look at the zip version of ActiveState's Python. > > There's a related thread in on this mailing list where I asked if the > zip files are missing the Microsoft VC runtime files required by the > Python interpreter. > > According to Trent from ActiveState, this is indeed the case. > > I recommend taking a look at this thread and contacting ActiveState to > see when they expect to have a fix. > > You might also try taking a look at Py2exe and building your own Python > "run time" (minus Idle). > > Malcolm > > > ----- Original message ----- > From: "balzer" > To: python-list at python.org > Date: Fri, 7 May 2010 15:31:32 +0300 > Subject: Re: Movable Python or ActivePython > > > "Sridhar Ratnakumar" wrote in message > news:mailman.2638.1273083585.23598.python-list at python.org... > > On 2010-05-05, at 5:47 AM, balzer wrote: > >> I want Python pack that can run without being installed, mostly for >> testing programs. As I read, Movable Python can run without being >> installed. It needs no registry entries and knows the path to all the >> dlls >> (system or otherwise) that it uses. >> Whats about ActivePython >> http://www.activestate.com/activepython/downloads? Does it requires >> installation? > > The .MSI installer does require installation, but there is also a .ZIP > package which doesn't. It is not visible in the downloads page, but you > can > always get it here: > > http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ > (substitute with latest version) > > When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 > x64 > machine - by extracting and running python.exe (from INSTALLDIR/) > without > installing - it just worked. > > -srid > > =========== > Not works for me. I tried run python script from INSTALLDIR/ - not works > for > me. Looks, its extremely inconveniet, not user-friendly. > There's a vaste quanity of various stuff inside pyhon folders. > > -- > http://mail.python.org/mailman/listinfo/python-list --------------- Is there some better, simpler ways for newbee? I need "install" Python on Windows XP without connection with windows system files or registry. And run Python it as independent framework. I just need test a few python scripts. Other question: how difficult is to convert Python code to pure C code? Thanks. From luke.leighton at googlemail.com Fri May 7 10:06:00 2010 From: luke.leighton at googlemail.com (lkcl) Date: Fri, 7 May 2010 07:06:00 -0700 (PDT) Subject: pyjamas 0.7 released References: <5cf8017c-d2e1-4ee4-b5d4-48e0cda19396@i37g2000yqn.googlegroups.com> <823f6745-c63a-45c5-a11e-860b7f344262@o11g2000yqj.googlegroups.com> <518it5t6hpvv4pdlue6cljmb09mse7ctov@4ax.com> <80d02ac5-b6ed-43fa-9508-67996cbedfde@b18g2000yqb.googlegroups.com> Message-ID: <04524266-6791-467c-b74d-40d4fd54486d@g21g2000yqk.googlegroups.com> On May 2, 7:16?am, Wolfgang Strobl wrote: > lkcl : > > > at least _some_ input would be good! ?the knowledge doesn't have to > >be there: just the bugreports saying "there's a problem and here's > >exactly how you reproduce it" would be a start! > >> So please make it simpler for more people to help. > > ... how?? there's a bugtracker, wiki, svn repository, over 30 > >examples and a developer list. ?the code really _is_ very very small > >(the UI widget set, with around 75 widgets, minus the license header > >text is only around 4,000 lines _total_, making it very very simple > >and very very easy for people to get used to). ?suggestions welcome! > > Well, the bunch of programming languages and APIs I collected over the > years is large enough already. These days I prefer to stay with python > and c, spiced with an occasional domain specific language. That's why I > was attracted bypyjamas, to begin with!. ?If I'd like to program using > Eclipse and Java or fool around with JavaScript, I'd do just that. But I > don't. ?IMHO, that ist a general problem of translation tools - they > attract the wrong people, from the point of view a developer who looks > for people sharing some of the workload. :-) > > So, Luke, I can only answer your question from the point of view of > somebody who is mostly a potentional consumer of your work, and most > problably not another developer. If you want to delegate some work you'd > like not to do yourself (for example because you prefer designing and > coding to testing and reorganizing and polishing the docs), than you > have at least to _define_ those pieces and to monitor progress. the project's run on a much much simpler basis than that: anyone who wants to contribute absolutely anything, ask, and you get svn access - simple as that. you get told what the rules are (code that's committed to trunk must work, must have a commit message, must be "single-purpose", must follow PEP8 mostly and so on - the usual obvious stuff). that's pretty much it. the project really _is_ run on the basis of it being "a useful tool for the developers, and if other people benefit from it that's great". kees wanted a better interpreter, i granted him svn rights, and in about four to five months he absolutely smacked the compiler into incredible and amazing shape, including implementing "yield" - fully and properly across _all_ browsers so that it passes even the python regression tests. me, personally, i would be happy with the state the compiler was in, back in 0.5, because that limited functionality served _my_ purposes. but, for kees, it definitely didn't: he wanted to be able to compile http://puremvc.org python code "as-is" and that meant that the compiler _had_ to be improved. so it's much _much_ simpler than "delegation of tasks". someone wants to do something? _great_ - knock yourself out. that having been said: we do have a TODO list. unsurprisingly, it's in the top level directory, called "TODO" :) > >> > then please issue bugreports for as many as you feel comfortable > >> >with / have time for. ? > > Well, ok. I put my notes in a Google chart, see http://spreadsheets.google.com/pub?key=0Au5LhqNQyrfCdGpDbTVjZFJwSERzV... ouaaaah, absolutely absolutely fantastic, thank you. ok. yep. the Controls one, someone provided a patch contributing the 2-axis slider and base class, but it was a bit of a mess, and i belieeve it only compile(s/d) with --strict. i've made some changes, _thank_ you for pointing these errors out, i've recorded them in issues. > I had to write a short patch against compile.py (see issue 397) in order > to make it compile the showcase examples on Windows. okaay, good stuff. > In addition, I've tried to create Selenium tests for automating the time > consuming job of checking all those examples, using Selenium IDE in > Firefox. I was my first experience using this against Ajax apps. The > results are somewhat mixed. Playing a round of "lightout" was a breeze, > but so far I hadn't much luck in driving the showcase example(s). I > didn't try very hard, though, because I ran out of time, as I do now. ? hell, your input has been incredibly valuable, i'm very grateful for the time you've put in. btw yes i started doing a UITest because yes, it's silly to have to do so much manual work. by writing a UITest app the goal is to be able to run the tests automated even across pyjd platforms. it'd be possible but raather tricky to run selenium under xulrunner/pyjd. l. From steve at REMOVE-THIS-cybersource.com.au Fri May 7 10:17:36 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 May 2010 14:17:36 GMT Subject: idiomatic way to collect and report multiple exceptions? References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> Message-ID: <4be420ff$0$8754$c3e8da3@news.astraweb.com> On Thu, 06 May 2010 21:56:10 -0700, Chris Rebert wrote: [...] > Output from example: > Traceback (most recent call last): > File "tmp.py", line 35, in > multiple_err.do_raise() > File "tmp.py", line 25, in do_raise > raise self > __main__.MultipleValidationErrors: See the following exception > tracebacks: > ============================================================================== > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'h' > > > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'e' [...] That's a nice trick, but I'd really hate to see it in real life code. Especially when each traceback was deep rather than shallow. Imagine having fifty errors, each one of which was ten or twenty levels deep! I also question how useful this would be in real life. Errors can cascade in practice, and so you would very likely get spurious errors that were caused by the first error. You see the same thing in doctests, e.g. if you do this: >>> x = 42/0 # oops, I meant 10 >>> y = x+1 not only do you get a legitimate DivideByZero error, but then you get a spurious NameError because x doesn't exist. (This is, I believe, a weakness of doctests.) Also, unless I'm badly mistaken, don't traceback objects interfere with garbage deletion? So keeping all those tracebacks around for some indefinite time could be very expensive. -- Steven From python at bdurham.com Fri May 7 10:21:39 2010 From: python at bdurham.com (python at bdurham.com) Date: Fri, 07 May 2010 10:21:39 -0400 Subject: Movable Python or ActivePython In-Reply-To: References: Message-ID: <1273242099.29417.1373909289@webmail.messagingengine.com> Balzer, > I just need test a few python scripts. I recommend you look at Movable Python or Portable Python. Malcolm From mannu_0523 at rediffmail.com Fri May 7 10:24:56 2010 From: mannu_0523 at rediffmail.com (mannu jha) Date: 7 May 2010 14:24:56 -0000 Subject: =?utf-8?B?UmU6IFJlOiBjb2x1bW4gc2VsZWN0aW9u?= In-Reply-To: <4BE40A74.8040706@ieee.org> Message-ID: <1273238939.S.3700.1037.H.TkRhdmUgQW5nZWwAUmU6IGNvbHVtbiBzZWxlY3Rpb24_.f4-234-118.1273242294.58146@webmail.rediffmail.com> On Fri, 07 May 2010 18:58:59 +0530 wrote >mannu jha wrote: > On Thu, 06 May 2010 18:54:59 +0530 wrote > >> mannu jha wrote: >> > > >> I tried with this: >> > > > > >> for line in open('1.txt'): >> > > >> columns = line.split() >> > > >> print columns[0], columns[1] >> > > >> if not line: continue >> > > > > >> but it is showing error: >> > > > > >> nmruser at caf:~> python split.py >> > > >> 24 ALA >> > > >> Traceback (most recent call last): >> > > >> File "split.py", line 3, in >> > > >> print columns[0], columns[1] >> > > >> IndexError: list index out of range >> > > >> nmruser at caf:~> >> > > > > >> Thanks, >> > > > > >> On Thu, 06 May 2010 15:44:07 +0530 wrote >> > > >> >> > > > > > > >> If your files have two blank lines between each useful line, you have to >> > > > > >> do something to avoid trying to print those items for the blank lines. >> > > > > >> Depending how sure you are about your formatting, you could either do a >> > > > > >> if not line: continue >> > > > > >> or a >> > > > > >> if columns < 3: continue >> > > > > > > >> DaveA >> > > > with this > > for line in open('8.txt'): > columns = line.split() > if columns python split.py > 24 ALA > Traceback (most recent call last): > File "split.py", line 4, in > print columns[0], columns[1] > IndexError: list index out of range > nmruser at caf:~> > > > > > > > >> >> > > (Don't top-post. It makes the message very confusing to someone else > > trying to follow it. Also, enable your mail program's quoting feature > > -- currently it's not adding the marks at the beginning of each line you > > quote.) > > > > If you're going to skip over blank lines, it'd be good to do it before > > trying to print from it. Move the test up by a line. > > > > DaveA > > > You forgot to include the list in your reply. Use reply-all, it's much easier. No clue what that "if columns..." line is supposed to be. It should get a parse error. DaveA Thankyou very much sir........Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From utabintarbo at gmail.com Fri May 7 10:32:49 2010 From: utabintarbo at gmail.com (utabintarbo) Date: Fri, 7 May 2010 07:32:49 -0700 (PDT) Subject: Cross-platform file paths Message-ID: Until now, I have used the UNC under Windows (XP) to allow my program to access files located on a Samba-equipped *nix box (eg. os.path.normpath(r"\\serverFQDN\sharename\dir\filename")). When I try to open this file under Linux (Red Hat 5), I get a file not found error. Is there a cross-platform method for accessing files on a network share using Python 2.X? TIA From dodo_do_not_wake_up at yahoo.Fr Fri May 7 10:33:13 2010 From: dodo_do_not_wake_up at yahoo.Fr (Dodo) Date: Fri, 07 May 2010 16:33:13 +0200 Subject: CGI python 3 write RAW BINARY In-Reply-To: <4bdc07d4$0$2980$ba4acef3@reader.news.orange.fr> References: <4bd8ae7e$0$27615$ba4acef3@reader.news.orange.fr> <4bd96540$0$27597$ba4acef3@reader.news.orange.fr> <4bd9b4c2$0$27606$ba4acef3@reader.news.orange.fr> <4bd9fc1a$0$2980$ba4acef3@reader.news.orange.fr> <4bdc07d4$0$2980$ba4acef3@reader.news.orange.fr> Message-ID: <4be424a8$0$27586$ba4acef3@reader.news.orange.fr> Le 01/05/2010 12:52, Dodo a ?crit : > Le 30/04/2010 17:52, Antoine Pitrou a ?crit : >> Le Thu, 29 Apr 2010 23:37:32 +0200, Dodo a ?crit : >>> ....I don't get a thing. >>> Now with the fix : >>> All browsers shows a different thing, but not the image! >>> http://ddclermont.homeip.net/misc/python/ >>> >>> If I save it to computer : >>> * Windows image viewer won't read it >>> * Irfanview can read it without problems >> >> Did you set the content-type and content-length in the HTTP headers? >> Can you post your code? >> >> > I didn't know about content-lenght > Here's the new code (I used a fixed image patch to make sure this is not > the source of the problem) > > > #!/usr/bin/python3 > import cgi, sys, cgitb > cgitb.enable() > > f = open("/home/dodo/54.jpg", "rb") > data = f.read() > l = len(data) > f.close() > > print("Content-type:image/jpg\nContent-length:%d\n\n" % l) > > sys.stdout.flush() > sys.stdout.buffer.write( data ) > > > > Dorian Anyone? From g.rodola at gmail.com Fri May 7 10:36:44 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Fri, 7 May 2010 16:36:44 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: You can easily avoid this by setting a lower timeout when calling asyncore.loop(), like 1 second or less (for example, Twisted uses 0.001 secs). Actually there's no reason for asyncore to have such a high default timeout (30 seconds). I think this should be signaled on the bug tracker. --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil 2010/5/6 Paul Moore : > >From a quick experiment, it seems that select.select with a timeout > doesn't react to a keyboard interrupt until the timeout expires. > Specifically, if I do > > s = socket.socket() > select.select([s], [], [], 30) > > and then press Ctrl-C, Python waits for the 30 seconds before raising > KeyboardInterrupt. > > Is this a known limitation on Windows? I see no mention of it in the > documentation. Assuming it is a known limitation, is there a way round > it? (I'm writing a tiny server using asyncore/asynchat, and the > delayed response to Ctrl-C is a mild nuisance. Solutions such as "use > twisted", while probably the sensible option in a wider context, don't > really apply here - I need something within the confines of the stdlib > if it's to be worth doing). > > Thanks, > Paul > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVE-THIS-cybersource.com.au Fri May 7 10:41:39 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 May 2010 14:41:39 GMT Subject: Classes: nested functions vs. private methodes References: Message-ID: <4be426a2$0$8754$c3e8da3@news.astraweb.com> On Thu, 06 May 2010 12:40:16 +0200, Richard Lamboj wrote: > Thank you for the nice sample, but what is with multiple inheritance in > your sample? I mean the super call. Why not _MyClass.blah(self, arg). super() should work correctly when you have more complicated multiple inheritance, while calling the parent class directly may not. Of course you can call _MyClass.blah if you prefer, for single inheritance it should be good enough. > What is when i have more then one Class from which i inherite and in > both are a methode called "blah", but i just want to call one of them > and not both, becouse they do different things? super() will not call both, it will call the first method that matches. Unfortunately, multiple inheritance is complicated. Here is a good article on super(): http://www.artima.com/weblogs/viewpost.jsp?thread=236275 And for fairness, here is an article which argues that super() is harmful: http://fuhm.net/super-harmful/ but really, it seems to me that he is arguing that super() is hard to get right, not harmful, and that is not because super() is hard, but because multiple inheritance is hard. -- Steven From pmaupin at gmail.com Fri May 7 10:45:02 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 7 May 2010 07:45:02 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: On May 6, 6:56?pm, Ben Finney wrote: > a... at pythoncraft.com (Aahz) writes: > > In article <4BE05D75.7030... at msn.com>, > > Rouslan Korneychuk ? wrote: > > > >The only question I have now is what about licensing? Is that > > >something I need to worry about? Should I go with LGPL, MIT, or > > >something else? > > > Which license you use depends partly on your political philosophy. > > Yes. > > Unless you place such a low value the freedom of your users that you'd > allow proprietary derivatives of your work to remove the freedoms you've > taken care to grant, Oh, you mean like Guido and the PSF, and all the Apache people. Yes, they're an uncaring bunch. I wouldn't trust software written by any of them, or attempt to emulate them in any way. > then you should choose a copyleft license like the > GPL. This is certainly appropriate in some circumstances. The only time I personally would use the GPL is if I thought I wrote something so wonderful and uneasily replicated that I wanted to directly make money off it, and thus wanted to make it harder for others to take it and sell enhanced versions without giving me the code back. For years, I have viewed the GPL as more of a commercial license than the permissive ones, a view that has been validated by several high profile events recently. > > Unless you have an aggressively Stallmanesque attitude that people > > using your code should be forced to contribute back any changes > > Er, no. Anyone who thinks that a copyleft license ?forces? anyone to do > anything is mistaken about copyright law Perhaps you feel "forces" is too loaded of a word. There is no question, however, that a copyright license can require that if you do "X" with some code, you must also do "Y". There is also no question that the GPL uses this capability in copyright law to require anybody who distributes a derivative work to provide the source. Thus, "forced to contribute back any changes" is definitely what happens once the decision is made to distribute said changes in object form. >, or the GPL, or both. The GPL > only grants permissions, like any other free software license. But the conditions attached to those permissions make it not at all "like any other free software license." And that's true whether we use the word "forces" or not. Regards, Pat From pmaupin at gmail.com Fri May 7 10:58:30 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 7 May 2010 07:58:30 -0700 (PDT) Subject: fast regex References: <87eihp2gf8.fsf@castleamber.com> <35bb1a8a-6f63-428e-8b96-1dcc41c4cb76@h20g2000prn.googlegroups.com> Message-ID: On May 6, 9:44?pm, james_027 wrote: > On May 6, 11:33?pm, John Bokma wrote: > > > james_027 writes: > > > I was working with regex on a very large text, really large but I have > > > time constrained. Does python has any other regex library or string > > > manipulation library that works really fast? > > > Hard to answer without seeing your regex and requirements first. > > Your question is like: I had a meal yesterday and it upset my > > stomach. Can you suggest a different meal for today? > > > -- > > John Bokma ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? j3b > > > Hacking & Hiking in Mexico - ?http://johnbokma.com/http://castleamber.com/-Perl & Python Development > > I am doing something like this > > for key, value in words_list.items(): > ? ? compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) > ? ? search = compile.sub(value, content) > > where the content is a large text about 500,000 characters and the > word list is about 5,000 > > Any optimization for the code above? Sure. for key, value in words_list.items(): pass compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) search = compile.sub(value, content) From fpm at u.washington.edu Fri May 7 11:23:53 2010 From: fpm at u.washington.edu (cassiope) Date: Fri, 7 May 2010 08:23:53 -0700 (PDT) Subject: Cross-platform file paths References: Message-ID: <421e3c4c-df08-40bc-89dc-33254d990639@t26g2000prt.googlegroups.com> On May 7, 7:32?am, utabintarbo wrote: > Until now, I have used the UNC under Windows (XP) to allow my program > to access files located on a Samba-equipped *nix box (eg. > os.path.normpath(r"\\serverFQDN\sharename\dir\filename")). When I try > to open this file under Linux (Red Hat 5), I get a file not found > error. > > Is there a cross-platform method for accessing files on a network > share using Python 2.X? > > TIA normpath will convert forward slashes to backslashes on WinXX systems, but does not seem to do the reverse on posix systems...so try changing your string to use forward slashes. Also- is the path otherwise the same on your Linux system? HTH.. -f From mkiever at Pirx.sirius.org Fri May 7 11:45:52 2010 From: mkiever at Pirx.sirius.org (Matthias Kievernagel) Date: Fri, 7 May 2010 15:45:52 +0000 (UTC) Subject: py3 tkinter acceps bytes. why? References: <4BE352E5.4060004@v.loewis.de> Message-ID: Me: >> If I don't want bytes to get passed to tkinter >> I just have to raise an exception in AsObj, no? >> Or is it even sufficient to just remove the bytes case? Martin v. Loewis wrote: > But why would you want that? There are commands which legitimately > return bytes, e.g. the file and network io libraries of Tcl (not that > you would usually want to use them in Python, but Tkinter is actually > Tclinter, and should support all Tcl commands). I'm just looking for a reliable error message when I pass something to GUI functions which is not fit for display, i.e. not a string. If bytes pass unnoticed, I'll sooner or later have a surprise. Just to make sure I decode all bytes (coming from a socket) before I pass them on to the GUI. Regards, Matthias Kievernagel From wrw at mac.com Fri May 7 12:30:10 2010 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Fri, 07 May 2010 12:30:10 -0400 Subject: Frustration debugging serial code Message-ID: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> Hello World - I'm new to both Python and this list, but here's hoping someone can spot my problem. System: Mac OS-X, 10.6.3 (Intel dual quad processor) Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 The following snippet of code is designed to open a port via a KeySpan USB-to-serial converter and communicate with an X10 power line signaling system. Before you look at the code, let me mention that my frustration is the it executes perfectly if i enter it line by line at the Python prompt, and executes perfectly if I run it under the Wing IDE. It fails silently (no errors) if I run it as a standalone script. Clearly, I'm missing something. TIA, Bill Wing import serial, string port = '/dev/tty.KeySerial1' ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port stat1 = ser.write('\x02') # Write "Attention" to PowerLink print(' Stat1 is:', stat1) ack = ser.read(2) # Check to see if PowerLink is ready if ack == '\x06\r': # It returns ACK (\x06) \r if it is stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at House Code B, device code 2 print(' Stat2 is:', stat2) stat3 = ser.close() # Close serial port print(' Stat3 is:', stat3) elif ack =='\x15': # PowerLink sends NAC (hex 15) if it isn't. print('Received NAK after first open') else: print("Something's wrong at 1.\n") dummy = raw_input(' Hit any key to continue: ') -------------- next part -------------- An HTML attachment was scrubbed... URL: From utabintarbo at gmail.com Fri May 7 12:33:20 2010 From: utabintarbo at gmail.com (utabintarbo) Date: Fri, 7 May 2010 09:33:20 -0700 (PDT) Subject: Cross-platform file paths References: <421e3c4c-df08-40bc-89dc-33254d990639@t26g2000prt.googlegroups.com> Message-ID: <277ec1e8-85d0-44f2-b7ce-6efd42694a66@g21g2000yqk.googlegroups.com> On May 7, 11:23?am, cassiope wrote: > > normpath will convert forward slashes to backslashes on WinXX systems, > but > does not seem to do the reverse on posix systems...so try changing > your > string to use forward slashes. ?Also- is the path otherwise the same > on > your Linux system? > > HTH.. > ? -f I tried forward slashes: lst_p = open(os.path.normpath('//serverFQDN/sharename/dir/ filename'),'r').readlines() Traceback (most recent call last): File "", line 1, in IOError: [Errno 2] No such file or directory: '//serverFQDN/sharename/ dir/filename' BTW, this works on WinXP. It is as if it does not resolve, yet I have '//serverFQDN/sharename' mounted, proving that it does resolve. Is this an issue with the way python deals with the network? It does not seem like a network-only issue. From ron.eggler at gmail.com Fri May 7 12:45:10 2010 From: ron.eggler at gmail.com (Ron Eggler) Date: Fri, 7 May 2010 09:45:10 -0700 Subject: Broken pipe In-Reply-To: References: <201005062311.23076.ron.eggler@gmail.com> Message-ID: <201005070945.11284.ron.eggler@gmail.com> -- Ron Eggler Suite# 1804 1122 Gilford St Vancouver, BC V6G 2P5 Canada (778) 230-9442 > On Thu, May 6, 2010 at 11:11 PM, Ron Eggler wrote: > > On May 6, 2010 10:37:14 pm Chris Rebert wrote: > >> On Thu, May 6, 2010 at 10:27 PM, cerr wrote: > >> > Hi There, > >> > > >> > I'm very new to Python and i wanna write a script that sends a certain > >> > string to a server. The code I came up with looks like this: > >> > #!/usr/bin/python > >> > > >> > import sys > >> > import string > >> > > >> > from socket import * > >> > usage="USAGE: "+sys.argv[0]+" "; > >> > if len(sys.argv) != 3: > >> > print usage; > >> > sys.exit(0); > >> > host = sys.argv[1]; > >> > port = sys.argv[2]; > >> > buf = 1024; > >> > addr = (host,port); > >> > sock = socket(AF_INET, SOCK_STREAM); > >> > data = string.join("NovaxTest",'\n'); > >> > sock.send(data); > >> > sock.close(); > >> > and I'm calling this script like that: "./TestService.py 127.0.0.1 > >> > 1514" but when I call it I get following back: > >> > sending data to 127.0.0.1:1514 > >> > data: NovaxTest > >> > Traceback (most recent call last): > >> > File "./TestService.py", line 18, in > >> > sock.send(data); > >> > socket.error: [Errno 32] Broken pipe > >> > I understand that UNIX sends an Errno32 if the server closes the > >> > connection. But if i telnet to localhost on 1514 and send NovaxTest by > >> > hand everything works just fine. So what might be wrong here? > >> > >> You never called sock.connect(addr). Your code doesn't even use `addr` > >> at all. > > > > Oh, yeah, hOOps :$ > > > > > Hm weird now I get something like: > > Traceback (most recent call last): > > File "./TestService.py", line 14, in > > sock.connect((host,port)) > > File "", line 1, in connect > > TypeError: an integer is required > > > > > What does that mean? :( > > You never converted `port` to an int, it's still a string. port = int(sys.argv[2]) doesn't seem to help it either :( > > You might consider reading the socket module docs: > http://docs.python.org/library/socket.html mh, i browsed through it but didn't quite find what i'm looking for, do you have any more hints? Thanks, Ron From ron.eggler at gmail.com Fri May 7 13:24:10 2010 From: ron.eggler at gmail.com (cerr) Date: Fri, 7 May 2010 10:24:10 -0700 (PDT) Subject: Broken pipe References: <201005062311.23076.ron.eggler@gmail.com> Message-ID: <1bbfbae8-3eef-4268-8b86-e0326e74a5ac@a34g2000yqn.googlegroups.com> On May 7, 9:45?am, Ron Eggler wrote: > -- > Ron Eggler > Suite# 1804 > 1122 Gilford St > Vancouver, BC V6G 2P5 > Canada > (778) 230-9442 > > > > > > > On Thu, May 6, 2010 at 11:11 PM, Ron Eggler wrote: > > > On May 6, 2010 10:37:14 pm Chris Rebert wrote: > > >> On Thu, May 6, 2010 at 10:27 PM, cerr wrote: > > >> > Hi There, > > > >> > I'm very new to Python and i wanna write a script that sends a certain > > >> > string to a server. The code I came up with looks like this: > > >> > #!/usr/bin/python > > > >> > import sys > > >> > import string > > > >> > from socket import * > > >> > usage="USAGE: "+sys.argv[0]+" "; > > >> > if len(sys.argv) != 3: > > >> > ? ? ? ? ? ? ?print usage; > > >> > ? ? ? ? ? ? ?sys.exit(0); > > >> > host = sys.argv[1]; > > >> > port = sys.argv[2]; > > >> > buf = 1024; > > >> > addr = (host,port); > > >> > sock = socket(AF_INET, SOCK_STREAM); > > >> > data = string.join("NovaxTest",'\n'); > > >> > sock.send(data); > > >> > sock.close(); > > >> > and I'm calling this script like that: "./TestService.py 127.0.0.1 > > >> > 1514" but when I call it I get following back: > > >> > sending data to 127.0.0.1:1514 > > >> > data: NovaxTest > > >> > Traceback (most recent call last): > > >> > ?File "./TestService.py", line 18, in > > >> > ? ?sock.send(data); > > >> > socket.error: [Errno 32] Broken pipe > > >> > I understand that UNIX sends an Errno32 if the server closes the > > >> > connection. But if i telnet to localhost on 1514 and send NovaxTest by > > >> > hand everything works just fine. So what might be wrong here? > > > >> You never called sock.connect(addr). Your code doesn't even use `addr` > > >> at all. > > > > Oh, yeah, hOOps :$ > > > > > > > Hm weird now I get something like: > > > Traceback (most recent call last): > > > ?File "./TestService.py", line 14, in > > > ? ?sock.connect((host,port)) > > > ?File "", line 1, in connect > > > TypeError: an integer is required > > > > > > > What does that mean? :( > > > You never converted `port` to an int, it's still a string. > > port = int(sys.argv[2]) > > doesn't seem to help it either :( > > > > > You might consider reading the socket module docs: > >http://docs.python.org/library/socket.html > > mh, i browsed through it but didn't quite find what i'm looking for, do you > have any more hints? > Ah, okay, I figured that out! I actually just needed to add a \n at the end to signal the server that this is the end of the line. All good now, thanks for your help! -- Ron From python at mrabarnett.plus.com Fri May 7 14:08:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 May 2010 19:08:59 +0100 Subject: Frustration debugging serial code In-Reply-To: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> Message-ID: <4BE4573B.2020809@mrabarnett.plus.com> William R. Wing (Bill Wing) wrote: > Hello World - > I'm new to both Python and this list, but here's hoping someone can spot > my problem. > > System: Mac OS-X, 10.6.3 (Intel dual quad processor) > Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 > > The following snippet of code is designed to open a port via a KeySpan > USB-to-serial converter and communicate with an X10 power line signaling > system. Before you look at the code, let me mention that my frustration > is the it executes perfectly if i enter it line by line at the Python > prompt, and executes perfectly if I run it under the Wing IDE. It fails > silently (no errors) if I run it as a standalone script. Clearly, I'm > missing something. > What do you mean "It fails silently"? It might be unable to find the modules if you double-click on the script. You could check for that by printing a message if the import statement raises an ImportError. > TIA, > Bill Wing > > import serial, string > > port = '/dev/tty.KeySerial1' > > ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port > stat1 = ser.write('\x02') # Write "Attention" to > PowerLink > print(' Stat1 is:', stat1) > ack = ser.read(2) # Check to see if PowerLink > is ready > if ack == '\x06\r': # It returns ACK (\x06) \r > if it is > stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at > House Code B, device code 2 > print(' Stat2 is:', stat2) > stat3 = ser.close() # Close serial port > print(' Stat3 is:', stat3) > elif ack =='\x15': # PowerLink sends NAC (hex > 15) if it isn't. > print('Received NAK after first open') > else: print("Something's wrong at 1.\n") > > dummy = raw_input(' Hit any key to continue: ') > From solipsis at pitrou.net Fri May 7 14:37:25 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Fri, 7 May 2010 18:37:25 +0000 (UTC) Subject: Windows - select.select, timeout and KeyboardInterrupt References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: Le Fri, 07 May 2010 16:36:44 +0200, Giampaolo Rodol? a ?crit?: > You can easily avoid this by setting a lower timeout when calling > asyncore.loop(), like 1 second or less (for example, Twisted uses 0.001 > secs). > Actually there's no reason for asyncore to have such a high default > timeout (30 seconds). The reason for a high default timeout would be to avoid waking the CPU and do useless work too often. This is important on laptops and smaller devices, in order to conserve power. Under Unix, it's easy to have a separate fd on which you write a byte when an signal comes, and which wakes up your select() call. Under Windows, it may be more involved -- first because select() only takes sockets, not pipes. From jim.vickroy at noaa.gov Fri May 7 14:44:01 2010 From: jim.vickroy at noaa.gov (j vickroy) Date: Fri, 07 May 2010 12:44:01 -0600 Subject: unable to get Hudson to run unit tests Message-ID: Hello, I apologize if this is not the appropriate forum for a question about Hudson (http://hudson-ci.org/), but I did not know where else to ask and my web searches have not been fruitful. I'm attempting to use Hudson to run nose (http://somethingaboutorange.com/mrl/projects/nose/0.11.3/) unit tests but without success. The Hudson job configuration contains the following entry in the **Source Code Management** section: svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 which successfully retrieves the desired project code from the subversion repository. The *Build* section, of the job configuration page, contains the following entry: "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" in the *Execute Python Script* subsection. Note, the above nose command runs as expected from a command shell prompt on my computer. As an additional check, I added the following command: #!python.exe print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' in the *Execute shell* subsection of the job configuration *Build* section. The Hudson console output for this job after a *Build Now* request is: Started by user anonymous Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 At revision 3379 no change for svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build [workspace] $ python C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson6901585295620519415.py [workspace] $ python.exe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson851004747320097491.sh FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO Recording test results Test reports were found but none of them are new. Did tests run? For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml is 20 min old Finished: FAILURE which seems to indicate the unit tests were not run since nosetests.xml was generated by a previous execution of nose from a command shell. I have been unable to get this to work (after trying many permutations in the Hudson job configuration section) and would appreciate your guidance. Thanks, -- jv P.S. My system particulars are: Microsoft Windows XP Professional (Service Pack 3) Python 2.6.4 nose 0.11.3 Hudson 1.355 From scott.freemire at gmail.com Fri May 7 15:14:35 2010 From: scott.freemire at gmail.com (Scott) Date: Fri, 7 May 2010 12:14:35 -0700 (PDT) Subject: Help running Windows programs from Python Message-ID: <6acc04da-41bf-473e-a502-bfe2a9c4e9fa@r34g2000yqj.googlegroups.com> I want to write a script to automate log archiving/compressing on a Win2003 server. I have Python 2.6 installed. I am planning to use 7- zip for compression (because I have been using it manually for a while now). For now all operations will be local in the C: drive. As a total beginner I'm having trouble grasping the control of external programs. I have found these options but have not tried any yet - I would like some advice on which approach would be the most appropriate to begin with. Command Line Application Approach: os.system os.spawn* os.popen* popen2.* commands.* All of the above recommend replacing with subprocess module subprocess - latest way to do command line? pexpect module - http://sourceforge.net/projects/pexpect/, Most recent file is dated 1/5/2008 It should work on any platform that supports the standard Python pty module. (Windows?) pty - "On Windows, only sockets are supported; on Unix, all file descriptors." (gulp, ??) COM Application Approach: Per the 7-zip FAQ: Use the 7z.dll or 7za.dll - I haven't found these files yet on sf.net. comtypes 0.6.2 - has the word COM in it? pywin32 / win32com - there's that word again. And then there is this whole idea of "wrappers." Thanks, Scott From python at mrabarnett.plus.com Fri May 7 15:23:38 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 May 2010 20:23:38 +0100 Subject: Frustration debugging serial code In-Reply-To: References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> Message-ID: <4BE468BA.7090907@mrabarnett.plus.com> William R. Wing (Bill Wing) wrote: > > On May 7, 2010, at 2:08 PM, MRAB wrote: > >> William R. Wing (Bill Wing) wrote: >>> Hello World - >>> I'm new to both Python and this list, but here's hoping someone can >>> spot my problem. >>> System: Mac OS-X, 10.6.3 (Intel dual quad processor) >>> Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 >>> The following snippet of code is designed to open a port via a >>> KeySpan USB-to-serial converter and communicate with an X10 power >>> line signaling system. Before you look at the code, let me mention >>> that my frustration is the it executes perfectly if i enter it line >>> by line at the Python prompt, and executes perfectly if I run it >>> under the Wing IDE. It fails silently (no errors) if I run it as a >>> standalone script. Clearly, I'm missing something. >> What do you mean "It fails silently"? It might be unable to find the >> modules if you double-click on the script. You could check for that by >> printing a message if the import statement raises an ImportError. > > Maybe I should have been more explicit. The first line in the Python > file is: > > #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results > either way). > > and what I meant was that when I invoke it from a terminal window, it fails. > If the import were failing, wouldn't I get failures on the serial > operations? If the import fails then you wouldn't be able to create a serial object. > In particular, the ser object is exactly what it should be. If I print > it out, I get > the same value for ser in either terminal window mode or in the debugger. > > The various status print statements give exactly the expected results in > both > cases. But when invoked from the terminal window, the X10 controller > doesn't > get commands. > So you can execute: stat1 = ser.write('\x02') but the X10 controller just isn't receiving it? Is stat1 the same in both cases (ie, working and non-working)? >>> import serial, string >>> port = '/dev/tty.KeySerial1' >>> ser = serial.Serial(port, 9600, timeout=1) # Set up handle to >>> serial port >>> stat1 = ser.write('\x02') # Write "Attention" to >>> PowerLink >>> print(' Stat1 is:', stat1) ack = ser.read(2) >>> # Check to see if PowerLink is ready >>> if ack == '\x06\r': # It returns ACK (\x06) >>> \r if it is >>> stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at >>> House Code B, device code 2 >>> print(' Stat2 is:', stat2) >>> stat3 = ser.close() # Close serial port >>> print(' Stat3 is:', stat3) >>> elif ack =='\x15': # PowerLink sends NAC >>> (hex 15) if it isn't. >>> print('Received NAK after first open') >>> else: print("Something's wrong at 1.\n") >>> dummy = raw_input(' Hit any key to continue: ') >> From p.f.moore at gmail.com Fri May 7 15:25:56 2010 From: p.f.moore at gmail.com (Paul Moore) Date: Fri, 7 May 2010 20:25:56 +0100 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: On 7 May 2010 15:36, Giampaolo Rodol? wrote: > You can easily avoid this by setting a lower timeout when calling > asyncore.loop(), like 1 second or less (for example, Twisted uses > 0.001 secs). Thanks, that's what I was considering. > Actually there's no reason for asyncore to have such a high default > timeout (30 seconds). I assumed it was to avoid busy waiting. > I think this should be signaled on the bug tracker. If a longer timeout doesn't have issues with busy waiting, then I'd agree. Paul From wrw at mac.com Fri May 7 15:36:20 2010 From: wrw at mac.com (William R. Wing) Date: Fri, 07 May 2010 15:36:20 -0400 Subject: Frustration debugging serial code In-Reply-To: <4BE4573B.2020809@mrabarnett.plus.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> Message-ID: <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> On May 7, 2010, at 2:08 PM, MRAB wrote: > William R. Wing (Bill Wing) wrote: >> Hello World - >> I'm new to both Python and this list, but here's hoping someone can spot my problem. >> System: Mac OS-X, 10.6.3 (Intel dual quad processor) >> Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 >> The following snippet of code is designed to open a port via a KeySpan USB-to-serial converter and communicate with an X10 power line signaling system. Before you look at the code, let me mention that my frustration is the it executes perfectly if i enter it line by line at the Python prompt, and executes perfectly if I run it under the Wing IDE. It fails silently (no errors) if I run it as a standalone script. Clearly, I'm missing something. > What do you mean "It fails silently"? It might be unable to find the > modules if you double-click on the script. You could check for that by > printing a message if the import statement raises an ImportError. Maybe I should have been more explicit. The first line in the Python file is: #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results either way). and what I meant was that when I invoke it from a UNIX CLI window, it fails. If the import were failing, wouldn't I get failures on the serial operations? In particular, the ser object is exactly what it should be. If I print it out, I get the same value for ser from either the UNIX CLI or in the debugger, and in both cases it says "open=True" The various status print statements give exactly the same (expected) results in both cases. But when invoked from the terminal window, the X10 controller doesn't get commands. If I invoke python from the same window, and enter the script code interactively one line at a time - it works just fine. >> TIA, >> Bill Wing >> import serial, string >> port = '/dev/tty.KeySerial1' >> ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port >> stat1 = ser.write('\x02') # Write "Attention" to PowerLink >> print(' Stat1 is:', stat1) ack = ser.read(2) # Check to see if PowerLink is ready >> if ack == '\x06\r': # It returns ACK (\x06) \r if it is >> stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at House Code B, device code 2 >> print(' Stat2 is:', stat2) >> stat3 = ser.close() # Close serial port >> print(' Stat3 is:', stat3) >> elif ack =='\x15': # PowerLink sends NAC (hex 15) if it isn't. >> print('Received NAK after first open') >> else: print("Something's wrong at 1.\n") >> dummy = raw_input(' Hit any key to continue: ') > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid.invalid Fri May 7 15:40:22 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 7 May 2010 19:40:22 +0000 (UTC) Subject: Frustration debugging serial code References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> Message-ID: William R. Wing (Bill Wing) wrote: > Hello World - > I'm new to both Python and this list, but here's hoping someone can spot > my problem. > > System: Mac OS-X, 10.6.3 (Intel dual quad processor) > Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 > > The following snippet of code is designed to open a port via a KeySpan > USB-to-serial converter and communicate with an X10 power line signaling > system. Before you look at the code, let me mention that my frustration > is the it executes perfectly if i enter it line by line at the Python > prompt, and executes perfectly if I run it under the Wing IDE. It fails > silently (no errors) if I run it as a standalone script. Clearly, I'm > missing something. Well, the timing is vastly different in the two cases you cite. Have you tried adding some delays in your code? -- Grant Edwards grant.b.edwards Yow! Don't SANFORIZE me!! at gmail.com From invalid at invalid.invalid Fri May 7 15:41:41 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 7 May 2010 19:41:41 +0000 (UTC) Subject: Frustration debugging serial code References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> Message-ID: On 2010-05-07, Grant Edwards wrote: > William R. Wing (Bill Wing) wrote: >> Hello World - >> I'm new to both Python and this list, but here's hoping someone can spot >> my problem. >> >> System: Mac OS-X, 10.6.3 (Intel dual quad processor) >> Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 >> >> The following snippet of code is designed to open a port via a KeySpan >> USB-to-serial converter and communicate with an X10 power line signaling >> system. Before you look at the code, let me mention that my frustration >> is the it executes perfectly if i enter it line by line at the Python >> prompt, and executes perfectly if I run it under the Wing IDE. It fails >> silently (no errors) if I run it as a standalone script. Clearly, I'm >> missing something. > > Well, the timing is vastly different in the two cases you cite. Have > you tried adding some delays in your code? Never mind. I missed the fact that there were 3 cases. The timing in the IDE (which works) is going to be pretty much the same as when you run it stand-alone (which doesn't work). -- Grant Edwards grant.b.edwards Yow! Well, I'm INVISIBLE at AGAIN ... I might as well gmail.com pay a visit to the LADIES ROOM ... From g.rodola at gmail.com Fri May 7 15:55:15 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Fri, 7 May 2010 21:55:15 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: 2010/5/7 Antoine Pitrou : > Le Fri, 07 May 2010 16:36:44 +0200, Giampaolo Rodol? a ?crit?: >> You can easily avoid this by setting a lower timeout when calling >> asyncore.loop(), like 1 second or less (for example, Twisted uses 0.001 >> secs). >> Actually there's no reason for asyncore to have such a high default >> timeout (30 seconds). > > The reason for a high default timeout would be to avoid waking the CPU > and do useless work too often. This is important on laptops and smaller > devices, in order to conserve power. > Of course, but 30 seconds look a little bit too much to me, also because (I might be wrong here) I noticed that a smaller timeout seems to result in better performances. Plus, if scheduled callbacks are ever gonna be added to asyncore we would be forced to lower the default timeout anyway in order to have a decent reactivity. --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From python.list at tim.thechases.com Fri May 7 16:05:53 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 May 2010 15:05:53 -0500 Subject: ConfigParser.get() defaults? Message-ID: <4BE472A1.3010208@tim.thechases.com> With a normal dictionary, I can specify a default fallback value in the event the requested key isn't present: d = {} print d.get(42, 'Some default goes here') However, with the ConfigParser object, there doesn't seem to be any way to do a similar cp = ConfigParser(...) # ... print cp.get('MySection', 'MyValue', 'Some default goes here') that, in the event either "MySection" doesn't exist in the config file, or "MyValue" doesn't exist within "MySection", it simply & quietly returns my default. At the moment, I have to mimic this with try: val = cp.get('MySection', 'MyValue') except (NoSectionError, NoOptionError), e: val = 'Some default goes here' print val which is a real pain when you have multiple options, some using various combinations of get(), getboolean(), getint(), or getfloat(). Yes, I can write some cheap wrappers to do these, but it feels like something that should be built-in. I've played with the DEFAULT, but that seems to just create its own section that I have to *ask* for: cp.get('DEFAULT', 'MyValue') I've thumbed through the source to ConfigParser.py but don't see any indication that it's possible to do what I'd like short of wrapping all my cp.get*() calls in try/except blocks or creating a forked version of ConfigParser.py locally. Is there anything I'm missing, or a better workaround to this? Thanks, -tkc From mensanator at aol.com Fri May 7 16:07:01 2010 From: mensanator at aol.com (Mensanator) Date: Fri, 7 May 2010 13:07:01 -0700 (PDT) Subject: Help running Windows programs from Python References: <6acc04da-41bf-473e-a502-bfe2a9c4e9fa@r34g2000yqj.googlegroups.com> Message-ID: On May 7, 2:14?pm, Scott wrote: > I want to write a script to automate log archiving/compressing on a > Win2003 server. I have Python 2.6 installed. I am planning to use 7- > zip for compression (because I have been using it manually for a while > now). For now all operations will be local in the C: drive. > > As a total beginner I'm having trouble grasping the control of > external programs. > > I have found these options but have not tried any yet - I would like > some advice on which approach would be the most appropriate to begin > with. > > Command Line Application Approach: > os.system > os.spawn* > os.popen* > popen2.* > commands.* > All of the above recommend replacing with subprocess module > subprocess - latest way to do command line? > pexpect module -http://sourceforge.net/projects/pexpect/, Most recent > file is dated 1/5/2008 > ? ? It should work on any platform that supports the standard Python > pty ?module. (Windows?) > ? ? ? ? pty - "On Windows, only sockets are supported; on Unix, all > file descriptors." (gulp, ??) > > COM Application Approach: > Per the 7-zip FAQ: Use the 7z.dll or 7za.dll - I haven't found these > files yet on sf.net. > comtypes 0.6.2 - has the word COM in it? > pywin32 / win32com ?- there's that word again. > > And then there is this whole idea of "wrappers." > > Thanks, > Scott Here's a simple example: >>> import os >>> the_output = os.popen("dir "+"c:\\python31\\user\\*.py").readlines() >>> for i in the_output:print(i,end='') Volume in drive C has no label. Volume Serial Number is 06DE-55B4 Directory of c:\python31\user 09/08/2009 01:38 PM 689 3435.py 11/10/2009 06:43 PM 614 4697.py 03/09/2010 08:42 PM 5,922 5x.py 03/30/2010 07:51 PM 1,937 7[18] impure.py 08/28/2009 08:43 PM 1,867 bones.py 05/05/2010 07:21 PM 441 code.py 03/22/2010 04:31 PM 639 collatz_curiosity.py 09/18/2009 08:06 PM 17,125 collatz_game.py 08/20/2009 03:09 PM 406 csv_file_fix__minimal_2_all.py 11/06/2009 08:18 PM 432 digitsets.py 07/20/2009 07:03 PM 14,451 gmpy_geni_test_3.py 10/23/2009 05:35 PM 2,952 hit_target.py 03/19/2010 07:52 PM 245 how_many_random.py 04/15/2010 07:06 PM 217 issquare.py 07/31/2009 05:14 PM 1,132 itune.py 07/31/2009 04:41 PM 527 itune_stats.py 10/08/2009 08:08 PM 6,202 make_numbers.py 04/14/2010 08:00 PM 354 montyhall4.py 04/21/2010 07:46 PM 1,196 Ryan_Whited.py 03/25/2010 07:53 PM 4,318 ultimate_cycle.py 20 File(s) 61,666 bytes 0 Dir(s) 102,634,008,576 bytes free >>> From jcd at sdf.lonestar.org Fri May 7 16:12:23 2010 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 07 May 2010 16:12:23 -0400 Subject: Frustration debugging serial code In-Reply-To: <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> Message-ID: <1273263143.8440.4.camel@cliff-laptop> On Fri, 2010-05-07 at 15:36 -0400, William R. Wing wrote: > > Maybe I should have been more explicit. The first line in the Python > file is: > > > #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results > either way). > python should be lowercased when referring to the name of the executable. Unix filesystems are, of course, case sensitive. From jcd at sdf.lonestar.org Fri May 7 16:12:38 2010 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 07 May 2010 16:12:38 -0400 Subject: Frustration debugging serial code In-Reply-To: <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> Message-ID: <1273263158.8440.5.camel@cliff-laptop> On Fri, 2010-05-07 at 15:36 -0400, William R. Wing wrote: > > Maybe I should have been more explicit. The first line in the Python > file is: > > > #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results > either way). > python should be lowercased when referring to the name of the executable. Unix filesystems are, of course, case sensitive. From jim.vickroy at noaa.gov Fri May 7 16:38:34 2010 From: jim.vickroy at noaa.gov (j vickroy) Date: Fri, 07 May 2010 14:38:34 -0600 Subject: Help running Windows programs from Python In-Reply-To: <6acc04da-41bf-473e-a502-bfe2a9c4e9fa@r34g2000yqj.googlegroups.com> References: <6acc04da-41bf-473e-a502-bfe2a9c4e9fa@r34g2000yqj.googlegroups.com> Message-ID: Scott wrote: > I want to write a script to automate log archiving/compressing on a > Win2003 server. I have Python 2.6 installed. I am planning to use 7- > zip for compression (because I have been using it manually for a while > now). For now all operations will be local in the C: drive. > > As a total beginner I'm having trouble grasping the control of > external programs. > > I have found these options but have not tried any yet - I would like > some advice on which approach would be the most appropriate to begin > with. > > Command Line Application Approach: > os.system > os.spawn* > os.popen* > popen2.* > commands.* > All of the above recommend replacing with subprocess module > subprocess - latest way to do command line? > pexpect module - http://sourceforge.net/projects/pexpect/, Most recent > file is dated 1/5/2008 > It should work on any platform that supports the standard Python > pty module. (Windows?) > pty - "On Windows, only sockets are supported; on Unix, all > file descriptors." (gulp, ??) > > COM Application Approach: > Per the 7-zip FAQ: Use the 7z.dll or 7za.dll - I haven't found these > files yet on sf.net. > comtypes 0.6.2 - has the word COM in it? > pywin32 / win32com - there's that word again. > > And then there is this whole idea of "wrappers." > > Thanks, > Scott Hello Scott, I did not see what version of Python you are using (3.x?, 2.x?) so I'll answer based on Python 2.6.4 which I am using. If you already can accomplish your task with a series of commands, from a console window, my recommendation is to first read the Python documentation for os.system(...) which allows you to pass, as a parameter, any command you can type at a console window. Then, read the subprocess module documentation (particularly Section "18.1.3.3. Replacing os.system()"). Use the subprocess module Popen(...) function as a replacement for os.system(...). You may include as many calls to Popen(...), in your Python script, as needed. I do not know much about 7-zip so I can not say if the above command-line-like approach is feasible, but a quick glance at the FAQ indicates it probably is. Since you are just getting started, for simplicity, I would recommend against trying to use the 7-zip COM (http://en.wikipedia.org/wiki/Component_Object_Model) interface or the 7z.dll (which should be in the C:\Program Files\7-Zip\ folder) directly via the Python ctypes module (included in Python 2.6). HTH, -- jv From solipsis at pitrou.net Fri May 7 16:45:20 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Fri, 7 May 2010 20:45:20 +0000 (UTC) Subject: Windows - select.select, timeout and KeyboardInterrupt References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: Le Fri, 07 May 2010 21:55:15 +0200, Giampaolo Rodol? a ?crit?: > Of course, but 30 seconds look a little bit too much to me, also because > (I might be wrong here) I noticed that a smaller timeout seems to result > in better performances. That's probably bogus. > Plus, if scheduled callbacks are ever gonna be added to asyncore we > would be forced to lower the default timeout anyway in order to have a > decent reactivity. Why? From tjreedy at udel.edu Fri May 7 16:54:21 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 May 2010 16:54:21 -0400 Subject: List comprehension + lambdas - strange behaviour In-Reply-To: <84ifh5Fj5aU5@mid.individual.net> References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> <84ifh5Fj5aU5@mid.individual.net> Message-ID: On 5/7/2010 8:31 AM, Neil Cerutti wrote: > On 2010-05-07, Terry Reedy wrote: >> On 5/6/2010 3:34 PM, Artur Siekielski wrote: >>> Hello. >>> I found this strange behaviour of lambdas, closures and list >>> comprehensions: >>> >>>>>> funs = [lambda: x for x in range(5)] >>>>>> [f() for f in funs] >>> [4, 4, 4, 4, 4] >> >> You succumbed to lambda hypnosis, a common malady ;-). The >> above will not work in 3.x, which does not leak comprehension >> iteration variables. > > It functions the same in 3.1. > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> funs = [lambda: x for x in range(5)] >>>> [f() for f in funs] > [4, 4, 4, 4, 4] Ok. >>> x Traceback (most recent call last): File "", line 1, in x NameError: name 'x' is not defined #only in 3.x But because the list comp is implemented in 3.x as an anonymous function, which is then called and discarded (an implementation that I believe is not guaranteed by the language ref), the lambda expression defines a nested function which captures the (final) value of x. >>> funs[0].__closure__[0].cell_contents 4 So it works (runs without exception), but somewhat accidentally and for a different reason than in 2.x, where 'x' is 4 at the global level. Terry Jan Reedy From aahz at pythoncraft.com Fri May 7 17:28:05 2010 From: aahz at pythoncraft.com (Aahz) Date: 7 May 2010 14:28:05 -0700 Subject: idiomatic way to collect and report multiple exceptions? References: Message-ID: In article , Ben Cohen wrote: > >eg -- I'd like to do something like this: > >errors = [] >for item in data: > try: > process(item) > except ValidationError as e: > errors.append(e) >raise MultipleValidationErrors(*errors) First of all, please DO NOT post code with TABs in it. In fact, you shouldn't even be writing code with TABs -- TAB characters are obsolete for new Python code. I would write your code this way: errors = [] for item in data: try: process(item) except ValidationError as e: errors.append(str(e)) if errors: raise MultipleValidationErrors(errors) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From db3l.net at gmail.com Fri May 7 17:41:16 2010 From: db3l.net at gmail.com (David Bolen) Date: Fri, 07 May 2010 17:41:16 -0400 Subject: Extract a bordered, skewed rectangle from an image References: Message-ID: "Paul Hemans" writes: > I am wondering whether there are any people here that have experience with > openCV and Python. If so, could you either give me some pointers on how to > approach this, or if you feel so inclined, bid on the project. There are 2 > problems: Can't offer actual services, but I've done image tracking and object identification in Python with OpenCV so can suggest some approaches. You might also try the OpenCV mailing list, though it's sometimes varies wildly in terms of S/N ratio. And for OpenCV specifically, I definitely recommend the book "Learning OpenCV" by O'Reilly. It's really hard to grasp the concepts and applications of the raw OpenCV calls from the API documentation, and I found the book (albeit not cheap) helped me out tremendously and was well worth it. I'll flip the two questions since the second is quicker to answer. > How to do this through Python into openCV? I am a newbie to Python, not > strong in Maths and ignorant of the usage of openCV. After trying a few wrappers, the bulk of my experience is with the ctypes-opencv wrapper and OpenCV 1.x (either 1.0 or 1.1pre). Things change a lot with the recent 2.x (which needs C++ wrappers), and I'm not sure the various wrappers are as stable yet. So if you don't have a hard requirement for 2.x, I might suggest at least starting with 1.x and ctypes-opencv, which is very robust, though I'm a little biased as I've contributed code to the wrapper. > How do I get openCV to ignore the contents of the label and just focus on > the border? There's likely no single answer, since multiple mechanisms for identifying features in an image exist, and you can also derive additional heuristics based on your own knowledge of the domain space (your own images). Without knowing exactly what the border design to make it easy to detect is, it's hard to say anything definitive. But in broad strokes, you'll often: 1. Normalize the image in some way. This can be to adjust for brightness from various scans to make later processing more consistent, or to switch spaces (to make color matching more effective) or even to remove color altogether if it just complicates matters. You may also mask of entire portions of the image if you have information that says they can't possibly be part of what you are looking for. 2. Attempt to remove noise. Even when portions of an image looks like a solid color, at the pixel level there can be may different variations in pixel values. Operations such as blurring or smoothing help to average out those values and simplify matching entire regions. 3. Attempt to identify the regions or features of interest. Here's where a ton of algorithms may apply due to your needs, but the simplest form to start with is basic color matching. For edge detection (like of your label) convolutions (such as gradient detection) might also ideal. 4. Process identified regions to attempt to clean them up, if possible weakening regions likely to be extraneous, and strengthening those more likely to be correct. Morphology operations are one class of processing likely to help here. 5. Select among features (if more than one) to identify the best match, using any knowledge you may have that can be used to rank them (e.g., size, position in image, etc...) My own processing is ball tracking in motion video, so I have some additional data in terms of adjacent frames that helps me remove static background information and minimize the regions under consideration for step 3, but a single image probably won't have that. But given that you have scanned documents, there may be other simplifying rules you can use, like eliminating anything too white or too black (depending on label color). My own flow works like: 1. Normalize each frame 1. Blur the frame (cvSmooth with CV_BLUR, 5x5 matrix). This smooths out the pixel values, improving the color conversion. 2. Balance brightess (in RGB space). I ended up just offsetting the image a fixed (x,x,x) value to maximize the RGB values. Found it worked better doing it in RGB before Lab conversion. 3. Convert the image to the "Lab" color space. I used Lab because the conversion process was fastest, but when frame rate isn't critical, HLS is likely better since hue/saturation are completely separate from lightness which makes for easier color matching. 2. Identify uninteresting regions in the current frame This may not apply to you, but here is where I mask out static information from prior background frames, based on difference calculations with the current frame, or very dark areas that I knew couldn't include what I was interested in. In your case, for example, if you know the label is going to show up fairly saturated (say it's a solid red or something), you could probably eliminate everything that is below a certain saturation level. Or if they are black and white documents, but the label has a color, it might be very easy to filter out everything but the label. If you're lucky, some simple heuristics applied here might have the net effect of masking the majority of your document image away, leaving primarily the label. 3. Color matching 1. Mask off regions of the image not falling within a specific Lab pixel range, sufficient to encompass my object under a variety of lighting/camera conditions. I typically use cvInRangeS to set the mask bits for pixels within the range. 2. Perform an erosion/dilation process - cvMorphologyEx against the mask as CV_MOP_CLOSE. What this does is apply an erosion followed by a dilation. The erosion removes very small features (likely unnecessary matches) while the dilation combines nearby features with each other. The net effect is to strengthen larger matched areas (and help them become contiguous) while removing tiny features. Note in my case I was looking for a relatively solid color ball (it had gaps since it was a whiffle ball), so if, for example, your label is alternating colors, or dashed lines or something like that it might not work as well. There are more complicated algorithms that can match more elaborate patterns, sometimes with initial training on target images. 4. Object selection 1. Locate all top level contours of any remaining solid areas in the mask (cvFindContours). This will identify connected areas in the mask, so in your case, ideally one of the located contours would be the label edge. This does assume that your feature identification in the prior step is likely to create contiguous areas. Even just a few pixels of gaps will net a non-closed contour which is harder to work with, though the morphology operation will sometimes close those gaps. 2. Evaluate "best" contour when multiple choices exist. Very small areas are eliminated, and remaining areas are evaluated for average Lab value distance from a target point (somewhat arbitrarily chosen at this point to represent the "ideal" ball). The nearest (in color distance) contour is picked, except in the case of two "close" contours where the further contour can win if it is at least 4x (arbitrarily chosen) as large. In your case, for example, any contours located within the label itself would necessarily be smaller than the label, so you could probably just pick largest. Also, when calling cvFindContours you can prevent it from finding "interior" contours. 3. Compute and return a minimum bounding circle (center, radius) for the selected contour. In your case, you'd likely just use the contour itself - you can use the contour (with 'n' line segments) as is, or convert into an approximate polygon. The nice thing about Python with OpenCV is the interactive experimentation you can do right in the interpreter. Open a highgui window, load in your image and then experiment. After performing various processes, just quickly show the new image in the existing or a new window. You can keep several windows up to date when you test process an image through several transforms to see the results. Hope this at least gives you some thoughts as to how to proceed. -- David From joncle at googlemail.com Fri May 7 17:46:26 2010 From: joncle at googlemail.com (Jon Clements) Date: Fri, 7 May 2010 14:46:26 -0700 (PDT) Subject: ConfigParser.get() defaults? References: Message-ID: <1aa30045-be87-4dba-88c5-37ba8e4c94fd@e1g2000yqe.googlegroups.com> On 7 May, 21:05, Tim Chase wrote: > With a normal dictionary, I can specify a default fallback value > in the event the requested key isn't present: > > ? ?d = {} > ? ?print d.get(42, 'Some default goes here') > > However, with the ConfigParser object, there doesn't seem to be > any way to do a similar > > ? ?cp = ConfigParser(...) > ? ?# ... > ? ?print cp.get('MySection', 'MyValue', 'Some default goes here') > > that, in the event either "MySection" doesn't exist in the config > file, or "MyValue" doesn't exist within "MySection", it simply & > quietly returns my default. ?At the moment, I have to mimic this with > > ? ?try: > ? ? ?val = cp.get('MySection', 'MyValue') > ? ?except (NoSectionError, NoOptionError), e: > ? ? ?val = 'Some default goes here' > ? ?print val > > which is a real pain when you have multiple options, some using > various combinations of get(), getboolean(), getint(), or > getfloat(). ?Yes, I can write some cheap wrappers to do these, > but it feels like something that should be built-in. > > I've played with the DEFAULT, but that seems to just create its > own section that I have to *ask* for: > > ? ?cp.get('DEFAULT', 'MyValue') > > I've thumbed through the source to ConfigParser.py but don't see > any indication that it's possible to do what I'd like short of > wrapping all my cp.get*() calls in try/except blocks or creating > a forked version of ConfigParser.py locally. ?Is there anything > I'm missing, or a better workaround to this? > > Thanks, > > -tkc Not convinced about this, but a quick "work-around" would be something like: def get_config(config, section, option, ctype=str, default=None): if default is None: ret = config.get(section, option) else: confdict = config.__dict__.get('_sections') ret = confdict.get(section).get(option, default) return ctype(ret) That should cover most exceptions and the get* functions..., just provide your own factory function to post-parse it... Of course, I'm probably missing something as usual... Anyway, Cheers, Jon. From bryanjugglercryptographer at yahoo.com Fri May 7 17:51:13 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Fri, 7 May 2010 14:51:13 -0700 (PDT) Subject: Fast Efficient way to transfer an object to another list References: Message-ID: <69b59d77-3f22-4f57-8f92-63e674da1fd8@a39g2000prb.googlegroups.com> Gabriel Genellina wrote: > I'd do that in two steps: > > def transfer_stock(stock_code, old_list, new_list): > ? ?# find the indexes to transfer > ? ?indexes = [i for i,stock in enumerate(old_list) > ? ? ? ? ? ? ? if stock.code==stock_code] > ? ?# actually transfer them > ? ?for index in reversed(indexes): > ? ? ?stock = old_list[index] > ? ? ?new_list.append(stock) > ? ? ?del old_list[index] > ? ?# I would not return anything The first step -- finding the items -- looks great. The step of adding items to new_list is just a bit squirly in that it reverse the order they had in old_list. The last step -- deleting them from old_list -- is a sluggish order n**2 run-time; it can be done in order n. (That's worst-case; your solution is linear time if either very few elements get transferred or very few do not get transferred.) Inspired by your use of list comprehension, and noting the simplicity of the condition for transferring an item, I suggest the following compact, order-preserving, linear-time solution: def transfer_stock(stock_code, old_list, new_list): new_list.extend(s for s in old_list if s.code==stock_code) old_list[:] = [s for s in old_list if s.code!=stock_code] # # Even obviously-correct code deserves testing: # from random import choice class Blurf: def __init__(self, code): self.code = code for nitems in range(10): for _ in range(17): nl_prefix = choice(range(13)) new_list = [Blurf(3) for _ in range(nl_prefix)] old_list = [Blurf(choice([3, 9])) for _ in range(nitems)] nitems = len(new_list) + len(old_list) original_new_list = new_list[:] original_old_list = old_list[:] transfer_stock(3, old_list, new_list) assert len(old_list) + len(new_list) == nitems for n in new_list: assert n.code == 3 assert n in original_new_list or n in original_old_list source = original_new_list + original_old_list assert new_list == [s for s in source if s in new_list] for n in old_list: assert n.code != 3 assert n in original_new_list or n in original_old_list assert old_list == [s for s in original_old_list if s in old_list] -- --Bryan From ben+python at benfinney.id.au Fri May 7 18:33:15 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 08 May 2010 08:33:15 +1000 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: <8739y3fil0.fsf@benfinney.id.au> Patrick Maupin writes: > On May 6, 6:56?pm, Ben Finney wrote: > > Er, no. Anyone who thinks that a copyleft license ?forces? anyone to > > do anything is mistaken about copyright law > > Perhaps you feel "forces" is too loaded of a word. There is no > question, however, that a copyright license can require that if you do > "X" with some code, you must also do "Y". No. A free software license doesn't require anything. It permits the recipient to do things otherwise prohibited. Copyright law taketh, and the license giveth as an exception to the law. That is: it is copyright law that forces the recipient to abstain from a broad range of actions. A free software license grants exceptions, explicitly allowing specific actions to be performed. > There is also no question that the GPL uses this capability in > copyright law to require anybody who distributes a derivative work to > provide the source. Thus, "forced to contribute back any changes" is > definitely what happens once the decision is made to distribute said > changes in object form. You might as well say that a restaurant ?forces? patrons to pay for their meal. They don't; it's merely a proviso for performing the act of eating the food. Since no-one is forcing anyone to take any of the actions permitted in the license, and since those actions would not otherwise be permitted under copyright law, it's both false and misleading to refer to them as ?forced?. -- \ ?We are stuck with technology when what we really want is just | `\ stuff that works.? ?Douglas Adams | _o__) | Ben Finney From pmaupin at gmail.com Fri May 7 19:27:17 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 7 May 2010 16:27:17 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> Message-ID: On May 7, 5:33?pm, Ben Finney wrote: > Patrick Maupin writes: > > On May 6, 6:56?pm, Ben Finney wrote: > > > Er, no. Anyone who thinks that a copyleft license ?forces? anyone to > > > do anything is mistaken about copyright law > > > Perhaps you feel "forces" is too loaded of a word. There is no > > question, however, that a copyright license can require that if you do > > "X" with some code, you must also do "Y". > > No. A free software license doesn't require anything. It permits the > recipient to do things otherwise prohibited. Copyright law taketh, and > the license giveth as an exception to the law. Finely parsed semantics with a meaningless difference when applied to what I said in the context of comparing GPL vs. permissive licenses. > That is: it is copyright law that forces the recipient to abstain from a > broad range of actions. A free software license grants exceptions, > explicitly allowing specific actions to be performed. Yes, and as I said, the exceptions are not as encompassing, and come with more restrictions, when using the GPL vs. using a permissive license. > > There is also no question that the GPL uses this capability in > > copyright law to require anybody who distributes a derivative work to > > provide the source. Thus, "forced to contribute back any changes" is > > definitely what happens once the decision is made to distribute said > > changes in object form. > > You might as well say that a restaurant ?forces? patrons to pay for > their meal. They don't; it's merely a proviso for performing the act of > eating the food. I certainly *would* say that. Try eating at a restaurant with a halfway watchful staff near a police station and see if you can get away without payment. Same thing with buying groceries or dry goods. The restaurants and the stores, with the full weight of the government, force you to do certain things if you partake of their wares. So do do software authors via their licenses, which, as you correctly point out, derive their power from the fact that your legal rights may be very limited absent a valid license to a piece of software. On the odd occasion that a restaurant or a store offers you something for "free" (with no asterisks or fine print) they really mean it -- you can take it home and do what you want with it, with no force applied. (Don't start on the whole libre vs. gratis thing -- as far as I'm concerned, neither "free as in beer" software nor GPLed software is as free as the occasional free meal or trinket I get, which is much more akin to "public domain" in software.) > Since no-one is forcing anyone to take any of the actions permitted in > the license, and since those actions would not otherwise be permitted > under copyright law, it's both false and misleading to refer to them as > ?forced?. Again, the force is applied once you choose to do a particular thing with the software -- is is really that hard to understand that concept? Even the permissive licenses force you to retain the copyright notice on the source, but other than that, they don't try to exert any kind of control over derivative works. By the way, in selectively quoting from my email, you conveniently neglected to address the significant issue of Guido et al apparently disrespecting their users by "placing a low value on their freedom". You may think that "force" has been misused here; I happen to think that you are (and with a lot of other company, no doubt) misusing the word "freedom" to mean only those *particular* freedoms that *you* deem appropriate, and trying to paint others who disagree with your priorities as somehow immoral. Yet when good examples of these apparently immoral people and their software are given, somehow the conversation is always directed back away from this issue. Personally, I usually like to give my customers (paid or unpaid) the ability to use the software as they see fit. It's basically a gift; although I force them to include my copyright notice on subsequent source copies, I don't expect anything else in return, either directly or indirectly. I certainly don't attempt to control the licensing of any software they write that happens to use my software; I would view that as an attempted abrogation of their freedom. But this just gets back to the ancient philosophical question of whether a man is really free if he is not allowed to sell himself into slavery. I would argue that he is not; obviously you and Stallman believe that the man is not free unless someone forces him to remain free by keeping him from selling himself. Regards, Pat From ben+python at benfinney.id.au Fri May 7 19:44:06 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 08 May 2010 09:44:06 +1000 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> Message-ID: <87tyqje0qh.fsf@benfinney.id.au> Patrick Maupin writes: > On May 7, 5:33?pm, Ben Finney wrote: > > Since no-one is forcing anyone to take any of the actions permitted > > in the license, and since those actions would not otherwise be > > permitted under copyright law, it's both false and misleading to > > refer to them as ?forced?. > > Again, the force is applied once you choose to do a particular thing > with the software And again, that would be the case with or without the specific free software license, so it's false and misleading to say the license forces anything. The actions that are prohibited are prohibited by copyright law, not by the license. I think we're done here. -- \ ?Members of the general public commonly find copyright rules | `\ implausible, and simply disbelieve them.? ?Jessica Litman, | _o__) _Digital Copyright_ | Ben Finney From steve at REMOVE-THIS-cybersource.com.au Fri May 7 20:56:48 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 00:56:48 GMT Subject: ConfigParser.get() defaults? References: Message-ID: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> On Fri, 07 May 2010 15:05:53 -0500, Tim Chase wrote: > With a normal dictionary, I can specify a default fallback value in the > event the requested key isn't present: [...] > However, with the ConfigParser object, there doesn't seem to be any way > to do a similar [...] Sounds like a nice feature to have. When you submit a patch (*grin*), please make sure the caller can specify what to do on missing section and missing option independently. > I've thumbed through the source to ConfigParser.py but don't see any > indication that it's possible to do what I'd like short of wrapping all > my cp.get*() calls in try/except blocks or creating a forked version of > ConfigParser.py locally. Is there anything I'm missing, or a better > workaround to this? Don't fork the source code, that's ridiculously overkill. Subclass ConfigParser and add the required functionality. -- Steven From ncohen at ucsd.edu Fri May 7 21:06:43 2010 From: ncohen at ucsd.edu (Ben Cohen) Date: Fri, 7 May 2010 19:06:43 -0600 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> Message-ID: <4D388C82-9DE8-43C3-89D8-F2C72623338E@ucsd.edu> Many thanks for the excellent example!! You rock! Ben On May 6, 2010, at 10:56 PM, Chris Rebert wrote: > On Thu, May 6, 2010 at 8:50 PM, Ben Cohen wrote: >> Is there a pythonic way to collect and display multiple exceptions at the same time? >> >> For example let's say you're trying to validate the elements of a list and you'd like to validate as many of the elements as possible in one run and still report exception's raised while validating a failed element. >> >> eg -- I'd like to do something like this: >> >> errors = [] >> for item in data: >> try: >> process(item) >> except ValidationError as e: >> errors.append(e) >> raise MultipleValidationErrors(*errors) >> >> where if the raised MultipleValidationErrors exception goes uncaught the interpreter will print a nice traceback that includes the tracebacks of each raised ValidationError. But I don't know how MultipleValidationErrors should be written ... > > import sys, traceback > > def _traceback_for(exc_info): > return ''.join(traceback.format_exception(*exc_info)) > > # StandardError can obviously be replaced with > # whatever exception superclass you want. > class MultipleValidationErrors(StandardError): > def __init__(self, errors=None): > self.errors = errors or [] > > def __str__(self): > tracebacks = "\n\n".join(_traceback_for(exc_info) for exc_info in \ > self.errors) > parts=("See the following exception tracebacks:", "="*78, tracebacks) > msg = '\n'.join(parts) > return msg > > def capture_current_exception(self): > self.errors.append(sys.exc_info()) > > def do_raise(self): > """Raises itself if it contains any errors""" > if self.errors: > raise self > > > #Example usage: > multiple_err = MultipleValidationErrors() > for c in "hello": > try: > int(c) # obviously fails > except ValueError: # whatever error type you care about > multiple_err.capture_current_exception() > multiple_err.do_raise() > > > Output from example: > Traceback (most recent call last): > File "tmp.py", line 35, in > multiple_err.do_raise() > File "tmp.py", line 25, in do_raise > raise self > __main__.MultipleValidationErrors: See the following exception tracebacks: > ============================================================================== > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'h' > > > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'e' > > > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'l' > > > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'l' > > > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'o' > > > Cheers, > Chris > -- > Go Tritons! > http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Fri May 7 21:11:59 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 01:11:59 GMT Subject: idiomatic way to collect and report multiple exceptions? References: Message-ID: <4be4ba5e$0$27798$c3e8da3@news.astraweb.com> On Fri, 07 May 2010 14:28:05 -0700, Aahz wrote: > In article , Ben > Cohen wrote: >> >>eg -- I'd like to do something like this: >> >>errors = [] >>for item in data: >> try: >> process(item) >> except ValidationError as e: >> errors.append(e) >>raise MultipleValidationErrors(*errors) > > First of all, please DO NOT post code with TABs in it. In fact, you > shouldn't even be writing code with TABs -- TAB characters are obsolete > for new Python code. I don't believe this is correct. Do you have a source for this? Four spaces are recommended by PEP 8, and are compulsory for patches to the standard library, but Python continues to accept either multi-space indents or tabs, and in your own personal code you can use whichever you like. The documentation for Python 3 continues to state that either spaces or tabs will be accepted (and warns against mixing them): http://docs.python.org/py3k/reference/lexical_analysis.html#indentation According to my tests, Python 3.1 continues to accept both spaces and tabs. Tabs on their own are accepted without warning: [steve at sylar ~]$ cat tabs.py def f(x): # This function uses tabs for indents. return x print(f("tabs")) [steve at sylar ~]$ python3.1 tabs.py tabs Even mixing tabs and spaces in the one indent is allowed: [steve at sylar ~]$ cat mixed.py def f(x): # This uses mixed tabs and spaces. return x print(f("mixed tabs and spaces")) [steve at sylar ~]$ python3.1 mixed.py mixed tabs and spaces But using both tab-based indents and space-based indents is not: [steve at sylar ~]$ cat both.py def f(x): # This uses both tabs and spaces. pass # space-indent return x # tab-indent print(f("both tabs and spaces")) [steve at sylar ~]$ python3.1 both.py File "both.py", line 4 return x # tab-indent ^ TabError: inconsistent use of tabs and spaces in indentation -- Steven From crebert at ucsd.edu Fri May 7 21:24:24 2010 From: crebert at ucsd.edu (Chris Rebert) Date: Fri, 7 May 2010 18:24:24 -0700 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: <4D388C82-9DE8-43C3-89D8-F2C72623338E@ucsd.edu> References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> <4D388C82-9DE8-43C3-89D8-F2C72623338E@ucsd.edu> Message-ID: > On May 6, 2010, at 10:56 PM, Chris Rebert wrote: >> On Thu, May 6, 2010 at 8:50 PM, Ben Cohen wrote: >>> Is there a pythonic way to collect and display multiple exceptions at the same time? >>> >>> For example let's say you're trying to validate the elements of a list and you'd like to validate as many of the elements as possible in one run and still report exception's raised while validating a failed element. >>> >>> eg -- I'd like to do something like this: >>> >>> errors = [] >>> for item in data: >>> ? ? ? ?try: >>> ? ? ? ? ? ? ? ?process(item) >>> ? ? ? ?except ValidationError as e: >>> ? ? ? ? ? ? ? ?errors.append(e) >>> raise MultipleValidationErrors(*errors) >>> >>> where if the raised MultipleValidationErrors exception goes uncaught the interpreter will print a nice traceback that includes the tracebacks of each raised ValidationError. ?But I don't know how MultipleValidationErrors should be written ... On Fri, May 7, 2010 at 6:06 PM, Ben Cohen wrote: > Many thanks for the excellent example!! You rock! > > Ben However, I do agree with Steven that this approach to error handling is unusual. But I assume you have your reasons for wanting to do it this way. Cheers, Chris -- Python + Bioinformatics = Win http://blog.rebertia.com From wrw at mac.com Fri May 7 21:33:43 2010 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Fri, 07 May 2010 21:33:43 -0400 Subject: Frustration debugging serial code In-Reply-To: <4BE468BA.7090907@mrabarnett.plus.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <4BE468BA.7090907@mrabarnett.plus.com> Message-ID: See comments in-line. On May 7, 2010, at 3:23 PM, MRAB wrote: > William R. Wing (Bill Wing) wrote: >> On May 7, 2010, at 2:08 PM, MRAB wrote: >>> William R. Wing (Bill Wing) wrote: >>>> Hello World - >>>> I'm new to both Python and this list, but here's hoping someone can spot my problem. >>>> System: Mac OS-X, 10.6.3 (Intel dual quad processor) >>>> Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 >>>> The following snippet of code is designed to open a port via a KeySpan USB-to-serial converter and communicate with an X10 power line signaling system. Before you look at the code, let me mention that my frustration is the it executes perfectly if i enter it line by line at the Python prompt, and executes perfectly if I run it under the Wing IDE. It fails silently (no errors) if I run it as a standalone script. Clearly, I'm missing something. >>> What do you mean "It fails silently"? It might be unable to find the >>> modules if you double-click on the script. You could check for that by >>> printing a message if the import statement raises an ImportError. >> Maybe I should have been more explicit. The first line in the Python file is: >> #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results either way). >> and what I meant was that when I invoke it from a terminal window, it fails. >> If the import were failing, wouldn't I get failures on the serial operations? > > If the import fails then you wouldn't be able to create a serial object. Which I can, in all three cases. > >> In particular, the ser object is exactly what it should be. If I print it out, I get >> the same value for ser in either terminal window mode or in the debugger. >> The various status print statements give exactly the expected results in both >> cases. But when invoked from the terminal window, the X10 controller doesn't >> get commands. > So you can execute: > > stat1 = ser.write('\x02') > > but the X10 controller just isn't receiving it? Is stat1 the same in > both cases (ie, working and non-working)? The X10 controller not only receives it, it echos the response (\x06\r) that means it saw it and is ready for the next command in all three cases. The serial write that immediately follows, in which five hex bytes get sent to it is the one which succeeds interactively and in the IDE, and fails when executed as a bash script. > >>>> import serial, string >>>> port = '/dev/tty.KeySerial1' >>>> ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port >>>> stat1 = ser.write('\x02') # Write "Attention" to PowerLink >>>> print(' Stat1 is:', stat1) ack = ser.read(2) # Check to see if PowerLink is ready >>>> if ack == '\x06\r': # It returns ACK (\x06) \r if it is >>>> stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at House Code B, device code 2 >>>> print(' Stat2 is:', stat2) >>>> stat3 = ser.close() # Close serial port >>>> print(' Stat3 is:', stat3) >>>> elif ack =='\x15': # PowerLink sends NAC (hex 15) if it isn't. >>>> print('Received NAK after first open') >>>> else: print("Something's wrong at 1.\n") >>>> dummy = raw_input(' Hit any key to continue: ') >>> > -- > http://mail.python.org/mailman/listinfo/python-list From gallium.arsenide at gmail.com Fri May 7 21:37:57 2010 From: gallium.arsenide at gmail.com (John Yeung) Date: Fri, 7 May 2010 18:37:57 -0700 (PDT) Subject: Help running Windows programs from Python References: <6acc04da-41bf-473e-a502-bfe2a9c4e9fa@r34g2000yqj.googlegroups.com> Message-ID: <000675ee-0f6c-46d4-822c-f1ea8f4627cb@40g2000vbr.googlegroups.com> On May 7, 3:14?pm, Scott wrote: > I want to write a script to automate log archiving/compressing on a > Win2003 server. I have Python 2.6 installed. I am planning to use 7- > zip for compression (because I have been using it manually for a while > now). For now all operations will be local in the C: drive. For your purposes, I personally think os.system() is enough of an interface to 7-Zip and any other basic operating system commands you might need for your task. It's what I use myself to do batch archiving with 7-Zip. I think you will find everything you need within the os module (to get the names of files and such), and of course Python's built-in string methods. Especially since you say you are a beginner, my recommendation is to keep it simple; and to me, using only the os module is the simplest way to go. (That is why I went with it, after all. ;) Also, don't be afraid to try stuff. I can understand not wanting to mess stuff up. Well, create your own test directory and dummy files to practice on first, and just have at it. John From wrw at mac.com Fri May 7 21:38:33 2010 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Fri, 07 May 2010 21:38:33 -0400 Subject: Frustration debugging serial code In-Reply-To: <1273263143.8440.4.camel@cliff-laptop> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> <1273263143.8440.4.camel@cliff-laptop> Message-ID: <56733D2A-F1F1-4DA3-B48E-C8A6C1E46C36@mac.com> On May 7, 2010, at 4:12 PM, J. Cliff Dyer wrote: > On Fri, 2010-05-07 at 15:36 -0400, William R. Wing wrote: > >> >> Maybe I should have been more explicit. The first line in the Python >> file is: >> >> >> #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results >> either way). >> > > python should be lowercased when referring to the name of the > executable. Unix filesystems are, of course, case sensitive. > Cliff, True, although on a Mac the case is ignored. But you're right, best practice would make it lower case. However, I've tried it both ways with the same results. But thanks. Still frustrated, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Fri May 7 21:46:47 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 May 2010 20:46:47 -0500 Subject: ConfigParser.get() defaults? In-Reply-To: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> References: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4BE4C287.9070505@tim.thechases.com> On 05/07/2010 07:56 PM, Steven D'Aprano wrote: > On Fri, 07 May 2010 15:05:53 -0500, Tim Chase wrote: >> With a normal dictionary, I can specify a default fallback value in the >> event the requested key isn't present: > [...] >> However, with the ConfigParser object, there doesn't seem to be any way >> to do a similar > > Sounds like a nice feature to have. When you submit a patch (*grin*), I'm game to create and provide a patch, though I've had no success in the past trying to push tweaks into the Python Core (adding a subclass of optparse.HelpFormatter that respects newlines for text-wrapping). But if there's a straightforward way to do this, I'd love to patch the file and submit the deltas. I just need to know - what sort of patch (unified diff, context diff, ed) - against which version? I'm currently running the 2.5 that Debian Testing defaults to, though I have 2.6 available through my repository. - any tests needed/expected? run how? internal as an "if __name__ == '__main__'" block, or an external test suite? - where (or to whom) to I submit the patch (and possibly tests) I asked these questions about my optparse patch and never heard anything back (it was against 2.4 so I'm sure optparse has changed enough to render my past patches somewhat defunct) > please make sure the caller can specify what to do on missing section and > missing option independently. Could you detail what you envision here? For my use case, it's that the option doesn't exist, whether because there's no section, or there's a section but no option. Either way, something failed and I want a default value back. I don't have a mental model of what you expect in the "section exists but no option" that would behave differently from the "section doesn't exist" case. Do you also have suggestions for how it should interact with the weird [DEFAULT] section oddities (that don't really seem to default the way I expect them to)? Perhaps the two interrelate? >> I've thumbed through the source to ConfigParser.py but don't see any >> indication that it's possible to do what I'd like short of wrapping all >> my cp.get*() calls in try/except blocks or creating a forked version of >> ConfigParser.py locally. Is there anything I'm missing, or a better >> workaround to this? > > Don't fork the source code, that's ridiculously overkill. Subclass > ConfigParser and add the required functionality. Sorry for such loaded terms -- my "forking" suggestion wasn't intended to be Python, the Tim Version(tm), but rather, "copy the ConfigParser.py into my project directory, make the edits I need/want, and have it available to my project" (something similar to what I did for one of my projects copying in the python2.6 zipfile.py to my python2.4 code-base to supersede the standard 2.4 library's zipfile.py). Ideally, I'd tweak the base RawConfigParser class (and its subclasses if needed) rather than subclass, as it's functionality that would be useful in all cases (Raw, regular, and Safe). But yes, doing this would allow me to proffer the above-suggested patches. Thanks for your input, -tkc From vincent at vincentdavis.net Fri May 7 22:04:41 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Fri, 7 May 2010 20:04:41 -0600 Subject: is there a functional assert(x==y, 'error msg') Message-ID: Is there a functional assert(x==y, 'error msg') ? I can only find the assert that is used like; assert x==y, 'error msg' *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Fri May 7 22:18:56 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 08 May 2010 03:18:56 +0100 Subject: Frustration debugging serial code In-Reply-To: References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <4BE468BA.7090907@mrabarnett.plus.com> Message-ID: <4BE4CA10.4010608@mrabarnett.plus.com> William R. Wing (Bill Wing) wrote: > See comments in-line. > > On May 7, 2010, at 3:23 PM, MRAB wrote: > >> William R. Wing (Bill Wing) wrote: >>> On May 7, 2010, at 2:08 PM, MRAB wrote: >>>> William R. Wing (Bill Wing) wrote: >>>>> Hello World - >>>>> I'm new to both Python and this list, but here's hoping someone can spot my problem. >>>>> System: Mac OS-X, 10.6.3 (Intel dual quad processor) >>>>> Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 >>>>> The following snippet of code is designed to open a port via a KeySpan USB-to-serial converter and communicate with an X10 power line signaling system. Before you look at the code, let me mention that my frustration is the it executes perfectly if i enter it line by line at the Python prompt, and executes perfectly if I run it under the Wing IDE. It fails silently (no errors) if I run it as a standalone script. Clearly, I'm missing something. >>>> What do you mean "It fails silently"? It might be unable to find the >>>> modules if you double-click on the script. You could check for that by >>>> printing a message if the import statement raises an ImportError. >>> Maybe I should have been more explicit. The first line in the Python file is: >>> #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results either way). >>> and what I meant was that when I invoke it from a terminal window, it fails. >>> If the import were failing, wouldn't I get failures on the serial operations? >> If the import fails then you wouldn't be able to create a serial object. > > Which I can, in all three cases. > >>> In particular, the ser object is exactly what it should be. If I print it out, I get >>> the same value for ser in either terminal window mode or in the debugger. >>> The various status print statements give exactly the expected results in both >>> cases. But when invoked from the terminal window, the X10 controller doesn't >>> get commands. >> So you can execute: >> >> stat1 = ser.write('\x02') >> >> but the X10 controller just isn't receiving it? Is stat1 the same in >> both cases (ie, working and non-working)? > > The X10 controller not only receives it, it echos the response (\x06\r) that means > it saw it and is ready for the next command in all three cases. The serial write > that immediately follows, in which five hex bytes get sent to it is the one which > succeeds interactively and in the IDE, and fails when executed as a bash script. > Does the ' Hit any key to continue: ' message appear when run as a bash script? I'm just wondering whether it's that when run from the Python prompt or IDE the 'ser' object continues to exist for a while, but when run as a bash script Python is terminating before all of the bytes have been sent. Of course, I'd expect 'ser.close()' to return only when there's nothing left to be sent, or, at least, for there to be enough time while it's waiting for you to press ENTER. >>>>> import serial, string >>>>> port = '/dev/tty.KeySerial1' >>>>> ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port >>>>> stat1 = ser.write('\x02') # Write "Attention" to PowerLink >>>>> print(' Stat1 is:', stat1) ack = ser.read(2) # Check to see if PowerLink is ready >>>>> if ack == '\x06\r': # It returns ACK (\x06) \r if it is >>>>> stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at House Code B, device code 2 >>>>> print(' Stat2 is:', stat2) >>>>> stat3 = ser.close() # Close serial port >>>>> print(' Stat3 is:', stat3) >>>>> elif ack =='\x15': # PowerLink sends NAC (hex 15) if it isn't. >>>>> print('Received NAK after first open') >>>>> else: print("Something's wrong at 1.\n") >>>>> dummy = raw_input(' Hit any key to continue: ') From prologic at shortcircuit.net.au Fri May 7 22:38:25 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 8 May 2010 12:38:25 +1000 Subject: is there a functional assert(x==y, 'error msg') In-Reply-To: References: Message-ID: On Sat, May 8, 2010 at 12:04 PM, Vincent Davis wrote: > Is there a functional assert(x==y, 'error msg') ? > I can only find the assert that is used like; > assert x==y, 'error msg' > What about: def assertfunc(expr, msg): assert expr, msg cheers James -------------- next part -------------- An HTML attachment was scrubbed... URL: From wrw at mac.com Fri May 7 22:42:00 2010 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Fri, 07 May 2010 22:42:00 -0400 Subject: Frustration debugging serial code In-Reply-To: <4BE4CA10.4010608@mrabarnett.plus.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <4BE468BA.7090907@mrabarnett.plus.com> <4BE4CA10.4010608@mrabarnett.plus.com> Message-ID: On May 7, 2010, at 10:18 PM, MRAB wrote: > William R. Wing (Bill Wing) wrote: >> See comments in-line. >> On May 7, 2010, at 3:23 PM, MRAB wrote: >>> William R. Wing (Bill Wing) wrote: >>>> On May 7, 2010, at 2:08 PM, MRAB wrote: [byte -byte- byte] >>>>> >> The X10 controller not only receives it, it echos the response (\x06\r) that means >> it saw it and is ready for the next command in all three cases. The serial write >> that immediately follows, in which five hex bytes get sent to it is the one which >> succeeds interactively and in the IDE, and fails when executed as a bash script. > Does the ' Hit any key to continue: ' message appear when run as a bash > script? Yes, in all three cases, and just for completeness, the neither of the error returns from the first open statement ever are taken - that is, I never get either the \x15, which would print "Received NAK" nor the "Something's wrong" print that would indicate any other random return. > I'm just wondering whether it's that when run from the Python prompt or > IDE the 'ser' object continues to exist for a while, but when run as a > bash script Python is terminating before all of the bytes have been > sent. > > Of course, I'd expect 'ser.close()' to return only when there's nothing > left to be sent, or, at least, for there to be enough time while it's > waiting for you to press ENTER. > >>>>>> import serial, string >>>>>> port = '/dev/tty.KeySerial1' >>>>>> ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port >>>>>> stat1 = ser.write('\x02') # Write "Attention" to PowerLink >>>>>> print(' Stat1 is:', stat1) ack = ser.read(2) # Check to see if PowerLink is ready >>>>>> if ack == '\x06\r': # It returns ACK (\x06) \r if it is >>>>>> stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at House Code B, device code 2 >>>>>> print(' Stat2 is:', stat2) >>>>>> stat3 = ser.close() # Close serial port >>>>>> print(' Stat3 is:', stat3) >>>>>> elif ack =='\x15': # PowerLink sends NAC (hex 15) if it isn't. >>>>>> print('Received NAK after first open') >>>>>> else: print("Something's wrong at 1.\n") >>>>>> dummy = raw_input(' Hit any key to continue: ') > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at vincentdavis.net Fri May 7 22:43:22 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Fri, 7 May 2010 20:43:22 -0600 Subject: is there a functional assert(x==y, 'error msg') In-Reply-To: References: Message-ID: On Fri, May 7, 2010 at 8:38 PM, James Mills wrote: > On Sat, May 8, 2010 at 12:04 PM, Vincent Davis wrote: > >> Is there a functional assert(x==y, 'error msg') ? >> I can only find the assert that is used like; >> assert x==y, 'error msg' >> > > What about: > > def assertfunc(expr, msg): > assert expr, msg > I know but there are such nice asserts in unittest, but should (I assume can) they only be used in a unittest or would it be ok to use in code like the "normal" assert? *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri May 7 22:48:23 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 08 May 2010 12:48:23 +1000 Subject: recursive converting object to string which hasn't __str__ or/and__repr__ In-Reply-To: References: Message-ID: <4be4d153$1@dnews.tpgi.com.au> On 05/06/10 14:40, Daneel Yaitskov wrote: > Hi, > > > > Everybody knows class's __str__ and __repr__ can be used to get readable > user representation of an object. > > > But for simple classes or debug aims it is tediously to code these > methods. And Python has very powerful reflection. I believe that > somebody has already written such library with this method. > > I search library which can universally print state all not callable > attributes of an object. If object's attribute isn't int and float and > string and boolean and none then the method calls itself recursively. does dir() or printing __dict__ works for you? From python at mrabarnett.plus.com Fri May 7 22:49:29 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 08 May 2010 03:49:29 +0100 Subject: Frustration debugging serial code In-Reply-To: References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <4BE468BA.7090907@mrabarnett.plus.com> <4BE4CA10.4010608@mrabarnett.plus.com> Message-ID: <4BE4D139.1060503@mrabarnett.plus.com> William R. Wing (Bill Wing) wrote: > > On May 7, 2010, at 10:18 PM, MRAB wrote: > >> William R. Wing (Bill Wing) wrote: >>> See comments in-line. >>> On May 7, 2010, at 3:23 PM, MRAB wrote: >>>> William R. Wing (Bill Wing) wrote: >>>>> On May 7, 2010, at 2:08 PM, MRAB wrote: > > [byte -byte- byte] > >>>>>> >>> The X10 controller not only receives it, it echos the response >>> (\x06\r) that means >>> it saw it and is ready for the next command in all three cases. The >>> serial write >>> that immediately follows, in which five hex bytes get sent to it is >>> the one which >>> succeeds interactively and in the IDE, and fails when executed as a >>> bash script. >> Does the ' Hit any key to continue: ' message appear when run as a bash >> script? > > Yes, in all three cases, and just for completeness, the neither of the > error returns > from the first open statement ever are taken - that is, I never get > either the \x15, which > would print "Received NAK" nor the "Something's wrong" print that would > indicate > any other random return. > So clutching at straws doesn't work either... :-( >> I'm just wondering whether it's that when run from the Python prompt or >> IDE the 'ser' object continues to exist for a while, but when run as a >> bash script Python is terminating before all of the bytes have been >> sent. >> >> Of course, I'd expect 'ser.close()' to return only when there's nothing >> left to be sent, or, at least, for there to be enough time while it's >> waiting for you to press ENTER. >> From exarkun at twistedmatrix.com Fri May 7 23:18:30 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sat, 08 May 2010 03:18:30 -0000 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: <20100508031830.1660.308996474.divmod.xquotient.16@localhost.localdomain> On 7 May, 07:25 pm, p.f.moore at gmail.com wrote: >On 7 May 2010 15:36, Giampaolo Rodol? wrote: >>You can easily avoid this by setting a lower timeout when calling >>asyncore.loop(), like 1 second or less (for example, Twisted uses >>0.001 secs). > >Thanks, that's what I was considering. This is a good example of why it's a bad idea to use select on Windows. Instead, use WaitForMultipleObjects. >>Actually there's no reason for asyncore to have such a high default >>timeout (30 seconds). > >I assumed it was to avoid busy waiting. >>I think this should be signaled on the bug tracker. > >If a longer timeout doesn't have issues with busy waiting, then I'd >agree. The *default* timeout is only the default. An application that knows better can supply a different value. I'm not sure how much good can be done by fiddling with the default. Jean-Paul From greg.ewing at canterbury.ac.nz Sat May 8 00:21:39 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 08 May 2010 16:21:39 +1200 Subject: Teaching Programming In-Reply-To: References: Message-ID: <84k6k1Fl14U1@mid.individual.net> alex23 wrote: > This is my biggest issue with Knuth's view of literate programming. If > the generated source isn't readable, am I just supposed to trust it? > How can I tell if an error lies in my expression of the algorithm or > in the code generation itself? Knuth would say that the code generator should itself be a literate program, so that it's obviously correct. :-) -- Greg From stefan_ml at behnel.de Sat May 8 00:27:50 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 08 May 2010 06:27:50 +0200 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: j vickroy, 07.05.2010 20:44: > I apologize if this is not the appropriate forum for a question about > Hudson (http://hudson-ci.org/), but I did not know where else to ask and > my web searches have not been fruitful. Certainly nice to read something about Hudson in this forum, which is rare enough. It's seriously the greatest CI tool I've ever used, and it works great with Python apps. > "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" > > in the *Execute Python Script* subsection. The problem is that this isn't a "Python Script". I's a an executable, native program. Use the "execute shell" build step instead. Stefan From ncohen at ucsd.edu Sat May 8 01:22:08 2010 From: ncohen at ucsd.edu (Ben Cohen) Date: Fri, 7 May 2010 23:22:08 -0600 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: References: Message-ID: <36BDE98F-BE47-431D-971E-732B6A9B2289@ucsd.edu> Apologies for the TABs -- I wrote that example for demonstration purposes in my mail client -- I'll copy and paste from a real code editor in the future. Ben On May 7, 2010, at 3:28 PM, Aahz wrote: > In article , > Ben Cohen wrote: >> >> eg -- I'd like to do something like this: >> >> errors = [] >> for item in data: >> try: >> process(item) >> except ValidationError as e: >> errors.append(e) >> raise MultipleValidationErrors(*errors) > > First of all, please DO NOT post code with TABs in it. In fact, you > shouldn't even be writing code with TABs -- TAB characters are obsolete > for new Python code. > > I would write your code this way: > > errors = [] > for item in data: > try: > process(item) > except ValidationError as e: > errors.append(str(e)) > if errors: > raise MultipleValidationErrors(errors) > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > f u cn rd ths, u cn gt a gd jb n nx prgrmmng. > -- > http://mail.python.org/mailman/listinfo/python-list From brandshoes08 at yahoo.com Sat May 8 01:47:43 2010 From: brandshoes08 at yahoo.com (brandtrade) Date: Fri, 7 May 2010 22:47:43 -0700 (PDT) Subject: Parmigiani Fleurier Watch wholesale from china,paypal payment and free shipping Message-ID: Ebel Watch wholesale (paypal payment) (http://www.jordanonline06/) Bape Watch wholesale (paypal payment) (http://www.jordanonline06/) Bell&Ross Watch wholesale (paypal payment) (http:// www.jordanonline06/) Breit Ling Watch wholesale (paypal payment) (http:// www.jordanonline06/) Burberry Watch wholesale (paypal payment) (http://www.jordanonline06/) Cartier Watch wholesale (paypal payment) (http://www.jordanonline06/) Chopard Watch wholesale (paypal payment) (http://www.jordanonline06/) D&G Watch wholesale (paypal payment) (http://www.jordanonline06/) Givenchy Watch wholesale (paypal payment) (http://www.jordanonline06/) Jacob&Co Watch wholesale (paypal payment) (http://www.jordanonline06/) Kappa Watch wholesale (paypal payment) (http://www.jordanonline06/ ) Prada Watch wholesale (paypal payment) (http://www.jordanonline06/) Tissot Watch wholesale (paypal payment) (http://www.jordanonline06/) Titoni Watch wholesale (paypal payment) (http://www.jordanonline06/) U-BOAT Watch wholesale (paypal payment) (http://www.jordanonline06/) Zenith Watch wholesale (paypal payment) (http://www.jordanonline06/) A.Lange&Sohne Watch wholesale (paypal payment) (http:// www.jordanonline06/) Audemars Piguet Watch wholesale (paypal payment) (http:// www.jordanonline06/) Baume&Mercier Watch wholesale (paypal payment) (http:// www.jordanonline06/) Blancpain Watch wholesale (paypal payment) (http:// www.jordanonline06/) Breguet Watch wholesale (paypal payment) (http://www.jordanonline06/) BRM Watch wholesale (paypal payment) (http://www.jordanonline06/) Bvlgari Watch wholesale (paypal payment) (http://www.jordanonline06/) Chanel Watch wholesale (paypal payment) (http://www.jordanonline06/) Concord Watch wholesale (paypal payment) (http://www.jordanonline06/) Corum Watch wholesale (paypal payment) (http://www.jordanonline06/) Dewitt Watch wholesale (paypal payment) (http://www.jordanonline06/) Ferrari Watch wholesale (paypal payment) (http://www.jordanonline06/) Franck Muller Watch wholesale (paypal payment) (http:// www.jordanonline06/) Girard Perregaux Watch (paypal payment) (http://www.jordanonline06/) Glashutte Watch (paypal payment) (http://www.jordanonline06/) Graham Watch wholesale (paypal payment) (http://www.jordanonline06/) GUCCI Watch wholesale (paypal payment) (http://www.jordanonline06/) GUESS Watch wholesale (paypal payment) (http://www.jordanonline06/) Hamilton Watch wholesale (paypal payment) (http://www.jordanonline06/) Hermes Watch wholesale (paypal payment) (http://www.jordanonline06/) Hublot Watch wholesale (paypal payment) (http://www.jordanonline06/) IWC Watch wholesale (paypal payment) (http://www.jordanonline06/) Jaeger Le Coultre Watch wholesale (paypal payment) (http:// www.jordanonline06/) Longines Watch wholesale (paypal payment) (http://www.jordanonline06/) LV Watch wholesale (paypal payment) (http://www.jordanonline06/) Montblanc Watch wholesale (paypal payment) (http:// www.jordanonline06/) Movado Watch wholesale (paypal payment) (http://www.jordanonline06/) Omega Watch wholesale (paypal payment) (http://www.jordanonline06/) Oris Watch wholesale (paypal payment) (http://www.jordanonline06/) Paket Philippe Watch wholesale (paypal payment) (http:// www.jordanonline06/) Panerai Watch wholesale (paypal payment) (http://www.jordanonline06/) Parmigiani Fleurier Watch wholesale (paypal payment) (http:// www.jordanonline06/) Piaget Watch wholesale (paypal payment) (http://www.jordanonline06/) Porsche Design Watch wholesale (paypal payment) (http:// www.jordanonline06/) Rolex Watch wholesale (paypal payment) (http://www.jordanonline06/) Romain Jerome Titanic-Dna Watch wholesale (paypal payment)(http:// www.jordanonline06/) Tag Heuer Watch wholesale (paypal payment) (http:// www.jordanonline06/) Tudor Watch wholesale (paypal payment) (http://www.jordanonline06/) Vach.Constantine Watch wholesale (paypal payment) (http:// www.jordanonline06/) Armani Watch wholesale (paypal payment) (http://www.jordanonline06/) RADO Watch wholesale (paypal payment) (http://www.jordanonline06/) From ncohen at ucsd.edu Sat May 8 02:34:14 2010 From: ncohen at ucsd.edu (Ben Cohen) Date: Sat, 8 May 2010 00:34:14 -0600 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> <4D388C82-9DE8-43C3-89D8-F2C72623338E@ucsd.edu> Message-ID: <3DB109B4-71D3-483D-B63D-165B49A98251@ucsd.edu> I've condensed the advice from this thread into this. import sys import traceback class ExceptionList(object): def __init__(self, msg, errors=None, *args): self.errortb = errors or [] super(ExceptionList, self).__init__(msg, *args) def __str__(self): """Print a pretty traceback of captured tracebacks """ tracebacks = '\n'.join(self.errortb) msg = super(ExceptionList, self).__str__() parts=(msg, "="*78, tracebacks) msg = '\n'.join(parts) return msg def capture_traceback(limit=None): tb = traceback.format_exception(limit=None, *sys.exc_info()) tb = "".join(traceback for traceback in tb) return tb class SomeException(ExceptionList, Exception): pass errors = [] for c in 'hello': try: int(c) except ValueError: errors.append(capture_traceback()) if errors: raise SomeException('Multiple Exceptions encountered, see below tracebacks', errors) This is like Aahz's method but I wanted to include the whole traceback and his example only captures the exception's error message. I changed the example from Chris to only capture the text of the traceback rather than the whole traceback. As for whether this is terribly strange or not useful -- Steven said > That's a nice trick, but I'd really hate to see it in real life code. > Especially when each traceback was deep rather than shallow. Imagine > having fifty errors, each one of which was ten or twenty levels deep! I don't want to get buried in overlong stack traces either so I included the optional limit parameter to the format_traceback call -- > I also question how useful this would be in real life. Errors can cascade > in practice, and so you would very likely get spurious errors that were > caused by the first error. You see the same thing in doctests, e.g. if > you do this: I think this has use as in the example case -- when sequentially processing the elements of a list with the processing of each element being sufficiently 'independent' of the processing of the other elements so that the errors won't cascade. This seems handy for debugging situations like that, as might be common when developing a command line tool... Or as in my case, when 'validating' a sequence of elements. I'd be curious if others think this use seems odd or a bad idea ... Thanks to all for the free advice! Ben On May 7, 2010, at 7:24 PM, Chris Rebert wrote: >> On May 6, 2010, at 10:56 PM, Chris Rebert wrote: >>> On Thu, May 6, 2010 at 8:50 PM, Ben Cohen wrote: >>>> Is there a pythonic way to collect and display multiple exceptions at the same time? >>>> >>>> For example let's say you're trying to validate the elements of a list and you'd like to validate as many of the elements as possible in one run and still report exception's raised while validating a failed element. >>>> >>>> eg -- I'd like to do something like this: >>>> >>>> errors = [] >>>> for item in data: >>>> try: >>>> process(item) >>>> except ValidationError as e: >>>> errors.append(e) >>>> raise MultipleValidationErrors(*errors) >>>> >>>> where if the raised MultipleValidationErrors exception goes uncaught the interpreter will print a nice traceback that includes the tracebacks of each raised ValidationError. But I don't know how MultipleValidationErrors should be written ... > > > On Fri, May 7, 2010 at 6:06 PM, Ben Cohen wrote: >> Many thanks for the excellent example!! You rock! >> >> Ben > > However, I do agree with Steven that this approach to error handling > is unusual. But I assume you have your reasons for wanting to do it > this way. > > Cheers, > Chris > -- > Python + Bioinformatics = Win > http://blog.rebertia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Sat May 8 02:40:22 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 7 May 2010 23:40:22 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> Message-ID: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> On May 7, 6:44?pm, Ben Finney wrote: > Patrick Maupin writes: > > On May 7, 5:33?pm, Ben Finney wrote: > > > Since no-one is forcing anyone to take any of the actions permitted > > > in the license, and since those actions would not otherwise be > > > permitted under copyright law, it's both false and misleading to > > > refer to them as ?forced?. > > > Again, the force is applied once you choose to do a particular thing > > with the software > > And again, that would be the case with or without the specific free > software license But the OP wasn't asking whether he should supply a license or not (the absence of a license would presumably force everybody who wanted to use the software to download a copy from an authorized site, and not allow them to make copies for friends); he was asking *which* license he should use, and he explicitly mentioned MIT and LGPL. In the post you directly responded to, Aahz had responded to the OP with a suggested license of "MIT". So, in the context of the original question and original answer, the comparison is permissive vs. (L)GPL, *not* (L)GPL vs. no license at all. > so it's false and misleading to say the license forces > anything. I have already adequately covered what I believe Aahz meant by "forced" and I think it's a reasonable term for the discussed situation. Personally, I believe that if anything is false and misleading, it is the attempt to try to completely change the discussion from MIT vs. GPL to GPL vs. no license (and thus very few rights for the software users), after first trying to imply that people who distribute software under permissive licenses (that give the user *more* rights than the GPL) are somehow creating a some sort of moral hazard that might adversely affect their users, and then refusing to have any further discussion on that particular issue. So which is it? GPL good because a user can do more with the software than if he had no license, or MIT bad because a user can do more with the software than if it were licensed under GPL? > The actions that are prohibited are prohibited by copyright > law, not by the license. Yes, just like the taking of food from the restaurant is prohibited by laws against theft, and in both cases, these prohibitions may be backed up by the force of the government. But as discussed, this does not mean that the restaurant or software author cannot give you something for free if they desire to. > I think we're done here. Certainly appears that neither of us is going to convince the other of anything. Regards, Pat From varnikat22 at gmail.com Sat May 8 02:54:57 2010 From: varnikat22 at gmail.com (varnikat t) Date: Sat, 8 May 2010 12:24:57 +0530 Subject: how to play a sound file repeatedly in loop Message-ID: How to run sound file repeatedly in loop ? When I do this, it does nothing and terminates: import pygst pygst.require("0.10") import gst, gtk n=0 while n<10: player = gst.element_factory_make("playbin2", "player") player.set_property("uri", "file:/home/varnika/hello.ogg") player.set_state(gst.STATE_PLAYING) n=n+1 Regards Varnika Tewari -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Sat May 8 03:48:11 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 08 May 2010 19:48:11 +1200 Subject: Windows - select.select, timeout and KeyboardInterrupt References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: In message , exarkun at twistedmatrix.com wrote: > This is a good example of why it's a bad idea to use select on Windows. > Instead, use WaitForMultipleObjects. How are you supposed to write portable code, then? From steve at REMOVE-THIS-cybersource.com.au Sat May 8 04:37:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 08:37:01 GMT Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> Message-ID: <4be522ac$0$27798$c3e8da3@news.astraweb.com> On Fri, 07 May 2010 23:40:22 -0700, Patrick Maupin wrote: > Personally, I believe that if anything is false and misleading, it is > the attempt to try to completely change the discussion from MIT vs. GPL > to GPL vs. no license (and thus very few rights for the software users), > after first trying to imply that people who distribute software under > permissive licenses (that give the user *more* rights than the GPL) are > somehow creating a some sort of moral hazard that might adversely affect > their users If encouraging third parties to take open source code and lock it up behind proprietary, closed licences *isn't* a moral hazard, then I don't know what one is. For the record, I've published software under an MIT licence because I judged the cost of the moral hazard introduced by encouraging freeloaders to be less than the benefits of having a more permissive licence that encourages freeloading and therefore attracts more users. For other software, I might judge that the cost/benefit ratio falls in a different place, and hence choose the GPL. > So which is it? GPL good because a user can do more with the software > than if he had no license, or MIT bad because a user can do more with > the software than if it were licensed under GPL? Good or bad isn't just a matter of which gives you more freedoms, they're also a matter of *what* freedoms they give. Weaponized ebola would allow you to kill hundreds of millions of people in a matter of a few weeks, but it takes a very special sort of mind to consider that the freedom to bring about the extinction of the human race a "good". I consider the freedom granted by the MIT licence for my users to take my source code and lock it up behind restrictive licences (and therefore *not* grant equivalent freedoms to their users in turn) to be a bad, not a good. But in some cases it is a cost worth paying, primarily because not all people who use MIT-licenced software go on to re-publish it under a restrictive licence, but nevertheless won't consider the GPL (possibly due to misunderstandings, confusion or political interference). -- Steven From martin.hellwig at dcuktec.org Sat May 8 05:33:46 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 08 May 2010 10:33:46 +0100 Subject: Picking a license In-Reply-To: <4be522ac$0$27798$c3e8da3@news.astraweb.com> References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: On 05/08/10 09:37, Steven D'Aprano wrote: > If encouraging third parties to take open source code and lock it up > behind proprietary, closed licences *isn't* a moral hazard, then I don't > know what one is. I fail to see what is morally wrong with it. When I ,as the author, share my work to the public, I should have made peace with the fact that I, for all intends and purposes, lost control over its use. And that is rightfully so; who am I to say: "Yeah you can use it but only once in a blue moon when Jupiter aligns with Mars and a solar eclipse reaches its high on Greenwich at noon exactly." But just for argument sake say that you can put restrictions on the use, who is going to enforce these restrictions? The author/Police/special interest groups? Anyway I usually put stuff under the MIT/BSD license, but when I can I use the beerware license (http://people.freebsd.org/~phk/) and I fully agree with PHK's reasoning. -- mph From g.rodola at gmail.com Sat May 8 07:47:53 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Sat, 8 May 2010 13:47:53 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: 2010/5/7 Antoine Pitrou : > Le Fri, 07 May 2010 21:55:15 +0200, Giampaolo Rodol? a ?crit?: >> Of course, but 30 seconds look a little bit too much to me, also because >> (I might be wrong here) I noticed that a smaller timeout seems to result >> in better performances. > > That's probably bogus. Probably, I'll try to write a benchmark script and see what happens. >> Plus, if scheduled callbacks are ever gonna be added to asyncore we >> would be forced to lower the default timeout anyway in order to have a >> decent reactivity. > > Why? Assuming loop() function does something like this: ... select.select(r, w, e, timeout) scheduler() # checks for scheduled calls to be fired ... ...imagine a case where there's a connection (aka a dispatcher instance) which does not receive or send any data *and* a scheduled call which is supposed to be fired after, say, 5 seconds. The entire loop would hang on select.select() which won't return for 30 seconds because the socket is not ready for reading and/or writing resulting in scheduler() be called too late. --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From promptc2 at hotmail.com Sat May 8 08:34:21 2010 From: promptc2 at hotmail.com (www.promptc.com) Date: Sat, 8 May 2010 05:34:21 -0700 (PDT) Subject: MBT shoes($62,1:1 quality),online shopping www.promptc.com Message-ID: <18331a69-4dfb-49e8-bb47-d9786b301540@32g2000prq.googlegroups.com> dear Mr/Ms, Great day! welcome to visit online shopping website www.Promptc.com Basic information: 1)Payment:Paypal,WU,TT etc 2)Delivery time:3-7 days door to door safety delivery 3)Delivery methods:DHL,TNT,EMS etc 4)quality condition:Super A 5) Price range:$30-$37 6)various brands ,various 2010 newest fashion style,various colors 7)can do drop-ship to your customers! 8)more order more discount ! ! ! 9)we would send out your order within 24-36 hours once confirmed your Pyament and then send you the tracking number via email for you to track the status of the goods. Main trade:Jersey,handbag,brand shoes like nike shox,nike air max,nike jordan,MBT shoes ,Skirt,T-shirt,sunglass,caps etc We are manufacture-sale company.Other companies invest fund in advertisement but our company invest in improving the quality of our goods and offer our customers the lowest price.We believe that the excellent quality itself is our company's advertisment.Since now the excellent of our goods have found a good market in many countries. some links of the nike shox : 1)http://www.promptc.com/index.php?main_page=index&cPath=168_183 2)http://www.promptc.com/index.php? main_page=index&cPath=168_183&sort=20a&page=6 3)http://www.promptc.com/index.php?main_page=index&cPath=168_189 4)http://www.promptc.com/index.php? main_page=index&cPath=168_183&sort=20a&page=10 5)http://www.promptc.com/index.php?main_page=index&cPath=168_190 6)http://www.promptc.com/index.php?main_page=index&cPath=168_184 7)http://www.promptc.com/index.php?main_page=index&cPath=168_174 8)http://www.promptc.com/index.php?main_page=index&cPath=168_188 Don't hesitate,take action !You can shopping online or contact us for more details! waitting for your early reply. Best wishes Sale Manager Megan Li Promptc Co.,Ltd www.promptc.com From news1234 at free.fr Sat May 8 08:51:32 2010 From: news1234 at free.fr (News123) Date: Sat, 08 May 2010 14:51:32 +0200 Subject: Cross-platform file paths In-Reply-To: References: Message-ID: <4be55e54$0$32091$426a74cc@news.free.fr> Hi TIA, utabintarbo wrote: > Until now, I have used the UNC under Windows (XP) to allow my program > to access files located on a Samba-equipped *nix box (eg. > os.path.normpath(r"\\serverFQDN\sharename\dir\filename")). When I try > to open this file under Linux (Red Hat 5), I get a file not found > error. > > Is there a cross-platform method for accessing files on a network > share using Python 2.X? > Up to my knowledge there is now path name under linux, which gives you access to samba shares without mounting then. Perhaps there's some special user space file system drivers providing that functionality, but I don't expect it to be standard linux behaviour. What is your linux distribution? I would suggest to change the subject line to something like: "accessing samba shares from a linux host without mounting them" or "cross-platform liibrary to access samba shares" From martin at v.loewis.de Sat May 8 09:26:55 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 08 May 2010 15:26:55 +0200 Subject: py3 tkinter acceps bytes. why? In-Reply-To: References: <4BE352E5.4060004@v.loewis.de> Message-ID: <4BE5669F.1090408@v.loewis.de> Matthias Kievernagel wrote: > Me: >>> If I don't want bytes to get passed to tkinter >>> I just have to raise an exception in AsObj, no? >>> Or is it even sufficient to just remove the bytes case? > Martin v. Loewis wrote: >> But why would you want that? There are commands which legitimately >> return bytes, e.g. the file and network io libraries of Tcl (not that >> you would usually want to use them in Python, but Tkinter is actually >> Tclinter, and should support all Tcl commands). > > I'm just looking for a reliable error message when I pass > something to GUI functions which is not fit for display, > i.e. not a string. If bytes pass unnoticed, > I'll sooner or later have a surprise. > Just to make sure I decode all bytes (coming from a socket) > before I pass them on to the GUI. I see. I think it's just not possible to provide such a check, given Tcl's (non-existent) type system. Regards, Martin From python.list at tim.thechases.com Sat May 8 09:52:27 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 08 May 2010 08:52:27 -0500 Subject: [PATCH] Re: ConfigParser.get() defaults? In-Reply-To: <4BE4C287.9070505@tim.thechases.com> References: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> <4BE4C287.9070505@tim.thechases.com> Message-ID: <4BE56C9B.8010309@tim.thechases.com> > On 05/07/2010 07:56 PM, Steven D'Aprano wrote: >> On Fri, 07 May 2010 15:05:53 -0500, Tim Chase wrote: >>> With a normal dictionary, I can specify a default fallback value in the >>> event the requested key isn't present: >> [...] >>> However, with the ConfigParser object, there doesn't seem to be any way >>> to do a similar >> >> Sounds like a nice feature to have. When you submit a patch (*grin*), > > I'm game to create and provide a patch, Attached is my initial patch against 2.6's ConfigParser.py to work in some defaults (though it should also apply fairly cleanly against 2.5). It doesn't differentiate between missing sections and missing options, as both cases are the same in my use: the user didn't provide a setting, so I want to specify a default without lots of try/except wrapping. For the type-specific get[int/float/boolean]() functions, it also provides an optional parameter to raise the ValueError or just return the default if it's provided-but-bogus (it may also yell at you if your default creates a ValueError). My distributed ConfigParser.py didn't seem to have any tests, so I didn't include any; but would be glad to write a few if they'd be integrated into the standard core testing. Is this the sort of things that should also be sent to python-dev, or are the powers-that-be lurking sufficiently on this list to see this patch fly? -tkc -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ConfigParser.diff URL: From exarkun at twistedmatrix.com Sat May 8 09:57:48 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sat, 08 May 2010 13:57:48 -0000 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: <20100508135748.1660.423455733.divmod.xquotient.21@localhost.localdomain> On 07:48 am, ldo at geek-central.gen.new_zealand wrote: >In message , >exarkun at twistedmatrix.com wrote: >>This is a good example of why it's a bad idea to use select on >>Windows. >>Instead, use WaitForMultipleObjects. > >How are you supposed to write portable code, then? With WaitForMultipleObjects on Windows, epoll on Linux, kqueue on BSD, event completion on Solaris, etc... Sound like more work than using select() everywhere? Yea, a bit. But not once you abstract it away from your actual application code. After all, it's not like these *do* different things. They all do the same thing (basically) - differently. Jean-Paul From exarkun at twistedmatrix.com Sat May 8 10:00:02 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sat, 08 May 2010 14:00:02 -0000 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: <20100508140002.1660.1843072524.divmod.xquotient.25@localhost.localdomain> On 11:47 am, g.rodola at gmail.com wrote: >2010/5/7 Antoine Pitrou : >>Le Fri, 07 May 2010 21:55:15 +0200, Giampaolo Rodol? a ?crit?: >>>Of course, but 30 seconds look a little bit too much to me, also >>>because >>>(I might be wrong here) I noticed that a smaller timeout seems to >>>result >>>in better performances. >> >>That's probably bogus. > >Probably, I'll try to write a benchmark script and see what happens. >>>Plus, if scheduled callbacks are ever gonna be added to asyncore we >>>would be forced to lower the default timeout anyway in order to have >>>a >>>decent reactivity. >> >>Why? > >Assuming loop() function does something like this: > > ... > select.select(r, w, e, timeout) > scheduler() # checks for scheduled calls to be fired > ... > >...imagine a case where there's a connection (aka a dispatcher >instance) which does not receive or send any data *and* a scheduled >call which is supposed to be fired after, say, 5 seconds. >The entire loop would hang on select.select() which won't return for >30 seconds because the socket is not ready for reading and/or writing >resulting in scheduler() be called too late. This would be an intensely lame way to implement support for scheduled callbacks. Try this trivial modification instead, to make it awesome: ... select.select(r, w, e, scheduler.time_until_next_call()) scheduler.run() ... (Or maybe just use Twisted. ;) Jean-Paul From solipsis at pitrou.net Sat May 8 10:00:09 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sat, 8 May 2010 16:00:09 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: <20100508160009.749631d9@pitrou.net> On Sat, 8 May 2010 13:47:53 +0200 Giampaolo Rodol? wrote: > > Assuming loop() function does something like this: > > ... > select.select(r, w, e, timeout) > scheduler() # checks for scheduled calls to be fired > ... > > ...imagine a case where there's a connection (aka a dispatcher > instance) which does not receive or send any data *and* a scheduled > call which is supposed to be fired after, say, 5 seconds. > The entire loop would hang on select.select() which won't return for > 30 seconds because the socket is not ready for reading and/or writing > resulting in scheduler() be called too late. Well, obviously you have to change the timeout based on the delay for the next scheduled call. If your patch doesn't do that, it probably needs fixing :) Regards Antoine. From mehgcap at gmail.com Sat May 8 10:08:08 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 8 May 2010 10:08:08 -0400 Subject: shortcut for large amount of global var declarations? Message-ID: Hi all, I am sorry if this is the second message about this you get; I typed this and hit send (on gmail website) but I got a 404 error, so I am not sure if the previous message made it out or not. Anyway, I have about fifteen vars in a function which have to be global. Is there a faster and more space-efficient way of doing this than putting each var on its own line; that is, fifteen "global varName" declarations? Thanks. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From luke.leighton at googlemail.com Sat May 8 10:08:08 2010 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 8 May 2010 07:08:08 -0700 (PDT) Subject: Python is cool!! References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> <4BA8F56D.6060305@timgolden.me.uk> <62d1f435-e473-4ba5-a7a6-334f5c69e4e3@d37g2000yqn.googlegroups.com> Message-ID: <29222386-00a0-46bf-89c2-e055d1bf1fca@d19g2000yqf.googlegroups.com> On Mar 23, 9:24?pm, Patrick Maupin wrote: > On Mar 23, 3:12?pm, Tim Golden wrote: > > > I can't say I thought *very* hard before sending that but... > > The OP asked for "integrate Python in Web Pages with HTML" > > which I understood -- perhaps wrongly -- to mean: run Python > > in the browser. The only two ways I'm aware of doing that > > in Python are the undersupported Python-as-IE-scripting-language > > and IronPython/Silverlight. > > If I had to run Python in a browser, the first thing I would do is > turn toPyjamas: ?http://pyjs.org/ or http://skulpt.org or an old version of pypy with the JS back-end (no longer maintained) ... but there's another way - actually several. i documented them all here: http://wiki.python.org/moin/WebBrowserProgramming solutions include appcelerator, pxpcomext and so on. appcelerator comprises, as best i can make out, some simple "glue" logic which connects silverlight/moonlight to DOM access functions via .NET (and from there to languages such as python or ruby, through IronRuby and IronPython) all pretty fucking horrendous, to be honest, and non-portable, making pyjs and skulpt the infinitely better choices for cross-platform / cross-browser interoperability. skulpt doesn't come with any UI widgets (not in JS nor in python) but pyjamas does. it entirely depends what you want to do. l. From bryanjugglercryptographer at yahoo.com Sat May 8 10:08:55 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sat, 8 May 2010 07:08:55 -0700 (PDT) Subject: fast regex References: <87eihp2gf8.fsf@castleamber.com> <4BE37F36.3090701@tim.thechases.com> Message-ID: Tim Chase wrote: > James wrote: > > [Tim had written:] > If the keys in your word_list are more than just words, then the > regexp may not find them all, and thus not replace them all. ?In > that case you may have to resort to my 2nd regexp which builds > the 5k branch regexp from your actual dictionary keys: > > >> ?r = re.compile(r'\b(%s)\b' % ( > >> ? ?'|'.join(re.escape(s) for s in words_list.keys()) > >> ? ?), > >> ? ?re.IGNORECASE) > > This method on the above dictionary (modified) > > ? ?d = { > ? ? ?'hello': 'goodbye', > ? ? ?'world': 'python', > ? ? ?'stuff with spaces?': 'tadah!', > ? ? ?} > > would create a regexp of > > ? ?\b(about|world|stuff\ with\ spaces\?)\b There's a subtle issue of the order of the keywords. Pythons (ir)regular expressions do not strictly guarantee to find the longest match. For example, re.findall(r'\b(about|about\-faced)\b', 'does about-faced match?') returns ['about'], which is the first complete match, not the longest. Sorting the keywords into longest-first order avoids the problem. > This has considerable performance implications as len(word_list) > grows, unless you can figure a way to determine that some > replacements are more probable than others and push them to the > front of this regexp, but that's more complex and requires > knowledge of your word-list. There is another method which is to factor out common prefixes, so the re module's search-and-backtrack engine never has a choice of multiple paths. Instead of: \b(abolished|abolition)\b we'd use: \b(aboli(shed|tion)\b The RE-generator is of course more complex than Tim's one-liner, but I happen to have code, which I'll include below. It's probably academic, as I'd agree with Tim that his first solution is the better candidate at this point. With my giant prefix-combined RE's, I can re.compile one with 4000 words randomly chosen from a Unix words file, but 5000 results in "regular expression code size limit exceeded". Tim's version which doesn't combine prefixes tops out a little lower. This is on 32-bit Windows, standard distribution. One could, of course, build multiple smaller RE's, but that starts to suck. -Bryan Olson from random import sample import re def build_big_re(str_list): """ Build a non-backtracking regular expression matching any of the words in str_list. """ def trie_insert(table, str): if str: submap = table.setdefault(str[0], {}) trie_insert(submap, str[1:]) else: table[""] = {} def sequentialize(table, lst): if table: keys = table.keys() keys.sort(key=len, reverse=True) lst.append('(?:') seperator = '' for key in keys: lst.append(seperator + re.escape(key)) submap = table[key] while len(submap) == 1: key = submap.keys()[0] submap = submap[key] lst.append(re.escape(key)) sequentialize(submap, lst) seperator = '|' lst.append(')') table = {} for str in str_list: trie_insert(table, str) lst = [r'\b'] sequentialize(table, lst) lst.append(r'\b') re_str = "".join(lst) # print "RE is: '%s'\n" % re_str return re.compile(re_str, re.IGNORECASE) def simple_re(str_list): str_list = sorted(str_list, key=len, reverse=True) re_str = r'\b(%s)\b' % ( '|'.join(re.escape(s) for s in str_list)) # print "RE is", re_str return re.compile(re_str, re.IGNORECASE) def testy(): words_file = r'/usr/share/dict/words' # Common Unix # words_file = r'C:\z\wordlist.txt' # Just my box nkeywords = 3500 from random import sample with open(words_file, 'r') as f: allwords = [w.strip() for w in f.readlines()] keywords = sample(allwords, nkeywords) bigtext = ' '.join(allwords) print 'Building simple RE...' simpre = simple_re(keywords) print 'Run simple re...' z1 = simpre.findall(bigtext) print 'Done.\n' print 'Building complex RE...' compre = build_big_re(keywords) print 'Run complex re...' z2 = compre.findall(bigtext) print 'Done.' assert z1 == z2 testy() From luke.leighton at googlemail.com Sat May 8 10:11:57 2010 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 8 May 2010 07:11:57 -0700 (PDT) Subject: Python is cool!! References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> <4bab7acb$0$2873$426a74cc@news.free.fr> Message-ID: On Mar 25, 3:01?pm, Bruno Desthuilliers wrote: > Jose Manuel a ?crit : > > > I have been learning Python, and it is amazing .... I am using the > > tutorial that comes with the official distribution. > > > At the end my goal is to develop applied mathematic in engineering > > applications to be published on the Web, specially on app. oriented to > > simulations and control systems, I was about to start learning Java > > but I found Python which seems easier to learn that Java. > > Python is indeed quite lightweight when compared to Java. But it has > it's share of non-obvious features, dark corners, gotchas, and plain > warts too. good god. it does?? :) that's news to me, bruno! where? i haven't found _any_ of those things - it's aaalll been blindingly obvious and... ok maybe not metaclasses i alllmost grok those :) l. From python at mrabarnett.plus.com Sat May 8 10:26:14 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 08 May 2010 15:26:14 +0100 Subject: fast regex In-Reply-To: References: <87eihp2gf8.fsf@castleamber.com> <4BE37F36.3090701@tim.thechases.com> Message-ID: <4BE57486.3060908@mrabarnett.plus.com> Bryan wrote: > Tim Chase wrote: >> James wrote: >>> [Tim had written:] >> If the keys in your word_list are more than just words, then the >> regexp may not find them all, and thus not replace them all. In >> that case you may have to resort to my 2nd regexp which builds >> the 5k branch regexp from your actual dictionary keys: >> >>>> r = re.compile(r'\b(%s)\b' % ( >>>> '|'.join(re.escape(s) for s in words_list.keys()) >>>> ), >>>> re.IGNORECASE) >> This method on the above dictionary (modified) >> >> d = { >> 'hello': 'goodbye', >> 'world': 'python', >> 'stuff with spaces?': 'tadah!', >> } >> >> would create a regexp of >> >> \b(about|world|stuff\ with\ spaces\?)\b > > > There's a subtle issue of the order of the keywords. Pythons > (ir)regular expressions do not strictly guarantee to find the longest > match. For example, > > re.findall(r'\b(about|about\-faced)\b', > 'does about-faced match?') > > returns ['about'], which is the first complete match, not the longest. > Sorting the keywords into longest-first order avoids the problem. > > >> This has considerable performance implications as len(word_list) >> grows, unless you can figure a way to determine that some >> replacements are more probable than others and push them to the >> front of this regexp, but that's more complex and requires >> knowledge of your word-list. > > There is another method which is to factor out common prefixes, so the > re module's search-and-backtrack engine never has a choice of multiple > paths. Instead of: > > \b(abolished|abolition)\b > > we'd use: > > \b(aboli(shed|tion)\b > > The RE-generator is of course more complex than Tim's one-liner, but I > happen to have code, which I'll include below. It's probably academic, > as I'd agree with Tim that his first solution is the better candidate > at this point. > > With my giant prefix-combined RE's, I can re.compile one with 4000 > words randomly chosen from a Unix words file, but 5000 results in > "regular expression code size limit exceeded". Tim's version which > doesn't combine prefixes tops out a little lower. This is on 32-bit > Windows, standard distribution. One could, of course, build multiple > smaller RE's, but that starts to suck. > There's an alternative regex module at: http://bugs.python.org/issue2636 and also at: http://pypi.python.org/pypi/regex/0.1.2010414 It looks for common prefixes and suffixes internally and can handle much larger regexes. From joncle at googlemail.com Sat May 8 10:26:16 2010 From: joncle at googlemail.com (Jon Clements) Date: Sat, 8 May 2010 07:26:16 -0700 (PDT) Subject: shortcut for large amount of global var declarations? References: Message-ID: On 8 May, 15:08, Alex Hall wrote: > Hi all, > I am sorry if this is the second message about this you get; I typed > this and hit send (on gmail website) but I got a 404 error, so I am > not sure if the previous message made it out or not. > Anyway, I have about fifteen vars in a function which have to be > global. Is there a faster and more space-efficient way of doing this > than putting each var on its own line; that is, fifteen "global > varName" declarations? Thanks. > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg... at gmail.com;http://www.facebook.com/mehgcap About 15 that *need* to be global; smells bad to me. However, you can amend a function's .func_globals attribute. Just wouldn't be going there myself. Why do you have this many? What's your use case? Jon. From aahz at pythoncraft.com Sat May 8 10:26:31 2010 From: aahz at pythoncraft.com (Aahz) Date: 8 May 2010 07:26:31 -0700 Subject: Picking a license References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: In article <4be522ac$0$27798$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > >For the record, I've published software under an MIT licence because I >judged the cost of the moral hazard introduced by encouraging freeloaders >to be less than the benefits of having a more permissive licence that >encourages freeloading and therefore attracts more users. For other >software, I might judge that the cost/benefit ratio falls in a different >place, and hence choose the GPL. Well, yes, which is more-or-less what I posted in the first place. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From python at mrabarnett.plus.com Sat May 8 10:29:30 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 08 May 2010 15:29:30 +0100 Subject: shortcut for large amount of global var declarations? In-Reply-To: References: Message-ID: <4BE5754A.9040106@mrabarnett.plus.com> Alex Hall wrote: > Hi all, > I am sorry if this is the second message about this you get; I typed > this and hit send (on gmail website) but I got a 404 error, so I am > not sure if the previous message made it out or not. > Anyway, I have about fifteen vars in a function which have to be > global. Is there a faster and more space-efficient way of doing this > than putting each var on its own line; that is, fifteen "global > varName" declarations? Thanks. > 'global' will accept multiple names: def foo(): global a, b, c ... From mehgcap at gmail.com Sat May 8 11:03:04 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 8 May 2010 11:03:04 -0400 Subject: shortcut for large amount of global var declarations? In-Reply-To: References: Message-ID: On 5/8/10, Jon Clements wrote: > On 8 May, 15:08, Alex Hall wrote: >> Hi all, >> I am sorry if this is the second message about this you get; I typed >> this and hit send (on gmail website) but I got a 404 error, so I am >> not sure if the previous message made it out or not. >> Anyway, I have about fifteen vars in a function which have to be >> global. Is there a faster and more space-efficient way of doing this >> than putting each var on its own line; that is, fifteen "global >> varName" declarations? Thanks. >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehg... at gmail.com;http://www.facebook.com/mehgcap > > About 15 that *need* to be global; smells bad to me. However, you can > amend a function's .func_globals attribute. How do you do this exactly? > Just wouldn't be going there myself. Why do you have this many? What's your > use case? They are in a "setOptions" function in config.py, which reads from an ini file and sets up all options for the program. All other files then can read these options. For example, anyone else can import config, then, if they are rounding a number, they can know how many places to round to by looking at config.rnd. I have everything in a function instead of being initialized upon importing since I offer a function to reload the ini file if the user changes something. Eventually I will have a gui for setting options, and that gui, to save options, will write an ini file then call setOptions so all options are then reset according to the newly created ini. If I do not make everything in setOptions global, no other file seems able to read it; I get an exception the first time another file tries to access a setting. Thanks. > > Jon. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From g.rodola at gmail.com Sat May 8 11:03:07 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Sat, 8 May 2010 17:03:07 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: <20100508160009.749631d9@pitrou.net> References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> <20100508160009.749631d9@pitrou.net> Message-ID: 2010/5/8 Antoine Pitrou : > On Sat, 8 May 2010 13:47:53 +0200 > Giampaolo Rodol? wrote: >> >> Assuming loop() function does something like this: >> >> ? ? ?... >> ? ? ?select.select(r, w, e, timeout) >> ? ? ?scheduler() ?# checks for scheduled calls to be fired >> ? ? ?... >> >> ...imagine a case where there's a connection (aka a dispatcher >> instance) which does not receive or send any data *and* a scheduled >> call which is supposed to be fired after, say, 5 seconds. >> The entire loop would hang on select.select() which won't return for >> 30 seconds because the socket is not ready for reading and/or writing >> resulting in scheduler() be called too late. > > Well, obviously you have to change the timeout based on the delay for > the next scheduled call. If your patch doesn't do that, it probably > needs fixing :) > > Regards > > Antoine. No it doesn't and I didn't consider this solution at the time. Thanks. =) --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From prologic at shortcircuit.net.au Sat May 8 11:13:17 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sun, 9 May 2010 01:13:17 +1000 Subject: shortcut for large amount of global var declarations? In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 12:08 AM, Alex Hall wrote: > Hi all, > I am sorry if this is the second message about this you get; I typed > this and hit send (on gmail website) but I got a 404 error, so I am > not sure if the previous message made it out or not. > Anyway, I have about fifteen vars in a function which have to be > global. Is there a faster and more space-efficient way of doing this > than putting each var on its own line; that is, fifteen "global > varName" declarations? Thanks. Using "globals" (global variables) is generally considered bad practise. Consider instead using a class/object. You could for example have a "config" object that is shared by other modules. cheers James From sridharr at activestate.com Sat May 8 11:34:36 2010 From: sridharr at activestate.com (Sridhar) Date: Sat, 08 May 2010 08:34:36 -0700 Subject: ActivePython - how to configure portable framework? In-Reply-To: References: Message-ID: <4BE5848C.3010606@activestate.com> Copy all the files in the ZIP to your USB stick and run INSTALLDIR\python.exe -srid On 5/7/2010 3:24 AM, balzer wrote: > I downloaded ActivePython-2.6.5.12-win32-x86.zip, it contains two > folders and 3 files: > > SystemFolder > INSTALLDIR > sh2.py > install.bat > _install.py > > Anyone know how to configure this Python environment as "portable > application" to work with it without installation, to set a > fully-functional Python environment that executes entirely from hard > drive (or USB stick) without leaving no registry entries, no mess with > windows system files, etc on machine it's run on. > > I created folder "Python", what files I should copy inside? > > thanks. From joncle at googlemail.com Sat May 8 13:04:30 2010 From: joncle at googlemail.com (Jon Clements) Date: Sat, 8 May 2010 10:04:30 -0700 (PDT) Subject: shortcut for large amount of global var declarations? References: Message-ID: <96ddcf17-4ee1-471a-9422-323b7063f926@24g2000yqy.googlegroups.com> On 8 May, 16:03, Alex Hall wrote: > On 5/8/10, Jon Clements wrote: > > > On 8 May, 15:08, Alex Hall wrote: > >> Hi all, > >> I am sorry if this is the second message about this you get; I typed > >> this and hit send (on gmail website) but I got a 404 error, so I am > >> not sure if the previous message made it out or not. > >> Anyway, I have about fifteen vars in a function which have to be > >> global. Is there a faster and more space-efficient way of doing this > >> than putting each var on its own line; that is, fifteen "global > >> varName" declarations? Thanks. > > >> -- > >> Have a great day, > >> Alex (msg sent from GMail website) > >> mehg... at gmail.com;http://www.facebook.com/mehgcap > > > About 15 that *need* to be global; smells bad to me. However, you can > > amend a function's .func_globals attribute. > > How do you do this exactly?> Just wouldn't be going there myself. Why do you have this many? What's your > > use case? > > They are in a "setOptions" function in config.py, which reads from an > ini file and sets up all options for the program. All other files then > can read these options. For example, anyone else can import config, > then, if they are rounding a number, they can know how many places to > round to by looking at config.rnd. I have everything in a function > instead of being initialized upon importing since I offer a function > to reload the ini file if the user changes something. Eventually I > will have a gui for setting options, and that gui, to save options, > will write an ini file then call setOptions so all options are then > reset according to the newly created ini. If I do not make everything > in setOptions global, no other file seems able to read it; I get an > exception the first time another file tries to access a setting. > Thanks. > > > > > Jon. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg... at gmail.com;http://www.facebook.com/mehgcap Umm, okay at least now we know the context. Similar to what James suggested just have a dict object in your config module called 'settings' or something and access that. I still prefer the "giveth rather than taketh" approach though. But heck, if it works, who cares? Jon. From pmaupin at gmail.com Sat May 8 13:14:18 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 10:14:18 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: On May 8, 3:37?am, Steven D'Aprano wrote: > On Fri, 07 May 2010 23:40:22 -0700, Patrick Maupin wrote: > > Personally, I believe that if anything is false and misleading, it is > > the attempt to try to completely change the discussion from MIT vs. GPL > > to GPL vs. no license (and thus very few rights for the software users), > > after first trying to imply that people who distribute software under > > permissive licenses (that give the user *more* rights than the GPL) are > > somehow creating a some sort of moral hazard that might adversely affect > > their users > > If encouraging third parties to take open source code and lock it up > behind proprietary, closed licences *isn't* a moral hazard, then I don't > know what one is. For a start, there is a difference between "encouraging" and "allowing". But in point of fact, you have it exactly backwards. Putting the code out there and making it a tort to republish it under a closed license creates a moral hazard -- a trap that many companies including Linksys/Cisco have fallen into. If I expect nothing in return, if it's a gift, then the likelihood of moral hazard is significantly reduced. Unless you are somehow suggesting that I owe my user's customers anything (which suggestion, btw, is frequently made in veiled terms, and always pisses me off), there is no other moral hazard produced by me choosing a permissive license for my code. > > So which is it? ?GPL good because a user can do more with the software > > than if he had no license, or MIT bad because a user can do more with > > the software than if it were licensed under GPL? > > Good or bad isn't just a matter of which gives you more freedoms, they're > also a matter of *what* freedoms they give. Weaponized ebola would allow > you to kill hundreds of millions of people in a matter of a few weeks, > but it takes a very special sort of mind to consider that the freedom to > bring about the extinction of the human race a "good". You're missing the context where Mr. Finney keeps changing what he's arguing about. I agree completely that different licenses are valid for different expectations, and said as much in my first post on this subject. But it's extremely silly to compare weaponized ebola to publishing free software, unless you want to give ammunition to those amoral profiteers who claim that it is so dangerous for hackers to give out source code at all that doing so should be criminalized. > I consider the freedom granted by the MIT licence for my users to take my > source code and lock it up behind restrictive licences (and therefore > *not* grant equivalent freedoms to their users in turn) to be a bad, not > a good. But in some cases it is a cost worth paying, primarily because > not all people who use MIT-licenced software go on to re-publish it under > a restrictive licence, but nevertheless won't consider the GPL (possibly > due to misunderstandings, confusion or political interference). "Political interference" is certainly the main reason that I won't use the GPL, but it is probably not the same politics you are thinking of. When I seriously consider investing in learning a piece of software so that I can make it part of my "toolbox," a major consideration is how well it plays with the other tools in my toolbox, and exactly which construction jobs I can use it on. RMS has managed to create a scenario where the GPL not only doesn't play nicely with some other licenses, but now doesn't even always play nicely with itself -- some people who liked GPL v2 but weren't willing to cede control of their future licensing terms to the FSF now have GPL v2 code that can't be linked to GPL v3 code. So, when a package is GPL licensed, for me it can create more contemplation about whether the package is worth dealing with or not. If the package is large, well-maintained, and standalone, and I'm just planning on being a user, the fact that it's GPL-licensed is not at all a negative. If I'm looking at two roughly equivalent programming toolkits, I will take the BSD/MIT one any day, because I know that when I learn it, I "own" it to the extent that I can use it on anything I want in any fashion in the future. Regards, Pat From dasacc22 at gmail.com Sat May 8 13:19:16 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sat, 8 May 2010 10:19:16 -0700 (PDT) Subject: Fastest way to calculate leading whitespace Message-ID: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Hi This is a simple question. I'm looking for the fastest way to calculate the leading whitespace (as a string, ie ' '). Here are some different methods I have tried so far --- solution 1 a = ' some content\n' b = a.strip() c = ' '*(len(a)-len(b)) --- solution 2 a = ' some content\n' b = a.strip() c = a.partition(b[0])[0] --- solution 3 def get_leading_whitespace(s): def _get(): for x in s: if x != ' ': break yield x return ''.join(_get()) --- Solution 1 seems to be about as fast as solution 2 except in certain circumstances where the value of b has already been determined for other purposes. Solution 3 is slower due to the function overhead. Curious to see what other types of solutions people might have. Thanks, Daniel From shashank.sunny.singh at gmail.com Sat May 8 13:33:39 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Sat, 8 May 2010 23:03:39 +0530 Subject: Fastest way to calculate leading whitespace In-Reply-To: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: On Sat, May 8, 2010 at 10:49 PM, dasacc22 wrote: > Hi > > This is a simple question. I'm looking for the fastest way to > calculate the leading whitespace (as a string, ie ' '). > > Here are some different methods I have tried so far > --- solution 1 > > a = ' some content\n' > b = a.strip() > c = ' '*(len(a)-len(b)) > use lstrip if you want to remove leading whitespaces only. strip removes trailing white spaces too > > --- solution 2 > > a = ' some content\n' > b = a.strip() > c = a.partition(b[0])[0] > > --- solution 3 > > def get_leading_whitespace(s): > def _get(): > for x in s: > if x != ' ': > break > yield x > return ''.join(_get()) > why do you need a generator (and as you mentioned the extra function call overheads)? How about this? def get_leading_whitespaces(s): count = 0 for c in s: if c != ' ': break count += 1 return ' ' * count > > --- > > Solution 1 seems to be about as fast as solution 2 except in certain > circumstances where the value of b has already been determined for > other purposes. Solution 3 is slower due to the function overhead. > > Curious to see what other types of solutions people might have. > > Thanks, > Daniel > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From dasacc22 at gmail.com Sat May 8 13:48:06 2010 From: dasacc22 at gmail.com (Daniel Skinner) Date: Sat, 8 May 2010 12:48:06 -0500 Subject: Fastest way to calculate leading whitespace In-Reply-To: References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: That solution actually runs slower then the generator method. On Sat, May 8, 2010 at 12:33 PM, Shashank Singh < shashank.sunny.singh at gmail.com> wrote: > > > On Sat, May 8, 2010 at 10:49 PM, dasacc22 wrote: > >> Hi >> >> This is a simple question. I'm looking for the fastest way to >> calculate the leading whitespace (as a string, ie ' '). >> >> Here are some different methods I have tried so far >> --- solution 1 >> >> a = ' some content\n' >> b = a.strip() >> c = ' '*(len(a)-len(b)) >> > > use lstrip if you want to remove leading whitespaces only. > strip removes trailing white spaces too > >> >> --- solution 2 >> >> a = ' some content\n' >> b = a.strip() >> c = a.partition(b[0])[0] >> >> --- solution 3 >> >> def get_leading_whitespace(s): >> def _get(): >> for x in s: >> if x != ' ': >> break >> yield x >> return ''.join(_get()) >> > > why do you need a generator (and as you mentioned the extra function call > overheads)? > > How about this? > > def get_leading_whitespaces(s): > count = 0 > for c in s: > if c != ' ': break > count += 1 > return ' ' * count > > >> >> --- >> >> Solution 1 seems to be about as fast as solution 2 except in certain >> circumstances where the value of b has already been determined for >> other purposes. Solution 3 is slower due to the function overhead. >> >> Curious to see what other types of solutions people might have. >> >> Thanks, >> Daniel >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > Regards > Shashank Singh > Senior Undergraduate, Department of Computer Science and Engineering > Indian Institute of Technology Bombay > shashank.sunny.singh at gmail.com > http://www.cse.iitb.ac.in/~shashanksingh > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dasacc22 at gmail.com Sat May 8 13:50:51 2010 From: dasacc22 at gmail.com (Daniel Skinner) Date: Sat, 8 May 2010 12:50:51 -0500 Subject: Fastest way to calculate leading whitespace In-Reply-To: References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: sorry, my mistake it runs faster (looking at the wrong line of code). But the first two solutions are still faster. On Sat, May 8, 2010 at 12:48 PM, Daniel Skinner wrote: > That solution actually runs slower then the generator method. > > > On Sat, May 8, 2010 at 12:33 PM, Shashank Singh < > shashank.sunny.singh at gmail.com> wrote: > >> >> >> On Sat, May 8, 2010 at 10:49 PM, dasacc22 wrote: >> >>> Hi >>> >>> This is a simple question. I'm looking for the fastest way to >>> calculate the leading whitespace (as a string, ie ' '). >>> >>> Here are some different methods I have tried so far >>> --- solution 1 >>> >>> a = ' some content\n' >>> b = a.strip() >>> c = ' '*(len(a)-len(b)) >>> >> >> use lstrip if you want to remove leading whitespaces only. >> strip removes trailing white spaces too >> >>> >>> --- solution 2 >>> >>> a = ' some content\n' >>> b = a.strip() >>> c = a.partition(b[0])[0] >>> >>> --- solution 3 >>> >>> def get_leading_whitespace(s): >>> def _get(): >>> for x in s: >>> if x != ' ': >>> break >>> yield x >>> return ''.join(_get()) >>> >> >> why do you need a generator (and as you mentioned the extra function call >> overheads)? >> >> How about this? >> >> def get_leading_whitespaces(s): >> count = 0 >> for c in s: >> if c != ' ': break >> count += 1 >> return ' ' * count >> >> >>> >>> --- >>> >>> Solution 1 seems to be about as fast as solution 2 except in certain >>> circumstances where the value of b has already been determined for >>> other purposes. Solution 3 is slower due to the function overhead. >>> >>> Curious to see what other types of solutions people might have. >>> >>> Thanks, >>> Daniel >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> >> -- >> Regards >> Shashank Singh >> Senior Undergraduate, Department of Computer Science and Engineering >> Indian Institute of Technology Bombay >> shashank.sunny.singh at gmail.com >> http://www.cse.iitb.ac.in/~shashanksingh >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Sat May 8 13:59:03 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 10:59:03 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: <5b36caaf-f1d6-47a5-ae0c-b11b0f3078b9@l28g2000yqd.googlegroups.com> On May 8, 12:19?pm, dasacc22 wrote: > Hi > > This is a simple question. I'm looking for the fastest way to > calculate the leading whitespace (as a string, ie ' ? ?'). > > Here are some different methods I have tried so far > --- solution 1 > > a = ' ? ?some content\n' > b = a.strip() > c = ' '*(len(a)-len(b)) > > --- solution 2 > > a = ' ? ?some content\n' > b = a.strip() > c = a.partition(b[0])[0] > > --- solution 3 > > def get_leading_whitespace(s): > ? ? def _get(): > ? ? ? ? for x in s: > ? ? ? ? ? ? if x != ' ': > ? ? ? ? ? ? ? ? break > ? ? ? ? ? ? yield x > ? ? return ''.join(_get()) > > --- > > Solution 1 seems to be about as fast as solution 2 except in certain > circumstances where the value of b has already been determined for > other purposes. Solution 3 is slower due to the function overhead. > > Curious to see what other types of solutions people might have. > > Thanks, > Daniel Well, you could try a solution using re, but that's probably only likely to be faster if you can use it on multiple concatenated lines. I usually use something like your solution #1. One thing to be aware of, though, is that strip() with no parameters will strip *any* whitespace, not just spaces, so the implicit assumption in your code that what you have stripped is spaces may not be justified (depending on the source data). OTOH, depending on how you use that whitespace information, it may not really matter. But if it does matter, you can use strip(' ') If speed is really an issue for you, you could also investigate mxtexttools, but, like re, it might perform better if the source consists of several batched lines. Regards, Pat From dasacc22 at gmail.com Sat May 8 14:16:49 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sat, 8 May 2010 11:16:49 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <5b36caaf-f1d6-47a5-ae0c-b11b0f3078b9@l28g2000yqd.googlegroups.com> Message-ID: On May 8, 12:59?pm, Patrick Maupin wrote: > On May 8, 12:19?pm, dasacc22 wrote: > > > > > > > Hi > > > This is a simple question. I'm looking for the fastest way to > > calculate the leading whitespace (as a string, ie ' ? ?'). > > > Here are some different methods I have tried so far > > --- solution 1 > > > a = ' ? ?some content\n' > > b = a.strip() > > c = ' '*(len(a)-len(b)) > > > --- solution 2 > > > a = ' ? ?some content\n' > > b = a.strip() > > c = a.partition(b[0])[0] > > > --- solution 3 > > > def get_leading_whitespace(s): > > ? ? def _get(): > > ? ? ? ? for x in s: > > ? ? ? ? ? ? if x != ' ': > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? yield x > > ? ? return ''.join(_get()) > > > --- > > > Solution 1 seems to be about as fast as solution 2 except in certain > > circumstances where the value of b has already been determined for > > other purposes. Solution 3 is slower due to the function overhead. > > > Curious to see what other types of solutions people might have. > > > Thanks, > > Daniel > > Well, you could try a solution using re, but that's probably only > likely to be faster if you can use it on multiple concatenated lines. > I usually use something like your solution #1. ?One thing to be aware > of, though, is that strip() with no parameters will strip *any* > whitespace, not just spaces, so the implicit assumption in your code > that what you have stripped is spaces may not be justified (depending > on the source data). ?OTOH, depending on how you use that whitespace > information, it may not really matter. ?But if it does matter, you can > use strip(' ') > > If speed is really an issue for you, you could also investigate > mxtexttools, but, like re, it might perform better if the source > consists of several batched lines. > > Regards, > Pat Hi, thanks for the info. Using .strip() to remove all whitespace in solution 1 is a must. If you only stripped ' ' spaces then line endings would get counted in the len() call and when multiplied against ' ', would produce an inaccurate result. Regex is significantly slower for my purposes but ive never heard of mxtexttools. Even if it proves slow its spurred my curiousity as to what functionality it provides (on an unrelated note) From mmanns at gmx.net Sat May 8 14:43:45 2010 From: mmanns at gmx.net (Martin Manns) Date: Sat, 8 May 2010 20:43:45 +0200 Subject: [ANN] Pyspread 0.1.1 released Message-ID: Pyspread 0.1.1 released ======================= I am pleased to announce the new release 0.1.1 of pyspread. About: ------ Pyspread is a cross-platform Python spreadsheet application. It is based on and written in the programming language Python. Instead of spreadsheet formulas, Python expressions are entered into the spreadsheet cells. Each expression returns a Python object that can be accessed from other cells. These objects can represent anything including lists or matrices. Pyspread runs on Linux and *nix platforms with GTK support as well as on Windows (XP and Vista tested). On Mac OS X, some icons are too small but the application basically works. Homepage -------- http://pyspread.sourceforge.net Changes to 0.1 -------------- * Grid is faster. * Copying only partly filled cells works now. * Cells that get attributes but no string no longer display None. Enjoy Martin From steve at REMOVE-THIS-cybersource.com.au Sat May 8 14:46:26 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 18:46:26 GMT Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: <4be5b182$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 10:19:16 -0700, dasacc22 wrote: > Hi > > This is a simple question. I'm looking for the fastest way to calculate > the leading whitespace (as a string, ie ' '). Is calculating the amount of leading whitespace really the bottleneck in your application? If not, then trying to shave off microseconds from something which is a trivial part of your app is almost certainly a waste of your time. [...] > a = ' some content\n' > b = a.strip() > c = ' '*(len(a)-len(b)) I take it that you haven't actually tested this code for correctness, because it's buggy. Let's test it: >>> leading_whitespace = " "*2 + "\t"*2 >>> a = leading_whitespace + "some non-whitespace text\n" >>> b = a.strip() >>> c = " "*(len(a)-len(b)) >>> assert c == leading_whitespace Traceback (most recent call last): File "", line 1, in AssertionError Not only doesn't it get the whitespace right, but it doesn't even get the *amount* of whitespace right: >>> assert len(c) == len(leading_whitespace) Traceback (most recent call last): File "", line 1, in AssertionError It doesn't even work correctly if you limit "whitespace" to mean spaces and nothing else! It's simply wrong in every possible way. This is why people say that premature optimization is the root of all (programming) evil. Instead of wasting time and energy trying to optimise code, you should make it correct first. Your solutions 2 and 3 are also buggy. And solution 3 can be easily re- written to be more straightforward. Instead of the complicated: > def get_leading_whitespace(s): > def _get(): > for x in s: > if x != ' ': > break > yield x > return ''.join(_get()) try this version: def get_leading_whitespace(s): accumulator = [] for c in s: if c in ' \t\v\f\r\n': accumulator.append(c) else: break return ''.join(accumulator) Once you're sure this is correct, then you can optimise it: def get_leading_whitespace(s): t = s.lstrip() return s[:len(s)-len(t)] >>> c = get_leading_whitespace(a) >>> assert c == leading_whitespace >>> Unless your strings are very large, this is likely to be faster than any other pure-Python solution you can come up with. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 8 14:47:32 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 18:47:32 GMT Subject: shortcut for large amount of global var declarations? References: Message-ID: <4be5b1c4$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 10:08:08 -0400, Alex Hall wrote: > Hi all, > I am sorry if this is the second message about this you get; I typed > this and hit send (on gmail website) but I got a 404 error, so I am not > sure if the previous message made it out or not. Anyway, I have about > fifteen vars in a function which have to be global. Is there a faster > and more space-efficient way of doing this than putting each var on its > own line; that is, fifteen "global varName" declarations? Thanks. global google, for_, global_, variables, considered, harmful -- Steven From dluzius at comcast.net Sat May 8 14:52:33 2010 From: dluzius at comcast.net (Dave Luzius) Date: Sat, 08 May 2010 18:52:33 GMT Subject: Need help with my 1st python program Message-ID: Pleaser help me with this. Here's a copy of the program, but it keeps calling for me to define pressure. # A small program to fetch local barometer reading from weather.com # and convert the value from metric to imperial. # My first attempt at Python. #-------------------------------------------------------------------- import urllib # next line does the fetching urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", pressure) # next line does the conversion to imperial imppress = 0.029875 * float(pressure) # next line shows the results. print imppress as you can see, I'm stuck on what should be relatively simple. TIA, Dave From benjamin at python.org Sat May 8 14:56:01 2010 From: benjamin at python.org (Benjamin Peterson) Date: Sat, 8 May 2010 13:56:01 -0500 Subject: [RELEASED] Python 2.7 beta 2 Message-ID: On behalf of the Python development team, I'm elated to announce the second beta release of Python 2.7. Python 2.7 is scheduled (by Guido and Python-dev) to be the last major version in the 2.x series. 2.7 will have an extended period of bugfix maintenance. 2.7 includes many features that were first released in Python 3.1. The faster io module, the new nested with statement syntax, improved float repr, set literals, dictionary views, and the memoryview object have been backported from 3.1. Other features include an ordered dictionary implementation, unittests improvements, a new sysconfig module, and support for ttk Tile in Tkinter. For a more extensive list of changes in 2.7, see http://doc.python.org/dev/whatsnew/2.7.html or Misc/NEWS in the Python distribution. To download Python 2.7 visit: http://www.python.org/download/releases/2.7/ While this is a development release and is thus not suitable for production use, we encourage Python application and library developers to test the release with their code and report any bugs they encounter to: http://bugs.python.org/ 2.7 documentation can be found at: http://docs.python.org/2.7/ Enjoy! -- Benjamin Peterson 2.7 Release Manager benjamin at python.org (on behalf of the entire python-dev team and 2.7's contributors) From steve at REMOVE-THIS-cybersource.com.au Sat May 8 14:58:41 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 18:58:41 GMT Subject: ConfigParser.get() defaults? References: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4be5b460$0$27798$c3e8da3@news.astraweb.com> On Fri, 07 May 2010 20:46:47 -0500, Tim Chase wrote: > On 05/07/2010 07:56 PM, Steven D'Aprano wrote: >> On Fri, 07 May 2010 15:05:53 -0500, Tim Chase wrote: >>> With a normal dictionary, I can specify a default fallback value in >>> the event the requested key isn't present: >> [...] >>> However, with the ConfigParser object, there doesn't seem to be any >>> way to do a similar >> >> Sounds like a nice feature to have. When you submit a patch (*grin*), > > I'm game to create and provide a patch, though I've had no success in > the past trying to push tweaks into the Python Core (adding a subclass > of optparse.HelpFormatter that respects newlines for text-wrapping). If your patch doesn't attract the interest of a Python-Dev developer, you might need to give them a prod occasionally. Their time for reviewing bugs and patches is always in short supply. > But if there's a straightforward way to do this, I'd love to patch the > file and submit the deltas. I just need to know > > - what sort of patch (unified diff, context diff, ed) > > - against which version? I'm currently running the 2.5 that Debian > Testing defaults to, though I have 2.6 available through my repository. > > - any tests needed/expected? run how? internal as an "if __name__ == > '__main__'" block, or an external test suite? > > - where (or to whom) to I submit the patch (and possibly tests) Submit the patch and tests to the bug tracker at http://bugs.python.org/ Look at the tests in (e.g.) /usr/local/lib/python2.6/test/ for an idea of what you should do. Because this is a new feature, and 2.5 (and 2.6?) are in bug fix only mode, you should probably aim for 2.7 or 3.2 as the ideal. Patches written against 2.6 or 3.1 are probably good enough though. And you want a unified diff. See also: http://www.python.org/dev/patches/ >> please make sure the caller can specify what to do on missing section >> and missing option independently. > > Could you detail what you envision here? For my use case, it's that the > option doesn't exist, whether because there's no section, or there's a > section but no option. Either way, something failed and I want a > default value back. I don't have a mental model of what you expect in > the "section exists but no option" that would behave differently from > the "section doesn't exist" case. > > Do you also have suggestions for how it should interact with the weird > [DEFAULT] section oddities (that don't really seem to default the way I > expect them to)? > > Perhaps the two interrelate? I haven't really given it any detailed thought, but what I was thinking was something like: config.set_missing_section("FOO") config.set_missing_value("missing") Then if you ask for the value of key 'x' in section BAR, and BAR doesn't exist, then 'x' is looked up in FOO instead; if 'x' doesn't exist there either, then "missing" is returned. If section BAR *does* exist, but 'x' doesn't, then "missing" is also returned. >>> I've thumbed through the source to ConfigParser.py but don't see any >>> indication that it's possible to do what I'd like short of wrapping >>> all my cp.get*() calls in try/except blocks or creating a forked >>> version of ConfigParser.py locally. Is there anything I'm missing, or >>> a better workaround to this? >> >> Don't fork the source code, that's ridiculously overkill. Subclass >> ConfigParser and add the required functionality. > > Sorry for such loaded terms -- my "forking" suggestion wasn't intended > to be Python, the Tim Version(tm), but rather, "copy the ConfigParser.py > into my project directory, make the edits I need/want, and have it > available to my project" (something similar to what I did for one of my > projects copying in the python2.6 zipfile.py to my python2.4 code-base > to supersede the standard 2.4 library's zipfile.py). That's what I thought you meant. Forking is the right term in this case (you are forking the ConfigParser module, not all of Python), and I still say it is overkill. Generally speaking, when a module doesn't do what you want, and modifying it isn't an option, there are five things you can do. In order of decreasing desirability: (1) Write a small wrapper function to tweak the behaviour. (2) Sub-class the class to gain new behaviour. (3) Monkey-patch the module at runtime. (4) Fork the module and modify that. (5) Re-write the whole thing from scratch. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 8 15:02:42 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 19:02:42 GMT Subject: Need help with my 1st python program References: Message-ID: <4be5b552$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 18:52:33 +0000, Dave Luzius wrote: > Pleaser help me with this. Here's a copy of the program, but it keeps > calling for me to define pressure. That's because you haven't defined pressure. When Python tells you there is a bug in your program, it is almost always correct. > # A small program to fetch local barometer reading from weather.com > # and convert the value from metric to imperial. > # My first attempt at Python. > #-------------------------------------------------------------------- > import urllib > > # next line does the fetching > urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", > pressure) What is pressure? It is an undefined name. Where does pressure get its value from? -- Steven From dluzius at comcast.net Sat May 8 15:13:12 2010 From: dluzius at comcast.net (Dave Luzius) Date: Sat, 08 May 2010 19:13:12 GMT Subject: Need help with my 1st python program References: <4be5b552$0$27798$c3e8da3@news.astraweb.com> Message-ID: On Sat, 08 May 2010 19:02:42 +0000, Steven D'Aprano wrote: > On Sat, 08 May 2010 18:52:33 +0000, Dave Luzius wrote: > >> Pleaser help me with this. Here's a copy of the program, but it keeps >> calling for me to define pressure. > > That's because you haven't defined pressure. > > When Python tells you there is a bug in your program, it is almost > always correct. > > >> # A small program to fetch local barometer reading from weather.com # >> and convert the value from metric to imperial. # My first attempt at >> Python. >> #-------------------------------------------------------------------- >> import urllib >> >> # next line does the fetching >> urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", >> pressure) > > What is pressure? It is an undefined name. Where does pressure get its > value from? Pressure is a term for barometric pressure, and is understood by Conky, which this program is designed to work with, and is understood by weather.com. But the value it passes to conky is metric, and I want it to display in imperial. What should I do.... From wolfram.hinderer at googlemail.com Sat May 8 15:15:22 2010 From: wolfram.hinderer at googlemail.com (Wolfram Hinderer) Date: Sat, 8 May 2010 12:15:22 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: On 8 Mai, 20:46, Steven D'Aprano wrote: > def get_leading_whitespace(s): > ? ? t = s.lstrip() > ? ? return s[:len(s)-len(t)] > > >>> c = get_leading_whitespace(a) > >>> assert c == leading_whitespace > > Unless your strings are very large, this is likely to be faster than any > other pure-Python solution you can come up with. Returning s[:-1 - len(t)] is faster. From wb4REMOVE_THIS_TEXT at wbrameld4.name Sat May 8 15:35:37 2010 From: wb4REMOVE_THIS_TEXT at wbrameld4.name (Walter Brameld IV) Date: Sat, 08 May 2010 15:35:37 -0400 Subject: Need help with my 1st python program In-Reply-To: References: <4be5b552$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4BE5BD09.2020908@wbrameld4.name> Dave Luzius wrote: > On Sat, 08 May 2010 19:02:42 +0000, Steven D'Aprano wrote: > >> On Sat, 08 May 2010 18:52:33 +0000, Dave Luzius wrote: >> >>> Pleaser help me with this. Here's a copy of the program, but it keeps >>> calling for me to define pressure. >> That's because you haven't defined pressure. >> >> When Python tells you there is a bug in your program, it is almost >> always correct. >> >> >>> # A small program to fetch local barometer reading from weather.com # >>> and convert the value from metric to imperial. # My first attempt at >>> Python. >>> #-------------------------------------------------------------------- >>> import urllib >>> >>> # next line does the fetching >>> urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", >>> pressure) >> What is pressure? It is an undefined name. Where does pressure get its >> value from? > > Pressure is a term for barometric pressure, and is understood by Conky, > which this program is designed to work with, and is understood by > weather.com. But the value it passes to conky is metric, and I want it to > display in imperial. > > What should I do.... You're passing in the value of pressure as the 'data' parameter to urllib.urlopen. So...what is the value of pressure? You haven't assigned any value to it before calling urlopen. Therein lies the problem. From steve at REMOVE-THIS-cybersource.com.au Sat May 8 15:38:52 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 19:38:52 GMT Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 10:14:18 -0700, Patrick Maupin wrote: > On May 8, 3:37?am, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 07 May 2010 23:40:22 -0700, Patrick Maupin wrote: >> > Personally, I believe that if anything is false and misleading, it is >> > the attempt to try to completely change the discussion from MIT vs. >> > GPL to GPL vs. no license (and thus very few rights for the software >> > users), after first trying to imply that people who distribute >> > software under permissive licenses (that give the user *more* rights >> > than the GPL) are somehow creating a some sort of moral hazard that >> > might adversely affect their users >> >> If encouraging third parties to take open source code and lock it up >> behind proprietary, closed licences *isn't* a moral hazard, then I >> don't know what one is. > > For a start, there is a difference between "encouraging" and "allowing". Finely parsed semantics with a meaningless difference when applied to what I said in the context of comparing GPL vs. more permissive licenses. > But in point of fact, you have it exactly backwards. Putting the code > out there and making it a tort to republish it under a closed license > creates a moral hazard -- a trap that many companies including > Linksys/Cisco have fallen into. What? That's crazy talk. You think Linksys and Cisco don't have people capable of reading licences? What sort of two-bit organisation do you think they are? They have lawyers, they have people whose job it is to make sure that they don't infringe other people's copyright. They wouldn't use software copyrighted by Microsoft without making sure they were legally licenced. One can only wonder why they thought they didn't need to treat the GPL with an equal amount of respect. Since you raised the analogy of a restaurant giving away freebies, if a restaurant stuck a sign on the door saying "Free softdrink with every burger", and some Cisco engineer walked in the door and started loading up a trolley with cans of drink from the fridge ("they're free, right?"), would you argue that this was the restaurant's fault for creating a moral hazard? I don't think you understand what a moral hazard is. Under no circumstances is it a moral hazard to say "If you do X, I will do Y" -- in this case, "If you obey these restrictions on redistribution, I'll licence this copyrighted work to you". Perhaps you should check the definition before arguing further that the GPL imposes a moral hazard on anyone: http://en.wikipedia.org/wiki/Moral_hazard > If I expect nothing in return, if it's > a gift, then the likelihood of moral hazard is significantly reduced. > Unless you are somehow suggesting that I owe my user's customers > anything (which suggestion, btw, is frequently made in veiled terms, and > always pisses me off), there is no other moral hazard produced by me > choosing a permissive license for my code. No, you don't *owe* them anything, but this brings us back to Ben's original post. If you care about the freedoms of Cisco's customers as much as you care about the freedoms of Cisco, then that's a good reason to grant those customers the same rights as you granted Cisco. And let's not forget self-interest -- if you care about *your own freedoms*, then it is in your own self-interest to encourage others to use open licences rather than closed ones. The MIT licence merely encourages openness by example, while the GPL makes it a legal requirement. Which brings us back full circle to Ben's position, which you took exception to. If the global freedoms granted by the GPL are sufficiently important to you, then you should use the GPL. If you have other factors which are more important, then choose another licence. Why you considered this controversial enough to require sarcastic comments about the untrustworthiness of Guido and the PSF, I don't know. -- Steven From benjamin.kaplan at case.edu Sat May 8 15:41:26 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 8 May 2010 15:41:26 -0400 Subject: Need help with my 1st python program In-Reply-To: References: <4be5b552$0$27798$c3e8da3@news.astraweb.com> Message-ID: On Sat, May 8, 2010 at 3:13 PM, Dave Luzius wrote: > > Pressure is a term for barometric pressure, and is understood by Conky, > which this program is designed to work with, and is understood by > weather.com. But the value it passes to conky is metric, and I want it to > display in imperial. > > What should I do.... > -- Don't tell us what pressure is. Tell Python. >>> urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", pressure) What do you think this line does? Because it does absolutely nothing. Assuming pressure is defined It creates a file-like object connected to that URL. But because that file-like object is never assigned to anything, it's reference count drops to 0 and it's immediately closed and deleted. You have to 1) Assign the file-like object to some name. 2) Read the data from the file-like object 3) convert the string you read from the file-like object into a float 4) use the float to do math Python is succinct, but it isn't magic. Just like every other programming language, it can't guess what you want it to do. From steve at REMOVE-THIS-cybersource.com.au Sat May 8 15:42:24 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 19:42:24 GMT Subject: Need help with my 1st python program References: <4be5b552$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4be5be9f$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 19:13:12 +0000, Dave Luzius wrote: >> What is pressure? It is an undefined name. Where does pressure get its >> value from? > > Pressure is a term for barometric pressure, and is understood by Conky, > which this program is designed to work with, and is understood by > weather.com. But the value it passes to conky is metric, and I want it > to display in imperial. I know what pressure is in English. What is it in your program? When the Python compiler sees the word "pressure", what do you expect it to do? > What should I do.... Perhaps you should start with a few simple tutorials and introductions to programming before tackling this program. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 8 15:46:56 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 19:46:56 GMT Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 12:15:22 -0700, Wolfram Hinderer wrote: > On 8 Mai, 20:46, Steven D'Aprano > wrote: > >> def get_leading_whitespace(s): >> ? ? t = s.lstrip() >> ? ? return s[:len(s)-len(t)] >> >> >>> c = get_leading_whitespace(a) >> >>> assert c == leading_whitespace >> >> Unless your strings are very large, this is likely to be faster than >> any other pure-Python solution you can come up with. > > Returning s[:-1 - len(t)] is faster. I'm sure it is. Unfortunately, it's also incorrect. >>> z = "*****abcde" >>> z[:-1-5] '****' >>> z[:len(z)-5] '*****' However, s[:-len(t)] should be both faster and correct. -- Steven From vincent at vincentdavis.net Sat May 8 15:49:49 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Sat, 8 May 2010 13:49:49 -0600 Subject: Need help with my 1st python program In-Reply-To: <4BE5BD09.2020908@wbrameld4.name> References: <4be5b552$0$27798$c3e8da3@news.astraweb.com> <4BE5BD09.2020908@wbrameld4.name> Message-ID: I think what is not clear by what is being said is that you have passed in pressure and not 'pressure'. The first is undefined, pressure = 1 would define it. Where as 'pressure' is a string type. On Sat, May 8, 2010 at 1:35 PM, Walter Brameld IV < wb4REMOVE_THIS_TEXT at wbrameld4.name> wrote: > Dave Luzius wrote: > >> On Sat, 08 May 2010 19:02:42 +0000, Steven D'Aprano wrote: >> >> On Sat, 08 May 2010 18:52:33 +0000, Dave Luzius wrote: >>> >>> Pleaser help me with this. Here's a copy of the program, but it keeps >>>> calling for me to define pressure. >>>> >>> That's because you haven't defined pressure. >>> >>> When Python tells you there is a bug in your program, it is almost >>> always correct. >>> >>> >>> # A small program to fetch local barometer reading from weather.com # >>>> and convert the value from metric to imperial. # My first attempt at >>>> Python. >>>> #-------------------------------------------------------------------- >>>> import urllib >>>> >>>> # next line does the fetching >>>> urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", >>>> pressure) >>>> >>> What is pressure? It is an undefined name. Where does pressure get its >>> value from? >>> >> >> Pressure is a term for barometric pressure, and is understood by Conky, >> which this program is designed to work with, and is understood by >> weather.com. But the value it passes to conky is metric, and I want it to >> display in imperial. >> >> What should I do.... >> > > You're passing in the value of pressure as the 'data' parameter to > urllib.urlopen. So...what is the value of pressure? You haven't assigned > any value to it before calling urlopen. Therein lies the problem. > > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Sat May 8 16:05:21 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 13:05:21 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> Message-ID: <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> On May 8, 2:38?pm, Steven D'Aprano wrote: > I don't think you understand what a moral hazard is. Under no > circumstances is it a moral hazard to say "If you do X, I will do Y" -- > in this case, "If you obey these restrictions on redistribution, I'll > licence this copyrighted work to you". Perhaps you should check the > definition before arguing further that the GPL imposes a moral hazard on > anyone: > > http://en.wikipedia.org/wiki/Moral_hazard Well, definition is a tricky thing. Note that the wikipedia article is disputed. One definition of moral hazard is "The tendency of a person or entity that is imperfectly monitored to engage in undesirable behavior." Under this definition, Linksys apparently thought that the imperfect monitoring would let it get away with GPL violations. Certainly, even if Linksys as a corporation wasn't trying to get away with anything, their employees were improperly monitored, and getting a product out was more important than any potential copyright violation at the time (which shows there was a moral hazard their employees took advantage of under either the definition I gave or the wikipedia definition.) There are probably other companies (or employees of those companies) getting away with GPL violations right now -- certainly the risk of discovery if you just use a small portion of GPL code and don't distribute your source must be very small. There are certainly fewer companies getting away with MIT license violations, simply because the license is so much harder to violate. > > If I expect nothing in return, if it's > > a gift, then the likelihood of moral hazard is significantly reduced. > > Unless you are somehow suggesting that I owe my user's customers > > anything (which suggestion, btw, is frequently made in veiled terms, and > > always pisses me off), there is no other moral hazard produced by me > > choosing a permissive license for my code. > > No, you don't *owe* them anything, but this brings us back to Ben's > original post. If you care about the freedoms of Cisco's customers as > much as you care about the freedoms of Cisco, then that's a good reason > to grant those customers the same rights as you granted Cisco. But I *do* grant them the same rights -- they can come to my site and download my software!!! > And let's not forget self-interest -- if you care about *your own > freedoms*, then it is in your own self-interest to encourage others to > use open licences rather than closed ones. The MIT licence merely > encourages openness by example, while the GPL makes it a legal > requirement. But I *do* care about my own freedom. I thought I made that crystal clear. If I produce something under the MIT license, it's because I want to give it away with no strings. If I produce something under the GPL (that's not merely a small addendum to a preexisting project), it's probably going to be because I think it's pretty valuable stuff, maybe even valuable enough I might be able to make some money with it. If I'm going to use any prebuilt components, those *can't* be licensed under the GPL if I want to deliver the final package under the MIT license. Even if I'm using the GPL for my valuable software, my monetization options are more limited if I use a third party component that is licensed under the GPL, because I now don't have the viable option of dual-licensing. So, that gets back to my argument about what I like to see in a package I use, and how I license things according to what I would like see. For me, the golden rule dictates that when I give a gift of software, I release it under a permissive license. I realize that others see this differently. > Which brings us back full circle to Ben's position, which you took > exception to. If the global freedoms granted by the GPL are sufficiently > important to you, then you should use the GPL. If you have other factors > which are more important, then choose another licence. Why you considered > this controversial enough to require sarcastic comments about the > untrustworthiness of Guido and the PSF, I don't know. To me, the clear implication of the blanket statement that you have to use the GPL if you care at all about users is that anybody who doesn't use the GPL is uncaring. I think that's a silly attitude, and will always use any tool at hand, including sarcasm, to point out when other people try to impose their own narrow sense of morality on others by painting what I perceive to be perfectly normal, moral, decent, and legal behavior as somehow detrimental to the well-being of the species (honestly -- ebola???) Regards, Pat From rolf.oltmans at gmail.com Sat May 8 16:41:44 2010 From: rolf.oltmans at gmail.com (Oltmans) Date: Sat, 8 May 2010 13:41:44 -0700 (PDT) Subject: Kindly show me a better way to do it Message-ID: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Hi, I've a list that looks like following a = [ [1,2,3,4], [5,6,7,8] ] Currently, I'm iterating through it like for i in [k for k in a]: for a in i: print a but I was wondering if there is a shorter, more elegant way to do it? From python.list at tim.thechases.com Sat May 8 16:41:55 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 08 May 2010 15:41:55 -0500 Subject: ConfigParser.get() defaults? In-Reply-To: <4be5b460$0$27798$c3e8da3@news.astraweb.com> References: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> <4be5b460$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4BE5CC93.9060700@tim.thechases.com> On 05/08/2010 01:58 PM, Steven D'Aprano wrote: > If your patch doesn't attract the interest of a Python-Dev > developer, you might need to give them a prod occasionally. > Their time for reviewing bugs and patches is always in short > supply. > >> - where (or to whom) to I submit the patch (and possibly >> tests) > > Submit the patch and tests to the bug tracker at > http://bugs.python.org/ Okay -- a good first stop, and vastly more helpful than the non-reply I got regarding my optparse patch. >> - any tests needed/expected? run how? internal as an "if >> __name__ == '__main__'" block, or an external test suite? >> > Look at the tests in (e.g.) /usr/local/lib/python2.6/test/ for > an idea of what you should do. I poked in my Debian analogue (/usr/bin/lib/python2.6/test/) but the tests there seemed a bit...um...lacking? There was nothing testing ConfigParser at all, just three high-level test modules. Granted, I could create some tests that exercise my code, and perhaps some that should have been there in the first place, but that's a big jump from merely adding a couple tests (non)existing ConfigParser tests. > Because this is a new feature, and 2.5 (and 2.6?) are in bug fix only > mode, you should probably aim for 2.7 or 3.2 as the ideal. Patches > written against 2.6 or 3.1 are probably good enough though. Okay, I've submitted the patch to dev.python.org in the hopes something comes of it, even if it's 2.7 or 3.2 > That's what I thought you meant. Forking is the right term in this case > (you are forking the ConfigParser module, not all of Python), and I still > say it is overkill. Generally speaking, when a module doesn't do what you > want, and modifying it isn't an option, there are five things you can do. > In order of decreasing desirability: > > (1) Write a small wrapper function to tweak the behaviour. > > (2) Sub-class the class to gain new behaviour. > > (3) Monkey-patch the module at runtime. > > (4) Fork the module and modify that. > > (5) Re-write the whole thing from scratch. I'd say the ordering of your #3 and #4 are more ambiguous -- if I'm distributing/deploying a project and my monkey-patching gets broken (there's a reason monkey-patching feels dirty) by some python lib upgrade external to my control, then I & my code look bad. If I freeze a modified/locally-forked library module, it continues to work regardless of the environment. Maybe that's an indicator that I did a bad job of monkey patching, but I prefer to prevent breakage where I can. -tkc From dickinsm at gmail.com Sat May 8 16:46:59 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 May 2010 13:46:59 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> Message-ID: <489ffaa0-1563-45a1-93aa-cc83cdd6abd9@j35g2000yqm.googlegroups.com> On May 8, 8:46?pm, Steven D'Aprano wrote: > On Sat, 08 May 2010 12:15:22 -0700, Wolfram Hinderer wrote: > > On 8 Mai, 20:46, Steven D'Aprano > > wrote: > > >> def get_leading_whitespace(s): > >> ? ? t = s.lstrip() > >> ? ? return s[:len(s)-len(t)] > > >> >>> c = get_leading_whitespace(a) > >> >>> assert c == leading_whitespace > > >> Unless your strings are very large, this is likely to be faster than > >> any other pure-Python solution you can come up with. > > > Returning s[:-1 - len(t)] is faster. > > I'm sure it is. Unfortunately, it's also incorrect. > > >>> z = "*****abcde" > >>> z[:-1-5] > '****' > >>> z[:len(z)-5] > > '*****' > > However, s[:-len(t)] should be both faster and correct. Unless len(t) == 0, surely? -- Mark From utente at esempio.net Sat May 8 16:53:33 2010 From: utente at esempio.net (superpollo) Date: Sat, 08 May 2010 22:53:33 +0200 Subject: Kindly show me a better way to do it In-Reply-To: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> Oltmans ha scritto: > Hi, I've a list that looks like following > > a = [ [1,2,3,4], [5,6,7,8] ] > > Currently, I'm iterating through it like > > for i in [k for k in a]: > for a in i: i think you used te a identifier for two meanings... > print a > > but I was wondering if there is a shorter, more elegant way to do it? add = lambda a,b: a+b for i in reduce(add,a): print i From clp2 at rebertia.com Sat May 8 16:55:30 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 8 May 2010 13:55:30 -0700 Subject: Kindly show me a better way to do it In-Reply-To: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: On Sat, May 8, 2010 at 1:41 PM, Oltmans wrote: > Hi, I've a list that looks like following > > a = [ [1,2,3,4], [5,6,7,8] ] > > Currently, I'm iterating through it like > > for i in [k for k in a]: > ? ? ? ?for a in i: > ? ? ? ? ? ? ? ?print a > > but I was wondering if there is a shorter, more elegant way to do it? Just use a different variable name besides `a` in the nested loop so you don't have to make the copy of `a`. I arbitrarily chose `b`: for i in a: for b in i: print b Cheers, Chris -- http://blog.rebertia.com From utente at esempio.net Sat May 8 16:56:17 2010 From: utente at esempio.net (superpollo) Date: Sat, 08 May 2010 22:56:17 +0200 Subject: Kindly show me a better way to do it In-Reply-To: <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> Message-ID: <4be5cff2$0$815$4fafbaef@reader5.news.tin.it> superpollo ha scritto: > Oltmans ha scritto: >> Hi, I've a list that looks like following >> >> a = [ [1,2,3,4], [5,6,7,8] ] >> >> Currently, I'm iterating through it like >> >> for i in [k for k in a]: >> for a in i: > > i think you used te a identifier for two meanings... > >> print a >> >> but I was wondering if there is a shorter, more elegant way to do it? > > > add = lambda a,b: a+b or: from operator import add > for i in reduce(add,a): > print i From alain at dpt-info.u-strasbg.fr Sat May 8 16:56:25 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sat, 08 May 2010 22:56:25 +0200 Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: <87eihmxgcm.fsf@dpt-info.u-strasbg.fr> Oltmans writes: > a = [ [1,2,3,4], [5,6,7,8] ] > > Currently, I'm iterating through it like > > for i in [k for k in a]: > for a in i: > print a I would prefer: for i in a: for v in i: print v i.e., not messing with a and avoiding an additional list. > but I was wondering if there is a shorter, more elegant way to do it? I can't see any, but if you need to save space, you may use for v in (e for l in a for e in l): ... -- Alain. From tycho at tycho.ws Sat May 8 17:00:47 2010 From: tycho at tycho.ws (Tycho Andersen) Date: Sat, 8 May 2010 16:00:47 -0500 Subject: Kindly show me a better way to do it In-Reply-To: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: On Sat, May 8, 2010 at 3:41 PM, Oltmans wrote: > Hi, I've a list that looks like following > > a = [ [1,2,3,4], [5,6,7,8] ] > > Currently, I'm iterating through it like > > for i in [k for k in a]: > ? ? ? ?for a in i: > ? ? ? ? ? ? ? ?print a > > but I was wondering if there is a shorter, more elegant way to do it? How about itertools? In python 2.6: >>> a = [ [1,2,3,4], [5,6,7,8] ] >>> from itertools import chain >>> for i in chain(*a): ... print i ... 1 2 3 4 5 6 7 8 From rolf.oltmans at gmail.com Sat May 8 17:06:33 2010 From: rolf.oltmans at gmail.com (Oltmans) Date: Sat, 8 May 2010 14:06:33 -0700 (PDT) Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> Message-ID: <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> On May 9, 1:53?am, superpollo wrote: > add = lambda a,b: a+b > for i in reduce(add,a): > ? ? ?print i This is very neat. Thank you. Sounds like magic to me. Can you please explain how does that work? Many thanks again. From gd.usenet at spamfence.net Sat May 8 17:09:06 2010 From: gd.usenet at spamfence.net (=?UTF-8?Q?G=C3=BCnther?= Dietrich) Date: Sat, 08 May 2010 23:09:06 +0200 Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: Tycho Andersen wrote: >On Sat, May 8, 2010 at 3:41 PM, Oltmans wrote: >> Hi, I've a list that looks like following >> >> a = [ [1,2,3,4], [5,6,7,8] ] >> >> Currently, I'm iterating through it like >> >> for i in [k for k in a]: >> ? ? ? ?for a in i: >> ? ? ? ? ? ? ? ?print a >> >> but I was wondering if there is a shorter, more elegant way to do it? > >How about itertools? In python 2.6: > >>>> a = [ [1,2,3,4], [5,6,7,8] ] >>>> from itertools import chain >>>> for i in chain(*a): >... print i >... >1 >2 >3 >4 >5 >6 >7 >8 Why not this way? >>> a = [[1,2,3,4], [5,6,7,8]] >>> for i in a: ... for j in i: ... print(j) ... 1 2 3 4 5 6 7 8 Too simple? Best regards, G?nther From utente at esempio.net Sat May 8 17:10:43 2010 From: utente at esempio.net (superpollo) Date: Sat, 08 May 2010 23:10:43 +0200 Subject: Kindly show me a better way to do it In-Reply-To: <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> Message-ID: <4be5d354$0$815$4fafbaef@reader5.news.tin.it> Oltmans ha scritto: > On May 9, 1:53 am, superpollo wrote: > >> add = lambda a,b: a+b >> for i in reduce(add,a): >> print i > > This is very neat. Thank you. Sounds like magic to me. Can you please > explain how does that work? Many thanks again. > here: http://tinyurl.com/3xpdddd and here: http://tinyurl.com/39kdge5 bye From dasacc22 at gmail.com Sat May 8 17:27:32 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sat, 8 May 2010 14:27:32 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: U presume entirely to much. I have a preprocessor that normalizes documents while performing other more complex operations. Theres nothing buggy about what im doing On May 8, 1:46?pm, Steven D'Aprano wrote: > On Sat, 08 May 2010 10:19:16 -0700, dasacc22 wrote: > > Hi > > > This is a simple question. I'm looking for the fastest way to calculate > > the leading whitespace (as a string, ie ' ? ?'). > > Is calculating the amount of leading whitespace really the bottleneck in > your application? If not, then trying to shave off microseconds from > something which is a trivial part of your app is almost certainly a waste > of your time. > > [...] > > > a = ' ? ?some content\n' > > b = a.strip() > > c = ' '*(len(a)-len(b)) > > I take it that you haven't actually tested this code for correctness, > because it's buggy. Let's test it: > > >>> leading_whitespace = " "*2 + "\t"*2 > >>> a = leading_whitespace + "some non-whitespace text\n" > >>> b = a.strip() > >>> c = " "*(len(a)-len(b)) > >>> assert c == leading_whitespace > > Traceback (most recent call last): > ? File "", line 1, in > AssertionError > > Not only doesn't it get the whitespace right, but it doesn't even get the > *amount* of whitespace right: > > >>> assert len(c) == len(leading_whitespace) > > Traceback (most recent call last): > ? File "", line 1, in > AssertionError > > It doesn't even work correctly if you limit "whitespace" to mean spaces > and nothing else! It's simply wrong in every possible way. > > This is why people say that premature optimization is the root of all > (programming) evil. Instead of wasting time and energy trying to optimise > code, you should make it correct first. > > Your solutions 2 and 3 are also buggy. And solution 3 can be easily re- > written to be more straightforward. Instead of the complicated: > > > def get_leading_whitespace(s): > > ? ? def _get(): > > ? ? ? ? for x in s: > > ? ? ? ? ? ? if x != ' ': > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? yield x > > ? ? return ''.join(_get()) > > try this version: > > def get_leading_whitespace(s): > ? ? accumulator = [] > ? ? for c in s: > ? ? ? ? if c in ' \t\v\f\r\n': > ? ? ? ? ? ? accumulator.append(c) > ? ? ? ? else: > ? ? ? ? ? ? break > ? ? return ''.join(accumulator) > > Once you're sure this is correct, then you can optimise it: > > def get_leading_whitespace(s): > ? ? t = s.lstrip() > ? ? return s[:len(s)-len(t)] > > >>> c = get_leading_whitespace(a) > >>> assert c == leading_whitespace > > Unless your strings are very large, this is likely to be faster than any > other pure-Python solution you can come up with. > > -- > Steven From tycho at tycho.ws Sat May 8 17:40:05 2010 From: tycho at tycho.ws (Tycho Andersen) Date: Sat, 8 May 2010 16:40:05 -0500 Subject: Kindly show me a better way to do it In-Reply-To: References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: On Sat, May 8, 2010 at 4:09 PM, G?nther Dietrich wrote: [snip] > Too simple? No, not at all. I really only intended to point the OP to itertools, because it does lots of useful things exactly like this one. \t From pmaupin at gmail.com Sat May 8 18:18:00 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 15:18:00 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <5b36caaf-f1d6-47a5-ae0c-b11b0f3078b9@l28g2000yqd.googlegroups.com> Message-ID: On May 8, 1:16?pm, dasacc22 wrote: > On May 8, 12:59?pm, Patrick Maupin wrote: > > > > > On May 8, 12:19?pm, dasacc22 wrote: > > > > Hi > > > > This is a simple question. I'm looking for the fastest way to > > > calculate the leading whitespace (as a string, ie ' ? ?'). > > > > Here are some different methods I have tried so far > > > --- solution 1 > > > > a = ' ? ?some content\n' > > > b = a.strip() > > > c = ' '*(len(a)-len(b)) > > > > --- solution 2 > > > > a = ' ? ?some content\n' > > > b = a.strip() > > > c = a.partition(b[0])[0] > > > > --- solution 3 > > > > def get_leading_whitespace(s): > > > ? ? def _get(): > > > ? ? ? ? for x in s: > > > ? ? ? ? ? ? if x != ' ': > > > ? ? ? ? ? ? ? ? break > > > ? ? ? ? ? ? yield x > > > ? ? return ''.join(_get()) > > > > --- > > > > Solution 1 seems to be about as fast as solution 2 except in certain > > > circumstances where the value of b has already been determined for > > > other purposes. Solution 3 is slower due to the function overhead. > > > > Curious to see what other types of solutions people might have. > > > > Thanks, > > > Daniel > > > Well, you could try a solution using re, but that's probably only > > likely to be faster if you can use it on multiple concatenated lines. > > I usually use something like your solution #1. ?One thing to be aware > > of, though, is that strip() with no parameters will strip *any* > > whitespace, not just spaces, so the implicit assumption in your code > > that what you have stripped is spaces may not be justified (depending > > on the source data). ?OTOH, depending on how you use that whitespace > > information, it may not really matter. ?But if it does matter, you can > > use strip(' ') > > > If speed is really an issue for you, you could also investigate > > mxtexttools, but, like re, it might perform better if the source > > consists of several batched lines. > > > Regards, > > Pat > > Hi, > > thanks for the info. Using .strip() to remove all whitespace in > solution 1 is a must. If you only stripped ' ' spaces then line > endings would get counted in the len() call and when multiplied > against ' ', would produce an inaccurate result. Regex is > significantly slower for my purposes but ive never heard of > mxtexttools. Even if it proves slow its spurred my curiousity as to > what functionality it provides (on an unrelated note) Could you reorganize your code to do multiple lines at a time? That might make regex competitive. Regards, Pat From nathan.alexander.rice at gmail.com Sat May 8 18:31:26 2010 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Sat, 8 May 2010 18:31:26 -0400 Subject: Kindly show me a better way to do it In-Reply-To: References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: itertools is also written in c, so if you're working with a big nested list is long it will be a lot faster. On Sat, May 8, 2010 at 5:40 PM, Tycho Andersen wrote: > On Sat, May 8, 2010 at 4:09 PM, G?nther Dietrich > wrote: > [snip] > > Too simple? > > No, not at all. I really only intended to point the OP to itertools, > because it does lots of useful things exactly like this one. > > \t > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat May 8 19:29:07 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 09 May 2010 00:29:07 +0100 Subject: how to play a sound file repeatedly in loop In-Reply-To: References: Message-ID: <4BE5F3C3.7030206@mrabarnett.plus.com> varnikat t wrote: > > How to run sound file repeatedly in loop ? > > When I do this, it does nothing and terminates: > > import pygst > pygst.require("0.10") > import gst, gtk > > > n=0 > > while n<10: > player = gst.element_factory_make("playbin2", "player") > player.set_property("uri", "file:/home/varnika/hello.ogg") > player.set_state(gst.STATE_PLAYING) > n=n+1 > It's not doing nothing, it's repeatedly making a player, starting it, and then on the next iteration making another player and starting it. The line: player.set_state(gst.STATE_PLAYING) doesn't wait until the sound file has finished before returning. From pavlovevidence at gmail.com Sat May 8 19:39:33 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 8 May 2010 16:39:33 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: On May 6, 4:56?pm, Ben Finney wrote: > a... at pythoncraft.com (Aahz) writes: > > In article <4BE05D75.7030... at msn.com>, > > Rouslan Korneychuk ? wrote: > > > >The only question I have now is what about licensing? Is that > > >something I need to worry about? Should I go with LGPL, MIT, or > > >something else? > > > Which license you use depends partly on your political philosophy. > > Yes. > > Unless you place such a low value the freedom of your users that you'd > allow proprietary derivatives of your work to remove the freedoms you've > taken care to grant, then you should choose a copyleft license like the > GPL. GPL is about fighting a holy war against commercial software. People who esteem their users give them freedom to use software however they see fit, including combining it with proprietary software. Carl Banks From thomasstruth at gmail.com Sat May 8 19:50:11 2010 From: thomasstruth at gmail.com (ben) Date: Sat, 8 May 2010 16:50:11 -0700 (PDT) Subject: accessing superclass methods from subclass Message-ID: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Why doesn't this work: class C1: def f1(self): print("f1") class C2(C1): f1() It throws this error: Traceback (most recent call last): File "./c1.py", line 7, in class C2(C1): File "./c1.py", line 8, in C2 f1() NameError: name 'f1' is not defined f1() is an attribute of class C1, C2 inherits C1, so why can't it see it? thanks! From clp2 at rebertia.com Sat May 8 20:05:44 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 8 May 2010 17:05:44 -0700 Subject: accessing superclass methods from subclass In-Reply-To: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: On Sat, May 8, 2010 at 4:50 PM, ben wrote: > Why doesn't this work: > > class C1: > ? ?def f1(self): > ? ? ? ?print("f1") > > class C2(C1): > ? ?f1() > > > It throws this error: > > Traceback (most recent call last): > ?File "./c1.py", line 7, in > ? ?class C2(C1): > ?File "./c1.py", line 8, in C2 > ? ?f1() > NameError: name 'f1' is not defined > > > f1() is an attribute of class C1, C2 inherits C1, so why can't it see > it? The way classes work in Python, C2 isn't actually created until after its body suite has been executed, so that's why Python can't find f1. Additionally, it makes no sense to call an *instance* method such as f1() in a class context. Or in Java-speak: you can't call a non-static method in a static context. Cheers, Chris -- http://blog.rebertia.com From python at mrabarnett.plus.com Sat May 8 20:13:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 09 May 2010 01:13:18 +0100 Subject: accessing superclass methods from subclass In-Reply-To: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: <4BE5FE1E.5070809@mrabarnett.plus.com> ben wrote: > Why doesn't this work: > > class C1: > def f1(self): > print("f1") > > class C2(C1): > f1() > > > It throws this error: > > Traceback (most recent call last): > File "./c1.py", line 7, in > class C2(C1): > File "./c1.py", line 8, in C2 > f1() > NameError: name 'f1' is not defined > > > f1() is an attribute of class C1, C2 inherits C1, so why can't it see > it? > Name lookup works differently from some other languages. You need to be explicit and tell it where 'f1' is defined: C1.f1() However, that will raise a different exception. I don't know what you're trying to do. From aahz at pythoncraft.com Sat May 8 20:36:51 2010 From: aahz at pythoncraft.com (Aahz) Date: 8 May 2010 17:36:51 -0700 Subject: Picking a license References: <87k4rgfutu.fsf@benfinney.id.au> Message-ID: In article , Carl Banks wrote: > >GPL is about fighting a holy war against commercial software. And really, that's a Good Thing. We wouldn't have Python, to some extent, were it not for Stallman and his crusade. That doesn't mean we should slavishly worship him, though. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From ben+python at benfinney.id.au Sat May 8 21:41:11 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 09 May 2010 11:41:11 +1000 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> Message-ID: <87fx21ets8.fsf@benfinney.id.au> Patrick Maupin writes: > On May 8, 2:38?pm, Steven D'Aprano cybersource.com.au> wrote: > > Which brings us back full circle to Ben's position, which you took > > exception to. [?] > To me, the clear implication of the blanket statement that you have to > use the GPL if you care at all about users is that anybody who doesn't > use the GPL is uncaring. I think that's a silly attitude [?] Fortunately, neither that silly blanket statement nor its implication are represented in any of my messages in this thread. I hope that helps. -- \ ?I've always wanted to be somebody, but I see now that I should | `\ have been more specific.? ?Jane Wagner, via Lily Tomlin | _o__) | Ben Finney From ben+python at benfinney.id.au Sat May 8 21:42:11 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 09 May 2010 11:42:11 +1000 Subject: Picking a license References: <87k4rgfutu.fsf@benfinney.id.au> Message-ID: <87bpcpetqk.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > In article , > Carl Banks wrote: > > > >GPL is about fighting a holy war against commercial software. > > And really, that's a Good Thing. We wouldn't have Python, to some > extent, were it not for Stallman and his crusade. That doesn't mean we > should slavishly worship him, though. +1. -- \ ?A child of five could understand this. Fetch me a child of | `\ five.? ?Groucho Marx | _o__) | Ben Finney From pmaupin at gmail.com Sat May 8 22:34:24 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 19:34:24 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <87fx21ets8.fsf@benfinney.id.au> Message-ID: On May 8, 8:41?pm, Ben Finney wrote: > Patrick Maupin writes: > > On May 8, 2:38?pm, Steven D'Aprano > cybersource.com.au> wrote: > > > Which brings us back full circle to Ben's position, which you took > > > exception to. > > [?] > > > To me, the clear implication of the blanket statement that you have to > > use the GPL if you care at all about users is that anybody who doesn't > > use the GPL is uncaring. ?I think that's a silly attitude [?] > > Fortunately, neither that silly blanket statement nor its implication > are represented in any of my messages in this thread. Hmm, I must have misunderstood this: "Unless you place such a low value the freedom of your users that you'd allow proprietary derivatives of your work to remove the freedoms you've taken care to grant, then you should choose a copyleft license like the GPL." To me, placing "such a low value on the freedom of [my] users" sounds like I'm ready to consign them to slavery or something, so I certainly originally viewed this as a "blanket" (e.g. unqualified) "statement" (well, that should be obvious) that I have to use the GPL "if [I] care at all about [my] users". > I hope that helps. Well, perhaps you meant less by your wording of "a low value on the freedom" than could be read into it, just as Aahz and I meant less by "forced" than you apparently read into that. I think we all have more or less accurate understandings of the differences between GPL and permissive licenses, but only disagree somewhat on how important the various features are, and at the end of the day we all come to some reasonably nuanced view of how to proceed with our projects. One thing I realized that I didn't cover in my earlier posts is that I think that for a lot of library-type projects, LGPL v2.1 is a really fine license, offering a great balance of competing interests. I view the new licensing on QT from Nokia (commercial, GPL v3, or LGPL v2.1) as a good example of a balanced strategy. Regards, Pat From timr at probo.com Sat May 8 22:47:33 2010 From: timr at probo.com (Tim Roberts) Date: Sat, 08 May 2010 19:47:33 -0700 Subject: Cross-platform file paths References: Message-ID: <1e8cu5tcvl87979vq5r0mecos28m9vat6v@4ax.com> utabintarbo wrote: > >Until now, I have used the UNC under Windows (XP) to allow my program >to access files located on a Samba-equipped *nix box (eg. >os.path.normpath(r"\\serverFQDN\sharename\dir\filename")). When I try >to open this file under Linux (Red Hat 5), I get a file not found >error. > >Is there a cross-platform method for accessing files on a network >share using Python 2.X? No. On Linux, you need to mount the share in some empty directory (using mount or smbmount), then read the files from that directory. It's kind of odd to use a Windows network protocol to access a Linux file system from another Linux machine. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From no.email at nospam.invalid Sat May 8 22:58:48 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 19:58:48 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: <7x39y1vl07.fsf@ruckus.brouhaha.com> Carl Banks writes: > People who esteem their users give them freedom to use software > however they see fit, including combining it with proprietary > software. Huh???? That makes no sense at all. Why should a standard like that be expected from free software developers, when it isn't expected from the makers of the proprietary software who you're proposing deserve to rake in big bucks from locking up other people's work that they didn't pay for? I've got no problem writing stuff for inclusion in proprietary products. But I do that as a professional, which means I expect to get paid for it. And I think you have the "esteem" issue backwards. Users who esteem developers who write and share software for community benefit, should not whine and pout that the largesse doesn't extend as far as inviting monopolistic corporations to lock it away from further sharing. From no.email at nospam.invalid Sat May 8 23:03:32 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 20:03:32 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: <7xy6ftu67v.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > I fail to see what is morally wrong with it. When I ,as the author, > share my work to the public, I should have made peace with the fact > that I, for all intends and purposes, lost control over its use. Does the same thing apply to Microsoft? If I get a copy of MS Office, do you think I should be able to incorporate its code into my own products for repackaging and sale any way that I want, without their having any say? If not, why should Microsoft be entitled to do that with software that -I- write? Is there something in the water making people think these inequitable things? If Microsoft's licenses are morally respectable then so is the GPL. From no.email at nospam.invalid Sat May 8 23:12:47 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 20:12:47 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: <7xtyqhu5sg.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > For the record, I've published software under an MIT licence because I > judged the cost of the moral hazard introduced by encouraging freeloaders > to be less than the benefits of having a more permissive licence that > encourages freeloading and therefore attracts more users. For other > software, I might judge that the cost/benefit ratio falls in a different > place, and hence choose the GPL. I don't know if it counts as a moral hazard but some programmers simply don't want to do proprietary product development for free. That's why Linux (GPL) has far more developers (and consequentially far more functionality and more users) than the free versions of BSD, and GCC (GPL) has far more developers than Python. Of course the BSD license did allow Bill Gates and Steve Jobs to become billionaires off the work off the developers who actually wrote the Berkeley code and are now struggling to make their rent. But at least those developers can be proud that the Microsoft and Apple DRM empires benefited so much from their efforts. THAT's a level of self-sacrifice that I can do without. Note, "permissive license" is a Microsoft propaganda term from what I can tell. "Forbidding forbidden" is how I like to think of the GPL. From thomasstruth at gmail.com Sat May 8 23:24:28 2010 From: thomasstruth at gmail.com (ben) Date: Sat, 8 May 2010 20:24:28 -0700 (PDT) Subject: accessing superclass methods from subclass References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: Ok, thanks for the info. What would be a better way to do this? What I'm trying to do is treat things in a reasonable OOP manner (all fairly new to me, esp. in Python). Here's a made-up example with a little more context. Let's say you're making a drawing program that can draw various shapes. So in the interest of not repeating oneself, I want a class Shape that handles everything that shapes have, such as a color, and a location. Then I can subclass Shape to create Square, which has code specific to drawing a square (e.g. 4 equal sides). So, like this: class Shape: x = 0 y = 0 def setColor(self,color): self.color = color def setLocation(self,x,y): self.x = x self.y = y def getLocation(self): return [self.x,self.y] class Square(Shape): size = 0 def __init__(self,size): self.size = size def draw(self): location = getLocation() # code to draw shape from location[0],location[1] at size size # etc... It seems to me that you would want the location code handled in the Shape class so that I'm not rewriting it for Circle, Triangle, etc., but I'm not allowed to call any of those methods from the subclass. I must be thinking of this in the wrong way. Help? thanks! On May 8, 7:05?pm, Chris Rebert wrote: > On Sat, May 8, 2010 at 4:50 PM, ben wrote: > > Why doesn't this work: > > > class C1: > > ? ?def f1(self): > > ? ? ? ?print("f1") > > > class C2(C1): > > ? ?f1() > > > It throws this error: > > > Traceback (most recent call last): > > ?File "./c1.py", line 7, in > > ? ?class C2(C1): > > ?File "./c1.py", line 8, in C2 > > ? ?f1() > > NameError: name 'f1' is not defined > > > f1() is an attribute of class C1, C2 inherits C1, so why can't it see > > it? > > The way classes work in Python, C2 isn't actually created until after > its body suite has been executed, so that's why Python can't find f1. > > Additionally, it makes no sense to call an *instance* method such as > f1() in a class context. Or in Java-speak: you can't call a non-static > method in a static context. > > Cheers, > Chris > --http://blog.rebertia.com From 1 at depikt.net Sat May 8 23:33:14 2010 From: 1 at depikt.net (3Jane) Date: Sat, 8 May 2010 20:33:14 -0700 (PDT) Subject: A more general solution Message-ID: <44e7ce5a-6ec3-460e-9f36-05762ebe59b0@i9g2000yqi.googlegroups.com> You could interpret [[1,2,3,4],[5,6,7,8]] as a tree and your task as traversal of its leaves. All solutions before would not work with trees with bigger height. Here is how to traverse such trees recursively: def eventualPrint(x): for v in x: if isinstance(v, list): eventualPrint(x) else: print(v) Then eventualPrint(a) does the job. This would only cope with lists as proper nodes. More general tests than isinstance() could be tried, hasattr(x, 'getitem') would match all sequence types for example. Also "for v in x:" should perhaps tested for exceptions. Optimal directives for both alternatives depend on the scope of the code's purpose. As often the price for generality is performance here. Good luck, Joost From robert.kern at gmail.com Sat May 8 23:38:00 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 08 May 2010 22:38:00 -0500 Subject: Picking a license In-Reply-To: <7xy6ftu67v.fsf@ruckus.brouhaha.com> References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> Message-ID: On 2010-05-08 22:03 , Paul Rubin wrote: > "Martin P. Hellwig" writes: >> I fail to see what is morally wrong with it. When I ,as the author, >> share my work to the public, I should have made peace with the fact >> that I, for all intends and purposes, lost control over its use. > > Does the same thing apply to Microsoft? If I get a copy of MS Office, > do you think I should be able to incorporate its code into my own > products for repackaging and sale any way that I want, without their > having any say? If not, why should Microsoft be entitled to do that > with software that -I- write? Martin is not saying that you *ought* to release your code under a liberal license. He is only saying that he does not believe he is inviting moral hazard when *he* decides to release *his* code under a liberal license. He was responding to Steven who was claiming otherwise. > Is there something in the water making > people think these inequitable things? Is there something in the water making people think that every statement of opinion about how one licenses one's own code is actually an opinion about how everyone should license their code? > If Microsoft's licenses are > morally respectable then so is the GPL. Martin is not saying that the GPL is not morally respectable. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Sat May 8 23:44:21 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 08 May 2010 22:44:21 -0500 Subject: Picking a license In-Reply-To: <7xtyqhu5sg.fsf@ruckus.brouhaha.com> References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> Message-ID: On 2010-05-08 22:12 , Paul Rubin wrote: > Steven D'Aprano writes: >> For the record, I've published software under an MIT licence because I >> judged the cost of the moral hazard introduced by encouraging freeloaders >> to be less than the benefits of having a more permissive licence that >> encourages freeloading and therefore attracts more users. For other >> software, I might judge that the cost/benefit ratio falls in a different >> place, and hence choose the GPL. > > I don't know if it counts as a moral hazard but some programmers simply > don't want to do proprietary product development for free. That's why > Linux (GPL) has far more developers (and consequentially far more > functionality and more users) than the free versions of BSD, and GCC > (GPL) has far more developers than Python. Post hoc ergo propter hoc? Show me some controlled studies demonstrating that this is actually the causative agent in these cases, then maybe I'll believe you. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From clp2 at rebertia.com Sat May 8 23:44:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 8 May 2010 20:44:59 -0700 Subject: accessing superclass methods from subclass In-Reply-To: References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: > On May 8, 7:05?pm, Chris Rebert wrote: >> On Sat, May 8, 2010 at 4:50 PM, ben wrote: >> > Why doesn't this work: >> >> > class C1: >> > ? ?def f1(self): >> > ? ? ? ?print("f1") >> >> > class C2(C1): >> > ? ?f1() >> >> > It throws this error: >> >> > Traceback (most recent call last): >> > ?File "./c1.py", line 7, in >> > ? ?class C2(C1): >> > ?File "./c1.py", line 8, in C2 >> > ? ?f1() >> > NameError: name 'f1' is not defined >> >> > f1() is an attribute of class C1, C2 inherits C1, so why can't it see >> > it? >> >> The way classes work in Python, C2 isn't actually created until after >> its body suite has been executed, so that's why Python can't find f1. >> >> Additionally, it makes no sense to call an *instance* method such as >> f1() in a class context. Or in Java-speak: you can't call a non-static >> method in a static context. On Sat, May 8, 2010 at 8:24 PM, ben wrote: > Ok, thanks for the info. > > What would be a better way to do this? What I'm trying to do is treat > things in a reasonable OOP manner (all fairly new to me, esp. in > Python). Here's a made-up example with a little more context. Let's > say you're making a drawing program that can draw various shapes. So > in the interest of not repeating oneself, I want a class Shape that > handles everything that shapes have, such as a color, and a location. > Then I can subclass Shape to create Square, which has code specific to > drawing a square (e.g. 4 equal sides). So, like this: > > class Shape: > > x = 0 > y = 0 > > def setColor(self,color): > self.color = color > > def setLocation(self,x,y): > self.x = x > self.y = y > > def getLocation(self): > return [self.x,self.y] > > class Square(Shape): > > size = 0 > > def __init__(self,size): > self.size = size > > def draw(self): > location = getLocation() > # code to draw shape from location[0],location[1] at size size > # etc... > > It seems to me that you would want the location code handled in the > Shape class so that I'm not rewriting it for Circle, Triangle, etc., > but I'm not allowed to call any of those methods from the subclass. I > must be thinking of this in the wrong way. Help? Your code suggests you need to read a tutorial on Python's object-oriented features. The relevant part of Python's official tutorial is http://docs.python.org/tutorial/classes.html For starters, Python is not Java and getters/setters are not usually necessary nor Pythonic; see http://dirtsimple.org/2004/12/python-is-not-java.html Secondly, Python does not have instance variable declarations; doing `x = 0` at the class-level creates a static/class variable, it *does not* declare an instance variable. Thirdly, to call an instance method such as getLocation, you need to specify the receiver, i.e. `self.getLocation()`, not merely `getLocation()` Here is how I would rewrite your example: class Shape(object): def __init__(self, x=0, y=0): self.x = x self.y = y @property def location(self): return (self.x, self.y) @location.setter def location(self, val): self.x, self.y = val class Square(Shape): def __init__(self,size): super(Square, self).__init__() self.size = size def draw(self): x, y = self.location # code to draw shape from location[0],location[1] at size size # etc... This uses some minor magic involving property(), see http://docs.python.org/library/functions.html#property for how that works. Cheers, Chris -- http://blog.rebertia.com From dasacc22 at gmail.com Sat May 8 23:48:36 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sat, 8 May 2010 20:48:36 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <5b36caaf-f1d6-47a5-ae0c-b11b0f3078b9@l28g2000yqd.googlegroups.com> Message-ID: <69fb31dc-f5f8-4fc7-bb47-5e60e92e6485@24g2000yqy.googlegroups.com> On May 8, 5:18?pm, Patrick Maupin wrote: > On May 8, 1:16?pm, dasacc22 wrote: > > > > > > > On May 8, 12:59?pm, Patrick Maupin wrote: > > > > On May 8, 12:19?pm, dasacc22 wrote: > > > > > Hi > > > > > This is a simple question. I'm looking for the fastest way to > > > > calculate the leading whitespace (as a string, ie ' ? ?'). > > > > > Here are some different methods I have tried so far > > > > --- solution 1 > > > > > a = ' ? ?some content\n' > > > > b = a.strip() > > > > c = ' '*(len(a)-len(b)) > > > > > --- solution 2 > > > > > a = ' ? ?some content\n' > > > > b = a.strip() > > > > c = a.partition(b[0])[0] > > > > > --- solution 3 > > > > > def get_leading_whitespace(s): > > > > ? ? def _get(): > > > > ? ? ? ? for x in s: > > > > ? ? ? ? ? ? if x != ' ': > > > > ? ? ? ? ? ? ? ? break > > > > ? ? ? ? ? ? yield x > > > > ? ? return ''.join(_get()) > > > > > --- > > > > > Solution 1 seems to be about as fast as solution 2 except in certain > > > > circumstances where the value of b has already been determined for > > > > other purposes. Solution 3 is slower due to the function overhead. > > > > > Curious to see what other types of solutions people might have. > > > > > Thanks, > > > > Daniel > > > > Well, you could try a solution using re, but that's probably only > > > likely to be faster if you can use it on multiple concatenated lines. > > > I usually use something like your solution #1. ?One thing to be aware > > > of, though, is that strip() with no parameters will strip *any* > > > whitespace, not just spaces, so the implicit assumption in your code > > > that what you have stripped is spaces may not be justified (depending > > > on the source data). ?OTOH, depending on how you use that whitespace > > > information, it may not really matter. ?But if it does matter, you can > > > use strip(' ') > > > > If speed is really an issue for you, you could also investigate > > > mxtexttools, but, like re, it might perform better if the source > > > consists of several batched lines. > > > > Regards, > > > Pat > > > Hi, > > > thanks for the info. Using .strip() to remove all whitespace in > > solution 1 is a must. If you only stripped ' ' spaces then line > > endings would get counted in the len() call and when multiplied > > against ' ', would produce an inaccurate result. Regex is > > significantly slower for my purposes but ive never heard of > > mxtexttools. Even if it proves slow its spurred my curiousity as to > > what functionality it provides (on an unrelated note) > > Could you reorganize your code to do multiple lines at a time? ?That > might make regex competitive. > > Regards, > Pat I have tried this already, the problem here is that it's not a trivial matter. Iterating over each line is unavoidable, and I found that using various python builtins to perform string operations (like say the wonderful partition builtin) during each iteration works 3 fold faster then regexing the entire document with various needs. Another issue is having to keep a line count and when iterating over regex matches and counting lines, it doesn't scale nearly as well as a straight python solution using builtins to process the information. At the heart of this here, determining the leading white-space is a trivial matter. I have much more complex problems to deal with. I was much more interested in seeing what kind of solutions ppl would come up with to such a problem, and perhaps uncover something new in python that I can apply to a more complex problem. What spurred the thought was this piece written up by guido concerning "what's the best way to convert a list of integers into a string". It's a simple question where concepts are introduced that can lead to solving more complex problems. http://www.python.org/doc/essays/list2str.html From no.email at nospam.invalid Sat May 8 23:49:59 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 20:49:59 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> Message-ID: <7xk4rdpwd4.fsf@ruckus.brouhaha.com> Martin wrote: >>> I fail to see what is morally wrong with it. When I ,as the author, >>> share my work to the public, I should have made peace with the fact >>> that I, for all intends and purposes, lost control over its use. Robert Kern writes: > Martin is not saying that you *ought* to release your code under a > liberal license. He is only saying that he does not believe he is > inviting moral hazard when *he* decides to release *his* code under a > liberal license. He was responding to Steven who was claiming > otherwise. As I read it, he is saying that when someone releases free software, they have "for all intends and purposes lost control over its use", so they "should have made peace with the fact" and surrender gracefully. I'm asking why he doesn't think Microsoft has lost control the same way. From pavlovevidence at gmail.com Sun May 9 00:04:44 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 8 May 2010 21:04:44 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <7x39y1vl07.fsf@ruckus.brouhaha.com> Message-ID: <73bcbd04-4e31-4532-a220-9389c5c299d9@r11g2000yqa.googlegroups.com> On May 8, 7:58?pm, Paul Rubin wrote: > Carl Banks writes: > > People who esteem their users give them freedom to use software > > however they see fit, including combining it with proprietary > > software. > > Huh???? ?That makes no sense at all. ?Why should a standard like that be > expected from free software developers, when it isn't expected from the > makers of the proprietary software who you're proposing deserve to rake > in big bucks from locking up other people's work that they didn't pay > for? Same thing's true commercial software, Sparky. If a commercial developer has a EULA that prevents users from combining their tools with tools from (say) their competitors, they would be very much disrespecting their users. The GPL does exactly that, and people who release GPL software disrespect their users just as much as a commercial entity that requires you not to use competing products. But for some reason when someone and inflicts the disrespect of the GPL on the community they're considered folk heroes. Bah. > I've got no problem writing stuff for inclusion in proprietary products. > But I do that as a professional, which means I expect to get paid for > it. ?And I think you have the "esteem" issue backwards. ?Users who > esteem developers who write and share software for community benefit, > should not whine and pout that the largesse doesn't extend as far as > inviting monopolistic corporations to lock it away from further sharing. In your petty jealous zeal to prevent megacorporations from profiting off free software, you prevent guys like me from doing useful, community-focused things like writing extensions for commercial software that uses GPL-licensed code. The GPL drives a wedge between commercial and free software, making it difficult for the two to coexist. That is far more detrimental to open source community than the benefits of making a monopolistic corporation do a little extra work to avoid having their codebase tainted by GPL. Carl Banks From aahz at pythoncraft.com Sun May 9 00:18:31 2010 From: aahz at pythoncraft.com (Aahz) Date: 8 May 2010 21:18:31 -0700 Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> Message-ID: In article <7xtyqhu5sg.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >I don't know if it counts as a moral hazard but some programmers simply >don't want to do proprietary product development for free. That's why >Linux (GPL) has far more developers (and consequentially far more >functionality and more users) than the free versions of BSD, and GCC >(GPL) has far more developers than Python. What does your argument claim about Apache? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From dasacc22 at gmail.com Sun May 9 00:24:50 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sat, 8 May 2010 21:24:50 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> Message-ID: <8b1ac372-ebe0-4b11-8bb8-8b5379134aa5@r11g2000yqa.googlegroups.com> On May 8, 2:46?pm, Steven D'Aprano wrote: > On Sat, 08 May 2010 12:15:22 -0700, Wolfram Hinderer wrote: > > On 8 Mai, 20:46, Steven D'Aprano > > wrote: > > >> def get_leading_whitespace(s): > >> ? ? t = s.lstrip() > >> ? ? return s[:len(s)-len(t)] > > >> >>> c = get_leading_whitespace(a) > >> >>> assert c == leading_whitespace > > >> Unless your strings are very large, this is likely to be faster than > >> any other pure-Python solution you can come up with. > > > Returning s[:-1 - len(t)] is faster. > > I'm sure it is. Unfortunately, it's also incorrect. > > >>> z = "*****abcde" > >>> z[:-1-5] > '****' > >>> z[:len(z)-5] > > '*****' > > However, s[:-len(t)] should be both faster and correct. > > -- > Steven This is without a doubt faster and simpler then any solution thus far. Thank you for this From no.email at nospam.invalid Sun May 9 00:29:26 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 21:29:26 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <7x39y1vl07.fsf@ruckus.brouhaha.com> <73bcbd04-4e31-4532-a220-9389c5c299d9@r11g2000yqa.googlegroups.com> Message-ID: <7x4oihn1eh.fsf@ruckus.brouhaha.com> Carl Banks writes: > If a commercial developer has a EULA that prevents users from > combining their tools with tools from (say) their competitors, Do you mean something like a EULA that stops you from buying a copy of Oracle and combining it with tools from IBM on the computer that you install Oracle on? Those EULAs exist but are not remotely comparable to the GPL. > The GPL does exactly that, No it doesn't (not like the above). You, the licensee under the GPL, can make those combinations and use them as much as you want on your own computers. You just can't distribute the resulting derivative to other people. With proprietary software you can't redistribute the software to other people from day zero (or even use more copies within your own company than you've paid for), regardless of whether you've combined it with anything. And since you usually don't get the source code, it's awfully hard to make derived combinatoins. From no.email at nospam.invalid Sun May 9 00:36:11 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 21:36:11 -0700 Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> Message-ID: <7xwrvdlmis.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > What does your argument claim about Apache? No idea. I don't have the impression the developer communities are really similar, and Apache httpd doesn't have all that many developers compared with something like Linux (I don't know what happens if you add all the sister projects like Lucene). I do know that the GPL has gotten companies to release major GCC improvements that they would have preferred to make proprietary if they'd had the option. That includes G++. From wolfgang at rohdewald.de Sun May 9 00:52:25 2010 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Sun, 9 May 2010 06:52:25 +0200 Subject: Cross-platform file paths In-Reply-To: <1e8cu5tcvl87979vq5r0mecos28m9vat6v@4ax.com> References: <1e8cu5tcvl87979vq5r0mecos28m9vat6v@4ax.com> Message-ID: <201005090652.25777.wolfgang@rohdewald.de> On Sonntag 09 Mai 2010, Tim Roberts wrote: > No. On Linux, you need to mount the share in some empty > directory (using mount or smbmount), then read the files from > that directory. actually the mount directory does not have to be empty - whatever it contains is invisible while someting is mounted in it. But of course using an empty directory gets you less surprises. -- Wolfgang From simula67 at comcast.net Sun May 9 00:56:36 2010 From: simula67 at comcast.net (Eric Stechmann) Date: Sat, 8 May 2010 23:56:36 -0500 Subject: [ANN] Leipzig Python User Group - Meeting, May 11, 2010, 08:00pm In-Reply-To: <4BE43936.7080600@sschwarzer.net> References: <4BE43936.7080600@sschwarzer.net> Message-ID: On May 7, 2010, at 11:00 AM, Stefan Schwarzer wrote: > === Leipzig Python User Group === > > We will meet on Tuesday, May 11, 8:00 pm at the training > center of Python Academy in Leipzig, Germany > ( http://www.python-academy.com/center/find.html ). > > Julian Moritz will give a talk about CouchDB. > > Food and soft drinks are provided. Please send a short > confirmation mail to info at python-academy.de, so we can prepare > appropriately. > > Everybody who uses Python, plans to do so or is interested in > learning more about the language is encouraged to participate. > > While the meeting language will be mainly German, we will provide > English translation if needed. > > Current information about the meetings are at > http://www.python-academy.com/user-group . > > Stefan > > > == Leipzig Python User Group === > > Wir treffen uns am Dienstag, 11.05.2010 um 20:00 Uhr > im Schulungszentrum der Python Academy in Leipzig > ( http://www.python-academy.de/Schulungszentrum/anfahrt.html ). > > Julian Moritz h?lt einen Vortrag ?ber CouchDB. > > F?r das leibliche Wohl wird gesorgt. Eine Anmeldung unter > info at python-academy.de w?re nett, damit wir genug Essen > besorgen k?nnen. > > Willkommen ist jeder, der Interesse an Python hat, die Sprache > bereits nutzt oder nutzen m?chte. > > Aktuelle Informationen zu den Treffen sind unter > http://www.python-academy.de/User-Group zu finden. > > Viele Gr??e > Stefan > > > > > > > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations/ From pmaupin at gmail.com Sun May 9 01:01:48 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 22:01:48 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <7x39y1vl07.fsf@ruckus.brouhaha.com> <73bcbd04-4e31-4532-a220-9389c5c299d9@r11g2000yqa.googlegroups.com> <7x4oihn1eh.fsf@ruckus.brouhaha.com> Message-ID: On May 8, 11:29?pm, Paul Rubin wrote: > No it doesn't (not like the above). ?You, the licensee under the GPL, > can make those combinations and use them as much as you want on your own > computers. ?You just can't distribute the resulting derivative to other > people. ?With proprietary software you can't redistribute the software > to other people from day zero (or even use more copies within your own > company than you've paid for), regardless of whether you've combined it > with anything. ?And since you usually don't get the source code, it's > awfully hard to make derived combinatoins. But the point is that a lot of small developers who are writing software don't need to distribute any software other than software they wrote themselves. Their customers will have Oracle/Microsoft/IBM/ CA/whatever licenses already. Companies like Oracle support various APIs that allow custom software to be connected to their software, so if Carl is writing stuff to support Oracle, he can just distribute his software to the customer, and let the customer link it himself. Now when Carl's software links to GPLed software, it gets interesting. Although it's probably a legal overreach, the FSF often attempts to claim that software like Carl's, *by itself*, must be licensed under the GPL, simply because it can link to GPLed software, even if it doesn't actually contain any GPLed software. (Whether it's a legal overreach or not, it's the position of the FSF, and of a lot of authors who use the GPL, so morally it's probably best to follow their wishes.) The end result is that Carl can deliver software to his customer that lets the customer link Oracle and Microsoft software together, for example, but is prohibited from delivering software that lets the customer link GPLed code to Oracle code, because the FSF considers that software that would do that is a "derived work" and that Carl is making a distribution when he gives it to his customer, and he is not allowed to distribute GPLed code that links to proprietary Oracle code. Regards, Pat From pmaupin at gmail.com Sun May 9 01:09:14 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 22:09:14 -0700 (PDT) Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> Message-ID: <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> On May 8, 11:36?pm, Paul Rubin wrote: > a... at pythoncraft.com (Aahz) writes: > > What does your argument claim about Apache? > > No idea. ?I don't have the impression the developer communities are > really similar, and Apache httpd doesn't have all that many developers > compared with something like Linux (I don't know what happens if you add > all the sister projects like Lucene). > > I do know that the GPL has gotten companies to release major GCC > improvements that they would have preferred to make proprietary if > they'd had the option. ?That includes G++. Absolutely, and as Aahz acknowledges, RMS was a pioneer in introducing people to the concept of free software. But fast forward to today, and as ESR points out, the FOSS development model is so superior for many classes of software that proprietary companies contribute to free software even when they don't have to, and are working hard to support hybrid models that the GPL doesn't support. See, for example, Apple's support of BSD, Webkit, and LLVM. Apple is not a "do no evil" corporation, and their contributions back to these packages are driven far more by hard-nosed business decisions than by any expectation of community goodwill. Regards, Pat From steve at REMOVE-THIS-cybersource.com.au Sun May 9 01:13:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 05:13:11 GMT Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> <489ffaa0-1563-45a1-93aa-cc83cdd6abd9@j35g2000yqm.googlegroups.com> Message-ID: <4be64467$0$27783$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 13:46:59 -0700, Mark Dickinson wrote: >> However, s[:-len(t)] should be both faster and correct. > > Unless len(t) == 0, surely? Doh! The hazards of insufficient testing. Thanks for catching that. -- Steven From lie.1296 at gmail.com Sun May 9 01:17:38 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 09 May 2010 15:17:38 +1000 Subject: Kindly show me a better way to do it In-Reply-To: References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: <4be645cf@dnews.tpgi.com.au> On 05/09/10 07:09, G?nther Dietrich wrote: > > Why not this way? > >>>> a = [[1,2,3,4], [5,6,7,8]] >>>> for i in a: > .... for j in i: > .... print(j) > .... > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > > Too simple? IMHO that's more complex due to the nested loop, though I would personally do it as: a = [ [1,2,3,4], [5,6,7,8] ] from itertools import chain for i in chain.from_iterable(a): print i so it won't choke when 'a' is an infinite stream of iterables. From steve at REMOVE-THIS-cybersource.com.au Sun May 9 01:19:47 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 05:19:47 GMT Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: <4be645f2$0$27783$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 16:39:33 -0700, Carl Banks wrote: > GPL is about fighting a holy war against commercial software. Much GPL software *is* commercial software. Given that you're so badly misinformed about the GPL that you think it can't be commercial, why should we pay any attention to your opinions about it? -- Steven From no.email at nospam.invalid Sun May 9 01:27:25 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 22:27:25 -0700 Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> Message-ID: <7x39y14pc2.fsf@ruckus.brouhaha.com> Patrick Maupin writes: > hybrid models that the GPL doesn't support. See, for example, Apple's > support of BSD, Webkit, and LLVM. Apple is not a "do no evil" > corporation, and their contributions back to these packages are driven > far more by hard-nosed business decisions than by any expectation of > community goodwill. That is true. They've also supported GPL projects. I think they just don't want to be in the business of selling those sorts of products. They're making too much money selling iphones and laptops to want such a distraction. Things were different with G++. The company that developed it would have liked to go into the compiler business with it, but it wasn't an option, so they released under GPL. Linus has said similar things have happened with Linux, but I don't know details. From pmaupin at gmail.com Sun May 9 02:01:52 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 23:01:52 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> Message-ID: <9f54536c-8428-4de8-bba8-fa16fe728a1f@n15g2000yqf.googlegroups.com> On May 9, 12:19?am, Steven D'Aprano wrote: > On Sat, 08 May 2010 16:39:33 -0700, Carl Banks wrote: > > GPL is about fighting a holy war against commercial software. > > Much GPL software *is* commercial software. Given that you're so badly > misinformed about the GPL that you think it can't be commercial, why > should we pay any attention to your opinions about it? I think, when Carl wrote "commercial" he meant what many others, including RMS, would call "proprietary." And, although many people who use the GPL license may not be fighting the holy war, the original author of the license certainly is. When asked how he sees proprietary software businesses making a profit when more and more software is free, RMS replied "That's unethical, they shouldn't be making any money. I hope to see all proprietary software wiped out. That's what I aim for. That would be a World in which our freedom is respected. A proprietary program is a program that is not free. That is to say, a program that does respect the user's essential rights. That's evil. A proprietary program is part of a predatory scheme where people who don't value their freedom are drawn into giving it up in order to gain some kind of practical convenience." And while I agree somewhat with RMS when the subject is certain proprietary companies that try really hard to lock in users and lock up their data, I don't view all proprietary software as evil, and I certainly agree that RMS's language is couched in religious rhetoric. Regards, Pat From steve at REMOVE-THIS-cybersource.com.au Sun May 9 02:17:07 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 06:17:07 GMT Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> Message-ID: <4be65362$0$27783$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 14:06:33 -0700, Oltmans wrote: > On May 9, 1:53?am, superpollo wrote: > >> add = lambda a,b: a+b >> for i in reduce(add,a): >> ? ? ?print i > > This is very neat. Thank you. Sounds like magic to me. Can you please > explain how does that work? Many thanks again. Don't use this except for small lists, it is very inefficient and will be slow for large lists. It is a Shlemiel The Painter algorithm: http://www.joelonsoftware.com/articles/fog0000000319.html The most idiomatic solution is a simple, straightforward nested iteration: for sublist in a: for item in sublist: do_something_with(item) Say that there are 10 sublists with 10 items each. Then nested iteration will iterate 100 times in total. The solution with reduce will iterate: 10+10 # add the first sublist and the second sublist 20+10 # add the third sublist 30+10 # add the fourth sublist 40+10 # and so on... 50+10 60+10 70+10 80+10 90+10 # add the last sublist 100 # and now iterate over the combined list or 640 times in total. If there are 100 sublists of 10 items each, the performance is even worse: 51,490 for the reduce solution, versus 1000 for the nested iteration. Admittedly those iterations will be in fast C code instead of slow Python code, which is why you might not notice the difference at first, but you're still doing a lot of unnecessary work which takes time. How much time? Python makes it easy to find out. >>> from timeit import Timer >>> setup = "data = [range(10) for i in range(10)]" >>> t1 = Timer("""for sublist in data: ... for item in sublist: ... pass""", setup) >>> t2 = Timer("""for item in reduce(lambda x,y: x+y, data): ... pass""", setup) >>> >>> min(t1.repeat(number=100000)) 0.94107985496520996 >>> min(t2.repeat(number=100000)) 1.7509880065917969 So for ten sublists of ten items each, the solution using reduce is nearly twice as slow as the nested iteration. If we make the number of lists ten times larger, the nested for-loop solution takes ten times longer, as you would expect: >>> setup = "data = [range(10) for i in range(100)]" >>> t1 = Timer("""for sublist in data: ... for item in sublist: ... pass""", setup) >>> min(t1.repeat(number=100000)) 10.349304914474487 But the reduce solution slows down by a factor of thirty-two rather than ten: >>> t2 = Timer("""for item in reduce(lambda x,y: x+y, data): ... pass""", setup) >>> min(t2.repeat(number=100000)) 58.116463184356689 If we were to increase the number of sublists further, the reduce solution will perform even more badly. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun May 9 02:25:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 06:25:01 GMT Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4be6553d$0$27783$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 14:27:32 -0700, dasacc22 wrote: > U presume entirely to much. I have a preprocessor that normalizes > documents while performing other more complex operations. Theres > nothing buggy about what im doing I didn't *presume* anything, I took your example code and ran it and discovered that it didn't do what you said it was doing. -- Steven From no.email at nospam.invalid Sun May 9 02:42:31 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 23:42:31 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <9f54536c-8428-4de8-bba8-fa16fe728a1f@n15g2000yqf.googlegroups.com> Message-ID: <7xr5lllgo8.fsf@ruckus.brouhaha.com> Patrick Maupin writes: > I certainly agree that RMS's language is couched in religious rhetoric. I would say political movement rhetoric. He's not religious. He uses the word "spiritual" sometimes but has made it clear he doesn't mean that in a religious sense. From pavlovevidence at gmail.com Sun May 9 03:05:59 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 9 May 2010 00:05:59 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> Message-ID: On May 8, 10:19?pm, Steven D'Aprano wrote: > On Sat, 08 May 2010 16:39:33 -0700, Carl Banks wrote: > > GPL is about fighting a holy war against commercial software. > > Much GPL software *is* commercial software. Given that you're so badly > misinformed about the GPL that you think it can't be commercial, why > should we pay any attention to your opinions about it? In the interests of not allowing petty semantics to interfere with this rational discussion, I will correct myself slightly although I diagree with the terminology. The GPL is a holy war against closed source commercial software. Anyone who GPL's their code is fighting that war whether they intend to or not. And losing it, I might add. There are a small number--maybe 20--of GPLed packages that have the leverage to force monopolistic corporations to release their code when they wouldn't have otherwise. Even then it's only bits and pieces (e.g., NVIDIA's kernel model-- fortunately the X Video driver is allowed to be closed source, otherwise there'd be no driver on Linux). Meanwhile there's thousands of GPL packages the corporations won't touch and they--and we--suffer because of it. I might like to buy a commercial plugin for Blender, but there aren't any because it's GPL. If good commercial plugins are available, maybe some firms would find Blender a reasonable low-cost alternative to expensive products like Maya, thus benefiting the whole community. As it is, there is no chance of that happening, all thanks to GPL. That's the real effect of the GPL, the one that happens on the ground every day. But if you want to think that the GPL is furthering the cause of open souce on account of a few companies who donated a few lines of code to GCC, be my guest. As for open-source "commercial" software, there's a different holy war being waged against it, namely reality. No one actually makes money on it. Open source is the bait to attract customers to buy other services, ans that's what they make money on. To me this means it's not commercial but it doesn't matter: the GPL even interferes with this. Companies do make money supporting GPL, but it's in spite of GPL and not because of it. A permissive license would allow companies more freedom to offer their proprietary enhancements. Bottom line is, GPL hurts everyone: the companies and open source community. Unless you're one of a handful of projects with sufficient leverage, or are indeed a petty jealous person fighting a holy war, the GPL is a bad idea and everyone benefits from a more permissive licence. Carl Banks From pavlovevidence at gmail.com Sun May 9 03:22:21 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 9 May 2010 00:22:21 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <7x39y1vl07.fsf@ruckus.brouhaha.com> <73bcbd04-4e31-4532-a220-9389c5c299d9@r11g2000yqa.googlegroups.com> <7x4oihn1eh.fsf@ruckus.brouhaha.com> Message-ID: <3bf126e8-0f77-48a9-ba29-8650ae79f09b@j35g2000yqm.googlegroups.com> On May 8, 9:29?pm, Paul Rubin wrote: > Carl Banks writes: > > If a commercial developer has a EULA that prevents users from > > combining their tools with tools from (say) their competitors, > > Do you mean something like a EULA that stops you from buying a copy of > Oracle and combining it with tools from IBM on the computer that you > install Oracle on? Yes > ?Those EULAs exist but are not remotely comparable to > the GPL. They're not exactly the same but they're quite comparable and both disrespectful to the user. > > The GPL does exactly that, > > No it doesn't (not like the above). ?You, the licensee under the GPL, > can make those combinations and use them as much as you want on your own > computers. ?You just can't distribute the resulting derivative to other > people. ?With proprietary software you can't redistribute the software > to other people from day zero (or even use more copies within your own > company than you've paid for), regardless of whether you've combined it > with anything. ?And since you usually don't get the source code, it's > awfully hard to make derived combinatoins. Really, commercial closed source programs don't have APIs? If the EULA isn't disrespectful likle the GPL, then I could write a program that links against multiple closed source API and distribute closed or open source binaries. Can't do either if you change one of the proprietary programs to GPL. GPL is a lot more restrictive than mere closed source proprietary when it comes to stuff like that. Carl Banks From isso.moh at gmail.com Sun May 9 04:15:59 2010 From: isso.moh at gmail.com (mohamed issolah) Date: Sun, 9 May 2010 10:15:59 +0200 Subject: win32com Message-ID: hey, there is an alternative of win32com in linux? what i want to say : can communicate with application (ex: evolution or another) throught python like in windows with win32com thanks, sorry for my english need help -- issolah mohamed -------------- next part -------------- An HTML attachment was scrubbed... URL: From dasarathulagopi at gmail.com Sun May 9 04:16:21 2010 From: dasarathulagopi at gmail.com (gopi krishna) Date: Sun, 9 May 2010 13:46:21 +0530 Subject: flattening list Message-ID: Hi , Anyone can pls help me in flattening the list. if p is the my list which is defined below p=[1,[2,3,4],[5,6,],9,[[11,12]]] from the above how to get a list as [1,2,3,4,5,6,9,11,12] -------------- next part -------------- An HTML attachment was scrubbed... URL: From dasarathulagopi at gmail.com Sun May 9 04:19:20 2010 From: dasarathulagopi at gmail.com (gopi krishna) Date: Sun, 9 May 2010 13:49:20 +0530 Subject: can we change the variables with function Message-ID: Hi can I change the variable in a function using the function suppose >>>def a(): x=20 can we change the variable using the function -------------- next part -------------- An HTML attachment was scrubbed... URL: From dasarathulagopi at gmail.com Sun May 9 04:20:18 2010 From: dasarathulagopi at gmail.com (gopi krishna) Date: Sun, 9 May 2010 13:50:18 +0530 Subject: Why list comprehension faster than for loop? Message-ID: Why list comprehension faster than for loop? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun May 9 04:21:38 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 May 2010 01:21:38 -0700 Subject: flattening list In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 1:16 AM, gopi krishna wrote: > Hi , > ??? Anyone can pls help me in flattening the list. > if p is the my list which is defined below > p=[1,[2,3,4],[5,6,],9,[[11,12]]] > from the above how to get a list > as [1,2,3,4,5,6,9,11,12] http://www.lmgtfy.com/?q=python+flatten+list Cheers, Chris -- python-list doesn't like doing other people's homework. http://blog.rebertia.com From clp2 at rebertia.com Sun May 9 04:25:02 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 May 2010 01:25:02 -0700 Subject: can we change the variables with function In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 1:19 AM, gopi krishna wrote: > Hi > ?? can I change the variable in a function using the function > suppose >>>>def a(): > x=20 > can we change the variable using the function Your question is incomprehensible. Please rephrase it more clearly and provide more details. Regards, Chris -- http://blog.rebertia.com From matthew.brett at gmail.com Sun May 9 04:28:14 2010 From: matthew.brett at gmail.com (Matthew Brett) Date: Sun, 9 May 2010 01:28:14 -0700 (PDT) Subject: zlib.decompress fails, zlib.decompressobj succeeds - bug or feature? Message-ID: <089c36fa-a2a9-463d-af21-06403e0e6afb@t14g2000prm.googlegroups.com> Hi, I sorry if this is a bad place to ask, but I wanted to find out if the behavior I'm seeing is a bug. I maintain scipy's matlab file readers, and I came across a zlib compressed string that causes a zlib error on decompression, but only with zlib.decompress, not zlib.decompressobj. I saved the original compressed string as a binary file at http://dl.dropbox.com/u/794947/mat.bin Now if I do: import zlib data = open('mat.bin', 'rb').read() out = zlib.decompress(data) I get an error : Error -5 while decompressing data) If instead I do this: out = zlib.decompressobj().decompress(data) I get a usable uncompressed string. I was expecting these two calls to do the same thing. Is that expectation right? If not, is there somewhere I could find out why? Thanks a lot, Matthew From contact at xavierho.com Sun May 9 04:29:27 2010 From: contact at xavierho.com (Xavier Ho) Date: Sun, 9 May 2010 18:29:27 +1000 Subject: Why list comprehension faster than for loop? In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 6:20 PM, gopi krishna wrote: > Why list comprehension faster than for loop? > > Because Python optimises for certain special cases, when the number of iterations is predicable in a list comprehension. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Sun May 9 04:37:12 2010 From: contact at xavierho.com (Xavier Ho) Date: Sun, 9 May 2010 18:37:12 +1000 Subject: can we change the variables with function In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 6:19 PM, gopi krishna wrote: > Hi > can I change the variable in a function using the function > suppose > >>>def a(): > x=20 > can we change the variable using the function > Can you give us an example of how you'd like to "change the variable", in code, and show us what didn't work? We might be able to help with some sample code. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From ideamonk at gmail.com Sun May 9 04:38:29 2010 From: ideamonk at gmail.com (Abhishek Mishra) Date: Sun, 9 May 2010 14:08:29 +0530 Subject: flattening list In-Reply-To: References: Message-ID: thanks for the excercise just figured out this - #!/usr/bin/env python import sys sys.setrecursionlimit(2000) def flatten(l): flattened = [] for i in l: if type(i) == type([]): flattened += flatten(i) else: flattened.append(i) return flattened if __name__=='__main__': p=[1,[2,3,4],[5,6,],9,[[11,12]]] print flatten(p) But a google search will lead you to more elegant generic solutions :) On Sun, May 9, 2010 at 1:46 PM, gopi krishna wrote: > Hi , > Anyone can pls help me in flattening the list. > if p is the my list which is defined below > p=[1,[2,3,4],[5,6,],9,[[11,12]]] > from the above how to get a list > as [1,2,3,4,5,6,9,11,12] > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ideamonk at gmail.com Sun May 9 04:39:52 2010 From: ideamonk at gmail.com (Abhishek Mishra) Date: Sun, 9 May 2010 14:09:52 +0530 Subject: can we change the variables with function In-Reply-To: References: Message-ID: Could you also demonstrate with an example as to what kind of effect you're expecting from whatever you've been desiring to do? On Sun, May 9, 2010 at 1:49 PM, gopi krishna wrote: > Hi > can I change the variable in a function using the function > suppose > >>>def a(): > x=20 > can we change the variable using the function > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun May 9 04:47:12 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 May 2010 01:47:12 -0700 Subject: win32com In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 1:15 AM, mohamed issolah wrote: > hey, > > there is an alternative of win32com in linux? > > what i want to say : can communicate with application (ex: evolution or > another) throught python like in windows with win32com The closest equivalent would probably be python-dbus. See the "Python" section of http://www.freedesktop.org/wiki/Software/DBusBindings Information on D-Bus generally: http://en.wikipedia.org/wiki/D-Bus Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Sun May 9 05:01:58 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 May 2010 02:01:58 -0700 Subject: can we change the variables with function In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 1:33 AM, gopi krishna wrote: > My Question is > can we access the variables defined in a function ? >>>> class A: > ? ? def b(self): > ? ? ? ? x=40 > ? ? z=40 > > >>>> q=A() >>>> q.z > 40 >>>> q.z=60 >>>> q.z > 60 > We can access the variables defined in a class as shown above ?in the same > way can we access the variables defined in a method? There is likely a very hackish way to do it involving bytecode disassembly, but it's ill-advised. Further, what if the variable isn't a constant, as `y` is in the following example?: ? ?def foo(self, x): ? ? ? ?y = x + 3 What would you expect to get for y's value? Why would you want such an ability in the first place? I suspect that if you explained your use-case/situation, someone could offer a much better alternative approach. Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun May 9 05:18:10 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 09:18:10 GMT Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be645cf@dnews.tpgi.com.au> Message-ID: <4be67dd2$0$27783$c3e8da3@news.astraweb.com> On Sun, 09 May 2010 15:17:38 +1000, Lie Ryan wrote: > On 05/09/10 07:09, G?nther Dietrich wrote: >> >> Why not this way? >> >>>>> a = [[1,2,3,4], [5,6,7,8]] >>>>> for i in a: >> .... for j in i: >> .... print(j) >> .... >> 1 >> 2 >> 3 >> 4 >> 5 >> 6 >> 7 >> 8 >> >> Too simple? > > IMHO that's more complex due to the nested loop, What's so complex about a nested loop? And why are you saying that it is "more complex" than the Original Poster's solution, which also had a nested loop, plus a pointless list comprehension? > though I would > personally do it as: > > a = [ [1,2,3,4], [5,6,7,8] ] > from itertools import chain > for i in chain.from_iterable(a): > print i > > so it won't choke when 'a' is an infinite stream of iterables. Neither will a nested for-loop. -- Steven From utente at esempio.net Sun May 9 05:20:35 2010 From: utente at esempio.net (superpollo) Date: Sun, 09 May 2010 11:20:35 +0200 Subject: solve a newspaper quiz Message-ID: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> "if a b c are digits, solve ab:c=a*c+b" solved in one minute with no thought: for a in range(10): for b in range(10): for c in range(10): try: if (10.*a+b)/c==a*c+b: print "%i%i:%i=%i*%i+%i" % (a,b,c,a,c,b) except: pass any suggestion for improvement? bye From martin.hellwig at dcuktec.org Sun May 9 05:22:47 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sun, 09 May 2010 10:22:47 +0100 Subject: Picking a license In-Reply-To: <7xk4rdpwd4.fsf@ruckus.brouhaha.com> References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> Message-ID: On 05/09/10 04:49, Paul Rubin wrote: > As I read it, he is saying that when someone releases free software, > they have "for all intends and purposes lost control over its use", so > they "should have made peace with the fact" and surrender gracefully. > I'm asking why he doesn't think Microsoft has lost control the same way. Microsoft has indeed lost control of it in the same way, it is just because we here in the 'western' world spend huge amount of money on prosecuting and bringing to 'justice' does who, whether for commercial purposes or otherwise, make a copy of a piece of code. Think about it, it is not stealing, the original is still there and no further resources where needed from the original developer. What I am saying is that all this license crap is only needed because we are used to a commercial environment where we can repeatedly profit from the same work already done. I am not saying that you should not profit, of course you should otherwise there is no interest in making it in the first place. What I am saying is that we as developers should encourage pay for work and not pay for code. This will, as I believe it, keep everything much more healthy and balanced. At least we can cut all the crap of software patents and copyrights. For those who say it can't be done, sure it can, all you have to do is nothing, it takes effort to enforce policies. -- mph From contact at xavierho.com Sun May 9 05:31:49 2010 From: contact at xavierho.com (Xavier Ho) Date: Sun, 9 May 2010 19:31:49 +1000 Subject: solve a newspaper quiz In-Reply-To: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> References: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> Message-ID: On Sun, May 9, 2010 at 7:20 PM, superpollo wrote: > "if a b c are digits, solve ab:c=a*c+b" > Sorry, what does the notation ab:c mean? Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sun May 9 05:58:17 2010 From: andreengels at gmail.com (Andre Engels) Date: Sun, 9 May 2010 11:58:17 +0200 Subject: solve a newspaper quiz In-Reply-To: References: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> Message-ID: On Sun, May 9, 2010 at 11:31 AM, Xavier Ho wrote: > On Sun, May 9, 2010 at 7:20 PM, superpollo wrote: >> >> "if a b c are digits, solve ab:c=a*c+b" > > Sorry, what does the notation ab:c mean? The number ab divided by c. -- Andr? Engels, andreengels at gmail.com From ldo at geek-central.gen.new_zealand Sun May 9 05:59:15 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 09 May 2010 21:59:15 +1200 Subject: Windows - select.select, timeout and KeyboardInterrupt References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: In message , exarkun at twistedmatrix.com wrote: > On 07:48 am, ldo at geek-central.gen.new_zealand wrote: > >>In message , >>exarkun at twistedmatrix.com wrote: >> >>>This is a good example of why it's a bad idea to use select on >>>Windows. >>>Instead, use WaitForMultipleObjects. >> >>How are you supposed to write portable code, then? > > With WaitForMultipleObjects on Windows, epoll on Linux, kqueue on BSD, > event completion on Solaris, etc... > > Sound like more work than using select() everywhere? Yea, a bit. But > not once you abstract it away from your actual application code. After > all, it's not like these *do* different things. They all do the same > thing (basically) - differently. Do you understand what ?portable? means? From trent at snakebite.org Sun May 9 07:02:28 2010 From: trent at snakebite.org (Trent Nelson) Date: Sun, 9 May 2010 04:02:28 -0700 Subject: Why list comprehension faster than for loop? In-Reply-To: References: Message-ID: <58440DD8-A427-4280-BF0F-509BC7DEF750@snakebite.org> On 9 May 2010, at 16:29, Xavier Ho wrote: On Sun, May 9, 2010 at 6:20 PM, gopi krishna > wrote: Why list comprehension faster than for loop? Because Python optimises for certain special cases, when the number of iterations is predicable in a list comprehension. The fact that list comprehensions can only be comprised of expressions, not statements, is a considerable factor, as much less work is required behind the scenes for each iteration. Another factor is that the underlying iteration mechanism for list comprehensions is much closer to a C loop than execution of a for loop. Exact same reason Perl's map { } is much faster than an equivalent for/foreach loop. (Psyco can speed up certain list comprehensions quite significantly, too, but it isn't able to perform the same magic on an equivalent for loop.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alain at dpt-info.u-strasbg.fr Sun May 9 07:02:45 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sun, 09 May 2010 13:02:45 +0200 Subject: solve a newspaper quiz References: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> Message-ID: <87aas9xrqi.fsf@dpt-info.u-strasbg.fr> superpollo writes: > "if a b c are digits, solve ab:c=a*c+b" > > solved in one minute with no thought: Obviously. > for a in range(10): > for b in range(10): > for c in range(10): > try: > if (10.*a+b)/c==a*c+b: > print "%i%i:%i=%i*%i+%i" % (a,b,c,a,c,b) > except: > pass > > any suggestion for improvement? Here is my take (sorry, no nice prints): # c = 0 has no solution # c = 1 -> 9a = 0 whatever b for b in xrange(10): print 0,b,1 # c = 2 -> 6a = b for a in xrange(2): print a,a*6,2 # c = 3 -> a = 2b for b in xrange(0,5): print 2*b,b,3 # c = 4-9 -> a = b = 0 for c in xrange(4,10): print 0,0,c Improvements: a lot more fun to design, a lot more efficient to run -- Alain. From isso.moh at gmail.com Sun May 9 07:37:19 2010 From: isso.moh at gmail.com (mohamed issolah) Date: Sun, 9 May 2010 13:37:19 +0200 Subject: win32com In-Reply-To: References: Message-ID: hey, I wich to have an example please need help 2010/5/9 Chris Rebert > On Sun, May 9, 2010 at 1:15 AM, mohamed issolah > wrote: > > hey, > > > > there is an alternative of win32com in linux? > > > > what i want to say : can communicate with application (ex: evolution or > > another) throught python like in windows with win32com > > The closest equivalent would probably be python-dbus. See the "Python" > section of http://www.freedesktop.org/wiki/Software/DBusBindings > > Information on D-Bus generally: http://en.wikipedia.org/wiki/D-Bus > > Cheers, > Chris > -- > http://blog.rebertia.com > -- issolah mohamed -------------- next part -------------- An HTML attachment was scrubbed... URL: From pan-news at infocentrality.co.uk Sun May 9 07:39:13 2010 From: pan-news at infocentrality.co.uk (TFH) Date: Sun, 09 May 2010 11:39:13 GMT Subject: accessing superclass methods from subclass References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: On Sat, 08 May 2010 16:50:11 -0700, ben wrote: > Why doesn't this work: > > class C1: > def f1(self): > print("f1") > > class C2(C1): > f1() > > > It throws this error: > > Traceback (most recent call last): > File "./c1.py", line 7, in > class C2(C1): > File "./c1.py", line 8, in C2 > f1() > NameError: name 'f1' is not defined > > > f1() is an attribute of class C1, C2 inherits C1, so why can't it see > it? > > thanks! Try this: class C1: def f1(self): return "From C1: f1" class C2(C1): def f2(self): return self.f1() c2 = C2() print c2.f2() regards Trevor From python.list at tim.thechases.com Sun May 9 07:42:02 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 09 May 2010 06:42:02 -0500 Subject: A more general solution In-Reply-To: <44e7ce5a-6ec3-460e-9f36-05762ebe59b0@i9g2000yqi.googlegroups.com> References: <44e7ce5a-6ec3-460e-9f36-05762ebe59b0@i9g2000yqi.googlegroups.com> Message-ID: <4BE69F8A.9040304@tim.thechases.com> On 05/08/2010 10:33 PM, 3Jane wrote: > You could interpret [[1,2,3,4],[5,6,7,8]] as a tree and > your task as traversal of its leaves. All solutions before > would not work with trees with bigger height. > > Here is how to traverse such trees recursively: > > def eventualPrint(x): > for v in x: > if isinstance(v, list): eventualPrint(x) > else: print(v) > > Then eventualPrint(a) does the job. Caveat: ...but wanders off into the bushes for recursive lists :) x = [1,2,3] x.append (x) eventualPrint(x) Not a particular concern in this case since I'm now two levels of hypothetical removed from the OP's question (from flatten one layer to recursively flattening arbitrary nestings to recursively flattening arbitrary & self-referential nestings)... For the record, I'm in the itertools camp of proposed solutions to the OP's question. -tkc From qq13234722 at gmail.com Sun May 9 07:56:41 2010 From: qq13234722 at gmail.com (=?UTF-8?B?55av5Zu+54G1?=) Date: Sun, 9 May 2010 04:56:41 -0700 (PDT) Subject: The python theme T-shirt is cool ? Message-ID: <065df098-2db4-4743-b3ff-7fd244573fe0@40g2000pry.googlegroups.com> To see the picture http://wooogooo.pixa.us/images/18838653/1 http://wooogooo.pixa.us/images/18838652/2 Welcome to discus . lol From darwin at nowhere.com Sun May 9 08:03:29 2010 From: darwin at nowhere.com (Paul Hemans) Date: Sun, 9 May 2010 22:03:29 +1000 Subject: Extract a bordered, skewed rectangle from an image References: Message-ID: Thanks David, that is a 'tonne' of information. I am going to have a play with it, probably looking at masking out the contents of the label and finding the label border within the scanned document is the place to start. Looks like there is going to be a learning curve here. Thanks again for your help you really put a lot of effort into this. From e_d_k at yahoo.com Sun May 9 08:09:22 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Sun, 9 May 2010 05:09:22 -0700 (PDT) Subject: Picking a license In-Reply-To: Message-ID: <305451.48785.qm@web58704.mail.re1.yahoo.com> Stepping back from the political/philosophical/religious arguments, I'd like to give some adjectival advice based on my own perspective. How you license your software should be based on how you want it to be used. If you are releasing an end user application I do not care how you license it. If it is useful I will use it. If you believe some of the code is of commercial value, and that you hope to profit from it you should use the GPL, so you can license it separately to someone who wants to use it in a closed source product. If, on the other hand you are releasing a library, to be incorporated into other products, If you release it under the GPL I will not take the time to learn it. I do not want to have to think about what took I can legally use for what job. Libraries with permissive licenses can be used in any project. Many contracts prohibit the use of GPL or LGPL code. So I do not waist my time learning to use libraries covered by restrictive licenses. So if you want me to even consider using your library do not use GPL, or LGPL. I favor the Boost license in this case. I hope this is useful. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From lie.1296 at gmail.com Sun May 9 08:52:55 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 09 May 2010 22:52:55 +1000 Subject: Kindly show me a better way to do it In-Reply-To: <4be67dd2$0$27783$c3e8da3@news.astraweb.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be645cf@dnews.tpgi.com.au> <4be67dd2$0$27783$c3e8da3@news.astraweb.com> Message-ID: <4be6b084$1@dnews.tpgi.com.au> On 05/09/10 19:18, Steven D'Aprano wrote: > On Sun, 09 May 2010 15:17:38 +1000, Lie Ryan wrote: > >> On 05/09/10 07:09, G?nther Dietrich wrote: >>> >>> Why not this way? >>> >>>>>> a = [[1,2,3,4], [5,6,7,8]] >>>>>> for i in a: >>> .... for j in i: >>> .... print(j) >>> .... >>> 1 >>> 2 >>> 3 >>> 4 >>> 5 >>> 6 >>> 7 >>> 8 >>> >>> Too simple? >> >> IMHO that's more complex due to the nested loop, > > What's so complex about a nested loop? one more nested tab. That extra whitespaces is quite irritating. And why are you saying that it is > "more complex" than the Original Poster's solution, which also had a > nested loop, plus a pointless list comprehension? You misunderstood. Tycho Anderson posted an itertools.chain(*chain) solution for which Gunther Dietrich remarked "why not a nested loop"; I am replying to Gunther Dietrich's nested loop with "because nested loop is more complex than chain()" and added that the original[Tycho Anderson's] chain solution has a subtle bug when facing infinite generator of iterables. >> though I would >> personally do it as: >> >> a = [ [1,2,3,4], [5,6,7,8] ] >> from itertools import chain >> for i in chain.from_iterable(a): >> print i >> >> so it won't choke when 'a' is an infinite stream of iterables. > > Neither will a nested for-loop. From fuzzyman at gmail.com Sun May 9 08:54:18 2010 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 9 May 2010 05:54:18 -0700 (PDT) Subject: Python is cool!! References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> <4BA8F56D.6060305@timgolden.me.uk> Message-ID: On Mar 23, 10:04?pm, geremy condra wrote: > On Tue, Mar 23, 2010 at 1:07 PM, Tim Golden wrote: > > On 23/03/2010 16:55, Jose Manuel wrote: > > >> I have been learning Python, and it is amazing .... I am using the > >> tutorial that comes with the official distribution. > > >> At the end my goal is to develop applied mathematic in engineering > >> applications to be published on the Web, specially on app. oriented to > >> simulations and control systems, I was about to start learning Java > >> but I found Python which seems easier to learn that Java. > > >> Would it be easy to integrate Python in Web pages with HTML? I have > >> read many info on Internet saying it is, and I hope so .... > > > You probably want to be looking at IronPython and Silverlight. > > In fact, the prolific Michael Foord has already produced an > > example of this, which gives you the Python tutorial online! > > > ?http://trypython.org > > > TJG > > Granted that I know next to nothing about webwork, but > is there a reason why you recommended a competing, > nonstandard technology rather than simply pointing him > towards more standards compliant tools that exist to do > exactly what he asked for? Seems a bit dodgy to > advocate a closed solution when the alternative has 100% > market share. > Maybe because it is a good tool and for the specific task it achieves there is nothing close... The closest is Skulpt which is very much an incomplete implementation of Python that runs in the browser. Michael Foord -- http://voidspace.org.uk/blog From solipsis at pitrou.net Sun May 9 08:57:50 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 9 May 2010 14:57:50 +0200 Subject: zlib.decompress fails, zlib.decompressobj succeeds - bug or feature? References: <089c36fa-a2a9-463d-af21-06403e0e6afb@t14g2000prm.googlegroups.com> Message-ID: <20100509145750.345b72b1@pitrou.net> On Sun, 9 May 2010 01:28:14 -0700 (PDT) Matthew Brett wrote: > > If instead I do this: > > out = zlib.decompressobj().decompress(data) How about: d = zlib.decompressobj() out = d.decompress(data) + d.flush() ? Notice the documentation for decompressobj.decompress (emphasis mine): ?Decompress string, returning a string containing the uncompressed data corresponding to *at least part* of the data in string?. From wolfram.hinderer at googlemail.com Sun May 9 08:58:18 2010 From: wolfram.hinderer at googlemail.com (Wolfram Hinderer) Date: Sun, 9 May 2010 05:58:18 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> Message-ID: On 8 Mai, 21:46, Steven D'Aprano wrote: > On Sat, 08 May 2010 12:15:22 -0700, Wolfram Hinderer wrote: > > Returning s[:-1 - len(t)] is faster. > > I'm sure it is. Unfortunately, it's also incorrect. > However, s[:-len(t)] should be both faster and correct. Ouch. Thanks for correcting me. No, I'll never tell how that -1 crept in... From guillermo.listas at googlemail.com Sun May 9 09:03:41 2010 From: guillermo.listas at googlemail.com (Guillermo) Date: Sun, 9 May 2010 06:03:41 -0700 (PDT) Subject: virtualenvwrapper for Windows (Powershell) Message-ID: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com> Hi, If you've ever missed it on Windows and you can use Powershell, you might want to take a look at this port of virtualenvwrapper: http://bitbucket.org/guillermooo/virtualenvwrapper/wiki/Home It's a work in progress, but is should be fairly functional already. It requires Powershell v2. Regards, Guillermo From sjmachin at lexicon.net Sun May 9 09:28:14 2010 From: sjmachin at lexicon.net (John Machin) Date: Sun, 9 May 2010 13:28:14 +0000 (UTC) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: dasacc22 gmail.com> writes: > > U presume entirely to much. I have a preprocessor that normalizes > documents while performing other more complex operations. Theres > nothing buggy about what im doing Are you sure? Your "solution" calculates (the number of leading whitespace characters) + (the number of TRAILING whitespace characters). Problem 1: including TRAILING whitespace. Example: "content" + 3 * " " + "\n" has 4 leading spaces according to your reckoning; should be 0. Fix: use lstrip() instead of strip() Problem 2: assuming all whitespace characters have *effective* width the same as " ". Examples: TAB has width 4 or 8 or whatever you want it to be. There are quite a number of whitespace characters, even when you stick to ASCII. When you look at Unicode, there are heaps more. Here's a list of BMP characters such that character.isspace() is True, showing the Unicode codepoint, the Python repr(), and the name of the character (other than for control characters): U+0009 u'\t' ? U+000A u'\n' ? U+000B u'\x0b' ? U+000C u'\x0c' ? U+000D u'\r' ? U+001C u'\x1c' ? U+001D u'\x1d' ? U+001E u'\x1e' ? U+001F u'\x1f' ? U+0020 u' ' SPACE U+0085 u'\x85' ? U+00A0 u'\xa0' NO-BREAK SPACE U+1680 u'\u1680' OGHAM SPACE MARK U+2000 u'\u2000' EN QUAD U+2001 u'\u2001' EM QUAD U+2002 u'\u2002' EN SPACE U+2003 u'\u2003' EM SPACE U+2004 u'\u2004' THREE-PER-EM SPACE U+2005 u'\u2005' FOUR-PER-EM SPACE U+2006 u'\u2006' SIX-PER-EM SPACE U+2007 u'\u2007' FIGURE SPACE U+2008 u'\u2008' PUNCTUATION SPACE U+2009 u'\u2009' THIN SPACE U+200A u'\u200a' HAIR SPACE U+200B u'\u200b' ZERO WIDTH SPACE U+2028 u'\u2028' LINE SEPARATOR U+2029 u'\u2029' PARAGRAPH SEPARATOR U+202F u'\u202f' NARROW NO-BREAK SPACE U+205F u'\u205f' MEDIUM MATHEMATICAL SPACE U+3000 u'\u3000' IDEOGRAPHIC SPACE Hmmm, looks like all kinds of widths, from zero upwards. From dickinsm at gmail.com Sun May 9 09:34:38 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 9 May 2010 06:34:38 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> <489ffaa0-1563-45a1-93aa-cc83cdd6abd9@j35g2000yqm.googlegroups.com> <4be64467$0$27783$c3e8da3@news.astraweb.com> Message-ID: On May 9, 6:13?am, Steven D'Aprano wrote: > On Sat, 08 May 2010 13:46:59 -0700, Mark Dickinson wrote: > >> However, s[:-len(t)] should be both faster and correct. > > > Unless len(t) == 0, surely? > > Doh! The hazards of insufficient testing. Thanks for catching that. I have a love-hate relationship with the negative index semantics for exactly this reason: code like 'x[-n]' always seems smelly to me. It's often not what the code author actually wanted, except when n is guaranteed strictly positive for some reason. 'x[-1]' is fine, of course. -- Mark From e_d_k at yahoo.com Sun May 9 09:58:13 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Sun, 9 May 2010 06:58:13 -0700 (PDT) Subject: Picking a license (an atempt to give real advice) Message-ID: <490877.83999.qm@web58706.mail.re1.yahoo.com> Stepping back from the political/philosophical/religious arguments, I'd like to give some real advice based on my own perspective. How you license your software should be based on how you want it to be used. If you are releasing an end user application I do not care how you license it. If it is useful I will use it. If you believe some of the code is of commercial value, and that you hope to profit from it you should use the GPL, so you can license it separately to someone who wants to use it in a closed source product. If, on the other hand you are releasing a library, to be incorporated into other products, if you release it under the GPL I will not take the time to learn it. I do not want to have to think about what took I can legally use for what job. Libraries with permissive licenses can be used in any project. I can not use GPL or LGPL code in many contracts. So I do not waist my time learning to use libraries covered by restrictive licenses. So if you want me to even consider using your library do not use GPL, or LGPL. I favor the Boost license in this case. Again, if you want to also offer other licenses, for a fee, you should use GPL, I will not use it, but others might, and you may get paid for your work. The bottom line is: if you want the largest possible user base, go with a less restrictive license; If you hope to profit financially from your work, use the GPL. Just my $0.02, I hope it is helpful. ???-EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From lie.1296 at gmail.com Sun May 9 10:01:59 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 10 May 2010 00:01:59 +1000 Subject: accessing superclass methods from subclass In-Reply-To: References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: <4be6c0b3$1@dnews.tpgi.com.au> On 05/09/10 10:05, Chris Rebert wrote: > Additionally, it makes no sense to call an *instance* method such as > f1() in a class context. Or in Java-speak: you can't call a non-static > method in a static context. Actually, in python it does make sense, with a caveat that you have to provide the instance as the first argument (i.e. as 'self'). The semantic of "instance method" in python is a class method whose first argument is curried/bound to a specific instance. I think it's better not to confuse OP even further by drawing comparison with Java; as Python and Java has a confusingly similar name but wholly different "static method". Also python has nothing similar to "static context". > The way classes work in Python, C2 isn't actually created until after > its body suite has been executed, so that's why Python can't find f1. That isn't the reason why OP's code doesn't work. Python cannot find f1 because there is no f1 in the current scope. Class definition in Python is done by *execution of class body*; the class body is executed in *a new scope*, which will later become the class' scope. (btw, a "scope" in python is nothing but sugar for a dictionary (waves a limb airily)). An instance's scope is a shadow of the class' scope [with respect to descriptor protocol] + __dict__ + the rest of __mro__; and this __mro__ is not known until the class body execution is finished and type() is called to create the class. That's why f1() is not in the class' scope at class declaration time. In fact, the whole class declaration syntax is more or less sugar for: class_scope = {} exec "pass" in globals(), class_scope Foo = type("Foo", (Parent1, Parent2), class_scope) # class Foo(Parent1, Parent2): # pass the exec statement cannot access its Parent scope, except by explicit reference through globals() (e.g. Parent1.foo). From catalinfest at gmail.com Sun May 9 10:22:19 2010 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Sun, 9 May 2010 07:22:19 -0700 (PDT) Subject: Getting a Python program to run of off a flash drive? References: Message-ID: On Apr 1, 4:22?am, timo verbeek wrote: > On Apr 1, 12:48?am, Abethebabe wrote: > > > I wanted to know if there was a way I could get a Python program to > > run off of my flash drive as soon as the computer (Windows) detected > > the device? > > > For example I could have a a simple program that would create a text > > document on the computers desktop when my flash drive is detected. > > You could use Autorun.inf if your using Windows but for linux I don't > now Portable python from http://www.portablepython.com/ From andre.roberge at gmail.com Sun May 9 12:03:15 2010 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 9 May 2010 09:03:15 -0700 (PDT) Subject: Python is cool!! References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> Message-ID: On Mar 23, 1:55?pm, Jose Manuel wrote: > I have been learning Python, and it is amazing .... I am using the > tutorial that comes with the official distribution. > > At the end my goal is to develop applied mathematic in engineering > applications to be published on the Web, specially on app. oriented to > simulations and control systems, I was about to start learning Java > but I found Python which seems easier to learn that Java. > > Would it be easy to integrate Python in Web pages with HTML? I have > read many info on Internet saying it is, and I hope so .... > An alternative approach to those already mentioned is to use Crunchy (http://code.google.com/p/crunchy) as a local app in combination with a browser. Andr? > Any opinion From matthew.brett at gmail.com Sun May 9 12:25:16 2010 From: matthew.brett at gmail.com (Matthew Brett) Date: Sun, 9 May 2010 09:25:16 -0700 (PDT) Subject: zlib.decompress fails, zlib.decompressobj succeeds - bug or feature? References: <089c36fa-a2a9-463d-af21-06403e0e6afb@t14g2000prm.googlegroups.com> Message-ID: Hi, Thanks for the reply. > > If instead I do this: > > > out = zlib.decompressobj().decompress(data) > > How about: > > d = zlib.decompressobj() > out = d.decompress(data) + d.flush() Do you mean, that you would then expect the decompressobj method to fail as well? But, no, d.flush() returns the empty string after decompressing ``data``. Thanks again, Matthew From paul at subsignal.org Sun May 9 12:46:32 2010 From: paul at subsignal.org (=?UTF-8?B?UGF1bCBLw7ZsbGU=?=) Date: Sun, 09 May 2010 18:46:32 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: Am 09.05.2010 11:59, schrieb Lawrence D'Oliveiro: > In message, > exarkun at twistedmatrix.com wrote: > >> On 07:48 am, ldo at geek-central.gen.new_zealand wrote: >> >>> In message, >>> exarkun at twistedmatrix.com wrote: >>> >>>> This is a good example of why it's a bad idea to use select on >>>> Windows. >>>> Instead, use WaitForMultipleObjects. >>> >>> How are you supposed to write portable code, then? >> >> With WaitForMultipleObjects on Windows, epoll on Linux, kqueue on BSD, >> event completion on Solaris, etc... >> >> Sound like more work than using select() everywhere? Yea, a bit. But >> not once you abstract it away from your actual application code. After >> all, it's not like these *do* different things. They all do the same >> thing (basically) - differently. > > Do you understand what ?portable? means? Yes. For me it means run as best as possible on all platforms I care about. It does *not* mean force one method from *one* platform upon all platforms for purely ideological reasons (like GTK being too stupid to tell the difference between %HOMEPATH% and %APPDATA%). cheers Paul From paul at boddie.org.uk Sun May 9 13:08:19 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 10:08:19 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> Message-ID: <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> On 9 Mai, 09:05, Carl Banks wrote: > > Bottom line is, GPL hurts everyone: the companies and open source > community. ?Unless you're one of a handful of projects with sufficient > leverage, or are indeed a petty jealous person fighting a holy war, > the GPL is a bad idea and everyone benefits from a more permissive > licence. Oh sure: the GPL hurts everyone, like all the companies who have made quite a lot of money out of effectively making Linux the new enterprise successor to Unix, plus all the companies and individuals who have taken the sources and rolled their own distributions. It's not worth my time picking through your "holy war" rhetoric when you're throwing "facts" like these around. As is almost always the case, the people who see the merit in copyleft-style licensing have clearly given the idea a lot more thought than those who immediately start throwing mud at Richard Stallman because people won't let them use some software as if it originated in a (universally acknowledged) public domain environment. Paul P.S. And the GPL isn't meant to further the cause of open source: it's meant to further the Free Software cause, which is not at all the same thing. Before you ridicule other people's positions, at least get your terminology right. From paul at boddie.org.uk Sun May 9 13:23:29 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 10:23:29 -0700 (PDT) Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> Message-ID: <51262580-bd0b-4ded-af3b-5099c81d7890@e2g2000yqn.googlegroups.com> On 9 Mai, 07:09, Patrick Maupin wrote: > > See, for example, Apple's > support of BSD, Webkit, and LLVM. ?Apple is not a "do no evil" > corporation, and their contributions back to these packages are driven > far more by hard-nosed business decisions than by any expectation of > community goodwill. This being the same Apple that is actively pursuing software patent litigation against other organisations; a company which accuses other companies of promoting closed solutions while upholding some of the most closed and restrictive platforms in widespread use. Your definition of "do no evil" is obviously more relaxed than mine. Paul From apt.shansen at gmail.com Sun May 9 13:24:42 2010 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 9 May 2010 10:24:42 -0700 Subject: Picking a license In-Reply-To: References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> Message-ID: On Sun, May 9, 2010 at 2:22 AM, Martin P. Hellwig < martin.hellwig at dcuktec.org> wrote: > Microsoft has indeed lost control of it in the same way, it is just because > we here in the 'western' world spend huge amount of money on prosecuting and > bringing to 'justice' does who, whether for commercial purposes or > otherwise, make a copy of a piece of code. Think about it, it is not > stealing, the original is still there and no further resources where needed > from the original developer. > > What I am saying is that all this license crap is only needed because we > are used to a commercial environment where we can repeatedly profit from the > same work already done. > > I am not saying that you should not profit, of course you should otherwise > there is no interest in making it in the first place. > > What I am saying is that we as developers should encourage pay for work and > not pay for code. This will, as I believe it, keep everything much more > healthy and balanced. At least we can cut all the crap of software patents > and copyrights. > Wait, what? Why shouldn't I profit repeatedly from the "same work already done"? *I* created, its *mine*. I put blood, sweat and tears into it and perhaps huge amounts of resources, risking financial security and sanity, and you're arguing I shouldn't have the right to sell it after its done? Exactly how do you imagine I'm going to make money off of it? How the existing system works is that I sell... multiple copies of it. Maybe hundreds or thousands before that investment is recouped. At that point, do I no longer get to sell multiple copies? Or do I have to find someone to retroactively pay me some kind of salary? What does "pay for work" even mean? What's wrong with software copyrights? Don't lump intellectual property issues together, they're not comparable. Copyrights have nothing at all to do with patents which have nothing at all to do with trademarks. Each is a very different set of law. Sure, there's some nutty corner cases in copyrights, which need to be addressed-- including things like fair use and DRM. But on the whole, copyrights aren't really all that broken. Its nothing like the situation with software patents, which are just sort of crazy. > For those who say it can't be done, sure it can, all you have to do is > nothing, it takes effort to enforce policies. > And an entire industry ceases to exist overnight, with countless new homeless people showing up on the streets. You can believe in the Free Software movement (I'm not saying you do, this 'you' is impersonal and metaphorical)-- and if you do, good for you. You can believe in "morality" with regards to "freedom" and the "essential rights" of the users. I find it all nonsensical. But good for you if you believe in it. But the Free Software movement exists *because* of copyrights. Copyright Law is what makes the GPL even possible. Microsoft charges you money for the use of their copyrighted software, and doesn't allow you to share it with others. The FSF charges you with an obligation to fall in line should you wish to distribute their copyrighted software, but allows you to use it as you see fit otherwise. Both stances are empowered by the copyrights of the respective organizations. You're free to use Microsoft products if you are amenable to their terms. Or FSF products if you're amenable to theirs. If you don't like either, don't use either. If that means you resort to piracy, so be it. No, its not "stealing"-- the RIAA/MPAA's campaign to equate copyright violation to stealing is actively harmful towards the issue, but its also completely irrelevant. Its a violation of copyright. The right to make copies. And it makes you a little bit of a jackass if you're out of puberty, and allows me to sue your ass if I find out. :) But I fail to see what's fundamentally wrong with that system. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From apt.shansen at gmail.com Sun May 9 13:28:06 2010 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 9 May 2010 10:28:06 -0700 Subject: Picking a license In-Reply-To: <51262580-bd0b-4ded-af3b-5099c81d7890@e2g2000yqn.googlegroups.com> References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> <51262580-bd0b-4ded-af3b-5099c81d7890@e2g2000yqn.googlegroups.com> Message-ID: On Sun, May 9, 2010 at 10:23 AM, Paul Boddie wrote: > On 9 Mai, 07:09, Patrick Maupin wrote: > > Apple is ***not**** a "do no evil" corporation > > This being the same Apple that is actively pursuing software patent > litigation against other organisations; a company which accuses other > companies of promoting closed solutions while upholding some of the > most closed and restrictive platforms in widespread use. Your > definition of "do no evil" is obviously more relaxed than mine. > Emphasis added. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From solipsis at pitrou.net Sun May 9 13:33:32 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 9 May 2010 19:33:32 +0200 Subject: zlib.decompress fails, zlib.decompressobj succeeds - bug or feature? References: <089c36fa-a2a9-463d-af21-06403e0e6afb@t14g2000prm.googlegroups.com> Message-ID: <20100509193332.67ecf22a@pitrou.net> On Sun, 9 May 2010 09:25:16 -0700 (PDT) Matthew Brett wrote: > > How about: > > > > d = zlib.decompressobj() > > out = d.decompress(data) + d.flush() > > Do you mean, that you would then expect the decompressobj method to > fail as well? Yes. > But, no, d.flush() returns the empty string after decompressing > ``data``. Hmm, then it's a bug. Can you report it to http://bugs.python.org ? Thank you Antoine. From steve at REMOVE-THIS-cybersource.com.au Sun May 9 13:55:51 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 17:55:51 GMT Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> <51262580-bd0b-4ded-af3b-5099c81d7890@e2g2000yqn.googlegroups.com> Message-ID: <4be6f727$0$27783$c3e8da3@news.astraweb.com> On Sun, 09 May 2010 10:23:29 -0700, Paul Boddie wrote: > On 9 Mai, 07:09, Patrick Maupin wrote: >> >> See, for example, Apple's >> support of BSD, Webkit, and LLVM. ?Apple is not a "do no evil" >> corporation, and their contributions back to these packages are driven >> far more by hard-nosed business decisions than by any expectation of >> community goodwill. > > This being the same Apple that is actively pursuing software patent > litigation against other organisations; a company which accuses other > companies of promoting closed solutions while upholding some of the most > closed and restrictive platforms in widespread use. Your definition of > "do no evil" is obviously more relaxed than mine. Patrick said that Apple is NOT a "do no evil" company. Speaking as a former Mac fan boy, I came to the conclusion a long time ago that if Apple and Microsoft exchanged market share, Apple would be *far* more evil than MS has even dreamed of being. Nothing I've seen in Apple's behaviour in the last few years has made me change my mind. They do truly awesome hardware and UI design, but also have a company culture that gives me the heebie-jeebies: the wolf of take-no-prisoners corporatism disguised as the sheep of "Think Different" and the counter- culture. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun May 9 13:58:38 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 17:58:38 GMT Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be645cf@dnews.tpgi.com.au> <4be67dd2$0$27783$c3e8da3@news.astraweb.com> <4be6b084$1@dnews.tpgi.com.au> Message-ID: <4be6f7ce$0$27783$c3e8da3@news.astraweb.com> On Sun, 09 May 2010 22:52:55 +1000, Lie Ryan wrote: >>> IMHO that's more complex due to the nested loop, >> >> What's so complex about a nested loop? > > one more nested tab. That extra whitespaces is quite irritating. Then say you don't like it, don't try to make a subjective dislike seem objectively bad with a spurious claim of complexity. There's nothing complex about an extra level of indentation. It's *one token*, with zero run-time cost and virtually no compile-time cost. -- Steven From paul at boddie.org.uk Sun May 9 14:02:20 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 11:02:20 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> Message-ID: On 8 Mai, 22:05, Patrick Maupin wrote: > On May 8, 2:38?pm, Steven D'Aprano > > > No, you don't *owe* them anything, but this brings us back to Ben's > > original post. If you care about the freedoms of Cisco's customers as > > much as you care about the freedoms of Cisco, then that's a good reason > > to grant those customers the same rights as you granted Cisco. > > But I *do* grant them the same rights -- they can come to my site and > download my software!!! Of course they can, but it doesn't mean that they can run that software on the Cisco equipment they've bought, nor does it mean that the original software can interoperate with the modified software, that the end-user can enhance the original software in a way that they prefer and have it work with the rest of the Cisco solution, or that the data produced by the Cisco solution can be understood by a user- enhanced version of the original solution or by other software that normally interoperates with the original software. People often argue that the GPL only cares about the software's freedom, not the recipient's freedom, which I find to be a laughable claim because if one wanted to point at something the GPL places higher than anything else, it would be the "four freedoms" preserved for each user's benefit. Really, copyleft licences are all about treating all recipients of the software and modified versions or extensions of the software in the same way: that someone receiving the software, in whatever state of enhancement, has all the same privileges that the individual or organisation providing the software to them enjoyed; those "four freedoms" should still apply to whatever software they received. That this is achieved by asking that everyone make the same commitment to end-user freedoms (or privileges), yet is seen as unreasonable or actually perceived as coercion by some, says a great deal about the perspective of those complaining about it. [...] > So, that gets back to my argument > about what I like to see in a package I use, and how I license things > according to what I would like see. ?For me, the golden rule dictates > that when I give a gift of software, I release it under a permissive > license. ?I realize that others see this differently. Yes, but what irritates a lot of people is when you see other people arguing that some other random person should license their own software permissively because it's "better" or "more free" when what they really mean is that "I could use it to make a proprietary product". [...] > To me, the clear implication of the blanket statement that you have to > use the GPL if you care at all about users is that anybody who doesn't > use the GPL is uncaring. Well, if you want the users to enjoy those "four freedoms" then you should use a copyleft licence. If you choose a permissive licence then it more or less means that you don't care about (or have no particular position on the matter of) the users being able to enjoy those privileges. I believe you coined the term "uncaring", but I think Mr Finney's statement stands up to scrutiny. Paul From steve at REMOVE-THIS-cybersource.com.au Sun May 9 14:03:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 18:03:37 GMT Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> Message-ID: <4be6f8f8$0$27783$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 13:05:21 -0700, Patrick Maupin wrote: [...] > certainly the > risk of discovery if you just use a small portion of GPL code and don't > distribute your source must be very small. There are certainly fewer > companies getting away with MIT license violations, simply because the > license is so much harder to violate. Do you really think it is harder for copyright infringers to copy and paste a small portion of MIT-licenced code and incorporate it into their code than it is for them to do the same to GPL code? [...] > If I produce something under the MIT license, it's because I > want to give it away with no strings. A reasonable position to take. But no strings means that others can add strings back again. You're giving people the freedom to actively work against the freedoms you grant. This is very similar to (e.g.) the question of tolerance and free speech. In the West, society is very tolerate of differing viewpoints. Does this mean that we should tolerate intolerant and bigoted viewpoints? Does tolerance for other points of view imply that we should just accept it when the intolerant tell us to change our behaviour? Perhaps some people think that tolerance implies that we should quietly acquiesce whenever the intolerant, racist, sexist and bigoted demand we give up our tolerance and free speech in the name of tolerating their hateful beliefs. I prefer David Brin's philosophy: "We have to go forth and crush every world view that doesn't believe in tolerance and free speech." If you value tolerance, then tolerating the intolerant is self-defeating. And if you value freedom, then giving others the freedom to take freedoms away is also self-defeating. In the long term, a free society may come to regret the existence of MIT-style licences -- to use a rather old- fashioned phrase, these licences give comfort and support to the enemy (those who would deny freedoms to everyone but themselves). But in the short term, as I have said, one can't fight every battle all the time, and MIT-style licences have their place. It's certainly true that an MIT licence will allow you to maximise the number of people who will use your software, but maximising the number of users is not the only motive for writing software. > If I'm > going to use any prebuilt components, those *can't* be licensed under > the GPL if I want to deliver the final package under the MIT license. An over generalisation. It depends on the nature of the linkage between components. For instance, you can easily distribute a GPLed Python module with your application without the rest of your application being GPLed. [...] > To me, the clear implication of the blanket statement that you have to > use the GPL if you care at all about users is that anybody who doesn't > use the GPL is uncaring. I think that's a silly attitude, and will > always use any tool at hand, including sarcasm, to point out when other > people try to impose their own narrow sense of morality on others by > painting what I perceive to be perfectly normal, moral, decent, and > legal behavior as somehow detrimental to the well-being of the species > (honestly -- ebola???) In context, you were implying that "freedoms" are always a good, and that more freedom always equals better. I provided a counter-example of where more freedom can be a bad. What's so difficult to understand about this? -- Steven From paul at boddie.org.uk Sun May 9 14:07:50 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 11:07:50 -0700 (PDT) Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> <51262580-bd0b-4ded-af3b-5099c81d7890@e2g2000yqn.googlegroups.com> <4be6f727$0$27783$c3e8da3@news.astraweb.com> Message-ID: On 9 Mai, 19:55, Steven D'Aprano wrote: > > Patrick said that Apple is NOT a "do no evil" company. Yes, apologies to Patrick for reading something other than what he wrote. I suppose I've been reading too many Apple apologist commentaries of late and probably started to skim the text after I hit the all-too-often mentioned trinity of "BSD, Webkit, and LLVM", expecting to be asked to sing the praises of Apple's wholesome "commitment" to open source. Paul From godson.g at gmail.com Sun May 9 14:36:37 2010 From: godson.g at gmail.com (Godson Gera) Date: Mon, 10 May 2010 00:06:37 +0530 Subject: Python is cool!! In-Reply-To: References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> <4BA8F56D.6060305@timgolden.me.uk> Message-ID: On Sun, May 9, 2010 at 6:24 PM, Fuzzyman wrote: > On Mar 23, 10:04 pm, geremy condra wrote: > > On Tue, Mar 23, 2010 at 1:07 PM, Tim Golden > wrote: > > > On 23/03/2010 16:55, Jose Manuel wrote: > > > > The closest is Skulpt which is very much an incomplete implementation > of Python that runs in the browser. > Since you have mentioned Skulpt, take a look at much better pyjamas http://pyjs.org/ demos are awesome. -- Thanks & Regards, Godson Gera IVRS India -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Sun May 9 14:40:16 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 11:40:16 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <4be6f8f8$0$27783$c3e8da3@news.astraweb.com> Message-ID: <01eb930d-7e59-4aae-9864-326072885427@37g2000yqm.googlegroups.com> On May 9, 1:03?pm, Steven D'Aprano wrote: > On Sat, 08 May 2010 13:05:21 -0700, Patrick Maupin wrote: > > [...] > > > certainly the > > risk of discovery if you just use a small portion of GPL code and don't > > distribute your source must be very small. There are certainly fewer > > companies getting away with MIT license violations, simply because the > > license is so much harder to violate. > > Do you really think it is harder for copyright infringers to copy and > paste a small portion of MIT-licenced code and incorporate it into their > code than it is for them to do the same to GPL code? No, but there is less incentive for them to hide their tracks. > > If I produce something under the MIT license, it's because I > > want to give it away with no strings. > > A reasonable position to take. But no strings means that others can add > strings back again. You're giving people the freedom to actively work > against the freedoms you grant. Only on modified versions. The internet is a wonderful thing. A smart user can certainly find my original package if he is interested. A dumb user -- well, maybe I don't want to support them anyway. > This is very similar to (e.g.) the question of tolerance and free speech. > In the West, society is very tolerate of differing viewpoints. Does this > mean that we should tolerate intolerant and bigoted viewpoints? Does > tolerance for other points of view imply that we should just accept it > when the intolerant tell us to change our behaviour? Perhaps some people > think that tolerance implies that we should quietly acquiesce whenever > the intolerant, racist, sexist and bigoted demand we give up our > tolerance and free speech in the name of tolerating their hateful > beliefs. I prefer David Brin's philosophy: > > "We have to go forth and crush every world view that doesn't believe in > tolerance and free speech." Okaaaaay, but I think, given most current fair use interpretations, most software licensing doesn't implicate free speech concerns. In any case, GWB's attempt to impose tolerance and free speech on the rest of the world shows that going forth and crushing may not, in some cases, be the best policy, especially when the crushing involves trampling the very rights you are trying to promulgate. > If you value tolerance, then tolerating the intolerant is self-defeating. Possibly, but you need a measured response. We don't patrol the roads to make sure that nobody driving down them is a KKK member. We deal with KKK members according to their words and/or actions. If you value personal responsibility, you let people make bad choices and then suffer the consequences of their own actions. (Like letting me license my stuff under MIT :-) > And if you value freedom, then giving others the freedom to take freedoms > away is also self-defeating. As I wrote in an earlier post in this thread, a lot of the discussion gets down to the age old question about whether someone is really free if he is not allowed to sell himself into slavery. This is a very interesting philosophical question that has had many words written about it. I personally don't think the answer is black-and-white, but then I'm not much of a religious fanatic about anything. > In the long term, a free society may come to > regret the existence of MIT-style licences -- to use a rather old- > fashioned phrase, these licences give comfort and support to the enemy > (those who would deny freedoms to everyone but themselves). Or in the long term, a free society may come to realize that the license incompatibilities pioneered by the FSF and embodied in the GPL set free software development back by two decades by making an incremental approach difficult. Or it may be that the way things are going is the normal chaotic market approach that actually speeds things up and is actually the optimum way to get there from here. The future is very difficult to predict, and even, in a few years, with 20-20 hindsight, it will be difficult to accurately speculate on what might have been. > But in the short term, as I have said, one can't fight every battle all > the time, and MIT-style licences have their place. It's certainly true > that an MIT licence will allow you to maximise the number of people who > will use your software, but maximising the number of users is not the > only motive for writing software. I think we're in violent agreement that both permissive and GPL licensing have their place. Certainly, the GPL is a more comforting license to some people, and any license that encourages more good free software to be written is a great thing. A developer ought to be able to license his creation under a license of his choosing, and from my perspective the whole purpose of the debate in this thread is to make points for and against various licensing schemes to help the OP and others in their decisions. > > If I'm > > going to use any prebuilt components, those *can't* be licensed under > > the GPL if I want to deliver the final package under the MIT license. > > An over generalisation. It depends on the nature of the linkage between > components. For instance, you can easily distribute a GPLed Python module > with your application without the rest of your application being GPLed. I agree that's probably true. However, if you read and parse Stallman and Moglen very carefully, they don't *want* it to be true and in some cases deny that it's true. The fact that a lot of people who use the GPL take their word for this and also believe it means that it may be morally wrong to make this sort of software combination even in some cases where it is legally permissible, so in general I assume that if someone distributes something under the GPL (as opposed to the LGPL) then their intention is that any system that uses their software as a component is also GPL. > > To me, the clear implication of the blanket statement that you have to > > use the GPL if you care at all about users is that anybody who doesn't > > use the GPL is uncaring. ?I think that's a silly attitude, and will > > always use any tool at hand, including sarcasm, to point out when other > > people try to impose their own narrow sense of morality on others by > > painting what I perceive to be perfectly normal, moral, decent, and > > legal behavior as somehow detrimental to the well-being of the species > > (honestly -- ebola???) > > In context, you were implying that "freedoms" are always a good, and that > more freedom always equals better. I provided a counter-example of where > more freedom can be a bad. What's so difficult to understand about this? Well, for one thing, it was not my intention to imply that more freedom is always good. I was answering the phrase "Unless you place such a low value the freedom of your users" which is, IMHO, somewhat inflammatory language, with equally inflammatory language. Obviously, the truth is somewhere in the middle. Regards, Pat From cns090209 at gmail.com Sun May 9 14:58:55 2010 From: cns090209 at gmail.com (Shattered Soldier) Date: Sun, 9 May 2010 11:58:55 -0700 (PDT) Subject: Where can I buy Soma without a prescription. Purchasing Soma quick delivery no prescription. Buy Soma w/out insurance. Non generic Soma no prescription. Buy Soma online prescription. References: Message-ID: <90eec74d-2e14-43d5-9541-4225d1212433@o1g2000vbe.googlegroups.com> I have some generic somas that I'd like to part with. I'm charging only $1.00 per pill plus S&H. Please let me know if you are interested. ShatteredSoldier at hushmail.com From dasacc22 at gmail.com Sun May 9 14:59:23 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sun, 9 May 2010 11:59:23 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: <2288af61-7f92-4832-b6d0-ea1dd1eb6ab6@p2g2000yqh.googlegroups.com> On May 9, 8:28?am, John Machin wrote: > dasacc22 gmail.com> writes: > > > > > U presume entirely to much. I have a preprocessor that normalizes > > documents while performing other more complex operations. ?Theres > > nothing buggy about what im doing > > Are you sure? > > Your "solution" calculates (the number of leading whitespace characters) + (the > number of TRAILING whitespace characters). > > Problem 1: including TRAILING whitespace. > Example: "content" + 3 * " " + "\n" has 4 leading spaces according to your > reckoning; should be 0. > Fix: use lstrip() instead of strip() > > Problem 2: assuming all whitespace characters have *effective* width the same as > " ". > Examples: TAB has width 4 or 8 or whatever you want it to be. There are quite a > number of whitespace characters, even when you stick to ASCII. When you look at > Unicode, there are heaps more. Here's a list of BMP characters such that > character.isspace() is True, showing the Unicode codepoint, the Python repr(), > and the name of the character (other than for control characters): > > U+0009 u'\t' ? > U+000A u'\n' ? > U+000B u'\x0b' ? > U+000C u'\x0c' ? > U+000D u'\r' ? > U+001C u'\x1c' ? > U+001D u'\x1d' ? > U+001E u'\x1e' ? > U+001F u'\x1f' ? > U+0020 u' ' SPACE > U+0085 u'\x85' ? > U+00A0 u'\xa0' NO-BREAK SPACE > U+1680 u'\u1680' OGHAM SPACE MARK > U+2000 u'\u2000' EN QUAD > U+2001 u'\u2001' EM QUAD > U+2002 u'\u2002' EN SPACE > U+2003 u'\u2003' EM SPACE > U+2004 u'\u2004' THREE-PER-EM SPACE > U+2005 u'\u2005' FOUR-PER-EM SPACE > U+2006 u'\u2006' SIX-PER-EM SPACE > U+2007 u'\u2007' FIGURE SPACE > U+2008 u'\u2008' PUNCTUATION SPACE > U+2009 u'\u2009' THIN SPACE > U+200A u'\u200a' HAIR SPACE > U+200B u'\u200b' ZERO WIDTH SPACE > U+2028 u'\u2028' LINE SEPARATOR > U+2029 u'\u2029' PARAGRAPH SEPARATOR > U+202F u'\u202f' NARROW NO-BREAK SPACE > U+205F u'\u205f' MEDIUM MATHEMATICAL SPACE > U+3000 u'\u3000' IDEOGRAPHIC SPACE > > Hmmm, looks like all kinds of widths, from zero upwards. I unfortunately mixed the solution with a string that would never make it in the state i typed it in, the trailing whitespace This is my fault From pmaupin at gmail.com Sun May 9 15:07:40 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 12:07:40 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> Message-ID: <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> On May 9, 1:02?pm, Paul Boddie wrote: > On 8 Mai, 22:05, Patrick Maupin wrote: > > > On May 8, 2:38?pm, Steven D'Aprano > > > No, you don't *owe* them anything, but this brings us back to Ben's > > > original post. If you care about the freedoms of Cisco's customers as > > > much as you care about the freedoms of Cisco, then that's a good reason > > > to grant those customers the same rights as you granted Cisco. > > > But I *do* grant them the same rights -- they can come to my site and > > download my software!!! > > Of course they can, but it doesn't mean that they can run that > software on the Cisco equipment they've bought, nor does it mean that > the original software can interoperate with the modified software, > that the end-user can enhance the original software in a way that they > prefer and have it work with the rest of the Cisco solution, or that > the data produced by the Cisco solution can be understood by a user- > enhanced version of the original solution or by other software that > normally interoperates with the original software. I agree, and those people who will develop more software if they aren't lying awake at night worried about whether Cisco or some other big corporation is going to misappropriate their precious creations should certainly use the GPL. More people building more free softare is a great thing, and to the extent the GPL encourages this behavior, it is a great thing. > People often argue > that the GPL only cares about the software's freedom, not the > recipient's freedom, which I find to be a laughable claim because if > one wanted to point at something the GPL places higher than anything > else, it would be the "four freedoms" preserved for each user's > benefit. Well, I don't think you saw me arguing it that way. I will say, just like anything else, that there is a cost associated with using GPL software, and it is not necessarily a cost that I want to impose on users of all my software. > Really, copyleft licences are all about treating all recipients of the > software and modified versions or extensions of the software in the > same way: that someone receiving the software, in whatever state of > enhancement, has all the same privileges that the individual or > organisation providing the software to them enjoyed; Sure, and for a major work I think that's great, especially if it helps attract developers. Sometimes I see people GPL little 100 line libraries (of often not very good code quality) in a clear attempt to have the tail wag the dog, and that's laughably pathetic. > those "four > freedoms" should still apply to whatever software they received. That > this is achieved by asking that everyone make the same commitment to > end-user freedoms (or privileges), yet is seen as unreasonable or > actually perceived as coercion by some, says a great deal about the > perspective of those complaining about it. Well, I *do* think it's, maybe not unreasonable, but certainly unrealistic, for the author of a small library to attempt to leverage control over several potentially much larger works by placing the small library under the GPL, so in general I don't do it. I also happen to believe that there are a lot of people (perhaps like Carl Banks if I understand his post correctly) who make money delivering small customized solutions to sit on top of proprietary software solutions. If I can save one of these guys some time, perhaps they will contribute back. If I use the GPL, I will have insured that one of these guys cannot possibly link my software to, e.g. Oracle, so he has to reinvent the wheel. So, for some use-cases, I sincerely believe that the GPL license creates unnecessary, wasteful friction. But the tone of your last statement and some of your statements below make it abundantly clear that you've made up your mind about my morals and aren't at all interested in my reasoning. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? So, that gets back to my argument > > about what I like to see in a package I use, and how I license things > > according to what I would like see. ?For me, the golden rule dictates > > that when I give a gift of software, I release it under a permissive > > license. ?I realize that others see this differently. > > Yes, but what irritates a lot of people is when you see other people > arguing that some other random person should license their own > software permissively because it's "better" or "more free" when what > they really mean is that "I could use it to make a proprietary > product". I'm not telling anybody what to do. I'm just explaining why I usually use the MIT license for things I write, and will often not consider using a library licensed under the GPL. What irritated me enough to comment on this thread was the IMHO sanctimonious and inflammatory "Unless you place such a low value the freedom of your users". > > To me, the clear implication of the blanket statement that you have to > > use the GPL if you care at all about users is that anybody who doesn't > > use the GPL is uncaring. > > Well, if you want the users to enjoy those "four freedoms" then you > should use a copyleft licence. If you choose a permissive licence then > it more or less means that you don't care about (or have no particular > position on the matter of) the users being able to enjoy those > privileges. I believe you coined the term "uncaring", but I think Mr > Finney's statement stands up to scrutiny. I personally don't think that RMS's "four freedoms" are the last word on the best way for society to develop software, no. But using "Unless you place such a low value the freedom of your users" is truly an inflammatory statement, because it was given in a context where the GPL had not yet been carefully parsed and discussed, and did not make it clear that the "freedoms" being discussed are a particular set of "freedoms" and not, for example, those freedoms enshrined in the Bill of Rights. (And as Steven has carefully pointed out, not all freedoms are necessarily Good Things.) Regards, Pat From pmaupin at gmail.com Sun May 9 15:26:02 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 12:26:02 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <9f54536c-8428-4de8-bba8-fa16fe728a1f@n15g2000yqf.googlegroups.com> <7xr5lllgo8.fsf@ruckus.brouhaha.com> Message-ID: <3255993f-1652-44aa-b1e3-7944f029003a@a34g2000yqn.googlegroups.com> On May 9, 1:42?am, Paul Rubin wrote: > Patrick Maupin writes: > > I certainly agree that RMS's language is couched in religious rhetoric. > > I would say political movement rhetoric. ?He's not religious. ?He uses > the word "spiritual" sometimes but has made it clear he doesn't mean > that in a religious sense. Oh, I agree he's not religious. OTOH, I don't think bin Laden, or most of the Ayatollahs, or priests who molest little boys, or Mormon polygamists, or Branch Davidians are religious either. But what these people have in common (and also have in common with some _real_ religious people) is a fervent type of language and style of speaking and writing, designed to attract religious followers, and the ability and desire to frame disputes in black-and-white, moralistic terms. (And here in the states, at least, it's getting increasingly hard to separate religion from politics in any case.) This is not necessarily a bad thing -- it's what the religious leaders exhort their followers to do that makes them good or bad. As I have discussed in other posts, I think the GPL is a good license for some software and some programmers. In a perfect world with no proprietary software, it might even be the only license that was necessary, except then it wouldn't even be necessary. But in the messy real world we live in, I don't personally believe that it is the best solution for a large class of software licensing problems. Personally, I think the LGPL is a much better license for those who are worried about people giving back, but the FSF has now, for all practical purposes, deprecated it -- not directly, of course, but implicitly, by changing the name from "Library" to "Lesser" and damning it with faint praise by actually encouraging people who write library components to try to help the tail wag the dog by using the GPL instead of the LGPL. Regards, Pat From pmaupin at gmail.com Sun May 9 15:31:48 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 12:31:48 -0700 (PDT) Subject: Picking a license (an atempt to give real advice) References: Message-ID: <4e883106-0664-47eb-a454-e88feb2e93b5@a21g2000yqn.googlegroups.com> On May 9, 8:58?am, Ed Keith wrote: > Stepping back from the political/philosophical/religious arguments, I'd like to give some real advice based on my own perspective. > > How you license your software should be based on how you want it to be used. > > If you are releasing an end user application I do not care how you license it. If it is useful I will use it. If you believe some of the code is of commercial value, and that you hope to profit from it you should use the GPL, so you can license it separately to someone who wants to use it in a closed source product. > > If, on the other hand you are releasing a library, to be incorporated into other products, if you release it under the GPL I will not take the time to learn it. I do not want to have to think about what took I can legally use for what job. Libraries with permissive licenses can be used in any project. I can not use GPL or LGPL code in many contracts. So I do not waist my time learning to use libraries covered by restrictive licenses. So if you want me to even consider using your library do not use GPL, or LGPL. I favor the Boost license in this case. Again, if you want to also offer other licenses, for a fee, you should use GPL, I will not use it, but others might, and you may get paid for your work. > > The bottom line is: if you want the largest possible user base, go with a less restrictive license; If you hope to profit financially from your work, use the GPL. I agree completely, except for the part where you say "Stepping back from the political/philosophical/religious arguments." I've been trying to say practically the same thing, but it's apparently contentious :-) Regards, Pat From martin.hellwig at dcuktec.org Sun May 9 15:33:30 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sun, 09 May 2010 20:33:30 +0100 Subject: Picking a license In-Reply-To: References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> Message-ID: <4BE70E0A.8060208@dcuktec.org> On 05/09/10 18:24, Stephen Hansen wrote: > > Wait, what? Why shouldn't I profit repeatedly from the "same work > already done"? *I* created, its *mine*. I put blood, sweat and tears > into it and perhaps huge amounts of resources, risking financial > security and sanity, and you're arguing I shouldn't have the right to > sell it after its done? Of course, but what do you do if you find out that your potential customer already has your software without paying you? > > Exactly how do you imagine I'm going to make money off of it? How the > existing system works is that I sell... multiple copies of it. Maybe > hundreds or thousands before that investment is recouped. At that > point, do I no longer get to sell multiple copies? Or do I have to > find someone to retroactively pay me some kind of salary? What does > "pay for work" even mean? > As a simple developer I do not think my craft is more special than any other craft like carpentry, masonry, plumbing, electrician etc. And as I see how other crafts get paid I think is reasonable for my craft too, I am either employed and paid by the hour or take more risks and do projects, commissions, etc. etc. Of course if I would be in the construction business and I build a house I can either sell it or let it, but then I do take the risk that the occupant uses my work beyond what I expected and eventually end up with a huge repair costs. I am sure you can imagine the rest of my comparison arguments between construction and software development. > What's wrong with software copyrights? Don't lump intellectual > property issues together, they're not comparable. Copyrights have > nothing at all to do with patents which have nothing at all to do with > trademarks. Each is a very different set of law. Very true and in my opinion they all share the same trait, although they are once made to make sure the original author gets credit and profit for his/her work they are primarily used now to profit beyond reasonableness and actually encumber future development and good use, IMHO they actually hinder the intellectual development of the human race. > > Sure, there's some nutty corner cases in copyrights, which need to be > addressed-- including things like fair use and DRM. But on the whole, > copyrights aren't really all that broken. Its nothing like the > situation with software patents, which are just sort of crazy. Okay so what do you actually do if you find out that in another country, which do not share the same legislation (about the other 80% of the population) brakes your copyright or does not uphold the patent restrictions? If your big like Microsoft you might try to convince that particular government that their citizens should pay you, otherwise good luck (even for Microsoft as they seem to fail more often than succeed in that notion). They are broken because by definition restrictions need enforcement to uphold them, if there is no enforcement it will not work. Perhaps a better solution would be to find a way that does not need any enforcement (or limited amount of it), say like the economy worked prior to patents and copyrights minus kings and tyrants. > > For those who say it can't be done, sure it can, all you have to > do is nothing, it takes effort to enforce policies. > > > And an entire industry ceases to exist overnight, with countless new > homeless people showing up on the streets. I have the opposite opinion but neither of us have given any facts or proven research papers on this so shall we call this quits? > > You can believe in the Free Software movement (I'm not saying you do, > this 'you' is impersonal and metaphorical)-- and if you do, good for > you. You can believe in "morality" with regards to "freedom" and the > "essential rights" of the users. I find it all nonsensical. But good > for you if you believe in it. But the Free Software movement exists > *because* of copyrights. Copyright Law is what makes the GPL even > possible. > I don't believe in a system which is based on enforcing rules and where breaking of this rule at most results in a hypothetical loss of income. Some enforced rules are of course necessary, like not going on a pillage/killing/raping spree (except of course if this is your job but then your still governed by the rules of Geneva -- yeah I know bold military statement, but I have been there too, the military that is). I rather like to find a way where minimal rule enforcing is necessary to make a living. > But I fail to see what's fundamentally wrong with that system. > I hope I have further explained my point of view and hope that you agree with me at least from my perspective, I do understand though that your point of view is perfectly valid and reasonable. It is just that I am a sucker for seeking alternative ways to improve systems even if they only show small amounts of defects. So you could argue that I have my sight set for an Utopia while you rather remain in the reality, if you can find yourself with this than at least we can agree on that :-) -- mph From martin.hellwig at dcuktec.org Sun May 9 15:33:30 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sun, 09 May 2010 20:33:30 +0100 Subject: Picking a license In-Reply-To: References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> Message-ID: <4BE70E0A.8060208@dcuktec.org> On 05/09/10 18:24, Stephen Hansen wrote: > > Wait, what? Why shouldn't I profit repeatedly from the "same work > already done"? *I* created, its *mine*. I put blood, sweat and tears > into it and perhaps huge amounts of resources, risking financial > security and sanity, and you're arguing I shouldn't have the right to > sell it after its done? Of course, but what do you do if you find out that your potential customer already has your software without paying you? > > Exactly how do you imagine I'm going to make money off of it? How the > existing system works is that I sell... multiple copies of it. Maybe > hundreds or thousands before that investment is recouped. At that > point, do I no longer get to sell multiple copies? Or do I have to > find someone to retroactively pay me some kind of salary? What does > "pay for work" even mean? > As a simple developer I do not think my craft is more special than any other craft like carpentry, masonry, plumbing, electrician etc. And as I see how other crafts get paid I think is reasonable for my craft too, I am either employed and paid by the hour or take more risks and do projects, commissions, etc. etc. Of course if I would be in the construction business and I build a house I can either sell it or let it, but then I do take the risk that the occupant uses my work beyond what I expected and eventually end up with a huge repair costs. I am sure you can imagine the rest of my comparison arguments between construction and software development. > What's wrong with software copyrights? Don't lump intellectual > property issues together, they're not comparable. Copyrights have > nothing at all to do with patents which have nothing at all to do with > trademarks. Each is a very different set of law. Very true and in my opinion they all share the same trait, although they are once made to make sure the original author gets credit and profit for his/her work they are primarily used now to profit beyond reasonableness and actually encumber future development and good use, IMHO they actually hinder the intellectual development of the human race. > > Sure, there's some nutty corner cases in copyrights, which need to be > addressed-- including things like fair use and DRM. But on the whole, > copyrights aren't really all that broken. Its nothing like the > situation with software patents, which are just sort of crazy. Okay so what do you actually do if you find out that in another country, which do not share the same legislation (about the other 80% of the population) brakes your copyright or does not uphold the patent restrictions? If your big like Microsoft you might try to convince that particular government that their citizens should pay you, otherwise good luck (even for Microsoft as they seem to fail more often than succeed in that notion). They are broken because by definition restrictions need enforcement to uphold them, if there is no enforcement it will not work. Perhaps a better solution would be to find a way that does not need any enforcement (or limited amount of it), say like the economy worked prior to patents and copyrights minus kings and tyrants. > > For those who say it can't be done, sure it can, all you have to > do is nothing, it takes effort to enforce policies. > > > And an entire industry ceases to exist overnight, with countless new > homeless people showing up on the streets. I have the opposite opinion but neither of us have given any facts or proven research papers on this so shall we call this quits? > > You can believe in the Free Software movement (I'm not saying you do, > this 'you' is impersonal and metaphorical)-- and if you do, good for > you. You can believe in "morality" with regards to "freedom" and the > "essential rights" of the users. I find it all nonsensical. But good > for you if you believe in it. But the Free Software movement exists > *because* of copyrights. Copyright Law is what makes the GPL even > possible. > I don't believe in a system which is based on enforcing rules and where breaking of this rule at most results in a hypothetical loss of income. Some enforced rules are of course necessary, like not going on a pillage/killing/raping spree (except of course if this is your job but then your still governed by the rules of Geneva -- yeah I know bold military statement, but I have been there too, the military that is). I rather like to find a way where minimal rule enforcing is necessary to make a living. > But I fail to see what's fundamentally wrong with that system. > I hope I have further explained my point of view and hope that you agree with me at least from my perspective, I do understand though that your point of view is perfectly valid and reasonable. It is just that I am a sucker for seeking alternative ways to improve systems even if they only show small amounts of defects. So you could argue that I have my sight set for an Utopia while you rather remain in the reality, if you can find yourself with this than at least we can agree on that :-) -- mph From pmaupin at gmail.com Sun May 9 15:55:32 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 12:55:32 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> Message-ID: <6554e4fa-9fc0-49ab-a28d-413bd3152739@l31g2000yqm.googlegroups.com> On May 9, 12:08?pm, Paul Boddie wrote: > On 9 Mai, 09:05, Carl Banks wrote: > > > > > Bottom line is, GPL hurts everyone: the companies and open source > > community. ?Unless you're one of a handful of projects with sufficient > > leverage, or are indeed a petty jealous person fighting a holy war, > > the GPL is a bad idea and everyone benefits from a more permissive > > licence. > > Oh sure: the GPL hurts everyone, like all the companies who have made > quite a lot of money out of effectively making Linux the new > enterprise successor to Unix, plus all the companies and individuals > who have taken the sources and rolled their own distributions. So, people overstate their cases to make their points. That happens on both sides. > It's not worth my time picking through your "holy war" rhetoric when > you're throwing "facts" like these around. As is almost always the > case, the people who see the merit in copyleft-style licensing have > clearly given the idea a lot more thought than those who immediately > start throwing mud at Richard Stallman because people won't let them > use some software as if it originated in a (universally acknowledged) > public domain environment. No, you appear to have a kneejerk reaction much worse than Carl's. You have assumed you fully understand the motives of people who point out issues with the GPL, and that those motives are uniformly bad, and this colors your writing and thinking quite heavily, even to the point where you naturally assumed I was defending all of Apple's egregious behavior. As far as my throwing mud at Stallman, although I release some open source stuff on my own, I make a living writing software that belongs to other people, and Stallman has said that that's unethical and I shouldn't be able to make money in this fashion. Sorry, but he's not on my side. > P.S. And the GPL isn't meant to further the cause of open source: it's > meant to further the Free Software cause, which is not at all the same > thing. Before you ridicule other people's positions, at least get your > terminology right. And, again, that's "free" according to a somewhat contentious definition made by someone who is attempting to frame the debate by co- opting all the "mother and apple pie" words, who is blindly followed by others who think they are the only ones who are capable of thoughts which are both rational and pure. I'm not saying everybody who uses the GPL is in this category, but some of your words here indicate that you, in fact, might be. Regards, Pat From apt.shansen at gmail.com Sun May 9 16:06:09 2010 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 9 May 2010 13:06:09 -0700 Subject: Picking a license In-Reply-To: <4BE70E0A.8060208@dcuktec.org> References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> <4BE70E0A.8060208@dcuktec.org> Message-ID: On Sun, May 9, 2010 at 12:33 PM, Martin P. Hellwig < martin.hellwig at dcuktec.org> wrote: > On 05/09/10 18:24, Stephen Hansen wrote: > >> >> >> Wait, what? Why shouldn't I profit repeatedly from the "same work already >> done"? *I* created, its *mine*. I put blood, sweat and tears into it and >> perhaps huge amounts of resources, risking financial security and sanity, >> and you're arguing I shouldn't have the right to sell it after its done? >> > Of course, but what do you do if you find out that your potential customer > already has your software without paying you? Nothing. There's really very little benefit to me to go after "potential customers". There will always be warez trading and cracked versions of any product out there that someone can pirate. So what? The vast majority of the people downloading that aren't actually *potential customers*. They'd never have bought the products to begin with. Now, if I find out some other company happens to be selling my software, them I'd sue into oblivion and make a killing -- copyright lets me do that. > >> Exactly how do you imagine I'm going to make money off of it? How the >> existing system works is that I sell... multiple copies of it. Maybe >> hundreds or thousands before that investment is recouped. At that point, do >> I no longer get to sell multiple copies? Or do I have to find someone to >> retroactively pay me some kind of salary? What does "pay for work" even >> mean? >> >> As a simple developer I do not think my craft is more special than any > other craft like carpentry, masonry, plumbing, electrician etc. > And as I see how other crafts get paid I think is reasonable for my craft > too, I am either employed and paid by the hour or take more risks and do > projects, commissions, etc. etc. > > Of course if I would be in the construction business and I build a house I > can either sell it or let it, but then I do take the risk that the occupant > uses my work beyond what I expected and eventually end up with a huge repair > costs. > > I am sure you can imagine the rest of my comparison arguments between > construction and software development. You're comparing apples to rabbits. There's nothing even vaguely alike between the two no matter how much you are trying to compare them: carpentry, masonry, plumbing, all of that deal with *physical* items, that by their very nature create singular, specific, tangible items and/or services. If I create a software product on commission for some private company, that's almost-kind of like what happens for other "crafts", wherein someone pays me some amount of money for some amount of work to produce a finished product. But how exactly do you imagine I would make money if I have some idea for some great new program and I write it on my own? The only way is to... sell multiple copies. Or try to find someone to give me one big lump sum for the privilege of releasing it to the universe. Software is intangible, irregardless of the fact that it might show up on a physical medium. You can't compare work of the mind with work of physical crafts-- one is not more worthy of money then the other, but they are *different*. > > What's wrong with software copyrights? Don't lump intellectual property >> issues together, they're not comparable. Copyrights have nothing at all to >> do with patents which have nothing at all to do with trademarks. Each is a >> very different set of law. >> > Very true and in my opinion they all share the same trait, although they > are once made to make sure the original author gets credit and profit for > his/her work they are primarily used now to profit beyond reasonableness and > actually encumber future development and good use, IMHO they actually hinder > the intellectual development of the human race. You say 'very true' but then you lump them all together again. "They" are not at all for the same thing. Copyrights are intended, indeed, to make sure the original author gets credit and profit for his creative work. They tend to last a rather long time these days. Patents are intended to allow a relatively short-term monopoly on some new invention, so that the vast costs of R&D can be justified, but also so that the -result- of that R&D will be published to the public and after that monopoly is over, allow everyone to benefit. They are an encumbrance, yes, but a temporary one: and after that encumbrance is over, the inventor losers all control over the invented. Unfortunately, patents are woefully broken due to business methods and software being allowed to be 'patented', which is just silly on both cases. Trademarks are intended to protect the *consumers*, by disallowing companies from marketing in a confusing way such that what they are selling may be mistaken for what a reputable third-party is selling. A company can trademark its "brand", and by doing so customers can know that brand and IF they trust it, rely on it when they see it. Trademarks actually, IMHO, work quite well -- companies actually have to enforce them and be pro-active about them, unlike with patents, where one can sit around and wait for another to firmly establish themselves with technology based on your patent, then jump in and sue. I fail to see how there's really anything "encumbering" about trademarks. > >> Sure, there's some nutty corner cases in copyrights, which need to be >> addressed-- including things like fair use and DRM. But on the whole, >> copyrights aren't really all that broken. Its nothing like the situation >> with software patents, which are just sort of crazy. >> > Okay so what do you actually do if you find out that in another country, > which do not share the same legislation (about the other 80% of the > population) brakes your copyright or does not uphold the patent > restrictions? > If your big like Microsoft you might try to convince that particular > government that their citizens should pay you, otherwise good luck (even for > Microsoft as they seem to fail more often than succeed in that notion). > Umm. http://upload.wikimedia.org/wikipedia/commons/7/76/Berne_Convention_signatories.svg http://upload.wikimedia.org/wikipedia/commons/c/c1/WIPO.png And a couple others, including the Pair Convention of something or other. Intellectual property law is pretty globally standard these days. That's not to say that in some places its not largely ignored in certain sectors, but see first response above. > They are broken because by definition restrictions need enforcement to > uphold them, if there is no enforcement it will not work. Perhaps a better > solution would be to find a way that does not need any enforcement (or > limited amount of it), say like the economy worked prior to patents and > copyrights minus kings and tyrants. ... copyright dates back to the 1700's. And, there are ways to enforce the "restrictions"-- which are not restrictions, but instead enforcement of rights that I, as the one who made this creative work, hold. Its a civil action. (Though certain types and kinds of infringement may in some jurisdictions be a criminal offense) > >> You can believe in the Free Software movement (I'm not saying you do, this >> 'you' is impersonal and metaphorical)-- and if you do, good for you. You can >> believe in "morality" with regards to "freedom" and the "essential rights" >> of the users. I find it all nonsensical. But good for you if you believe in >> it. But the Free Software movement exists *because* of copyrights. Copyright >> Law is what makes the GPL even possible. >> >> > I don't believe in a system which is based on enforcing rules and where > breaking of this rule at most results in a hypothetical loss of income. Some > enforced rules are of course necessary, like not going on a > pillage/killing/raping spree (except of course if this is your job but then > your still governed by the rules of Geneva -- yeah I know bold military > statement, but I have been there too, the military that is). I rather like > to find a way where minimal rule enforcing is necessary to make a living. I find i can make a living quite well with basically zero "rule enforcing", because of copyrights. I really don't need to enforce that every kid out there might get an illegal copy of a program I wrote. They aren't my customers. However, because I have copyright, I can be sure that no other companies are going to start completing with me based on my own work. (That I made this argument in a thread about open source licensing, and the irony therein, does not escape me) Cuz then I'll sue their ass off. But its never happened. And I don't expect it to happen. Because copyright is an international, pretty clearly standardized set of law. > > But I fail to see what's fundamentally wrong with that system. >> >> I hope I have further explained my point of view and hope that you agree > with me at least from my perspective, I do understand though that your point > of view is perfectly valid and reasonable. It is just that I am a sucker for > seeking alternative ways to improve systems even if they only show small > amounts of defects. So you could argue that I have my sight set for an > Utopia while you rather remain in the reality, if you can find yourself with > this than at least we can agree on that :-) > Had you stuck to wanting to make patents make sense, I would have agreed with you about half the way-- but I actually, mostly, sorta think copyrights are fine. Even with idiocies like DRM. I think the market has to decide to turn away from DRM. (I'm looking at you Ubisoft: you've lost over $100 already from me!) --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From robin1 at cnsp.com Sun May 9 16:28:06 2010 From: robin1 at cnsp.com (Robin) Date: Sun, 9 May 2010 13:28:06 -0700 (PDT) Subject: python to exe Message-ID: Does anyone know of a way I can make a python script into an exe that runs on windows7, I don't care if it is a python to c++ or python to c translator or anything like it. The version of python I am using is python 3.1. Thanks, -Robin From clp2 at rebertia.com Sun May 9 16:37:39 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 May 2010 13:37:39 -0700 Subject: python to exe In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 1:28 PM, Robin wrote: > Does anyone know of a way I can make a python script into an exe that > runs on windows7, I don't care if it is a python to c++ or python to c > translator or anything like it. The version of python I am using is > python 3.1. Thanks, The standard tools for that are: http://www.py2exe.org/ http://www.pyinstaller.org/ I'm unsure whether they work with Python 3.x or Windows 7 though; their websites don't say explicitly. They probably work with Windows 7. It's a bit less likely that they work with Python 3.x Perhaps someone who's tried those combinations will chime in. Cheers, Chris -- I'm on OS X myself, so... http://blog.rebertia.com From paul at subsignal.org Sun May 9 16:50:20 2010 From: paul at subsignal.org (=?ISO-8859-1?Q?Paul_K=F6lle?=) Date: Sun, 09 May 2010 22:50:20 +0200 Subject: Django as exemplary design In-Reply-To: <2010050619481239450-tomfsessile@gmailcom> References: <2010050312243328275-tomfsessile@gmailcom> <2010050619481239450-tomfsessile@gmailcom> Message-ID: Am 07.05.2010 04:48, schrieb TomF: > On 2010-05-06 18:20:02 -0700, Trent Nelson said: >>> I'm interested in improving my python design by studying a large, >>> well-designed codebase. >> >> I'll tell you one of the best ways to improve your Python code: attend >> one of Raymond Hettinger's Code Clinic workshops at a Python conference >> and put some up of your work up on the projector for 20+ developers to >> rip apart, line by line ;-) You'll pick up more in 30 minutes than you >> ever thought possible. > > I don't doubt it. But I'm not really interested in line (micro) level > code issues at the moment. Not that my code couldn't stand being > improved, but I'm more interested in seeing how medium/large OO python > systems are designed. If I could get this from a book I would, but I > suspect I need to study real code. Then trac might be a good candidate, start here http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture then read http://trac.edgewall.org/browser/trunk/trac/core.py#latest there is one rather dubious hack in the implementation of implements() but I like the conceptual simplicity. cheers Paul From vlastimil.brom at gmail.com Sun May 9 17:05:13 2010 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sun, 9 May 2010 23:05:13 +0200 Subject: python to exe In-Reply-To: References: Message-ID: 2010/5/9 Robin : > Does anyone know of a way I can make a python script into an exe that > runs on windows7, I don't care if it is a python to c++ or python to c > translator or anything like it. The version of python I am using is > python 3.1. Thanks, > -Robin > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, you may check e.g. cx-freeze http://cx-freeze.sourceforge.net/ which apparently supports python 3.1. However I don't use it myself, hence I can't offer any details. py2exe doesn't seem to have python 3 support just now. hth, vbr From matthew.brett at gmail.com Sun May 9 17:19:45 2010 From: matthew.brett at gmail.com (Matthew Brett) Date: Sun, 9 May 2010 14:19:45 -0700 (PDT) Subject: zlib.decompress fails, zlib.decompressobj succeeds - bug or feature? References: <089c36fa-a2a9-463d-af21-06403e0e6afb@t14g2000prm.googlegroups.com> Message-ID: Hi, > > Do you mean, that you would then expect the decompressobj method to > > fail as well? > > Yes. > > > But, no, d.flush() returns the empty string after decompressing > > ``data``. > > Hmm, then it's a bug. Can you report it tohttp://bugs.python.org? I will - thanks for your advice, Matthew From paul at boddie.org.uk Sun May 9 17:21:09 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 14:21:09 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> Message-ID: <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> On 9 Mai, 21:07, Patrick Maupin wrote: > On May 9, 1:02?pm, Paul Boddie wrote: > > > > People often argue > > that the GPL only cares about the software's freedom, not the > > recipient's freedom, which I find to be a laughable claim because if > > one wanted to point at something the GPL places higher than anything > > else, it would be the "four freedoms" preserved for each user's > > benefit. > > Well, I don't think you saw me arguing it that way. ?I will say, just > like anything else, that there is a cost associated with using GPL > software, and it is not necessarily a cost that I want to impose on > users of all my software. I didn't say that you personally argued that way, but people do argue that way. In fact, it's understandable that this is how some people attempt to understand the GPL - the software maintains a particular state of openness - but they miss the final step in the reasoning which leads them to see that the licence preserves a set of privileges for recipients as well. The "cost" with the GPL is that people cannot take GPL-licensed software and just do whatever they want with it, although it is also the case that permissive licences also have a set of conditions associated with each of them as well, albeit ones which do not mandate the delivery of the source code to recipients. Thus, the observation of software licences can never be about taking code which was publicly available and combining it without thought to what those licences say. Thus, remarks about Cisco and Linksys - that they were somehow "caught out" - are disingenuous: if you're in the business of distributing software, particularly if that software itself has a restrictive licence, you cannot claim ignorance about licensing or that you just "found some good code". > > Really, copyleft licences are all about treating all recipients of the > > software and modified versions or extensions of the software in the > > same way: that someone receiving the software, in whatever state of > > enhancement, has all the same privileges that the individual or > > organisation providing the software to them enjoyed; > > Sure, and for a major work I think that's great, especially if it > helps attract developers. ?Sometimes I see people GPL little 100 line > libraries (of often not very good code quality) in a clear attempt to > have the tail wag the dog, and that's laughably pathetic. Why is it pathetic that someone gets to choose the terms under which their work is made available? By default, if I release something without any licence, the recipient has very few privileges with respect to that work: it's literally a case of "all rights reserved" for the creator. And if it's such a trivial library then why not reimplement the solution yourself? > > those "four > > freedoms" should still apply to whatever software they received. That > > this is achieved by asking that everyone make the same commitment to > > end-user freedoms (or privileges), yet is seen as unreasonable or > > actually perceived as coercion by some, says a great deal about the > > perspective of those complaining about it. > > Well, I *do* think it's, maybe not unreasonable, but certainly > unrealistic, for the author of a small library to attempt to leverage > control over several potentially much larger works by placing the > small library under the GPL, so in general I don't do it. I dislike the way that when someone releases something under the GPL, it is claimed that they are coercing or attempting to "leverage" something. They have merely shared something on their terms. If you don't like the terms, don't use their software. > ?I also > happen to believe that there are a lot of people (perhaps like Carl > Banks if I understand his post correctly) who make money delivering > small customized solutions to sit on top of proprietary software > solutions. ?If I can save one of these guys some time, perhaps they > will contribute back. ?If I use the GPL, I will have insured that one > of these guys cannot possibly link my software to, e.g. Oracle, so he > has to reinvent the wheel. ?So, for some use-cases, I sincerely > believe that the GPL license creates unnecessary, wasteful friction. But it is not universally true that GPL-licensed software cannot be linked to proprietary software: there are a number of caveats in the GPL covering cases where existing proprietary systems are in use. Otherwise, you'd never have GPL-licensed software running on proprietary systems at all. > But the tone of your last statement and some of your statements below > make it abundantly clear that you've made up your mind about my morals > and aren't at all interested in my reasoning. Not at all. Recently, I've had the misfortune to hear lots of arguments about how the GPL supposedly restricts stuff like "collaboration" and "growth" despite copious evidence to the contrary, usually from people who seem to be making a career of shouting down the GPL or the FSF at every available occasion. Now I'm not saying that you have the same apparent motivations as these people, but I maintain that when someone claims that people are "forced" to share their work when they voluntarily make use of someone else's work, or that they are at the peril of some "moral hazard", it does have a lot to say about their perspective. (Not least because people are only obliged to make their work available under a GPL-compatible licence so that people who are using the combined work may redistribute it under the GPL. You yourself have mentioned elsewhere in this discussion one well-known software project that is not GPL-licensed but was effectively distributed under the GPL to most of its users for a considerable period of time.) [...] > > Yes, but what irritates a lot of people is when you see other people > > arguing that some other random person should license their own > > software permissively because it's "better" or "more free" when what > > they really mean is that "I could use it to make a proprietary > > product". > > I'm not telling anybody what to do. ?I'm just explaining why I usually > use the MIT license for things I write, and will often not consider > using a library licensed under the GPL. ?What irritated me enough to > comment on this thread was the IMHO sanctimonious and inflammatory > "Unless you place such a low value the freedom of your users". It is hardly a rare occurrence now that I come across someone who has written in some corner of the Internet, "It's a shame project XYZ is GPL-licensed because I can't use it for commercial software development. Can the project maintainers not choose another licence?" Sometimes, someone who is seeking licensing advice might not want to be unpopular and might choose a permissive licence because people reassure them that their project will only be widely used if the licence lets people use it "commercially" (or, in other words, in proprietary software). My impression is that many in the core community around Python seem to emphasise such popularity over all other concerns. What I want to point out, and some have done so much more directly than I have in other forums and in other discussions, is that some advice about licensing often stems from a direct motivation amongst those giving the advice to secure preferential terms for themselves, and that although such advice may be dressed up as doing the "right" or "best" thing, those giving the advice stand to gain directly and even selfishly from having their advice followed. I'm not saying you have done this, but this is frequently seen in the core Python community, such that anyone suggesting a copyleft licence is seen as obstructing or undermining some community dynamic or other, while those suggesting a permissive licence are somehow doing so "in the spirit of Python" (to the point where the inappropriate PSF licence for Python is used for independent projects). > > Well, if you want the users to enjoy those "four freedoms" then you > > should use a copyleft licence. If you choose a permissive licence then > > it more or less means that you don't care about (or have no particular > > position on the matter of) the users being able to enjoy those > > privileges. I believe you coined the term "uncaring", but I think Mr > > Finney's statement stands up to scrutiny. > > I personally don't think that RMS's "four freedoms" are the last word > on the best way for society to develop software, no. ?But using > "Unless you place such a low value the freedom of your users" is truly > an inflammatory statement, because it was given in a context where the > GPL had not yet been carefully parsed and discussed, and did not make > it clear that the "freedoms" being discussed are a particular set of > "freedoms" and not, for example, those freedoms enshrined in the Bill > of Rights. ?(And as Steven has carefully pointed out, not all freedoms > are necessarily Good Things.) I tend not to use the terms "freedom" or "right" except when mentioning things like the "four freedoms": the word "privilege" is adequate in communicating what actually is conferred when combining copyright and software licences. Nevertheless, the "four freedoms" and "freedom of your users" are still useful notions: if a proprietary variant of Python became widespread and dominant, although various parts of the software might be freely available in their original forms, the ability to reconstruct or change the software would be impaired and provide fewer opportunities for user involvement than the primary implementations of Python available today. And should such proprietary software become mandated by government agencies or become a de-facto standard, that really does have an effect on the freedom of users. Paul From fuzzyman at gmail.com Sun May 9 17:38:27 2010 From: fuzzyman at gmail.com (Michael Foord) Date: Sun, 9 May 2010 23:38:27 +0200 Subject: Python is cool!! In-Reply-To: References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> <4BA8F56D.6060305@timgolden.me.uk> Message-ID: On 9 May 2010 20:36, Godson Gera wrote: > > > On Sun, May 9, 2010 at 6:24 PM, Fuzzyman wrote: > >> On Mar 23, 10:04 pm, geremy condra wrote: >> > On Tue, Mar 23, 2010 at 1:07 PM, Tim Golden >> wrote: >> > > On 23/03/2010 16:55, Jose Manuel wrote: >> > >> >> The closest is Skulpt which is very much an incomplete implementation >> of Python that runs in the browser. >> > > Since you have mentioned Skulpt, take a look at much better pyjamas > http://pyjs.org/ demos are awesome. > > I'm aware of Pyjamas. It is a Python to Javascript translator and *not* (as far as I know) capable of running an interpreter in the browser. Michael > -- > Thanks & Regards, > Godson Gera > IVRS India > -- http://www.ironpythoninaction.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Sun May 9 18:02:03 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 15:02:03 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> Message-ID: <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> On May 9, 4:21?pm, Paul Boddie wrote: (Lots of good and balanced commentary snipped...) > I didn't say that you personally argued that way, but people do argue > that way. In fact, it's understandable that this is how some people > attempt to understand the GPL - the software maintains a particular > state of openness - but they miss the final step in the reasoning > which leads them to see that the licence preserves a set of privileges > for recipients as well. Obviously, that's a bit subtle and certainly some people might miss the step that says "the final user can always use *my* software, and by choice of license I could decide to insure that if anybody else fixes bugs in my software or combines it with other software they write, then my end users will always be able to use that as well." But others might notice that and still decide that it isn't the right license for their software. > Thus, remarks about Cisco and Linksys - that they were somehow "caught > out" - are disingenuous: if you're in the business of distributing > software, particularly if that software itself has a restrictive > licence, you cannot claim ignorance about licensing or that you just > "found some good code". Any remarks I made about this were only in the debate about "moral hazard" by which I meant something different than Steven did. I'm not at all attempting to condone what Cisco did, just pointing out that if I license code under the MIT license and Cisco uses it, I certainly have no reason to complain about it, and wouldn't dream of doing so in any case, but if I license code under the GPL, then yes, my intentions are clear, and Cisco is complicit in either deliberately turning a blind eye, or inadvertently not watching employees closely enough. I thought I made it clear that I believe that at some level, some human being had to do something that was wrong in order to get Cisco into that position. My sole argument was that in general, I don't want to be the one to put Cisco in that position, and conversely, I don't want anybody else putting me in that position (I want to do the right thing) so I usually don't license stuff under the GPL, or incorporate stuff licensed under the GPL into anything I do. > Why is it pathetic that someone gets to choose the terms under which > their work is made available? By default, if I release something > without any licence, the recipient has very few privileges with > respect to that work: it's literally a case of "all rights reserved" > for the creator. And if it's such a trivial library then why not > reimplement the solution yourself? You just answered your own question. It's pathetic to try to change people's behavior by offering them something worthless if they change their license to match yours. (I'm not at all saying that all GPL code is worthless, but I have seen things like under 30 line snippets that weren't even very well written that were "licensed" under the GPL.) > I dislike the way that when someone releases something under the GPL, > it is claimed that they are coercing or attempting to "leverage" > something. They have merely shared something on their terms. If you > don't like the terms, don't use their software. Well, I don't always make that claim, but I do make it when I see a little "recipe" under the GPL. Often these recipes require so much customization for any particular task that they are really just pedagogical, and some of them aren't even very good. Color me a cynic, but when I see something so short and generic that any sort of judicial test would declare that there was no copyrightable "there" there, that has an arguably politicized license slapped on it, I smell an agenda. > But it is not universally true that GPL-licensed software cannot be > linked to proprietary software: there are a number of caveats in the > GPL covering cases where existing proprietary systems are in use. > Otherwise, you'd never have GPL-licensed software running on > proprietary systems at all. Agreed, but most of those are at very clearly delineated boundaries, like the OS. > > But the tone of your last statement and some of your statements below > > make it abundantly clear that you've made up your mind about my morals > > and aren't at all interested in my reasoning. > > Not at all. Recently, I've had the misfortune to hear lots of > arguments about how the GPL supposedly restricts stuff like > "collaboration" and "growth" despite copious evidence to the contrary, > usually from people who seem to be making a career of shouting down > the GPL or the FSF at every available occasion. Now I'm not saying > that you have the same apparent motivations as these people, but I > maintain that when someone claims that people are "forced" to share > their work when they voluntarily make use of someone else's work, or > that they are at the peril of some "moral hazard", it does have a lot > to say about their perspective. (Not least because people are only > obliged to make their work available under a GPL-compatible licence so > that people who are using the combined work may redistribute it under > the GPL. You yourself have mentioned elsewhere in this discussion one > well-known software project that is not GPL-licensed but was > effectively distributed under the GPL to most of its users for a > considerable period of time.) Sorry, guess I misunderstood where you are coming from. > It is hardly a rare occurrence now that I come across someone who has > written in some corner of the Internet, "It's a shame project XYZ is > GPL-licensed because I can't use it for commercial software > development. Can the project maintainers not choose another licence?" > Sometimes, someone who is seeking licensing advice might not want to > be unpopular and might choose a permissive licence because people > reassure them that their project will only be widely used if the > licence lets people use it "commercially" (or, in other words, in > proprietary software). My impression is that many in the core > community around Python seem to emphasise such popularity over all > other concerns. Yes, but I see the same sort of popularity effects tilt towards the GPL sometimes, too. > What I want to point out, and some have done so much more directly > than I have in other forums and in other discussions, is that some > advice about licensing often stems from a direct motivation amongst > those giving the advice to secure preferential terms for themselves, > and that although such advice may be dressed up as doing the "right" > or "best" thing, those giving the advice stand to gain directly and > even selfishly from having their advice followed. I'm not saying you > have done this, but this is frequently seen in the core Python > community, such that anyone suggesting a copyleft licence is seen as > obstructing or undermining some community dynamic or other, while > those suggesting a permissive licence are somehow doing so "in the > spirit of Python" (to the point where the inappropriate PSF licence > for Python is used for independent projects). Agreed that every project is different, and lots of considerations should be taken into account. > > I tend not to use the terms "freedom" or "right" except when > mentioning things like the "four freedoms": the word "privilege" is > adequate in communicating what actually is conferred when combining > copyright and software licences. Nevertheless, the "four freedoms" and > "freedom of your users" are still useful notions: if a proprietary > variant of Python became widespread and dominant, although various > parts of the software might be freely available in their original > forms, the ability to reconstruct or change the software would be > impaired and provide fewer opportunities for user involvement than the > primary implementations of Python available today. And should such > proprietary software become mandated by government agencies or become > a de-facto standard, that really does have an effect on the freedom of > users. I don't worry too much about that happening. I think that ESR is right that the powerful network effects of free development would overwhelm any attempt to take something like Python private. Regards, Pat From paul at boddie.org.uk Sun May 9 18:05:04 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 15:05:04 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> <6554e4fa-9fc0-49ab-a28d-413bd3152739@l31g2000yqm.googlegroups.com> Message-ID: On 9 Mai, 21:55, Patrick Maupin wrote: > On May 9, 12:08?pm, Paul Boddie wrote: > > > Oh sure: the GPL hurts everyone, like all the companies who have made > > quite a lot of money out of effectively making Linux the new > > enterprise successor to Unix, plus all the companies and individuals > > who have taken the sources and rolled their own distributions. > > So, people overstate their cases to make their points. ?That happens > on both sides. Overstate their cases? The "GPL hurts everyone" is a flat-out falsehood. > > It's not worth my time picking through your "holy war" rhetoric when > > you're throwing "facts" like these around. As is almost always the > > case, the people who see the merit in copyleft-style licensing have > > clearly given the idea a lot more thought than those who immediately > > start throwing mud at Richard Stallman because people won't let them > > use some software as if it originated in a (universally acknowledged) > > public domain environment. > > No, you appear to have a kneejerk reaction much worse than Carl's. > You have assumed you fully understand the motives of people who point > out issues with the GPL, and that those motives are uniformly bad, and > this colors your writing and thinking quite heavily, even to the point > where you naturally assumed I was defending all of Apple's egregious > behavior. I skimmed your post in that particular case and apologised for doing so. How have I not understood the motives of people who do not like the GPL? The GPL sets out a number of conditions on the use of a particular work; these conditions are not liked by some people typically because it means that they cannot use that work as part of a proprietary product or solution, just as the authors of the licence intended; various people would prefer that authors license their works permissively, precisely because this lets them use such works in proprietary software; some of the rhetoric employed to persuade people to permissively license their work involves phrases like "more freedom" (which are subjective at best, although never acknowledged as such) or the more absurd "holy war", evidently. I once attended a talk by someone from the FSF Europe, a few years ago now, where the inevitable assertion that the BSD licences were "more free" was made by an audience member. In my experience, such people are very reluctant to acknowledge the different philosophical dimensions of "freedom", whereas people who apply copyleft licences to their works have typically had to confront such issues even before being asked over and over again to relicense them. > As far as my throwing mud at Stallman, although I release some open > source stuff on my own, I make a living writing software that belongs > to other people, and Stallman has said that that's unethical and I > shouldn't be able to make money in this fashion. ?Sorry, but he's not > on my side. A lot of people seem to take issue with the GPL because they don't like Stallman, but that only leads to their judgement being clouded as a consequence. When Stallman's warnings become fulfilled, as has been the case with things like BitKeeper, this only serves to infuriate people further, often because they know they could have ignored the messenger but should not have ignored the message. Most people writing software are doing so for other people, and many people are doing so as part of a proprietary process. Thus, the only way to interpret what Stallman has to say (should you not wish to reject it completely) is to consider it as some kind of absolute guidance, not some kind of personal judgement. > > P.S. And the GPL isn't meant to further the cause of open source: it's > > meant to further the Free Software cause, which is not at all the same > > thing. Before you ridicule other people's positions, at least get your > > terminology right. > > And, again, that's "free" according to a somewhat contentious > definition made by someone who is attempting to frame the debate by co- > opting all the "mother and apple pie" words, who is blindly followed > by others who think they are the only ones who are capable of thoughts > which are both rational and pure. ?I'm not saying everybody who uses > the GPL is in this category, but some of your words here indicate that > you, in fact, might be. No, I am saying that the Free Software movement is a well-defined thing - that's why the name uses capital letters, but it could be called the "Planet of the Zebras movement" for all the name should reasonably distract from what the movement is actually about - and that it has a very different agenda from the "open source" movement which advocates very similar licensing on the basis of things like higher software quality and other "pragmatic" consequences of using such licensing. As for the terminology, I've already noted that I prefer the term "privileges" to "rights" or "freedoms" because it communicates that something is gained. Again, some people assume that the natural state of a work is (or should be) a free-for-all and that the GPL revokes privileges: this is a misrepresentation of how copyright and licensing functions. Paul From martin.hellwig at dcuktec.org Sun May 9 19:05:31 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 10 May 2010 00:05:31 +0100 Subject: Picking a license In-Reply-To: References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> <4BE70E0A.8060208@dcuktec.org> Message-ID: <4BE73FBB.3050405@dcuktec.org> On 05/09/10 21:06, Stephen Hansen wrote: > On Sun, May 9, 2010 at 12:33 PM, Martin P. Hellwig > > wrote: > > On 05/09/10 18:24, Stephen Hansen wrote: > > > > Wait, what? Why shouldn't I profit repeatedly from the "same > work already done"? *I* created, its *mine*. I put blood, > sweat and tears into it and perhaps huge amounts of resources, > risking financial security and sanity, and you're arguing I > shouldn't have the right to sell it after its done? > > Of course, but what do you do if you find out that your potential > customer already has your software without paying you? > > > Nothing. There's really very little benefit to me to go after > "potential customers". There will always be warez trading and cracked > versions of any product out there that someone can pirate. So what? > The vast majority of the people downloading that aren't actually > *potential customers*. They'd never have bought the products to begin > with. > > Now, if I find out some other company happens to be selling my > software, them I'd sue into oblivion and make a killing -- copyright > lets me do that. Assuming that you have enough financial resources and that company is within the same jurisdiction, granted otherwise it is still possible but often seen unfeasible. > > > Exactly how do you imagine I'm going to make money off of it? > How the existing system works is that I sell... multiple > copies of it. Maybe hundreds or thousands before that > investment is recouped. At that point, do I no longer get to > sell multiple copies? Or do I have to find someone to > retroactively pay me some kind of salary? What does "pay for > work" even mean? > > As a simple developer I do not think my craft is more special than > any other craft like carpentry, masonry, plumbing, electrician etc. > And as I see how other crafts get paid I think is reasonable for > my craft too, I am either employed and paid by the hour or take > more risks and do projects, commissions, etc. etc. > > Of course if I would be in the construction business and I build a > house I can either sell it or let it, but then I do take the risk > that the occupant uses my work beyond what I expected and > eventually end up with a huge repair costs. > > I am sure you can imagine the rest of my comparison arguments > between construction and software development. > > > You're comparing apples to rabbits. There's nothing even vaguely alike > between the two no matter how much you are trying to compare them: > carpentry, masonry, plumbing, all of that deal with *physical* items, > that by their very nature create singular, specific, tangible items > and/or services. > > If I create a software product on commission for some private company, > that's almost-kind of like what happens for other "crafts", wherein > someone pays me some amount of money for some amount of work to > produce a finished product. But how exactly do you imagine I would > make money if I have some idea for some great new program and I write > it on my own? > > The only way is to... sell multiple copies. Or try to find someone to > give me one big lump sum for the privilege of releasing it to the > universe. I have seen a couple of times when one organization/user has not the financial resources to commission or further develop an (software) idea that they through trade or sector organization combine their resources to get there, this happen quite often in education institutes for the development for administration programs. Personally I think that where there is a will there is a way. > > Software is intangible, irregardless of the fact that it might show up > on a physical medium. You can't compare work of the mind with work of > physical crafts-- one is not more worthy of money then the other, but > they are *different*. Like poetry, music and the such, which indeed share much of the same problems as software. Still they flourished even before rule enforcement. I am sure that Muhammad ibn M?s? al-Khw?rizm?, didn't have too much problems in that regard. > > What's wrong with software copyrights? Don't lump intellectual > property issues together, they're not comparable. Copyrights have > nothing at all to do with patents which have nothing at all to do > with trademarks. Each is a very different set of law. > > Very true and in my opinion they all share the same trait, > although they are once made to make sure the original author gets > credit and profit for his/her work they are primarily used now to > profit beyond reasonableness and actually encumber future > development and good use, IMHO they actually hinder the > intellectual development of the human race. > > > You say 'very true' but then you lump them all together again. "They" > are not at all for the same thing. I said they share a same trait, I did not say they where the same thing and above that I said it was IMHO, which should indicate that I am aware that opinions differ on that. > > Copyrights are intended, indeed, to make sure the original author gets > credit and profit for his creative work. They tend to last a rather > long time these days. > > Patents are intended to allow a relatively short-term monopoly on some > new invention, so that the vast costs of R&D can be justified, but > also so that the -result- of that R&D will be published to the public > and after that monopoly is over, allow everyone to benefit. They are > an encumbrance, yes, but a temporary one: and after that encumbrance > is over, the inventor losers all control over the invented. > Unfortunately, patents are woefully broken due to business methods and > software being allowed to be 'patented', which is just silly on both > cases. > > Trademarks are intended to protect the *consumers*, by disallowing > companies from marketing in a confusing way such that what they are > selling may be mistaken for what a reputable third-party is selling. A > company can trademark its "brand", and by doing so customers can know > that brand and IF they trust it, rely on it when they see it. > Trademarks actually, IMHO, work quite well -- companies actually have > to enforce them and be pro-active about them, unlike with patents, > where one can sit around and wait for another to firmly establish > themselves with technology based on your patent, then jump in and sue. > I fail to see how there's really anything "encumbering" about trademarks. Uh I missed the bit about me being against trademarks, I actually agree that this is a good thing, because this prevents fraud. > > > Sure, there's some nutty corner cases in copyrights, which > need to be addressed-- including things like fair use and DRM. > But on the whole, copyrights aren't really all that broken. > Its nothing like the situation with software patents, which > are just sort of crazy. > > Okay so what do you actually do if you find out that in another > country, which do not share the same legislation (about the other > 80% of the population) brakes your copyright or does not uphold > the patent restrictions? > If your big like Microsoft you might try to convince that > particular government that their citizens should pay you, > otherwise good luck (even for Microsoft as they seem to fail more > often than succeed in that notion). > > > Umm. > > http://upload.wikimedia.org/wikipedia/commons/7/76/Berne_Convention_signatories.svg > http://upload.wikimedia.org/wikipedia/commons/c/c1/WIPO.png > > And a couple others, including the Pair Convention of something or other. > > Intellectual property law is pretty globally standard these days. > That's not to say that in some places its not largely ignored in > certain sectors, but see first response above. > > They are broken because by definition restrictions need > enforcement to uphold them, if there is no enforcement it will not > work. Perhaps a better solution would be to find a way that does > not need any enforcement (or limited amount of it), say like the > economy worked prior to patents and copyrights minus kings and > tyrants. > > > ... copyright dates back to the 1700's. In Europe (UK) and US. > > And, there are ways to enforce the "restrictions"-- which are not > restrictions, but instead enforcement of rights that I, as the one who > made this creative work, hold. Its a civil action. (Though certain > types and kinds of infringement may in some jurisdictions be a > criminal offense) > > > You can believe in the Free Software movement (I'm not saying > you do, this 'you' is impersonal and metaphorical)-- and if > you do, good for you. You can believe in "morality" with > regards to "freedom" and the "essential rights" of the users. > I find it all nonsensical. But good for you if you believe in > it. But the Free Software movement exists *because* of > copyrights. Copyright Law is what makes the GPL even possible. > > > I don't believe in a system which is based on enforcing rules and > where breaking of this rule at most results in a hypothetical loss > of income. Some enforced rules are of course necessary, like not > going on a pillage/killing/raping spree (except of course if this > is your job but then your still governed by the rules of Geneva -- > yeah I know bold military statement, but I have been there too, > the military that is). I rather like to find a way where minimal > rule enforcing is necessary to make a living. > > > I find i can make a living quite well with basically zero "rule > enforcing", because of copyrights. I really don't need to enforce that > every kid out there might get an illegal copy of a program I wrote. > They aren't my customers. However, because I have copyright, I can be > sure that no other companies are going to start completing with me > based on my own work. (That I made this argument in a thread about > open source licensing, and the irony therein, does not escape me) It makes perfect sense to me, just as you said open source license is just another form of copyright. > > Cuz then I'll sue their ass off. > > But its never happened. And I don't expect it to happen. Because > copyright is an international, pretty clearly standardized set of law. Stating the fact that copyright is a clear international standard, only on a limited scale contributes to the argument that it is an effective process. Supporting this argument that is has never happened to you nor that you expect it to happen only demonstrates that your software is just not popular enough to suffer infringement, because _all_ other popular software does (according to virtual every lobby group). Actually you could go so far and define the popularity of software by the amount of copyright infringements. > > > But I fail to see what's fundamentally wrong with that system. > > I hope I have further explained my point of view and hope that you > agree with me at least from my perspective, I do understand though > that your point of view is perfectly valid and reasonable. It is > just that I am a sucker for seeking alternative ways to improve > systems even if they only show small amounts of defects. So you > could argue that I have my sight set for an Utopia while you > rather remain in the reality, if you can find yourself with this > than at least we can agree on that :-) > > > Had you stuck to wanting to make patents make sense, I would have > agreed with you about half the way-- but I actually, mostly, sorta > think copyrights are fine. Even with idiocies like DRM. I think the > market has to decide to turn away from DRM. (I'm looking at you > Ubisoft: you've lost over $100 already from me!) > > --S Well if may sum it up (minus trademarks as we both agree on the need for it): Your opinion is that copyrights, within reason, work on a global scale. Patents are necessary and also work on a global scale. I have no doubt that copyrights and patents exist. I have no doubt that globally governments indicate that they are enforcing it. However I do doubt that they work, I think the enforcing is highly ineffective. If at average at least 1 in 5 software products use is an 'illegal' version (http://www.nationmaster.com/graph/cri_sof_pir_rat-crime-software-piracy-rate) then by no way you can say if is effectively enforced. Take it from another perspective, everybody who uses illegal software in full awareness (according to those terms) is by that definition a criminal, equal to somebody stealing a car radio. This would make most of the people out there criminals, from primary school goers to senior citizens. And to be true this is what bothers me the most, it criminalizes people who otherwise would never be attributed to malice. I took a firm stand against copyrights and patents in this thread, but I am not that fanatic, in reality I prefer open-source, but I do buy software, like recently Spore. I don't buy my Microsoft software because I can download and use them for free (I have an MSDN & Technet subscription). However for myself I do not contribute to copyrights, but because the rest of the world does I need to stick at least the MIT/BSD license on it. Patents, well I suppose big corporation that have huge investment need to see a ROI, I mean Amazon would have been in a financial crisis if they didn't patented their innovating the single-click shopping. Small time and accidental inventors don't have the financial means anyway to afford a global patent these days. -- mph -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Sun May 9 19:39:12 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 16:39:12 -0700 (PDT) Subject: Picking a license References: <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> Message-ID: <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> On 10 Mai, 00:02, Patrick Maupin wrote: > > You just answered your own question. ?It's pathetic to try to change > people's behavior by offering them something worthless if they change > their license to match yours. ?(I'm not at all saying that all GPL > code is worthless, but I have seen things like under 30 line snippets > that weren't even very well written that were "licensed" under the > GPL.) If this is code that you would consider using in an existing project, but if they aren't pitching it directly at you, why would you believe that they are trying to change your behaviour? It is you who gets to decide whether you use the code or not. If the licence isn't acceptable to you, what prevents you from asking for a special licence, especially if you are going to incorporate the code in a product which is sold? In the more general case of people just releasing small programs and libraries, all such people are doing is saying, "Here is something I have done, and here are the terms through which this is shared." If anything, they are reaching out to see if anyone will work together with them on making something better, where everyone agrees to a common framework upon which that work will be done. I'm sure people didn't think much of Linus Torvalds' work in the beginning, either. Paul From aharrisreid at googlemail.com Sun May 9 19:43:01 2010 From: aharrisreid at googlemail.com (Alan Harris-Reid) Date: Mon, 10 May 2010 00:43:01 +0100 Subject: Binary file email attachment problem Message-ID: <4BE74885.8010602@googlemail.com> Hi there, Using Python 3.1.2 I am having a problem sending binary attachment files (jpeg, pdf, etc.) - MIMEText attachments work fine. The code in question is as follows... for file in self.attachments: part = MIMEBase('application', "octet-stream") part.set_payload(open(file,"rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % file) msg.attach(part) # msg is an instance of MIMEMultipart() server = smtplib.SMTP(host, port) server.login(username, password) server.sendmail(from_addr, all_recipients, msg.as_string()) However, way down in the calling-stack (see traceback below), it looks as though msg.as_string() has received an attachment which creates a payload of 'bytes' type instead of string. I suspect the error lies in the encoding somewhere, but I've no idea where. I have also tried MIMEApplication and MIMEImage, but the error still remains. I have seen many similar code examples on the web, all of which fail for me, so I wonder if there is something wrong with my environment. Has anyone any idea what might be causing the problem? Any help would be appreciated. Alan ________________________________________________________________ builtins.TypeError: string payload expected: File "c:\Dev\CommonPY\Scripts\email_send.py", line 147, in send server.sendmail(self.from_addr, all_recipients, msg.as_string()) File "c:\Program Files\Python31\Lib\email\message.py", line 136, in as_string g.flatten(self, unixfrom=unixfrom) File "c:\Program Files\Python31\Lib\email\generator.py", line 76, in flatten self._write(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 101, in _write self._dispatch(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 127, in _dispatch meth(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 181, in _handle_multipart g.flatten(part, unixfrom=False) File "c:\Program Files\Python31\Lib\email\generator.py", line 76, in flatten self._write(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 101, in _write self._dispatch(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 127, in _dispatch meth(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 155, in _handle_text raise TypeError('string payload expected: %s' % type(payload)) ____________________________________________________________ From pmaupin at gmail.com Sun May 9 21:09:59 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 18:09:59 -0700 (PDT) Subject: Picking a license References: <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> Message-ID: On May 9, 6:39?pm, Paul Boddie wrote: > On 10 Mai, 00:02, Patrick Maupin wrote: > If this is code that you would consider using in an existing project, Well, in a few cases I'm talking about, I wouldn't consider using the code -- I just stumbled across it when researching some terms, and discounted it immediately. Honestly, I'm talking about code that is so small and generic that it doesn't deserve any copyright protection (and wouldn't get any if it came to that in court). > but if they aren't pitching it directly at you, why would you believe > that they are trying to change your behaviour? Because I've seen people specifically state that their purpose in GPLing small libraries is to encourage other people to change their behavior. I take those statements at face value. Certainly RMS carefully lays out that the LGPL should be used sparingly in his "Why you shouldn't use the Lesser GPL for your next library" post. (Hint: he's not suggesting a permissive license instead.) > It is you who gets to > decide whether you use the code or not. If the licence isn't > acceptable to you, what prevents you from asking for a special > licence, especially if you are going to incorporate the code in a > product which is sold? Well, the only time I can remember even hinting around for any kind of different license was when I was found an svglib bug for use with rst2pdf. svglib is a "real" library (unlike the code snippets I was discussing) licensed under the GPL. I would be quite happy to consider learning it and contributing patches to it, but I didn't want to maintain a fork myself, and the maintainer doesn't have a public repository and was quite busy with other stuff, and when I asked him if he would accept patches, it was ten days before he got back to me. rst2pdf was licensed under the MIT license before I started contributing to it, and there is no way I was going to even consider adding patches for a GPLed package (which would certainly have to be GPLed) into the rst2pdf repository. (Say what you will about how sometimes differently licensed code can be combined, but RMS has to share quite a bit of the blame/credit for the whole combining licenses FUD.) So I took a completely different path and right now the best way to use .svg files with rst2pdf is to use inkscape to convert them to PDFs, and use some code I wrote that allows you to use preexisting PDFs as images. Despite being a real library, svglib is quite small at ca. 1200 lines, and if the license were compatible with the rst2pdf codebase license (e.g. even if it were LGPL), I would have just stuffed the file into the rst2pdf codebase and started hacking on it. So there's a nice little piece of GPLed code that isn't getting as much attention as it would have if it were LGPLed or licensed permissively, or even if the author had just dumped it onto sourceforge or googlecode under the GPL but given me commit rights. As it is, I don't think it's been maintained in 8 years. This is exactly the same situation that Carl was describing, only with two different open source packages rather than with a proprietary package and a GPL package. The whole reason people use words like "force" and "viral" with the GPL is that this issue would not have come up if svglib were MIT and rst2pdf were GPL. (Note that the LGPL forces you to give back changes, but not in a way that makes it incompatible with software under other licenses. That's why you see very few complaints about the LGPL.) > In the more general case of people just releasing small programs and > libraries, all such people are doing is saying, "Here is something I > have done, and here are the terms through which this is shared." Sure, and all I'm explaining is why I reject the terms in some cases. I particularly reject the terms when a license that was originally designed for a whole program is used for a small library, with the express intent of getting more people to use said license. > If anything, they are reaching out to see if anyone will work together > with them on making something better, where everyone agrees to a > common framework upon which that work will be done. That's absolutely not always the case. Often, it's more "here's something I've done; take it or leave it but if you take it, it's on these terms." > I'm sure people > didn't think much of Linus Torvalds' work in the beginning, either. I think the GPL was a great license for the development model for Linux. I have no issues with how that worked. Part of that is that Linus was always active in the development. I think that, particularly when the concept of free software was relatively new, the license might have been an effective focal point for rallying contributions. But I have definitely seen cases where people are offering something that is not of nearly as much value as they seem to think it is, where one of the goals is obviously to try to spread the GPL. Regards, Pat From pmaupin at gmail.com Sun May 9 21:41:32 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 18:41:32 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> <6554e4fa-9fc0-49ab-a28d-413bd3152739@l31g2000yqm.googlegroups.com> Message-ID: On May 9, 5:05?pm, Paul Boddie wrote: > On 9 Mai, 21:55, Patrick Maupin wrote: > > > On May 9, 12:08?pm, Paul Boddie wrote: > > > > Oh sure: the GPL hurts everyone, like all the companies who have made > > > quite a lot of money out of effectively making Linux the new > > > enterprise successor to Unix, plus all the companies and individuals > > > who have taken the sources and rolled their own distributions. > > > So, people overstate their cases to make their points. ?That happens > > on both sides. > > Overstate their cases? The "GPL hurts everyone" is a flat-out > falsehood. Well, just like in some cases it makes us all richer, in some cases it also makes us all poorer. See my prior example about svglib. > > > It's not worth my time picking through your "holy war" rhetoric when > > > you're throwing "facts" like these around. As is almost always the > > > case, the people who see the merit in copyleft-style licensing have > > > clearly given the idea a lot more thought than those who immediately > > > start throwing mud at Richard Stallman because people won't let them > > > use some software as if it originated in a (universally acknowledged) > > > public domain environment. > > > No, you appear to have a kneejerk reaction much worse than Carl's. > > You have assumed you fully understand the motives of people who point > > out issues with the GPL, and that those motives are uniformly bad, and > > this colors your writing and thinking quite heavily, even to the point > > where you naturally assumed I was defending all of Apple's egregious > > behavior. > > I skimmed your post in that particular case and apologised for doing > so. Apology accepted. > How have I not understood the motives of people who do not like the > GPL? The GPL sets out a number of conditions on the use of a > particular work; these conditions are not liked by some people > typically because it means that they cannot use that work as part of a > proprietary product or solution, just as the authors of the licence > intended; As I have shown in another post, in one case, I wanted to contribute a fix for making one piece of GPLed software work better with another case of MIT licensed software. The fact that one piece was GPLed and the author didn't have a repository and was relatively unresponsive via email, combined with the fact that I was too lazy to start a new repository just to maintain a fork of one small library, means that I didn't devote any time to fixing bugs and making the GPLed software better. A "proprietary product or solution" never entered into the picture. > various people would prefer that authors license their works > permissively, precisely because this lets them use such works in > proprietary software; You also are ignoring the fact that a lot of people practice what they preach on the other side of this issue. Since I don't want to make other people jump through these sorts of licensing hoops, I license stuff under the MIT license. MIT, BSD, and Apache are "universal donor licenses" and just like type O blood, I think this increases the value of the code licensed under them. > some of the rhetoric employed to persuade people > to permissively license their work involves phrases like "more > freedom" (which are subjective at best, although never acknowledged as > such) or the more absurd "holy war", evidently. Well, I think the reason "more freedom" is used is because RMS has attempted to co-opt the word "freedom" and I think "holy war," though inflammatory, accurately portrays the kind of language RMS uses to attract his followers. YMMV > I once attended a talk by someone from the FSF Europe, a few years ago > now, where the inevitable assertion that the BSD licences were "more > free" was made by an audience member. In my experience, such people > are very reluctant to acknowledge the different philosophical > dimensions of "freedom", whereas people who apply copyleft licences to > their works have typically had to confront such issues even before > being asked over and over again to relicense them. Well, the whole reason I got involved in this thread was I felt that I was, by association, being accused of not caring about others' "freedom" so this is a pot/kettle issue. Also, when you're deeply involved in an issue, you might miss or ignore insults hurled by others seemingly on your side; it's always easier to spot the logical fallacies made by members of the opposing side, and come to the conclusion that your side is smarter, more moral, and generally superior. > > As far as my throwing mud at Stallman, although I release some open > > source stuff on my own, I make a living writing software that belongs > > to other people, and Stallman has said that that's unethical and I > > shouldn't be able to make money in this fashion. ?Sorry, but he's not > > on my side. > > A lot of people seem to take issue with the GPL because they don't > like Stallman, but that only leads to their judgement being clouded as > a consequence. When Stallman's warnings become fulfilled, as has been > the case with things like BitKeeper, this only serves to infuriate > people further, often because they know they could have ignored the > messenger but should not have ignored the message. Most people writing > software are doing so for other people, and many people are doing so > as part of a proprietary process. Thus, the only way to interpret what > Stallman has to say (should you not wish to reject it completely) is > to consider it as some kind of absolute guidance, not some kind of > personal judgement. Oh, but I do consider the licenses separately, and describe when I think they are appropriate. Again, if you're addressing half the debaters, you're missing the people on your side (not necessarily in this particular thread) who quote Stallman and Moglen as if their word is the final word on everything. Even in the example you quote here, it was obvious what was going to happen with bitkeeper to the most casual observer, so I don't think that by itself shows incredible powers of observation on Stallman's part. I also think that if Stallman didn't exist, we would have invented him -- it was time for that particular philosophy. > > > P.S. And the GPL isn't meant to further the cause of open source: it's > > > meant to further the Free Software cause, which is not at all the same > > > thing. Before you ridicule other people's positions, at least get your > > > terminology right. > > > And, again, that's "free" according to a somewhat contentious > > definition made by someone who is attempting to frame the debate by co- > > opting all the "mother and apple pie" words, who is blindly followed > > by others who think they are the only ones who are capable of thoughts > > which are both rational and pure. ?I'm not saying everybody who uses > > the GPL is in this category, but some of your words here indicate that > > you, in fact, might be. > > No, I am saying that the Free Software movement is a well-defined > thing - that's why the name uses capital letters, but it could be > called the "Planet of the Zebras movement" for all the name should > reasonably distract from what the movement is actually about - and > that it has a very different agenda from the "open source" movement > which advocates very similar licensing on the basis of things like > higher software quality and other "pragmatic" consequences of using > such licensing. But you're missing the point that it is called the "Free Software" movement precisely for all the religious/political reasons that piss some people off. People wouldn't get all hot and bothered about it if it were the Planet of the Zebras movement, but RMS never would have called it that. > As for the terminology, I've already noted that I prefer the term > "privileges" to "rights" or "freedoms" because it communicates that > something is gained. That's a reasonable starting point, but you still need a way to distinguish who is getting the privileges -- in the case of the GPL, it's often the non-programming general public, whereas in the case of the MIT license, it's anybody who wants to do the software equivalent of mash-ups, whether they want to generally share with the public or not. Even that's not quite right -- the GPL allows me to make any kind of mash-up I want as long as I don't want to share it with *anybody* else; it's only when I want to share that it becomes a problem if I used the wrong ingredients inside my mash-up. That's where the "force" and "viral" words come from -- Microsoft doesn't force me to use their license if I code to their API and don't distribute their code, but the FSF's viewpoint is that any linking (static or dynamic) forces me to use the GPL on my code even if I'm not distributing the GPLed code I'm dynamically linking to. (Legally, I think that's probably wrong, but that's their opinion, and apparently the opinion of a lot of their adherents, so morally it would be wrong for me to go against their wishes.) > Again, some people assume that the natural state > of a work is (or should be) a free-for-all and that the GPL revokes > privileges: this is a misrepresentation of how copyright and licensing > functions. As I said earlier in the thread, the OP's question was not "no license or GPL" but rather "MIT or GPL" so the relevance of a non-licensed alternative wasn't really a point of this particular discussion. Regards, Pat From zhongby at ucweb.com Sun May 9 22:40:51 2010 From: zhongby at ucweb.com (=?gb2312?B?1tOx/tPC?=) Date: Mon, 10 May 2010 10:40:51 +0800 Subject: Queue.Queue() AttributeError exception Message-ID: <201005101040516097598@ucweb.com> I have a multi-thread program work with Queue.Queue(), sometimes put request to the work queue, but throw an exception as below traceback information, it will always throw the exception until restart program, cound please have any experience, your help will be greatly appreciated! File "/usr/local/lib/python2.4/Queue.py", line 71, in put self.not_full.acquire() AttributeError: '_Condition' object has no attribute 'acquire' -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at nospam.invalid Sun May 9 23:58:08 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 09 May 2010 20:58:08 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <4be6f8f8$0$27783$c3e8da3@news.astraweb.com> Message-ID: <7xhbmgwgq7.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > It's certainly true > that an MIT licence will allow you to maximise the number of people who > will use your software, but maximising the number of users is not the > only motive for writing software. I'd say proprietary licenses where you spend billions on marketing and lobbying get you the most users. Windows has orders of magnitude more users than either Linux or BSD. FOSS under any license isn't about maximizing users. From pavlovevidence at gmail.com Mon May 10 02:31:13 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 9 May 2010 23:31:13 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> Message-ID: <99386b28-1636-4f81-beec-3756970d37e8@11g2000prv.googlegroups.com> On May 9, 10:08?am, Paul Boddie wrote: > On 9 Mai, 09:05, Carl Banks wrote: > > Bottom line is, GPL hurts everyone: the companies and open source > > community. ?Unless you're one of a handful of projects with sufficient > > leverage, or are indeed a petty jealous person fighting a holy war, > > the GPL is a bad idea and everyone benefits from a more permissive > > licence. > > Oh sure: the GPL hurts everyone, like all the companies who have made > quite a lot of money out of effectively making Linux the new > enterprise successor to Unix, plus all the companies and individuals > who have taken the sources and rolled their own distributions. Relative to what they could have done with a more permissive license? Yes. GPL hurts everyone relative to licenses that don't drive wedges and prevent interoperability between software. You might argue that GPL is sometimes better than proprietary closed source, and I won't disagree, but it's nearly always worse than other open source licenses. > P.S. And the GPL isn't meant to further the cause of open source: it's > meant to further the Free Software cause, which is not at all the same > thing. It doesn't matter what the GPL "meant" to do, it matters what it does, which is hurt everyone (relative to almost all other licenses). > Before you ridicule other people's positions, at least get your > terminology right. I don't agree with FSF's defintion of free software and refuse to abide by it. GPL isn't free software; any software that tells me I can't compile it in with a closed source API isn't free. Period. Carl Banks From stefan_ml at behnel.de Mon May 10 02:54:19 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 May 2010 08:54:19 +0200 Subject: Fastest way to calculate leading whitespace In-Reply-To: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: dasacc22, 08.05.2010 19:19: > This is a simple question. I'm looking for the fastest way to > calculate the leading whitespace (as a string, ie ' '). Here is an (untested) Cython 0.13 solution: from cpython.unicode cimport Py_UNICODE_ISSPACE def leading_whitespace(unicode ustring): cdef Py_ssize_t i cdef Py_UNICODE uchar for i, uchar in enumerate(ustring): if not Py_UNICODE_ISSPACE(uchar): return ustring[:i] return ustring Cython compiles this to the obvious C code, so this should be impossible to beat in plain Python code. However, since Cython 0.13 hasn't been officially released yet (may take another couple of weeks or so), you'll need to use the current developer version from here: http://hg.cython.org/cython-devel Stefan From stefan_ml at behnel.de Mon May 10 03:25:43 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 May 2010 09:25:43 +0200 Subject: Fastest way to calculate leading whitespace In-Reply-To: References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: Stefan Behnel, 10.05.2010 08:54: > dasacc22, 08.05.2010 19:19: >> This is a simple question. I'm looking for the fastest way to >> calculate the leading whitespace (as a string, ie ' '). > > Here is an (untested) Cython 0.13 solution: > > from cpython.unicode cimport Py_UNICODE_ISSPACE > > def leading_whitespace(unicode ustring): > cdef Py_ssize_t i > cdef Py_UNICODE uchar > > for i, uchar in enumerate(ustring): > if not Py_UNICODE_ISSPACE(uchar): > return ustring[:i] > return ustring > > Cython compiles this to the obvious C code, so this should be impossible > to beat in plain Python code. ... and it is. For a simple string like u = u" abcdefg" + u"fsdf"*20 timeit gives me this for "s=u.lstrip(); u[:-len(s)]": 1000000 loops, best of 3: 0.404 usec per loop and this for "leading_whitespace(u)": 10000000 loops, best of 3: 0.0901 usec per loop It's closer for the extreme case of an all whitespace string like " "*60, where I get this for the lstrip variant: 1000000 loops, best of 3: 0.277 usec per loop and this for the Cython code: 10000000 loops, best of 3: 0.177 usec per loop But I doubt that this is the main use case of the OP. Stefan From bieffe62 at gmail.com Mon May 10 03:40:17 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Mon, 10 May 2010 00:40:17 -0700 (PDT) Subject: solve a newspaper quiz References: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> Message-ID: <89888164-41a1-4306-ad7a-2e7d3957c02a@37g2000yqm.googlegroups.com> On 9 Mag, 11:20, superpollo wrote: > "if a b c are digits, solve ab:c=a*c+b" > > solved in one minute with no thought: > > for a in range(10): > ? ? ?for b in range(10): > ? ? ? ? ?for c in range(10): > ? ? ? ? ? ? ?try: > ? ? ? ? ? ? ? ? ?if (10.*a+b)/c==a*c+b: > ? ? ? ? ? ? ? ? ? ? ?print "%i%i:%i=%i*%i+%i" % (a,b,c,a,c,b) > ? ? ? ? ? ? ?except: > ? ? ? ? ? ? ? ? ?pass > > any suggestion for improvement? > > bye The obvious one-liner. Maybe not an improvement, but more compact (I included the solutions for the really lazy ones). But you need to think just one second to exclude 0 from the values of c and avoid a divide by zero exception. >>> [(a,b,c) for a in range(10) for b in range(10) for c in range(1,10) if (a*10+b)/c == a*c+b ] [(0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 0, 5), (0, 0, 6), (0, 0, 7), (0, 0, 8), (0, 0, 9), (0, 1, 1), (0, 2, 1), (0, 3, 1), (0, 4, 1), (0, 5, 1), (0, 6, 1), (0, 7, 1), (0, 8, 1), (0, 9, 1), (1, 0, 3), (1, 5, 2), (1, 6, 2), (2, 0, 3), (2, 1, 3), (3, 1, 3), (4, 1, 3), (4, 2, 3), (5, 2, 3), (6, 2, 3), (6, 3, 3), (7, 3, 3), (8, 3, 3), (8, 4, 3), (9, 4, 3)] Ciao --- FB From nilly16 at yahoo.com Mon May 10 04:40:05 2010 From: nilly16 at yahoo.com (Jimbo) Date: Mon, 10 May 2010 01:40:05 -0700 (PDT) Subject: Extract all words that begin with x Message-ID: Hello I am trying to find if there is a string OR list function that will search a list of strings for all the strings that start with 'a' & return a new list containing all the strings that started with 'a'. I have had a search of Python site & I could not find what I am looking for, does a function like this exist? The only one that I think could work is, use the string function .count() algorithm: to exract all the words inside a list that start with 'a' - make sure the list is arranged in alphabetical order - convert the list to a big string - use list_string.count(',a') to obtain the index where the last 'a' word occurs - convert back into string (yes this is a REAL hack :P) - and then create a new list, ie, new_list = list[0:32] - & return new_list Ok that algorithm is terrible, I know, & I just realise that it wont work for letters after 'a'. So if anyone could suggest a function or algorithm it would be extremely helpful From contact at xavierho.com Mon May 10 04:50:56 2010 From: contact at xavierho.com (Xavier Ho) Date: Mon, 10 May 2010 18:50:56 +1000 Subject: Extract all words that begin with x In-Reply-To: References: Message-ID: Have I missed something, or wouldn't this work just as well: >>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas'] >>> [word for word in list_of_strings if word[0] == 'a'] ['awes', 'asdgas'] Cheers, Xav On Mon, May 10, 2010 at 6:40 PM, Jimbo wrote: > Hello > > I am trying to find if there is a string OR list function that will > search a list of strings for all the strings that start with 'a' & > return a new list containing all the strings that started with 'a'. > > I have had a search of Python site & I could not find what I am > looking for, does a function like this exist? > > The only one that I think could work is, use the string > function .count() > > algorithm: to exract all the words inside a list that start with 'a' > - make sure the list is arranged in alphabetical order > - convert the list to a big string > - use list_string.count(',a') to obtain the index where the last 'a' > word occurs > - convert back into string (yes this is a REAL hack :P) > - and then create a new list, ie, new_list = list[0:32] > - & return new_list > > Ok that algorithm is terrible, I know, & I just realise that it wont > work for letters after 'a'. So if anyone could suggest a function or > algorithm it would be extremely helpful > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From utente at esempio.net Mon May 10 05:11:59 2010 From: utente at esempio.net (superpollo) Date: Mon, 10 May 2010 11:11:59 +0200 Subject: Extract all words that begin with x In-Reply-To: References: Message-ID: <4be7cddf$0$1105$4fafbaef@reader4.news.tin.it> Jimbo ha scritto: > Hello > > I am trying to find if there is a string OR list function that will > search a list of strings for all the strings that start with 'a' & > return a new list containing all the strings that started with 'a'. > > I have had a search of Python site & I could not find what I am > looking for, does a function like this exist? >>> sw = lambda s: lambda t: t.startswith(s) >>> list = ["a string","another one","this is a string","and so is this one"] >>> filter(sw("a"),list) ['a string', 'another one', 'and so is this one'] >>> bye From jeanmichel at sequans.com Mon May 10 05:26:56 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 11:26:56 +0200 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: <4BE7D160.8030300@sequans.com> Stefan Behnel wrote: > j vickroy, 07.05.2010 20:44: >> I apologize if this is not the appropriate forum for a question about >> Hudson (http://hudson-ci.org/), but I did not know where else to ask and >> my web searches have not been fruitful. > > Certainly nice to read something about Hudson in this forum, which is > rare enough. It's seriously the greatest CI tool I've ever used, and > it works great with Python apps. > We use it, but this is a python list that's why there's few topics about it. :) Speaking for myself, I use it to execute the linter (pylint) on the code and run unitary tests. Great tool for sure. JM From jiazhao62 at yahoo.com Mon May 10 05:30:00 2010 From: jiazhao62 at yahoo.com (world-trade) Date: Mon, 10 May 2010 02:30:00 -0700 (PDT) Subject: NFL NBA MLB NHL jersey Message-ID: <1297af1d-09da-4b72-b08f-d166c8a4f4fb@31g2000prc.googlegroups.com> AAA quality clothes cheap wholesale . (http:// www.jordanonline06.com/) NFL jersey wholesale (http://www.jordanonline06.com/) NFL NBA MLB NHL soccer soccer jerseys (http:// www.jordanonline06.com/) nike brand,MLB jerseys china supplier (http:// www.jordanonline06.com/) MLB jerseys china wholesaler.(http://www.jordanonline06.com/) wholesale MLB jerseys.(http://www.jordanonline06.com/) NFL shop,,NFL NBA MLB NHL jerser wholesale,NFL NBA MLB NHL (http://www.jordanonline06.com/) jersey supplier(http://www.jordanonline06.com/) NFL NBA MLB NHL jersey korea supplier (http:// www.jordanonline06.com/) NFL NBA jersey stock (http://www.jordanonline06.com/) alibaba,wholesale NFL NBA MLB NHL jerseys.(http:// www.jordanonline06.com/) soccer jersey china supplier (http://www.jordanonline06.com/) soccer jerseys china wholesale.(http://www.jordanonline06.com/) wholesale soccer jersey,supply soccer jerseys (http:// www.jordanonline06.com/) NFL NBA MLB NHL copy jersey (http://www.jordanonline06.com/) copy www.guoshitrade.com paypal paymentjerseys from china (http://www.jordanonline06.com/) NFL jerseys from china.(http://www.jordanonline06.com/) NBA www.guoshitrade.com paypal payment shop (http:// www.jordanonline06.com/) NFL jersey wholesale womens NBA jersey (http:// www.jordanonline06.com/) NBA jersey sale (http://www.jordanonline06.com/) cheap authentic NBA jersey (http://www.jordanonline06.com/) 07 jersey NBA star (http://www.jordanonline06.com/) NBA jersey numbers (http://www.jordanonline06.com/) NBA vintage jersey NBA throw back jersey (http://www.jordanonline06.com/) NBA jersey dress for woman (http://www.jordanonline06.com/) reebok NBA jersey (http://www.jordanonline06.com/) NBA jersey for toddler (http://www.jordanonline06.com/) old NBA jersey (http://www.jordanonline06.com/) youth NBA swingman jersey (http://www.jordanonline06.com/) NBA authentic basketball jersey (http://www.jordanonline06.com/) basketball jersey NBA new style (http://www.jordanonline06.com/) NBA all star game jersey (http://www.jordanonline06.com/) NBA new jersey (http://www.jordanonline06.com/) adidas NBA jersey (http://www.jordanonline06.com/) official NBA jersey (http://www.jordanonline06.com/) classics hardwood jersey NBA (http://www.jordanonline06.com/) old school NBA jersey (http://www.jordanonline06.com/) NBA jersey for woman (http://www.jordanonline06.com/) classic NBA jersey (http://www.jordanonline06.com/) NFL jersey korea supplier(http://www.jordanonline06.com/) mitchell and ness NBA jersey (http://www.jordanonline06.com/) 2009 game jersey NBA star (http://www.jordanonline06.com/) alternate jersey NBA (http://www.jordanonline06.com/) best selling NBA jersey (http://www.jordanonline06.com/) NBA jersey card (http://www.jordanonline06.com/) authenic NBA jersey (http://www.jordanonline06.com/) discount NBA jersey (http://www.jordanonline06.com/) Wholesale MLB jerseys,paypal,cheap MLB jersey(http:// www.jordanonline06.com/) wholesale football jerseys,(http://www.jordanonline06.com/) reebok MLB player jerseys,(http://www.jordanonline06.com/) authentic MLB jerseys,discount MLB jerseys,mitchell ness jerseys,throwback (http:// www.jordanonline06.com/) Nice jerseys,replica MLB jerseys,(http://www.jordanonline06.com/) women MLB jerseys,youth MLB (http://www.jordanonline06.com/) jerseys,official MLB jerseys,(http://www.jordanonline06.com/) pro Bowl jerseys,super bowl jerseys,(http://www.jordanonline06.com/) nhljerseys,hockey jerseys,nba jerseys,(http:// www.jordanonline06.com/) all star jersey,mlb baseball jerseys (http://www.jordanonline06.com/) (http://www.jordanonline06.com/) From prologic at shortcircuit.net.au Mon May 10 05:35:05 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 10 May 2010 19:35:05 +1000 Subject: Extract all words that begin with x In-Reply-To: References: Message-ID: On Mon, May 10, 2010 at 6:50 PM, Xavier Ho wrote: > Have I missed something, or wouldn't this work just as well: > >>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas'] >>>> [word for word in list_of_strings if word[0] == 'a'] > ['awes', 'asdgas'] I would do this for completeness (just in case): >>>> [word for word in list_of_strings if word and word[0] == 'a'] Just guards against empty strings which may or may not be in the list. --James From utente at esempio.net Mon May 10 05:41:08 2010 From: utente at esempio.net (superpollo) Date: Mon, 10 May 2010 11:41:08 +0200 Subject: Extract all words that begin with x In-Reply-To: <4be7cddf$0$1105$4fafbaef@reader4.news.tin.it> References: <4be7cddf$0$1105$4fafbaef@reader4.news.tin.it> Message-ID: <4be7d4b5$0$1106$4fafbaef@reader4.news.tin.it> superpollo ha scritto: > Jimbo ha scritto: >> Hello >> >> I am trying to find if there is a string OR list function that will >> search a list of strings for all the strings that start with 'a' & >> return a new list containing all the strings that started with 'a'. >> >> I have had a search of Python site & I could not find what I am >> looking for, does a function like this exist? > > >>> sw = lambda s: lambda t: t.startswith(s) > >>> list = ["a string","another one","this is a string","and so is this > one"] > >>> filter(sw("a"),list) > ['a string', 'another one', 'and so is this one'] > >>> > > bye of course there is a simpler way: >>> [string for string in list if string.startswith("a")] ['a string', 'another one', 'and so is this one'] >>> bye From jeanmichel at sequans.com Mon May 10 05:50:59 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 11:50:59 +0200 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: <36BDE98F-BE47-431D-971E-732B6A9B2289@ucsd.edu> References: <36BDE98F-BE47-431D-971E-732B6A9B2289@ucsd.edu> Message-ID: <4BE7D703.7050100@sequans.com> Ben Cohen wrote: > Apologies for the TABs -- I wrote that example for demonstration purposes in my mail client -- I'll copy and paste from a real code editor in the future. > Ben > There's nothing to apologies for. Be wary of those trying to get you out of the right path, they will lie to you stating python does not support Tabs while it surely does. Did you know that before generating bytecode, python replace all 4 spaces by a tabulations ? If that is not a proof that TABS is the all mighty indentation, I'm Mickey Mouse. Feel free to join our group for promoting TABS (monthly fee 50$). You an also purchase the book 'TABS Are Beautiful' (12 pages, 380$). JM From paul at boddie.org.uk Mon May 10 07:01:29 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 10 May 2010 04:01:29 -0700 (PDT) Subject: Picking a license References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> Message-ID: <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> On 10 Mai, 03:09, Patrick Maupin wrote: > On May 9, 6:39?pm, Paul Boddie wrote: > > but if they aren't pitching it directly at you, why would you believe > > that they are trying to change your behaviour? > > Because I've seen people specifically state that their purpose in > GPLing small libraries is to encourage other people to change their > behavior. ?I take those statements at face value. ?Certainly RMS > carefully lays out that the LGPL should be used sparingly in his "Why > you shouldn't use the Lesser GPL for your next library" post. ?(Hint: > he's not suggesting a permissive license instead.) Sure, but all he's asking you to do is to make the software available under a GPL-compatible licence. [...] > rst2pdf was licensed under the MIT license before I started > contributing to it, and there is no way I was going to even consider > adding patches for a GPLed package (which would certainly have to be > GPLed) into the rst2pdf repository. ?(Say what you will about how > sometimes differently licensed code can be combined, but RMS has to > share quite a bit of the blame/credit for the whole combining licenses > FUD.) I think the FSF are quite clear about combining licences - they even go to the trouble of telling you which ones are compatible with the GPL - so I don't see where "FUD" comes into it, apart from possible corner cases where people are trying to circumvent the terms of a licence and probably know themselves that what they're trying to do is at the very least against the spirit of the licence. Even then, warning people about their little project to make proprietary plugins, or whatever, is not really "FUD". As for rst2pdf, what your modifications would mean is that the software would need to be redistributed under a GPL-compatible licence. I'll accept that this does affect what people can then do with the project, but once again, you've mentioned at least one LGPL- licensed project which was previously in this very situation, and it was never actually GPL-licensed itself. Here's the relevant FAQ entry: http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL [...] > This is exactly the same situation that Carl was describing, only with > two different open source packages rather than with a proprietary > package and a GPL package. ?The whole reason people use words like > "force" and "viral" with the GPL is that this issue would not have > come up if svglib were MIT and rst2pdf were GPL. ?(Note that the LGPL > forces you to give back changes, but not in a way that makes it > incompatible with software under other licenses. ?That's why you see > very few complaints about the LGPL.) Actually, the copyleft licences don't "force" anyone to "give back changes": they oblige people to pass on changes. [...] > But I have definitely seen cases where people are offering something > that is not of nearly as much value as they seem to think it is, where > one of the goals is obviously to try to spread the GPL. Well, even the FSF doesn't approve of trivial projects using the GPL: http://www.gnu.org/licenses/gpl-faq.html#WhatIfWorkIsShort Paul From jeanmichel at sequans.com Mon May 10 07:14:47 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 13:14:47 +0200 Subject: accessing superclass methods from subclass In-Reply-To: References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: <4BE7EAA7.1030103@sequans.com> ben wrote: > Ok, thanks for the info. > > What would be a better way to do this? What I'm trying to do is treat > things in a reasonable OOP manner (all fairly new to me, esp. in > Python). Here's a made-up example with a little more context. Let's > say you're making a drawing program that can draw various shapes. So > in the interest of not repeating oneself, I want a class Shape that > handles everything that shapes have, such as a color, and a location. > Then I can subclass Shape to create Square, which has code specific to > drawing a square (e.g. 4 equal sides). So, like this: > > class Shape: > > x = 0 > y = 0 > > def setColor(self,color): > self.color = color > > def setLocation(self,x,y): > self.x = x > self.y = y > > def getLocation(self): > return [self.x,self.y] > > class Square(Shape): > > size = 0 > > def __init__(self,size): > self.size = size > > def draw(self): > location = getLocation() > # code to draw shape from location[0],location[1] at size size > # etc... > > It seems to me that you would want the location code handled in the > Shape class so that I'm not rewriting it for Circle, Triangle, etc., > but I'm not allowed to call any of those methods from the subclass. I > must be thinking of this in the wrong way. Help? > > thanks! > > > > Hi Ben, Please do not top post. You already been given good advices, especially the one suggesting to go through the tutorial. You're making basic mistakes here. Here is a very simple version of your code. class Shape: def __init__(self, x=0, y=0): self.x = 0 self.y = 0 self.color = None def draw(self): print 'drawing %s' % self class Square(Shape): def __init__(self,size): self.size = size def draw(self): Shape.draw(self) # this is one way to call the base class method location = (self.x, self.y) # code to draw shape from self.x, self.y at size self.size # etc... mySquare = Square(5,2) mySquare.color = 'red' print mySquare.x >>> 5 Since your attributes are flagged as public, you don't really need setters & getters. JM From jeanmichel at sequans.com Mon May 10 07:30:00 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 13:30:00 +0200 Subject: Kindly show me a better way to do it In-Reply-To: <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> Message-ID: <4BE7EE38.5040100@sequans.com> Oltmans wrote: > On May 9, 1:53 am, superpollo wrote: > > >> add = lambda a,b: a+b >> for i in reduce(add,a): >> print i >> > > This is very neat. Thank you. Sounds like magic to me. Can you please > explain how does that work? Many thanks again. > > shorter <> nicer IMO. Those alternatives are interesting from a tech point of view, but nothing can beat the purity of a vintage 'for' loop with *meaningful names*. salads = [['apple', 'banana'], ['apple', 'lemon', 'kiwi']] ingredients = [] for salad in salads: for fruit in salad: ingredients.append(fruit) print 'Remember to buy %s' % ingredients Lame & effective (1st adjective is irrelevant outside a geek contest) JM From luke.leighton at googlemail.com Mon May 10 07:35:43 2010 From: luke.leighton at googlemail.com (lkcl) Date: Mon, 10 May 2010 04:35:43 -0700 (PDT) Subject: Python is cool!! References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> Message-ID: On Mar 23, 4:55?pm, Jose Manuel wrote: > I have been learning Python, and it is amazing .... I am using the > tutorial that comes with the official distribution. > > At the end my goal is to develop applied mathematic in engineering > applications to be published on the Web, specially on app. oriented to > simulations and control systems, I was about to start learning Java > but I found Python which seems easier to learn that Java. > > Would it be easy to integrate Python in Web pages with HTML? I have > read many info on Internet saying it is, and I hope so .... jose, hi, perhaps it should be pointed out that there are four completely different types of answers, as outlined here: http://www.advogato.org/article/993.html python can be involved in absolutely every single one of those four separate types of answers. you should ideally read that article to determine which of the four approaches is most appropriate for you, and let people here know; and then people here will be able to respond accordingly and advise you accurately and with less time spent on their part, in guessing what it is that you want to do. l. From space.ship.traveller at gmail.com Mon May 10 08:24:22 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 11 May 2010 00:24:22 +1200 Subject: Is Python a functional programming language? Message-ID: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> Dear Friends, Is Python a functional programming language? Is this a paradigm that is well supported by both the language syntax and the general programming APIs? I heard that lambdas were limited to a single expression, and that other functional features were slated for removal in Python 3... is this the case or have I been misinformed? Finally, even if Python supports functional features, is this a model that is used often in client/application code? Kind regards, Samuel From jayeola at gmail.com Mon May 10 08:38:49 2010 From: jayeola at gmail.com (John Maclean) Date: Mon, 10 May 2010 13:38:49 +0100 Subject: unittest not being run Message-ID: <4BE7FE59.408@gmail.com> hi, can some one explain why the __first__ test is not being run? #!/usr/bin/env python import unittest # {{{ class T1TestCase(unittest.TestCase): def setUp(self): pass # can we use global variables here? def tearDown(self): pass # garbage collection def test_T1(self): '''this test aint loading''' self.assertEquals(1, 0) def test_T2(self): ## test method names begin 'test*' self.assertEquals((1 + 2), 3) self.assertEquals(0 + 1, 1) def test_T3(self): self.assertEquals((0 * 10), 0) self.assertEquals((5 * 8), 40) # the output is better. prints each test and ok or fail suite = unittest.TestLoader().loadTestsFromTestCase(T1TestCase) unittest.TextTestRunner(verbosity=2).run(suite) # }}} ''' halp! the first test ain't loading... python blaht.py test_T2 (__main__.T1TestCase) ... ok test_T3 (__main__.T1TestCase) ... ok ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK ''' From paul at boddie.org.uk Mon May 10 08:39:57 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 10 May 2010 05:39:57 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> <99386b28-1636-4f81-beec-3756970d37e8@11g2000prv.googlegroups.com> Message-ID: <1e93ddfd-ea89-4062-bc46-ba3db0b4f359@d39g2000yqa.googlegroups.com> On 10 Mai, 08:31, Carl Banks wrote: > On May 9, 10:08?am, Paul Boddie wrote: > > Oh sure: the GPL hurts everyone, like all the companies who have made > > quite a lot of money out of effectively making Linux the new > > enterprise successor to Unix, plus all the companies and individuals > > who have taken the sources and rolled their own distributions. > > Relative to what they could have done with a more permissive license? Well, yes. Some people would have it that the only reason why BSD variants never became as popular as Linux (or rather, GNU/Linux, but lets keep this focused) is because the litigation around the BSD code base "scared people away". Yet I remember rather well back in the mid-1990s when people using the same proprietary-and-doomed platform as myself started looking into Unix-flavoured operating systems, and a group of people deliberately chose NetBSD because of the favourable licensing conditions and because there was a portability headstart over Linux, which at the time people seriously believed was rather non- portable. So, that "scary AT&T" myth can be sunk, at least when considering its impact on what people were doing in 1994. Although the NetBSD port in question lives on, and maybe the people responsible all took jobs in large companies, its success on that platform and its derivatives has been dwarfed by that of the corresponding Linux port. > Yes. ?GPL hurts everyone relative to licenses that don't drive wedges > and prevent interoperability between software. I can think of another case, actually connected to the above proprietary platform and its practitioners, where software licensing stood in the way of "just getting on with business" which is what you seem to be advocating: a company released their application under the GPL, except for one critical library which remained proprietary software. Now, although you can argue that everyone's life would be richer had the GPL not prohibited "interoperability" (although I imagine that the application's licensing actually employed an exception to glue everything together in that particular case), a community never formed because people probably assumed that their role would only ever be about tidying up someone else's code so that the original authors could profit from it. All the GPL is designed to do in such cases is to encourage people to seek control (in terms of the "four freedoms") of all the technology, rather than be placated by the occasional airdrop of proprietary software and to be convinced never to explore the possibility of developing something similar for themselves. The beneficiary of the refusal to work on the above application was the GPL-licensed Inkscape, which might not be as well-liked by many people, but it does demonstrate, firstly, that permissive licences do not have the monopoly on encouraging people to work on stuff, and secondly, that actually going and improving something else is the answer if you don't like the licensing of something. > You might argue that GPL is sometimes better than proprietary closed > source, and I won't disagree, but it's nearly always worse than other > open source licenses. For me, I would argue that the GPL is always better than "proprietary closed source", recalling that the consideration is that of licensing and not mixing in other concerns like whether a particular program is technically better. In ensuring that an end-user gets some code and can break out those "four freedoms" on it, it is clearly not "worse than other open source licenses", and I don't accept that this is some rare thing that only happens outside a theoretical setting on an occasional basis. > > P.S. And the GPL isn't meant to further the cause of open source: it's > > meant to further the Free Software cause, which is not at all the same > > thing. > > It doesn't matter what the GPL "meant" to do, it matters what it does, > which is hurt everyone (relative to almost all other licenses). This is your opinion, not objectively established fact. > > Before you ridicule other people's positions, at least get your > > terminology right. > > I don't agree with FSF's defintion of free software and refuse to > abide by it. ?GPL isn't free software; any software that tells me I > can't compile it in with a closed source API isn't free. ?Period. Well, if you can't (or can't be bothered) to distinguish between what is known as Free Software and "open source", then I'm hardly surprised that you take offence at people releasing software for one set of reasons while you only consider another set of reasons to be valid ones. Throughout this discussion I've been accused of not being able to put myself in the position of the other side, but I completely understand that people just want as much publicly available software as possible to be permissively licensed, frequently for the reason that it will "grease the wheels of commerce", that it reduces (but, contrary to popular belief, does *not* eliminate) the amount of thought required when combining works, and that "the boss" or "the company lawyers" feel more comfortable with permissive licences, perhaps because they are scared about what might happen to their patent portfolio or something (in which case they might want to re- read some of those licences). It isn't news to me that some people emphasise developer "freedoms" and others emphasise user "freedoms", and frequently advocates of the former can only consider unrestricted personal gratification as "freedom". But to argue for the latter, I don't need to argue about how some style of licence is "better" according to some hastily arranged and fragile criteria: it's clear what the goal of copyleft licensing is; take it or leave it. There's no real disinformation campaign or "propaganda"; the FSF aren't "forcing" people to do anything, in contrast to various proprietary software licences and the way that most people are more obviously "forced" to buy a Microsoft product when they buy a computer (and be told that there's no refund, that it's "part of the product", contrary to what the EULA actually says for obvious regulatory reasons). So, given an acknowledgement of the motivation for copyleft licensing, the argument for applying it practically makes itself. I don't need to bring terminology like "holy war" or references to Bin Laden to make my case. I wonder, then, why people feel the need to do just that. Paul From werner.bruhin at free.fr Mon May 10 08:42:35 2010 From: werner.bruhin at free.fr (Werner F. Bruhin) Date: Mon, 10 May 2010 14:42:35 +0200 Subject: Upgrade Python 2.6.4 to 2.6.5 Message-ID: <4BE7FF3B.7030101@free.fr> Just upgraded on my Windows 7 machine my copy of 2.6.4 to 2.6.5. However doing sys.version still shows 2.6.4 even so python.exe is dated 19. March 2010 with a size of 26.624 bytes. Is this a known issue? Or did I do something wrong? If I install to a new folder all is well, but I would have to install all my other stuff again (kinterbasdb, matplotlib, sphinx etc etc). Werner From goon12 at gmail.com Mon May 10 08:44:44 2010 From: goon12 at gmail.com (Joe Riopel) Date: Mon, 10 May 2010 08:44:44 -0400 Subject: unittest not being run In-Reply-To: <4BE7FE59.408@gmail.com> References: <4BE7FE59.408@gmail.com> Message-ID: On Mon, May 10, 2010 at 8:38 AM, John Maclean wrote: > hi, > > can some one explain why the __first__ test is not being run? It looks like you defined test_T1 inside of the tearDown method. From stefan_ml at behnel.de Mon May 10 08:52:51 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 May 2010 14:52:51 +0200 Subject: Is Python a functional programming language? In-Reply-To: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> Message-ID: Samuel Williams, 10.05.2010 14:24: > Is Python a functional programming language? No. Python is a multi-paradigm language. But it does have functions (and methods) as first-class objects. > Is this a paradigm that is well supported by both the language syntax > and the general programming APIs? I'd say so, but it certainly depends on what functional language features you desire. > I heard that lambdas were limited to a single expression ... which is a good thing. An expression in Python can do pretty complex things already. Not allowing more puts a limit to code readability degradation. > and that other > functional features were slated for removal in Python 3... is this the > case or have I been misinformed? No such functionality has been removed in Py3, and in fact, several core language features were adapted to make functional programming easier and more efficient. > Finally, even if Python supports functional features, is this a model > that is used often in client/application code? From my point of view, yes. But the beauty is that Python is multi-paradigm, so you're not restricted to functional language features. Stefan From bruno.42.desthuilliers at websiteburo.invalid Mon May 10 09:11:13 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 10 May 2010 15:11:13 +0200 Subject: Is Python a functional programming language? In-Reply-To: References: Message-ID: <4be805f0$0$12228$426a34cc@news.free.fr> Samuel Williams a ?crit : > Dear Friends, > > Is Python a functional programming language? Depends on your definition of "functional programming language", but well, not really. It's mostly an imperative, object-oriented (but not pure-object) language. It has some restricted support for some functional idioms but trying to use it a true FPL would be a waste of time (both developper's and computer's). > Is this a paradigm that is well supported by both the language syntax and the general programming APIs? No. > I heard that lambdas were limited to a single expression, True. > and that other functional features were slated for removal in Python 3... False. Some FP-inspired functions and types are moving from builtins to a dedicated module, but they are still available. > is this the case or have I been misinformed? > > Finally, even if Python supports functional features, is this a model that is used often in client/application code? Once again, depends on your definitions of what's "functional". Some FP-inspired idioms and features are definitly idiomatic, but that doesn't make for true functional programming. Once again, trying to do pure FP in Python would be fighting against the language. From jim.vickroy at noaa.gov Mon May 10 09:30:32 2010 From: jim.vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 07:30:32 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: <4BE80A78.2030502@noaa.gov> Stefan Behnel wrote: > j vickroy, 07.05.2010 20:44: >> I apologize if this is not the appropriate forum for a question about >> Hudson (http://hudson-ci.org/), but I did not know where else to ask and >> my web searches have not been fruitful. > > Certainly nice to read something about Hudson in this forum, which is > rare enough. It's seriously the greatest CI tool I've ever used, and it > works great with Python apps. > > >> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >> >> in the *Execute Python Script* subsection. > > The problem is that this isn't a "Python Script". I's a an executable, > native program. Use the "execute shell" build step instead. > > Stefan > Thanks for your reply, Stefan. When the above command "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" is moved to the "Execute shell" section of the job configuration page along with the following "tracer" command: #!python.exe print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' their is still no indication the unit tests are run. Here is the output from the Hudson Console Output page ------------------------------------------------------------------- Started by user anonymous Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 At revision 3401 no change for svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build [workspace] $ python.exe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2011616575490005324.sh FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO [workspace] $ cmd.exe -xe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson902246697107326581.sh Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace>Recording test results Test reports were found but none of them are new. Did tests run? For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml is 2 days 19 hr old Finished: FAILURE ------------------------------------------------------------------- As a side note, my Hudson "global" configuration page contains: cmd.exe in the "Shell executable" section and NOSEDIR C:\Python26\Scripts in the "Global properties" section. -- jv From Jim.Vickroy at noaa.gov Mon May 10 09:30:32 2010 From: Jim.Vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 07:30:32 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: <4BE80A78.2030502@noaa.gov> Stefan Behnel wrote: > j vickroy, 07.05.2010 20:44: >> I apologize if this is not the appropriate forum for a question about >> Hudson (http://hudson-ci.org/), but I did not know where else to ask and >> my web searches have not been fruitful. > > Certainly nice to read something about Hudson in this forum, which is > rare enough. It's seriously the greatest CI tool I've ever used, and it > works great with Python apps. > > >> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >> >> in the *Execute Python Script* subsection. > > The problem is that this isn't a "Python Script". I's a an executable, > native program. Use the "execute shell" build step instead. > > Stefan > Thanks for your reply, Stefan. When the above command "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" is moved to the "Execute shell" section of the job configuration page along with the following "tracer" command: #!python.exe print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' their is still no indication the unit tests are run. Here is the output from the Hudson Console Output page ------------------------------------------------------------------- Started by user anonymous Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 At revision 3401 no change for svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build [workspace] $ python.exe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2011616575490005324.sh FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO [workspace] $ cmd.exe -xe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson902246697107326581.sh Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace>Recording test results Test reports were found but none of them are new. Did tests run? For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml is 2 days 19 hr old Finished: FAILURE ------------------------------------------------------------------- As a side note, my Hudson "global" configuration page contains: cmd.exe in the "Shell executable" section and NOSEDIR C:\Python26\Scripts in the "Global properties" section. -- jv From jim.vickroy at noaa.gov Mon May 10 09:31:57 2010 From: jim.vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 07:31:57 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: <4BE80ACD.8080805@noaa.gov> Jean-Michel Pichavant wrote: > Stefan Behnel wrote: >> j vickroy, 07.05.2010 20:44: >>> I apologize if this is not the appropriate forum for a question about >>> Hudson (http://hudson-ci.org/), but I did not know where else to ask and >>> my web searches have not been fruitful. >> >> Certainly nice to read something about Hudson in this forum, which is >> rare enough. It's seriously the greatest CI tool I've ever used, and >> it works great with Python apps. >> > We use it, but this is a python list that's why there's few topics about > it. :) > Speaking for myself, I use it to execute the linter (pylint) on the > code and run unitary tests. Great tool for sure. > > JM > Is there a more appropriate forum to ass about Python and Hudson? -- jv From Jim.Vickroy at noaa.gov Mon May 10 09:31:57 2010 From: Jim.Vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 07:31:57 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: <4BE80ACD.8080805@noaa.gov> Jean-Michel Pichavant wrote: > Stefan Behnel wrote: >> j vickroy, 07.05.2010 20:44: >>> I apologize if this is not the appropriate forum for a question about >>> Hudson (http://hudson-ci.org/), but I did not know where else to ask and >>> my web searches have not been fruitful. >> >> Certainly nice to read something about Hudson in this forum, which is >> rare enough. It's seriously the greatest CI tool I've ever used, and >> it works great with Python apps. >> > We use it, but this is a python list that's why there's few topics about > it. :) > Speaking for myself, I use it to execute the linter (pylint) on the > code and run unitary tests. Great tool for sure. > > JM > Is there a more appropriate forum to ass about Python and Hudson? -- jv From jcd at sdf.lonestar.org Mon May 10 09:38:44 2010 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 10 May 2010 09:38:44 -0400 Subject: unittest not being run In-Reply-To: <4BE7FE59.408@gmail.com> References: <4BE7FE59.408@gmail.com> Message-ID: <1273498724.2997.3.camel@cliff-laptop> My guess is you mixed tabs and spaces. One tab is always treated by the python interpreter as being equal to eight spaces, which is two indentation levels in your code. Though if it were exactly as you show it, you'd be getting a syntax error, because even there, it looks like the indentation of your `def test_T1(self):` line is off by one column, relative to pass, and by three columns relative to the other methods. Cheers, Cliff On Mon, 2010-05-10 at 13:38 +0100, John Maclean wrote: > hi, > > can some one explain why the __first__ test is not being run? > > #!/usr/bin/env python > import unittest # {{{ > class T1TestCase(unittest.TestCase): > > def setUp(self): > pass # can we use global variables here? > > def tearDown(self): > pass # garbage collection > > def test_T1(self): > '''this test aint loading''' > self.assertEquals(1, 0) > > def test_T2(self): ## test method names begin 'test*' > self.assertEquals((1 + 2), 3) > self.assertEquals(0 + 1, 1) > > def test_T3(self): > self.assertEquals((0 * 10), 0) > self.assertEquals((5 * 8), 40) > > # the output is better. prints each test and ok or fail > suite = unittest.TestLoader().loadTestsFromTestCase(T1TestCase) > unittest.TextTestRunner(verbosity=2).run(suite) # }}} > > > ''' halp! > > the first test ain't loading... > > python blaht.py > test_T2 (__main__.T1TestCase) ... ok > test_T3 (__main__.T1TestCase) ... ok > > ---------------------------------------------------------------------- > Ran 2 tests in 0.000s > > OK > > ''' From kaklis at gmail.com Mon May 10 10:00:54 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Mon, 10 May 2010 07:00:54 -0700 (PDT) Subject: HTTP Post Request Message-ID: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> Hi to all, i want to ask you a question, concerning the best way to do the following as a POST request: There is server-servlet that accepts xml commands It had the following HTTP request headers: Host: somehost.com User-Agent: Jakarta Commons-HttpClient Content-Type: text/xml Content-Length: 415 and the following request body (reformatted here for clarity): search How can i send the above to the Listener Servlet? Thanks in advance From googler.1.webmaster at spamgourmet.com Mon May 10 10:06:48 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Mon, 10 May 2010 07:06:48 -0700 (PDT) Subject: INCREF DECREF manually Message-ID: <6033c45c-1eb7-45c7-9cb8-9597cd5e0e8d@o14g2000yqb.googlegroups.com> Hi, just a small question. Is it possible to change the refcount of a reference manually? For debugging / ... Thanks! moerchendiser2k3 From jeanmichel at sequans.com Mon May 10 10:14:19 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 16:14:19 +0200 Subject: INCREF DECREF manually In-Reply-To: <6033c45c-1eb7-45c7-9cb8-9597cd5e0e8d@o14g2000yqb.googlegroups.com> References: <6033c45c-1eb7-45c7-9cb8-9597cd5e0e8d@o14g2000yqb.googlegroups.com> Message-ID: <4BE814BB.9020106@sequans.com> moerchendiser2k3 wrote: > Hi, > > just a small question. Is it possible to change the refcount of a > reference manually? For debugging / ... > > Thanks! > > moerchendiser2k3 > Why don't you just create a global reference to the object ? Unless this one is removed, the object will be kept in memory. JM From jayeola at gmail.com Mon May 10 10:21:26 2010 From: jayeola at gmail.com (John Maclean) Date: Mon, 10 May 2010 15:21:26 +0100 Subject: unittest not being run In-Reply-To: <1273498724.2997.3.camel@cliff-laptop> References: <4BE7FE59.408@gmail.com> <1273498724.2997.3.camel@cliff-laptop> Message-ID: <4BE81666.80301@gmail.com> On 10/05/2010 14:38, J. Cliff Dyer wrote: > My guess is you mixed tabs and spaces. One tab is always treated by the > python interpreter as being equal to eight spaces, which is two > indentation levels in your code. > > Though if it were exactly as you show it, you'd be getting a syntax > error, because even there, it looks like the indentation of your `def > test_T1(self):` line is off by one column, relative to pass, and by > three columns relative to the other methods. > > Cheers, > Cliff 'twas a spaces/indent issue. thanks! From kushal.kumaran+python at gmail.com Mon May 10 10:22:53 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Mon, 10 May 2010 19:52:53 +0530 Subject: HTTP Post Request In-Reply-To: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> Message-ID: On Mon, May 10, 2010 at 7:30 PM, kaklis at gmail.com wrote: > Hi to all, i want to ask you a question, concerning the best way to do > the following as a POST request: > There is server-servlet that accepts xml commands > It had the following HTTP request headers: > > ? ? ? ? ? ?Host: somehost.com > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient > ? ? ? ? ? ?Content-Type: text/xml > ? ? ? ? ? ?Content-Length: 415 > > and the following request body (reformatted here for clarity): > > ? ? ? ? ? ? > ? ? ? ? ? ? > ? ? ? ? ? ? ?search > ? ? ? ? ? ? > How can i send the above to the Listener Servlet? > Thanks in advance Use the xmlrpclib module. -- regards, kushal From jeanmichel at sequans.com Mon May 10 10:26:13 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 16:26:13 +0200 Subject: unable to get Hudson to run unit tests In-Reply-To: <4BE80A78.2030502@noaa.gov> References: <4BE80A78.2030502@noaa.gov> Message-ID: <4BE81785.8090402@sequans.com> j vickroy wrote: > Stefan Behnel wrote: >> j vickroy, 07.05.2010 20:44: >>> I apologize if this is not the appropriate forum for a question about >>> Hudson (http://hudson-ci.org/), but I did not know where else to ask >>> and >>> my web searches have not been fruitful. >> >> Certainly nice to read something about Hudson in this forum, which is >> rare enough. It's seriously the greatest CI tool I've ever used, and >> it works great with Python apps. >> >> >>> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >>> >>> in the *Execute Python Script* subsection. >> >> The problem is that this isn't a "Python Script". I's a an >> executable, native program. Use the "execute shell" build step instead. >> >> Stefan >> > Thanks for your reply, Stefan. > > When the above command > > "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" > > is moved to the "Execute shell" section of the job configuration page > along with the following "tracer" command: > > #!python.exe > print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' > > their is still no indication the unit tests are run. > > Here is the output from the Hudson Console Output page > > ------------------------------------------------------------------- > Started by user anonymous > Updating svn://vm-svn/GOES data > processing/trunk/GOES/13,14,15/SXI/level-1 > At revision 3401 > no change for svn://vm-svn/GOES data > processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build > [workspace] $ python.exe > C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2011616575490005324.sh > FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO > [workspace] $ cmd.exe -xe > C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson902246697107326581.sh > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI > Level-1 Products Generation\workspace>Recording test results > Test reports were found but none of them are new. Did tests run? > For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES > 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml > is 2 days 19 hr old > > Finished: FAILURE > ------------------------------------------------------------------- > > As a side note, my Hudson "global" configuration page contains: > > cmd.exe > > in the "Shell executable" section and > > NOSEDIR > C:\Python26\Scripts > > in the "Global properties" section. > > -- jv Maybe something is missing on the machine hosting hudson, did you try to execute nosetests.exe on that machine ? I'm also confused with something, you do not provide nosetests with the location of your package, assuming the current directory contains that package (my guess). Instead of printing 'FOOO', try "import os ; print os.getcwd(); print os.listdir(os.getcwd())" to know where you are exactly and if this dir contains your python package. JM From googler.1.webmaster at spamgourmet.com Mon May 10 10:26:42 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Mon, 10 May 2010 07:26:42 -0700 (PDT) Subject: INCREF DECREF manually References: <6033c45c-1eb7-45c7-9cb8-9597cd5e0e8d@o14g2000yqb.googlegroups.com> Message-ID: Do to some debugging if a version contains a bug and needs to be fixed there manually. From kaklis at gmail.com Mon May 10 10:56:34 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Mon, 10 May 2010 07:56:34 -0700 (PDT) Subject: HTTP Post Request References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> Message-ID: <06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com> On May 10, 10:22?am, Kushal Kumaran wrote: > On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com wrote: > > Hi to all, i want to ask you a question, concerning the best way to do > > the following as a POST request: > > There is server-servlet that accepts xml commands > > It had the following HTTP request headers: > > > ? ? ? ? ? ?Host: somehost.com > > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient > > ? ? ? ? ? ?Content-Type: text/xml > > ? ? ? ? ? ?Content-Length: 415 > > > and the following request body (reformatted here for clarity): > > > ? ? ? ? ? ? > > ? ? ? ? ? ? > > ? ? ? ? ? ? ?search > > ? ? ? ? ? ? > > How can i send the above to the Listener Servlet? > > Thanks in advance > > Use the xmlrpclib module. > > -- > regards, > kushal OK, sending headers with xmlrpclib, but how do i send the XML message? Thanks A.K. From pmaupin at gmail.com Mon May 10 11:01:55 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Mon, 10 May 2010 08:01:55 -0700 (PDT) Subject: Picking a license References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> Message-ID: On May 10, 6:01?am, Paul Boddie wrote: > On 10 Mai, 03:09, Patrick Maupin wrote: > > > On May 9, 6:39?pm, Paul Boddie wrote: > > > but if they aren't pitching it directly at you, why would you believe > > > that they are trying to change your behaviour? > > > Because I've seen people specifically state that their purpose in > > GPLing small libraries is to encourage other people to change their > > behavior. ?I take those statements at face value. ?Certainly RMS > > carefully lays out that the LGPL should be used sparingly in his "Why > > you shouldn't use the Lesser GPL for your next library" post. ?(Hint: > > he's not suggesting a permissive license instead.) > > Sure, but all he's asking you to do is to make the software available > under a GPL-compatible licence. I'll be charitable and assume the fact that you can make that statement without apparent guile merely means that you haven't read the post I was referring to: http://www.gnu.org/philosophy/why-not-lgpl.html > [...] > > > rst2pdf was licensed under the MIT license before I started > > contributing to it, and there is no way I was going to even consider > > adding patches for a GPLed package (which would certainly have to be > > GPLed) into the rst2pdf repository. ?(Say what you will about how > > sometimes differently licensed code can be combined, but RMS has to > > share quite a bit of the blame/credit for the whole combining licenses > > FUD.) > > I think the FSF are quite clear about combining licences - they even > go to the trouble of telling you which ones are compatible with the > GPL Yes, but one of the things they are quite clear on is that the overall work must be licensed as GPL, if any of the components are licensed as GPL. They claim this is true, even if a non-GPL work dynamically links to a GPL work. - so I don't see where "FUD" comes into it, apart from possible > corner cases where people are trying to circumvent the terms of a > licence and probably know themselves that what they're trying to do is > at the very least against the spirit of the licence. Legally, I don't think they can dictate the license terms of, e.g. clisp just because it can link to readline. But practically, they DID manage to do this, simply because Bruno Haible, the clisp author, was more concerned about writing software than spending too much time sparring with Stallman over the license, so he finally licensed clisp under the gpl. clisp *could* use readline, but didn't require it; nonetheless Stallman argued that clisp was a "derivative" of readline. That case of the tail wagging the dog would be laughable if it hadn't worked. In any case, Stallman's success at that tactic is probably one of the things that led him to write the paper on why you should use GPL for your library. (As an aside, since rst2pdf *can* use GPL-licensed svglib, it could possibly be subject to the same kind of political pressure as clisp. But the fact that more people are better informed now and that the internet would publicize the dispute more widely more quickly means that this is a battle Stallman is unlikely to wage at this point, because if the leader of any such targeted project has enough cojones, the FSF's inevitable loss would reduce some of the FUD dramatically.) > Even then, > warning people about their little project to make proprietary plugins, > or whatever, is not really "FUD". I think that, legally, they probably don't have a leg to stand on for some of their overarching claims (e.g. about shipping proprietary software that could link to readline, without even shipping readline). But morally -- well, they've made their position reasonably clear and I try to abide by it. That still doesn't make it "not really FUD." I'd call this sort of badgering "copyright misuse" myself. > As for rst2pdf, what your modifications would mean is that the > software would need to be redistributed under a GPL-compatible > licence. That's parsing semantics rather finely. In practice, what it really means is that the combination (e.g. the whole program) would effectively be GPL-licensed. This then means that downstream users would have to double-check that they are not combining the whole work with licenses which are GPL-incompatible, even if they are not using the svg feature. Hence, the term "viral." > I'll accept that this does affect what people can then do > with the project, but once again, you've mentioned at least one LGPL- > licensed project which was previously in this very situation, and it > was never actually GPL-licensed itself. Here's the relevant FAQ entry: > > http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL Yes, I've read that, but this is much more informative: http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystem "A system incorporating a GPL-covered program is an extended version of that program. The GPL says that any extended version of the program must be released under the GPL if it is released at all." This makes it clear that the overall work must be GPLed. Now, all of a sudden, downstream users cannot do some things they could have done before. Can you not see that taking a preexisting MIT-licensed project and adding code to make it GPL could negatively affect some of its users and that that is not necessarily an unalloyed good? > [...] > > > This is exactly the same situation that Carl was describing, only with > > two different open source packages rather than with a proprietary > > package and a GPL package. ?The whole reason people use words like > > "force" and "viral" with the GPL is that this issue would not have > > come up if svglib were MIT and rst2pdf were GPL. ?(Note that the LGPL > > forces you to give back changes, but not in a way that makes it > > incompatible with software under other licenses. ?That's why you see > > very few complaints about the LGPL.) > > Actually, the copyleft licences don't "force" anyone to "give back > changes": they oblige people to pass on changes. True, if pedantic. I meant "give back" in the more general sense. > [...] > > > But I have definitely seen cases where people are offering something > > that is not of nearly as much value as they seem to think it is, where > > one of the goals is obviously to try to spread the GPL. > > Well, even the FSF doesn't approve of trivial projects using the GPL: > > http://www.gnu.org/licenses/gpl-faq.html#WhatIfWorkIsShort Sure, that's a pragmatic view -- copyright might not even be permitted on something that short that is mainly functional. However, length is not the only arbiter of trivial. To stay with the same example, personally, I would consider readline "trivial" within the context of a lot of software which might use it, regardless of whether the readline implementation itself used all sorts of fancy neural net technology to predict what word the user was going to type or whatever. But whether it was trivial or not, if I ship software that *could* link to it but doesn't *require* it (like the case of clisp) without shipping readline, I think it's FUD and an attempt at copyright misuse to call my software a derivative work of readline. But obviously YMMV Regards, Pat From aahz at pythoncraft.com Mon May 10 11:06:24 2010 From: aahz at pythoncraft.com (Aahz) Date: 10 May 2010 08:06:24 -0700 Subject: Picking a license References: <30aff350- <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> Message-ID: In article <074b412a-c2f4-4090-a52c-4d69edb29a22 at d39g2000yqa.googlegroups.com>, Paul Boddie wrote: > >Actually, the copyleft licences don't "force" anyone to "give back >changes": they oblige people to pass on changes. IMO, that's a distinction without a difference, particularly if you define "give back" as referring to the community rather than the original project. With the FSF itself using "pressure" in the FAQ entry you linked to, I have no clue why you and Ben Finney object to my use of "force". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From zhangdongche001 at gmail.com Mon May 10 11:12:40 2010 From: zhangdongche001 at gmail.com (xiao wu) Date: Mon, 10 May 2010 08:12:40 -0700 (PDT) Subject: Wholesale Sports Shoes Clear Air Force One AAA++quality(www.cnnshoe.com) Message-ID: <8b973d50-0857-4257-8eee-52aea3ae04b9@z15g2000prh.googlegroups.com> supply sports shoes. The brand Sports shoes basketball shoes, Boot, walling shoes, Athletic shoes, Jogging shoes, running shoes, leather shoes, football, shoe sports shoe Footwear Sneaker, Shox Max Rift T- shirts, womens t-shirts, Clothing womens clothing, wear hats Caps Jersey jeans Sock Jacks, Watches, wallet, handbags, and Jeans Lady Clothing and so on. Please contact us by email to get more information. please kindly visite our website: http://www.cnnshoe.com msn: cnnshoe2009 at hotmail.com email: cnnshoe at gmail.com From solipsis at pitrou.net Mon May 10 11:17:07 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Mon, 10 May 2010 17:17:07 +0200 Subject: INCREF DECREF manually References: <6033c45c-1eb7-45c7-9cb8-9597cd5e0e8d@o14g2000yqb.googlegroups.com> Message-ID: <20100510171707.565ebb79@pitrou.net> On Mon, 10 May 2010 07:26:42 -0700 (PDT) moerchendiser2k3 wrote: > > Do to some debugging if a version contains a bug and needs to be fixed > there manually. This is certainly the wrong approach. To know if your Python code is leaking references, use either sys.getrefcount(), or (better) a weakref -- and don't forget to call gc.collect(). To know if some C extension is buggy, use your C debugger (or your favourite alternative debugging method, such as printf()). Changing reference counts from Python will lead to two possible consequences: - if you increment a reference count, you will have a permanent memory leak - if you decrement a reference count, you will eventually crash the interpreter From aahz at pythoncraft.com Mon May 10 11:21:14 2010 From: aahz at pythoncraft.com (Aahz) Date: 10 May 2010 08:21:14 -0700 Subject: Picking a license References: <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> <99386b28-1636-4f81-beec-3756970d37e8@11g2000prv.googlegroups.com> Message-ID: [we have previously been using "MIT-style" and "BSD-style" licensing in this thread for the most part -- given the poster who suggested that Apache makes more sense these days, I'm switching to that terminology] In article <99386b28-1636-4f81-beec-3756970d37e8 at 11g2000prv.googlegroups.com>, Carl Banks wrote: > >You might argue that GPL is sometimes better than proprietary closed >source, and I won't disagree, but it's nearly always worse than other >open source licenses. That I completely disagree with. I'm not going to bother making arguments (Paul Boddie et al has done a much better job than I could), but I wanted to register my disagreement as someone who generally prefers Apache-style licenses. I will just add that I believe that Apache-style licensing could not work in the absence of GPL software. IOW, I believe that GPL confers a form of herd immunity to Open Source in general, and Stallman gets full credit for creating the idea of GPL to protect Open Source. I believe that Stallman understands this perfectly well and it in part represents why he is so opposed to non-GPL licensing; it makes sense that he feels some resentment toward the "freeloading" from the rest of the Open Source community. OTOH, I also believe that having only GPL would destroy Open Source as a viable development environment and community; it's too restrictive for some very valuable projects (including Python in specific, to bring this back on topic). Each project needs to think carefully about its relationship to the Open Source ecosystem and community before deciding on a license. But for small projects trying to get users, defaulting to Apache makes sense. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From Jim.Vickroy at noaa.gov Mon May 10 11:39:14 2010 From: Jim.Vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 09:39:14 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: <4BE80A78.2030502@noaa.gov> Message-ID: <4BE828A2.2070106@noaa.gov> Jean-Michel Pichavant wrote: > j vickroy wrote: >> Stefan Behnel wrote: >>> j vickroy, 07.05.2010 20:44: >>>> I apologize if this is not the appropriate forum for a question about >>>> Hudson (http://hudson-ci.org/), but I did not know where else to ask >>>> and >>>> my web searches have not been fruitful. >>> >>> Certainly nice to read something about Hudson in this forum, which is >>> rare enough. It's seriously the greatest CI tool I've ever used, and >>> it works great with Python apps. >>> >>> >>>> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >>>> >>>> in the *Execute Python Script* subsection. >>> >>> The problem is that this isn't a "Python Script". I's a an >>> executable, native program. Use the "execute shell" build step instead. >>> >>> Stefan >>> >> Thanks for your reply, Stefan. >> >> When the above command >> >> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >> >> is moved to the "Execute shell" section of the job configuration page >> along with the following "tracer" command: >> >> #!python.exe >> print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' >> >> their is still no indication the unit tests are run. >> >> Here is the output from the Hudson Console Output page >> >> ------------------------------------------------------------------- >> Started by user anonymous >> Updating svn://vm-svn/GOES data >> processing/trunk/GOES/13,14,15/SXI/level-1 >> At revision 3401 >> no change for svn://vm-svn/GOES data >> processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build >> [workspace] $ python.exe >> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2011616575490005324.sh >> FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO >> [workspace] $ cmd.exe -xe >> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson902246697107326581.sh >> Microsoft Windows XP [Version 5.1.2600] >> (C) Copyright 1985-2001 Microsoft Corp. >> >> C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI >> Level-1 Products Generation\workspace>Recording test results >> Test reports were found but none of them are new. Did tests run? >> For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES >> 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml >> is 2 days 19 hr old >> >> Finished: FAILURE >> ------------------------------------------------------------------- >> >> As a side note, my Hudson "global" configuration page contains: >> >> cmd.exe >> >> in the "Shell executable" section and >> >> NOSEDIR >> C:\Python26\Scripts >> >> in the "Global properties" section. >> >> -- jv > Maybe something is missing on the machine hosting hudson, did you try to > execute nosetests.exe on that machine ? Hudson is running on my workstation (which also has python and nose installed). > I'm also confused with something, you do not provide nosetests with the > location of your package, assuming the current directory contains that > package (my guess). That is correct but see below ... > Instead of printing 'FOOO', try "import os ; print os.getcwd(); print > os.listdir(os.getcwd())" to know where you are exactly and if this dir > contains your python package. great suggestion ! This showed the current working directory to be one level above where I expected so that was definitely a problem so I changed my nose command, in the Hudson Job configuration Execute shell box, to be nosetests.exe --where=level-1 --with-xunit --verbose and saved the configuration change. This works as expected when run from a command shell in the Hudson current working directory for this Hudson job. Unfortunately, when "Hudson Build now" is performed, the Hudson Console output, for this job, is: ------------------------------------------------------------ Started by user anonymous Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 At revision 3403 no change for svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build [workspace] $ python.exe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson5273111667332806239.sh os.getcwd(): C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace os.listdir(os.getcwd()): ['level-1'] [workspace] $ cmd.exe -xe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson991194264891924641.sh Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace>Recording test results No test report files were found. Configuration error? Finished: FAILURE ------------------------------------------------------------ The second [workspace] section output (above) looks like cmd.exe is being executed with no parameters (i.e., without the "nosetests.exe --where=level-1 --with-xunit --verbose") parameter. Thanks for thinking about this; I realize how difficult it is to remotely troubleshoot a problem like this. -- jv > > JM > > From jim.vickroy at noaa.gov Mon May 10 11:39:14 2010 From: jim.vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 09:39:14 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: <4BE80A78.2030502@noaa.gov> Message-ID: <4BE828A2.2070106@noaa.gov> Jean-Michel Pichavant wrote: > j vickroy wrote: >> Stefan Behnel wrote: >>> j vickroy, 07.05.2010 20:44: >>>> I apologize if this is not the appropriate forum for a question about >>>> Hudson (http://hudson-ci.org/), but I did not know where else to ask >>>> and >>>> my web searches have not been fruitful. >>> >>> Certainly nice to read something about Hudson in this forum, which is >>> rare enough. It's seriously the greatest CI tool I've ever used, and >>> it works great with Python apps. >>> >>> >>>> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >>>> >>>> in the *Execute Python Script* subsection. >>> >>> The problem is that this isn't a "Python Script". I's a an >>> executable, native program. Use the "execute shell" build step instead. >>> >>> Stefan >>> >> Thanks for your reply, Stefan. >> >> When the above command >> >> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >> >> is moved to the "Execute shell" section of the job configuration page >> along with the following "tracer" command: >> >> #!python.exe >> print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' >> >> their is still no indication the unit tests are run. >> >> Here is the output from the Hudson Console Output page >> >> ------------------------------------------------------------------- >> Started by user anonymous >> Updating svn://vm-svn/GOES data >> processing/trunk/GOES/13,14,15/SXI/level-1 >> At revision 3401 >> no change for svn://vm-svn/GOES data >> processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build >> [workspace] $ python.exe >> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2011616575490005324.sh >> FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO >> [workspace] $ cmd.exe -xe >> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson902246697107326581.sh >> Microsoft Windows XP [Version 5.1.2600] >> (C) Copyright 1985-2001 Microsoft Corp. >> >> C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI >> Level-1 Products Generation\workspace>Recording test results >> Test reports were found but none of them are new. Did tests run? >> For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES >> 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml >> is 2 days 19 hr old >> >> Finished: FAILURE >> ------------------------------------------------------------------- >> >> As a side note, my Hudson "global" configuration page contains: >> >> cmd.exe >> >> in the "Shell executable" section and >> >> NOSEDIR >> C:\Python26\Scripts >> >> in the "Global properties" section. >> >> -- jv > Maybe something is missing on the machine hosting hudson, did you try to > execute nosetests.exe on that machine ? Hudson is running on my workstation (which also has python and nose installed). > I'm also confused with something, you do not provide nosetests with the > location of your package, assuming the current directory contains that > package (my guess). That is correct but see below ... > Instead of printing 'FOOO', try "import os ; print os.getcwd(); print > os.listdir(os.getcwd())" to know where you are exactly and if this dir > contains your python package. great suggestion ! This showed the current working directory to be one level above where I expected so that was definitely a problem so I changed my nose command, in the Hudson Job configuration Execute shell box, to be nosetests.exe --where=level-1 --with-xunit --verbose and saved the configuration change. This works as expected when run from a command shell in the Hudson current working directory for this Hudson job. Unfortunately, when "Hudson Build now" is performed, the Hudson Console output, for this job, is: ------------------------------------------------------------ Started by user anonymous Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 At revision 3403 no change for svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build [workspace] $ python.exe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson5273111667332806239.sh os.getcwd(): C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace os.listdir(os.getcwd()): ['level-1'] [workspace] $ cmd.exe -xe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson991194264891924641.sh Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace>Recording test results No test report files were found. Configuration error? Finished: FAILURE ------------------------------------------------------------ The second [workspace] section output (above) looks like cmd.exe is being executed with no parameters (i.e., without the "nosetests.exe --where=level-1 --with-xunit --verbose") parameter. Thanks for thinking about this; I realize how difficult it is to remotely troubleshoot a problem like this. -- jv > > JM > > From michele.simionato at gmail.com Mon May 10 11:53:48 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 10 May 2010 08:53:48 -0700 (PDT) Subject: Sphinx hosting References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> <1aeaac06-ff0e-4ec1-8f7d-fc71891228c0@b18g2000yqb.googlegroups.com> Message-ID: <7ec09351-f77a-4fa1-bb9e-13b0f01cf923@n15g2000yqf.googlegroups.com> On May 5, 8:00?am, James Mills wrote: > On Wed, May 5, 2010 at 3:35 PM, Michele Simionato > > wrote: > > I am sure it has, but I was talking about just putting in the > > repository an index.html file and have it published, the wayI hear ?it > > works in BitBucket and GitHub. > > I'm pretty sure Google Code Hosting doesn't support > rendering text/html mime-type files in the repository (like Trac can). At the end I discovered that if you put HTML files into a Googlecode repository and you click on "display raw file" it just works (TM). So my problem was already solved and I my worries were unjustified. I have just committed my talk at the Italian PyCon and all the stylesheets are recognized just fine: http://micheles.googlecode.com/hg/pypers/pycon10/talk.html From aahz at pythoncraft.com Mon May 10 12:48:21 2010 From: aahz at pythoncraft.com (Aahz) Date: 10 May 2010 09:48:21 -0700 Subject: Extract all words that begin with x References: Message-ID: In article , James Mills wrote: >On Mon, May 10, 2010 at 6:50 PM, Xavier Ho wrote: >> Have I missed something, or wouldn't this work just as well: >> >>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas'] >>>>> [word for word in list_of_strings if word[0] == 'a'] >> ['awes', 'asdgas'] > >I would do this for completeness (just in case): > >>>>> [word for word in list_of_strings if word and word[0] == 'a'] > >Just guards against empty strings which may or may not be in the list. No need to do that with startswith(): >>> ''.startswith('x') False You would only need to use your code if you suspected that some elements might be None. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From paul at boddie.org.uk Mon May 10 13:37:24 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 10 May 2010 10:37:24 -0700 (PDT) Subject: Picking a license References: <30aff350- <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> Message-ID: <9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com> On 10 Mai, 17:06, a... at pythoncraft.com (Aahz) wrote: > In article <074b412a-c2f4-4090-a52c-4d69edb29... at d39g2000yqa.googlegroups.com>, > Paul Boddie ? wrote: > >Actually, the copyleft licences don't "force" anyone to "give back > >changes": they oblige people to pass on changes. > > IMO, that's a distinction without a difference, particularly if you > define "give back" as referring to the community rather than the original > project. There is a difference: I know of at least one vendor of GPL-licensed solutions who received repeated requests that they make their sources available to all-comers, even though the only obligation is to those receiving the software in the first place. Yes, the code can then become public - if Red Hat decided to only release sources to their customers, and those customers shared the sources publicly, then CentOS would still be around as a Red Hat "clone" - but there are situations where recipients of GPL-licensed code may decide that it is in their best interests not to just upload it to the public Internet. > ?With the FSF itself using "pressure" in the FAQ entry you > linked to, I have no clue why you and Ben Finney object to my use of > "force". Because no-one is being forced to do anything. Claiming that "force" is involved is like hearing a schoolboy saying, "I really wanted that chocolate, but why is that man forcing me to pay for it?" Well, you only have to pay for it if you decide you want to take it - that's the only reasonable response. Paul From no.email at nospam.invalid Mon May 10 14:00:57 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 10 May 2010 11:00:57 -0700 Subject: Is Python a functional programming language? References: Message-ID: <7xvdavd4bq.fsf@ruckus.brouhaha.com> Samuel Williams writes: > Is Python a functional programming language? It supports some aspects of functional programming but I wouldn't go as far as to call it an FPL. > Is this a paradigm that is well supported by both the language syntax > and the general programming APIs? I'd say "somewhat supported" rather than "well supported". > I heard that lambdas were limited to a single expression, and that > other functional features were slated for removal in Python 3... is > this the case or have I been misinformed? I think, some features were slated for removal, but after some discussion they were moved to libraries instead of eliminated completely. > Finally, even if Python supports functional features, is this a model > that is used often in client/application code? That's more a question of the programmers than the programs. If you're comfortable programming in functional style, that will tend to show up in your python code. There are some contortions you have to do though. If your goal is to engage in functional programming, you're better off using a language designed for that purpose. Python is a pragmatic language from an imperative tradition, that has some functional features tacked on. Python is pleasant for imperative programming while letting you make some use of functional style. From aahz at pythoncraft.com Mon May 10 14:18:04 2010 From: aahz at pythoncraft.com (Aahz) Date: 10 May 2010 11:18:04 -0700 Subject: Is Python a functional programming language? References: <7xvdavd4bq.fsf@ruckus.brouhaha.com> Message-ID: In article <7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >If your goal is to engage in functional programming, you're better off >using a language designed for that purpose. Python is a pragmatic >language from an imperative tradition, that has some functional features >tacked on. While your first sentence is spot-on, saying that functional features are "tacked on" understates the case. Consider how frequently people reach for list comps and gen exps. Function dispatch through dicts is the standard replacement for a switch statement. Lambda callbacks are common. Etc, etc, etc -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From aclark at aclark.net Mon May 10 14:29:49 2010 From: aclark at aclark.net (Alex Clark) Date: Mon, 10 May 2010 18:29:49 +0000 (UTC) Subject: Turbogears 2 training this weekend in Washington, DC USA Message-ID: Hi all, Sorry for the short notice. We (the Zope/Python Users Group of DC) are having a TurboGears 2 training class this weekend in Washington, DC USA taught by core developer Chris Perkins. Please consider attending! And, I would appreciate you spreading the word to anyone you think may be interested as well. Details are here: http://www.meetup.com/python-meetup-dc/messages/10123013/ And here is a taste: --- The DC Python Meetup is pleased to present Turbogears 2 training, delivered by Turbogears core developer Christopher Perkins. You can register now at http://tg2-class.eventbrite.com/ Turbogears is a modern python web framework with a powerful ORM (the one and only SQLAlchemy), designer friendly templates, and a widget system that simplifies Ajax development. If you're a web developer interested in expanding your toolkit or a python developer who wants to dabble in the web space, this training is an excellent opportunity to learn an agile and mature web framework. The training itself will be wonderfully practical, taking you from basic setup to a real application over the course of a day. You're invited to bring your own data, so that you can work with Chris to start migrating that legacy PHP app you have sitting around to Python beauty. This hands-on training aims to bring students up to speed with TurboGears 2, its administration interface, and touch common deployment scenarios. Students will also get to customize auto generated forms and tables. --- I hope to see you there! Alex, http://zpugdc.org -- Alex Clark ? http://aclark.net Author of Plone 3.3 Site Administration ? http://aclark.net/plone-site-admin From pmaupin at gmail.com Mon May 10 14:36:27 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Mon, 10 May 2010 11:36:27 -0700 (PDT) Subject: Picking a license References: <30aff350- <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> <9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com> Message-ID: <7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> On May 10, 12:37?pm, Paul Boddie wrote: > On 10 Mai, 17:06, a... at pythoncraft.com (Aahz) wrote: > > > In article <074b412a-c2f4-4090-a52c-4d69edb29... at d39g2000yqa.googlegroups.com>, > > Paul Boddie ? wrote: > > >Actually, the copyleft licences don't "force" anyone to "give back > > >changes": they oblige people to pass on changes. > > > IMO, that's a distinction without a difference, particularly if you > > define "give back" as referring to the community rather than the original > > project. > > There is a difference: I know of at least one vendor of GPL-licensed > solutions who received repeated requests that they make their sources > available to all-comers, even though the only obligation is to those > receiving the software in the first place. Yes, the code can then > become public - if Red Hat decided to only release sources to their > customers, and those customers shared the sources publicly, then > CentOS would still be around as a Red Hat "clone" - but there are > situations where recipients of GPL-licensed code may decide that it is > in their best interests not to just upload it to the public Internet. > > > ?With the FSF itself using "pressure" in the FAQ entry you > > linked to, I have no clue why you and Ben Finney object to my use of > > "force". > > Because no-one is being forced to do anything. Claiming that "force" > is involved is like hearing a schoolboy saying, "I really wanted that > chocolate, but why is that man forcing me to pay for it?" Well, you > only have to pay for it if you decide you want to take it - that's the > only reasonable response. I've addressed this before. Aahz used a word in an accurate, but to you, inflammatory, sense, but it's still accurate -- the man *would* force you to pay for the chocolate if you took it. You're making it sound like whining, but Aahz was simply trying to state a fact. The fact is, I know the man would force me to pay for the chocolate, so in some cases that enters into the equation and keeps me from wanting the chocolate. This isn't whining; just a common-sense description of reality. Personally, I think this use of the word "force" is much less inflammatory than the deliberate act of co-opting the word "freedom" to mean "if you think you can take this software and do anything you want with it, you're going to find out differently when we sue you." Regards, Pat From nobody at nowhere.com Mon May 10 15:45:51 2010 From: nobody at nowhere.com (Nobody) Date: Mon, 10 May 2010 20:45:51 +0100 Subject: Is Python a functional programming language? References: Message-ID: On Tue, 11 May 2010 00:24:22 +1200, Samuel Williams wrote: > Is Python a functional programming language? Not in any meaningful sense of the term. > Is this a paradigm that is well supported by both the language syntax and > the general programming APIs? No. > I heard that lambdas were limited to a single expression, Yes. In a functional language that wouldn't be a problem, as there's no limit to the complexity of an expression. Python's expressions are far more limited, which restricts what can be done with a lambda. > and that other > functional features were slated for removal in Python 3... is this the > case or have I been misinformed? I don't know about this. > Finally, even if Python supports functional features, is this a model that > is used often in client/application code? Not really. List comprehensions are probably the most common example of functional idioms, but again they're limited by Python's rather limited concept of an expression. From anthony.cole at gmail.com Mon May 10 15:55:10 2010 From: anthony.cole at gmail.com (Anthony Cole) Date: Mon, 10 May 2010 20:55:10 +0100 Subject: Hex String Message-ID: How can I concatenate 2 hex strings (e.g. '\x16' and '\xb9') then convert the answer to an integer? When I try i always end up with the ASCII equivalent! Thanks, Anthony From matt at tplus1.com Mon May 10 16:13:44 2010 From: matt at tplus1.com (Matthew Wilson) Date: Mon, 10 May 2010 20:13:44 +0000 (UTC) Subject: How to measure speed improvements across revisions over time? Message-ID: I know how to use timeit and/or profile to measure the current run-time cost of some code. I want to record the time used by some original implementation, then after I rewrite it, I want to find out if I made stuff faster or slower, and by how much. Other than me writing down numbers on a piece of paper on my desk, does some tool that does this already exist? If it doesn't exist, how should I build it? Matt From clp2 at rebertia.com Mon May 10 16:15:05 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 10 May 2010 13:15:05 -0700 Subject: Hex String In-Reply-To: References: Message-ID: On Mon, May 10, 2010 at 12:55 PM, Anthony Cole wrote: > How can I concatenate 2 hex strings (e.g. '\x16' and '\xb9') then convert > the answer to an integer? > > When I try i always end up with the ASCII equivalent! I think you want the `struct` module: struct ? Interpret strings as packed binary data http://docs.python.org/library/struct.html Cheers, Chris -- http://blog.rebertia.com From python at mrabarnett.plus.com Mon May 10 16:15:20 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 10 May 2010 21:15:20 +0100 Subject: Hex String In-Reply-To: References: Message-ID: <4BE86958.6080407@mrabarnett.plus.com> Anthony Cole wrote: > How can I concatenate 2 hex strings (e.g. '\x16' and '\xb9') then convert > the answer to an integer? > > When I try i always end up with the ASCII equivalent! > Those are just bytestrings (assuming you're using Python 2.x), ie strings using 1 byte per character. You can convert a bytestring to an integer using the functions in the 'struct' module. From martin at v.loewis.de Mon May 10 16:25:37 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 10 May 2010 22:25:37 +0200 Subject: Upgrade Python 2.6.4 to 2.6.5 In-Reply-To: References: Message-ID: <4BE86BC1.8040102@v.loewis.de> Werner F. Bruhin wrote: > Just upgraded on my Windows 7 machine my copy of 2.6.4 to 2.6.5. > > However doing sys.version still shows 2.6.4 even so python.exe is dated > 19. March 2010 with a size of 26.624 bytes. > > Is this a known issue? Or did I do something wrong? Look at the copy of python26.dll. This should be the new one; perhaps you have another copy in the system32 folder? Did the upgrade inform you that it was an upgrade, or did it warn you that you would overwrite the previous installation? Regards, Martin From martin at v.loewis.de Mon May 10 16:25:37 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 10 May 2010 22:25:37 +0200 Subject: Upgrade Python 2.6.4 to 2.6.5 In-Reply-To: References: Message-ID: <4BE86BC1.8040102@v.loewis.de> Werner F. Bruhin wrote: > Just upgraded on my Windows 7 machine my copy of 2.6.4 to 2.6.5. > > However doing sys.version still shows 2.6.4 even so python.exe is dated > 19. March 2010 with a size of 26.624 bytes. > > Is this a known issue? Or did I do something wrong? Look at the copy of python26.dll. This should be the new one; perhaps you have another copy in the system32 folder? Did the upgrade inform you that it was an upgrade, or did it warn you that you would overwrite the previous installation? Regards, Martin From phlip2005 at gmail.com Mon May 10 16:29:04 2010 From: phlip2005 at gmail.com (Phlip) Date: Mon, 10 May 2010 13:29:04 -0700 (PDT) Subject: [Epydoc-devel] How to? epydoc --top=README Message-ID: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> Pythonistas: I have a question to epydoc-devel, but it might be languishing: http://sourceforge.net/mailarchive/forum.php?thread_name=l2n860c114f1005061707k1ccf68cdz277a3d875b99fe04%40mail.gmail.com&forum_name=epydoc-devel How do you populate the index.html output with your (insanely clever) contents of your README file? When I try the obvious notations, such as --top=README or -- top=README.html, I get: Warning: Identifier 'README' looks suspicious; using it anyway. Warning: Could not find top page 'README'; using module-tree.html instead And, yes, the README is included in the input list, and yes I get a script-README-module.html ----8<------------------------------------------ The question for the rest of Python-Land: Should I be using a better documentation extractor? (pydoc is too mundane so far.) Or should I be using a better forum for epydoc users questions? -- yes-I-know-topicality-ly-yrs Phlip http://c2.com/cgi/wiki?ZeekLand From clp2 at rebertia.com Mon May 10 16:39:25 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 10 May 2010 13:39:25 -0700 Subject: [Epydoc-devel] How to? epydoc --top=README In-Reply-To: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> Message-ID: On Mon, May 10, 2010 at 1:29 PM, Phlip wrote: > Pythonistas: > The question for the rest of Python-Land: Should I be using a better > documentation extractor? (pydoc is too mundane so far.) Sphinx is in vogue right now: http://sphinx.pocoo.org/ It's used for the official docs and its results are quite pretty. Cheers, Chris -- http://blog.rebertia.com From phlip2005 at gmail.com Mon May 10 16:51:17 2010 From: phlip2005 at gmail.com (Phlip) Date: Mon, 10 May 2010 13:51:17 -0700 (PDT) Subject: How to? epydoc --top=README References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> Message-ID: <4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com> On May 10, 1:39?pm, Chris Rebert wrote: > Sphinx is in vogue right now:http://sphinx.pocoo.org/ > > It's used for the official docs and its results are quite pretty. The manager said to hold off on Sphinx until the next phase - then ran off to get married or something. But yet I persevere... From amphioxus at yahoo.com Mon May 10 17:01:10 2010 From: amphioxus at yahoo.com (Armin) Date: Mon, 10 May 2010 14:01:10 -0700 Subject: Problem displaying jpgs in Tkinter via PIL Message-ID: <2010051014011093749-amphioxus@yahoocom> Hi everyone, I'm new to Python and have been playing around with it using the Enthought Python distribution for Mac OS X 10.6.3 (EPD academic license, version 6.1 with python 2.6.4). It's been great learning the basics, but I've started running into problems when I'm trying to use the PIL library with Tkinter. All I'm trying to do is display a JPG as a Tkinter label: # code below: from Tkinter import * import Image, ImageTk def main(): filename = "images/testimg.jpg" imgPIL = Image.open(filename) root = Tk() imgTK = ImageTk.PhotoImage(imgPIL) label = Label(root, image=imgTK) label.pack() root.mainloop() main() # end of code It all works fine when I'm just using GIF images through Tkinter's photoimage object, but as soon as I'm trying to convert an image through ImageTk, I get the following error: ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/PIL/_imagingtk.so, 2): Library not loaded: /System at rpath/Tcl Referenced from: /Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/PIL/_imagingtk.so Reason: image not found I have no idea what that means, but I've always assumed the EPD includes all the stuff that's needed to make Tkinter work with PIL. Any advice would be greatly appreciated. Thanks! From phlip2005 at gmail.com Mon May 10 17:11:33 2010 From: phlip2005 at gmail.com (Phlip) Date: Mon, 10 May 2010 14:11:33 -0700 (PDT) Subject: lame sphinx questions [Was: lame epydoc questions] References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> <4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com> Message-ID: <289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com> On May 10, 1:51?pm, Phlip wrote: > On May 10, 1:39?pm, Chris Rebert wrote: > > > Sphinx is in vogue right now:http://sphinx.pocoo.org/ Okay, we have ten thousand classes to document. How to add them all to index.rst? From cjw at ncf.ca Mon May 10 17:17:24 2010 From: cjw at ncf.ca (cjw) Date: Mon, 10 May 2010 17:17:24 -0400 Subject: unittest not being run In-Reply-To: References: <4BE7FE59.408@gmail.com> <1273498724.2997.3.camel@cliff-laptop> Message-ID: On 10-May-10 10:21 AM, John Maclean wrote: > On 10/05/2010 14:38, J. Cliff Dyer wrote: >> My guess is you mixed tabs and spaces. One tab is always treated by the >> python interpreter as being equal to eight spaces, which is two >> indentation levels in your code. >> >> Though if it were exactly as you show it, you'd be getting a syntax >> error, because even there, it looks like the indentation of your `def >> test_T1(self):` line is off by one column, relative to pass, and by >> three columns relative to the other methods. >> >> Cheers, >> Cliff > > 'twas a spaces/indent issue. thanks! > > > PyScripter and PythonWin permit the user to choose the equivalence of tabs and spaces. I like two spaces = on tab, it's a matter of taste. I feel that eight spaces is too much. Colin W. From exarkun at twistedmatrix.com Mon May 10 19:04:36 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 10 May 2010 23:04:36 -0000 Subject: How to measure speed improvements across revisions over time? In-Reply-To: References: Message-ID: <20100510230436.1843.386684761.divmod.xquotient.13@localhost.localdomain> On 08:13 pm, matt at tplus1.com wrote: >I know how to use timeit and/or profile to measure the current run-time >cost of some code. > >I want to record the time used by some original implementation, then >after I rewrite it, I want to find out if I made stuff faster or >slower, >and by how much. > >Other than me writing down numbers on a piece of paper on my desk, does >some tool that does this already exist? > >If it doesn't exist, how should I build it? http://github.com/tobami/codespeed sounds like the kind of thing you're looking for. You can see an example of what it does at http://speed.pypy.org/ Jean-Paul > >Matt > >-- >http://mail.python.org/mailman/listinfo/python-list From aonlazio at gmail.com Mon May 10 19:25:35 2010 From: aonlazio at gmail.com (AON LAZIO) Date: Mon, 10 May 2010 19:25:35 -0400 Subject: Difference between 'is not' and '!=' ? Message-ID: As subject says, what is the differences of 'is not' and '!='. Confusing.. -- Passion is my style -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon May 10 19:31:54 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 10 May 2010 16:31:54 -0700 Subject: Difference between 'is not' and '!=' ? In-Reply-To: References: Message-ID: On Mon, May 10, 2010 at 4:25 PM, AON LAZIO wrote: > As subject says, what is the differences of 'is not' and '!='. Confusing.. != checks value inequality, `is not` checks object identity / "pointer" inequality Unless you're doing `foo is not None`, you almost always want !=. By way of demonstration (using the non-negated versions to be less confusing): >>> x = [1, 2] >>> y = [1, 2] >>> x == y True >>> x is y False >>> z = x >>> x is z True >>> z is y False >>> x.append(3) >>> x [1, 2, 3] >>> y [1, 2] >>> z [1, 2, 3] >>> x is z True Cheers, Chris -- http://blog.rebertia.com From lists at cheimes.de Mon May 10 19:32:45 2010 From: lists at cheimes.de (Christian Heimes) Date: Tue, 11 May 2010 01:32:45 +0200 Subject: Difference between 'is not' and '!=' ? In-Reply-To: References: Message-ID: AON LAZIO wrote: > As subject says, what is the differences of 'is not' and '!='. Confusing.. "is not" checks if two objects are not identical. "!=" checks if two objects are not equal. Example: Two apples may be equal in size, form and color but they can never be identical because they are made up from different atoms. Christian From goon12 at gmail.com Mon May 10 19:36:25 2010 From: goon12 at gmail.com (Joe Riopel) Date: Mon, 10 May 2010 19:36:25 -0400 Subject: unittest not being run In-Reply-To: References: <4BE7FE59.408@gmail.com> <1273498724.2997.3.camel@cliff-laptop> Message-ID: On Mon, May 10, 2010 at 5:17 PM, cjw wrote: > PyScripter and PythonWin permit the user to choose the equivalence of tabs > and spaces. ?I like two spaces = on tab, it's a matter of taste. ?I feel > that eight spaces is too much. While it is a matter of taste, PEP 8 recommends 4 spaces per indentation level. http://www.python.org/dev/peps/pep-0008/ From luismgz at gmail.com Mon May 10 21:04:29 2010 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 10 May 2010 18:04:29 -0700 (PDT) Subject: Is Python a functional programming language? References: Message-ID: <06f5541f-ccbe-427a-83ad-176fcb947d29@e35g2000yqm.googlegroups.com> On 10 mayo, 09:24, Samuel Williams wrote: > Dear Friends, > > Is Python a functional programming language? > > Is this a paradigm that is well supported by both the language syntax and the general programming APIs? > > I heard that lambdas were limited to a single expression, and that other functional features were slated for removal in Python 3... is this the case or have I been misinformed? > > Finally, even if Python supports functional features, is this a model that is used often in client/application code? > > Kind regards, > Samuel I'm no expert of functional programming at all, but I read many times (from famous programmers) that Python is very lisp-like, but with a more conventional syntax. For example, Paul Graham and others have some interesting views on this subject: http://www.prescod.net/python/IsPythonLisp.html That doesn't mean python can compete with other purely functional languages, but it's probably as functional as it can be for a more conventional, multiparadigm language. Luis From ben+python at benfinney.id.au Mon May 10 21:15:37 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 11 May 2010 11:15:37 +1000 Subject: Picking a license References: <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> Message-ID: <87vdavck7a.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > Paul Boddie wrote: > >Actually, the copyleft licences don't "force" anyone to "give back > >changes": they oblige people to pass on changes. > > IMO, that's a distinction without a difference, particularly if you > define "give back" as referring to the community rather than the > original project. With the FSF itself using "pressure" in the FAQ > entry you linked to, I have no clue why you and Ben Finney object to > my use of "force". Precisely because there *is* force involved: copyright law is enforced, ultimately, by police with threats to put you in a box forcibly. But that force, it must be recognised, comes from the force of law. The GPL, and all free software licenses, do *not* force anyone to do anything; exactly the opposite is the case. Free software licenses grant specific exceptions to the enforcement of copyright law. They grant freedom to do things that would otherwise be prevented by force or the threat of force. This is obvious when you consider what would be the case in the absence of any free software license: everything that was prohibited is still prohibited in the absence of the license, and indeed some more things are now prohibited as well. Conversely, in the absence of any copyright law (not that I advocate that situation), copyright licenses would have no force in or behind them. So I object to muddying the issue by misrepresenting the source of that force. Whatever force there is in copyright comes from law, not any free software license. -- \ ?Let others praise ancient times; I am glad I was born in | `\ these.? ?Ovid (43 BCE?18 CE) | _o__) | Ben Finney From steven at REMOVE.THIS.cybersource.com.au Mon May 10 22:06:01 2010 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 May 2010 02:06:01 GMT Subject: How to measure speed improvements across revisions over time? References: Message-ID: On Mon, 10 May 2010 20:13:44 +0000, Matthew Wilson wrote: > I know how to use timeit and/or profile to measure the current run-time > cost of some code. > > I want to record the time used by some original implementation, then > after I rewrite it, I want to find out if I made stuff faster or slower, > and by how much. > > Other than me writing down numbers on a piece of paper on my desk, does > some tool that does this already exist? > > If it doesn't exist, how should I build it? from timeit import Timer before = Timer(before_code, setup) after = Timer(after_code, setup) improvement = min(before.repeat()) - min(after.repeat()) -- Steven From kushal.kumaran+python at gmail.com Mon May 10 22:06:53 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 11 May 2010 07:36:53 +0530 Subject: HTTP Post Request In-Reply-To: <06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com> References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> <06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com> Message-ID: On Mon, May 10, 2010 at 8:26 PM, kaklis at gmail.com wrote: > On May 10, 10:22?am, Kushal Kumaran > wrote: >> On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com wrote: >> > Hi to all, i want to ask you a question, concerning the best way to do >> > the following as a POST request: >> > There is server-servlet that accepts xml commands >> > It had the following HTTP request headers: >> >> > ? ? ? ? ? ?Host: somehost.com >> > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient >> > ? ? ? ? ? ?Content-Type: text/xml >> > ? ? ? ? ? ?Content-Length: 415 >> >> > and the following request body (reformatted here for clarity): >> >> > ? ? ? ? ? ? >> > ? ? ? ? ? ? >> > ? ? ? ? ? ? ?search >> > ? ? ? ? ? ? >> > How can i send the above to the Listener Servlet? >> > Thanks in advance >> >> Use the xmlrpclib module. >> > > OK, sending headers with xmlrpclib, > but how do i send the XML message? > Your XML message is an XML RPC message. You will use xmlrpclib like this: server_proxy = xmlrpclib.ServerProxy(('somehost.com', 80)) result = server_proxy.search() The call to server_proxy.search will result in an actual XML RPC message being sent. Read up on the xmlrpclib documentation here: http://docs.python.org/library/xmlrpclib.html, and the XMLRPC spec here: http://www.xmlrpc.com/spec -- regards, kushal From space.ship.traveller at gmail.com Mon May 10 23:17:49 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 11 May 2010 15:17:49 +1200 Subject: Is Python a functional programming language? In-Reply-To: References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> Message-ID: Thanks to everyone for their great feedback, it is highly appreciated. Kind regards, Samuel From tjreedy at udel.edu Mon May 10 23:23:01 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 May 2010 23:23:01 -0400 Subject: Extract all words that begin with x In-Reply-To: References: Message-ID: On 5/10/2010 5:35 AM, James Mills wrote: > On Mon, May 10, 2010 at 6:50 PM, Xavier Ho wrote: >> Have I missed something, or wouldn't this work just as well: >> >>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas'] >>>>> [word for word in list_of_strings if word[0] == 'a'] >> ['awes', 'asdgas'] > > I would do this for completeness (just in case): > >>>>> [word for word in list_of_strings if word and word[0] == 'a'] > > Just guards against empty strings which may or may not be in the list. ... word[0:1] does the same thing. All Python programmers should learn to use slicing to extract a char from a string that might be empty. The method call of .startswith() will be slower, I am sure. From tycho at tycho.ws Tue May 11 00:17:30 2010 From: tycho at tycho.ws (Tycho Andersen) Date: Mon, 10 May 2010 23:17:30 -0500 Subject: Extract all words that begin with x In-Reply-To: References: Message-ID: On Mon, May 10, 2010 at 10:23 PM, Terry Reedy wrote: > On 5/10/2010 5:35 AM, James Mills wrote: >> >> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho ?wrote: >>> >>> Have I missed something, or wouldn't this work just as well: >>> >>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas'] >>>>>> [word for word in list_of_strings if word[0] == 'a'] >>> >>> ['awes', 'asdgas'] >> >> I would do this for completeness (just in case): >> >>>>>> [word for word in list_of_strings if word and word[0] == 'a'] >> >> Just guards against empty strings which may or may not be in the list. > > ?... word[0:1] does the same thing. All Python programmers should learn to > use slicing to extract a ?char from a string that might be empty. > The method call of .startswith() will be slower, I am sure. Why? Isn't slicing just sugar for a method call? \t From ldo at geek-central.gen.new_zealand Tue May 11 01:43:59 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 May 2010 17:43:59 +1200 Subject: virtualenvwrapper for Windows (Powershell) References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com> Message-ID: In message <22cf35af-44d1-43fe-8b90-07f2c6545f63 at i10g2000yqh.googlegroups.com>, Guillermo wrote: > If you've ever missed it on Windows and you can use Powershell ... I thought the whole point of Windows was to get away from this command-line stuff. Not such a good idea after all? From ldo at geek-central.gen.new_zealand Tue May 11 01:46:56 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 May 2010 17:46:56 +1200 Subject: shortcut for large amount of global var declarations? References: Message-ID: In message , Alex Hall wrote: > ... I have about fifteen vars in a function which have to be > global. Why not make them class variables, e.g. class my_namespace : var1 = ... var2 = ... #end my_namespace def my_function(...) : ... can directly read/assign my_namespace.var1 etc here ... #end my_function Also has the benefit of minimizing pollution of the global namespace. From ldo at geek-central.gen.new_zealand Tue May 11 01:48:41 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 May 2010 17:48:41 +1200 Subject: fast regex References: Message-ID: In message , james_027 wrote: > I was working with regex on a very large text, really large but I have > time constrained. ?Fast regex? is a contradiction in terms. You use regexes when you want ease of definition and application, not speed. For speed, consider hand-coding your own state machine. Preferably in a compiled language like C. From stefan_ml at behnel.de Tue May 11 02:35:52 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 11 May 2010 08:35:52 +0200 Subject: unable to get Hudson to run unit tests In-Reply-To: <4BE828A2.2070106@noaa.gov> References: <4BE80A78.2030502@noaa.gov> <4BE828A2.2070106@noaa.gov> Message-ID: j vickroy, 10.05.2010 17:39: > Unfortunately, when "Hudson Build now" is performed, the Hudson Console > output, for this job, is: > > ------------------------------------------------------------ > Started by user anonymous > Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 > At revision 3403 > no change for svn://vm-svn/GOES data > processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build > [workspace] $ python.exe > C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson5273111667332806239.sh > os.getcwd(): C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES > 13-15 SXI Level-1 Products Generation\workspace > os.listdir(os.getcwd()): ['level-1'] > [workspace] $ cmd.exe -xe > C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson991194264891924641.sh > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI > Level-1 Products Generation\workspace>Recording test results > No test report files were found. Configuration error? > Finished: FAILURE > ------------------------------------------------------------ > > The second [workspace] section output (above) looks like cmd.exe is > being executed with no parameters (i.e., without the > "nosetests.exe --where=level-1 --with-xunit --verbose") parameter. No, what Hudson actually does, is, it writes your command(s) into a text file and runs it with the system's shell interpreter (which, unless otherwise configured, is "cmd.exe" on Windows). This assures the highest possible compatibility with the executed script. You can even use the shebang in Hudson's scripts that way, so that you can execute scripts in basically any scripting language. The likely reason why it doesn't find your test results is that you didn't tell it where to look. Put a wildcard path into the unit test config box that finds the XML files that nosetest writes. It's also best to tell nosetest where to put them explicitly using a command line option. Stefan From martin at v.loewis.de Tue May 11 02:44:28 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 11 May 2010 08:44:28 +0200 Subject: How to measure speed improvements across revisions over time? In-Reply-To: References: Message-ID: <4BE8FCCC.1060103@v.loewis.de> Matthew Wilson wrote: > I know how to use timeit and/or profile to measure the current run-time > cost of some code. > > I want to record the time used by some original implementation, then > after I rewrite it, I want to find out if I made stuff faster or slower, > and by how much. > > Other than me writing down numbers on a piece of paper on my desk, does > some tool that does this already exist? I recommend to use rrd. This can record time series, and then generate diagrams. Regards, Martin From isso.moh at gmail.com Tue May 11 02:52:43 2010 From: isso.moh at gmail.com (mohamed issolah) Date: Tue, 11 May 2010 08:52:43 +0200 Subject: win32com In-Reply-To: References: Message-ID: hey, I need help . 2010/5/9 mohamed issolah > hey, > I wich to have an example please > > need help > > > > 2010/5/9 Chris Rebert > > On Sun, May 9, 2010 at 1:15 AM, mohamed issolah >> wrote: >> > hey, >> > >> > there is an alternative of win32com in linux? >> > >> > what i want to say : can communicate with application (ex: evolution or >> > another) throught python like in windows with win32com >> >> The closest equivalent would probably be python-dbus. See the "Python" >> section of http://www.freedesktop.org/wiki/Software/DBusBindings >> >> Information on D-Bus generally: http://en.wikipedia.org/wiki/D-Bus >> >> Cheers, >> Chris >> -- >> http://blog.rebertia.com >> > > > > -- > issolah mohamed > -- issolah mohamed -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at nospam.invalid Tue May 11 03:08:13 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 11 May 2010 00:08:13 -0700 Subject: fast regex References: Message-ID: <7xaas6gbky.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > ?Fast regex? is a contradiction in terms. You use regexes when you want ease > of definition and application, not speed. > > For speed, consider hand-coding your own state machine. Preferably in a > compiled language like C. But, nothing stops a regexp library from doing that, and some of them do. From eckhardt at satorlaser.com Tue May 11 03:09:42 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 11 May 2010 09:09:42 +0200 Subject: Iterating a sequence two items at a time Message-ID: Hi! I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4), (5,6). I can of course roll my own, but I was wondering if there was already some existing library function that already does this. def as_pairs(seq): i = iter(seq) yield (i.next(), i.next()) Question to this code: Is the order of the "i.next()" calls guaranteed to be from left to right? Or could I end up with pairs being switched? Thanks! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From werner.bruhin at free.fr Tue May 11 03:10:24 2010 From: werner.bruhin at free.fr (Werner F. Bruhin) Date: Tue, 11 May 2010 09:10:24 +0200 Subject: Upgrade Python 2.6.4 to 2.6.5 In-Reply-To: <4BE86BC1.8040102@v.loewis.de> References: <4BE86BC1.8040102@v.loewis.de> Message-ID: <4BE902E0.8060108@free.fr> Martin, Thanks for the quick reply. On 10/05/2010 22:25, Martin v. Loewis wrote: > Werner F. Bruhin wrote: > >> Just upgraded on my Windows 7 machine my copy of 2.6.4 to 2.6.5. >> >> However doing sys.version still shows 2.6.4 even so python.exe is dated >> 19. March 2010 with a size of 26.624 bytes. >> >> Is this a known issue? Or did I do something wrong? >> > Look at the copy of python26.dll. This should be the new one; perhaps > you have another copy in the system32 folder? > The one in system32 is 2.6.5 and the one in c:\python26 is 2.6.4. When will it install into system32? > Did the upgrade inform you that it was an upgrade, or did it warn you > that you would overwrite the previous installation? > It warned me that there is a previous installation. Best regards Werner From no.email at nospam.invalid Tue May 11 03:17:30 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 11 May 2010 00:17:30 -0700 Subject: Is Python a functional programming language? References: <06f5541f-ccbe-427a-83ad-176fcb947d29@e35g2000yqm.googlegroups.com> Message-ID: <7xzl06ewl1.fsf@ruckus.brouhaha.com> Luis M. Gonz?lez writes: > That doesn't mean python can compete with other purely functional > languages, but it's probably as functional as it can be for a more > conventional, multiparadigm language. Ben Lippmeier made the interesting claim that one of the defining characteristics of functional programming is type systems based on the Curry-Howard correspondence. By that standard I think even Scheme (perhaps the grandaddy of functional languages) wouldn't qualify. I do think of Scheme as a functional language, but of Python and Lisp as imperative languages with functional aspects. I like learnyouahaskell.com if you want to get some exposure to Haskell, probably the archetypal functional language these days. I've been fooling with it on and off for the past couple years. I'm still not convinced that it's that good a vehicle for practical general purpose software development, but there are some specific areas where it works out just beautifully. And in terms of the challenges it presents and the amount I've learned from it, it's one of the most interesting things I've done as a programmer in as long as I can remember. It really is mind altering. From clp2 at rebertia.com Tue May 11 03:33:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 11 May 2010 00:33:59 -0700 Subject: Iterating a sequence two items at a time In-Reply-To: References: Message-ID: On Tue, May 11, 2010 at 12:09 AM, Ulrich Eckhardt wrote: > Hi! > > I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4), > (5,6). I can of course roll my own, but I was wondering if there was > already some existing library function that already does this. When a problem involves iteration, always check the `itertools` module in the std lib. >From the module docs's recipe section (http://docs.python.org/library/itertools.html#recipes): import itertools def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itertools.izip_longest(fillvalue=fillvalue, *args) >>> # Let's try it out. >>> list(grouper(2, [1,2,3,4,5,6])) [(1, 2), (3, 4), (5, 6)] >>> # Success! > def as_pairs(seq): > ? ?i = iter(seq) > ? ?yield (i.next(), i.next()) > > Question to this code: Is the order of the "i.next()" calls guaranteed to be > from left to right? Or could I end up with pairs being switched? Pretty sure left-to-right is guaranteed; see http://bugs.python.org/issue448679 Also, if you're using Python 2.6+, the line should be: yield (next(i), next(i)) See http://docs.python.org/library/functions.html#next Cheers, Chris -- http://blog.rebertia.com From kaklis at gmail.com Tue May 11 03:56:33 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 11 May 2010 00:56:33 -0700 (PDT) Subject: HTTP Post Request References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> <06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com> Message-ID: <95e73ff4-abe5-4874-8652-647818ed224a@k29g2000yqh.googlegroups.com> On May 11, 5:06?am, Kushal Kumaran wrote: > On Mon, May 10, 2010 at 8:26 PM, kak... at gmail.com wrote: > > On May 10, 10:22?am, Kushal Kumaran > > wrote: > >> On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com wrote: > >> > Hi to all, i want to ask you a question, concerning the best way to do > >> > the following as a POST request: > >> > There is server-servlet that accepts xml commands > >> > It had the following HTTP request headers: > > >> > ? ? ? ? ? ?Host: somehost.com > >> > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient > >> > ? ? ? ? ? ?Content-Type: text/xml > >> > ? ? ? ? ? ?Content-Length: 415 > > >> > and the following request body (reformatted here for clarity): > > >> > ? ? ? ? ? ? > >> > ? ? ? ? ? ? > >> > ? ? ? ? ? ? ?search > >> > ? ? ? ? ? ? > >> > How can i send the above to the Listener Servlet? > >> > Thanks in advance > > >> Use the xmlrpclib module. > > > OK, sending headers with xmlrpclib, > > but how do i send the XML message? > > Your XML message is an XML RPC message. ?You will use xmlrpclib like this: > > server_proxy = xmlrpclib.ServerProxy(('somehost.com', 80)) > result = server_proxy.search() > > The call to server_proxy.search will result in an actual XML RPC > message being sent. > > Read up on the xmlrpclib documentation here:http://docs.python.org/library/xmlrpclib.html, and the XMLRPC spec > here:http://www.xmlrpc.com/spec > > -- > regards, > kushal Ok I got it! Thank you!!! A.K From bruno.42.desthuilliers at websiteburo.invalid Tue May 11 04:05:37 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 11 May 2010 10:05:37 +0200 Subject: Iterating a sequence two items at a time In-Reply-To: References: Message-ID: <4be90fca$0$31987$426a74cc@news.free.fr> Ulrich Eckhardt a ?crit : > Hi! > > I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4), > (5,6). I can of course roll my own, but I was wondering if there was > already some existing library function that already does this. >>> l = range(10) >>> for x, y in zip(l[::2], l[1::2]): ... print x, y ... 0 1 2 3 4 5 6 7 8 9 SimplestThingThatCouldPossiblyWork(tm) - but might not be the most efficient idiom, specially with large lists... From richard.lamboj at bilcom.at Tue May 11 04:38:52 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Tue, 11 May 2010 10:38:52 +0200 Subject: inherit from data type Message-ID: <201005111038.52390.richard.lamboj@bilcom.at> Hello, i want to inherit from a data type. How can i do this? Can anyone explain more abou this? How knows python that it is a float, or a string? Kind Regards Richi From eckhardt at satorlaser.com Tue May 11 04:43:23 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 11 May 2010 10:43:23 +0200 Subject: Iterating a sequence two items at a time References: Message-ID: Ulrich Eckhardt wrote: > I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4), > (5,6). I can of course roll my own, but I was wondering if there was > already some existing library function that already does this. > > > def as_pairs(seq): > i = iter(seq) > yield (i.next(), i.next()) Obviously this code does _not_ do what I want, it must be like this: def as_pairs(seq): i = iter(seq) while True: yield (i.next(), i.next()) Gah! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From eckhardt at satorlaser.com Tue May 11 04:47:35 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 11 May 2010 10:47:35 +0200 Subject: inherit from data type References: Message-ID: <76inb7-m2g.ln1@satorlaser.homedns.org> Richard Lamboj wrote: > i want to inherit from a data type. How can i do this? Can anyone explain > more abou this? Other than in e.g. C++ where int and float are special types, you can inherit from them in Python like from any other type. The only speciality of int, float and string is that they are immutable. > How knows python that it is a float, or a string? I'm not actually sure I understand this question. If you derive from float, Python obviously knows that you derive from float.... Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From bryanjugglercryptographer at yahoo.com Tue May 11 04:50:19 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 11 May 2010 01:50:19 -0700 (PDT) Subject: fast regex References: Message-ID: <9a10e0e6-c8ac-4488-acee-f981cd416f68@k25g2000prh.googlegroups.com> Lawrence D'Oliveiro wrote: > ?Fast regex? is a contradiction in terms. You use > regexes when you want ease of definition and > application, not speed. Python or Perl regex's are not actually regular expressions. Real regular expression compilers produce blazing fast results, but they cannot support many of the features of offered by the search-and- backtrack engines that Python and Perl use. > For speed, consider hand-coding your own state > machine. Preferably in a compiled language like C. The speed of a real regular expression engine is hard to beat. I assume you're not actually suggesting hand-writing a state machine for the problem at issue here, which requires recognizing about 5000 different words. -- --Bryan From bruno.42.desthuilliers at websiteburo.invalid Tue May 11 04:55:17 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 11 May 2010 10:55:17 +0200 Subject: inherit from data type In-Reply-To: References: Message-ID: <4be91b6f$0$21797$426a74cc@news.free.fr> Richard Lamboj a ?crit : > Hello, > > i want to inherit from a data type. How can i do this? Hmmm, let's see... Could it be possible that it's documented somewhere ? Like, in the FineManual(tm) ?-) http://docs.python.org/tutorial/classes.html#inheritance > Can anyone explain more > abou this? How knows python that it is a float, or a string? which "it" ? Sorry, I'd like to help but I can't make sense of this question... From prologic at shortcircuit.net.au Tue May 11 04:58:00 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 11 May 2010 18:58:00 +1000 Subject: inherit from data type In-Reply-To: <201005111038.52390.richard.lamboj@bilcom.at> References: <201005111038.52390.richard.lamboj@bilcom.at> Message-ID: On Tue, May 11, 2010 at 6:38 PM, Richard Lamboj wrote: > i want to inherit from a data type. How can i do this? Can anyone explain more > abou this? How knows python that it is a float, or a string? $ python Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) [GCC 4.4.1 (CRUX)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class MyFloat(float): ... def __repr__(self): ... return "MyFloat(%f)" % self ... >>> x = MyFloat(3.1415926535897931) >>> x MyFloat(3.141593) >>> --James From Ron.Barak at lsi.com Tue May 11 05:10:19 2010 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 11 May 2010 10:10:19 +0100 Subject: How to eliminate "Debug: src/helpers.cpp(140): 'CreateActCtx' failed" message ? In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6A3B87789@enbmail01.lsi.com> Hi, I created my first py2exe windows exe, and when it's run, I see on the console: $ ./svm_ts_tool_in_progress.exe 11:49:32: Debug: src/helpers.cpp(140): 'CreateActCtx' failed with error 0x0000007b (the filename, directory name, or volume label syntax is incorrect.). This is a non-fatal error and the application continues to run. I googled, but did not find a way to eliminate this Debug message. Could you suggest how to eliminate this message ? Thanks, Ron. ________________________________ Notes: $ python -V Python 2.6.4 $ cat setup.py #!/usr/bin/env python from distutils.core import setup import py2exe from glob import glob """ data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\HHD Software\Hex Editor Neo\Microsoft.VC90.CRT\*.*'))] icon_files = [("icons", glob(r'c:\views\cc_view\TS_svm_ts_tool\svm_ts_tool\*.gif'))] """ file_list = [] for i in glob(r'c:\views\cc_view\TS_svm_ts_tool\svm_ts_tool\*.gif'): file_list.append(i) data_files = [("data", file_list)] setup( data_files=data_files ) setup( console=["svm_ts_tool_in_progress.py"], zipfile=None, options={ "py2exe" : { "optimize" : 1 } } ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From richard.lamboj at bilcom.at Tue May 11 05:18:54 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Tue, 11 May 2010 11:18:54 +0200 Subject: inherit from data type In-Reply-To: <76inb7-m2g.ln1@satorlaser.homedns.org> References: <76inb7-m2g.ln1@satorlaser.homedns.org> Message-ID: <201005111118.54491.richard.lamboj@bilcom.at> Am Tuesday 11 May 2010 10:47:35 schrieb Ulrich Eckhardt: > Richard Lamboj wrote: > > i want to inherit from a data type. How can i do this? Can anyone explain > > more abou this? > > Other than in e.g. C++ where int and float are special types, you can > inherit from them in Python like from any other type. The only speciality > of int, float and string is that they are immutable. > > > How knows python that it is a float, or a string? > > I'm not actually sure I understand this question. If you derive from float, > Python obviously knows that you derive from float.... > > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 "How knows python that it is a float, or a string?" Sorry this was bad expressed. I want to create a new data type, which inherits from float. I just know the "dir" function and the "help" function to get more infromations about the class, but i need to get more information about the class structure. What i also want to know: >>> variable1 = 10.50 >>> type(variable1) Is there a way to tell python that it use antoher class than float for float, like myfloat? Its just a "tell-me-what-is-possible". Sample: >>> variable1 = 10.50 >>> type(variable1) Kind Regards, Richi From mftian at gmail.com Tue May 11 05:29:25 2010 From: mftian at gmail.com (Xie&Tian) Date: Tue, 11 May 2010 17:29:25 +0800 Subject: How to make this doctest work? Message-ID: Hello I ran across this accidentally and wonders how to make the doctest in following code snippet work: import doctest def a(): """ >>> a = '\\r\\n' >>> print a No matter how many blank lines I add here, it just can't get enough -_- """ pass doctest.testmod() ps: I want variable "a" to be '\r\n', but python kept telling me ValueError: line 4 of the docstring has inconsistent leading whitespace: "'" Why can't doctest module deal with statement "a='\r\n'"? -- Luyun Xie http://magefromhell.blogspot.com/ (http://blog.hellmage.info/) -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue May 11 05:30:39 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 11 May 2010 02:30:39 -0700 Subject: inherit from data type In-Reply-To: <201005111118.54491.richard.lamboj@bilcom.at> References: <76inb7-m2g.ln1@satorlaser.homedns.org> <201005111118.54491.richard.lamboj@bilcom.at> Message-ID: On Tue, May 11, 2010 at 2:18 AM, Richard Lamboj wrote: > What i also want to know: >>>> variable1 = 10.50 >>>> type(variable1) > > > Is there a way to tell python that it use antoher class than float for float, > like myfloat? Its just a "tell-me-what-is-possible". > > Sample: >>>> variable1 = 10.50 >>>> type(variable1) > No, it's not possible to have the float literal syntax produce instances of your custom subclass. Cheers, Chris -- http://blog.rebertia.com From dguthriemail at gmail.com Tue May 11 05:35:30 2010 From: dguthriemail at gmail.com (Dave Guthrie) Date: Tue, 11 May 2010 02:35:30 -0700 (PDT) Subject: Dynamically compiling and reloading SWIG .pyd file Message-ID: I am creating an application which has it's code split between python and C. The Python is used to provide a high level GUI interface and the C is for low level functions. I use SWIG to create Python Bindings for the C functions. I want to implement a feature where there is a button in the toolbar of the GUI which will automatically compile the C code into a .pyd file. The problem I have is when the GUI is running, the .pyd is loaded as a DLL and thus is locked by the GUI, so I can't get "gcc" to overwrite the .pyd file. I have tried to force the GUI to close it's handle on the file handle = ctypes.windll.kernel32.GetModuleHandleA("_FirmwareSubSys.pyd") if handle == 0: print "_FirmwareSubSys.pyd not loaded" else: _ctypes.FreeLibrary(handle) But by doing this the next time I load the DLL python crashes. Do anyone know how to dynamically compile and load SWIG Python Bindings? From eckhardt at satorlaser.com Tue May 11 05:38:42 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 11 May 2010 11:38:42 +0200 Subject: inherit from data type References: <76inb7-m2g.ln1@satorlaser.homedns.org> Message-ID: <26lnb7-t6g.ln1@satorlaser.homedns.org> Richard Lamboj wrote: > "How knows python that it is a float, or a string?" Sorry this was bad > expressed. I want to create a new data type, which inherits from float. I > just know the "dir" function and the "help" function to get more > infromations about the class, but i need to get more information about the > class structure. I'd suggest the tutorial, see http://docs.python.org, though your question is already beyond the range of beginners' questions. > What i also want to know: >>>> variable1 = 10.50 >>>> type(variable1) > > > Is there a way to tell python that it use antoher class than float for > float, like myfloat? Its just a "tell-me-what-is-possible". > > Sample: >>>> variable1 = 10.50 >>>> type(variable1) > The expression "10.5" will always be a float, you can't change that. What you can do is create your own type, derived from float: >>> class myfloat(float): ... pass ... and then create an object of that type: >>> x = myfloat(3.14) >>> type(x) >>> Lastly one warning: In many cases where people wanted to derive from a concrete data type, their problems were easier solved by external code. I don't know your problem though. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From paul at boddie.org.uk Tue May 11 06:24:26 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 11 May 2010 03:24:26 -0700 (PDT) Subject: Picking a license References: <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> Message-ID: <3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> On 10 Mai, 17:01, Patrick Maupin wrote: > > I'll be charitable and assume the fact that you can make that > statement without apparent guile merely means that you haven't read > the post I was referring to: > > http://www.gnu.org/philosophy/why-not-lgpl.html Of course I have read it, and not just recently either. But this is a position paper by the author of the licence, and it doesn't mean that someone who has written a GPL-licensed library completely agrees with that position. And anyway, it's a case of "take it or leave it" - it's not like the author or the FSF are sneaking stuff into every product and every corner of the market and then telling you that you can't "unchoose" their stuff. [...] > Legally, I don't think they can dictate the license terms of, e.g. > clisp just because it can link to readline. ?But practically, they DID > manage to do this, simply because Bruno Haible, the clisp author, was > more concerned about writing software than spending too much time > sparring with Stallman over the license, so he finally licensed clisp > under the gpl. ?clisp *could* use readline, but didn't require it; > nonetheless Stallman argued that clisp was a "derivative" of > readline. ?That case of the tail wagging the dog would be laughable if > it hadn't worked. ?In any case, Stallman's success at that tactic is > probably one of the things that led him to write the paper on why you > should use GPL for your library. Although it seems quite unfair, the e-mail discussion about the licence does show that Stallman was not initially convinced that works should be affected in such a way (with regard to the Objective-C compiler developed by NeXT), and that Haible was not strongly opposed to changing the licence. You can argue that Stallman overreached by demanding a licence change and that consideration of such matters has progressed since that time, but Haible always had the option of not using or supporting readline - only the latter is contentious, and the obligation of GPL-compatible licensing (as opposed to GPL-licensing) now diminishes how contentious this is today. [...] > I think that, legally, they probably don't have a leg to stand on for > some of their overarching claims (e.g. about shipping proprietary > software that could link to readline, without even shipping > readline). ?But morally -- well, they've made their position > reasonably clear and I try to abide by it. ?That still doesn't make it > "not really FUD." ?I'd call this sort of badgering "copyright misuse" > myself. Again, you have to consider the intent of the licensing: that some software which links to readline results in a software system that should offer the "four freedoms", because that's the price of linking to readline whose licence has promised that any system which builds upon it shall offer those privileges. > > As for rst2pdf, what your modifications would mean is that the > > software would need to be redistributed under a GPL-compatible > > licence. > > That's parsing semantics rather finely. ?In practice, what it really > means is that the combination (e.g. the whole program) would > effectively be GPL-licensed. ?This then means that downstream users > would have to double-check that they are not combining the whole work > with licenses which are GPL-incompatible, even if they are not using > the svg feature. ?Hence, the term "viral." Once again, I refer you to the intent of the licensing: if someone has the software in front of them which uses svglib, then they need to have the privileges granted to them by the GPL. Yes, if the software also uses some component with a GPL-incompatible licence, then this causes a problem. [...] > http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystem > > "A system incorporating a GPL-covered program is an extended version > of that program. The GPL says that any extended version of the program > must be released under the GPL if it is released at all." > > This makes it clear that the overall work must be GPLed. ?Now, all of > a sudden, downstream users cannot do some things they could have done > before. ?Can you not see that taking a preexisting MIT-licensed > project and adding code to make it GPL could negatively affect some of > its users and that that is not necessarily an unalloyed good? Well, I have referred several times to WebKit without you taking the hint, but that provides a specific case of a project which is LGPL- licensed despite being based on (in GPLv3 terminology) libraries which were distributed under the GPL and combined with that software. Similarly, the effort to ensure that CPython's licence was GPL- compatible had a lot to do with the right to redistribute with GPL- licensed code (actually readline, if I remember correctly). [...] > > Well, even the FSF doesn't approve of trivial projects using the GPL: > > >http://www.gnu.org/licenses/gpl-faq.html#WhatIfWorkIsShort > > Sure, that's a pragmatic view -- copyright might not even be permitted > on something that short that is mainly functional. ?However, length is > not the only arbiter of trivial. ?To stay with the same example, > personally, I would consider readline "trivial" within the context of > a lot of software which might use it, regardless of whether the > readline implementation itself used all sorts of fancy neural net > technology to predict what word the user was going to type or > whatever. ?But whether it was trivial or not, if I ship software that > *could* link to it but doesn't *require* it (like the case of clisp) > without shipping readline, I think it's FUD and an attempt at > copyright misuse to call my software a derivative work of readline. > But obviously YMMV Is readline trivial? Was readline trivial in 1992? Does it even matter, because the author is more or less saying that they don't want their code incorporated in a proprietary system? It's interesting to see that GPLv3 doesn't talk about derived works or derivatives (at least not as much as GPLv2), but instead talks about things being "based on" other things, but as I've already said, at the point of someone running a bunch of software components together, the intent of copyleft licences is to say that the user should be able to take that (or part of it, in the case of "weak copyleft" licences) and change, recompile and distribute its sources, modified or not. Paul From kaklis at gmail.com Tue May 11 06:29:22 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 11 May 2010 03:29:22 -0700 (PDT) Subject: HTTP Post Request References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> <06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com> <95e73ff4-abe5-4874-8652-647818ed224a@k29g2000yqh.googlegroups.com> Message-ID: <2b94f35e-b3a0-49db-a66a-9ee1bf104a41@h20g2000prn.googlegroups.com> On May 11, 10:56?am, "kak... at gmail.com" wrote: > On May 11, 5:06?am, Kushal Kumaran > wrote: > > > > > On Mon, May 10, 2010 at 8:26 PM, kak... at gmail.com wrote: > > > On May 10, 10:22?am, Kushal Kumaran > > > wrote: > > >> On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com wrote: > > >> > Hi to all, i want to ask you a question, concerning the best way to do > > >> > the following as a POST request: > > >> > There is server-servlet that accepts xml commands > > >> > It had the following HTTP request headers: > > > >> > ? ? ? ? ? ?Host: somehost.com > > >> > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient > > >> > ? ? ? ? ? ?Content-Type: text/xml > > >> > ? ? ? ? ? ?Content-Length: 415 > > > >> > and the following request body (reformatted here for clarity): > > > >> > ? ? ? ? ? ? > > >> > ? ? ? ? ? ? > > >> > ? ? ? ? ? ? ?search > > >> > ? ? ? ? ? ? > > >> > How can i send the above to the Listener Servlet? > > >> > Thanks in advance > > > >> Use the xmlrpclib module. > > > > OK, sending headers with xmlrpclib, > > > but how do i send the XML message? > > > Your XML message is an XML RPC message. ?You will use xmlrpclib like this: > > > server_proxy = xmlrpclib.ServerProxy(('somehost.com', 80)) > > result = server_proxy.search() > > > The call to server_proxy.search will result in an actual XML RPC > > message being sent. > > > Read up on the xmlrpclib documentation here:http://docs.python.org/library/xmlrpclib.html, and the XMLRPC spec > > here:http://www.xmlrpc.com/spec > > > -- > > regards, > > kushal > > Ok I got it! > Thank you!!! > > A.K Apparently the server i'm trying to connect accepts only POST connections. So xmlrpclib is useless. I think I need the httplib library module. Any hints? A.K. From paul at boddie.org.uk Tue May 11 06:34:49 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 11 May 2010 03:34:49 -0700 (PDT) Subject: Picking a license References: <30aff350- <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> <9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com> <7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> Message-ID: On 10 Mai, 20:36, Patrick Maupin wrote: > > I've addressed this before. ?Aahz used a word in an accurate, but to > you, inflammatory, sense, but it's still accurate -- the man *would* > force you to pay for the chocolate if you took it. Yes, *if* you took it. He isn't forcing you to take it, though, is he? > You're making it sound like whining, but Aahz was simply trying to state a fact. It is whining if someone says, "I really want that chocolate, but that nasty man is going to make me pay for it!" >?The fact is, I know the man would force me to pay for the chocolate, so in > some cases that enters into the equation and keeps me from wanting the > chocolate. If the man said, "please take the chocolate, but I want you to share it with your friends", and you refused to do so because you couldn't accept that condition, would it be right to say, "that man is forcing me to share chocolate with my friends"? > ?This isn't whining; just a common-sense description of > reality. ?Personally, I think this use of the word "force" is much > less inflammatory than the deliberate act of co-opting the word > "freedom" to mean "if you think you can take this software and do > anything you want with it, you're going to find out differently when > we sue you." The word "freedom" means a number of things. If you don't like the way Messrs Finney and Stallman use the term, please take it up with them. But to say that someone entering a voluntary agreement is "forced" to do something, when they weren't forced into that agreement in the first place, is just nonsense. It's like saying that the shopkeeper is some kind of Darth Vader character who is coercing people to take the chocolate and then saddling them with obligations against their will. Paul From alt.mcarter at googlemail.com Tue May 11 06:40:03 2010 From: alt.mcarter at googlemail.com (Mark Carter) Date: Tue, 11 May 2010 03:40:03 -0700 (PDT) Subject: win32com sql update problem Message-ID: Consider the following snippet of code: import win32com.client DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=M:\\Finance\\camel\ \camel.mdb;' conn.Open(DSN) cursor = conn.Execute("UPDATE tblInvoice SET InvComments='Python' WHERE InvBillingPeriod = 'April 2010' AND InvJobCode = '2169'") rows = cursor.Affected_Rows() print rows conn.Close() I am using Python 2.6.5, and pywin32. If I try to run it, I get the response: Traceback (most recent call last): File "C:/Users/mcarter/tacc/pypms/post.py", line 79, in AdjustPms(d) File "C:/Users/mcarter/tacc/pypms/post.py", line 64, in AdjustPms cursor = conn.Execute("UPDATE tblInvoice SET InvComments='Python' WHERE InvBillingPeriod = 'April 2010' AND InvJobCode = '2169'") File "", line 3, in Execute File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 272, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft JET Database Engine', u"Cannot open database ''. It may not be a database that your application recognizes, or the file may be corrupt.", None, 5003049, -2147467259), None) I have used the same DNS to retrieve data from the database using SELECT statements, so I'm at a loss to figure out what's going wrong. It seems to think the database name as an empty string. I'm not sure if that's the root cause of the problem, though. Any ideas? From jeanmichel at sequans.com Tue May 11 06:54:49 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 11 May 2010 12:54:49 +0200 Subject: lame sphinx questions [Was: lame epydoc questions] In-Reply-To: <289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com> References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> <4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com> <289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com> Message-ID: <4BE93779.4030609@sequans.com> Phlip wrote: > On May 10, 1:51 pm, Phlip wrote: > >> On May 10, 1:39 pm, Chris Rebert wrote: >> >> >>> Sphinx is in vogue right now:http://sphinx.pocoo.org/ >>> > > Okay, we have ten thousand classes to document. How to add them all to > index.rst? > I remember trying using Sphinx for auto documented APIs, but it was not suitable at that time. You can include API docs generated from the code, but you still need to write the docs around. If I'm correct, Sphinx is one of the best tool to document public APIs. However to build internal documentation with everything from interfaces to implementations, epydoc is still the best, it builds everything with no additional writing, just press the button. JM From ldo at geek-central.gen.new_zealand Tue May 11 07:11:01 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 May 2010 23:11:01 +1200 Subject: Is Python a functional programming language? References: <7xvdavd4bq.fsf@ruckus.brouhaha.com> Message-ID: In message <7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Python is a pragmatic language from an imperative tradition ... I thought the opposite of ?functional? was ?procedural?, not ?imperative?. The opposite to the latter is ?declarative?. But (nearly) all procedural languages also have declarative constructs, not just imperative ones (certainly Python does). Presumably an ?imperative? language would not. From ldo at geek-central.gen.new_zealand Tue May 11 07:13:10 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 May 2010 23:13:10 +1200 Subject: Is Python a functional programming language? References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> Message-ID: In message , Stefan Behnel wrote: > But the beauty is that Python is multi-paradigm ... The trouble with ?multi-paradigm? is that it offends the zealots on all sides. It?s like saying that, to effect a compromise among multiple conflicting monotheistic religions, we should create a polytheistic amalgam of them. From steve at REMOVE-THIS-cybersource.com.au Tue May 11 07:18:07 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 May 2010 11:18:07 GMT Subject: Picking a license References: <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> <9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com> <7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> Message-ID: <4be93cee$0$27837$c3e8da3@news.astraweb.com> On Tue, 11 May 2010 03:34:49 -0700, Paul Boddie wrote: > It's like saying that the shopkeeper is some kind of Darth Vader > character who is coercing people to take the chocolate Last time I came home with chocolate, I tried that excuse on my wife. She didn't believe it for a second. Next time, I'll try claiming that I was obliged to eat the chocolate because of the GPL. -- Steven From stefan_ml at behnel.de Tue May 11 07:32:47 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 11 May 2010 13:32:47 +0200 Subject: Is Python a functional programming language? In-Reply-To: References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> Message-ID: Lawrence D'Oliveiro, 11.05.2010 13:13: > Stefan Behnel wrote: > >> But the beauty is that Python is multi-paradigm ... > > The trouble with ?multi-paradigm? is that it offends the zealots on all > sides. It?s like saying that, to effect a compromise among multiple > conflicting monotheistic religions, we should create a polytheistic amalgam > of them. The Romans were pretty successful in doing so, for several hundred years. Let's see if Python will conquer and rule for that long. Stefan From jayeola at gmail.com Tue May 11 07:41:12 2010 From: jayeola at gmail.com (John Maclean) Date: Tue, 11 May 2010 12:41:12 +0100 Subject: unittest basics Message-ID: <4BE94258.7010409@gmail.com> is there a way to test that a certian library or module is or can be loaded successfully? self.assert('import blah') -- John Maclean MSc. (DIC) BSc. (Hons) Linux Systems and Applications 07739 171 531 From richard.lamboj at bilcom.at Tue May 11 07:51:46 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Tue, 11 May 2010 13:51:46 +0200 Subject: inherit from data type In-Reply-To: <26lnb7-t6g.ln1@satorlaser.homedns.org> References: <26lnb7-t6g.ln1@satorlaser.homedns.org> Message-ID: <201005111351.46892.richard.lamboj@bilcom.at> Am Tuesday 11 May 2010 11:38:42 schrieb Ulrich Eckhardt: > Richard Lamboj wrote: > > "How knows python that it is a float, or a string?" Sorry this was bad > > expressed. I want to create a new data type, which inherits from float. I > > just know the "dir" function and the "help" function to get more > > infromations about the class, but i need to get more information about > > the class structure. > > I'd suggest the tutorial, see http://docs.python.org, though your question > is already beyond the range of beginners' questions. > > > What i also want to know: > >>>> variable1 = 10.50 > >>>> type(variable1) > > > > > > > > Is there a way to tell python that it use antoher class than float for > > float, like myfloat? Its just a "tell-me-what-is-possible". > > > > Sample: > >>>> variable1 = 10.50 > >>>> type(variable1) > > > > > > The expression "10.5" will always be a float, you can't change that. What > > you can do is create your own type, derived from float: > >>> class myfloat(float): > > ... pass > ... > > and then create an object of that type: > >>> x = myfloat(3.14) > >>> type(x) > > > > > > Lastly one warning: In many cases where people wanted to derive from a > concrete data type, their problems were easier solved by external code. I > don't know your problem though. > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 I just want to test what is possible with python and what not. There is no problem that i need to solve. This is what i'am searching for: http://docs.python.org/reference/datamodel.html Last year i have stopped programming python, but now i'am back with a big black hole in my brain and i want to understand what the interpreter is doing in the background. I think my question was not well formulated... Kind Regards From g.rodola at gmail.com Tue May 11 08:03:58 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Tue, 11 May 2010 14:03:58 +0200 Subject: unittest basics In-Reply-To: <4BE94258.7010409@gmail.com> References: <4BE94258.7010409@gmail.com> Message-ID: There's no reason for such a thing. You can just make "import module" in your test and if something goes wrong that will be treated as any other test failure. --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil 2010/5/11 John Maclean : > is there a way to test that a certian library or module is or can be loaded > successfully? > > self.assert('import blah') > > -- > John Maclean > MSc. (DIC) BSc. (Hons) > Linux Systems and Applications > 07739 171 531 > -- > http://mail.python.org/mailman/listinfo/python-list > From aurelien.gourrier at yahoo.fr Tue May 11 08:04:18 2010 From: aurelien.gourrier at yahoo.fr (=?iso-8859-1?Q?Aur=E9_Gourrier?=) Date: Tue, 11 May 2010 12:04:18 +0000 (GMT) Subject: how to import a module for global use in a library package ? Message-ID: <577270.86860.qm@web23105.mail.ird.yahoo.com> Dear all, I am building a library package of the form: rootlib ---__init__ ---subpackage1 ------__init__ ------sub1module1 ------sub1module2 ------... ---subpackage2 ------ __init__ ------sub2module1 ------sub2module2 ------... My rootlib.__init__ file contains: __name__ = ... __version__ = ... __author__ = ... __author_email__= ... __url__ = ... __description__ = ... import subpackage1 import subpackage2 __all__ = [] __all__.extend(['subpackage1','subpackage2']) My question is the following: I need to import an external package, say numpy, for use in various submodules. So far, I simply do an import numpy as _numpy where needed, say sub1module1 and sub2module2. This means that I import this package a number of times which doesn't seem to be a logical thing to do (?). In the end, I would like to make this module a "global" module for my library. I would find it more practical to simply do this import in the __init__ of rootlib and then use it directly in the submodules as rootlib._numpy calls, but I'm not sure exactly how to do this because it would mean that I would have to do an import rootlib in my subpackages which doesn't sound so good... Can anyone give me a hint ? Cheers, Aur? -------------- next part -------------- An HTML attachment was scrubbed... URL: From e_d_k at yahoo.com Tue May 11 08:12:23 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 11 May 2010 05:12:23 -0700 (PDT) Subject: Picking a license In-Reply-To: <87vdavck7a.fsf@benfinney.id.au> Message-ID: <388056.46566.qm@web58704.mail.re1.yahoo.com> --- On Mon, 5/10/10, Ben Finney wrote: > So I object to muddying the issue by misrepresenting the > source of that > force. Whatever force there is in copyright comes from law, > not any free > software license. You are the one muddying the waters. It does not mater whether you break my kneecaps, or hire someone else to break my kneecaps, either way my kneecaps are broken. You can use any license you want, but the simple fact is that if there are fewer restrictions in the license then the user has more freedom in how he uses the licensed code. If there are more restrictions he/she has less freedom in how he/she uses the licensed code. We can debate which is better (whether a man should be free to sell himself into slavery) but to claim that putting more restrictions on someone give them more freedom is pure Orwellian double speak. Sophistry is the last resort of those who have run out of good arguments. The more you engage in it the weaker you make your position. This thread is generating more heat than light, and probably should be dropped. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From jeanmichel at sequans.com Tue May 11 08:30:32 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 11 May 2010 14:30:32 +0200 Subject: how to import a module for global use in a library package ? In-Reply-To: <577270.86860.qm@web23105.mail.ird.yahoo.com> References: <577270.86860.qm@web23105.mail.ird.yahoo.com> Message-ID: <4BE94DE8.3000301@sequans.com> Aur? Gourrier wrote: > [snip] > My question is the following: I need to import an external package, > say numpy, for use in various submodules. So far, I simply do an > import numpy as _numpy where needed, say sub1module1 and sub2module2. > This means that I import this package a number of times which doesn't > seem to be a logical thing to do (?). No problem at all. You need numpy in a file, then import numpy at the very beginning of the file. You have 100 files requiring numpy? you'll end up with 100 'import numpy' statements, but who cares ? This is perfectly logic and pythonic in the way it is explicit. You could reference numpy as member of you rootlib package, but any call of numpy methods will be prefixed by rootlib.numpy, and you still need a import rootlib (circular imports since rootlib is importing your submodules !) JM > Aur? > > From guillermo.listas at googlemail.com Tue May 11 08:33:51 2010 From: guillermo.listas at googlemail.com (Guillermo) Date: Tue, 11 May 2010 05:33:51 -0700 (PDT) Subject: virtualenvwrapper for Windows (Powershell) References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com> Message-ID: <973ca0fa-4a2f-4e3b-91b9-e38917885c0f@d27g2000yqc.googlegroups.com> On May 11, 7:43?am, Lawrence D'Oliveiro wrote: > In message > <22cf35af-44d1-43fe-8b90-07f2c6545... at i10g2000yqh.googlegroups.com>, > > Guillermo wrote: > > If you've ever missed it on Windows and you can use Powershell ... > > I thought the whole point of Windows was to get away from this command-line > stuff. Not such a good idea after all? I suppose it depends. From chris at simplistix.co.uk Tue May 11 08:40:35 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 11 May 2010 13:40:35 +0100 Subject: unittest basics In-Reply-To: <4BE94258.7010409@gmail.com> References: <4BE94258.7010409@gmail.com> Message-ID: <4BE95043.8030201@simplistix.co.uk> import unittest class MyTestCase(unittest.TestCase): def test_my_import(self): import blah cheers, Chris John Maclean wrote: > is there a way to test that a certian library or module is or can be > loaded successfully? > > self.assert('import blah') > -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From mhv at dmu.dk Tue May 11 08:54:06 2010 From: mhv at dmu.dk (Hvidberg, Martin) Date: Tue, 11 May 2010 14:54:06 +0200 Subject: reading xml from python Message-ID: I'm looking for at way to read (and later write) small simple .xml file from Python. e.g. I would like to read the following from a small ini.xml file into a dictionary. default False False UBMlight True I would prefer a relative simple (not too much creating new classes) way to do this. Any suggestions appreciated. :-) Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: From drobinow at gmail.com Tue May 11 08:59:37 2010 From: drobinow at gmail.com (David Robinow) Date: Tue, 11 May 2010 08:59:37 -0400 Subject: virtualenvwrapper for Windows (Powershell) In-Reply-To: References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com> Message-ID: On Tue, May 11, 2010 at 1:43 AM, Lawrence D'Oliveiro wrote: > In message > <22cf35af-44d1-43fe-8b90-07f2c6545f63 at i10g2000yqh.googlegroups.com>, > Guillermo wrote: >> If you've ever missed it on Windows and you can use Powershell ... > I thought the whole point of Windows was to get away from this command-line > stuff. Not such a good idea after all? The whole point of Windows was to make money for Microsoft. Microsoft can be criticized for many things but a mindless devotion to principle is not one of them. From lie.1296 at gmail.com Tue May 11 09:00:22 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 11 May 2010 23:00:22 +1000 Subject: Picking a license In-Reply-To: <3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> References: <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> <3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> Message-ID: <4be95545$1@dnews.tpgi.com.au> On 05/11/10 20:24, Paul Boddie wrote: > On 10 Mai, 17:01, Patrick Maupin wrote: >> >> I'll be charitable and assume the fact that you can make that >> statement without apparent guile merely means that you haven't read >> the post I was referring to: >> >> http://www.gnu.org/philosophy/why-not-lgpl.html > > Of course I have read it, and not just recently either. But this is a > position paper by the author of the licence, and it doesn't mean that > someone who has written a GPL-licensed library completely agrees with > that position. And anyway, it's a case of "take it or leave it" - it's > not like the author or the FSF are sneaking stuff into every product > and every corner of the market and then telling you that you can't > "unchoose" their stuff. Come on, 99% of the projects released under GPL did so because they don't want to learn much about the law; they just need to release it under a certain license so their users have some legal certainty. Most programmers are not lawyers and don't care about the law and don't care about the GPL; if a commercial programmer want to use the GPL-code in an incompatible licensed program, and he comes up asking, many would just be happy to say yes. Most people release their code in GPL just because it's popular, not for the exact clauses in it. Heck, many people that releases code in GPL might not actually have read the full license. Only big GPL projects have the resources to waste on a lawyer. And only very big projects have the resources to waste on enforcing the license they uses. The rest of us just don't care. From clp2 at rebertia.com Tue May 11 09:17:07 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 11 May 2010 06:17:07 -0700 Subject: reading xml from python In-Reply-To: References: Message-ID: On Tue, May 11, 2010 at 5:54 AM, Hvidberg, Martin wrote: > I'm looking for at way to read (and later write) small simple .xml file from > Python. > > e.g. I would like to read the following?from a small ini.xml file into a > dictionary. > > > > > ?default > ?False > ?False > ?UBMlight > ?True > > > I would prefer a relative simple (not too much creating new classes) way to > do this. from xml.etree.ElementTree import ElementTree tree = ElementTree() tree.parse("ini.xml") as_dictionary = dict((child.tag, child.text) for child in tree.getchildren()) Writing is left as an exercise for another poster. Cheers, Chris -- http://blog.rebertia.com From philip at semanchuk.com Tue May 11 09:17:48 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 11 May 2010 09:17:48 -0400 Subject: reading xml from python In-Reply-To: References: Message-ID: <549D0765-9DD8-4816-BEE2-5C77101CB49C@semanchuk.com> On May 11, 2010, at 8:54 AM, Hvidberg, Martin wrote: > I'm looking for at way to read (and later write) small simple .xml > file from Python. > > e.g. I would like to read the following from a small ini.xml file > into a dictionary. > > > > default > False > False > UBMlight > True > > I would prefer a relative simple (not too much creating new classes) > way to do this. > > Any suggestions appreciated. Hej Martin, Did you look in the standard library? ElementTree in the XML section of the standard library will do what you want. There are several other choices there if you don't like that. bye Philip From dkgispam at gmail.com Tue May 11 09:22:29 2010 From: dkgispam at gmail.com (Dominik Gabi) Date: Tue, 11 May 2010 06:22:29 -0700 (PDT) Subject: urllib.urlopen blocking? Message-ID: Hi, I'm new to python and have been playing around with it for a few days now. So please forgive me if this is a stupid question :) I've tried writing a little application with pygtk and urllib. When a button is clicked I create a new thread that opens an URL with urllib. The new thread is running but as soon as I call urllib.urlopen("https://someurl", postdata) it blocks. It blocks until I do something in the interface (e.g. click another button). I've obviously missed something here. The interface should not interfere with anything that runs in an other thread!? Here are a few extracts from my code: def send_message(self, widget, data=None): # This is called when the button is clicked ... threading.Thread(target=message.send).start() ... def send(self): # This is executed in its own thread ... postdata = urllib.urlencode(data) # This line is the last one executed resp = urllib.urlopen('https://theurl', postdata) Regards, Dominik. From phlip2005 at gmail.com Tue May 11 09:27:18 2010 From: phlip2005 at gmail.com (Phlip) Date: Tue, 11 May 2010 06:27:18 -0700 (PDT) Subject: lame sphinx questions [Was: lame epydoc questions] References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> <4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com> <289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com> Message-ID: <656fab1f-2cb7-433e-84ba-ffebbc118dde@t26g2000prt.googlegroups.com> On May 11, 3:54?am, Jean-Michel Pichavant wrote: > I remember trying using Sphinx for auto documented APIs, but it was not > suitable at that time. You can include API docs generated from the code, > but you still need to write the docs around. > If I'm correct, ?Sphinx is one of the best tool to document public APIs. > However to build internal documentation with everything from interfaces > to implementations, epydoc is still the best, it builds everything with > no additional writing, just press the button. Ah, thanks. We are all about writing '''doc strings''', then ripping them to form documentation that we DO intend someone to READ and USE! Now the problem with epydoc is it uses a persnickety text markup language that... - throws a syntax error & reverts to
 when the wind blows
 - demands all kinds of extra markup, such as @param
 - uses >3 different kinds of escapes, @, L{}, & 
 - has no developer tests to speak of

I'm all about cross-linking and transcluding, and I wanted to upgrade
epydoc to do it, so I need to make sure that all those issues are
going to be either worth our time to fix or work around, and I didn't
overlook some better system.


From solipsis at pitrou.net  Tue May 11 09:54:57 2010
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Tue, 11 May 2010 15:54:57 +0200
Subject: urllib.urlopen blocking?
References: 
Message-ID: <20100511155457.2ecfa366@pitrou.net>

On Tue, 11 May 2010 06:22:29 -0700 (PDT)
Dominik Gabi  wrote:
> 
> I'm new to python and have been playing around with it for a few days
> now. So please forgive me if this is a stupid question :)
> 
> I've tried writing a little application with pygtk and urllib.

For the record, have you tried calling gobject.threads_init() at the
beginning of your application (just after importing all modules)?




From aahz at pythoncraft.com  Tue May 11 09:55:13 2010
From: aahz at pythoncraft.com (Aahz)
Date: 11 May 2010 06:55:13 -0700
Subject: Extract all words that begin with x
References: 
	
	
	
Message-ID: 

In article ,
Terry Reedy   wrote:
>On 5/10/2010 5:35 AM, James Mills wrote:
>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho  wrote:
>>> Have I missed something, or wouldn't this work just as well:
>>>
>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>> ['awes', 'asdgas']
>>
>> I would do this for completeness (just in case):
>>
>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>
>> Just guards against empty strings which may or may not be in the list.
>
>  ... word[0:1] does the same thing. All Python programmers should learn 
>to use slicing to extract a  char from a string that might be empty.
>The method call of .startswith() will be slower, I am sure.

And if it is slower, so what?  Using startswith() makes for faster
reading of the code for me, and I'm sure I'm not the only one.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From paul at boddie.org.uk  Tue May 11 10:00:16 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Tue, 11 May 2010 07:00:16 -0700 (PDT)
Subject: Picking a license
References: 
	<4be5bdcb$0$27798$c3e8da3@news.astraweb.com> 
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> 
	 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<4be95545$1@dnews.tpgi.com.au>
Message-ID: 

On 11 Mai, 15:00, Lie Ryan  wrote:
>
> Come on, 99% ?of the projects released under GPL did so because they
> don't want to learn much about the law; they just need to release it
> under a certain license so their users have some legal certainty.

Yes, this is frequently the case. And the GPL does offer some
certainty that various permissive licences do not.

> Most programmers are not lawyers and don't care about the law and don't care
> about the GPL; if a commercial programmer want to use the GPL-code in an
> incompatible licensed program, and he comes up asking, many would just
> be happy to say yes.

Yes, quite possibly. I did mention this myself elsewhere.

> Most people release their code in GPL just because it's popular, not for
> the exact clauses in it. Heck, many people that releases code in GPL
> might not actually have read the full license.

Yes, this is also probably the case for a number of people. Although
many probably understand the principles of the licence and feel that
it represents their wishes most accurately.

> Only big GPL projects have the resources to waste on a lawyer. And only
> very big projects have the resources to waste on enforcing the license
> they uses. The rest of us just don't care.

Well, that's always an option as well, but at the same time, there are
people willing to pursue licence violations, and these people have
done so successfully. There's no need to make an impassioned argument
for apathy, though. Some people do wish to dictate what others can do
with their work.

Or are you trying to make another point here? That people would choose
something other than the GPL if only they "knew better", perhaps?
Since the FSF goes out of its way to list lots of Free Software
licences, GPL-compatible or otherwise, and those other licences aren't
exactly secret anyway, I hardly think there's a conspiracy at work.

Paul


From jeanmichel at sequans.com  Tue May 11 10:04:19 2010
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Tue, 11 May 2010 16:04:19 +0200
Subject: lame sphinx questions [Was: lame epydoc questions]
In-Reply-To: <656fab1f-2cb7-433e-84ba-ffebbc118dde@t26g2000prt.googlegroups.com>
References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com>
		<4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com>	<289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com>
	
	<656fab1f-2cb7-433e-84ba-ffebbc118dde@t26g2000prt.googlegroups.com>
Message-ID: <4BE963E3.3040609@sequans.com>

Phlip wrote:
> On May 11, 3:54 am, Jean-Michel Pichavant 
> wrote:
>
>   
>> I remember trying using Sphinx for auto documented APIs, but it was not
>> suitable at that time. You can include API docs generated from the code,
>> but you still need to write the docs around.
>> If I'm correct,  Sphinx is one of the best tool to document public APIs.
>> However to build internal documentation with everything from interfaces
>> to implementations, epydoc is still the best, it builds everything with
>> no additional writing, just press the button.
>>     
>
> Ah, thanks. We are all about writing '''doc strings''', then ripping
> them to form documentation that we DO intend someone to READ and USE!
>   
> Now the problem with epydoc is it uses a persnickety text markup
> language that...
>
>  - throws a syntax error & reverts to 
 when the wind blows
>  - demands all kinds of extra markup, such as @param
>  - uses >3 different kinds of escapes, @, L{}, & 
>  - has no developer tests to speak of
>
> I'm all about cross-linking and transcluding, and I wanted to upgrade
> epydoc to do it, so I need to make sure that all those issues are
> going to be either worth our time to fix or work around, and I didn't
> overlook some better system.
>   
epydoc supports reStructured text markups. AFAIK it's still the best doc 
builder available for python code. Too bad it is not maintained since 2 
years and the 3.0 release.
If there was any effort to provide however, I think it would be on 
sphinx so it would allow building the complete doc from python code. As 
written in the doc, it's currently half-automated.

JM


From dkgispam at gmail.com  Tue May 11 10:35:52 2010
From: dkgispam at gmail.com (Dominik Gabi)
Date: Tue, 11 May 2010 07:35:52 -0700 (PDT)
Subject: urllib.urlopen blocking?
References: 
	
Message-ID: 

> For the record, have you tried calling gobject.threads_init() at the
> beginning of your application (just after importing all modules)?

I haven't... now it works, thanks :) Any tips on how to avoid mistakes
like that in the future? I'm somewhat confused as to how I was
supposed to get this out of the documentation...


From no.email at nospam.invalid  Tue May 11 10:36:30 2010
From: no.email at nospam.invalid (Paul Rubin)
Date: Tue, 11 May 2010 07:36:30 -0700
Subject: Is Python a functional programming language?
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
Message-ID: <7xvdau8pzl.fsf@ruckus.brouhaha.com>

Lawrence D'Oliveiro  writes:
> I thought the opposite of ?functional? was ?procedural?, not ?imperative?. 
> The opposite to the latter is ?declarative?. But (nearly) all procedural 
> languages also have declarative constructs, not just imperative ones 
> (certainly Python does). Presumably an ?imperative? language would not.

Offhand I can't tell that imperative and procedural mean something
different.  Both basically mean that the programmer specifies a series
of steps for the computer to carry out.  Functional languages are mostly
declarative; for example, an expression like
   x = 3
is called an "equation" rather than an "assignment".  It declares "x is
equal to 3", rather than directing x to be set to 3.  If someplace else
in the program you say "x = 4", that is an error, normally caught by
the compiler, since x cannot be equal to both 3 and 4.


From python at bdurham.com  Tue May 11 10:37:01 2010
From: python at bdurham.com (python at bdurham.com)
Date: Tue, 11 May 2010 10:37:01 -0400
Subject: Slice last char from string without raising exception on empty string
	(Re: Extract all words that begin with x)
In-Reply-To: 
References: 
	
Message-ID: <1273588621.1629.1374510539@webmail.messagingengine.com>

Terry,

>  ... word[0:1] does the same thing. All Python programmers should learn to use slicing to extract a char from a string that might be empty.

Is there an equivalent way to slice the last char from a string (similar
to an .endswith) that doesn't raise an exception when a string is empty?

Thanks,
Malcolm


From jim.vickroy at noaa.gov  Tue May 11 10:46:17 2010
From: jim.vickroy at noaa.gov (j vickroy)
Date: Tue, 11 May 2010 08:46:17 -0600
Subject: unable to get Hudson to run unit tests
In-Reply-To: 
References: 		<4BE80A78.2030502@noaa.gov>		<4BE828A2.2070106@noaa.gov>
	
Message-ID: <4BE96DB9.7040303@noaa.gov>

Thanks again, Stefan.  My comments are below.

Stefan Behnel wrote:
> j vickroy, 10.05.2010 17:39:
>> Unfortunately, when "Hudson Build now" is performed, the Hudson Console
>> output, for this job, is:
>>
>> ------------------------------------------------------------
>> Started by user anonymous
>> Updating svn://vm-svn/GOES data 
>> processing/trunk/GOES/13,14,15/SXI/level-1
>> At revision 3403
>> no change for svn://vm-svn/GOES data
>> processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build
>> [workspace] $ python.exe
>> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson5273111667332806239.sh
>> os.getcwd(): C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES
>> 13-15 SXI Level-1 Products Generation\workspace
>> os.listdir(os.getcwd()): ['level-1']
>> [workspace] $ cmd.exe -xe
>> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson991194264891924641.sh
>> Microsoft Windows XP [Version 5.1.2600]
>> (C) Copyright 1985-2001 Microsoft Corp.
>>
>> C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI
>> Level-1 Products Generation\workspace>Recording test results
>> No test report files were found. Configuration error?
>> Finished: FAILURE
>> ------------------------------------------------------------
>>
>> The second [workspace] section output (above) looks like cmd.exe is
>> being executed with no parameters (i.e., without the
>> "nosetests.exe --where=level-1 --with-xunit --verbose") parameter.
> 
> No, what Hudson actually does, is, it writes your command(s) into a text 
> file and runs it with the system's shell interpreter (which, unless 
> otherwise configured, is "cmd.exe" on Windows). 

This is not the behavior I am experiencing on my Windows XP Pro (Service 
Pack 3) workstation.

If I do not specify "C:\WINDOWS\system32\cmd.exe" for "Manage Hudson | 
Configuration System | Shell | Shell executable", the "Console output" 
after a "Build now" is:

-----------------------------------------------------
Started by user anonymous
Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1
At revision 3417
no change for svn://vm-svn/GOES data 
processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build
[workspace] $ sh -xe 
C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson869574722591302824.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: Cannot run program "sh" (in directory "C:\Documents 
and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products 
Generation\workspace"): CreateProcess error=2, The system cannot find 
the file specified
	at java.lang.ProcessBuilder.start(Unknown Source)
	at hudson.Proc$LocalProc.(Proc.java:149)
	at hudson.Proc$LocalProc.(Proc.java:121)
	at hudson.Launcher$LocalLauncher.launch(Launcher.java:636)
	at hudson.Launcher$ProcStarter.start(Launcher.java:271)
	at hudson.Launcher$ProcStarter.join(Launcher.java:278)
	at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:83)
	at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:58)
	at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:19)
	at 
hudson.model.AbstractBuild$AbstractRunner.perform(AbstractBuild.java:584)
	at hudson.model.Build$RunnerImpl.build(Build.java:174)
	at hudson.model.Build$RunnerImpl.doRun(Build.java:138)
	at hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:416)
	at hudson.model.Run.run(Run.java:1244)
	at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
	at hudson.model.ResourceController.execute(ResourceController.java:88)
	at hudson.model.Executor.run(Executor.java:122)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot 
find the file specified
	at java.lang.ProcessImpl.create(Native Method)
	at java.lang.ProcessImpl.(Unknown Source)
	at java.lang.ProcessImpl.start(Unknown Source)
	... 17 more
Recording test results
Finished: FAILURE
-----------------------------------------------------

Note Hudson is looking for "sh".

This assures the highest
> possible compatibility with the executed script. You can even use the 
> shebang in Hudson's scripts that way, so that you can execute scripts in 
> basically any scripting language.
> 
> The likely reason why it doesn't find your test results is that you 
> didn't tell it where to look. 

Actually, Hudson is not finding the tests results because they are not 
being generated.  There is no "nosetests.xml" file anywhere on my hard 
drive (except in the Recycle Bin from my explicit executions of the 
"nosetests.exe --where=level-1 --with-xunit --verbose" command).  This 
is why I thought Hudson was not executing the above nosetests.exe 
command (specified in "*job* | Configure | Build | Execute shell | command".


Put a wildcard path into the unit test
> config box that finds the XML files that nosetest writes. It's also best 
> to tell nosetest where to put them explicitly using a command line option.
> 
> Stefan
> 

Thanks again for your continued interest.  I quickly got Hudson to 
retrieve job source from our subversion repository so I thought it would 
be equally easy to get Hudson to run the unit tests, but that has proven 
to be difficult, and so far I do not know how to diagnose this since it 
seems there is no way to prevent Hudson from immediately deleting the 
temporary scripts it generates.


From michele.simionato at gmail.com  Tue May 11 10:49:55 2010
From: michele.simionato at gmail.com (Michele Simionato)
Date: Tue, 11 May 2010 07:49:55 -0700 (PDT)
Subject: Is Python a functional programming language?
References:  
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
Message-ID: 

On May 10, 8:18?pm, a... at pythoncraft.com (Aahz) wrote:
> saying that functional features
> are "tacked on" understates the case. ?Consider how frequently people
> reach for list comps and gen exps. ?Function dispatch through dicts is
> the standard replacement for a switch statement. ?Lambda callbacks are
> common. ?Etc, etc, etc

Just to play devil's advocate, I will notice that list comps and gen
exps are not really
functional (a generator has a state that changes at each call of
next). A functional language
would use streams instead. Function dispatch through dicts is very
lame compared to pattern matching. Lambdas are restricted. There is no
tail call optimization. Definitively Python functional features are
"tacked on" with respect to a language defined to be functional.
Having said that, the functional features are still usable and one can
use a functional style
in Python if she wants to (module a few caveats).


From solipsis at pitrou.net  Tue May 11 10:55:43 2010
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Tue, 11 May 2010 16:55:43 +0200
Subject: urllib.urlopen blocking?
References: 
	
	
Message-ID: <20100511165543.4a1d64f4@pitrou.net>

On Tue, 11 May 2010 07:35:52 -0700 (PDT)
Dominik Gabi  wrote:

> > For the record, have you tried calling gobject.threads_init() at the
> > beginning of your application (just after importing all modules)?
> 
> I haven't... now it works, thanks :) Any tips on how to avoid mistakes
> like that in the future? I'm somewhat confused as to how I was
> supposed to get this out of the documentation...

I'm afraid I don't know the answer. I'm not a pygtk expert at all, I
just remember that I had to do that in one of my applications long ago,
otherwise pygtk doesn't support Python threads properly.

Regards

Antoine.




From utente at esempio.net  Tue May 11 11:03:58 2010
From: utente at esempio.net (superpollo)
Date: Tue, 11 May 2010 17:03:58 +0200
Subject: Extract all words that begin with x
In-Reply-To: 
References: 
	
	
	
	
Message-ID: <4be971de$0$18659$4fafbaef@reader3.news.tin.it>

Aahz ha scritto:
> In article ,
> Terry Reedy   wrote:
>> On 5/10/2010 5:35 AM, James Mills wrote:
>>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho  wrote:
>>>> Have I missed something, or wouldn't this work just as well:
>>>>
>>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>> ['awes', 'asdgas']
>>> I would do this for completeness (just in case):
>>>
>>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>> Just guards against empty strings which may or may not be in the list.
>>  ... word[0:1] does the same thing. All Python programmers should learn 
>> to use slicing to extract a  char from a string that might be empty.
>> The method call of .startswith() will be slower, I am sure.
> 
> And if it is slower, so what?  Using startswith() makes for faster
> reading of the code for me, and I'm sure I'm not the only one.

also, what if the OP intended "words that begin with x" with x a string 
(as opposed to a single character) ?

then startswith is the solution methinks...

bye


From eckhardt at satorlaser.com  Tue May 11 11:08:02 2010
From: eckhardt at satorlaser.com (Ulrich Eckhardt)
Date: Tue, 11 May 2010 17:08:02 +0200
Subject: Iterating over dict and removing some elements
Message-ID: 

Hi!

I wrote a simple loop like this:

  d = {}
  ...
  for k in d:
      if some_condition(d[k]):
          d.pop(k)

If I run this, Python complains that the dictionary size changed during
iteration. I understand that the iterator relies on the internal structure
not changing, but how would I structure this loop otherwise?

My first approach was to simply postpone removing the elements, but I was
wondering if there was a more elegant solution.

Thanks!

Uli

-- 
Sator Laser GmbH
Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932



From stefan_ml at behnel.de  Tue May 11 11:11:50 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Tue, 11 May 2010 17:11:50 +0200
Subject: unable to get Hudson to run unit tests
In-Reply-To: <4BE96DB9.7040303@noaa.gov>
References: 		<4BE80A78.2030502@noaa.gov>		<4BE828A2.2070106@noaa.gov>	
	<4BE96DB9.7040303@noaa.gov>
Message-ID: 

j vickroy, 11.05.2010 16:46:
 > Stefan Behnel wrote:
>> No, what Hudson actually does, is, it writes your command(s) into a
>> text file and runs it with the system's shell interpreter (which,
>> unless otherwise configured, is "cmd.exe" on Windows).
>
> This is not the behavior I am experiencing on my Windows XP Pro (Service
> Pack 3) workstation.

Then setting the "Shell executable" to "cmd.exe" will do the right thing here.


>> This assures the highest
>> possible compatibility with the executed script. You can even use the
>> shebang in Hudson's scripts that way, so that you can execute scripts
>> in basically any scripting language.

... although the shebang isn't really supported by cmd.exe, I guess ...


>> The likely reason why it doesn't find your test results is that you
>> didn't tell it where to look.
>
> Actually, Hudson is not finding the tests results because they are not
> being generated. There is no "nosetests.xml" file anywhere on my hard
> drive

That's why I told you to configure nosetest to use an specific output path 
for the unit test file.


> Thanks again for your continued interest. I quickly got Hudson to
> retrieve job source from our subversion repository so I thought it would
> be equally easy to get Hudson to run the unit tests, but that has proven
> to be difficult, and so far I do not know how to diagnose this since it
> seems there is no way to prevent Hudson from immediately deleting the
> temporary scripts it generates.

Which is ok, since it prints what it does during the script execution, and 
the scripts contain nothing more than what you typed in.

Does nosetest produce an XML file when you call it manually from the 
command line? Is nosetest.exe in your PATH, so that the cmd.exe that Hudson 
starts can find it?

Personally, I'd always step into the target directory before running a 
command, so I'd make the script

     cd level-1
     nosetest.exe ...

Stefan



From utente at esempio.net  Tue May 11 11:13:50 2010
From: utente at esempio.net (superpollo)
Date: Tue, 11 May 2010 17:13:50 +0200
Subject: Slice last char from string without raising exception on empty
	string (Re: Extract all words that begin with x)
In-Reply-To: 
References: 	
	
Message-ID: <4be9742f$0$18659$4fafbaef@reader3.news.tin.it>

python at bdurham.com ha scritto:
> Terry,
> 
>>  ... word[0:1] does the same thing. All Python programmers should learn to use slicing to extract a char from a string that might be empty.
> 
> Is there an equivalent way to slice the last char from a string (similar
> to an .endswith) that doesn't raise an exception when a string is empty?
> 

could it be:

word[len(word)-1:] ?


From utente at esempio.net  Tue May 11 11:16:31 2010
From: utente at esempio.net (superpollo)
Date: Tue, 11 May 2010 17:16:31 +0200
Subject: Iterating over dict and removing some elements
In-Reply-To: 
References: 
Message-ID: <4be974cf$0$18659$4fafbaef@reader3.news.tin.it>

Ulrich Eckhardt ha scritto:
> Hi!
> 
> I wrote a simple loop like this:
> 
>   d = {}
>   ...
>   for k in d:
>       if some_condition(d[k]):
>           d.pop(k)
> 
> If I run this, Python complains that the dictionary size changed during
> iteration. I understand that the iterator relies on the internal structure
> not changing, but how would I structure this loop otherwise?

my first thought (untested):

use a copy of d for the if clause, then pop from the original.

bye


From michele.simionato at gmail.com  Tue May 11 11:21:07 2010
From: michele.simionato at gmail.com (Michele Simionato)
Date: Tue, 11 May 2010 08:21:07 -0700 (PDT)
Subject: Iterating over dict and removing some elements
References: 
	<4be974cf$0$18659$4fafbaef@reader3.news.tin.it>
Message-ID: 

Or you copy the whole dictionary or you just copy the keys:

for k in d.keys():
    ...

or

for k in list(d):
    ...


From peter_peyman_puk at yahoo.ca  Tue May 11 11:21:56 2010
From: peter_peyman_puk at yahoo.ca (Peyman Askari)
Date: Tue, 11 May 2010 08:21:56 -0700 (PDT)
Subject: PyMPI comm.gather problem
Message-ID: <180709.12854.qm@web43407.mail.sp1.yahoo.com>

Hi

I have run into a serious problem with PyMPI (Python bindings for the Message Passing Interface). Unfortunately I can not provide any example code as it is a massive program (38,000+ lines) and it is very difficult to break the program down due to multiple inheritance.

When I run the program (on multiple nodes), there is a linear increase in time per iteration. Every 1,500 iterations, it gains a tenth of a second per iteration. I timed different regions of my code which were engaged in messaging (broadcasting and gathering) and I found the increase to be in a gather statement, much like so

IO_list=self.comm.gather(IO,root=0)

each iteration this single command requires more and more time to pass information. I checked the size of IO being sent from every node (including root node) and it always remains constant. I also checked the size of the IO_list, and it too is always constant. Furthermore, I added a sleep(5) command before the line to make sure it was not a synchronization issue. 

Has anyone got any possible ideas as to what could possibly be going wrong? 

Cheers


Peyman Askari



-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From jim.vickroy at noaa.gov  Tue May 11 11:26:22 2010
From: jim.vickroy at noaa.gov (j vickroy)
Date: Tue, 11 May 2010 09:26:22 -0600
Subject: unable to get Hudson to run unit tests
In-Reply-To: 
References: 		<4BE80A78.2030502@noaa.gov>		<4BE828A2.2070106@noaa.gov>		<4BE96DB9.7040303@noaa.gov>
	
Message-ID: <4BE9771E.1040909@noaa.gov>

Stefan Behnel wrote:
> j vickroy, 11.05.2010 16:46:
>  > Stefan Behnel wrote:
>>> No, what Hudson actually does, is, it writes your command(s) into a
>>> text file and runs it with the system's shell interpreter (which,
>>> unless otherwise configured, is "cmd.exe" on Windows).
>>
>> This is not the behavior I am experiencing on my Windows XP Pro (Service
>> Pack 3) workstation.
> 
> Then setting the "Shell executable" to "cmd.exe" will do the right thing 
> here.
> 
> 
>>> This assures the highest
>>> possible compatibility with the executed script. You can even use the
>>> shebang in Hudson's scripts that way, so that you can execute scripts
>>> in basically any scripting language.
> 
> ... although the shebang isn't really supported by cmd.exe, I guess ...
> 
> 
>>> The likely reason why it doesn't find your test results is that you
>>> didn't tell it where to look.
>>
>> Actually, Hudson is not finding the tests results because they are not
>> being generated. There is no "nosetests.xml" file anywhere on my hard
>> drive
> 
> That's why I told you to configure nosetest to use an specific output 
> path for the unit test file.

OK, I will do this and report back.

> 
> 
>> Thanks again for your continued interest. I quickly got Hudson to
>> retrieve job source from our subversion repository so I thought it would
>> be equally easy to get Hudson to run the unit tests, but that has proven
>> to be difficult, and so far I do not know how to diagnose this since it
>> seems there is no way to prevent Hudson from immediately deleting the
>> temporary scripts it generates.
> 
> Which is ok, since it prints what it does during the script execution, 
> and the scripts contain nothing more than what you typed in.

Yes, and I am not seeing the nosetests.exe command listed anywhere in 
the Hudson console output.  This is why I do not think Hudson is 
executing it.

> 
> Does nosetest produce an XML file when you call it manually from the 
> command line? 

Yes it does.  The exact same command (specified for the Hudson job) 
works perfectly from a Windows console.

Is nosetest.exe in your PATH, so that the cmd.exe that
> Hudson starts can find it?

Yes, it is.  "C:\Python26\Scripts" is in PATH and that is where 
"nosetests.exe" is.
> 
> Personally, I'd always step into the target directory before running a 
> command, so I'd make the script
> 
>     cd level-1
>     nosetest.exe ...

OK, I will try this.

> 
> Stefan
> 


From utente at esempio.net  Tue May 11 11:26:29 2010
From: utente at esempio.net (superpollo)
Date: Tue, 11 May 2010 17:26:29 +0200
Subject: Iterating over dict and removing some elements
In-Reply-To: <4be974cf$0$18659$4fafbaef@reader3.news.tin.it>
References: 
	<4be974cf$0$18659$4fafbaef@reader3.news.tin.it>
Message-ID: <4be97725$0$18655$4fafbaef@reader3.news.tin.it>

superpollo ha scritto:
> Ulrich Eckhardt ha scritto:
>> Hi!
>>
>> I wrote a simple loop like this:
>>
>>   d = {}
>>   ...
>>   for k in d:
>>       if some_condition(d[k]):
>>           d.pop(k)
>>
>> If I run this, Python complains that the dictionary size changed during
>> iteration. I understand that the iterator relies on the internal 
>> structure
>> not changing, but how would I structure this loop otherwise?
> 
> my first thought (untested):
> 
> use a copy of d for the if clause, then pop from the original.
> 
> bye

i mean:

 >>> d = {"name":"max","surname":"zanardi","nick":"zanna"}
 >>> dc = copy.copy(d)
 >>> dc
{'nick': 'zanna', 'surname': 'zanardi', 'name': 'max'}
 >>> for k in dc:
...     if dc[k].startswith("z"):
...         d.pop(k)
...
'zanna'
'zanardi'
 >>> d
{'name': 'max'}
 >>> dc
{'nick': 'zanna', 'surname': 'zanardi', 'name': 'max'}
 >>>

bye


From malaclypse2 at gmail.com  Tue May 11 11:29:34 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Tue, 11 May 2010 11:29:34 -0400
Subject: Iterating over dict and removing some elements
In-Reply-To: 
References: 
Message-ID: 

On Tue, May 11, 2010 at 11:08 AM, Ulrich Eckhardt
 wrote:
> My first approach was to simply postpone removing the elements, but I was
> wondering if there was a more elegant solution.

Iterate over something other than the actual dictionary, like this:

d = {1: 'one', 2: 'two', 3: 'three'}

for k in d.keys():
    if d[k] == 'two':
        d.pop(k)


-- 
Jerry


From malaclypse2 at gmail.com  Tue May 11 11:32:22 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Tue, 11 May 2010 11:32:22 -0400
Subject: Slice last char from string without raising exception on empty 
	string (Re: Extract all words that begin with x)
In-Reply-To: <1273588621.1629.1374510539@webmail.messagingengine.com>
References: 
	
	
	
	
	<1273588621.1629.1374510539@webmail.messagingengine.com>
Message-ID: 

On Tue, May 11, 2010 at 10:37 AM,   wrote:
> Is there an equivalent way to slice the last char from a string (similar
> to an .endswith) that doesn't raise an exception when a string is empty?

If you use negative indexes in the slice, they refer to items from the
end of the sequence instead of the front.  So slicing the last
character from the string would be:

word[-1:]

-- 
Jerry


From jim.vickroy at noaa.gov  Tue May 11 11:42:55 2010
From: jim.vickroy at noaa.gov (j vickroy)
Date: Tue, 11 May 2010 09:42:55 -0600
Subject: unable to get Hudson to run unit tests
In-Reply-To: 
References: 		<4BE80A78.2030502@noaa.gov>		<4BE828A2.2070106@noaa.gov>		<4BE96DB9.7040303@noaa.gov>
	
Message-ID: <4BE97AFF.5080903@noaa.gov>

Stefan Behnel wrote:
> j vickroy, 11.05.2010 16:46:
>  > Stefan Behnel wrote:
>>> No, what Hudson actually does, is, it writes your command(s) into a
>>> text file and runs it with the system's shell interpreter (which,
>>> unless otherwise configured, is "cmd.exe" on Windows).
>>
>> This is not the behavior I am experiencing on my Windows XP Pro (Service
>> Pack 3) workstation.
> 
> Then setting the "Shell executable" to "cmd.exe" will do the right thing 
> here.
> 
> 
>>> This assures the highest
>>> possible compatibility with the executed script. You can even use the
>>> shebang in Hudson's scripts that way, so that you can execute scripts
>>> in basically any scripting language.
> 
> ... although the shebang isn't really supported by cmd.exe, I guess ...
> 
> 
>>> The likely reason why it doesn't find your test results is that you
>>> didn't tell it where to look.
>>
>> Actually, Hudson is not finding the tests results because they are not
>> being generated. There is no "nosetests.xml" file anywhere on my hard
>> drive
> 
> That's why I told you to configure nosetest to use an specific output 
> path for the unit test file.
> 
> 
>> Thanks again for your continued interest. I quickly got Hudson to
>> retrieve job source from our subversion repository so I thought it would
>> be equally easy to get Hudson to run the unit tests, but that has proven
>> to be difficult, and so far I do not know how to diagnose this since it
>> seems there is no way to prevent Hudson from immediately deleting the
>> temporary scripts it generates.
> 
> Which is ok, since it prints what it does during the script execution, 
> and the scripts contain nothing more than what you typed in.
> 
> Does nosetest produce an XML file when you call it manually from the 
> command line? Is nosetest.exe in your PATH, so that the cmd.exe that 
> Hudson starts can find it?
> 
> Personally, I'd always step into the target directory before running a 
> command, so I'd make the script
> 
>     cd level-1
>     nosetest.exe ...
> 
> Stefan
> 

Here are the Hudson job | Configure | Execute shell | Command inputs:

------------------------------------------------------------------
cd level-1
dir
nosetests.exe --with-xunit --xunit-file=nosetests.xml --verbose
------------------------------------------------------------------
#!python.exe
####print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO'
import os ; print 'os.getcwd():',os.getcwd(); print 
'os.listdir(os.getcwd()):',os.listdir(os.getcwd())
------------------------------------------------------------------


and here is the Hudson Console Output:

--------------------------------------------------------------------------------------
Started by user anonymous
Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1
At revision 3417
no change for svn://vm-svn/GOES data 
processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build
[workspace] $ C:\WINDOWS\system32\cmd.exe -xe 
C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2208088016039194869.sh
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI 
Level-1 Products Generation\workspace>[workspace] $ python.exe 
C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson6398132145818001258.sh
os.getcwd(): C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 
13-15 SXI Level-1 Products Generation\workspace
os.listdir(os.getcwd()): ['level-1']
Recording test results
No test report files were found. Configuration error?
Finished: FAILURE
--------------------------------------------------------------------------------------


There is no nosetests.xml file anywhere on my hard drive (except as 
previously noted in the Recycle Bin).

 From the above Console Output, I see no evidence that the nosetests.exe 
command was ever executed.


From python at bdurham.com  Tue May 11 12:01:38 2010
From: python at bdurham.com (python at bdurham.com)
Date: Tue, 11 May 2010 12:01:38 -0400
Subject: Slice last char from string without raising exception on empty 
	string (Re: Extract all words that begin with x)
In-Reply-To: <4be9742f$0$18659$4fafbaef@reader3.news.tin.it>
References: 
	
	<4be9742f$0$18659$4fafbaef@reader3.news.tin.it>
Message-ID: <1273593698.18399.1374527347@webmail.messagingengine.com>

Superpollo,

> word[len(word)-1:] 

Perfect! Thank you,

Malcolm


From python at bdurham.com  Tue May 11 12:05:48 2010
From: python at bdurham.com (python at bdurham.com)
Date: Tue, 11 May 2010 12:05:48 -0400
Subject: Slice last char from string without raising exception on empty 
	string (Re: Extract all words that begin with x)
In-Reply-To: 
References: <1273588621.1629.1374510539@webmail.messagingengine.com>
	
Message-ID: <1273593948.19179.1374528335@webmail.messagingengine.com>

Jerry,

> If you use negative indexes in the slice, they refer to items from the end of the sequence instead of the front. So slicing the last character from the string would be:
> 
> word[-1:]

Perfect! Thank you,

Malcolm


From cde3 at live.com  Tue May 11 12:08:45 2010
From: cde3 at live.com (Sandy Sandy)
Date: Tue, 11 May 2010 21:08:45 +0500
Subject: plot debugging problem
Message-ID: 


Hi friends

pls help with debugging problem

the mutter is:

during debugging the  debug processes stacks when fig is created

for example, in code



import random



import matplotlib.pyplot as plt

from pylab import *





x= 23;

y = 111111;

print(23456)

plt.plot(range(10))



plot([1,2,3])

show()



print(11111111)



a=888



it is impossible after show() to continue debug

as stated in

Beginning Python Visualization - Crafting Visual Transformation Scripts 
(2009)

page  187



Note If you?re not using matplotlib interactively in Python, be sure

to call the function show() after all

graphs have been generated, as it enters a user interface main loop

that will stop execution of the rest of

your code. The reason behind this behavior is that matplotlib is

designed to be embedded in a GUI as well.

In Windows, if you?re working from interactive Python, you need only

issue show() once; close the figures

(or figures) to return to the shell. Subsequent plots will be drawn

automatically without issuing show(), and

you?ll be able to plot graphs interactively.



Best Regards

Sandy 		 	   		  
_________________________________________________________________
Hotmail: Free, trusted and rich email service.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From cde3 at live.com  Tue May 11 12:26:13 2010
From: cde3 at live.com (Sandy Sandy)
Date: Tue, 11 May 2010 21:26:13 +0500
Subject: graphs in Python during debugging
Message-ID: 




Hi friends

Can you help pls  to find how to plot graphs in Python
during debugging without destroying figures to continue to debug

the mutter is:

during debugging the  debug processes stacks when fig is created

for example, in code

import random

import matplotlib.pyplot as plt

from pylab import *

x= 23;

y = 111111;

print(23456)

plt.plot(range(10))

plot([1,2,3])

show()

print(11111111)

a=888



it is impossible after show() to continue debug

as stated in

Beginning Python Visualization - Crafting Visual Transformation Scripts (2009)

page  187



Note If you?re not using matplotlib interactively in Python, be sure

to call the function show() after all

graphs have been generated, as it enters a user interface main loop

that will stop execution of the rest of

your code. The reason behind this behavior is that matplotlib is

designed to be embedded in a GUI as well.

In Windows, if you?re working from interactive Python, you need only

issue show() once; close the figures

(or figures) to return to the shell. Subsequent plots will be drawn

automatically without issuing show(), and

you?ll be able to plot graphs interactively.



Best Regards

Sandy

 		 	   		  
_________________________________________________________________
Your E-mail and More On-the-Go. Get Windows Live Hotmail Free.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From prologic at shortcircuit.net.au  Tue May 11 12:35:36 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Wed, 12 May 2010 02:35:36 +1000
Subject: Slice last char from string without raising exception on empty 
	string (Re: Extract all words that begin with x)
In-Reply-To: <1273593698.18399.1374527347@webmail.messagingengine.com>
References: 
	 
	 
	
	 
	
	<4be9742f$0$18659$4fafbaef@reader3.news.tin.it> 
	<1273593698.18399.1374527347@webmail.messagingengine.com>
Message-ID: 

On Wed, May 12, 2010 at 2:01 AM,   wrote:
>> word[len(word)-1:]

This works just as well:

>>> word[-1:]

cheers
James


From utente at esempio.net  Tue May 11 12:39:42 2010
From: utente at esempio.net (superpollo)
Date: Tue, 11 May 2010 18:39:42 +0200
Subject: Slice last char from string without raising exception on empty
	string (Re: Extract all words that begin with x)
In-Reply-To: 
References: 	
	
		
		<4be9742f$0$18659$4fafbaef@reader3.news.tin.it>
	<1273593698.18399.1374527347@webmail.messagingengine.com>
	
Message-ID: <4be9884f$0$18652$4fafbaef@reader3.news.tin.it>

James Mills ha scritto:
> On Wed, May 12, 2010 at 2:01 AM,   wrote:
>>> word[len(word)-1:]
> 
> This works just as well:
> 
>>>> word[-1:]

d'uh. ;-)


From stefan_ml at behnel.de  Tue May 11 12:46:37 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Tue, 11 May 2010 18:46:37 +0200
Subject: unable to get Hudson to run unit tests
In-Reply-To: <4BE97AFF.5080903@noaa.gov>
References: 		<4BE80A78.2030502@noaa.gov>		<4BE828A2.2070106@noaa.gov>		<4BE96DB9.7040303@noaa.gov>	
	<4BE97AFF.5080903@noaa.gov>
Message-ID: 

j vickroy, 11.05.2010 17:42:
> Here are the Hudson job | Configure | Execute shell | Command inputs:
>
> ------------------------------------------------------------------
> cd level-1
> dir
> nosetests.exe --with-xunit --xunit-file=nosetests.xml --verbose
> ------------------------------------------------------------------
> #!python.exe
> ####print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO'
> import os ; print 'os.getcwd():',os.getcwd(); print
> 'os.listdir(os.getcwd()):',os.listdir(os.getcwd())
> ------------------------------------------------------------------
>
>
> and here is the Hudson Console Output:
>
> --------------------------------------------------------------------------------------
>
> Started by user anonymous
> Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1
> At revision 3417
> no change for svn://vm-svn/GOES data
> processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build
> [workspace] $ C:\WINDOWS\system32\cmd.exe -xe
> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2208088016039194869.sh
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
>
> C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI
> Level-1 Products Generation\workspace>[workspace] $ python.exe

This is telling. It doesn't properly execute the cmd.exe shell. Maybe you 
have to configure the shell setup somehow to make it accept MS's cmd.exe? 
Note that cmd.exe isn't really what I'd call a "shell", so you may have to 
put some work into getting it to run your scripts.

You can also try to add a shebang "#!cmd.exe" to the script, it seems like 
Hudson interprets that by itself. Or execute nosetest from a Python script, 
just check what the nosetest main script is doing and do the same in a 
Python script.

Disclaimer: I never used Hudson on MS Windows, and I'm happy I don't have to.

Stefan



From amphioxus at yahoo.com  Tue May 11 12:57:01 2010
From: amphioxus at yahoo.com (Armin)
Date: Tue, 11 May 2010 09:57:01 -0700
Subject: Problem displaying jpgs in Tkinter via PIL
References: <2010051014011093749-amphioxus@yahoocom>
Message-ID: <2010051109570184033-amphioxus@yahoocom>

Never mind, I gave up on Tkinter and have switched to wxPython now. 
Getting jpg images to display in a wx frame worked like a charm... (As 
I said, I'm very new to Python, so I didn't really know what my options 
for GUI programming were.)

It seems like the ImageTk module on the Enthought distribution on my 
Mac is broken, but I can't figure out how to fix that. (I wiped my 
python installations and did a re-install, all to no avail.) As long as 
I don't need Tkinter for the GUI I'm envisioning, I don't really care 
however.



On 2010-05-10 14:01:10 -0700, Armin said:

> I'm new to Python and have been playing around with it using the 
> Enthought Python distribution for Mac OS X 10.6.3 (EPD academic 
> license, version 6.1 with python 2.6.4).
> 
> It's been great learning the basics, but I've started running into 
> problems when I'm trying to use the PIL library with Tkinter. All I'm 
> trying to do is display a JPG as a Tkinter label:
> 
> It all works fine when I'm just using GIF images through Tkinter's 
> photoimage object, but as soon as I'm trying to convert an image 
> through ImageTk, I get the following error:
> 
> ImportError: 
> dlopen(/Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/PIL/_imagingtk.so, 
> 2): Library not loaded: /System at rpath/Tcl Referenced from: 
> /Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/PIL/_imagingtk.so 
> Reason: image not found
> 
> I have no idea what that means, but I've always assumed the EPD 
> includes all the stuff that's needed to make Tkinter work with PIL.
> Any advice would be greatly appreciated. Thanks!




From solipsis at pitrou.net  Tue May 11 13:08:01 2010
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Tue, 11 May 2010 19:08:01 +0200
Subject: Problem displaying jpgs in Tkinter via PIL
References: <2010051014011093749-amphioxus@yahoocom>
	<2010051109570184033-amphioxus@yahoocom>
Message-ID: <20100511190801.51b8fdb4@pitrou.net>

On Tue, 11 May 2010 09:57:01 -0700
Armin  wrote:
> Never mind, I gave up on Tkinter and have switched to wxPython now. 
> Getting jpg images to display in a wx frame worked like a charm... (As 
> I said, I'm very new to Python, so I didn't really know what my options 
> for GUI programming were.)

You might also want to try PyQT, which is often considered more modern
than wxPython (I've never tried it, though).

Regards

Antoine.




From phlip2005 at gmail.com  Tue May 11 13:22:03 2010
From: phlip2005 at gmail.com (Phlip)
Date: Tue, 11 May 2010 10:22:03 -0700 (PDT)
Subject: lame sphinx questions [Was: lame epydoc questions]
References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> 
	
	<4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com>
	<289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com> 
	
	<656fab1f-2cb7-433e-84ba-ffebbc118dde@t26g2000prt.googlegroups.com>
	
Message-ID: <8a7e019a-4606-417c-b7c7-c4ee14b5d172@r21g2000prr.googlegroups.com>

> epydoc supports reStructured text markups.

Oh, good. For a moment there, I thought I'd be stuck with a markup
language that was persnickety!


From landimatte at gmail.com  Tue May 11 13:46:27 2010
From: landimatte at gmail.com (Matteo Landi)
Date: Tue, 11 May 2010 19:46:27 +0200
Subject: plot debugging problem
In-Reply-To: 
References: 
Message-ID: 

I imagine you have to create a separate thread for it. Just thoughts.

On Tue, May 11, 2010 at 6:08 PM, Sandy Sandy  wrote:
> Hi friends
> pls help with debugging problem
> the mutter is:
> during debugging the ?debug processes stacks when fig is created
> for example, in code
>
> import random
>
> import matplotlib.pyplot as plt
> from pylab import *
>
>
> x= 23;
> y = 111111;
> print(23456)
> plt.plot(range(10))
>
> plot([1,2,3])
> show()
>
> print(11111111)
>
> a=888
>
> it is impossible after show() to continue debug
> as stated in
> Beginning Python Visualization - Crafting Visual Transformation Scripts
> (2009)
> page ?187
>
> Note If you?re not using matplotlib interactively in Python, be sure
> to call the function show() after all
> graphs have been generated, as it enters a user interface main loop
> that will stop execution of the rest of
> your code. The reason behind this behavior is that matplotlib is
> designed to be embedded in a GUI as well.
> In Windows, if you?re working from interactive Python, you need only
> issue show() once; close the figures
> (or figures) to return to the shell. Subsequent plots will be drawn
> automatically without issuing show(), and
> you?ll be able to plot graphs interactively.
>
> Best Regards
> Sandy
> ________________________________
> Hotmail: Free, trusted and rich email service. Get it now.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



-- 
Matteo Landi
http://www.matteolandi.net/


From dweimer at ORSCHELN.com  Tue May 11 14:02:00 2010
From: dweimer at ORSCHELN.com (Dean Weimer)
Date: Tue, 11 May 2010 13:02:00 -0500
Subject: Pythonw.exe randomly crashing
Message-ID: 

Hi, I have a python application I wrote that is randomly crashing, I was
wondering if anyone else has ran into this error, or if anyone has any
idea about how to fix it.  This is currently running under Windows
server 2008 R2 x64 in terminal services, with Python 2.6.4 x64
installed.  I ran into this problem with previous versions of Python on
windows 2003 server running under 32 bit.  I have been unable to
duplicate the error under a devolvement platform.  The application is a
simple GUI used for time clock stations on a shop floor; it has a
multithreaded GUI which displays some rotating informational images.  A
Text box that displays a constantly updating clock, and a text box that
accepts employee clock number input and one that displays results
returned from a background thread that runs a telnet session to a
server.  I can't really tell you where the error is occurring within the
actual code, as it takes days of the application running to happen.

Does anyone have any suggestions as to how I can get it to give me more
information about the crash?

 

Log Name:      Application

Source:        Application Error

Date:          5/6/2010 3:33:40 PM

Event ID:      1000

Task Category: (100)

Level:         Error

Keywords:      Classic

User:          N/A

Description:

Faulting application name: pythonw.exe, version: 0.0.0.0, time stamp:
0x4ba3b0d9

Faulting module name: tcl85.dll, version: 8.5.2.2, time stamp:
0x48515e43

Exception code: 0xc0000005

Fault offset: 0x000000000005863d

Faulting process id: 0xa98

Faulting application start time: 0x01cae87cff98c7c4

Faulting application path: C:\Python26\pythonw.exe

Faulting module path: C:\Python26\DLLs\tcl85.dll

Report Id: a7a18c68-594e-11df-b65f-005056b55389

 

 

Thanks,

     Dean Weimer

     Network Administrator

     Orscheln Management Co

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From tjreedy at udel.edu  Tue May 11 14:13:19 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 14:13:19 -0400
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 	<7xvdavd4bq.fsf@ruckus.brouhaha.com>
	
Message-ID: 

On 5/11/2010 7:11 AM, Lawrence D'Oliveiro wrote:
> In message<7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote:
>
>> Python is a pragmatic language from an imperative tradition ...
>
> I thought the opposite of ?functional? was ?procedural?, not ?imperative?.
> The opposite to the latter is ?declarative?. But (nearly) all procedural
> languages also have declarative constructs, not just imperative ones
> (certainly Python does).

Python has only two: 'global' and now 'nonlocal'.
There are also two meta-declarations: the coding cookie (which 
would/will go away in an entirely unicode world) and future imports 
(which are effectively temporarily gone in 3.x until needed again).

Newbies sometimes trip over def and class being imperative (executable) 
statments rather than declarations.

Terry Jan Reedy





From tjreedy at udel.edu  Tue May 11 14:16:50 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 14:16:50 -0400
Subject: inherit from data type
In-Reply-To: <201005111351.46892.richard.lamboj@bilcom.at>
References: 		<26lnb7-t6g.ln1@satorlaser.homedns.org>
	<201005111351.46892.richard.lamboj@bilcom.at>
Message-ID: 

On 5/11/2010 7:51 AM, Richard Lamboj wrote:

> I just want to test what is possible with python and what not. There is no
> problem that i need to solve.
>
> This is what i'am searching for:
> http://docs.python.org/reference/datamodel.html
>
> Last year i have stopped programming python, but now i'am back with a big
> black hole in my brain and i want to understand what the interpreter is doing
> in the background.

I suggest you (re)read and try examples in the Tutorial. It covers the 
basic syntax pretty well.



From alan.isaac at gmail.com  Tue May 11 14:33:12 2010
From: alan.isaac at gmail.com (Alan G Isaac)
Date: Tue, 11 May 2010 14:33:12 -0400
Subject: documentation bug? (format spec mini language)
Message-ID: 

The documentation at http://docs.python.org/py3k/library/string.html#format-specification-mini-language

         '<' Forces the field to be left-aligned within the available space (This is the default.)

The conflicting example::

         >>> format(3.2,'10.5f')
         '   3.20000'
         >>> format(3.2,'<10.5f')
         '3.20000   '

Am I somehow misreading the documentation?

Thanks,
Alan Isaac




From landimatte at gmail.com  Tue May 11 14:37:39 2010
From: landimatte at gmail.com (Matteo Landi)
Date: Tue, 11 May 2010 20:37:39 +0200
Subject: plot debugging problem
In-Reply-To: 
References: 
	 
	
Message-ID: 

Well, I cannot tell you how to do that in a precise way, but googling
a bit I found this (expecially the second example):

http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/

Take a look also at the Matplotlib cookbook:

http://www.scipy.org/Cookbook/Matplotlib

ps. when you answer back, remember to include the list, or the flow will be cut!

On Tue, May 11, 2010 at 7:49 PM, Sandy Sandy  wrote:
> great!!!
> how to do it?
>
> this way it is not working:
>
> from pylab import plot,show,close
> x = range(10)
> plot(x)
> from threading import Timer
> t = Timer(0, show)
> t.start()
>
> y = [2, 8, 3, 9, 4]
> plot(y)
> close()
>
> Best Regards
> Sandy
>
>
>
>
>
>
>
>
>
>
>
>
>
>> From: landimatte at gmail.com
>> Date: Tue, 11 May 2010 19:46:27 +0200
>> Subject: Re: plot debugging problem
>> To: cde3 at live.com
>> CC: python-list at python.org
>>
>> I imagine you have to create a separate thread for it. Just thoughts.
>>
>> On Tue, May 11, 2010 at 6:08 PM, Sandy Sandy  wrote:
>> > Hi friends
>> > pls help with debugging problem
>> > the mutter is:
>> > during debugging the ?debug processes stacks when fig is created
>> > for example, in code
>> >
>> > import random
>> >
>> > import matplotlib.pyplot as plt
>> > from pylab import *
>> >
>> >
>> > x= 23;
>> > y = 111111;
>> > print(23456)
>> > plt.plot(range(10))
>> >
>> > plot([1,2,3])
>> > show()
>> >
>> > print(11111111)
>> >
>> > a=888
>> >
>> > it is impossible after show() to continue debug
>> > as stated in
>> > Beginning Python Visualization - Crafting Visual Transformation Scripts
>> > (2009)
>> > page ?187
>> >
>> > Note If you?re not using matplotlib interactively in Python, be sure
>> > to call the function show() after all
>> > graphs have been generated, as it enters a user interface main loop
>> > that will stop execution of the rest of
>> > your code. The reason behind this behavior is that matplotlib is
>> > designed to be embedded in a GUI as well.
>> > In Windows, if you?re working from interactive Python, you need only
>> > issue show() once; close the figures
>> > (or figures) to return to the shell. Subsequent plots will be drawn
>> > automatically without issuing show(), and
>> > you?ll be able to plot graphs interactively.
>> >
>> > Best Regards
>> > Sandy
>> > ________________________________
>> > Hotmail: Free, trusted and rich email service. Get it now.
>> > --
>> > http://mail.python.org/mailman/listinfo/python-list
>> >
>> >
>>
>>
>>
>> --
>> Matteo Landi
>> http://www.matteolandi.net/
>
> ________________________________
> Hotmail: Powerful Free email with security by Microsoft. Get it now.



-- 
Matteo Landi
http://www.matteolandi.net/


From tjreedy at udel.edu  Tue May 11 14:42:00 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 14:42:00 -0400
Subject: How to make this doctest work?
In-Reply-To: 
References: 
Message-ID: 

On 5/11/2010 5:29 AM, Xie&Tian wrote:
> Hello
>
> I ran across this accidentally and wonders how to make the doctest in
> following code snippet work:
>
>
> import doctest
>
> def a():
>       """
>      >>>  a = '\\r\\n'
>      >>>  print a
>
>
>      No matter how many blank lines I add here, it just can't get enough -_-
>      """
>      pass
>
> doctest.testmod()
>
>
>
> ps: I want variable "a" to be '\r\n', but python kept telling me
>          ValueError: line 4 of the docstring has inconsistent leading
> whitespace: "'"
>      Why can't doctest module deal with statement "a='\r\n'"?

You should post (copy and paste) entire error messages.
The problem is with the print statement, not the assignment.
I would prefix the docstring with r instead doubling \s within it.
The point of doctest is to imitate what one would get with the 
interactive interpreter. However, literally entering what you have 
within the doc string does (3.1)

 >>> a = '\\r\\n'
 >>> print(a)
\r\n
 >>>

Terry Jan Reedy





From backgoodoo at gmail.com  Tue May 11 15:06:36 2010
From: backgoodoo at gmail.com (Back9)
Date: Tue, 11 May 2010 12:06:36 -0700 (PDT)
Subject: default argument
Message-ID: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>

Hi,

Is this grammer working in Python?

class test:
  self._value = 10
  def func(self, self._value)

When i try it, it complains about undefined self.

i don't know why.

TIA


From backgoodoo at gmail.com  Tue May 11 15:08:04 2010
From: backgoodoo at gmail.com (Back9)
Date: Tue, 11 May 2010 12:08:04 -0700 (PDT)
Subject: default argument
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
Message-ID: <7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>

On May 11, 3:06?pm, Back9  wrote:
> Hi,
>
> Is this grammer working in Python?
>
> class test:
> ? self._value = 10
> ? def func(self, self._value)
>
> When i try it, it complains about undefined self.
>
> i don't know why.
>
> TIA

Sorry
here is the what i meant
class test:
  self._value = 10
  def func(self, pos = self._value)



From landimatte at gmail.com  Tue May 11 15:11:06 2010
From: landimatte at gmail.com (Matteo Landi)
Date: Tue, 11 May 2010 21:11:06 +0200
Subject: plot debugging problem
In-Reply-To: 
References: 
	 
	
	 
	
Message-ID: 

On Tue, May 11, 2010 at 8:59 PM, Sandy Sandy  wrote:
>
> 1
>
> remember to include the list,
>
> what does it mean??

I mean that you are leaving out the mlist from your answers. Instead
of press _reply_, look for a _reply-to-all_ button.

>
> 2
>
> do you mean
>
> Pseudo Color Plots
>
> in
>
> http://www.scipy.org/Cookbook/Matplotlib
>
> ??
>
> 3
>
> could you pls clarify what to see in
>
> http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/
>
>
> http://www.scipy.org/Cookbook/Matplotlib
>

As I stated in the previous email, I have no experience with
matplotlib, but in the first link I posted there is an example on how
to integrate matplotlib within a wxpython application. You can start
from it, and look how to attach plot within a gui mailoop.

> S
>
> Well, I cannot tell you how to do that in a precise way, but googling
> a bit I found this (expecially the second example):
>
> http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/
>
> Take a look also at the Matplotlib cookbook:
>
> http://www.scipy.org/Cookbook/Matplotlib
>
> ps. when you answer back, remember to include the list, or the flow will be
> cut!
>
> On Tue, May 11, 2010 at 7:49 PM, Sandy Sandy  wrote:
>> great!!!
>> how to do it?
>>
>> this way it is not working:
>>
>> from pylab import plot,show,close
>> x = range(10)
>> plot(x)
>> from threading import Timer
>> t = Timer(0, show)
>> t.start()
>>
>> y = [2, 8, 3, 9, 4]
>> plot(y)
>> close()
>>
>> Best Regards
>> Sandy
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>> From: landimatte at gmail.com
>>> Date: Tue, 11 May 2010 19:46:27 +0200
>>> Subject: Re: plot debugging problem
>>> To: cde3 at live.com
>>> CC: python-list at python.org
>>>
>>> I imagine you have to create a separate thread for it. Just thoughts.
>>>
>>> On Tue, May 11, 2010 at 6:08 PM, Sandy Sandy  wrote:
>>> > Hi friends
>>> > pls help with debugging problem
>>> > the mutter is:
>>> > during debugging the ?debug processes stacks when fig is created
>>> > for example, in code
>>> >
>>> > import random
>>> >
>>> > import matplotlib.pyplot as plt
>>> > from pylab import *
>>> >
>>> >
>>> > x= 23;
>>> > y = 111111;
>>> > print(23456)
>>> > plt.plot(range(10))
>>> >
>>> > plot([1,2,3])
>>> > show()
>>> >
>>> > print(11111111)
>>> >
>>> > a=888
>>> >
>>> > it is impossible after show() to continue debug
>>> > as stated in
>>> > Beginning Python Visualization - Crafting Visual Transformation Scripts
>>> > (2009)
>>> > page ?187
>>> >
>>> > Note If you?re not using matplotlib interactively in Python, be sure
>>> > to call the function show() after all
>>> > graphs have been generated, as it enters a user interface main loop
>>> > that will stop execution of the rest of
>>> > your code. The reason behind this behavior is that matplotlib is
>>> > designed to be embedded in a GUI as well.
>>> > In Windows, if you?re working from interactive Python, you need only
>>> > issue show() once; close the figures
>>> > (or figures) to return to the shell. Subsequent plots will be drawn
>>> > automatically without issuing show(), and
>>> > you?ll be able to plot graphs interactively.
>>> >
>>> > Best Regards
>>> > Sandy
>>> > ________________________________
>>> > Hotmail: Free, trusted and rich email service. Get it now.
>>> > --
>>> > http://mail.python.org/mailman/listinfo/python-list
>>> >
>>> >
>>>
>>>
>>>
>>> --
>>> Matteo Landi
>>> http://www.matteolandi.net/
>>
>> ________________________________
>> Hotmail: Powerful Free email with security by Microsoft. Get it now.
>
>
>
> --
> Matteo Landi
> http://www.matteolandi.net/
>
>
>> From: landimatte at gmail.com
>> Date: Tue, 11 May 2010 20:37:39 +0200
>> Subject: Re: plot debugging problem
>> To: cde3 at live.com
>> CC: python-list at python.org
>>
>> Well, I cannot tell you how to do that in a precise way, but googling
>> a bit I found this (expecially the second example):
>>
>> http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/
>>
>> Take a look also at the Matplotlib cookbook:
>>
>> http://www.scipy.org/Cookbook/Matplotlib
>>
>> ps. when you answer back, remember to include the list, or the flow will
>> be cut!
>>
>> On Tue, May 11, 2010 at 7:49 PM, Sandy Sandy  wrote:
>> > great!!!
>> > how to do it?
>> >
>> > this way it is not working:
>> >
>> > from pylab import plot,show,close
>> > x = range(10)
>> > plot(x)
>> > from threading import Timer
>> > t = Timer(0, show)
>> > t.start()
>> >
>> > y = [2, 8, 3, 9, 4]
>> > plot(y)
>> > close()
>> >
>> > Best Regards
>> > Sandy
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >> From: landimatte at gmail.com
>> >> Date: Tue, 11 May 2010 19:46:27 +0200
>> >> Subject: Re: plot debugging problem
>> >> To: cde3 at live.com
>> >> CC: python-list at python.org
>> >>
>> >> I imagine you have to create a separate thread for it. Just thoughts.
>> >>
>> >> On Tue, May 11, 2010 at 6:08 PM, Sandy Sandy  wrote:
>> >> > Hi friends
>> >> > pls help with debugging problem
>> >> > the mutter is:
>> >> > during debugging the ?debug processes stacks when fig is created
>> >> > for example, in code
>> >> >
>> >> > import random
>> >> >
>> >> > import matplotlib.pyplot as plt
>> >> > from pylab import *
>> >> >
>> >> >
>> >> > x= 23;
>> >> > y = 111111;
>> >> > print(23456)
>> >> > plt.plot(range(10))
>> >> >
>> >> > plot([1,2,3])
>> >> > show()
>> >> >
>> >> > print(11111111)
>> >> >
>> >> > a=888
>> >> >
>> >> > it is impossible after show() to continue debug
>> >> > as stated in
>> >> > Beginning Python Visualization - Crafting Visual Transformation
>> >> > Scripts
>> >> > (2009)
>> >> > page ?187
>> >> >
>> >> > Note If you?re not using matplotlib interactively in Python, be sure
>> >> > to call the function show() after all
>> >> > graphs have been generated, as it enters a user interface main loop
>> >> > that will stop execution of the rest of
>> >> > your code. The reason behind this behavior is that matplotlib is
>> >> > designed to be embedded in a GUI as well.
>> >> > In Windows, if you?re working from interactive Python, you need only
>> >> > issue show() once; close the figures
>> >> > (or figures) to return to the shell. Subsequent plots will be drawn
>> >> > automatically without issuing show(), and
>> >> > you?ll be able to plot graphs interactively.
>> >> >
>> >> > Best Regards
>> >> > Sandy
>> >> > ________________________________
>> >> > Hotmail: Free, trusted and rich email service. Get it now.
>> >> > --
>> >> > http://mail.python.org/mailman/listinfo/python-list
>> >> >
>> >> >
>> >>
>> >>
>> >>
>> >> --
>> >> Matteo Landi
>> >> http://www.matteolandi.net/
>> >
>> > ________________________________
>> > Hotmail: Powerful Free email with security by Microsoft. Get it now.
>>
>>
>>
>> --
>> Matteo Landi
>> http://www.matteolandi.net/
>
> ________________________________
> Hotmail: Powerful Free email with security by Microsoft. Get it now.



-- 
Matteo Landi
http://www.matteolandi.net/


From python at mrabarnett.plus.com  Tue May 11 15:19:53 2010
From: python at mrabarnett.plus.com (MRAB)
Date: Tue, 11 May 2010 20:19:53 +0100
Subject: documentation bug? (format spec mini language)
In-Reply-To: 
References: 
Message-ID: <4BE9ADD9.9030901@mrabarnett.plus.com>

Alan G Isaac wrote:
> The documentation at 
> http://docs.python.org/py3k/library/string.html#format-specification-mini-language 
> 
> 
>         '<' Forces the field to be left-aligned within the available 
> space (This is the default.)
> 
> The conflicting example::
> 
>         >>> format(3.2,'10.5f')
>         '   3.20000'
>         >>> format(3.2,'<10.5f')
>         '3.20000   '
> 
> Am I somehow misreading the documentation?
> 
It does look misleading. Numbers default to right-aligned, as you
discovered.

You usually want numbers to be right-aligned so that the decimal points
line up when writing a columns of them.


From clp2 at rebertia.com  Tue May 11 15:20:26 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Tue, 11 May 2010 12:20:26 -0700
Subject: default argument
In-Reply-To: <7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
	<7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>
Message-ID: 

On Tue, May 11, 2010 at 12:08 PM, Back9  wrote:
> On May 11, 3:06?pm, Back9  wrote:

>> When i try it, it complains about undefined self.
>>
>> i don't know why.
>>
>> TIA
>
> Sorry
> here is the what i meant
> class test:
> ?self._value = 10
> ?def func(self, pos = self._value)

You're still defining the class, so how could there possibly be an
instance of it to refer to as "self" yet (outside of a method body)?
Also, just so you know, default argument values are only evaluated
once, at the time the function/method is defined, so `pos =
self._value` is never going to work.

Do you mean for self._value to be a class variable (Java lingo: static
variable), or an instance variable?

Cheers,
Chris
--
http://blog.rebertia.com


From clp2 at rebertia.com  Tue May 11 15:25:11 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Tue, 11 May 2010 12:25:11 -0700
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
	
Message-ID: 

On Tue, May 11, 2010 at 11:13 AM, Terry Reedy  wrote:
> On 5/11/2010 7:11 AM, Lawrence D'Oliveiro wrote:
>> In message<7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote:
>>
>>> Python is a pragmatic language from an imperative tradition ...
>>
>> I thought the opposite of ?functional? was ?procedural?, not ?imperative?.
>> The opposite to the latter is ?declarative?. But (nearly) all procedural
>> languages also have declarative constructs, not just imperative ones
>> (certainly Python does).
>
> Python has only two: 'global' and now 'nonlocal'.
> There are also two meta-declarations: the coding cookie (which would/will go
> away in an entirely unicode world) and future imports (which are effectively
> temporarily gone in 3.x until needed again).
>
> Newbies sometimes trip over def and class being imperative (executable)
> statments rather than declarations.

Er, declarative programming has nothing to do with variable declarations.
http://en.wikipedia.org/wiki/Declarative_programming

Cheers,
Chris
--
http://blog.rebertia.com


From tjreedy at udel.edu  Tue May 11 15:25:43 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 15:25:43 -0400
Subject: how to import a module for global use in a library package ?
In-Reply-To: <577270.86860.qm@web23105.mail.ird.yahoo.com>
References: <577270.86860.qm@web23105.mail.ird.yahoo.com>
Message-ID: 

On 5/11/2010 8:04 AM, Aur? Gourrier wrote:
> Dear all,
>
> I am building a library package of the form:
>
> rootlib
> ---__init__
> ---subpackage1
> ------__init__
> ------sub1module1
> ------sub1module2
> ------...
> ---subpackage2
> ------ __init__
> ------sub2module1
> ------sub2module2
> ------...
>
> My rootlib.__init__ file contains:
>
> __name__        = ...
> __version__     = ...
> __author__      = ...
> __author_email__= ...
> __url__         = ...
> __description__ = ...
>
> import subpackage1
> import subpackage2
>
> __all__ = []
> __all__.extend(['subpackage1','subpackage2'])
>
> My question is the following: I need to import an external package,
say numpy, for use in various submodules. So far, I simply do an import
numpy as _numpy where needed, say sub1module1 and sub2module2. This
means that I import this package a number of times which doesn't seem to
be a logical thing to do (?). In the end, I would like to make this
module a "global" module for my library.

I have a similar package structure and after writing a few submodules, I 
developed a template that includes common text, including a couple of 
imports that are usually needed. I also made a backup copy of the 
template in case I open the template and forget to 'save as 
' before just 'save'ing ;-).

If I had several such imports, and thought the list might expand, I 
might make one submodule for imports and then do 'from rootlib.util 
import importmod as m' in the template. But I have no need now for such.

Terry Jan Reedy




From bookexplorer at msisinc.com  Tue May 11 15:28:00 2010
From: bookexplorer at msisinc.com (Donna Lane)
Date: Tue, 11 May 2010 13:28:00 -0600
Subject: First Timer
Message-ID: <002c01caf140$11a0eb00$34e2c100$@com>

I have downloaded Python and I'm a beginner in every sense.  What I want to
know now is when I am in Idle and have made a syntax error how do I repair?
After the error I can't type in

anything and I get this bing noise.  Usually I just start idle over again.

Thanks to anyone out there who responds.

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From backgoodoo at gmail.com  Tue May 11 15:41:48 2010
From: backgoodoo at gmail.com (Back9)
Date: Tue, 11 May 2010 12:41:48 -0700 (PDT)
Subject: default argument
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
	<7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com> 
	
Message-ID: <439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>

On May 11, 3:20?pm, Chris Rebert  wrote:
> On Tue, May 11, 2010 at 12:08 PM, Back9  wrote:
> > On May 11, 3:06?pm, Back9  wrote:
> 
> >> When i try it, it complains about undefined self.
>
> >> i don't know why.
>
> >> TIA
>
> > Sorry
> > here is the what i meant
> > class test:
> > ?self._value = 10
> > ?def func(self, pos = self._value)
>
> You're still defining the class, so how could there possibly be an
> instance of it to refer to as "self" yet (outside of a method body)?
> Also, just so you know, default argument values are only evaluated
> once, at the time the function/method is defined, so `pos =
> self._value` is never going to work.
>
> Do you mean for self._value to be a class variable (Java lingo: static
> variable), or an instance variable?
>
> Cheers,
> Chris
> --http://blog.rebertia.com

self._value will be instance variable


From tjreedy at udel.edu  Tue May 11 15:45:05 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 15:45:05 -0400
Subject: Iterating over dict and removing some elements
In-Reply-To: 
References: 
	
Message-ID: 

On 5/11/2010 11:29 AM, Jerry Hill wrote:
> On Tue, May 11, 2010 at 11:08 AM, Ulrich Eckhardt
>   wrote:
>> My first approach was to simply postpone removing the elements, but I was
>> wondering if there was a more elegant solution.
>
> Iterate over something other than the actual dictionary, like this:
>
> d = {1: 'one', 2: 'two', 3: 'three'}
>
> for k in d.keys():
>      if d[k] == 'two':
>          d.pop(k)

This, as written, does not work in 3.1, where d.keys is a view of the 
dict. Nor does

for k in filter(lambda k: d[k] == 'two', d):
         d.pop(k)

But these do

for k in list(filter(lambda k: d[k] == 'two', d)):
         d.pop(k)

for k in [k for k in d if d[k] == 'two']:
         d.pop(k)

Rather than make an external list of *all* keys, one only needs to make 
a list of keys to be removed, which often  will be much smaller.

Terry Jan Reedy



From nobody at nowhere.com  Tue May 11 15:46:33 2010
From: nobody at nowhere.com (Nobody)
Date: Tue, 11 May 2010 20:46:33 +0100
Subject: fast regex
References: 
	
Message-ID: 

On Tue, 11 May 2010 17:48:41 +1200, Lawrence D'Oliveiro wrote:

>> I was working with regex on a very large text, really large but I have
>> time constrained.
> 
> ?Fast regex? is a contradiction in terms.

Not at all. A properly-written regexp engine will be limited only by
memory bandwidth, provided that the state table fits into the primary
cache.

> You use regexes when you
> want ease of definition and application, not speed.

Other way around.

> For speed, consider hand-coding your own state machine. Preferably in a
> compiled language like C.

Or use a decent regexp library.

Even if you want to use non-regular expressions (e.g. backreferences), a
decent engine will still use a DFA, bactracking only where strictly
necessary.



From richard.lamboj at bilcom.at  Tue May 11 15:48:38 2010
From: richard.lamboj at bilcom.at (Richard Lamboj)
Date: Tue, 11 May 2010 21:48:38 +0200
Subject: inherit from data type
In-Reply-To: 
References: 
	<201005111351.46892.richard.lamboj@bilcom.at>
	
Message-ID: <201005112148.39057.richard.lamboj@bilcom.at>


Am Tuesday 11 May 2010 20:16:50 schrieb Terry Reedy:
> On 5/11/2010 7:51 AM, Richard Lamboj wrote:
> > I just want to test what is possible with python and what not. There is
> > no problem that i need to solve.
> >
> > This is what i'am searching for:
> > http://docs.python.org/reference/datamodel.html
> >
> > Last year i have stopped programming python, but now i'am back with a big
> > black hole in my brain and i want to understand what the interpreter is
> > doing in the background.
>
> I suggest you (re)read and try examples in the Tutorial. It covers the
> basic syntax pretty well.

There are many programming languages, so i have forgotten that python data 
types are objects and not a "wrapper". So its a little bit confusing 
that "self" returns the value of the datatype and not something 
like "self.value". But who cares about logical mistakes in my brain.


From no.email at please.post  Tue May 11 15:49:53 2010
From: no.email at please.post (kj)
Date: Tue, 11 May 2010 19:49:53 +0000 (UTC)
Subject: Limitation of os.walk
Message-ID: 




I want implement a function that walks through a directory tree
and performs an analsysis of all the subdirectories found.  The
task has two essential requirements that, AFAICT, make it impossible
to use os.walk for this:

1. I need to be able to prune certain directories from being visited.

2. The analysis on each directory can be performed only after it
   has been performed on all its subdirectories.

Unless I'm missing something, to do (1), os.walk must be run with
topdown=True, whereas to do (2) it must be run with topdown=False.

Is there a work around that I'm missing?

TIA!

~K

PS: I never understood why os.walk does not support hooks for key
events during such a tree traversal.


From clp2 at rebertia.com  Tue May 11 15:52:43 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Tue, 11 May 2010 12:52:43 -0700
Subject: default argument
In-Reply-To: <439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
	<7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>
	
	<439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
Message-ID: 

On Tue, May 11, 2010 at 12:41 PM, Back9  wrote:
> On May 11, 3:20?pm, Chris Rebert  wrote:
>> On Tue, May 11, 2010 at 12:08 PM, Back9  wrote:
>> > On May 11, 3:06?pm, Back9  wrote:
>> 
>> >> When i try it, it complains about undefined self.
>>
>> >> i don't know why.
>>
>> >> TIA
>>
>> > Sorry
>> > here is the what i meant
>> > class test:
>> > ?self._value = 10
>> > ?def func(self, pos = self._value)
>>
>> You're still defining the class, so how could there possibly be an
>> instance of it to refer to as "self" yet (outside of a method body)?
>> Also, just so you know, default argument values are only evaluated
>> once, at the time the function/method is defined, so `pos =
>> self._value` is never going to work.
>>
>> Do you mean for self._value to be a class variable (Java lingo: static
>> variable), or an instance variable?
>
> self._value will be instance variable

class Test(object):
    def __init__(self):
        self._value = 10
    def func(self, pos=None):
        if pos is None:
            pos = self._value
        #do whatever

Using None like this is the idiomatic way to have non-constant or
mutable default argument values in Python.

I recommend you read the part of the Python tutorial on
object-oriented programming:
http://docs.python.org/tutorial/classes.html

Cheers,
Chris
--
http://blog.rebertia.com


From jim.vickroy at noaa.gov  Tue May 11 15:59:36 2010
From: jim.vickroy at noaa.gov (j vickroy)
Date: Tue, 11 May 2010 13:59:36 -0600
Subject: default argument
In-Reply-To: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
Message-ID: <4BE9B728.8070602@noaa.gov>

Back9 wrote:
> Hi,
> 
> Is this grammer working in Python?
> 
> class test:
>   self._value = 10
>   def func(self, self._value)
> 
> When i try it, it complains about undefined self.
> 
> i don't know why.
> 
> TIA

... not exactly; try:

class Test:
    _value = 10
    def func(self):
       print id(self._value), self._value
       print id(Test._value), Test._value

t = Test()
t.func()


From lie.1296 at gmail.com  Tue May 11 15:59:50 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 12 May 2010 05:59:50 +1000
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 	<7xvdavd4bq.fsf@ruckus.brouhaha.com>
		
	
Message-ID: <4be9b795$1@dnews.tpgi.com.au>

On 05/12/10 05:25, Chris Rebert wrote:
> On Tue, May 11, 2010 at 11:13 AM, Terry Reedy  wrote:
>> On 5/11/2010 7:11 AM, Lawrence D'Oliveiro wrote:
>>> In message<7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote:
>>>
>>>> Python is a pragmatic language from an imperative tradition ...
>>>
>>> I thought the opposite of ?functional? was ?procedural?, not ?imperative?.
>>> The opposite to the latter is ?declarative?. But (nearly) all procedural
>>> languages also have declarative constructs, not just imperative ones
>>> (certainly Python does).
>>
>> Python has only two: 'global' and now 'nonlocal'.
>> There are also two meta-declarations: the coding cookie (which would/will go
>> away in an entirely unicode world) and future imports (which are effectively
>> temporarily gone in 3.x until needed again).
>>
>> Newbies sometimes trip over def and class being imperative (executable)
>> statments rather than declarations.
> 
> Er, declarative programming has nothing to do with variable declarations.
> http://en.wikipedia.org/wiki/Declarative_programming
> 

Variable declarations have everything to do with declarative programming.

An imperative way to create a variable is to allocate the memory
yourself and instead of "variables" you have just registers and the
memory; fortunately all popular imperative languages (wisely) picks up
declarative syntax from the declarative paradigm. In Python, the regular
def/class is a pseudo-declaration, but it is also possible to
*imperatively/procedurally* create a class by calling type() and a
function by passing a __call__() to type()'s __dict__ argument.

A fully declarative language just turn everything into declarations
including the "business logic" of the application (and of course,
variable declaration).


From tjreedy at udel.edu  Tue May 11 16:00:48 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 16:00:48 -0400
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 	<7xvdavd4bq.fsf@ruckus.brouhaha.com>
		
	
Message-ID: 

On 5/11/2010 3:25 PM, Chris Rebert wrote:
> On Tue, May 11, 2010 at 11:13 AM, Terry Reedy  wrote:
>> On 5/11/2010 7:11 AM, Lawrence D'Oliveiro wrote:
>>> In message<7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote:
>>>
>>>> Python is a pragmatic language from an imperative tradition ...
>>>
>>> I thought the opposite of ?functional? was ?procedural?, not ?imperative?.
>>> The opposite to the latter is ?declarative?. But (nearly) all procedural
>>> languages also have declarative constructs, not just imperative ones
>>> (certainly Python does).
>>
>> Python has only two: 'global' and now 'nonlocal'.
>> There are also two meta-declarations: the coding cookie (which would/will go
>> away in an entirely unicode world) and future imports (which are effectively
>> temporarily gone in 3.x until needed again).
>>
>> Newbies sometimes trip over def and class being imperative (executable)
>> statments rather than declarations.
>
> Er, declarative programming has nothing to do with variable declarations.
> http://en.wikipedia.org/wiki/Declarative_programming

I found it hard to get much from the vague description. I will leave it 
to Lawrence to list what *he* thinks are 'declarative constructs' in Python.




From nobody at nowhere.com  Tue May 11 16:03:35 2010
From: nobody at nowhere.com (Nobody)
Date: Tue, 11 May 2010 21:03:35 +0100
Subject: Is Python a functional programming language?
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
	<7xvdau8pzl.fsf@ruckus.brouhaha.com>
Message-ID: 

On Tue, 11 May 2010 07:36:30 -0700, Paul Rubin wrote:

> Offhand I can't tell that imperative and procedural mean something
> different.  Both basically mean that the programmer specifies a series of
> steps for the computer to carry out.  Functional languages are mostly
> declarative; for example, an expression like
>    x = 3
> is called an "equation" rather than an "assignment".  It declares "x is
> equal to 3", rather than directing x to be set to 3.  If someplace else in
> the program you say "x = 4", that is an error, normally caught by the
> compiler, since x cannot be equal to both 3 and 4.

In both ML and Haskell, bindings are explicitly scoped, i.e.

	let x = 3 in ... end	(ML)
	let x = 3 in ...	(Haskell)

If you bind a variable which is already bound, it introduces a new binding
which "overrides" the existing binding. It won't generate an error.

The key point is that a variable has a fixed (constant) value at any
specific point in the program. The value depends upon which bindings are
in scope at that point, and not on the "state" of the variable at a
particular point in time.

E.g. (Haskell):

	test y = let x = 3
	         in let f y = x + y
	            in let x = 5
	               in f y
	test 5
	8

x has the value 3 at the point that f is defined, so that's the value
which is used when f is used.



From clp2 at rebertia.com  Tue May 11 16:03:41 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Tue, 11 May 2010 13:03:41 -0700
Subject: First Timer
In-Reply-To: <002c01caf140$11a0eb00$34e2c100$@com>
References: <002c01caf140$11a0eb00$34e2c100$@com>
Message-ID: 

On Tue, May 11, 2010 at 12:28 PM, Donna Lane  wrote:
> I have downloaded Python and I'm a beginner in every sense.? What I want to
> know now is when I am in Idle and have made a syntax error how do I repair?
> After the error I can't type in
>
> anything and I get this bing noise.? Usually I just start idle over again.

You re-type or copy-paste and then fix the line(s) after the new >>>
prompt that appears after the SyntaxError message. You can't edit
lines you've already run.

Also, you can compose an entire file of code and then run the file,
rather than working directly at the interactive interpreter (aka
shell). File->New Window makes an empty file you can work in; pressing
F5 in the file editor window will run the file.

Cheers,
Chris
--
http://blog.rebertia.com


From nobody at nowhere.com  Tue May 11 16:07:30 2010
From: nobody at nowhere.com (Nobody)
Date: Tue, 11 May 2010 21:07:30 +0100
Subject: Is Python a functional programming language?
References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com>
	
	
Message-ID: 

On Tue, 11 May 2010 23:13:10 +1200, Lawrence D'Oliveiro wrote:

>> But the beauty is that Python is multi-paradigm ...
> 
> The trouble with ?multi-paradigm? is that it offends the zealots on
> all sides.

Is that how you view people who like languages to exhibit a degree of
consistency? Some people would prefer to have a manageable set of rules
rather than having to remember the results of all of the possible
combinations of interactions between language features.



From alan.isaac at gmail.com  Tue May 11 16:23:51 2010
From: alan.isaac at gmail.com (Alan G Isaac)
Date: Tue, 11 May 2010 16:23:51 -0400
Subject: documentation bug? (format spec mini language)
In-Reply-To: 
References: 
	
Message-ID: 

On 5/11/2010 3:19 PM, MRAB wrote:
> You usually want numbers to be right-aligned so that the decimal points
> line up when writing a columns of them.


Yes.  I'm not questioning the wisdom of the implementation,
just the documentation of it.

Thanks,
Alan



From pmaupin at gmail.com  Tue May 11 16:39:48 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Tue, 11 May 2010 13:39:48 -0700 (PDT)
Subject: Picking a license
References: 
	
	<4be5bdcb$0$27798$c3e8da3@news.astraweb.com>
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com>
	 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com>
Message-ID: <151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com>

On May 11, 5:24?am, Paul Boddie  wrote:
> On 10 Mai, 17:01, Patrick Maupin  wrote:
>
> > I'll be charitable and assume the fact that you can make that
> > statement without apparent guile merely means that you haven't read
> > the post I was referring to:
>
> >http://www.gnu.org/philosophy/why-not-lgpl.html
>
> Of course I have read it, and not just recently either. But this is a
> position paper by the author of the licence, and it doesn't mean that
> someone who has written a GPL-licensed library completely agrees with
> that position. And anyway, it's a case of "take it or leave it" - it's
> not like the author or the FSF are sneaking stuff into every product
> and every corner of the market and then telling you that you can't
> "unchoose" their stuff.

OK.  Now I'm REALLY confused.  I said "Certainly RMS
carefully lays out that the LGPL should be used sparingly in his "Why
you shouldn't use the Lesser GPL for your next library" post.  (Hint:
he's not suggesting a permissive license instead.)"

to which you replied:

"Sure, but all he's asking you to do is to make the software available
under a GPL-compatible licence."

and then I tried to politely show that you were wrong about RMS's
intentions, but now, but you're saying "oh, of course, he'd say that
-- he wrote the license"  which is basically what I've been saying all
along.  But if you have read it like you say, then it appears you were
being very disingenuous in your original reply!

> Although it seems quite unfair, the e-mail discussion about the
> licence does show that Stallman was not initially convinced that works
> should be affected in such a way (with regard to the Objective-C
> compiler developed by NeXT), and that Haible was not strongly opposed
> to changing the licence. You can argue that Stallman overreached by
> demanding a licence change and that consideration of such matters has
> progressed since that time, but Haible always had the option of not
> using or supporting readline - only the latter is contentious,

"was not strongly opposed to changing the license"  As I already
mentioned, he was more interested in doing useful stuff than worrying
about the license.  Yes, readline was the hook that sucked him into
using the GPL, but IMHO RMS was flat out wrong about the licensing
implications.  As I mentioned, though, the morality and the legality
are probably different animals.

> and the
> obligation of GPL-compatible licensing (as opposed to GPL-licensing)
> now diminishes how contentious this is today.

NO.  If you are building an application, and distributing GPLed stuff
as part of it, the FSF still maintains that the license is such that
the entire application must be GPLed.  You keep acting like this isn't
true, but it absolutely is if you're distributing the entire
application.

> > I think that, legally, they probably don't have a leg to stand on for
> > some of their overarching claims (e.g. about shipping proprietary
> > software that could link to readline, without even shipping
> > readline). ?But morally -- well, they've made their position
> > reasonably clear and I try to abide by it. ?That still doesn't make it
> > "not really FUD." ?I'd call this sort of badgering "copyright misuse"
> > myself.
>
> Again, you have to consider the intent of the licensing: that some
> software which links to readline results in a software system that
> should offer the "four freedoms", because that's the price of linking
> to readline whose licence has promised that any system which builds
> upon it shall offer those privileges.

But I did consider the intent, and as I have made clear, I think
that's a bullying tactic that fragments the software world
unnecessarily.  Obviously YMMV.

> > > As for rst2pdf, what your modifications would mean is that the
> > > software would need to be redistributed under a GPL-compatible
> > > licence.

NO.  You're still not paying attention.  The FSF's clear position is
that if you actually *redistribute* software under the GPL as *part of
a system* then the full package must be licensed *under the GPL*.

> Once again, I refer you to the intent of the licensing: if someone has
> the software in front of them which uses svglib, then they need to
> have the privileges granted to them by the GPL. Yes, if the software
> also uses some component with a GPL-incompatible licence, then this
> causes a problem.

It appears that the FSF's position is the ability to link to svglib
would require software to be licensed under the GPL.  I don't believe
that, but I do believe that if rst2pdf distributed svglib (or even
patches to svglib which were clearly derivative works) then yes,
rst2pdf would have to be distributed under the GPL.  This kind of
bullshit is only acceptable to people who only think a single license
is acceptable.

> [...]
>
> >http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystem
>
> > "A system incorporating a GPL-covered program is an extended version
> > of that program. The GPL says that any extended version of the program
> > must be released under the GPL if it is released at all."
>
> > This makes it clear that the overall work must be GPLed. ?Now, all of
> > a sudden, downstream users cannot do some things they could have done
> > before. ?Can you not see that taking a preexisting MIT-licensed
> > project and adding code to make it GPL could negatively affect some of
> > its users and that that is not necessarily an unalloyed good?
>
> Well, I have referred several times to WebKit without you taking the
> hint,

OK, I don't work with webkit.  I knew you were hinting at something,
but why the games, I don't know.  I guess it's all about mystique and
games.

> but that provides a specific case of a project which is LGPL-
> licensed despite being based on (in GPLv3 terminology) libraries which
> were distributed under the GPL and combined with that software.

What other libraries?  I don't know it's history.  I give you specific
examples at problems; you hint around at things you claim are not
problems and then still don't give specifics.

> Similarly, the effort to ensure that CPython's licence was GPL-
> compatible had a lot to do with the right to redistribute with GPL-
> licensed code (actually readline, if I remember correctly).

Yes, but the Python project doesn't actually distribute readline, and
(as I mentioned) people are more informed now, and it would be
difficult for RMS to bully Python into relicensing.  But if the Python
distribution *included* GNU Readline, then RMS would be on firmer
ground, and the license would probably have to be changed.  This is
*exactly* the situation I was describing with svglib -- can you still
not see that it is a problem to just toss unsupported free software
out there with a GPL license?  Unsupported Apache or MIT is fine --
fix it or ignore.  Unsupported GPL is an attractive nuisance.


> Is readline trivial? Was readline trivial in 1992?

Again, you could have neural net prediction and other fancy
technologies, but in general, yes, the concept is pretty trivial and
there were many systems that already had such things back then.

> Does it even
> matter, because the author is more or less saying that they don't want
> their code incorporated in a proprietary system?

Yes it matters because as others have pointed out, sometimes people
use stuff which is purported to be "free" without a full understanding
of all the implications.  But this gets back to my general complaint
about co-opting the word "free" which you don't think is a problem
because you have chosen to use other words.

> It's interesting to
> see that GPLv3 doesn't talk about derived works or derivatives (at
> least not as much as GPLv2), but instead talks about things being
> "based on" other things, but as I've already said, at the point of
> someone running a bunch of software components together, the intent of
> copyleft licences is to say that the user should be able to take that
> (or part of it, in the case of "weak copyleft" licences) and change,
> recompile and distribute its sources, modified or not.

Trust me, I know the intent, and could even consider it a noble goal.
But I think a lot of the means employed in getting to this end are
simply wrong.

Regards,
Pat


From davea at ieee.org  Tue May 11 16:42:35 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 May 2010 16:42:35 -0400
Subject: default argument
In-Reply-To: <439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>	<7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>
	
	<439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
Message-ID: <4BE9C13B.3020503@ieee.org>



Back9 wrote:
> On May 11, 3:20 pm, Chris Rebert  wrote:
>   
>> On Tue, May 11, 2010 at 12:08 PM, Back9  wrote:
>>     
>>> On May 11, 3:06 pm, Back9  wrote:
>>>       
>> 
>>     
>>>> When i try it, it complains about undefined self.
>>>>         
>>>> i don't know why.
>>>>         
>>>> TIA
>>>>         
>>> Sorry
>>> here is the what i meant
>>> class test:
>>>  self._value =0
>>>  def func(self, pos =elf._value)
>>>       
>> You're still defining the class, so how could there possibly be an
>> instance of it to refer to as "self" yet (outside of a method body)?
>> Also, just so you know, default argument values are only evaluated
>> once, at the time the function/method is defined, so `pos > self._value` is never going to work.
>>
>> Do you mean for self._value to be a class variable (Java lingo: static
>> variable), or an instance variable?
>>
>> Cheers,
>> Chris
>> --http://blog.rebertia.com
>>     
>
> self._value will be instance variable
>
>   
If you want an instance value to be your default, you'll need to us an 
indirect approach.  There are no instances at the time the class is 
defined.  So you want to create such a value in the __init__() method.
Something like the following (untested):

class  Test(object):
     def __init__(self, initvalue):
         self.value = initvalue
     def func(self, pos = None):
          if pos=None:   pos = self.value
          etc.

x = Test(44)
x.func(91)          #uses 91 for pos
x.func()              #uses 44 for pos


DaveA


From pmaupin at gmail.com  Tue May 11 16:50:41 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Tue, 11 May 2010 13:50:41 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	
Message-ID: 

On May 11, 5:34?am, Paul Boddie  wrote:
> On 10 Mai, 20:36, Patrick Maupin  wrote:

> > I've addressed this before. ?Aahz used a word in an accurate, but to
> > you, inflammatory, sense, but it's still accurate -- the man *would*
> > force you to pay for the chocolate if you took it.
>
> Yes, *if* you took it. He isn't forcing you to take it, though, is he?

No,  but he said a lot of words that I didn't immediately understand
about what it meant to be free and that it was free, and then after I
bit into it he told me he owned my soul now.

> > You're making it sound like whining, but Aahz was simply trying to state a fact.
>
> It is whining if someone says, "I really want that chocolate, but that
> nasty man is going to make me pay for it!"

But that's not what happened.  I mean, he just told me that I might
have to give some of it to others later.  He didn't mention that if I
spread peanut butter on mine before I ate it that I'd have to give
people Reese's Peanut Butter cups.

>
> >?The fact is, I know the man would force me to pay for the chocolate, so in
> > some cases that enters into the equation and keeps me from wanting the
> > chocolate.
>
> If the man said, "please take the chocolate, but I want you to share
> it with your friends", and you refused to do so because you couldn't
> accept that condition, would it be right to say, "that man is forcing
> me to share chocolate with my friends"?

But the thing is, he's *not* making me share the chocolate with any of
my friends.  He's not even making me share my special peanut butter
and chocolate.  What he's making me do is, if I give my peanut butter
and chocolate to one of my friends, he's making me make *that* friend
promise to share.  I try not to impose obligations like that on my
friends, so obviously the "nice" man with the chocolate isn't my
friend!

> > ?This isn't whining; just a common-sense description of
> > reality. ?Personally, I think this use of the word "force" is much
> > less inflammatory than the deliberate act of co-opting the word
> > "freedom" to mean "if you think you can take this software and do
> > anything you want with it, you're going to find out differently when
> > we sue you."
>
> The word "freedom" means a number of things. If you don't like the way
> Messrs Finney and Stallman use the term, please take it up with them.
> But to say that someone entering a voluntary agreement is "forced" to
> do something, when they weren't forced into that agreement in the
> first place, is just nonsense. It's like saying that the shopkeeper is
> some kind of Darth Vader character who is coercing people to take the
> chocolate and then saddling them with obligations against their will.

I explained this very carefully before multiple times.  Let me give
concrete examples -- (1) I have told my children before "if we take
that candy, then they will make us pay for it" and (2) if we included
(GPLed software) in this (MIT-licensed software) then we will have to
change the license.  In both these cases, once the decision has been
made, then yes, force enters into it.  And no, I don't think the
average shop keeper is nearly as evil as Darth, or even RMS.

Regards,
Pat


From pmaupin at gmail.com  Tue May 11 17:02:06 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Tue, 11 May 2010 14:02:06 -0700 (PDT)
Subject: Picking a license
References: 
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com>
	 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<4be95545$1@dnews.tpgi.com.au>
	
Message-ID: 

On May 11, 9:00?am, Paul Boddie  wrote:
> On 11 Mai, 15:00, Lie Ryan  wrote:
> > Come on, 99% ?of the projects released under GPL did so because they
> > don't want to learn much about the law; they just need to release it
> > under a certain license so their users have some legal certainty.
>
> Yes, this is frequently the case. And the GPL does offer some
> certainty that various permissive licences do not.

Huh? Permissive licenses offer much better certainty for someone
attempting a creative mash-up.  Different versions of the Apache
license don't conflict with each other.  If I use an MIT-licensed
component, it doesn't attempt to make me offer my whole work under
MIT.

[..]
>
> Well, that's always an option as well, but at the same time, there are
> people willing to pursue licence violations, and these people have
> done so successfully. There's no need to make an impassioned argument
> for apathy, though. Some people do wish to dictate what others can do
> with their work.

Oh, I get it.  You were discussing the certainty that an author can
control what downstream users do with the software to some extent.
Yes, I fully agree.  The GPL is for angry idealists who have an easily
outraged sense of justice, who don't have enough real problems to work
on.

BTW, I'm here to make an impassioned argument for apathy.  For
example, I think the world needs fewer suicide bombers, and the more
apathy we can get.

Regards,
Pat


From pmaupin at gmail.com  Tue May 11 17:03:08 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Tue, 11 May 2010 14:03:08 -0700 (PDT)
Subject: Picking a license
References: 
	
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	<4be93cee$0$27837$c3e8da3@news.astraweb.com>
Message-ID: <35e2b804-2e96-437e-8a72-325dc2b06c57@a39g2000prb.googlegroups.com>

On May 11, 6:18?am, Steven D'Aprano  wrote:
> Last time I came home with chocolate, I tried that excuse on my wife. She
> didn't believe it for a second.
>
> Next time, I'll try claiming that I was obliged to eat the chocolate
> because of the GPL.

Good luck with that.  Women can always see right through bad
analogies, especially where chocolate is concerned!

Regards,
Pat


From tjreedy at udel.edu  Tue May 11 17:05:19 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 17:05:19 -0400
Subject: documentation bug? (format spec mini language)
In-Reply-To: <4BE9ADD9.9030901@mrabarnett.plus.com>
References: 
	<4BE9ADD9.9030901@mrabarnett.plus.com>
Message-ID: 

On 5/11/2010 3:19 PM, MRAB wrote:
> Alan G Isaac wrote:
>> The documentation at
>> http://docs.python.org/py3k/library/string.html#format-specification-mini-language
>>
>>
>> '<' Forces the field to be left-aligned within the available space
>> (This is the default.)
>>
>> The conflicting example::
>>
>> >>> format(3.2,'10.5f')
>> ' 3.20000'
>> >>> format(3.2,'<10.5f')
>> '3.20000 '
>>
>> Am I somehow misreading the documentation?
>>
> It does look misleading. Numbers default to right-aligned, as you
> discovered.
>
> You usually want numbers to be right-aligned so that the decimal points
> line up when writing a columns of them.

http://bugs.python.org/issue8691



From martin at v.loewis.de  Tue May 11 17:13:55 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Tue, 11 May 2010 23:13:55 +0200
Subject: Upgrade Python 2.6.4 to 2.6.5
In-Reply-To: 
References: 	<4BE86BC1.8040102@v.loewis.de>
	
Message-ID: <4BE9C893.1070104@v.loewis.de>

> When will it install into system32?

When you install "for all users".

>> Did the upgrade inform you that it was an upgrade, or did it warn you
>> that you would overwrite the previous installation?
>>    
> It warned me that there is a previous installation.

Hmm. You don't remember the exact message, do you?
I guess it was a popup saying "[TARGETDIR] exists. Are you sure you want
to overwrite existing files?", and that it was not
a red text saying "This update will replace your existing [ProductLine]
installation."

Please confirm.

If so, you now have two Python installations in the same location; one
for all users, and the older one just for you (or vice versa).

I recommend to uninstall them both, and start over.

Regards,
Martin


From tjreedy at udel.edu  Tue May 11 17:19:50 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 17:19:50 -0400
Subject: default argument
In-Reply-To: <439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>	<7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>
	
	<439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
Message-ID: 

On 5/11/2010 3:41 PM, Back9 wrote:

>
> self._value will be instance variable

Then set it in the __init__ method. Read the tutorial and ref manual on 
Python class statements, which are a bit different from what you might 
be used to.




From python at bdurham.com  Tue May 11 17:27:03 2010
From: python at bdurham.com (python at bdurham.com)
Date: Tue, 11 May 2010 17:27:03 -0400
Subject: Upgrade Python 2.6.4 to 2.6.5
In-Reply-To: <4BE9C893.1070104@v.loewis.de>
References: 
	<4BE86BC1.8040102@v.loewis.de>
	<4BE9C893.1070104@v.loewis.de>
Message-ID: <1273613223.8700.1374581741@webmail.messagingengine.com>

Martin,

If we install over an existing version of Python 2.6.5, will our PTH
files and site-packages be preserved?

Or do we need to back out our 3rd party packages, install Python 2.6.5
and then manually restore our 3rd party packages?

Thank you,
Malcolm


From tjreedy at udel.edu  Tue May 11 17:37:53 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 17:37:53 -0400
Subject: First Timer
In-Reply-To: <002c01caf140$11a0eb00$34e2c100$@com>
References: <002c01caf140$11a0eb00$34e2c100$@com>
Message-ID: 

On 5/11/2010 3:28 PM, Donna Lane wrote:
> I have downloaded Python and I'm a beginner in every sense.

Welcome. I hope you enjoy Python too.

 > What I want to
> know now is when I am in Idle and have made a syntax error how do I repair?
> After the error I can't type in anything and I get this bing noise.
 > Usually I just start idle over again.

You cannot directly repair a line already ed. You must enter a 
new line. In the command line interpreter, you should be able to hit up 
arrow and have the line above copied to the current entry line for 
correction. In IDLE, this does not yet work, so copy and paste or retype.

For anything too complicated for either of those (more than one line), I 
use (and reuse) a temporary edit file in an edit window. Just make sure 
the file is named .py rather than just . You save 
and run the file with F5. If there is a syntax error, IDLE will say so 
and reopen the cursor window with the cursor at (or after) the location 
of the error. Fix and hit F5 again. Very fast.

The main thing to watch is that you must say 'print(x)' rather than just 
'x' to print. File/Recent files lets one easily reopen the tem file (or 
any other of the 20 most recently edited files).

I use the tem file when I copy and paste more than a single line of code 
from, say, a post here.

Terry Jan Reedy




From debatem1 at gmail.com  Tue May 11 17:40:36 2010
From: debatem1 at gmail.com (geremy condra)
Date: Tue, 11 May 2010 17:40:36 -0400
Subject: open(False) in python3
Message-ID: 

I'm unsure if this qualifies as a bug (it is also clearly user error) but I just
ran into a situation where open() was inadvertantly called on a False,
and I was somewhat surprised to see that this didn't bail horribly, but
rather hung forever. Here's some example sessions for python3.x and
python2.x:

@:~$ python3
Python 3.1.2 (r312:79147, Apr 15 2010, 12:35:07)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open(False)
>>> f.read()
^CTraceback (most recent call last):
  File "", line 1, in 
KeyboardInterrupt
>>>
@:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open(False)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: coercing to Unicode: need string or buffer, bool found
>>>

Should I chalk this up to stupid coder syndrome or file a bug report?

Geremy Condra


From vinay_sajip at yahoo.co.uk  Tue May 11 17:43:07 2010
From: vinay_sajip at yahoo.co.uk (Vinay Sajip)
Date: Tue, 11 May 2010 14:43:07 -0700 (PDT)
Subject: Version 0.3.9 of the Python config module has been released.
Message-ID: 

Version 0.3.9 of the Python config module has been released.

What Does It Do?
================
The config module allows you to implement a hierarchical configuration
scheme with support for mappings and sequences, cross-references
between one part of the configuration and another, the ability to
flexibly access real Python objects, facilities for configurations to
include and cross-reference one another, simple expression evaluation
and the ability to change, save, cascade and merge configurations. You
can easily integrate with command line options using optparse.

This module has been developed on python 2.3 but should work on
version 2.2 or greater. A test suite using unittest is included in the
distribution.

A very simple configuration file (simple.cfg):

# starts here
message: Hello, world!
#ends here

a very simple program to use it:

from config import Config

cfg = Config(file('simple.cfg'))
print cfg.message

results in:

Hello, world!

Configuration files are key-value pairs, but the values can be
containers that contain further values.

A simple example - with the example configuration file:

messages:
[
  {
    stream : `sys.stderr`
    message: 'Welcome'
    name: 'Harry'
  }
  {
    stream : `sys.stdout`
    message: 'Welkom'
    name: 'Ruud'
  }
  {
    stream : $messages[0].stream
    message: 'Bienvenue'
    name: Yves
  }
]

a program to read the configuration would be:

from config import Config

f = file('simple.cfg')
cfg = Config(f)
for m in cfg.messages:
    s = '%s, %s' % (m.message, m.name)
    try:
        print >> m.stream, s
    except IOError, e:
        print e

which, when run, would yield the console output:

Welcome, Harry
Welkom, Ruud
Bienvenue, Yves

The above example just scratches the surface. There's more information
about this module available at

http://www.red-dove.com/config-doc/

Comprehensive API documentation is available at

http://www.red-dove.com/config/index.html

As always, your feedback is most welcome (especially bug reports,
patches and suggestions for improvement). Enjoy!

Cheers

Vinay Sajip
Red Dove Consultants Ltd.

Changes since the last release posted on comp.lang.python[.announce]:
=====================================================
Fix bug in parsing numbers with exponents (reported
by Philip S?eberg).


From inq1ltd at inqvista.com  Tue May 11 17:49:43 2010
From: inq1ltd at inqvista.com (jim-on-linux)
Date: Tue, 11 May 2010 17:49:43 -0400
Subject: py2exe help
In-Reply-To: 
References: 
	
	
Message-ID: <201005111749.43342.inq1ltd@inqvista.com>

python help,

I'm open for suggestions.

I'm using py2exe to compile a working program.

The program runs and prints fine until I compile it with py2exe. 

After compiling the program, it runs fine until it tries to import 
the win32ui module, v2.6214.0. 

Then, I get a windows error message:

ImportError: Dll load failed:  
This application has failed to start because 
the application configuration is incorrect.
Reinstalling the application may fix this problem.


Anyone have the same problem with this?.

jim-on linux


From python.list at tim.thechases.com  Tue May 11 17:53:48 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Tue, 11 May 2010 16:53:48 -0500
Subject: Limitation of os.walk
In-Reply-To: 
References: 
Message-ID: <4BE9D1EC.8040500@tim.thechases.com>

On 05/11/2010 02:49 PM, kj wrote:
> I want implement a function that walks through a directory tree
> and performs an analsysis of all the subdirectories found.  The
> task has two essential requirements that, AFAICT, make it impossible
> to use os.walk for this:
>
> 1. I need to be able to prune certain directories from being visited.
>
> 2. The analysis on each directory can be performed only after it
>     has been performed on all its subdirectories.
>
> Unless I'm missing something, to do (1), os.walk must be run with
> topdown=True, whereas to do (2) it must be run with topdown=False.

I don't think there's a way to coerce os.walk into doing what you 
want.  That said, the core source for os.walk() is a whole 23 
lines of code, it's easy enough to just clone it and add what you 
need...

> PS: I never understood why os.walk does not support hooks for key
> events during such a tree traversal.

including hooks for calling pre/post hooks.

-tkc




From bryanjugglercryptographer at yahoo.com  Tue May 11 18:01:44 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Tue, 11 May 2010 15:01:44 -0700 (PDT)
Subject: Extract all words that begin with x
References: 
	 
	 
	
	
Message-ID: <1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com>

Tycho Andersen wrote:
> Terry Reedy wrote:
> > ?... word[0:1] does the same thing. All Python programmers should learn to
> > use slicing to extract a ?char from a string that might be empty.
> > The method call of .startswith() will be slower, I am sure.
>
> Why? Isn't slicing just sugar for a method call?

Yes, but finding the method doesn't require looking it up by name at
run-time, and startswith is built to work for startings of any length.

Let's timeit:

# -----
from timeit import Timer
from random import choice
from string import ascii_lowercase as letters

strs = [''.join([choice(letters) for _ in range(5)])
        for _ in range(5000)]

way1 = "[s for s in strs if s.startswith('a')]"
way2 = "[s for s in strs if s[:1] == 'a']"

assert eval(way1) == eval(way2)

for way in [way1, way2]:
    t = Timer(way, 'from __main__ import strs')
    print(way, ' took: ', t.timeit(1000))

# -----

On my particular box, I get:

[s for s in strs if s.startswith('a')]  took:  5.43566498797
[s for s in strs if s[:1] == 'a']  took:  3.20704924968

So Terry Reedy was right: startswith() is slower. I would,
nevertheless, use startswith(). Later, if users want my program to run
faster and my profiling shows a lot of the run-time is spent finding
words that start with 'a', I might switch.

--
--Bryan


From rtw at rtw.me.uk  Tue May 11 18:25:10 2010
From: rtw at rtw.me.uk (Rob Williscroft)
Date: Tue, 11 May 2010 17:25:10 -0500
Subject: py2exe help
References: 
	
	
	
Message-ID: 

jim-on-linux wrote in news:mailman.74.1273614703.32709.python-list at python.org 
in comp.lang.python:

> python help,
> 
> I'm open for suggestions.
> 
> I'm using py2exe to compile a working program.
> 
> The program runs and prints fine until I compile it with py2exe. 
> 
> After compiling the program, it runs fine until it tries to import 
> the win32ui module, v2.6214.0. 
> 
> Then, I get a windows error message:
> 
> ImportError: Dll load failed:  
> This application has failed to start because 
> the application configuration is incorrect.
> Reinstalling the application may fix this problem.
> 
> 
> Anyone have the same problem with this?.

http://www.py2exe.org/index.cgi/Py2exeAndWin32ui

Rob.


From gagsl-py2 at yahoo.com.ar  Tue May 11 18:27:37 2010
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Tue, 11 May 2010 19:27:37 -0300
Subject: open(False) in python3
References: 
Message-ID: 

En Tue, 11 May 2010 18:40:36 -0300, geremy condra   
escribi?:

> I'm unsure if this qualifies as a bug (it is also clearly user error)  
> but I just
> ran into a situation where open() was inadvertantly called on a False,
> and I was somewhat surprised to see that this didn't bail horribly, but
> rather hung forever. Here's some example sessions for python3.x and
> python2.x:
>
> @:~$ python3
> Python 3.1.2 (r312:79147, Apr 15 2010, 12:35:07)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> f = open(False)
>>>> f.read()
> ^CTraceback (most recent call last):
>   File "", line 1, in 
> KeyboardInterrupt

open() in Python 3 does a lot of things; it's like a mix of codecs.open()  
+ builtin open() + os.fdopen() from 2.x all merged together. It does  
different things depending on the type and quantity of its arguments, and  
even returns objects of different types.

In particular, open(some_integer) assumes some_integer is a file  
descriptor and return some variant of file object using the given file  
descriptor.

Now, False is an instance of bool, a subclass of int, and is numerically  
equal to 0:

p3> isinstance(False, int)
True
p3> False==0
True

so open(False) is the same as open(0), and 0 is the file descriptor  
associated to standard input. The program isn't hung, it's just waiting  
for you to type some text:

p3> f = open(False)
p3> f.read()
Type some text
^Z
^Z
'Type some text\n'
p3>


> Should I chalk this up to stupid coder syndrome or file a bug report?

Uhm, perhaps the bug is, bool should not inherit from int in Python 3, but  
it's way too late to change that.

-- 
Gabriel Genellina



From mensanator at aol.com  Tue May 11 19:03:37 2010
From: mensanator at aol.com (Mensanator)
Date: Tue, 11 May 2010 16:03:37 -0700 (PDT)
Subject: First Timer
References: <002c01caf140$11a0eb00$34e2c100$@com>
	
Message-ID: 

On May 11, 4:37?pm, Terry Reedy  wrote:
> On 5/11/2010 3:28 PM, Donna Lane wrote:
>
> > I have downloaded Python and I'm a beginner in every sense.
>
> Welcome. I hope you enjoy Python too.
>
> ?> What I want to> know now is when I am in Idle and have made a syntax error how do I repair?
> > After the error I can't type in anything and I get this bing noise.
>
> ?> Usually I just start idle over again.
>
> You cannot directly repair a line already ed.

Ok.

> You must enter a new line.

Huh?! I suppose it depends on what you mean by "enter".

> In the command line interpreter, you should be able to hit up
> arrow and have the line above copied to the current entry line for
> correction. In IDLE, this does not yet work,

It doesn't have to. Simply place the cursor on the line you originally
entered and hit .

> so copy and paste or retype.

The line will be repeated as a new line which you can edit
and make corrections.

>
> For anything too complicated for either of those (more than one line), I
> use (and reuse) a temporary edit file in an edit window. Just make sure
> the file is named .py rather than just . You save
> and run the file with F5. If there is a syntax error, IDLE will say so
> and reopen the cursor window with the cursor at (or after) the location
> of the error. Fix and hit F5 again. Very fast.

Sounds like you're making a mountain out of a molehill. You deserve
a medal if you've been using IDLE without knowing how to edit.

>
> The main thing to watch is that you must say 'print(x)' rather than just
> 'x' to print. File/Recent files lets one easily reopen the tem file (or
> any other of the 20 most recently edited files).
>
> I use the tem file when I copy and paste more than a single line of code
> from, say, a post here.
>
> Terry Jan Reedy



From no.email at please.post  Tue May 11 19:49:04 2010
From: no.email at please.post (kj)
Date: Tue, 11 May 2010 23:49:04 +0000 (UTC)
Subject: Limitation of os.walk
References: 
	
Message-ID: 

In  Tim Chase  writes:

>That said, the core source for os.walk() is a whole 23 
>lines of code, it's easy enough to just clone it and add what you 
>need...

Thanks, that was a good idea.

~K


From inq1ltd at inqvista.com  Tue May 11 21:24:12 2010
From: inq1ltd at inqvista.com (jim-on-linux)
Date: Tue, 11 May 2010 21:24:12 -0400
Subject: py2exe help
In-Reply-To: 
References: 
	
	
Message-ID: <201005112124.12663.inq1ltd@inqvista.com>



I appreciate the help, it's working.

jim-on-linux


> jim-on-linux wrote in
>  news:mailman.74.1273614703.32709.python-list at python.org
> 
> in comp.lang.python:
> > python help,
> >
> > I'm open for suggestions.
> >
> > I'm using py2exe to compile a working program.
> >
> > The program runs and prints fine until I compile it with 
py2exe.
> >
> > After compiling the program, it runs fine until it tries to 
import
> > the win32ui module, v2.6214.0.
> >
> > Then, I get a windows error message:
> >
> > ImportError: Dll load failed:
> > This application has failed to start because
> > the application configuration is incorrect.
> > Reinstalling the application may fix this problem.
> >
> >
> > Anyone have the same problem with this?.
> 
> http://www.py2exe.org/index.cgi/Py2exeAndWin32ui
> 
> Rob.
> 


From no.email at nospam.invalid  Tue May 11 21:31:03 2010
From: no.email at nospam.invalid (Paul Rubin)
Date: Tue, 11 May 2010 18:31:03 -0700
Subject: Is Python a functional programming language?
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
	<7xvdau8pzl.fsf@ruckus.brouhaha.com>
	
Message-ID: <7xr5lhaotk.fsf@ruckus.brouhaha.com>

Nobody  writes:
>> is called an "equation" rather than an "assignment".  It declares "x is
>> equal to 3", rather than directing x to be set to 3.  If someplace else in
>> the program you say "x = 4", that is an error, normally caught by the
>> compiler, since x cannot be equal to both 3 and 4.
>
> In both ML and Haskell, bindings are explicitly scoped, i.e.
> 	let x = 3 in ...	(Haskell)

I'm not talking about nested bindings.  I'm talking about two different
bindings of the same symbol in the same scope:

    $ cat meow.hs
    x = 3
    x = 4
    $ ghc meow.hs

    meow.hs:2:0:
        Multiple declarations of `Main.x'
        Declared at: meow.hs:1:0
                     meow.hs:2:0


From tjreedy at udel.edu  Tue May 11 21:50:02 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 21:50:02 -0400
Subject: Upgrade Python 2.6.4 to 2.6.5
In-Reply-To: <1273613223.8700.1374581741@webmail.messagingengine.com>
References: 	<4BE86BC1.8040102@v.loewis.de>	<4BE9C893.1070104@v.loewis.de>
	<1273613223.8700.1374581741@webmail.messagingengine.com>
Message-ID: 

On 5/11/2010 5:27 PM, python at bdurham.com wrote:
> Martin,
>
> If we install over an existing version of Python 2.6.5, will our PTH
> files and site-packages be preserved?
>
> Or do we need to back out our 3rd party packages, install Python 2.6.5
> and then manually restore our 3rd party packages?

In my experience on WinXP, installing x.y.z+1 over x.y.z nicely leaves 
sitepackages alone as well as any other directories I have added under 
the pythonxy directory. An uninstall and reinstall should also leave 
user stuff alone.

Installing x.y+1 create and install in a new pythonx directory, 
leaving one to copy from pythonxy subdirs as desired.

It appears that the OP confused things by switching between one and all 
user installs.

Terry Jan Reedy





From zhenhua.zhang at intel.com  Tue May 11 21:59:52 2010
From: zhenhua.zhang at intel.com (Zhang, Zhenhua)
Date: Wed, 12 May 2010 09:59:52 +0800
Subject: How to pass file descriptor through dbus call in python
Message-ID: <33AB447FBD802F4E932063B962385B351E79F6EB@shsmsx501.ccr.corp.intel.com>

Hi,
Hi,

DBus 1.3 supports passing file descriptor through dbus method call. So I am writing a python test case to verify my interface. Can someone answer my question: how to pass a file descriptor through python-dbus call? For example:

	import os
	
	m, s = os.openpty()
	
	bus = dbus.SystemBus()
	obj = dbus.Interface(bus.get_object('org.xxx', '/', interface)
	obj.Create(m)

Python tells me that: org.freedesktop.DBus.Error.UnknowMethod: Method 'Create' with signature "i" on interface 'xxx' doesn't exist. Obviously it interprets 'm' as 'i' instead of 'h'.

Regards,
Zhenhua
 

From tjreedy at udel.edu  Tue May 11 22:07:35 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 22:07:35 -0400
Subject: Limitation of os.walk
In-Reply-To: 
References: 
Message-ID: 

On 5/11/2010 3:49 PM, kj wrote:
>
>
>
> I want implement a function that walks through a directory tree
> and performs an analsysis of all the subdirectories found.  The
> task has two essential requirements that, AFAICT, make it impossible
> to use os.walk for this:
>
> 1. I need to be able to prune certain directories from being visited.
>
> 2. The analysis on each directory can be performed only after it
>     has been performed on all its subdirectories.
>
> Unless I'm missing something, to do (1), os.walk must be run with
> topdown=True, whereas to do (2) it must be run with topdown=False.
>
> Is there a work around that I'm missing?

(I was going to say, 'Copy the code from os.py and revise to suit' -- 
but I see this has been posted since I wrote it ;-)

> PS: I never understood why os.walk does not support hooks for key
> events during such a tree traversal.

Either 1) it is intentionally simple, with the expectation that people 
would write there own code for more complicated uses or 2) no one has 
submitted a 'full-featured' version or 3) both.

If os.walk were rewritten, it should be as an iterator (generator). 
Directory entry and exit functions could still be added as params.

Terry Jan Reedy






From tjreedy at udel.edu  Tue May 11 22:21:08 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 22:21:08 -0400
Subject: Extract all words that begin with x
In-Reply-To: <1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com>
References: 	
	
		
	<1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com>
Message-ID: 

On 5/11/2010 6:01 PM, Bryan wrote:
> Tycho Andersen wrote:
>> Terry Reedy wrote:
>>>   ... word[0:1] does the same thing. All Python programmers should learn to
>>> use slicing to extract a  char from a string that might be empty.
>>> The method call of .startswith() will be slower, I am sure.
>>
>> Why? Isn't slicing just sugar for a method call?
>
> Yes, but finding the method doesn't require looking it up by name at
> run-time, and startswith is built to work for startings of any length.
>
> Let's timeit:
>
> # -----
> from timeit import Timer
> from random import choice
> from string import ascii_lowercase as letters
>
> strs = [''.join([choice(letters) for _ in range(5)])
>          for _ in range(5000)]
>
> way1 = "[s for s in strs if s.startswith('a')]"
> way2 = "[s for s in strs if s[:1] == 'a']"
>
> assert eval(way1) == eval(way2)
>
> for way in [way1, way2]:
>      t = Timer(way, 'from __main__ import strs')
>      print(way, ' took: ', t.timeit(1000))
>
> # -----
>
> On my particular box, I get:
>
> [s for s in strs if s.startswith('a')]  took:  5.43566498797
> [s for s in strs if s[:1] == 'a']  took:  3.20704924968
>
> So Terry Reedy was right: startswith() is slower. I would,
> nevertheless, use startswith(). Later, if users want my program to run
> faster and my profiling shows a lot of the run-time is spent finding
> words that start with 'a', I might switch.

Thank you for that timing report.

My main point is that there are two ways to fetch a char, the difference 
being the error return -- exception IndexError versus error value ''. 
This is an example of out-of-band versus in-band error/exception 
signaling, which programmers, especially of Python, should understand.

The fact that in Python syntax tends to be faster than calls was 
secondary, though good to know on occasion.

.startswith and .endswith are methods that wrap the special cases of 
slice at an end and compare to one value. There are not necessary, and 
save no keystrokes, but Guido obviously thought they added enough to 
more than balance the slight expansion of the language. They were added 
after I learned Python and I thought the tradeoff to be a toss-up, but I 
will consider using the methods when writing didactic code meant to be 
read by others.

Terry Jan Reedy



From ldo at geek-central.gen.new_zealand  Tue May 11 22:31:04 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Wed, 12 May 2010 14:31:04 +1200
Subject: virtualenvwrapper for Windows (Powershell)
References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com>
	
	<973ca0fa-4a2f-4e3b-91b9-e38917885c0f@d27g2000yqc.googlegroups.com>
Message-ID: 

In message
<973ca0fa-4a2f-4e3b-91b9-e38917885c0f at d27g2000yqc.googlegroups.com>, 
Guillermo wrote:

> On May 11, 7:43 am, Lawrence D'Oliveiro 
> wrote:
>
>> In message
>> <22cf35af-44d1-43fe-8b90-07f2c6545... at i10g2000yqh.googlegroups.com>,
>>
>> Guillermo wrote:
>>
>>> If you've ever missed it on Windows and you can use Powershell ...
>>
>> I thought the whole point of Windows was to get away from this
>> command-line stuff. Not such a good idea after all?
> 
> I suppose it depends.

On the way it?s implemented? Microsoft seems to have botched that as well.


From tjreedy at udel.edu  Tue May 11 22:32:22 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 22:32:22 -0400
Subject: First Timer
In-Reply-To: 
References: <002c01caf140$11a0eb00$34e2c100$@com>	
	
Message-ID: 

On 5/11/2010 7:03 PM, Mensanator wrote:
> On May 11, 4:37 pm, Terry Reedy  wrote:
>
>> In the command line interpreter, you should be able to hit up
>> arrow and have the line above copied to the current entry line for
>> correction. In IDLE, this does not yet work,
>
> It doesn't have to. Simply place the cursor on the line you originally
> entered and hit.
>
>> so copy and paste or retype.
>
> The line will be repeated as a new line which you can edit
> and make corrections.

Thank you for the information. I obviously have never seen that written 
anywhere and never thought to try it. It will save me time.

>> For anything too complicated for either of those (more than one line), I
>> use (and reuse) a temporary edit file in an edit window. Just make sure
>> the file is named.py rather than just. You save
>> and run the file with F5. If there is a syntax error, IDLE will say so
>> and reopen the cursor window with the cursor at (or after) the location
>> of the error. Fix and hit F5 again. Very fast.
>
> Sounds like you're making a mountain out of a molehill. You deserve
> a medal if you've been using IDLE without knowing how to edit.

Huh? I was explaining, perhaps clumbsily, how to easily edit, run, 
re-edit, and re-run multiple statements, in an editor window meant for 
that job, which cannot so easily be done in the shell, if at all.

Unlike the raw interpreter window, IDLE does not allow pasting of 
multiple statements in its simulated shell (well it does, but it ignores 
any after the first). So using an editor window in that case also is 
necessary.

Terry Jan Reedy



From python.list at tim.thechases.com  Tue May 11 22:38:02 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Tue, 11 May 2010 21:38:02 -0500
Subject: Limitation of os.walk
In-Reply-To: 
References:  
Message-ID: <4BEA148A.7020800@tim.thechases.com>

  05/11/2010 09:07 PM, Terry Reedy wrote:
>> PS: I never understood why os.walk does not support hooks for key
>> events during such a tree traversal.
>
> Either 1) it is intentionally simple, with the expectation that people
> would write there own code for more complicated uses or 2) no one has
> submitted a 'full-featured' version or 3) both.
>
> If os.walk were rewritten, it should be as an iterator (generator).
> Directory entry and exit functions could still be added as params.

It *is* an iterator/generator.  However, I suspect you mean that 
it should slurp the dirs/files iteratively instead of using 
listdir() as was discussed on c.l.p a few months back.

The patch to os.py would be fairly simple, something like
--------------------------------------------
--- /usr/lib/python2.5/os.py
+++ ~/tmp/os.py
@@ -220,7 +220,7 @@

  __all__.extend(["makedirs", "removedirs", "renames"])

-def walk(top, topdown=True, onerror=None):
+def walk(top, topdown=True, onerror=None, pre=None, post=None):
      """Directory tree generator.

      For each directory in the directory tree rooted at top 
(including top
@@ -296,15 +296,19 @@
          else:
              nondirs.append(name)

+    if pre is not None:
+        top, dirs, nondirs = pre(top, dirs, nondirs)
      if topdown:
          yield top, dirs, nondirs
      for name in dirs:
          path = join(top, name)
          if not islink(path):
-            for x in walk(path, topdown, onerror):
+            for x in walk(path, topdown, onerror, pre=pre, 
post=post):
                  yield x
      if not topdown:
          yield top, dirs, nondirs
+    if post is not None:
+        post(top, dirs, nondirs)

--------------------------------------------

which would allow you to do things like

   def pre(top, dirs, nondirs):
       dirs = [d for d in dirs
               if d not in ('RCS', '.svn', '.hg', '.git')]
       return top, dirs, nondirs
   def post(top, dirs, nondirs):
       complex_process(top)
   for top, dirs, nondirs in my.walk(PATH, pre=pre, post=post):
       do_stuff(...)

I suspect if I thought about it much longer, only one would 
really be needed, the other accommodated by the "topdown" parameter.

-tkc





From lie.1296 at gmail.com  Tue May 11 23:06:53 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 12 May 2010 13:06:53 +1000
Subject: Picking a license
In-Reply-To: 
References: 
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com>
	
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com>
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com>
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com>
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com>
	
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com>
	<4be95545$1@dnews.tpgi.com.au>
	
	
Message-ID: <4bea1bac$1@dnews.tpgi.com.au>

On 05/12/10 07:02, Patrick Maupin wrote:
> On May 11, 9:00 am, Paul Boddie  wrote:
>> On 11 Mai, 15:00, Lie Ryan  wrote:
>>> Come on, 99%  of the projects released under GPL did so because they
>>> don't want to learn much about the law; they just need to release it
>>> under a certain license so their users have some legal certainty.
>>
>> Yes, this is frequently the case. And the GPL does offer some
>> certainty that various permissive licences do not.
> 
> Huh? Permissive licenses offer much better certainty for someone
> attempting a creative mash-up.  Different versions of the Apache
> license don't conflict with each other.  If I use an MIT-licensed
> component, it doesn't attempt to make me offer my whole work under
> MIT.

Legal certainty as in, imagine if you released a piece of code, and use
this as the license:

"Feel free to use the code"

Then some other programmers see it, and use it in their project. The
original author then sued them because he actually intended the code to
be linked to, not copied pasted into another code base.

Then he modified the license to sound:

"Feel free to link, include, or use the code"

Then some other programmers see the code, and modified it to fit their
purpose. The original author then sued them because he only intended the
code to be "used unchanged" not "modified".


"Feel free to link, include, use, or modify the code"

Then some other programmers see the code, and used it in some commercial
project. The original author then sued them because he only intended the
code to be used in open source projects.


Lather, Rinse, Repeat and you get twenty page long license like GPL or
OWL[*]. By this time, the other programmer have learnt not to use code
with such uncertain license and the original author would either have
taken a law degree or learn to use a well-known licenses (GPL or
whatever) instead of writing his own.

The other programmer would always find a loophole in such ad-hoc
license, inadvertantly or otherwise. If  the original author used GPL
(or OWL), the other programmer knows exactly when their use case is
protected by GPL/OWL (i.e. even if the original author later found that
he disagrees with a certain clause in the license he choose, it then
becomes his fault for choosing it; the other programmer's use case is
protected by the license and thus he have the legal certainty).

[*] OWL: other well-known license

As a plus, using a well-known license means the other programmer also
don't need to hire a lawyer to determine whether he can use your code.
The other programmer sees GPL and remembers that FSF listed the license
he's using as GPL-compatible, he knows immediately he can use the code
without reading the full text of GPL. The other programmer sees some
Apache and he remembers previously he had used another Apache-licensed
code and knows immediately that he can use this other Apache project. If
everyone writes their own license, then this knowledge reuse wouldn't be
possible.

>> Well, that's always an option as well, but at the same time, there are
>> people willing to pursue licence violations, and these people have
>> done so successfully. There's no need to make an impassioned argument
>> for apathy, though. Some people do wish to dictate what others can do
>> with their work.
> 
> Oh, I get it.  You were discussing the certainty that an author can
> control what downstream users do with the software to some extent.
> Yes, I fully agree.  The GPL is for angry idealists who have an easily
> outraged sense of justice, who don't have enough real problems to work
> on.

The point is, GPL (and OWL) is for programmers who just don't care about
the legal stuffs and would want to spend more time writing code than
writing license.


From kushal.kumaran+python at gmail.com  Tue May 11 23:13:29 2010
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Wed, 12 May 2010 08:43:29 +0530
Subject: HTTP Post Request
In-Reply-To: <2b94f35e-b3a0-49db-a66a-9ee1bf104a41@h20g2000prn.googlegroups.com>
References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com>
	
	<06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com>
	
	<95e73ff4-abe5-4874-8652-647818ed224a@k29g2000yqh.googlegroups.com>
	<2b94f35e-b3a0-49db-a66a-9ee1bf104a41@h20g2000prn.googlegroups.com>
Message-ID: 

On Tue, May 11, 2010 at 3:59 PM, kaklis at gmail.com  wrote:
> On May 11, 10:56?am, "kak... at gmail.com"  wrote:
>> On May 11, 5:06?am, Kushal Kumaran 
>> wrote:
>>
>>
>>
>> > On Mon, May 10, 2010 at 8:26 PM, kak... at gmail.com  wrote:
>> > > On May 10, 10:22?am, Kushal Kumaran 
>> > > wrote:
>> > >> On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com  wrote:
>> > >> > Hi to all, i want to ask you a question, concerning the best way to do
>> > >> > the following as a POST request:
>> > >> > There is server-servlet that accepts xml commands
>> > >> > It had the following HTTP request headers:
>>
>> > >> > ? ? ? ? ? ?Host: somehost.com
>> > >> > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient
>> > >> > ? ? ? ? ? ?Content-Type: text/xml
>> > >> > ? ? ? ? ? ?Content-Length: 415
>>
>> > >> > and the following request body (reformatted here for clarity):
>>
>> > >> > ? ? ? ? ? ?
>> > >> > ? ? ? ? ? ?
>> > >> > ? ? ? ? ? ? ?search
>> > >> > ? ? ? ? ? ?
>> > >> > How can i send the above to the Listener Servlet?
>> > >> > Thanks in advance
>>
>> > >> Use the xmlrpclib module.
>>
>> > > OK, sending headers with xmlrpclib,
>> > > but how do i send the XML message?
>>
>> > Your XML message is an XML RPC message. ?You will use xmlrpclib like this:
>>
>> > server_proxy = xmlrpclib.ServerProxy(('somehost.com', 80))
>> > result = server_proxy.search()
>>
>> > The call to server_proxy.search will result in an actual XML RPC
>> > message being sent.
>>
>> > Read up on the xmlrpclib documentation here:http://docs.python.org/library/xmlrpclib.html, and the XMLRPC spec
>> > here:http://www.xmlrpc.com/spec
>>
>>
>> Ok I got it!
>> Thank you!!!
>>
>> A.K
>
> Apparently the server i'm trying to connect accepts only POST
> connections. So xmlrpclib is useless.
> I think I need the httplib library module.
>
> Any hints?
>

I don't understand.  xmlrpclib sends POST requests only.  Are you
getting an exception?  If so, please post the entire stack trace.

If you want to send the data "by hand", use the httplib module.  you
can pass your XML to the HTTPConnection.request method as the "body"
argument.

-- 
regards,
kushal


From martin at v.loewis.de  Wed May 12 00:03:55 2010
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Wed, 12 May 2010 06:03:55 +0200
Subject: Upgrade Python 2.6.4 to 2.6.5
In-Reply-To: <1273613223.8700.1374581741@webmail.messagingengine.com>
References: 
	<4BE86BC1.8040102@v.loewis.de>
	<4BE9C893.1070104@v.loewis.de>
	<1273613223.8700.1374581741@webmail.messagingengine.com>
Message-ID: <4BEA28AB.6050505@v.loewis.de>

> If we install over an existing version of Python 2.6.5, will our PTH
> files and site-packages be preserved?
> 
> Or do we need to back out our 3rd party packages, install Python 2.6.5
> and then manually restore our 3rd party packages?

An upgrade installation will only replace the Python files, and leave
all other files alone.

Regards,
Martin


From python.leojay at gmail.com  Wed May 12 00:04:41 2010
From: python.leojay at gmail.com (Leo Jay)
Date: Wed, 12 May 2010 12:04:41 +0800
Subject: Why the inconsistent of those two base64 methods?
Message-ID: 

I'd like to encode a string in base64, but I found a inconsistent of
two methods:

>>> 'aaa'.encode('base64')
'YWFh\n'
>>> import base64
>>> base64.b64encode('aaa')
'YWFh'
>>>


as you can see, the result of
'aaa'.encode('base64')
has a '\n' at the end, but the other method doesn't.

Why the inconsistent?
Thanks.

-- 
Best Regards,
Leo Jay


From dasacc22 at gmail.com  Wed May 12 00:10:46 2010
From: dasacc22 at gmail.com (dasacc22)
Date: Tue, 11 May 2010 21:10:46 -0700 (PDT)
Subject: Fastest way to calculate leading whitespace
References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com>
	
	
Message-ID: <7e14423c-95e0-4b2d-93b3-504a282e5f53@p2g2000yqh.googlegroups.com>

On May 10, 2:25?am, Stefan Behnel  wrote:
> Stefan Behnel, 10.05.2010 08:54:
>
>
>
>
>
> > dasacc22, 08.05.2010 19:19:
> >> This is a simple question. I'm looking for the fastest way to
> >> calculate the leading whitespace (as a string, ie ' ').
>
> > Here is an (untested) Cython 0.13 solution:
>
> > ? ? from cpython.unicode cimport Py_UNICODE_ISSPACE
>
> > ? ? def leading_whitespace(unicode ustring):
> > ? ? ? ? cdef Py_ssize_t i
> > ? ? ? ? cdef Py_UNICODE uchar
>
> > ? ? ? ? for i, uchar in enumerate(ustring):
> > ? ? ? ? ? ? if not Py_UNICODE_ISSPACE(uchar):
> > ? ? ? ? ? ? ? ? return ustring[:i]
> > ? ? ? ? return ustring
>
> > Cython compiles this to the obvious C code, so this should be impossible
> > to beat in plain Python code.
>
> ... and it is. For a simple string like
>
> ? ? ?u = u" ? abcdefg" + u"fsdf"*20
>
> timeit gives me this for "s=u.lstrip(); u[:-len(s)]":
>
> 1000000 loops, best of 3: 0.404 usec per loop
>
> and this for "leading_whitespace(u)":
>
> 10000000 loops, best of 3: 0.0901 usec per loop
>
> It's closer for the extreme case of an all whitespace string like " "*60,
> where I get this for the lstrip variant:
>
> 1000000 loops, best of 3: 0.277 usec per loop
>
> and this for the Cython code:
>
> 10000000 loops, best of 3: 0.177 usec per loop
>
> But I doubt that this is the main use case of the OP.
>
> Stefan

indeed, actually ive been going back and forth on the idea to use
cython for some more intensive portions. That bit of code looks really
simple so I think I'll give cython a shot. Only deal is I need to be
able to use w/e the latest cython is available via easy_install, but
this should prove an interesting experience.


From hnassrat at gmail.com  Wed May 12 00:38:47 2010
From: hnassrat at gmail.com (Hatem Nassrat)
Date: Wed, 12 May 2010 01:38:47 -0300
Subject: PEP 3119 ABC - And how I learned to love the Abstract Bomb
Message-ID: 

Today I was doing a major re-write of a library I called yajl-py that
wraps the json 'sax-like' c-parser yajl, and decided I should look
into absract base classes since I knew they had been added to py26.
Truthfully, I was surprised when I found out that the BDFL accepted
this PEP, but hey were in 2010 :p.

So I was getting around to using it when I realised that I cannot make
my class as abstract as can be. Here is my?dilemma / requirements:

1. To create a YajlContentHandler class that forces all sub-classers
to implement a certain set of methods. (Great, thats what ABC is for)

There is a certain set of mutually exclusive callbacks, i.e. if you
implement the first set you need not implement the second, and vice
versa, so my second requirement is:

2. Conditional Abstractness! if certain methods are not implemented
then be able to require some method to be implemented.

Python is more flexible than Java, so having Conditional Meta Abstract
Base Classes seems only natural :P, maybe someone should write a PEP.
This only reminds me of the following tweet:
http://twitter.com/bos31337/status/13349058839

--
Hatem Nassrat


From aahz at pythoncraft.com  Wed May 12 01:18:25 2010
From: aahz at pythoncraft.com (Aahz)
Date: 11 May 2010 22:18:25 -0700
Subject: Extract all words that begin with x
References: 
	
	<1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com>
	
Message-ID: 

In article ,
Terry Reedy   wrote:
>
>.startswith and .endswith are methods that wrap the special cases of 
>slice at an end and compare to one value. There are not necessary, and 
>save no keystrokes, but Guido obviously thought they added enough to 
>more than balance the slight expansion of the language. They were added 
>after I learned Python and I thought the tradeoff to be a toss-up, but I 
>will consider using the methods when writing didactic code meant to be 
>read by others.

They were also added after I learned Python, and I think they're great!
Using them signals that you're doing simple string checking rather than
some more arcane slicing.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From gagsl-py2 at yahoo.com.ar  Wed May 12 01:29:01 2010
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 12 May 2010 02:29:01 -0300
Subject: PEP 3119 ABC - And how I learned to love the Abstract Bomb
References: 
Message-ID: 

En Wed, 12 May 2010 01:38:47 -0300, Hatem Nassrat   
escribi?:

> 1. To create a YajlContentHandler class that forces all sub-classers
> to implement a certain set of methods. (Great, thats what ABC is for)
>
> There is a certain set of mutually exclusive callbacks, i.e. if you
> implement the first set you need not implement the second, and vice
> versa, so my second requirement is:
>
> 2. Conditional Abstractness! if certain methods are not implemented
> then be able to require some method to be implemented.

Mmm, can't you use two separate ABCs? Perhaps inheriting from a common  
base.

-- 
Gabriel Genellina



From mensanator at aol.com  Wed May 12 01:56:51 2010
From: mensanator at aol.com (Mensanator)
Date: Tue, 11 May 2010 22:56:51 -0700 (PDT)
Subject: First Timer
References: <002c01caf140$11a0eb00$34e2c100$@com>
	 
	 
	
Message-ID: 

On May 11, 9:32?pm, Terry Reedy  wrote:
> On 5/11/2010 7:03 PM, Mensanator wrote:
>
> > On May 11, 4:37 pm, Terry Reedy ?wrote:
>
> >> In the command line interpreter, you should be able to hit up
> >> arrow and have the line above copied to the current entry line for
> >> correction. In IDLE, this does not yet work,
>
> > It doesn't have to. Simply place the cursor on the line you originally
> > entered and hit.
>
> >> so copy and paste or retype.
>
> > The line will be repeated as a new line which you can edit
> > and make corrections.
>
> Thank you for the information. I obviously have never seen that written
> anywhere and never thought to try it. It will save me time.
>
> >> For anything too complicated for either of those (more than one line), I
> >> use (and reuse) a temporary edit file in an edit window. Just make sure
> >> the file is named.py rather than just. You save
> >> and run the file with F5. If there is a syntax error, IDLE will say so
> >> and reopen the cursor window with the cursor at (or after) the location
> >> of the error. Fix and hit F5 again. Very fast.
>
> > Sounds like you're making a mountain out of a molehill. You deserve
> > a medal if you've been using IDLE without knowing how to edit.
>
> Huh? I was explaining, perhaps clumbsily, how to easily edit, run,
> re-edit, and re-run multiple statements, in an editor window meant for
> that job, which cannot so easily be done in the shell, if at all.
>
> Unlike the raw interpreter window, IDLE does not allow pasting of
> multiple statements in its simulated shell (well it does, but it ignores
> any after the first).

Really? Touche, I didn't know that.

Because it would never occur to me. The only time I would need
multiple
lines is in a def situation. And placing the cursor on the def line
repeats
the ENTIRE definition, spanning as many lines as needed, all of which
can be
edited.

Sure, I'll open an edit window when things get messy or need to be
saved.
But often the IDLE prompt is all I need

> So using an editor window in that case also is
> necessary.
>
> Terry Jan Reedy



From bryanjugglercryptographer at yahoo.com  Wed May 12 02:55:39 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Tue, 11 May 2010 23:55:39 -0700 (PDT)
Subject: Extract all words that begin with x
References: 
	 
	 
	
	 
	<1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com> 
	
Message-ID: <1295fd82-39ba-4edc-ad01-ee5f9fd8dc19@a39g2000prb.googlegroups.com>

Terry Reedy wrote:
> Thank you for that timing report.

Enjoyed doing it, and more on that below.

> My main point is that there are two ways to fetch a char, the difference
> being the error return -- exception IndexError versus error value ''.
> This is an example of out-of-band versus in-band error/exception
> signaling, which programmers, especially of Python, should understand.

Sure. I think your posts and the bits of Python code they contain are
great. Slicing is amazingly useful, and it helps that slices don't
barf just because 'start' or 'stop' falls outside the index range.

My main point was to show off how Python and its standard library make
answering the which-is-faster question easy. I think that's another
thing Python programmers should understand, even though I just learned
how today.

Now back to the arguably-interesting issue of speed in the particular
problem here: 'Superpollo' had suggested another variant, which I
appended to my timeit targets, resulting in:

[s for s in strs if s.startswith('a')]  took:  5.68393977159
[s for s in strs if s[:1] == 'a']  took:  3.31676491502
[s for s in strs if s and s[0] == 'a']  took:  2.29392950076

Superpollo's condition -- s and s[0] == 'a' -- is the fastest of the
three.

What's more, in my timeit script the strings in the list are all of
length 5, so the 'and' never gets to short-circuit. If a major portion
of the strings are in fact empty superpollo's condition should do even
better. But I didn't test and time that. Yet.

-Bryan Olson


# ----- timeit code -----

from random import choice
from string import ascii_lowercase as letters
from timeit import Timer

strs = [''.join([choice(letters) for _ in range(5)])
        for _ in range(5000)]

way1 = "[s for s in strs if s.startswith('a')]"
way2 = "[s for s in strs if s[:1] == 'a']"
way3 = "[s for s in strs if s and s[0] == 'a']"

assert eval(way1) == eval(way2) == eval(way3)

for way in [way1, way2, way3]:
    t = Timer(way, 'from __main__ import strs')
    print(way, ' took: ', t.timeit(1000))


From bryanjugglercryptographer at yahoo.com  Wed May 12 02:59:29 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Tue, 11 May 2010 23:59:29 -0700 (PDT)
Subject: Iterating over dict and removing some elements
References: 
	 
	
Message-ID: 

Terry Reedy wrote:
[...]
> for k in [k for k in d if d[k] == 'two']:
> ? ? ? ? ?d.pop(k)

We have a winner.


--
--Bryan




From puntabluda at gmail.com  Wed May 12 02:59:44 2010
From: puntabluda at gmail.com (Rebelo)
Date: Wed, 12 May 2010 08:59:44 +0200
Subject: Iterating over dict and removing some elements
In-Reply-To: 
References: 
Message-ID: 

On 05/11/2010 05:08 PM, Ulrich Eckhardt wrote:
> Hi!
>
> I wrote a simple loop like this:
>
>    d = {}
>    ...
>    for k in d:
>        if some_condition(d[k]):
>            d.pop(k)
>
> If I run this, Python complains that the dictionary size changed during
> iteration. I understand that the iterator relies on the internal structure
> not changing, but how would I structure this loop otherwise?
>
> My first approach was to simply postpone removing the elements, but I was
> wondering if there was a more elegant solution.
>
> Thanks!
>
> Uli
>


i am wondering why not like this:

 >>> d = {1: 'one', 2: 'two', 3: 'three'}
 >>> for k,v in d.items():
...     if k==1:
...          del d[k]
...
 >>> d
{2: 'two', 3: 'three'}
 >>>



From mhv at dmu.dk  Wed May 12 03:08:49 2010
From: mhv at dmu.dk (Hvidberg, Martin)
Date: Wed, 12 May 2010 09:08:49 +0200
Subject: Re.: reading xml from python - Sum-up
Message-ID: 

Thanks to all - Just to give a positive feed back.
The following solution works for me:


from xml.etree.ElementTree import ElementTree

tree = ElementTree()

tree.parse('inifile.xml')

dicIni = dict((child.tag, child.text) for child in tree.getroot().getchildren())

:-) Martin



This email is made of 100% recycled bytes ...


________________________________
From: Hvidberg, Martin
Sent: Tuesday, May 11, 2010 2:54 PM
To: 'python-list at python.org'
Subject: reading xml from python

I'm looking for at way to read (and later write) small simple .xml file from Python.

e.g. I would like to read the following from a small ini.xml file into a dictionary.



 default
 False
 False
 UBMlight
 True

I would prefer a relative simple (not too much creating new classes) way to do this.

Any suggestions appreciated.

:-) Martin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From lie.1296 at gmail.com  Wed May 12 03:19:26 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 12 May 2010 17:19:26 +1000
Subject: Picking a license
In-Reply-To: 
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
Message-ID: <4bea56dd$1@dnews.tpgi.com.au>

On 05/12/10 06:50, Patrick Maupin wrote:
> On May 11, 5:34 am, Paul Boddie  wrote:
>> On 10 Mai, 20:36, Patrick Maupin  wrote:
>>>  The fact is, I know the man would force me to pay for the chocolate, so in
>>> some cases that enters into the equation and keeps me from wanting the
>>> chocolate.
>>
>> If the man said, "please take the chocolate, but I want you to share
>> it with your friends", and you refused to do so because you couldn't
>> accept that condition, would it be right to say, "that man is forcing
>> me to share chocolate with my friends"?
> 
> But the thing is, he's *not* making me share the chocolate with any of
> my friends.  He's not even making me share my special peanut butter
> and chocolate.  What he's making me do is, if I give my peanut butter
> and chocolate to one of my friends, he's making me make *that* friend
> promise to share.  I try not to impose obligations like that on my
> friends, so obviously the "nice" man with the chocolate isn't my
> friend!

The analogy breaks here; unlike chocolate, the value of software/source
code, if shared, doesn't decrease (in fact, many software increases its
value when shared liberally, e.g. p2p apps).

There might be certain cases where the software contains some trade
secret whose value decreases the more people knows about it; but sharing
does not decrease the value of the software, at least not directly, it
is the value of the secret that decreases because of the sharing.


From werner.bruhin at free.fr  Wed May 12 03:24:49 2010
From: werner.bruhin at free.fr (Werner F. Bruhin)
Date: Wed, 12 May 2010 09:24:49 +0200
Subject: Upgrade Python 2.6.4 to 2.6.5
In-Reply-To: <4BE9C893.1070104@v.loewis.de>
References: 	<4BE86BC1.8040102@v.loewis.de>
	
	<4BE9C893.1070104@v.loewis.de>
Message-ID: <4BEA57C1.7080005@free.fr>

On 11/05/2010 23:13, Martin v. Loewis wrote:
>> When will it install into system32?
>>      
> When you install "for all users".
>
>    
>>> Did the upgrade inform you that it was an upgrade, or did it warn you
>>> that you would overwrite the previous installation?
>>>
>>>        
>> It warned me that there is a previous installation.
>>      
> Hmm. You don't remember the exact message, do you?
> I guess it was a popup saying "[TARGETDIR] exists. Are you sure you want
> to overwrite existing files?", and that it was not
> a red text saying "This update will replace your existing [ProductLine]
> installation."
>
> Please confirm.
>    
Correct that was it.
> If so, you now have two Python installations in the same location; one
> for all users, and the older one just for you (or vice versa).
>    
Yes, that is what I did ages ago.
> I recommend to uninstall them both, and start over.
>    
O.K., will do that.

Thanks for your help
Werner



From bruno.42.desthuilliers at websiteburo.invalid  Wed May 12 03:25:23 2010
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Wed, 12 May 2010 09:25:23 +0200
Subject: accessing superclass methods from subclass
In-Reply-To: 
References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com>		
	
Message-ID: <4bea57d7$0$20587$426a74cc@news.free.fr>

Chris Rebert a ?crit :
(snip)
> Here is how I would rewrite your example:
> 
> class Shape(object):
>     def __init__(self, x=0, y=0):
>         self.x = x
>         self.y = y
> 
>     @property
>     def location(self):
>         return (self.x, self.y)
> 
>     @location.setter
>     def location(self, val):
>        self.x, self.y = val

Not necessary but helps documenting the expected interface:

       def draw(self):
           raise NotImplementedError("Abstract method")

> class Square(Shape):
>    def __init__(self,size):
>        super(Square, self).__init__()
>        self.size = size

Why can't I specify a Square location ??? This looks rather inconsistant 
and inconveniant to me...

     def __init__(self, x=0, y=0, size=0):
         super(Square, self).__init__(x, y)
         self.size = size
	

>    def draw(self):
>        x, y = self.location
>        # code to draw shape from location[0],location[1] at size size
>        # etc...
> 


From varahalu2400 at yahoo.co.in  Wed May 12 03:27:16 2010
From: varahalu2400 at yahoo.co.in (varahalu 2400)
Date: Wed, 12 May 2010 12:57:16 +0530 (IST)
Subject: Python-list Digest, Vol 80, Issue 108
In-Reply-To: 
References: 
Message-ID: <483577.5422.qm@web8706.mail.in.yahoo.com>

please dont send mails




________________________________
From: "python-list-request at python.org" 
To: python-list at python.org
Sent: Wed, 12 May, 2010 12:00:02 AM
Subject: Python-list Digest, Vol 80, Issue 108

Note: Forwarded message is attached.

Send Python-list mailing list submissions to
    python-list at python.org

To subscribe or unsubscribe via the World Wide Web, visit
    http://mail.python.org/mailman/listinfo/python-list
or, via email, send a message with subject or body 'help' to
    python-list-request at python.org

You can reach the person managing the list at
    python-list-owner at python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Python-list digest..."
Today's Topics:

   1. Re: HTTP Post Request (Kushal Kumaran)
   2. Re: Picking a license (Lie Ryan)
   3. Re: Upgrade Python 2.6.4 to 2.6.5 (Martin v. L?wis)
   4. Why the inconsistent of those two base64 methods? (Leo Jay)
   5. Re: Fastest way to calculate leading whitespace (dasacc22)
   6. PEP 3119 ABC - And how I learned to love the Abstract Bomb
      (Hatem Nassrat)
   7. Re: Extract all words that begin with x (Aahz)
   8. Re: PEP 3119 ABC - And how I learned to love the Abstract
      Bomb (Gabriel Genellina)
   9. Re: First Timer (Mensanator)
  10. Re: Extract all words that begin with x (Bryan)
-- 
http://mail.python.org/mailman/listinfo/python-list

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From bryanjugglercryptographer at yahoo.com  Wed May 12 03:28:43 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Wed, 12 May 2010 00:28:43 -0700 (PDT)
Subject: Iterating over dict and removing some elements
References: 
	
Message-ID: <8465ce4b-8ddb-4bfb-ba31-25ad1c0924a0@s13g2000prc.googlegroups.com>

Rebelo wrote:
> i am wondering why not like this:
>
> ?>>> d = {1: 'one', 2: 'two', 3: 'three'}
> ?>>> for k,v in d.items():
> ... ? ? if k==1:
> ... ? ? ? ? ?del d[k]
> ...
> ?>>> d
> {2: 'two', 3: 'three'}
> ?>>>

Mostly because there's no reason to get 'v' if you're not going to use
it. That may be just because you simplified the example, and if you
are working in Python 2.x and the real test for whether to delete
involves the value and not just the key, that's a reasonable solution.

On subtler issues, it constucts an unnecessarily long temporary list
in current Python 2.X, and fails in Python 3.x, as Terry Ready
explained.


--
--Bryan


From kaklis at gmail.com  Wed May 12 03:38:32 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Wed, 12 May 2010 00:38:32 -0700 (PDT)
Subject: HTTP Post Request
References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com>
	
	<06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com>
	
	<95e73ff4-abe5-4874-8652-647818ed224a@k29g2000yqh.googlegroups.com>
	<2b94f35e-b3a0-49db-a66a-9ee1bf104a41@h20g2000prn.googlegroups.com> 
	
Message-ID: <4325e3d2-d684-4c75-b02c-8b78f38da6c9@d39g2000yqa.googlegroups.com>

On May 12, 6:13?am, Kushal Kumaran 
wrote:
> On Tue, May 11, 2010 at 3:59 PM, kak... at gmail.com  wrote:
> > On May 11, 10:56?am, "kak... at gmail.com"  wrote:
> >> On May 11, 5:06?am, Kushal Kumaran 
> >> wrote:
>
> >> > On Mon, May 10, 2010 at 8:26 PM, kak... at gmail.com  wrote:
> >> > > On May 10, 10:22?am, Kushal Kumaran 
> >> > > wrote:
> >> > >> On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com  wrote:
> >> > >> > Hi to all, i want to ask you a question, concerning the best way to do
> >> > >> > the following as a POST request:
> >> > >> > There is server-servlet that accepts xml commands
> >> > >> > It had the following HTTP request headers:
>
> >> > >> > ? ? ? ? ? ?Host: somehost.com
> >> > >> > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient
> >> > >> > ? ? ? ? ? ?Content-Type: text/xml
> >> > >> > ? ? ? ? ? ?Content-Length: 415
>
> >> > >> > and the following request body (reformatted here for clarity):
>
> >> > >> > ? ? ? ? ? ?
> >> > >> > ? ? ? ? ? ?
> >> > >> > ? ? ? ? ? ? ?search
> >> > >> > ? ? ? ? ? ?
> >> > >> > How can i send the above to the Listener Servlet?
> >> > >> > Thanks in advance
>
> >> > >> Use the xmlrpclib module.
>
> >> > > OK, sending headers with xmlrpclib,
> >> > > but how do i send the XML message?
>
> >> > Your XML message is an XML RPC message. ?You will use xmlrpclib like this:
>
> >> > server_proxy = xmlrpclib.ServerProxy(('somehost.com', 80))
> >> > result = server_proxy.search()
>
> >> > The call to server_proxy.search will result in an actual XML RPC
> >> > message being sent.
>
> >> > Read up on the xmlrpclib documentation here:http://docs.python.org/library/xmlrpclib.html, and the XMLRPC spec
> >> > here:http://www.xmlrpc.com/spec
>
> >> Ok I got it!
> >> Thank you!!!
>
> >> A.K
>
> > Apparently the server i'm trying to connect accepts only POST
> > connections. So xmlrpclib is useless.
> > I think I need the httplib library module.
>
> > Any hints?
>
> I don't understand. ?xmlrpclib sends POST requests only. ?Are you
> getting an exception? ?If so, please post the entire stack trace.
>
> If you want to send the data "by hand", use the httplib module. ?you
> can pass your XML to the HTTPConnection.request method as the "body"
> argument.
>
> --
> regards,
> kushal

Ok i found it. I sent the xml by hand with httplib module.
i use the last example of http://docs.python.org/library/httplib.html
and it worked.
Thank you very much for your response.

A.K.


From alia_khouri at yahoo.com  Wed May 12 04:01:03 2010
From: alia_khouri at yahoo.com (Alia Khouri)
Date: Wed, 12 May 2010 01:01:03 -0700 (PDT)
Subject: Is Python a functional programming language?
References:  
	<06f5541f-ccbe-427a-83ad-176fcb947d29@e35g2000yqm.googlegroups.com> 
	<7xzl06ewl1.fsf@ruckus.brouhaha.com>
Message-ID: <5b00fbd7-24e0-4fbc-bdbf-4538b897680e@a34g2000yqn.googlegroups.com>

Paul Rubin:

> I like learnyouahaskell.com if you want to get some exposure to Haskell,
> probably the archetypal functional language these days. ?I've been
> fooling with it on and off for the past couple years. ?I'm still not
> convinced that it's that good a vehicle for practical general purpose
> software development, but there are some specific areas where it works
> out just beautifully. ?And in terms of the challenges it presents and
> the amount I've learned from it, it's one of the most interesting things
> I've done as a programmer in as long as I can remember. ?It really is
> mind altering.

Completely agree with you. Learnyouahaskell.com is as good as it gets
to learn haskell: haven't had so much fun learning a language since I
picked up python :-)

For similarly mind-altering pleasure, have a look at pure-lang [http://
code.google.com/p/pure-lang/] which describes itself as:

"Pure is a modern-style functional programming language based on term
rewriting. It offers equational definitions with pattern matching,
full symbolic rewriting capabilities, dynamic typing, eager and lazy
evaluation, lexical closures, built-in list and matrix support and an
easy-to-use C interface. The interpreter uses LLVM as a backend to JIT-
compile Pure programs to fast native code."

Enjoy!

AK


From johan at forberg.se  Wed May 12 04:05:33 2010
From: johan at forberg.se (Johan =?iso-8859-1?q?F=F6rberg?=)
Date: Wed, 12 May 2010 08:05:33 +0000 (UTC)
Subject: open(False) in python3
References: 
	
Message-ID: 

On Tue, 11 May 2010 19:27:37 -0300, Gabriel Genellina wrote:

> so open(False) is the same as open(0), and 0 is the file descriptor
> associated to standard input. The program isn't hung, it's just waiting
> for you to type some text

That's interesting. Are there any more numbered pseudofiles? I suppose 
its mainly an excellent way to confuse people when you open(0).read(), 
but it would be interesting to know.

Johan F?rberg


From DugmoreB at Nedbankcapital.co.za  Wed May 12 04:07:35 2010
From: DugmoreB at Nedbankcapital.co.za (Biyana, D. (Dugmore))
Date: Wed, 12 May 2010 10:07:35 +0200
Subject: python list digest
Message-ID: <7C6068ED9BBEAE4CAC7A3F4C9781AD7F043E7DC9@EXVS135RC101.africa.nedcor.net>

Hi All!

I have a huge file and I want to extract subtext starting with "{1:" and
ending with "-}" inclusive. This subtext recurs in many places in the
file and I want the resultant to be in some output file. Any suggestions
about the best way forward. 


********************
Nedbank Limited Reg No 1951/000009/06. The following link displays
the names of the Nedbank Board of Directors and Company Secretary.
[ http://www.nedbank.co.za/terms/DirectorsNedbank.htm ]
This email is confidential and is intended for the addressee only.
The following link will take you to Nedbank's legal notice.
[ http://www.nedbank.co.za/terms/EmailDisclaimer.htm ]
********************
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From guillermo.listas at googlemail.com  Wed May 12 04:15:06 2010
From: guillermo.listas at googlemail.com (Guillermo)
Date: Wed, 12 May 2010 01:15:06 -0700 (PDT)
Subject: virtualenvwrapper for Windows (Powershell)
References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com>
	
	<973ca0fa-4a2f-4e3b-91b9-e38917885c0f@d27g2000yqc.googlegroups.com>
	
Message-ID: 

On May 12, 4:31?am, Lawrence D'Oliveiro  wrote:
> In message
> <973ca0fa-4a2f-4e3b-91b9-e38917885... at d27g2000yqc.googlegroups.com>,
>
> Guillermo wrote:
> > On May 11, 7:43 am, Lawrence D'Oliveiro 
> > wrote:
>
> >> In message
> >> <22cf35af-44d1-43fe-8b90-07f2c6545... at i10g2000yqh.googlegroups.com>,
>
> >> Guillermo wrote:
>
> >>> If you've ever missed it on Windows and you can use Powershell ...
>
> >> I thought the whole point of Windows was to get away from this
> >> command-line stuff. Not such a good idea after all?
>
> > I suppose it depends.
>
> On the way it?s implemented? Microsoft seems to have botched that as well.

File a bug then. It works here. But I think you're getting a wee bit
off-topic.


From jeanmichel at sequans.com  Wed May 12 04:26:33 2010
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Wed, 12 May 2010 10:26:33 +0200
Subject: how to import a module for global use in a library package ?
In-Reply-To: 
References: <577270.86860.qm@web23105.mail.ird.yahoo.com>
	
Message-ID: <4BEA6639.1060704@sequans.com>

Terry Reedy wrote:
> On 5/11/2010 8:04 AM, Aur? Gourrier wrote:
> I might make one submodule for imports and then do 'from rootlib.util 
> import importmod as m' in the template. But I have no need now for such.
>
> Terry Jan Reedy
>
>
We did that, and we so regret it. After 5 years of intensive dev on that 
application (with more than 10 different guys committing in the repos) 
this module is now nothing but a real mess.
As soon as someone is writing twice the same import: "Oh I should put 
this module into the auto import, it will save 4 sec of my time".

This module is now an inconsistent bunch of imports and global 
assignements  :( .

JM



From stefan_ml at behnel.de  Wed May 12 04:29:23 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 12 May 2010 10:29:23 +0200
Subject: Extract all words that begin with x
In-Reply-To: <1295fd82-39ba-4edc-ad01-ee5f9fd8dc19@a39g2000prb.googlegroups.com>
References: 	
	
		
	<1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com>
	
	<1295fd82-39ba-4edc-ad01-ee5f9fd8dc19@a39g2000prb.googlegroups.com>
Message-ID: 

Bryan, 12.05.2010 08:55:
> Now back to the arguably-interesting issue of speed in the particular
> problem here: 'Superpollo' had suggested another variant, which I
> appended to my timeit targets, resulting in:
>
> [s for s in strs if s.startswith('a')]  took:  5.68393977159
> [s for s in strs if s[:1] == 'a']  took:  3.31676491502
> [s for s in strs if s and s[0] == 'a']  took:  2.29392950076
>
> Superpollo's condition -- s and s[0] == 'a' -- is the fastest of the
> three.

Just out of curiosity, I ran the same code in the latest Cython pre-0.13 
and added some optimised Cython implementations. Here's the code:

def cython_way0(l):
     return [ s for s in l if s.startswith(u'a') ]

def cython_way1(list l):
     cdef unicode s
     return [ s for s in l if s.startswith(u'a') ]

def cython_way2(list l):
     cdef unicode s
     return [ s for s in l if s[:1] == u'a' ]

def cython_way3(list l):
     cdef unicode s
     return [ s for s in l if s[0] == u'a' ]

def cython_way4(list l):
     cdef unicode s
     return [ s for s in l if s and s[0] == u'a' ]

def cython_way5(list l):
     cdef unicode s
     return [ s for s in l if (s[0]) == u'a' ]

def cython_way6(list l):
     cdef unicode s
     return [ s for s in l if s and (s[0]) == u'a' ]


And here are the numbers (plain Python 2.6.5 first):

[s for s in strs if s.startswith(u'a')] took: 1.04618620872
[s for s in strs if s[:1] == u'a'] took: 0.518909931183
[s for s in strs if s and s[0] == u'a'] took: 0.617404937744

cython_way0(strs) took: 0.769457817078
cython_way1(strs) took: 0.0861849784851
cython_way2(strs) took: 0.208586931229
cython_way3(strs) took: 0.18615603447
cython_way4(strs) took: 0.190477132797
cython_way5(strs) took: 0.0366449356079
cython_way6(strs) took: 0.0368368625641

Personally, I think the cast to Py_UNICODE in the last two implementations 
shouldn't be required, that should happen automatically, so that way3/4 
runs equally fast as way5/6. I'll add that when I get to it.

Note that unicode.startswith() is optimised in Cython, so it's a pretty 
fast option, too. Also note that the best speed-up here is only a factor of 
14, so plain Python is quite competitive, unless the list is huge and this 
is really a bottleneck in an application.

Stefan



From ldo at geek-central.gen.new_zealand  Wed May 12 04:29:50 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Wed, 12 May 2010 20:29:50 +1200
Subject: virtualenvwrapper for Windows (Powershell)
References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com>
	
	<973ca0fa-4a2f-4e3b-91b9-e38917885c0f@d27g2000yqc.googlegroups.com>
	
	
Message-ID: 

In message
, 
Guillermo wrote:

> On May 12, 4:31 am, Lawrence D'Oliveiro 
> wrote:
>
>> In message
>> <973ca0fa-4a2f-4e3b-91b9-e38917885... at d27g2000yqc.googlegroups.com>,
>>
>> Guillermo wrote:
>> > On May 11, 7:43 am, Lawrence D'Oliveiro
>> >  wrote:
>>
>> >> In message
>> >> <22cf35af-44d1-43fe-8b90-07f2c6545... at i10g2000yqh.googlegroups.com>,
>>
>> >> Guillermo wrote:
>>
>> >>> If you've ever missed it on Windows and you can use Powershell ...
>>
>> >> I thought the whole point of Windows was to get away from this
>> >> command-line stuff. Not such a good idea after all?
>>
>> > I suppose it depends.
>>
>> On the way it?s implemented? Microsoft seems to have botched that as
>> well.
> 
> But I think you're getting a wee bit off-topic.

Hey, you were the one who brought it up.


From stefan_ml at behnel.de  Wed May 12 04:36:27 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 12 May 2010 10:36:27 +0200
Subject: open(False) in python3
In-Reply-To: 
References: 	
	
Message-ID: 

Johan F?rberg, 12.05.2010 10:05:
> On Tue, 11 May 2010 19:27:37 -0300, Gabriel Genellina wrote:
>
>> so open(False) is the same as open(0), and 0 is the file descriptor
>> associated to standard input. The program isn't hung, it's just waiting
>> for you to type some text
>
> That's interesting. Are there any more numbered pseudofiles? I suppose
> its mainly an excellent way to confuse people when you open(0).read(),
> but it would be interesting to know.

Standard Unix behaviour dictates that 0 is stdin, 1 is stdout, and 2 is 
stderr. So you can only read() from 0.

Stefan



From lists at cheimes.de  Wed May 12 04:42:41 2010
From: lists at cheimes.de (Christian Heimes)
Date: Wed, 12 May 2010 10:42:41 +0200
Subject: open(False) in python3
In-Reply-To: 
References: 	
	
Message-ID: 

Johan F?rberg every:
> That's interesting. Are there any more numbered pseudofiles? I suppose
> its mainly an excellent way to confuse people when you open(0).read(),
> but it would be interesting to know.

All opened files (and on Unix even network sockets, epoll queues, 
inotify handlers etc) have a number. It's called a file descriptor. By 
default stdin, stdout and stderr have the file descriptors 0, 1 and 2. 
The concept of file descriptors is much older than Python and not Python 
specific. Even shells use the numbers, e.g. "cmd >logfile 2>&1" means 
"write stdout to logfile, redirect and combine stderr stream with stdout".



From mbnoimi at gmx.com  Wed May 12 04:43:27 2010
From: mbnoimi at gmx.com (M. Bashir Al-Noimi)
Date: Wed, 12 May 2010 10:43:27 +0200
Subject: encoding issue (cp720)
Message-ID: <4BEA6A2F.5020905@gmx.com>

Hi All,

I'm still a newbie in Python (I started learn it yesterday)  and I faced 
a huge problem cuz python always crashes because of encoding issue!

> Fatal Python error: Py_Initialize: can't initialize sys standard streams
> LookupError: unknown encoding: cp720
>    

so I filed a bug report 
 
about it but I couldn't find a solution for this problem so could you 
please help me to run python correctly?

*Note:*

    * I'm using: Windows XP SP3 32Bit, Python 3.1.2
    * I tried to copy cp720.py
      
      to Python31\Lib\encodings but it didn't fix the issue and gives me
      an error message (see attachment plz)

-- 
Best Regards
Muhammad Bashir Al-Noimi
My Blog: http://mbnoimi.net

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: error-message.txt
URL: 

From stefan_ml at behnel.de  Wed May 12 04:43:39 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 12 May 2010 10:43:39 +0200
Subject: Extract all words that begin with x
In-Reply-To: <4be971de$0$18659$4fafbaef@reader3.news.tin.it>
References: 				
	<4be971de$0$18659$4fafbaef@reader3.news.tin.it>
Message-ID: 

superpollo, 11.05.2010 17:03:
> Aahz ha scritto:
>> In article ,
>> Terry Reedy  wrote:
>>> On 5/10/2010 5:35 AM, James Mills wrote:
>>>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho wrote:
>>>>> Have I missed something, or wouldn't this work just as well:
>>>>>
>>>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>>> ['awes', 'asdgas']
>>>> I would do this for completeness (just in case):
>>>>
>>>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>>> Just guards against empty strings which may or may not be in the list.
>>> ... word[0:1] does the same thing. All Python programmers should
>>> learn to use slicing to extract a char from a string that might be
>>> empty.
>>> The method call of .startswith() will be slower, I am sure.
>>
>> And if it is slower, so what? Using startswith() makes for faster
>> reading of the code for me, and I'm sure I'm not the only one.
>
> also, what if the OP intended "words that begin with x" with x a string
> (as opposed to a single character) ?

     word[:len(x)] == x

will work in that case.

Stefan



From utente at esempio.net  Wed May 12 04:48:00 2010
From: utente at esempio.net (superpollo)
Date: Wed, 12 May 2010 10:48:00 +0200
Subject: Extract all words that begin with x
In-Reply-To: 
References: 					<4be971de$0$18659$4fafbaef@reader3.news.tin.it>
	
Message-ID: <4bea6b40$0$40293$4fafbaef@reader2.news.tin.it>

Stefan Behnel ha scritto:
> superpollo, 11.05.2010 17:03:
>> Aahz ha scritto:
>>> In article ,
>>> Terry Reedy  wrote:
>>>> On 5/10/2010 5:35 AM, James Mills wrote:
>>>>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho 
>>>>> wrote:
>>>>>> Have I missed something, or wouldn't this work just as well:
>>>>>>
>>>>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>>>> ['awes', 'asdgas']
>>>>> I would do this for completeness (just in case):
>>>>>
>>>>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>>>> Just guards against empty strings which may or may not be in the list.
>>>> ... word[0:1] does the same thing. All Python programmers should
>>>> learn to use slicing to extract a char from a string that might be
>>>> empty.
>>>> The method call of .startswith() will be slower, I am sure.
>>>
>>> And if it is slower, so what? Using startswith() makes for faster
>>> reading of the code for me, and I'm sure I'm not the only one.
>>
>> also, what if the OP intended "words that begin with x" with x a string
>> (as opposed to a single character) ?
> 
>     word[:len(x)] == x
> 
> will work in that case.

yes ... thanks.


From news1234 at free.fr  Wed May 12 04:48:16 2010
From: news1234 at free.fr (News123)
Date: Wed, 12 May 2010 10:48:16 +0200
Subject: client to upload big files via https and get progress info
Message-ID: <4bea6b50$0$8925$426a74cc@news.free.fr>

Hi,

I'd like to perform huge file uploads via https.
I'd like to make sure,
- that I can obtain upload progress info (sometimes the nw is very slow)
- that (if the file exceeds a certain size) I don't have to
  read the entire file into RAM.

I found Active states recipe 146306, which constructs the whole
multipart message first in RAM and sends it then in one chunk.


I found a server side solutions, that will write out the data file chunk
wise ( http://webpython.codepoint.net/mod_python_publisher_big_file_upload
)



If I just wanted to have progress info, then I could probably
just split line 16 of Active State's recipe ( h.send(body) )
into multiple send, right?

chunksize = 1024
for i in range(0,len(body),chunksize):
    h.send(body[i:i+chunksize])
    show_progressinfo()


But how could I create body step by step?
I wouldn't know the content-length up front?

thanks in advance



N







From maarten.sneep at knmi.nl  Wed May 12 05:20:11 2010
From: maarten.sneep at knmi.nl (Maarten)
Date: Wed, 12 May 2010 02:20:11 -0700 (PDT)
Subject: Why the inconsistent of those two base64 methods?
References: 
Message-ID: 

On May 12, 6:04 am, Leo Jay  wrote:
> I'd like to encode a string in base64, but I found a inconsistent of
> two methods:
>
> >>> 'aaa'.encode('base64')
> 'YWFh\n'
> >>> import base64
> >>> base64.b64encode('aaa')
> 'YWFh'
>
> as you can see, the result of
> 'aaa'.encode('base64')
> has a '\n' at the end, but the other method doesn't.
>
> Why the inconsistent?

Don't know. Does it matter?

>>> import base64
>>> base64.decodestring(base64.b64encode('aaa'))
'aaa'

>>> 'aaa'.encode('base64').decode('base64')
'aaa'

(so far so good, and as expected)

>>> base64.decodestring('aaa'.encode('base64'))
'aaa'

>>> base64.b64encode('aaa').decode('base64')
'aaa'

(As far as I can see, both methods are completely consistent)

Maarten


From lie.1296 at gmail.com  Wed May 12 06:14:53 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 12 May 2010 20:14:53 +1000
Subject: encoding issue (cp720)
In-Reply-To: 
References: 
Message-ID: <4bea7ffc$1@dnews.tpgi.com.au>

On 05/12/10 18:43, M. Bashir Al-Noimi wrote:
> Hi All,
> 
> I'm still a newbie in Python (I started learn it yesterday)  and I faced
> a huge problem cuz python always crashes because of encoding issue!
> 
>> Fatal Python error: Py_Initialize: can't initialize sys standard streams
>> LookupError: unknown encoding: cp720
> 
> so I filed a bug report
> 
> about it but I couldn't find a solution for this problem so could you
> please help me to run python correctly?

This is partly a locale issue; your terminal (command prompt) is using a
locale yet unsupported by python. You can use 'chcp' to switch to
different terminal code page (e.g. use chcp 1250). You won't be able to
'print' arabic characters, but at least python should run.

> *Note:*
> 
>    * I'm using: Windows XP SP3 32Bit, Python 3.1.2
>    * I tried to copy cp720.py
>      
>      to Python31\Lib\encodings but it didn't fix the issue and gives me
>      an error message (see attachment plz)

You're using Python 3.1, the cp720.py file you copied is for Python 2.7
(trunk); there are some backward incompatible between python 2 and
python 3 (specifically in your case, unicode string is now default in
python 3, so unicode literal is no longer supported). Try using the
cp720.py from py3k branch:
http://svn.python.org/view/python/branches/py3k/Lib/encodings/cp720.py?view=markup


From albert at spenarnc.xs4all.nl  Wed May 12 07:25:28 2010
From: albert at spenarnc.xs4all.nl (Albert van der Horst)
Date: 12 May 2010 11:25:28 GMT
Subject: strange interaction between open and cwd
References: <4BDEDC73.1020301@ftml.net>
	
	
Message-ID: 

In article ,
Grant Edwards   wrote:

>
>Still, at the time, it _seemed_ like a good way to share a directory
>of source code amongst multiple projects.  I don't remember why
>symlinks wouldn't accomplish the task -- something to do with RCS...

Must be deep. I use RCS in combination with symlinks all the time.
Like symlinks to a directory tree on a mounted volume, where
one is not supposed to check out.
Or symlinking  happyd.sco,v to HAPPYD.SCO,v effectively making
file names case-insensitive.

>
>--
>Grant
>

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst



From paul at boddie.org.uk  Wed May 12 08:10:27 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 05:10:27 -0700 (PDT)
Subject: Picking a license
References: 
	<4be5bdcb$0$27798$c3e8da3@news.astraweb.com> 
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> 
	 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com>
Message-ID: 

On 11 Mai, 22:39, Patrick Maupin  wrote:
>
> OK. ?Now I'm REALLY confused. ?I said "Certainly RMS
> carefully lays out that the LGPL should be used sparingly in his "Why
> you shouldn't use the Lesser GPL for your next library" post. ?(Hint:
> he's not suggesting a permissive license instead.)"
>
> to which you replied:
>
> "Sure, but all he's asking you to do is to make the software available
> under a GPL-compatible licence."

Alright, then, all he's asking you to do is to make *your* software
available under a GPL-compatible licence. That's what I meant in the
context of the discussion. Usually, people complain about how the GPL
dictates a single licence, forbidding all others, that is then
inseparable from their work ("It's my work but they make me GPL it! I
can't even control my own work any more! The FSF owns it!" and such
nonsense), but I've already given examples of this not being the case
at all.

> and then I tried to politely show that you were wrong about RMS's
> intentions, but now, but you're saying "oh, of course, he'd say that
> -- he wrote the license" ?which is basically what I've been saying all
> along. ?But if you have read it like you say, then it appears you were
> being very disingenuous in your original reply!

What the licence asks you to do and what the author of the licence
wants you to do are two separate things.

[...]

> NO. ?If you are building an application, and distributing GPLed stuff
> as part of it, the FSF still maintains that the license is such that
> the entire application must be GPLed. ?You keep acting like this isn't
> true, but it absolutely is if you're distributing the entire
> application.

I wrote "the software" above when I meant "your software", but I have
not pretended that the whole system need not be available under the
GPL. Otherwise the following text would be logically inconsistent with
such claims:

[...]

> On May 11, 5:24 am, Paul Boddie  wrote:
> > Again, you have to consider the intent of the licensing: that some
> > software which links to readline results in a software system that
> > should offer the "four freedoms", because that's the price of linking
> > to readline whose licence has promised that any system which builds
> > upon it shall offer those privileges.
>
> But I did consider the intent, and as I have made clear, I think
> that's a bullying tactic that fragments the software world
> unnecessarily. ?Obviously YMMV.

More loaded terms to replace the last set, I see.

> > > > As for rst2pdf, what your modifications would mean is that the
> > > > software would need to be redistributed under a GPL-compatible
> > > > licence.
>
> NO. ?You're still not paying attention. ?The FSF's clear position is
> that if you actually *redistribute* software under the GPL as *part of
> a system* then the full package must be licensed *under the GPL*.

Again, what I meant was "your software", not the whole software
system. As I more or less state below...

> > Once again, I refer you to the intent of the licensing: if someone has
> > the software in front of them which uses svglib, then they need to
> > have the privileges granted to them by the GPL. Yes, if the software
> > also uses some component with a GPL-incompatible licence, then this
> > causes a problem.
>
> It appears that the FSF's position is the ability to link to svglib
> would require software to be licensed under the GPL.

It would require the resulting system to be licensed under the GPL. As
it stands by itself, rst2pdf would need to be licensed compatibly with
the GPL.

> I don't believe
> that, but I do believe that if rst2pdf distributed svglib (or even
> patches to svglib which were clearly derivative works) then yes,
> rst2pdf would have to be distributed under the GPL. ?This kind of
> bullshit is only acceptable to people who only think a single license
> is acceptable.

Take it or leave it, then.

[...]

> > Well, I have referred several times to WebKit without you taking the
> > hint,
>
> OK, I don't work with webkit. ?I knew you were hinting at something,
> but why the games, I don't know. ?I guess it's all about mystique and
> games.

You mentioned WebKit as a non-GPL-licensed project which attracted
contributions from hard-nosed business. WebKit started life as KHTML
and was (and still is) LGPL-licensed, but for all practical purposes,
KHTML was only ever experienced by KDE users whilst linked to the Qt
framework, then available under the GPL. Now, given that WebKit now
works with other GUI frameworks, yet is still LGPL-licensed (and this
has nothing to do with recent Qt licensing developments, since this
applies to the period before those changes), it is clear that any
assertion that WebKit "was made GPL-only", which is what a lot of
people claim, is incorrect.

> > but that provides a specific case of a project which is LGPL-
> > licensed despite being based on (in GPLv3 terminology) libraries which
> > were distributed under the GPL and combined with that software.
>
> What other libraries? ?I don't know it's history. ?I give you specific
> examples at problems; you hint around at things you claim are not
> problems and then still don't give specifics.

I've now given you the specifics.

> > Similarly, the effort to ensure that CPython's licence was GPL-
> > compatible had a lot to do with the right to redistribute with GPL-
> > licensed code (actually readline, if I remember correctly).
>
> Yes, but the Python project doesn't actually distribute readline, and
> (as I mentioned) people are more informed now, and it would be
> difficult for RMS to bully Python into relicensing.

All RMS and the FSF's lawyers wanted was that the CNRI licences be GPL-
compatible. There are actually various aspects of GPL-compatibility
that are beneficial, even if you don't like the copyleft-style
clauses, so I don't think it was to the detriment of the Python
project.

> But if the Python
> distribution *included* GNU Readline, then RMS would be on firmer
> ground, and the license would probably have to be changed. ?This is
> *exactly* the situation I was describing with svglib -- can you still
> not see that it is a problem to just toss unsupported free software
> out there with a GPL license? ?Unsupported Apache or MIT is fine --
> fix it or ignore. ?Unsupported GPL is an attractive nuisance.

Well, if you're planning to release code and just walk away from it,
then choosing a permissive licence might be acceptable, but not all
code "found" by people on the Internet is abandoned, even if it is
apparently mere fodder for their super-important project.

> > Is readline trivial? Was readline trivial in 1992?
>
> Again, you could have neural net prediction and other fancy
> technologies, but in general, yes, the concept is pretty trivial and
> there were many systems that already had such things back then.

Well, that may not be a judgement shared by the authors. There are
numerous tools and components which do dull jobs and whose maintenance
is tedious and generally unrewarding, but that doesn't mean that such
investment is worth nothing in the face of someone else's so-very-
topical high-profile project.

> > Does it even
> > matter, because the author is more or less saying that they don't want
> > their code incorporated in a proprietary system?
>
> Yes it matters because as others have pointed out, sometimes people
> use stuff which is purported to be "free" without a full understanding
> of all the implications. ?But this gets back to my general complaint
> about co-opting the word "free" which you don't think is a problem
> because you have chosen to use other words.

Well, if people are making use of "some good code found for free on
the Internet", particularly if they are corporations like Cisco, and
they choose not to understand things like copyright and licensing, or
they think "all rights reserved" is just a catchy slogan, then they
probably shouldn't be building larger works and redistributing them.
This may seem unfair to you, but there are plenty of other
organisations who are much less charitable about copyright
infringement than the FSF or the average Free Software developer.

But if you're more or less saying that the intentions of an author can
(or should) be disregarded if the desire to use that author's work is
great enough, well, that's certainly interesting to learn.

Paul


From adi at digitaltrowel.com  Wed May 12 08:13:05 2010
From: adi at digitaltrowel.com (Adi Eyal)
Date: Wed, 12 May 2010 14:13:05 +0200
Subject: Iterating over dict and removing some elements
Message-ID: 

> ---------- Forwarded message ----------
> From:?Bryan 
> To:?python-list at python.org
> Date:?Tue, 11 May 2010 23:59:29 -0700 (PDT)
> Subject:?Re: Iterating over dict and removing some elements
> Terry Reedy wrote:
> [...]
>> for k in [k for k in d if d[k] == 'two']:
>> ? ? ? ? ?d.pop(k)
>
> We have a winner.
>

also

foo = lambda k, d : d[k] == "two"
d = dict([(k, d[k]) for k in d.keys() if not foo(k, d)])

incidentally, this is marginally slower than pops and dels but has the
benefit of not modifying the original dict if that's what you need.

Adi


From paul at boddie.org.uk  Wed May 12 08:26:22 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 05:26:22 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<4be95545$1@dnews.tpgi.com.au>
	
	
Message-ID: <1d32b5bf-3445-454e-bbb5-172435741fa1@q30g2000yqd.googlegroups.com>

On 11 Mai, 23:02, Patrick Maupin  wrote:
>
> Huh? Permissive licenses offer much better certainty for someone
> attempting a creative mash-up. ?Different versions of the Apache
> license don't conflict with each other. ?If I use an MIT-licensed
> component, it doesn't attempt to make me offer my whole work under
> MIT.

What certainty does the MIT licence give contributors to a project
against patent infringement claims initiated by another contributor?

[...]

> Oh, I get it. ?You were discussing the certainty that an author can
> control what downstream users do with the software to some extent.
> Yes, I fully agree. ?The GPL is for angry idealists who have an easily
> outraged sense of justice, who don't have enough real problems to work
> on.

Again, the author does not exercise control when people must
voluntarily choose to use that author's work and thereby agree to
adhere to that author's set of terms.

Paul


From mbnoimi at gmx.com  Wed May 12 08:33:09 2010
From: mbnoimi at gmx.com (M. Bashir Al-Noimi)
Date: Wed, 12 May 2010 14:33:09 +0200
Subject: [SOLVED] encoding issue (cp720)
In-Reply-To: <4bea7ffc$1@dnews.tpgi.com.au>
References: 
	<4bea7ffc$1@dnews.tpgi.com.au>
Message-ID: <4BEAA005.8050601@gmx.com>

Hi Lie,

On 12/05/2010 12:14 ?, Lie Ryan wrote:
> On 05/12/10 18:43, M. Bashir Al-Noimi wrote:
>    
>> Hi All,
>>
>> I'm still a newbie in Python (I started learn it yesterday)  and I faced
>> a huge problem cuz python always crashes because of encoding issue!
>>
>>      
>>> Fatal Python error: Py_Initialize: can't initialize sys standard streams
>>> LookupError: unknown encoding: cp720
>>>        
>> so I filed a bug report
>> 
>> about it but I couldn't find a solution for this problem so could you
>> please help me to run python correctly?
>>      
> This is partly a locale issue; your terminal (command prompt) is using a
> locale yet unsupported by python. You can use 'chcp' to switch to
> different terminal code page (e.g. use chcp 1250). You won't be able to
> 'print' arabic characters, but at least python should run.
>    
Actually I tried to run chcp (some one mentioned it in bug report) but 
it didn't fix the issue.

>> *Note:*
>>
>>     * I'm using: Windows XP SP3 32Bit, Python 3.1.2
>>     * I tried to copy cp720.py
>>       
>>       to Python31\Lib\encodings but it didn't fix the issue and gives me
>>       an error message (see attachment plz)
>>      
> You're using Python 3.1, the cp720.py file you copied is for Python 2.7
> (trunk); there are some backward incompatible between python 2 and
> python 3 (specifically in your case, unicode string is now default in
> python 3, so unicode literal is no longer supported). Try using the
> cp720.py from py3k branch:
> http://svn.python.org/view/python/branches/py3k/Lib/encodings/cp720.py?view=markup
>    
Thanks a lot python currently works this is the right file.

-- 
Best Regards
Muhammad Bashir Al-Noimi
My Blog: http://mbnoimi.net



From paul at boddie.org.uk  Wed May 12 08:43:19 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 05:43:19 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	
Message-ID: <1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>

On 11 Mai, 22:50, Patrick Maupin  wrote:
> On May 11, 5:34?am, Paul Boddie  wrote:
>
> > Yes, *if* you took it. He isn't forcing you to take it, though, is he?
>
> No, ?but he said a lot of words that I didn't immediately understand
> about what it meant to be free and that it was free, and then after I
> bit into it he told me he owned my soul now.

Thus, "owned my soul" joins "holy war" and "Bin Laden" on the list.
That rhetorical toolbox is looking pretty empty at this point.

[...]

> > It is whining if someone says, "I really want that chocolate, but that
> > nasty man is going to make me pay for it!"
>
> But that's not what happened. ?I mean, he just told me that I might
> have to give some of it to others later. ?He didn't mention that if I
> spread peanut butter on mine before I ate it that I'd have to give
> people Reese's Peanut Butter cups.

He isn't, though. He's telling you that you can't force other people
to lick the chocolate off whatever "Reese's Peanut Butter cups" are,
rather than actually eating the combination of the two, when you offer
such a combination to someone else. Is the Creative Commons share-
alike clause just as objectionable to you, because it's that principle
we're talking about here?

[...]

> > If the man said, "please take the chocolate, but I want you to share
> > it with your friends", and you refused to do so because you couldn't
> > accept that condition, would it be right to say, "that man is forcing
> > me to share chocolate with my friends"?
>
> But the thing is, he's *not* making me share the chocolate with any of
> my friends. ?He's not even making me share my special peanut butter
> and chocolate. ?What he's making me do is, if I give my peanut butter
> and chocolate to one of my friends, he's making me make *that* friend
> promise to share. ?I try not to impose obligations like that on my
> friends, so obviously the "nice" man with the chocolate isn't my
> friend!

Yes, he's making everyone commit to sharing, and yes, it's like a
snowball effect once people agree to join in. But unless you hide that
commitment, no-one imposes anything on anyone. They can get their
chocolate elsewhere. They join in; they are not conscripted.

[...]

> I explained this very carefully before multiple times. ?Let me give
> concrete examples -- (1) I have told my children before "if we take
> that candy, then they will make us pay for it" and (2) if we included
> (GPLed software) in this (MIT-licensed software) then we will have to
> change the license. ?In both these cases, once the decision has been
> made, then yes, force enters into it. ?And no, I don't think the
> average shop keeper is nearly as evil as Darth, or even RMS.

Entering an agreement voluntarily does not mean that you are forced to
enter that agreement, even if the agreement then involves obligations
(as agreements inevitably do).

Paul


From czg0002 at gmail.com  Wed May 12 09:40:34 2010
From: czg0002 at gmail.com (chen zeguang)
Date: Wed, 12 May 2010 21:40:34 +0800
Subject: How to add callbacks that is the same function with different 
	argument in Tkinter python26?
Message-ID: 

code is in the end.
I want to print different number when pressing different button.
Yet the program outputs 8 no matter which button is pressed.
I guess it's because the callback function is not established untill the
button is pressed, and i has already reached to 8.

then How to add callbacks that is the same function with different argument?

CODE:
from Tkinter import *
root = Tk()
def func(x):
    print x
    return

func_en=[]
for i in range(9):
    func_en.append(lambda:func(i))
for i in range(9):
    func_en[i]()
for i in range(9):
    Button(root, text='%d'%i, command=func_en[i]).pack()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From jeanmichel at sequans.com  Wed May 12 10:09:05 2010
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Wed, 12 May 2010 16:09:05 +0200
Subject: How to add callbacks that is the same function with different
	argument in Tkinter python26?
In-Reply-To: 
References: 
Message-ID: <4BEAB681.9060108@sequans.com>

chen zeguang wrote:
> code is in the end.
> I want to print different number when pressing different button.
> Yet the program outputs 8 no matter which button is pressed.
> I guess it's because the callback function is not established untill 
> the button is pressed, and i has already reached to 8.
>
> then How to add callbacks that is the same function with different 
> argument?
>
> CODE:
> from Tkinter import *
> root = Tk()
> def func(x):
>     print x
>     return
>
> func_en=[]
> for i in range(9):
>     func_en.append(lambda:func(i))
> for i in range(9):
>     func_en[i]()
> for i in range(9):
>     Button(root, text='%d'%i, command=func_en[i]).pack()
from Tkinter import *
root = Tk()

def func(x):
    def _printme():
        print x
    return _printme

for i in range(9):
    Button(root, text='%d'%i, command=func(i)).pack()

Surely someone will explain why your code was not working, I can't 
'cause I don't use lambda, it brings more problems than it solves (maybe 
I'm not talented enough).
Above is how I would have written the code, I tested it, looks like it's 
working.

JM


From pmaupin at gmail.com  Wed May 12 10:10:52 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 07:10:52 -0700 (PDT)
Subject: Picking a license
References: 
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com>
	 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	
Message-ID: <3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com>

On May 12, 7:10?am, Paul Boddie  wrote:
> On 11 Mai, 22:39, Patrick Maupin  wrote:
>
>
>
> > OK. ?Now I'm REALLY confused. ?I said "Certainly RMS
> > carefully lays out that the LGPL should be used sparingly in his "Why
> > you shouldn't use the Lesser GPL for your next library" post. ?(Hint:
> > he's not suggesting a permissive license instead.)"
>
> > to which you replied:
>
> > "Sure, but all he's asking you to do is to make the software available
> > under a GPL-compatible licence."
>
> Alright, then, all he's asking you to do is to make *your* software
> available under a GPL-compatible licence. That's what I meant in the
> context of the discussion. Usually, people complain about how the GPL
> dictates a single licence, forbidding all others, that is then
> inseparable from their work ("It's my work but they make me GPL it! I
> can't even control my own work any more! The FSF owns it!" and such
> nonsense), but I've already given examples of this not being the case
> at all.

In that post, specifically, RMS says to use the GPL in some cases,
rather than the LGPL, for libraries.  Any other interpretation of
*that post* is disingenuous.

> > and then I tried to politely show that you were wrong about RMS's
> > intentions, but now, but you're saying "oh, of course, he'd say that
> > -- he wrote the license" ?which is basically what I've been saying all
> > along. ?But if you have read it like you say, then it appears you were
> > being very disingenuous in your original reply!
>
> What the licence asks you to do and what the author of the licence
> wants you to do are two separate things.

But the whole context was about what RMS wanted me to do and you
disagreed!

>
> > NO. ?If you are building an application, and distributing GPLed stuff
> > as part of it, the FSF still maintains that the license is such that
> > the entire application must be GPLed. ?You keep acting like this isn't
> > true, but it absolutely is if you're distributing the entire
> > application.
>
> I wrote "the software" above when I meant "your software", but I have
> not pretended that the whole system need not be available under the
> GPL.

You say you "have not pretended" but you've never mentioned that it
would or even acknowledged the correctness of my assertions about this
until now, just claiming that what I said was false.

> > On May 11, 5:24 am, Paul Boddie  wrote:
> > > Again, you have to consider the intent of the licensing: that some
> > > software which links to readline results in a software system that
> > > should offer the "four freedoms", because that's the price of linking
> > > to readline whose licence has promised that any system which builds
> > > upon it shall offer those privileges.
>
> > But I did consider the intent, and as I have made clear, I think
> > that's a bullying tactic that fragments the software world
> > unnecessarily. ?Obviously YMMV.
>
> More loaded terms to replace the last set, I see.

IMO "Bullying" is the correct term for some of Stallman's actions,
including in the clisp debacle.  I knew you wouldn't agree -- that's
why YMMV.  And I'm not "replacing" any set of terms -- part of the
"bullying" is the "forcing."

> > > > > As for rst2pdf, what your modifications would mean is that the
> > > > > software would need to be redistributed under a GPL-compatible
> > > > > licence.
>
> > NO. ?You're still not paying attention. ?The FSF's clear position is
> > that if you actually *redistribute* software under the GPL as *part of
> > a system* then the full package must be licensed *under the GPL*.
>
> Again, what I meant was "your software", not the whole software
> system. As I more or less state below...

BUT THAT DOESN'T MATTER.  Once the whole package is licensed under the
GPL, for someone downstream to try to scrape the GPL off and get to
just the underlying non-GPL parts is harder than scraping bubblegum
off your shoe on a hot Texas day.

> > > Once again, I refer you to the intent of the licensing: if someone has
> > > the software in front of them which uses svglib, then they need to
> > > have the privileges granted to them by the GPL. Yes, if the software
> > > also uses some component with a GPL-incompatible licence, then this
> > > causes a problem.
>
> > It appears that the FSF's position is the ability to link to svglib
> > would require software to be licensed under the GPL.
>
> It would require the resulting system to be licensed under the GPL. As
> it stands by itself, rst2pdf would need to be licensed compatibly with
> the GPL.

They've softened their stance considerably over the last few years,
and don't overreach nearly as much as they used to, I agree.

[...]

> You mentioned WebKit as a non-GPL-licensed project which attracted
> contributions from hard-nosed business. WebKit started life as KHTML
> and was (and still is) LGPL-licensed, but for all practical purposes,
> KHTML was only ever experienced by KDE users whilst linked to the Qt
> framework, then available under the GPL. Now, given that WebKit now
> works with other GUI frameworks, yet is still LGPL-licensed (and this
> has nothing to do with recent Qt licensing developments, since this
> applies to the period before those changes), it is clear that any
> assertion that WebKit "was made GPL-only", which is what a lot of
> people claim, is incorrect.

I didn't make that claim and have never heard of that claim, and I'm
not at all sure of the relevance of whatever you're trying to explain
to the licensing of an overall program, rather than a library.

> > > but that provides a specific case of a project which is LGPL-
> > > licensed despite being based on (in GPLv3 terminology) libraries which
> > > were distributed under the GPL and combined with that software.
>
> > What other libraries? ?I don't know it's history. ?I give you specific
> > examples at problems; you hint around at things you claim are not
> > problems and then still don't give specifics.
>
> I've now given you the specifics.

And now that I know the specifics, I think they are completely
irrelevant to any points I was trying to make in this discussion.

> > > Similarly, the effort to ensure that CPython's licence was GPL-
> > > compatible had a lot to do with the right to redistribute with GPL-
> > > licensed code (actually readline, if I remember correctly).
>
> > Yes, but the Python project doesn't actually distribute readline, and
> > (as I mentioned) people are more informed now, and it would be
> > difficult for RMS to bully Python into relicensing.
>
> All RMS and the FSF's lawyers wanted was that the CNRI licences be GPL-
> compatible. There are actually various aspects of GPL-compatibility
> that are beneficial, even if you don't like the copyleft-style
> clauses, so I don't think it was to the detriment of the Python
> project.

And I don't have a problem with that.  Honestly I don't.  But as far
as I'm concerned, although you finally admitted it, a lot of the
dancing around appeared to be an attempt to disprove my valid
assertion that a combined work would have to be distributed under the
GPL, and that no other free software license claims sovereignty over
the entire work.

> > But if the Python
> > distribution *included* GNU Readline, then RMS would be on firmer
> > ground, and the license would probably have to be changed. ?This is
> > *exactly* the situation I was describing with svglib -- can you still
> > not see that it is a problem to just toss unsupported free software
> > out there with a GPL license? ?Unsupported Apache or MIT is fine --
> > fix it or ignore. ?Unsupported GPL is an attractive nuisance.
>
> Well, if you're planning to release code and just walk away from it,
> then choosing a permissive licence might be acceptable, but not all
> code "found" by people on the Internet is abandoned, even if it is
> apparently mere fodder for their super-important project.

Code doesn't have to be abandoned to be an attractive nuisance.

> > > Is readline trivial? Was readline trivial in 1992?
>
> > Again, you could have neural net prediction and other fancy
> > technologies, but in general, yes, the concept is pretty trivial and
> > there were many systems that already had such things back then.
>
> Well, that may not be a judgement shared by the authors. There are
> numerous tools and components which do dull jobs and whose maintenance
> is tedious and generally unrewarding, but that doesn't mean that such
> investment is worth nothing in the face of someone else's so-very-
> topical high-profile project.

OK, so what you're saying is that readline is so dull and unrewarding
that the only reason to bother writing it is to reel people in to the
GPL?

> > > Does it even
> > > matter, because the author is more or less saying that they don't want
> > > their code incorporated in a proprietary system?
>
> > Yes it matters because as others have pointed out, sometimes people
> > use stuff which is purported to be "free" without a full understanding
> > of all the implications. ?But this gets back to my general complaint
> > about co-opting the word "free" which you don't think is a problem
> > because you have chosen to use other words.
>
> Well, if people are making use of "some good code found for free on
> the Internet", particularly if they are corporations like Cisco, and

I'm not talking about Cisco.  I'm talking about people like the author
of clisp, and you well know it.

> they choose not to understand things like copyright and licensing, or
> they think "all rights reserved" is just a catchy slogan, then they
> probably shouldn't be building larger works and redistributing them.

Well, the FSF seems to have softened its stance, but at the time,
clisp wasn't even distributing readline.  That's why I use terms like
"bullying".  The bully now knows it's harder to get away with that
particular lie, but he's still scheming about how to reel more people
in.

> This may seem unfair to you, but there are plenty of other
> organisations who are much less charitable about copyright
> infringement than the FSF or the average Free Software developer.

None of those claim that their software is "Free Software" (all
caps).  You apparently think it's fine that that's just a catchy
slogan.

> But if you're more or less saying that the intentions of an author can
> (or should) be disregarded if the desire to use that author's work is
> great enough, well, that's certainly interesting to learn.

I never said that and you know it.  I have explicitly gone out of my
way to indicate that I won't use GPLed software in cases where my
doing so might violate the author's wishes, even if it would be legal
to do so, and I have always said people should be able to use whatever
license they want.  But the intentions of an author, as viewed
through, e.g., the MIT license, are much easier to discern and much
more liberal for downstream users than the GPL, which is exceedingly
long and requires a huge FAQ to even begin to fathom.

Regards,
Pat


From pmaupin at gmail.com  Wed May 12 10:12:36 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 07:12:36 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<4be95545$1@dnews.tpgi.com.au>
	
	 
	<4bea1bac$1@dnews.tpgi.com.au>
Message-ID: <2f547c51-3779-4141-9f6a-d3ca938d7fbb@a21g2000yqn.googlegroups.com>

On May 11, 10:06?pm, Lie Ryan  wrote:

> The point is, GPL (and OWL) is for programmers who just don't care about
> the legal stuffs and would want to spend more time writing code than
> writing license.

Absolutely.  When I wrote "permissive license" I was not trying to
imply that everybody should roll their own.

Regards,
Pat


From pmaupin at gmail.com  Wed May 12 10:20:25 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 07:20:25 -0700 (PDT)
Subject: Picking a license
References: 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com>
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<4be95545$1@dnews.tpgi.com.au>
	
	 
	<1d32b5bf-3445-454e-bbb5-172435741fa1@q30g2000yqd.googlegroups.com>
Message-ID: <6c5ed669-96bb-4e4c-a203-03c478165dbe@24g2000yqy.googlegroups.com>

On May 12, 7:26?am, Paul Boddie  wrote:
> On 11 Mai, 23:02, Patrick Maupin  wrote:
> > Huh? Permissive licenses offer much better certainty for someone
> > attempting a creative mash-up. ?Different versions of the Apache
> > license don't conflict with each other. ?If I use an MIT-licensed
> > component, it doesn't attempt to make me offer my whole work under
> > MIT.
>
> What certainty does the MIT licence give contributors to a project
> against patent infringement claims initiated by another contributor?

None.  If I was worried about that, I'd probably use the Apache
license instead.

> > Oh, I get it. ?You were discussing the certainty that an author can
> > control what downstream users do with the software to some extent.
> > Yes, I fully agree. ?The GPL is for angry idealists who have an easily
> > outraged sense of justice, who don't have enough real problems to work
> > on.
>
> Again, the author does not exercise control when people must
> voluntarily choose to use that author's work and thereby agree to
> adhere to that author's set of terms.

So you're saying that Microsoft doesn't exercise control about keeping
me from using a copy of Windows on more than one machine -- it's not
"control" because I agreed to it up front.   Sorry, my mileage
varies.  In fact, I would (and do) say that Microsoft forces me to buy
one copy of Windows for every machine I want to run it on.

Regards,
Pat


From matt at tplus1.com  Wed May 12 10:23:29 2010
From: matt at tplus1.com (Matthew Wilson)
Date: Wed, 12 May 2010 14:23:29 +0000 (UTC)
Subject: Need help using callables and setup in timeit.Timer
Message-ID: 

I want to time some code that depends on some setup.  The setup code
looks a little like this:

    >>> b = range(1, 1001)

And the code I want to time looks vaguely like this:

    >>> sorted(b)

Except my code uses a different function than sorted.  But that ain't
important right now.

Anyhow, I know how to time this code as long as I pass in strings to timeit:

    >>> import timeit
    >>> t = timeit.Timer("sorted(b)", "b = range(1, 1001)")
    >>> min(t.repeat(3, 100))

How do I use a setup callable and have it put stuff into the namespace
that the stmt callable can access?

In other words, I want to do the same thing as above, but using
callables as the parameters to timeit.Timer, not strings of python code.

Here's my long-run goal.  I want to reuse code from my unit tests to
test performance:

    import unittest
    class TestSorting(unittest.TestCase):

        def setUp(self):
            self.b = range(1, 1001)

        def test_sorted(self):
            sorted(self.b)

I expect to have to do a little work.  The timeit setup will need to
make an instance of TestSorting and somehow the stmt code will have to
use that particular instance.

Once I understand how to have the timeit setup put stuff into the same
namespace as the timeit stmt, I'll attack how to translate
unittest.TestCase instances into something that can feed right into
timeit.Timer.

Matt





From pmaupin at gmail.com  Wed May 12 10:45:04 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 07:45:04 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
Message-ID: <5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>

On May 12, 7:43?am, Paul Boddie  wrote:
> On 11 Mai, 22:50, Patrick Maupin  wrote:
>
> > On May 11, 5:34?am, Paul Boddie  wrote:
>
> > > Yes, *if* you took it. He isn't forcing you to take it, though, is he?
>
> > No, ?but he said a lot of words that I didn't immediately understand
> > about what it meant to be free and that it was free, and then after I
> > bit into it he told me he owned my soul now.
>
> Thus, "owned my soul" joins "holy war" and "Bin Laden" on the list.
> That rhetorical toolbox is looking pretty empty at this point.

Not emptier than you analogy toolbox.  This is really a pretty stupid
analogy, but I guess my lame attempts at showing that are wasted.

> > > It is whining if someone says, "I really want that chocolate, but that
> > > nasty man is going to make me pay for it!"
>
> > But that's not what happened. ?I mean, he just told me that I might
> > have to give some of it to others later. ?He didn't mention that if I
> > spread peanut butter on mine before I ate it that I'd have to give
> > people Reese's Peanut Butter cups.
>
> He isn't, though. He's telling you that you can't force other people
> to lick the chocolate off whatever "Reese's Peanut Butter cups" are,
> rather than actually eating the combination of the two, when you offer
> such a combination to someone else.

No.  That's not what is happening, and you've now officially stretched
the analogy way past the breaking point.  In any case, he's telling me
I have to give the recipe for my homemade peanut butter.

> Is the Creative Commons share-
> alike clause just as objectionable to you, because it's that principle
> we're talking about here?

I have explained that, in some cases, I will use GPL software, and in
other cases I won't, and tried to explain why and what the difference
is.  Anybody can re-read my posts and figure out that the same might
apply to the various Creative Commons licenses.

> > > If the man said, "please take the chocolate, but I want you to share
> > > it with your friends", and you refused to do so because you couldn't
> > > accept that condition, would it be right to say, "that man is forcing
> > > me to share chocolate with my friends"?
>
> > But the thing is, he's *not* making me share the chocolate with any of
> > my friends. ?He's not even making me share my special peanut butter
> > and chocolate. ?What he's making me do is, if I give my peanut butter
> > and chocolate to one of my friends, he's making me make *that* friend
> > promise to share. ?I try not to impose obligations like that on my
> > friends, so obviously the "nice" man with the chocolate isn't my
> > friend!
>
> Yes, he's making everyone commit to sharing, and yes, it's like a
> snowball effect once people agree to join in.

Sorry, I sometimes have a hard time distinguishing the semantic
difference between "make" and "force".  Could you elucidate?

> But unless you hide that
> commitment, no-one imposes anything on anyone. They can get their
> chocolate elsewhere. They join in; they are not conscripted.

And I've already explained why, in some cases, someone might refuse
the tastiest chocolate in the world to not join in.

> > I explained this very carefully before multiple times. ?Let me give
> > concrete examples -- (1) I have told my children before "if we take
> > that candy, then they will make us pay for it" and (2) if we included
> > (GPLed software) in this (MIT-licensed software) then we will have to
> > change the license. ?In both these cases, once the decision has been
> > made, then yes, force enters into it. ?And no, I don't think the
> > average shop keeper is nearly as evil as Darth, or even RMS.
>
> Entering an agreement voluntarily does not mean that you are forced to
> enter that agreement, even if the agreement then involves obligations
> (as agreements inevitably do).

No, but copyright licenses are funny things, not like contracts where
there is a meeting of the minds up front.  For example, while the
Ciscos of the world have no excuse, I bet a lot of people who download
Ubuntu and make copies for their friends are unaware of this section
of the GPL FAQ:

"I downloaded just the binary from the net. If I distribute copies, do
I have to get the source and distribute that too?   Yes. The general
rule is, if you distribute binaries, you must distribute the complete
corresponding source code too. The exception for the case where you
received a written offer for source code is quite limited."

Regards,
Pat


From enleverLesX_XXmcX at XmclavXeauX.com.invalid  Wed May 12 10:51:27 2010
From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP)
Date: Wed, 12 May 2010 16:51:27 +0200
Subject: Upgrade Python 2.6.4 to 2.6.5
References: 
Message-ID: <4beac072$0$27583$ba4acef3@reader.news.orange.fr>

Hi! 

If you are under Vista, or Windows 7, have you unactivate UAC, before
the update?

@+

MCI


From pmaupin at gmail.com  Wed May 12 10:53:40 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 07:53:40 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<4bea56dd$1@dnews.tpgi.com.au>
Message-ID: <56c7788a-898f-4993-9b6f-e8d6723b573d@e2g2000yqn.googlegroups.com>

On May 12, 2:19?am, Lie Ryan  wrote:
> On 05/12/10 06:50, Patrick Maupin wrote:
>
>
>
> > On May 11, 5:34 am, Paul Boddie  wrote:
> >> On 10 Mai, 20:36, Patrick Maupin  wrote:
> >>> ?The fact is, I know the man would force me to pay for the chocolate, so in
> >>> some cases that enters into the equation and keeps me from wanting the
> >>> chocolate.
>
> >> If the man said, "please take the chocolate, but I want you to share
> >> it with your friends", and you refused to do so because you couldn't
> >> accept that condition, would it be right to say, "that man is forcing
> >> me to share chocolate with my friends"?
>
> > But the thing is, he's *not* making me share the chocolate with any of
> > my friends. ?He's not even making me share my special peanut butter
> > and chocolate. ?What he's making me do is, if I give my peanut butter
> > and chocolate to one of my friends, he's making me make *that* friend
> > promise to share. ?I try not to impose obligations like that on my
> > friends, so obviously the "nice" man with the chocolate isn't my
> > friend!
>
> The analogy breaks here; unlike chocolate, the value of software/source
> code, if shared, doesn't decrease (in fact, many software increases its
> value when shared liberally, e.g. p2p apps).

Absolutely true. Actually, the analogy was really pretty broken to
start with.  It wasn't my analogy -- I was just trying to play
along :-)

> There might be certain cases where the software contains some trade
> secret whose value decreases the more people knows about it; but sharing
> does not decrease the value of the software, at least not directly, it
> is the value of the secret that decreases because of the sharing.

Sure.  But in general, people will share, often even when doing so is
legally questionable.  Just look at the RIAA's woes if you don't
believe me.  The only real question here is whether the marginal value
achieved by adding constraints to force people to share (which most
would have done anyway) outweighs the costs to people who, for
whatever reason (perhaps a trade secret obligation) *can't* share.

The answer to that question may well vary depending on several
factors.  The fact that GPL and Apache and MIT and BSD are available
is a good thing -- whichever license an author feels best fits his
project is definitely the one he should use.

Regards,
Pat


From davea at ieee.org  Wed May 12 11:09:45 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 May 2010 11:09:45 -0400
Subject: How to add callbacks that is the same function with different
	argument in Tkinter python26?
In-Reply-To: <4BEAB681.9060108@sequans.com>
References: 
	<4BEAB681.9060108@sequans.com>
Message-ID: <4BEAC4B9.2070103@ieee.org>

Jean-Michel Pichavant wrote:
> chen zeguang wrote:
>> code is in the end.
>> I want to print different number when pressing different button.
>> Yet the program outputs 8 no matter which button is pressed.
>> I guess it's because the callback function is not established untill 
>> the button is pressed, and i has already reached to 8.
>>
>> then How to add callbacks that is the same function with different 
>> argument?
>>
>> CODE:
>> from Tkinter import *
>> root = Tk()
>> def func(x):
>>     print x
>>     return
>>
>> func_en=[]
>> for i in range(9):
>>     func_en.append(lambda:func(i))
>> for i in range(9):
>>     func_en[i]()
>> for i in range(9):
>>     Button(root, text='%d'%i, command=func_en[i]).pack()
> from Tkinter import *
> root = Tk()
>
> def func(x):
>    def _printme():
>        print x
>    return _printme
>
> for i in range(9):
>    Button(root, text='%d'%i, command=func(i)).pack()
>
> Surely someone will explain why your code was not working, I can't 
> 'cause I don't use lambda, it brings more problems than it solves 
> (maybe I'm not talented enough).
> Above is how I would have written the code, I tested it, looks like 
> it's working.
>
> JM
This solution works because of the nested function.  Chen could do the 
same with nested lambdas, or by using default arguments in the lambda.

The trick is just that you need separate instances of x for each 
callback, so they don't all get incremented in the loop.

DaveA


From aahz at pythoncraft.com  Wed May 12 11:33:49 2010
From: aahz at pythoncraft.com (Aahz)
Date: 12 May 2010 08:33:49 -0700
Subject: Extract all words that begin with x
References: 
	
	<4be971de$0$18659$4fafbaef@reader3.news.tin.it>
	
Message-ID: 

In article ,
Stefan Behnel   wrote:
>superpollo, 11.05.2010 17:03:
>> Aahz ha scritto:
>>> In article ,
>>> Terry Reedy  wrote:
>>>> On 5/10/2010 5:35 AM, James Mills wrote:
>>>>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho wrote:
>>>>>> Have I missed something, or wouldn't this work just as well:
>>>>>>
>>>>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>>>> ['awes', 'asdgas']
>>>>> I would do this for completeness (just in case):
>>>>>
>>>>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>>>> Just guards against empty strings which may or may not be in the list.
>>>> ... word[0:1] does the same thing. All Python programmers should
>>>> learn to use slicing to extract a char from a string that might be
>>>> empty.
>>>> The method call of .startswith() will be slower, I am sure.
>>>
>>> And if it is slower, so what? Using startswith() makes for faster
>>> reading of the code for me, and I'm sure I'm not the only one.
>>
>> also, what if the OP intended "words that begin with x" with x a string
>> (as opposed to a single character) ?
>
>     word[:len(x)] == x
>
>will work in that case.

But that's now going to be slower.  ;-)  (Unless one makes the obvious
optimization to hoist len(x) out of the loop.)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From stefan_ml at behnel.de  Wed May 12 12:15:48 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 12 May 2010 18:15:48 +0200
Subject: Extract all words that begin with x
In-Reply-To: 
References: 		<4be971de$0$18659$4fafbaef@reader3.news.tin.it>	
	
Message-ID: 

Aahz, 12.05.2010 17:33:
> Stefan Behnel  wrote:
>> superpollo, 11.05.2010 17:03:
>>> Aahz ha scritto:
>>>> In article,
>>>> Terry Reedy  wrote:
>>>>> On 5/10/2010 5:35 AM, James Mills wrote:
>>>>>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho  wrote:
>>>>>>> Have I missed something, or wouldn't this work just as well:
>>>>>>>
>>>>>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>>>>> ['awes', 'asdgas']
>>>>>> I would do this for completeness (just in case):
>>>>>>
>>>>>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>>>>> Just guards against empty strings which may or may not be in the list.
>>>>> ... word[0:1] does the same thing. All Python programmers should
>>>>> learn to use slicing to extract a char from a string that might be
>>>>> empty.
>>>>> The method call of .startswith() will be slower, I am sure.
>>>>
>>>> And if it is slower, so what? Using startswith() makes for faster
>>>> reading of the code for me, and I'm sure I'm not the only one.
>>>
>>> also, what if the OP intended "words that begin with x" with x a string
>>> (as opposed to a single character) ?
>>
>>      word[:len(x)] == x
>>
>> will work in that case.
>
> But that's now going to be slower.  ;-)  (Unless one makes the obvious
> optimization to hoist len(x) out of the loop.)

Right, I forgot to mention that I left that as an exercise to the reader.

Stefan



From tjreedy at udel.edu  Wed May 12 12:32:38 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Wed, 12 May 2010 12:32:38 -0400
Subject: Extract all words that begin with x
In-Reply-To: 
References: 		<4be971de$0$18659$4fafbaef@reader3.news.tin.it>	
	
Message-ID: 

On 5/12/2010 11:33 AM, Aahz wrote:

>>> also, what if the OP intended "words that begin with x" with x a string
>>> (as opposed to a single character) ?
>>
>>      word[:len(x)] == x
>>
>> will work in that case.
>
> But that's now going to be slower.  ;-)  (Unless one makes the obvious
> optimization to hoist len(x) out of the loop.)

If x were a known literal, then len(x) could be replaced by the actual 
size. But I admit that that is a nuisance and point of failure. I think 
comparing start/end strings of variable length or length greater than 
one is the real justification for the new methods, not the OP's trivial 
single-char case.

Terry Jan Reedy





From debatem1 at gmail.com  Wed May 12 12:53:18 2010
From: debatem1 at gmail.com (geremy condra)
Date: Wed, 12 May 2010 09:53:18 -0700
Subject: open(False) in python3
In-Reply-To: 
References: 
	
	
	
Message-ID: 

On Wed, May 12, 2010 at 1:36 AM, Stefan Behnel  wrote:
> Johan F?rberg, 12.05.2010 10:05:
>>
>> On Tue, 11 May 2010 19:27:37 -0300, Gabriel Genellina wrote:
>>
>>> so open(False) is the same as open(0), and 0 is the file descriptor
>>> associated to standard input. The program isn't hung, it's just waiting
>>> for you to type some text
>>
>> That's interesting. Are there any more numbered pseudofiles? I suppose
>> its mainly an excellent way to confuse people when you open(0).read(),
>> but it would be interesting to know.
>
> Standard Unix behaviour dictates that 0 is stdin, 1 is stdout, and 2 is
> stderr. So you can only read() from 0.
>
> Stefan

Nitpicking, but open(1).read() and open(2).read() both succeed
(for small values of success) the same way that open(0).read()
does.

Thanks for the advice, everybody.

Geremy Condra


From mensanator at aol.com  Wed May 12 13:12:06 2010
From: mensanator at aol.com (Mensanator)
Date: Wed, 12 May 2010 10:12:06 -0700 (PDT)
Subject: Why the inconsistent of those two base64 methods?
References:  
	
Message-ID: 

On May 12, 4:20?am, Maarten  wrote:
> On May 12, 6:04 am, Leo Jay  wrote:
>
> > I'd like to encode a string in base64, but I found a inconsistent of
> > two methods:
>
> > >>> 'aaa'.encode('base64')
> > 'YWFh\n'
> > >>> import base64
> > >>> base64.b64encode('aaa')
> > 'YWFh'
>
> > as you can see, the result of
> > 'aaa'.encode('base64')
> > has a '\n' at the end, but the other method doesn't.
>
> > Why the inconsistent?
>
> Don't know. Does it matter?

Yeah...

>>> import base64
>>> a = 'aaa'.encode('base64')
>>> aa = base64.b64encode('aaa')
>>> a == aa
False


>
> >>> import base64
> >>> base64.decodestring(base64.b64encode('aaa'))
>
> 'aaa'
>
> >>> 'aaa'.encode('base64').decode('base64')
>
> 'aaa'
>
> (so far so good, and as expected)
>
> >>> base64.decodestring('aaa'.encode('base64'))
>
> 'aaa'
>
> >>> base64.b64encode('aaa').decode('base64')
>
> 'aaa'
>
> (As far as I can see, both methods are completely consistent)

Your notion of 'consistency' is wanting.

>
> Maarten



From paul at boddie.org.uk  Wed May 12 13:17:18 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 10:17:18 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
Message-ID: <75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>

On 12 Mai, 16:45, Patrick Maupin  wrote:
> On May 12, 7:43?am, Paul Boddie  wrote:
> > Thus, "owned my soul" joins "holy war" and "Bin Laden" on the list.
> > That rhetorical toolbox is looking pretty empty at this point.
>
> Not emptier than you analogy toolbox. ?This is really a pretty stupid
> analogy, but I guess my lame attempts at showing that are wasted.

Yes they are. The analogy was to point out that someone can really
want something, but if they are not prepared to accept the "price" of
acquiring it, then there is no point in them whining about someone
withholding that thing from them, or whining about someone "forcing"
them to do stuff, especially when there is clearly no "force" involved
at all.

[...]

> > He isn't, though. He's telling you that you can't force other people
> > to lick the chocolate off whatever "Reese's Peanut Butter cups" are,
> > rather than actually eating the combination of the two, when you offer
> > such a combination to someone else.
>
> No. ?That's not what is happening, and you've now officially stretched
> the analogy way past the breaking point. ?In any case, he's telling me
> I have to give the recipe for my homemade peanut butter.

If you want to redefine the basis of the analogy, then you can talk
about the recipe all you like, yes. Otherwise, no: the analogy was
only about people whining about not being able to get stuff with no
strings attached. I could swap that analogy with one that has someone
really wanting a ride on a bus, or wanting to go to the moon, where
they don't like it when someone tells them that they can't get do that
stuff without agreeing to something or other first. Feel free to start
discussing the shape of the bus ticket or who pays for spacesuits if
you want, but to say, "I really want to use that thing, but that nasty
man has licensed it under the GPL" is whining in precisely the same
way as featured in the analogy.

> > Is the Creative Commons share-
> > alike clause just as objectionable to you, because it's that principle
> > we're talking about here?
>
> I have explained that, in some cases, I will use GPL software, and in
> other cases I won't, and tried to explain why and what the difference
> is. ?Anybody can re-read my posts and figure out that the same might
> apply to the various Creative Commons licenses.

So it is objectionable to you as well, then.

[...]

> > Yes, he's making everyone commit to sharing, and yes, it's like a
> > snowball effect once people agree to join in.
>
> Sorry, I sometimes have a hard time distinguishing the semantic
> difference between "make" and "force". ?Could you elucidate?

Yes: once they've agreed to join in, they "have to" go along with the
whole scheme.

> > But unless you hide that
> > commitment, no-one imposes anything on anyone. They can get their
> > chocolate elsewhere. They join in; they are not conscripted.
>
> And I've already explained why, in some cases, someone might refuse
> the tastiest chocolate in the world to not join in.

Well, great for them. I thought they were "forced" to join in. I guess
not.

[...]

> No, but copyright licenses are funny things, not like contracts where
> there is a meeting of the minds up front. ?For example, while the
> Ciscos of the world have no excuse, I bet a lot of people who download
> Ubuntu and make copies for their friends are unaware of this section
> of the GPL FAQ:
>
> "I downloaded just the binary from the net. If I distribute copies, do
> I have to get the source and distribute that too? ? Yes. The general
> rule is, if you distribute binaries, you must distribute the complete
> corresponding source code too. The exception for the case where you
> received a written offer for source code is quite limited."

Yes, and that's why, when Mepis Linux were found not to be
distributing the sources, they had to go along with the above section.
And that's also why version 3 of the GPL has a clause about nominating
a party that will honour the obligation to provide source. But what's
your problem exactly? The GPL applies to redistribution, and the
default state of a copyrighted work is that you don't have permission
to redistribute it, so before someone shares something they have to
know whether they are able to do so or not.

The various clauses are all there for their own reasons. If you don't
like them, don't use GPL-licensed software.

Paul


From g.rodola at gmail.com  Wed May 12 13:26:58 2010
From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=)
Date: Wed, 12 May 2010 19:26:58 +0200
Subject: open(False) in python3
In-Reply-To: 
References: 
	
Message-ID: 

2010/5/12 Gabriel Genellina :
> open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
> builtin open() + os.fdopen() from 2.x all merged together. It does different
> things depending on the type and quantity of its arguments, and even returns
> objects of different types.
>
> In particular, open(some_integer) assumes some_integer is a file descriptor
> and return some variant of file object using the given file descriptor.

Interesting. I wasn't aware of this.
Is it documented somewhere?


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil


From zapwireDASHgroups at yahoo.com  Wed May 12 13:42:31 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 10:42:31 -0700
Subject: Do any debuggers support "edit and continue?"
Message-ID: 

Just curious... in Microsoft's Visual Studio (and I would presume some other 
tools), for many languages (both interpreted and compiled!) there's an "edit 
and conitnue" option that, when you hit a breakpoint, allows you to modify a 
line of code before it's actually executed.

Does any Python debugger support this feature?  Being an interpreted language 
it doesn't seem like it would necessarily be too onerous to support?  It'd be 
quite handy in that, especially if you hit a breakpoint due to the interpreter 
throwing an error, you could fix just the line in question and keep going, 
rather than having to stop the entire program, fix the line, and then run 
again and potentially kill a bunch of time getting the program back into the 
same "state."

Thanks,
---Joel Koltner



From cde3 at live.com  Wed May 12 13:56:38 2010
From: cde3 at live.com (Sandy Sandy)
Date: Wed, 12 May 2010 22:56:38 +0500
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: 


good question
I also looking for debugging tools like Matlab in Python

do you know how to stop in breakpoint investigate the variables by using graphics in  figures and continue
the
mutter is:

during debugging the  debug processes stacks when fig is created

for example, in code

import random

import matplotlib.pyplot as plt

from pylab import *

x= 23;

y = 111111;

print(23456)

plt.plot(range(10))

plot([1,2,3])

show()

print(11111111)

a=888



it is impossible after show() to continue debug

as stated in

Beginning Python Visualization - Crafting Visual Transformation Scripts (2009)

page  187



Note If you?re not using matplotlib interactively in Python, be sure

to call the function show() after all

graphs have been generated, as it enters a user interface main loop

that will stop execution of the rest of

your code. The reason behind this behavior is that matplotlib is

designed to be embedded in a GUI as well.

In Windows, if you?re working from interactive Python, you need only

issue show() once; close the figures

(or figures) to return to the shell. Subsequent plots will be drawn

automatically without issuing show(), and

you?ll be able to plot graphs interactively.




the problem is that after show() the debugger stacks

the decision can be to use threads like this 

from pylab import plot,show,ion
ion()
x = range(10)
plot(x)
from threading import Timer
t = Timer(0, show)
t.start()

a = 1222233
y = [2, 8, 3, 9, 4]
plot(y)

zz= 12346
print(44444)




but it is not working, bug??

Sandy
  

> From: zapwireDASHgroups at yahoo.com
> Subject: Do any debuggers support "edit and continue?"
> Date: Wed, 12 May 2010 10:42:31 -0700
> To: python-list at python.org
> 
> Just curious... in Microsoft's Visual Studio (and I would presume some other 
> tools), for many languages (both interpreted and compiled!) there's an "edit 
> and conitnue" option that, when you hit a breakpoint, allows you to modify a 
> line of code before it's actually executed.
> 
> Does any Python debugger support this feature?  Being an interpreted language 
> it doesn't seem like it would necessarily be too onerous to support?  It'd be 
> quite handy in that, especially if you hit a breakpoint due to the interpreter 
> throwing an error, you could fix just the line in question and keep going, 
> rather than having to stop the entire program, fix the line, and then run 
> again and potentially kill a bunch of time getting the program back into the 
> same "state."
> 
> Thanks,
> ---Joel Koltner
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
 		 	   		  
_________________________________________________________________
Hotmail: Trusted email with Microsoft?s powerful SPAM protection.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From paul at boddie.org.uk  Wed May 12 14:00:09 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 11:00:09 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com>
Message-ID: <0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com>

On 12 Mai, 16:10, Patrick Maupin  wrote:
> On May 12, 7:10?am, Paul Boddie  wrote:
> > What the licence asks you to do and what the author of the licence
> > wants you to do are two separate things.
>
> But the whole context was about what RMS wanted me to do and you
> disagreed!

What RMS as an activist wants is that everyone releases GPL-licensed
code, except where permissively licensed code might encourage open
standards proliferation. What RMS the licence author requests is that
your work is licensed in a way which is compatible with the GPL.

[...]

> > I wrote "the software" above when I meant "your software", but I have
> > not pretended that the whole system need not be available under the
> > GPL.
>
> You say you "have not pretended" but you've never mentioned that it
> would or even acknowledged the correctness of my assertions about this
> until now, just claiming that what I said was false.

Well, excuse me! I think we both know that combining something with a
GPL-licensed work and redistributing it means that the "four freedoms"
must apply, and that recipients get the work under the GPL. You can
insist that I said something else, but I spell it out in this post:

http://groups.google.com/group/comp.lang.python/msg/034fbc8289a4d555

Specifically the part...

"Not least because people are only obliged to make their work
available under a GPL-compatible licence so that people who are using
the combined work may redistribute it under
the GPL."

In case you don't find this satisfactory, "their work" means "their
own work".

[...]

> > More loaded terms to replace the last set, I see.
>
> IMO "Bullying" is the correct term for some of Stallman's actions,
> including in the clisp debacle. ?I knew you wouldn't agree -- that's
> why YMMV. ?And I'm not "replacing" any set of terms -- part of the
> "bullying" is the "forcing."

Stallman gave Haible the choice to not use readline. Maybe that wasn't
very nice, and maybe Haible didn't believe that using readline would
incur any consequences, but that's what you get when you use a
copyrighted work. Your language is all about portraying the FSF as
operating in some kind of illegal or unethical way. I guess you
believe that if you throw enough mud, some of it will stick.

> > Again, what I meant was "your software", not the whole software
> > system. As I more or less state below...
>
> BUT THAT DOESN'T MATTER. ?Once the whole package is licensed under the
> GPL, for someone downstream to try to scrape the GPL off and get to
> just the underlying non-GPL parts is harder than scraping bubblegum
> off your shoe on a hot Texas day.

Big deal. If a project wants to avoid even looking at GPL-licensed
code for the reason that someone might end up getting the code under
the GPL, and that they're so bothered that the opportunity to not
grant such recipients the privileges of modification and
redistribution disappears because of the GPL, then that's their
problem.

[WebKit is LGPL-licensed but KHTML linked to GPL-licensed code,
shouldn't WebKit be GPL-licensed?]

> I didn't make that claim and have never heard of that claim, and I'm
> not at all sure of the relevance of whatever you're trying to explain
> to the licensing of an overall program, rather than a library.

The point is precisely the one you concede about a project needing to
be licensed compatibly with the GPL, even though to use the combined
work, the result will be GPL-licensed.

[...]

> > All RMS and the FSF's lawyers wanted was that the CNRI licences be GPL-
> > compatible. There are actually various aspects of GPL-compatibility
> > that are beneficial, even if you don't like the copyleft-style
> > clauses, so I don't think it was to the detriment of the Python
> > project.
>
> And I don't have a problem with that. ?Honestly I don't. ?But as far
> as I'm concerned, although you finally admitted it, a lot of the
> dancing around appeared to be an attempt to disprove my valid
> assertion that a combined work would have to be distributed under the
> GPL, and that no other free software license claims sovereignty over
> the entire work.

I never denied that the GPL would apply to the combined work! Read the
stuff I quote above. Your *own* stuff (for example, the WebKit stuff)
can be licensed compatibly with the GPL (for example, the LGPL), but
the *whole* thing as it lands in the user's lap will be GPL-licensed.

[...]

> > Well, that may not be a judgement shared by the authors. There are
> > numerous tools and components which do dull jobs and whose maintenance
> > is tedious and generally unrewarding, but that doesn't mean that such
> > investment is worth nothing in the face of someone else's so-very-
> > topical high-profile project.
>
> OK, so what you're saying is that readline is so dull and unrewarding
> that the only reason to bother writing it is to reel people in to the
> GPL?

No, what I am saying is that a fair amount of work might have gone
into making readline, even though it may not be shiny enough by some
people's standards, but that doesn't mean you can disregard the
authors' wishes by insisting that is it "trivial" or unimportant,
whereas your own software somehow is important. As soon as you go down
that road, everyone can start belittling the works of others purely so
that they can start disregarding the terms which regulate those works,
and then it's a free-for-all.

[...]

> > Well, if people are making use of "some good code found for free on
> > the Internet", particularly if they are corporations like Cisco, and
>
> I'm not talking about Cisco. ?I'm talking about people like the author
> of clisp, and you well know it.

Well, Cisco seemed to have a bit of a problem. Maybe they thought that
this "free stuff" was just a commodity, too.

> > they choose not to understand things like copyright and licensing, or
> > they think "all rights reserved" is just a catchy slogan, then they
> > probably shouldn't be building larger works and redistributing them.
>
> Well, the FSF seems to have softened its stance, but at the time,
> clisp wasn't even distributing readline. ?That's why I use terms like
> "bullying". ?The bully now knows it's harder to get away with that
> particular lie, but he's still scheming about how to reel more people
> in.

What the FSF did was regrettable if the author didn't feel he had a
choice. I have no idea what went on beyond what the public mailing
list record can reveal.

Paul


From kushal.kumaran+python at gmail.com  Wed May 12 14:05:37 2010
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Wed, 12 May 2010 23:35:37 +0530
Subject: open(False) in python3
In-Reply-To: 
References:  
	
	
Message-ID: 

On Wed, May 12, 2010 at 10:56 PM, Giampaolo Rodol?  wrote:
> 2010/5/12 Gabriel Genellina :
>> open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
>> builtin open() + os.fdopen() from 2.x all merged together. It does different
>> things depending on the type and quantity of its arguments, and even returns
>> objects of different types.
>>
>> In particular, open(some_integer) assumes some_integer is a file descriptor
>> and return some variant of file object using the given file descriptor.
>
> Interesting. I wasn't aware of this.
> Is it documented somewhere?
>

http://docs.python.org/py3k/library/functions.html#open

-- 
regards,
kushal


From rbrt.somerville at gmail.com  Wed May 12 14:10:20 2010
From: rbrt.somerville at gmail.com (robert somerville)
Date: Wed, 12 May 2010 11:10:20 -0700
Subject: How to test whether bit is set within a flag with Python ?
Message-ID: 

I am trying to determine how to test whether variors bits are set within a
byte (or larger flag) , the python 'and' and 'or' do not seem to be doing
what i want .. does anybody have some sample code showing how to do it ??

e.g. (in "C")

unsigned char a = 6;

is 3rd bit set ??

a & 4 =,  true in this case ....

thanks
Robert Somerville
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From phlip2005 at gmail.com  Wed May 12 14:23:42 2010
From: phlip2005 at gmail.com (Phlip)
Date: Wed, 12 May 2010 11:23:42 -0700 (PDT)
Subject: How to? epydoc --top=README
References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com>
Message-ID: 

On May 10, 1:29?pm, Phlip  wrote:
> Pythonistas:
>
> I have a question to epydoc-devel, but it might be languishing:
>
> http://sourceforge.net/mailarchive/forum.php?thread_name=l2n860c114f1...
>
> How do you populate the index.html output with your (insanely clever)
> contents of your README file?
>
> When I try the obvious notations, such as --top=README or --
> top=README.html, I get:
>
> Warning: Identifier 'README' looks suspicious; using it anyway.
> Warning: Could not find top page 'README'; using module-tree.html
> instead
>
> And, yes, the README is included in the input list, and yes I get a
> script-README-module.html
>
> ----8<------------------------------------------
>
> The question for the rest of Python-Land: Should I be using a better
> documentation extractor? (pydoc is too mundane so far.) Or should I be
> using a better forum for epydoc users questions?

Regardless of the advocacy, does anyone have an actual answer for
this?

>
> --
> ? yes-I-know-topicality-ly-yrs
> ? Phlip
> ?http://c2.com/cgi/wiki?ZeekLand



From tjreedy at udel.edu  Wed May 12 14:26:54 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Wed, 12 May 2010 14:26:54 -0400
Subject: open(False) in python3
In-Reply-To: 
References: 	
	
Message-ID: 

On 5/12/2010 1:26 PM, Giampaolo Rodol? wrote:
> 2010/5/12 Gabriel Genellina:
>> open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
>> builtin open() + os.fdopen() from 2.x all merged together. It does different
>> things depending on the type and quantity of its arguments, and even returns
>> objects of different types.

The change actually happened, according to 'What's new', in 2.6 when 
'open' was made a synonym for the new io.open.

>> In particular, open(some_integer) assumes some_integer is a file descriptor
>> and return some variant of file object using the given file descriptor.
>
> Interesting. I wasn't aware of this.
> Is it documented somewhere?

Right where it should be, in the entry for 'open' under 'built-in 
functions': "file is either ... or an integer file descriptor of the 
file to be wrapped"




From pmaupin at gmail.com  Wed May 12 14:29:38 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 11:29:38 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
Message-ID: <039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>

On May 12, 12:17?pm, Paul Boddie  wrote:
> On 12 Mai, 16:45, Patrick Maupin  wrote:
>
> > On May 12, 7:43?am, Paul Boddie  wrote:
> > > Thus, "owned my soul" joins "holy war" and "Bin Laden" on the list.
> > > That rhetorical toolbox is looking pretty empty at this point.
>
> > Not emptier than you analogy toolbox. ?This is really a pretty stupid
> > analogy, but I guess my lame attempts at showing that are wasted.
>
> Yes they are. The analogy was to point out that someone can really
> want something, but if they are not prepared to accept the "price" of
> acquiring it, then there is no point in them whining about someone
> withholding that thing from them, or whining about someone "forcing"
> them to do stuff, especially when there is clearly no "force" involved
> at all.

But nobody's whining about the strings attached to the software.  Just
pointing out why they sometimes won't use a particular piece of
software, and pointing out that some other people (e.g. random Ubuntu
users) might not understand the full cost of the software, and that
that is because the cost of the software has been deliberately
obscured by using unqualified terms like all-caps "Free Software."

> > > He isn't, though. He's telling you that you can't force other people
> > > to lick the chocolate off whatever "Reese's Peanut Butter cups" are,
> > > rather than actually eating the combination of the two, when you offer
> > > such a combination to someone else.
>
> > No. ?That's not what is happening, and you've now officially stretched
> > the analogy way past the breaking point. ?In any case, he's telling me
> > I have to give the recipe for my homemade peanut butter.
>
> If you want to redefine the basis of the analogy, then you can talk
> about the recipe all you like, yes. Otherwise, no: the analogy was
> only about people whining about not being able to get stuff with no
> strings attached. I could swap that analogy with one that has someone
> really wanting a ride on a bus, or wanting to go to the moon, where
> they don't like it when someone tells them that they can't get do that
> stuff without agreeing to something or other first. Feel free to start
> discussing the shape of the bus ticket or who pays for spacesuits if
> you want, but to say, "I really want to use that thing, but that nasty
> man has licensed it under the GPL" is whining in precisely the same
> way as featured in the analogy.

Oh, no wonder I didn't understand what you were getting at with the
analogy.  I'm not whining about people licensing stuff under the GPL,
just about its apologists pretending there are never any negative
consequences from it.

> > > Is the Creative Commons share-
> > > alike clause just as objectionable to you, because it's that principle
> > > we're talking about here?
>
> > I have explained that, in some cases, I will use GPL software, and in
> > other cases I won't, and tried to explain why and what the difference
> > is. ?Anybody can re-read my posts and figure out that the same might
> > apply to the various Creative Commons licenses.
>
> So it is objectionable to you as well, then.

I somehow knew that is how you would read my posts, but no.  It's
people like you putting words in my month that is objectionable.

> [...]
>
> > > Yes, he's making everyone commit to sharing, and yes, it's like a
> > > snowball effect once people agree to join in.
>
> > Sorry, I sometimes have a hard time distinguishing the semantic
> > difference between "make" and "force". ?Could you elucidate?
>
> Yes: once they've agreed to join in, they "have to" go along with the
> whole scheme.

Sorry, that is absolutely no different than what I originally said
when I was first defending Aahz's use of the word "force" to Ben
Finney back on the 7th:

"Perhaps you feel "forces" is too loaded of a word.  There is no
question, however, that a copyright license can require that if you do
"X" with some code, you must also do "Y".  There is also no question
that the GPL uses this capability in copyright law to require anybody
who distributes a derivative work to provide the source.  Thus,
"forced to contribute back any changes" is definitely what happens
once the decision is made to distribute said changes in object form."

Both your "make" and my "force" mean "to compel."  We've come full
circle.  The English language makes no real distinction between
"making everyone commit" and "forcing everyone [to] commit".


> > > But unless you hide that
> > > commitment, no-one imposes anything on anyone. They can get their
> > > chocolate elsewhere. They join in; they are not conscripted.
>
> > And I've already explained why, in some cases, someone might refuse
> > the tastiest chocolate in the world to not join in.
>
> Well, great for them. I thought they were "forced" to join in. I guess
> not.

That's because you use selective quoting of "forced" and deliberately
ignore the context it was used in.

> > No, but copyright licenses are funny things, not like contracts where
> > there is a meeting of the minds up front. ?For example, while the
> > Ciscos of the world have no excuse, I bet a lot of people who download
> > Ubuntu and make copies for their friends are unaware of this section
> > of the GPL FAQ:
>
> > "I downloaded just the binary from the net. If I distribute copies, do
> > I have to get the source and distribute that too? ? Yes. The general
> > rule is, if you distribute binaries, you must distribute the complete
> > corresponding source code too. The exception for the case where you
> > received a written offer for source code is quite limited."
>
> Yes, and that's why, when Mepis Linux were found not to be
> distributing the sources, they had to go along with the above section.
> And that's also why version 3 of the GPL has a clause about nominating
> a party that will honour the obligation to provide source. But what's
> your problem exactly?

My problem, exactly, is that bothering Mepis, yet not bothering Joe
Blow when he gives a copy to his friend, is exactly the kind of
selective enforcement of copyright rights that Microsoft is accused of
when they turn a blind eye to piracy in third-world countries.

>The GPL applies to redistribution, and the
> default state of a copyrighted work is that you don't have permission
> to redistribute it, so before someone shares something they have to
> know whether they are able to do so or not.

And Joe Blow assumes that something that says "Free Software" means
it.  Sure he *should* read the copyright license, but you've already
admitted he probably won't bother, and might not understand it if he
does.

> The various clauses are all there for their own reasons. If you don't
> like them, don't use GPL-licensed software.

I've already explained very carefully multiple times:

1) I often use GPL software, and don't have any problem with the
license at all *as a user*.
2) I very seldom create stuff under the GPL because I don't like
imposing those sorts of restrictions on software I am giving away; and
3) For stuff  I create which is not under the GPL, to make sure that I
can give it away without restrictions, I need to make sure that I am
not incorporating any GPL software.

Despite your opinion, there is nothing legally or morally wrong with
me using GPL software (and not redistributing it) just because I
happen to feel that (a) for my purposes, for most stuff I write, it
happens to be the wrong license, (b) (especially historically) some of
the practices used to insure proliferation of the GPL are ethically
questionable, and (c) whenever these ethically questionable practices
are discussed, quasi-religious apologists will take these questionable
practices to the next level, by selective quoting and bad analogies
and hinting at things without actually coming out and saying them, and
all sorts of other debate tactics designed to confuse rather than
enlighten.

Regards,
Pat


From davea at ieee.org  Wed May 12 14:36:28 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 May 2010 14:36:28 -0400
Subject: open(False) in python3
In-Reply-To: 
References: 	
	
Message-ID: <4BEAF52C.70504@ieee.org>



Giampaolo Rodol? wrote:
> 2010/5/12 Gabriel Genellina :
>   
>> open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
>> builtin open() + os.fdopen() from 2.x all merged together. It does different
>> things depending on the type and quantity of its arguments, and even returns
>> objects of different types.
>>
>> In particular, open(some_integer) assumes some_integer is a file descriptor
>> and return some variant of file object using the given file descriptor.
>>     
>
> Interesting. I wasn't aware of this.
> Is it documented somewhere?
>
>
>   
http://docs.python.org/py3k/library/functions.html#open

   .... or an integer file descriptor of the file to be wrapped.....




From python at mrabarnett.plus.com  Wed May 12 14:40:59 2010
From: python at mrabarnett.plus.com (MRAB)
Date: Wed, 12 May 2010 19:40:59 +0100
Subject: How to test whether bit is set within a flag with Python ?
In-Reply-To: 
References: 
Message-ID: <4BEAF63B.3020409@mrabarnett.plus.com>

robert somerville wrote:
> I am trying to determine how to test whether variors bits are set within 
> a byte (or larger flag) , the python 'and' and 'or' do not seem to be 
> doing what i want .. does anybody have some sample code showing how to 
> do it ??
> 
> e.g. (in "C")
> 
> unsigned char a = 6;
> 
> is 3rd bit set ??
> 
> a & 4 =,  true in this case ....
> 
'and', 'or' and 'not' are Boolean.

Python borrows its bitwise operators from C:

     &     bitwise and
     |     bitwise or
     ^     bitwise xor
     ~     bitwise not (ones' complement)
     <<    shift left
     >>    shift right

You also need to remember that Python's integers are of (virtually)
unlimited length.


From stef.mientki at gmail.com  Wed May 12 14:43:50 2010
From: stef.mientki at gmail.com (Stef Mientki)
Date: Wed, 12 May 2010 20:43:50 +0200
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: <4BEAF6E6.6020303@gmail.com>

On 12-05-2010 19:42, Joel Koltner wrote:
> Just curious... in Microsoft's Visual Studio (and I would presume some
> other tools), for many languages (both interpreted and compiled!)
> there's an "edit and conitnue" option that, when you hit a breakpoint,
> allows you to modify a line of code before it's actually executed.
>
> Does any Python debugger support this feature?  Being an interpreted
> language it doesn't seem like it would necessarily be too onerous to
> support?  It'd be quite handy in that, especially if you hit a
> breakpoint due to the interpreter throwing an error, you could fix
> just the line in question and keep going, rather than having to stop
> the entire program, fix the line, and then run again and potentially
> kill a bunch of time getting the program back into the same "state."
>
> Thanks,
> ---Joel Koltner
>
winpdb perhaps ?

Stef
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From tjreedy at udel.edu  Wed May 12 14:46:53 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Wed, 12 May 2010 14:46:53 -0400
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: 

On 5/12/2010 1:42 PM, Joel Koltner wrote:
> Just curious... in Microsoft's Visual Studio (and I would presume some
> other tools), for many languages (both interpreted and compiled!)
> there's an "edit and conitnue" option that, when you hit a breakpoint,
> allows you to modify a line of code before it's actually executed.
>
> Does any Python debugger support this feature? Being an interpreted
> language it doesn't seem like it would necessarily be too onerous to
> support? It'd be quite handy in that, especially if you hit a breakpoint
> due to the interpreter throwing an error, you could fix just the line in

CPython compiles Python code (a sequence of statements) to its private 
bytecode (a sequence of codes and operands) and then interprets the 
bytecode. So 'edit and continue' would have to recompile the statement 
and patch the result into the bytecode. Since function compilation 
depends on global analysis of the function, functions would have to be 
recompiled as a whole.

Another problem is recovery of state. If an exception is raised in the 
middle of a statememt, there would need to be a means to roll back the 
state of objects and namespaces to what they were before execution of 
the statement started. So the interpreter would need to act like a 
transactional database, which is not trivial. This would also slow 
normal execution, so it would have to be optional.

> question and keep going, rather than having to stop the entire program,
> fix the line, and then run again and potentially kill a bunch of time
> getting the program back into the same "state."

If would definitely be nice. Perhaps $500,000 in funding would do the trick.

Terry Jan Reedy



From lie.1296 at gmail.com  Wed May 12 14:49:24 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Thu, 13 May 2010 04:49:24 +1000
Subject: Picking a license
In-Reply-To: <56c7788a-898f-4993-9b6f-e8d6723b573d@e2g2000yqn.googlegroups.com>
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
	<4bea56dd$1@dnews.tpgi.com.au>
	<56c7788a-898f-4993-9b6f-e8d6723b573d@e2g2000yqn.googlegroups.com>
Message-ID: <4beaf893$1@dnews.tpgi.com.au>

On 05/13/10 00:53, Patrick Maupin wrote:
> On May 12, 2:19 am, Lie Ryan  wrote:
>> On 05/12/10 06:50, Patrick Maupin wrote:
>>
>>
>>
>>> On May 11, 5:34 am, Paul Boddie  wrote:
>>>> On 10 Mai, 20:36, Patrick Maupin  wrote:
>>>>>  The fact is, I know the man would force me to pay for the chocolate, so in
>>>>> some cases that enters into the equation and keeps me from wanting the
>>>>> chocolate.
>>
>>>> If the man said, "please take the chocolate, but I want you to share
>>>> it with your friends", and you refused to do so because you couldn't
>>>> accept that condition, would it be right to say, "that man is forcing
>>>> me to share chocolate with my friends"?
>>
>>> But the thing is, he's *not* making me share the chocolate with any of
>>> my friends.  He's not even making me share my special peanut butter
>>> and chocolate.  What he's making me do is, if I give my peanut butter
>>> and chocolate to one of my friends, he's making me make *that* friend
>>> promise to share.  I try not to impose obligations like that on my
>>> friends, so obviously the "nice" man with the chocolate isn't my
>>> friend!
>>
>> The analogy breaks here; unlike chocolate, the value of software/source
>> code, if shared, doesn't decrease (in fact, many software increases its
>> value when shared liberally, e.g. p2p apps).
> 
> Absolutely true. Actually, the analogy was really pretty broken to
> start with.  It wasn't my analogy -- I was just trying to play
> along :-)

All analogy is broken, except if the analogy is the exact situation; but
then again, if the analogy is the exact situation, then it's not an
analogy :-)


From no.email at please.post  Wed May 12 14:52:41 2010
From: no.email at please.post (kj)
Date: Wed, 12 May 2010 18:52:41 +0000 (UTC)
Subject: Limitation of os.walk
References:  
	
Message-ID: 

In  Tim Chase writes:
>  05/11/2010 09:07 PM, Terry Reedy wrote:
>> If os.walk were rewritten, it should be as an iterator (generator).
>> Directory entry and exit functions could still be added as params.

>It *is* an iterator/generator.  However, I suspect you mean that 
>it should slurp the dirs/files iteratively instead of using 
>listdir() as was discussed on c.l.p a few months back.

Thanks for mentioning this thread.  Very interesting stuff.  Apropos
the implementability of an iterative listdir, I wonder if some
variation of glob.iglob() would fit the bill.  (Maybe it's too
slow, though.)

>I suspect if I thought about it much longer, only one would 
>really be needed, the other accommodated by the "topdown" parameter.

Yeah, I think one only needs a post hook.  The fact that it's a
generator obviates need for a pre hook, since the yield returns
control to the calling function right around where the pre-hook
would run anyway.  For the same reason, the post hook is needed
only for the case topdown=True.

Another useful callback would be one that replaced listdir in the
generation of the current directory's contents.

~K


From zapwireDASHgroups at yahoo.com  Wed May 12 14:54:30 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 11:54:30 -0700
Subject: Do any debuggers support "edit and continue?"
References: 
	
Message-ID: 

"Terry Reedy"  wrote in message 
news:mailman.119.1273690025.32709.python-list at python.org...
> CPython compiles Python code (a sequence of statements) to its private 
> bytecode (a sequence of codes and operands) and then interprets the 
> bytecode. So 'edit and continue' would have to recompile the statement and 
> patch the result into the bytecode.

I believe this is what, e.g., Visual Studio does with, e.g., C++ code -- it 
compiles the modified code and then patches the binary to call the new code as 
a subroutine or somesuch.

> Another problem is recovery of state. If an exception is raised in the 
> middle of a statememt, there would need to be a means to roll back the state 
> of objects and namespaces to what they were before execution of the 
> statement started. So the interpreter would need to act like a transactional 
> database, which is not trivial.

Yeah, I can see this being challenging.  I think it's pretty cool how some 
Python debuggers will allow you to use a shell with the context set to the 
current function or any of the calling functions higher up the call stack 
hierarchy as well.

> This would also slow normal execution, so it would have to be optional.

That'd be a small price to pay. :-)  (Visual Studio only lets you do this with 
unoptimized code...)

> If would definitely be nice. Perhaps $500,000 in funding would do the trick.

Cool, if I win the lottery and add it to the "worty causes" list! :-)

Thanks for the information,
---Joel



From cjw at ncf.ca  Wed May 12 14:55:09 2010
From: cjw at ncf.ca (cjw)
Date: Wed, 12 May 2010 14:55:09 -0400
Subject: How to test whether bit is set within a flag with Python ?
In-Reply-To: 
References: 
	
Message-ID: 

On 12-May-10 14:40 PM, MRAB wrote:
> robert somerville wrote:
>> I am trying to determine how to test whether variors bits are set
>> within a byte (or larger flag) , the python 'and' and 'or' do not seem
>> to be doing what i want .. does anybody have some sample code showing
>> how to do it ??
>>
>> e.g. (in "C")
>>
>> unsigned char a = 6;
>>
>> is 3rd bit set ??
>>
>> a & 4 =, true in this case ....
>>
> 'and', 'or' and 'not' are Boolean.
>
> Python borrows its bitwise operators from C:
>
> & bitwise and
> | bitwise or
> ^ bitwise xor
> ~ bitwise not (ones' complement)
> << shift left
>  >> shift right
>
> You also need to remember that Python's integers are of (virtually)
> unlimited length.

a= 6
if a & 2:
   print 'hit'
else:
   print 'miss'

This hits.

Colin W.



From pmaupin at gmail.com  Wed May 12 15:02:07 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 12:02:07 -0700 (PDT)
Subject: Picking a license
References: 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com>
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com> 
	<0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com>
Message-ID: <356d235e-63e3-4d36-bb7e-e436d9279f27@l28g2000yqd.googlegroups.com>

On May 12, 1:00?pm, Paul Boddie  wrote:
> On 12 Mai, 16:10, Patrick Maupin  wrote:
>
> > On May 12, 7:10?am, Paul Boddie  wrote:
> > > What the licence asks you to do and what the author of the licence
> > > wants you to do are two separate things.
>
> > But the whole context was about what RMS wanted me to do and you
> > disagreed!
>
> What RMS as an activist wants is that everyone releases GPL-licensed
> code, except where permissively licensed code might encourage open
> standards proliferation. What RMS the licence author requests is that
> your work is licensed in a way which is compatible with the GPL.

Sorry, didn't know they were twins.

>
> [...]
>
> > > I wrote "the software" above when I meant "your software", but I have
> > > not pretended that the whole system need not be available under the
> > > GPL.
>
> > You say you "have not pretended" but you've never mentioned that it
> > would or even acknowledged the correctness of my assertions about this
> > until now, just claiming that what I said was false.
>
> Well, excuse me! I think we both know that combining something with a
> GPL-licensed work and redistributing it means that the "four freedoms"
> must apply, and that recipients get the work under the GPL. You can
> insist that I said something else, but I spell it out in this post:
>
> http://groups.google.com/group/comp.lang.python/msg/034fbc8289a4d555
>
> Specifically the part...
>
> "Not least because people are only obliged to make their work
> available under a GPL-compatible licence so that people who are using
> the combined work may redistribute it under
> the GPL."
>
> In case you don't find this satisfactory, "their work" means "their
> own work".

OK, but in the last several threads on this sub-part, you kept
contradicting me for some supposed technicality (how was I to know
there were two RMS's?) when I was trying to make the same point.

>
> [...]
>
> > > More loaded terms to replace the last set, I see.
>
> > IMO "Bullying" is the correct term for some of Stallman's actions,
> > including in the clisp debacle. ?I knew you wouldn't agree -- that's
> > why YMMV. ?And I'm not "replacing" any set of terms -- part of the
> > "bullying" is the "forcing."
>
> Stallman gave Haible the choice to not use readline. Maybe that wasn't
> very nice,

It wasn't even legally correct.  At that point, Stallman had access to
counsel, etc. and should have known better.

> and maybe Haible didn't believe that using readline would
> incur any consequences,

He wasn't distributing it!  It didn't incur any legal consequences;
only the consequence due to not realizing that using readline placed
him squarely inside RMS's chess game.

> but that's what you get when you use a
> copyrighted work.

No.  That's what you get when you use a copyrighted work authored by
an idealist who is trying to spread his choice of license.

> Your language is all about portraying the FSF as
> operating in some kind of illegal or unethical way.

Sorry, didn't mean to be that subtle.  RMS and others at the FSF have,
on multiple occasions, made statements about how licenses work which
are legally false.  This is not illegal, but it is, in my opinion,
unethical.  Some of these claims appear to not be made so boldly any
more, so perhaps they are catching on that others have caught on.

> I guess you
> believe that if you throw enough mud, some of it will stick.

I don't care about mud or sticking.  I am happy to see that the
current wording of the FAQ probably means that another clisp/readline
scenario won't happen, and like to believe that the public outcry over
this sort of thing, and reminders of it in this sort of discussion,
help to remind the FSF that others are watching them.

> > > Again, what I meant was "your software", not the whole software
> > > system. As I more or less state below...
>
> > BUT THAT DOESN'T MATTER. ?Once the whole package is licensed under the
> > GPL, for someone downstream to try to scrape the GPL off and get to
> > just the underlying non-GPL parts is harder than scraping bubblegum
> > off your shoe on a hot Texas day.
>
> Big deal. If a project wants to avoid even looking at GPL-licensed
> code for the reason that someone might end up getting the code under
> the GPL, and that they're so bothered that the opportunity to not
> grant such recipients the privileges of modification and
> redistribution disappears because of the GPL, then that's their
> problem.

Yes, I understand it's no big deal to you.  However, what you have
said is not quite right.  If I license something under the MIT
license, I cannot guarantee that no one will ever get it under the
GPL, because it could be redistributed downstream under the GPL (but
then I don't care to in any case).  However, I *can* guarantee that
the code I write (and all the underlying code it relies on) will
remain freely available from me for people who need the ability to,
for example, link with proprietary code.

Despite this not being a very big deal to you, the whole tempest in a
teacup here is about this very issue.  Yes, I understand it is a
problem for me, or any other author who wants to provide code that can
be used freely by people who download it.  And, as has been pointed
out in this discussion, many people don't read licenses very
carefully, so someone who doesn't want to restrict other people from
linking his library with third party proprietary code should think
twice about using the GPL.

> [WebKit is LGPL-licensed but KHTML linked to GPL-licensed code,
> shouldn't WebKit be GPL-licensed?]
>
> > I didn't make that claim and have never heard of that claim, and I'm
> > not at all sure of the relevance of whatever you're trying to explain
> > to the licensing of an overall program, rather than a library.
>
> The point is precisely the one you concede about a project needing to
> be licensed compatibly with the GPL, even though to use the combined
> work, the result will be GPL-licensed.

You keep spinning around on what you're trying to argue or prove.  I
don't know what I'm supposed to have "conceded" -- I was only stating
the obvious about how if I incorporate GPL licensed code in a project,
the entire project has to be GPL licensed.

>
> > > All RMS and the FSF's lawyers wanted was that the CNRI licences be GPL-
> > > compatible. There are actually various aspects of GPL-compatibility
> > > that are beneficial, even if you don't like the copyleft-style
> > > clauses, so I don't think it was to the detriment of the Python
> > > project.
>
> > And I don't have a problem with that. ?Honestly I don't. ?But as far
> > as I'm concerned, although you finally admitted it, a lot of the
> > dancing around appeared to be an attempt to disprove my valid
> > assertion that a combined work would have to be distributed under the
> > GPL, and that no other free software license claims sovereignty over
> > the entire work.
>
> I never denied that the GPL would apply to the combined work! Read the
> stuff I quote above. Your *own* stuff (for example, the WebKit stuff)
> can be licensed compatibly with the GPL (for example, the LGPL), but
> the *whole* thing as it lands in the user's lap will be GPL-licensed.

Yes, but at the outset, I was talking about incorporating (at least to
the point of redistributing) GPL-licensed code.  That forces the
license.

> No, what I am saying is that a fair amount of work might have gone
> into making readline, even though it may not be shiny enough by some
> people's standards, but that doesn't mean you can disregard the
> authors' wishes by insisting that is it "trivial" or unimportant,
> whereas your own software somehow is important. As soon as you go down
> that road, everyone can start belittling the works of others purely so
> that they can start disregarding the terms which regulate those works,
> and then it's a free-for-all.

Ahh, well done.  You've sucked me into a meaningless side debate.  If
I'm not distributing readline, then legally the license distribution
terms don't apply to me.  End of story.  (Morally, now we might get
into how trivial it is or isn't.)

> > > Well, if people are making use of "some good code found for free on
> > > the Internet", particularly if they are corporations like Cisco, and
>
> > I'm not talking about Cisco. ?I'm talking about people like the author
> > of clisp, and you well know it.
>
> Well, Cisco seemed to have a bit of a problem. Maybe they thought that
> this "free stuff" was just a commodity, too.

Well, that's the problem with an "attractive nuisance."  It's
attractive, or people wouldn't use it, and it's a nuisance -- either
you have to have the lawyers look at all this paperwork, or you can
just ignore it and hope for the best and be bothered by the nuisance
later.  And before you start talking about how the license isn't any
worse than Microsoft, etc.  -- just remember that, for Cisco, part of
what makes it attractive is the availability of source.

> > > they choose not to understand things like copyright and licensing, or
> > > they think "all rights reserved" is just a catchy slogan, then they
> > > probably shouldn't be building larger works and redistributing them.
>
> > Well, the FSF seems to have softened its stance, but at the time,
> > clisp wasn't even distributing readline. ?That's why I use terms like
> > "bullying". ?The bully now knows it's harder to get away with that
> > particular lie, but he's still scheming about how to reel more people
> > in.
>
> What the FSF did was regrettable if the author didn't feel he had a
> choice. I have no idea what went on beyond what the public mailing
> list record can reveal.

But you don't need to know anything else.  RMS claimed clisp was a
derivative work of readline, even though readline wasn't even
distributed with clisp.  That's just plain copyright misuse, and if it
had gone to court with good lawyers, RMS might have lost the copyright
protections for readline.

Regards,
Pat


From no.email at please.post  Wed May 12 15:04:47 2010
From: no.email at please.post (kj)
Date: Wed, 12 May 2010 19:04:47 +0000 (UTC)
Subject: Limitation of os.walk
References: 
	
Message-ID: 

In  Terry Reedy  writes:

>On 5/11/2010 3:49 PM, kj wrote:
>> PS: I never understood why os.walk does not support hooks for key
>> events during such a tree traversal.

>Either 1) it is intentionally simple, with the expectation that people 
>would write there own code for more complicated uses or 2) no one has 
>submitted a 'full-featured' version or 3) both.

I hope it's not (1): I want the language I use to include more
"batteries" not fewer.

It seems that a similar "simplicity argument" was invoked
to strip the cmp option from sort in Python 3.  Grrrr.  Simplicity
is great, but when the drive for it starts causing useful functionality
to be thrown out, then it is going too far.  Yes, I know that it
is possible to do everything that sort's cmp option does through
clever tricks with key, but grokking and coding this maneuver
requires a *lot* more Python-fu than cmp did, which makes this
functionality a lot less accessible to beginners that the intrinsic
complexity of the problem warrants.  And for what?  To get rid of
an *option* that could be easily disregarded by anyone who found
it too "complex"? It makes no sense to me.


From lie.1296 at gmail.com  Wed May 12 15:05:45 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Thu, 13 May 2010 05:05:45 +1000
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: <4beafc68$1@dnews.tpgi.com.au>

On 05/13/10 03:42, Joel Koltner wrote:
> Just curious... in Microsoft's Visual Studio (and I would presume some
> other tools), for many languages (both interpreted and compiled!)
> there's an "edit and conitnue" option that, when you hit a breakpoint,
> allows you to modify a line of code before it's actually executed.
> 
> Does any Python debugger support this feature?  Being an interpreted
> language it doesn't seem like it would necessarily be too onerous to
> support?  It'd be quite handy in that, especially if you hit a
> breakpoint due to the interpreter throwing an error, you could fix just
> the line in question and keep going, rather than having to stop the
> entire program, fix the line, and then run again and potentially kill a
> bunch of time getting the program back into the same "state."
> 

Using pdb, if you step through a function, you can execute arbitrary
python function in the break and then 'jump' to the line after the next,
effectively simulating "edit and continue". I don't know if there's any
GUI interface to pdb that uses them though.


From phlip2005 at gmail.com  Wed May 12 15:33:18 2010
From: phlip2005 at gmail.com (Phlip)
Date: Wed, 12 May 2010 12:33:18 -0700 (PDT)
Subject: Do any debuggers support "edit and continue?"
References: 
Message-ID: 

On May 12, 10:42?am, "Joel Koltner" 
wrote:

> Does any Python debugger support this feature?

I have worked for >3 years by now in Python and have never once
debugged.

People who need "edit and continue" probably need developer tests
instead. You typically edit the test a little, run all the code, edit
the code a little, run all the code, and integrate whenever the code's
a little better and all the tests pass.

To avoid debugging, if the tests fail unexpectedly or mysteriously,
you just 'git reset --hard HEAD'. Your bug disappears. Better than a
debugger!


From zapwireDASHgroups at yahoo.com  Wed May 12 15:44:06 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 12:44:06 -0700
Subject: Do any debuggers support "edit and continue?"
References: 
	
Message-ID: 

"Phlip"  wrote in message 
news:d580dece-bd42-4753-a0c6-783ce69b5a81 at m31g2000pre.googlegroups.com...
> People who need "edit and continue" probably need developer tests
> instead. You typically edit the test a little, run all the code, edit
> the code a little, run all the code, and integrate whenever the code's
> a little better and all the tests pass.

I find myself making mistakes in typing the name of classes and/or methods 
when I'm first getting started with them (there are some thousands of them 
after all, and even of commonly used classes/methods you're probably talking 
upwards of a hundred), *particularly* when using libraries such as wxWidgets 
that use "fancy" imports that aren't correctly picked up by the "code 
intelligence" analyzers in, e.g., Komodo or Wing.



From martin at v.loewis.de  Wed May 12 16:24:09 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Wed, 12 May 2010 22:24:09 +0200
Subject: open(False) in python3
In-Reply-To: 
References: 			
	
Message-ID: <4BEB0E69.8080506@v.loewis.de>

geremy condra wrote:
> On Wed, May 12, 2010 at 1:36 AM, Stefan Behnel  wrote:
>> Johan F?rberg, 12.05.2010 10:05:
>>> On Tue, 11 May 2010 19:27:37 -0300, Gabriel Genellina wrote:
>>>
>>>> so open(False) is the same as open(0), and 0 is the file descriptor
>>>> associated to standard input. The program isn't hung, it's just waiting
>>>> for you to type some text
>>> That's interesting. Are there any more numbered pseudofiles? I suppose
>>> its mainly an excellent way to confuse people when you open(0).read(),
>>> but it would be interesting to know.
>> Standard Unix behaviour dictates that 0 is stdin, 1 is stdout, and 2 is
>> stderr. So you can only read() from 0.
>>
>> Stefan
> 
> Nitpicking, but open(1).read() and open(2).read() both succeed
> (for small values of success) the same way that open(0).read()
> does.

That's because your operating system made that so. Try a different
operating system, and you may get different results.

Regards,
Martin


From phlip2005 at gmail.com  Wed May 12 16:31:05 2010
From: phlip2005 at gmail.com (Phlip)
Date: Wed, 12 May 2010 13:31:05 -0700 (PDT)
Subject: Do any debuggers support "edit and continue?"
References:  
	 
	
Message-ID: <75c050d2-365e-4b08-8716-884ed5473572@k25g2000prh.googlegroups.com>

On May 12, 12:44?pm, "Joel Koltner" 
wrote:

> I find myself making mistakes in typing the name of classes and/or methods
> when I'm first getting started with them (there are some thousands of them
> after all, and even of commonly used classes/methods you're probably talking
> upwards of a hundred), *particularly* when using libraries such as wxWidgets
> that use "fancy" imports that aren't correctly picked up by the "code
> intelligence" analyzers in, e.g., Komodo or Wing.

Are you implying that you then run the code, and - after a handful of
higher-level calls - control flow gets down to the lines you just
typed, and the run fails because they are misspelled? The only fix is
decoupling, and _expecting_ your first few debugger or test runs to
fail.

Other than that, lolwut?


From zapwireDASHgroups at yahoo.com  Wed May 12 16:38:25 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 13:38:25 -0700
Subject: Do any debuggers support "edit and continue?"
References: 
	
	
	<75c050d2-365e-4b08-8716-884ed5473572@k25g2000prh.googlegroups.com>
Message-ID: <7lEGn.122365$iG7.15555@en-nntp-12.dc1.easynews.com>

"Phlip"  wrote in message 
news:75c050d2-365e-4b08-8716-884ed5473572 at k25g2000prh.googlegroups.com...
On May 12, 12:44 pm, "Joel Koltner" 
wrote:
>Are you implying that you then run the code, and - after a handful of
>higher-level calls - control flow gets down to the lines you just
>typed, and the run fails because they are misspelled?

Correct.

>The only fix is
>decoupling, and _expecting_ your first few debugger or test runs to
>fail.

Well, sure, that is the current fix... but an "edit and continue" feature 
would make for a much faster fix. :-)



From phlip2005 at gmail.com  Wed May 12 16:40:53 2010
From: phlip2005 at gmail.com (Phlip)
Date: Wed, 12 May 2010 13:40:53 -0700 (PDT)
Subject: Do any debuggers support "edit and continue?"
References:  
	 
	
	<75c050d2-365e-4b08-8716-884ed5473572@k25g2000prh.googlegroups.com>
	<7lEGn.122365$iG7.15555@en-nntp-12.dc1.easynews.com>
Message-ID: 

On May 12, 1:38?pm, "Joel Koltner" 
wrote:

> Well, sure, that is the current fix... but an "edit and continue" feature
> would make for a much faster fix. :-)

Are you implying, after an edit, you need to start a program again,
then enter several user inputs, to navigate back to the place where
you hit the syntax error? (WxWidgets noted - props!)


From cde3 at live.com  Wed May 12 17:01:37 2010
From: cde3 at live.com (Sandy Sandy)
Date: Thu, 13 May 2010 02:01:37 +0500
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: 



maybe ipython?


http://showmedo.com/videos/video?name=1000020&fromSeriesID=100



> From: zapwireDASHgroups at yahoo.com
> Subject: Do any debuggers support "edit and continue?"
> Date: Wed, 12 May 2010 10:42:31 -0700
> To: python-list at python.org
> 
> Just curious... in Microsoft's Visual Studio (and I would presume some other 
> tools), for many languages (both interpreted and compiled!) there's an "edit 
> and conitnue" option that, when you hit a breakpoint, allows you to modify a 
> line of code before it's actually executed.
> 
> Does any Python debugger support this feature?  Being an interpreted language 
> it doesn't seem like it would necessarily be too onerous to support?  It'd be 
> quite handy in that, especially if you hit a breakpoint due to the interpreter 
> throwing an error, you could fix just the line in question and keep going, 
> rather than having to stop the entire program, fix the line, and then run 
> again and potentially kill a bunch of time getting the program back into the 
> same "state."
> 
> Thanks,
> ---Joel Koltner
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
 		 	   		  
_________________________________________________________________
Hotmail: Powerful Free email with security by Microsoft.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nagle at animats.com  Wed May 12 17:18:53 2010
From: nagle at animats.com (John Nagle)
Date: Wed, 12 May 2010 14:18:53 -0700
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: <4beb15c5$0$1634$742ec2ed@news.sonic.net>

Joel Koltner wrote:
> Just curious... in Microsoft's Visual Studio (and I would presume some 
> other tools), for many languages (both interpreted and compiled!) 
> there's an "edit and conitnue" option that, when you hit a breakpoint, 
> allows you to modify a line of code before it's actually executed.
> 
> Does any Python debugger support this feature?  Being an interpreted 
> language it doesn't seem like it would necessarily be too onerous to 
> support?  It'd be quite handy in that, especially if you hit a 
> breakpoint due to the interpreter throwing an error, you could fix just 
> the line in question and keep going, rather than having to stop the 
> entire program, fix the line, and then run again and potentially kill a 
> bunch of time getting the program back into the same "state."

    Having actually used LISP systems with "edit and continue", it's a good
thing that Python doesn't have it.  It encourages a "patch" mentality, and
the resulting code is usually disappointing.

    What the original poster seems to need is a global analysis
tool that insures that all names used are defined.  Like "pylint".

					John Nagle


From joax.spec at gmail.com  Wed May 12 17:21:22 2010
From: joax.spec at gmail.com (Joax Spec)
Date: Wed, 12 May 2010 16:21:22 -0500
Subject: fails to call python from jython for types, functools, csv modules
Message-ID: 

Hello I'm very new to python/jython, and trying yo *call a program from
jython*, which works very good in python.
I got some issues which resolve as I expose here, but I think these are
unsatisfactory solutions.
If you want to reply please do it to my address.

thanks,
Jx

PD. both are great projects!!!

1. FIRST Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 1, in 
  File "C:\Python26\lib\re.py", line 283, in 
    import copy_reg
  File "C:\Python26\lib\copy_reg.py", line 7, in 
    from types import ClassType as _ClassType
  File "C:\Python26\lib\types.py", line 36, in 
    BufferType = buffer
NameError: name 'buffer' is not defined

*Solution --> comment in types.py   #BufferType = buffer (line 37)*

2. SECOND Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 3, in 
  File "C:\Python26\lib\csv.py", line 7, in 
    from functools import reduce
  File "C:\Python26\lib\functools.py", line 10, in 
    from _functools import partial, reduce
ImportError: cannot import name reduce

*Solution --> comment in functools.py   #, reduce (line 10)
Problem --> IDLE for windows doesn't work anymore, I mean I can lauch the
GUI, but I can still use python from command line*

3. THIRD Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 3, in 
  File "C:\Python26\lib\csv.py", line 7, in 
    from functools import reduce
ImportError: cannot import name reduce

*Solution --> comment in csv.py  #@fieldnames.setter (line 96)*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From zapwireDASHgroups at yahoo.com  Wed May 12 18:03:36 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 15:03:36 -0700
Subject: Do any debuggers support "edit and continue?"
References: 
	
	
	<75c050d2-365e-4b08-8716-884ed5473572@k25g2000prh.googlegroups.com>
	<7lEGn.122365$iG7.15555@en-nntp-12.dc1.easynews.com>
	
Message-ID: 

"Phlip"  wrote in message 
news:c014ae9f-99d8-4857-a3f7-e6ac16e45250 at e34g2000pra.googlegroups.com...
>Are you implying, after an edit, you need to start a program again,
>then enter several user inputs, to navigate back to the place where
>you hit the syntax error? (WxWidgets noted - props!)

Pretty much, yeah... Realistically, we're probably talking less than a minute 
each time, so objectively it's not really a big deal -- it's just different 
than what I'm used to so I'm noticing it more. :-)

I guess what I'm realizing here is that one of the upsides of compiled 
languages is that they'll (usually) catch most typos before your program even 
runs!



From zapwireDASHgroups at yahoo.com  Wed May 12 18:07:37 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 15:07:37 -0700
Subject: Do any debuggers support "edit and continue?"
References: 
	<4beb15c5$0$1634$742ec2ed@news.sonic.net>
Message-ID: 

"John Nagle"  wrote in message 
news:4beb15c5$0$1634$742ec2ed at news.sonic.net...
>    Having actually used LISP systems with "edit and continue", it's a good
> thing that Python doesn't have it.  It encourages a "patch" mentality, and
> the resulting code is usually disappointing.

Hey, a lot of people would argue that Python's lack of strong typing and 
data/member protection (from one class to another) encourages sloppy 
programming too. :-)  (Some people even figure that automatic garbage 
collection does so!)

>    What the original poster seems to need is a global analysis
> tool that insures that all names used are defined.  Like "pylint".

Sounds intriguing... I'll check it out; thanks!

---Joel



From phlip2005 at gmail.com  Wed May 12 18:13:50 2010
From: phlip2005 at gmail.com (Phlip)
Date: Wed, 12 May 2010 15:13:50 -0700 (PDT)
Subject: Do any debuggers support "edit and continue?"
References:  
	 
	
	<75c050d2-365e-4b08-8716-884ed5473572@k25g2000prh.googlegroups.com>
	<7lEGn.122365$iG7.15555@en-nntp-12.dc1.easynews.com>
	
	
Message-ID: 

On May 12, 3:03?pm, "Joel Koltner" 
wrote:

> Pretty much, yeah... Realistically, we're probably talking less than a minute
> each time, so objectively it's not really a big deal -- it's just different
> than what I'm used to so I'm noticing it more. :-)
>
> I guess what I'm realizing here is that one of the upsides of compiled
> languages is that they'll (usually) catch most typos before your program even
> runs!

When you write developer tests ("unit tests"), you edit the code for a
while, hit a test button, and get instant feedback - syntax errors,
assertion failures, or a green bar. Then you edit a little more. This
allows you to learn to make the smallest possible edits that
constantly return you to a testworthy state.

Each test case does everything you did, manually. It sets up various
inputs and runs them thru a system. Better, it sets up inputs for each
specific method, not just for the whole app. That helps decouple the
specific methods, so they don't accidentally depend on everything.


From pmaupin at gmail.com  Wed May 12 18:26:23 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 15:26:23 -0700 (PDT)
Subject: Limitation of os.walk
References: 
	 
	
Message-ID: <970bdae6-2436-4e3a-95b2-6bdaf67a3218@d27g2000yqc.googlegroups.com>

On May 12, 2:04?pm, kj  wrote:
> It seems that a similar "simplicity argument" was invoked
> to strip the cmp option from sort in Python 3. ?Grrrr. ?Simplicity
> is great, but when the drive for it starts causing useful functionality
> to be thrown out, then it is going too far. ?Yes, I know that it
> is possible to do everything that sort's cmp option does through
> clever tricks with key, but grokking and coding this maneuver
> requires a *lot* more Python-fu than cmp did, which makes this
> functionality a lot less accessible to beginners that the intrinsic
> complexity of the problem warrants. ?And for what? ?To get rid of
> an *option* that could be easily disregarded by anyone who found
> it too "complex"? It makes no sense to me.

I didn't follow the discussion on cmp and Python 3, but I would assume
one reason it was removed was for performance.  cmp is very slow
compared to key, and if there should be one obvious way to do it, it
should probably be the way that runs faster.  Also, while in many
cases cmp can be easier to use than key, it would be possible for a
naive person with a complicated data structure to come up with a cmp
function that, e.g. sorted A > B, B > C, and C > A.  It's impossible
to come up with a key function that will break sort in that fashion.
So, while I understand the frustration of having a favorite tool
removed, I have no trouble believing that there were good reasons for
the removal.

Regards,
Pat


From paul at boddie.org.uk  Wed May 12 18:41:42 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 15:41:42 -0700 (PDT)
Subject: Picking a license
References: 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com>
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com> 
	<0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com> 
	<356d235e-63e3-4d36-bb7e-e436d9279f27@l28g2000yqd.googlegroups.com>
Message-ID: <845fc53a-5940-44fc-9189-a5a8ff56a95d@n15g2000yqf.googlegroups.com>

On 12 Mai, 21:02, Patrick Maupin  wrote:
> On May 12, 1:00?pm, Paul Boddie  wrote:

[Quoting himself...]

> > "Not least because people are only obliged to make their work
> > available under a GPL-compatible licence so that people who are using
> > the combined work may redistribute it under
> > the GPL."
>
> > In case you don't find this satisfactory, "their work" means "their
> > own work".
>
> OK, but in the last several threads on this sub-part, you kept
> contradicting me for some supposed technicality (how was I to know
> there were two RMS's?) when I was trying to make the same point.

We both agree that any combining a work with a GPL-licensed work means
that the result has to be distributable under the GPL. I was also
merely pointing out that the non-GPL-licensed work has to be licensed
compatibly if the possibility of combination with GPL-licensed works
exists, but you still get to choose the licence. You even acknowledged
this:

"In practice, what it really means is that the combination (e.g. the
whole program) would effectively be GPL-licensed.  This then means
that downstream users would have to double-check that they are not
combining the whole work with licenses which are GPL-incompatible,
even if they are not using the svg feature."

And for the last time, Stallman's opinion on what you should or should
not do is a distinct matter from the actual use of these licences.

[Haible and readline]

> He wasn't distributing it! ?It didn't incur any legal consequences;
> only the consequence due to not realizing that using readline placed
> him squarely inside RMS's chess game.

Really, what Stallman did in 1992 is a matter for Stallman to defend.
Whether a bunch of people use the GPL to license their work or not is
a separate matter. All I can say is that Stallman's reasoning was
probably driven by the possibility that someone could license their
work in a fashion that is incompatible with readline, but deliberately
be able to make use of it technically, and then when a user combines
that work and readline, the user is told that although readline is
used in that combined work, the licensing terms do not now apply.

[...]

> No. ?That's what you get when you use a copyrighted work authored by
> an idealist who is trying to spread his choice of license.

Well, take it up with Stallman, then. It's a separate issue from the
use of the FSF's licences and even how the FSF functions today.

[...]

> Yes, I understand it's no big deal to you. ?However, what you have
> said is not quite right. ?If I license something under the MIT
> license, I cannot guarantee that no one will ever get it under the
> GPL, because it could be redistributed downstream under the GPL (but
> then I don't care to in any case). ?However, I *can* guarantee that
> the code I write (and all the underlying code it relies on) will
> remain freely available from me for people who need the ability to,
> for example, link with proprietary code.

Yes, and as I said, in the context of a program landing in a user's
lap, there is no guarantee that such a program will offer users any
privileges other than to run the program, and then maybe only under
certain conditions. Which is how this discussion began.

> Despite this not being a very big deal to you, the whole tempest in a
> teacup here is about this very issue. ?Yes, I understand it is a
> problem for me, or any other author who wants to provide code that can
> be used freely by people who download it. ?And, as has been pointed
> out in this discussion, many people don't read licenses very
> carefully, so someone who doesn't want to restrict other people from
> linking his library with third party proprietary code should think
> twice about using the GPL.

Sure, the permissive licences declare fewer restrictions or
obligations on immediate recipients, but what kicked this discussion
off was the remark about end-user privileges, not what certain
recipients (but not others) are able to do with the code.

[...]

> > No, what I am saying is that a fair amount of work might have gone
> > into making readline, even though it may not be shiny enough by some
> > people's standards, but that doesn't mean you can disregard the
> > authors' wishes by insisting that is it "trivial" or unimportant,
> > whereas your own software somehow is important. As soon as you go down
> > that road, everyone can start belittling the works of others purely so
> > that they can start disregarding the terms which regulate those works,
> > and then it's a free-for-all.
>
> Ahh, well done. ?You've sucked me into a meaningless side debate. ?If
> I'm not distributing readline, then legally the license distribution
> terms don't apply to me. ?End of story. ?(Morally, now we might get
> into how trivial it is or isn't.)

According to the FSF, whose opinions you don't trust, it doesn't
matter if you do distribute readline or not:

http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL
http://www.gnu.org/licenses/gpl-faq.html#IfLibraryIsGPL

>From version 3 of the GPL:

"For example, Corresponding Source includes interface definition files
associated with source files for the work, and the source code for
shared libraries and dynamically linked subprograms that the work is
specifically designed to require, such as by intimate data
communication or control flow between those subprograms and other
parts of the work."

You may beg to differ. I would advise against doing so in a courtroom.

[...]

> But you don't need to know anything else. ?RMS claimed clisp was a
> derivative work of readline, even though readline wasn't even
> distributed with clisp. ?That's just plain copyright misuse, and if it
> had gone to court with good lawyers, RMS might have lost the copyright
> protections for readline.

Now that *is* a ridiculous statement. Just because a decision is made
that one work is not derived from another does not mean that the
claimed original work is no longer subject to copyright.

Paul


From mensanator at aol.com  Wed May 12 18:56:45 2010
From: mensanator at aol.com (Mensanator)
Date: Wed, 12 May 2010 15:56:45 -0700 (PDT)
Subject: How to test whether bit is set within a flag with Python ?
References:  
	
Message-ID: 

On May 12, 1:40?pm, MRAB  wrote:
> robert somerville wrote:
> > I am trying to determine how to test whether variors bits are set within
> > a byte (or larger flag) , the python 'and' and 'or' do not seem to be
> > doing what i want .. does anybody have some sample code showing how to
> > do it ??
>
> > e.g. (in "C")
>
> > unsigned char a = 6;
>
> > is 3rd bit set ??
>
> > a & 4 =, ?true in this case ....
>
> 'and', 'or' and 'not' are Boolean.
>
> Python borrows its bitwise operators from C:
>
> ? ? ?& ? ? bitwise and
> ? ? ?| ? ? bitwise or
> ? ? ?^ ? ? bitwise xor
> ? ? ?~ ? ? bitwise not (ones' complement)
> ? ? ?<< ? ?shift left
> ? ? ?>> ? ?shift right
>
> You also need to remember that Python's integers are of (virtually)
> unlimited length.

The gmpy module has a wonderful set of functions tailored to the
bit twiddler:

FUNCTIONS
    bit_length(...)
        bit_length(x): returns length of string representing x in base
2

>>> gmpy.bit_length(275)
9

    digits(...)
        digits(x[,base]): returns Python string representing x in the
        given base (2 to 36, default 10 if omitted or 0); leading '-'
        present if x<0, but no leading '+' if x>=0. x must be an mpz,
        or else gets coerced into one.

>>> gmpy.digits(275,2)
'100010011'

    hamdist(...)
        hamdist(x,y): returns the Hamming distance (number of bit-
positions
        where the bits differ) between x and y.  x and y must be mpz,
or else
        get coerced to mpz.

>>> a = 275    # '100010011'
>>> b = 333    # '101001101'
               #    x xxxx
>>> gmpy.hamdist(a,b)
5

    lowbits(...)
        lowbits(x,n): returns the n lowest bits of x; n must be an
        ordinary Python int, >0; x must be an mpz, or else gets
        coerced to one.

>>> gmpy.digits(gmpy.lowbits(333,8),2)
'1001101' # (bit 7 was a 0)

    numdigits(...)
        numdigits(x[,base]): returns length of string representing x
in
        the given base (2 to 36, default 10 if omitted or 0); the
value
        returned may sometimes be 1 more than necessary; no provision
        for any 'sign' character, nor leading '0' or '0x' decoration,
        is made in the returned length.  x must be an mpz, or else
gets
        coerced into one.

>>> import collatz_functions
>>> c = collatz_functions.Type12MH(6,1)
>>> gmpy.numdigits(c,2)
177149

    popcount(...)
        popcount(x): returns the number of 1-bits set in x; note that
        this is 'infinite' if x<0, and in that case, -1 is returned.
        x must be an mpz, or else gets coerced to one.

>>> gmpy.popcount(3**33)
34
>>> gmpy.digits(3**33,2)
'10011101111111110111110100110010110101011101110000011'

    scan0(...)
        scan0(x, n=0): returns the bit-index of the first 0-bit of x
(that
        is at least n); n must be an ordinary Python int, >=0.  If no
more
        0-bits are in x at or above bit-index n (which can only happen
for
        x<0, notionally extended with infinite 1-bits), None is
returned.
        x must be an mpz, or else gets coerced to one.

>>> gmpy.scan0(3**33,4) # find first 0 bit starting at bit4
4
'10011101111111110111110100110010110101011101110000011'
                                                 x
    scan1(...)
        scan1(x, n=0): returns the bit-index of the first 1-bit of x
(that
        is at least n); n must be an ordinary Python int, >=0.  If no
more
        1-bits are in x at or above bit-index n (which can only happen
for
        x>=0, notionally extended with infinite 0-bits), None is
returned.
        x must be an mpz, or else gets coerced to one.

>>> gmpy.scan1(3**33,4) # find first 1 bit starting at bit4
7
'10011101111111110111110100110010110101011101110000011'
                                              x

    setbit(...)
        setbit(x,n,v=1): returns a copy of the value of x, with bit n
set
        to value v; n must be an ordinary Python int, >=0; v, 0 or !
=0;
        x must be an mpz, or else gets coerced to one.

>>> a = 2**24+1
>>> gmpy.digits(a,2)
'1000000000000000000000001'
>>> a = gmpy.setbit(a,12,1)
>>> gmpy.digits(a,2)
'1000000000001000000000001'


From zuo at chopin.edu.pl  Wed May 12 19:07:15 2010
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Thu, 13 May 2010 01:07:15 +0200
Subject: open(False) in python3
In-Reply-To: 
References: 
	
	
	
Message-ID: <20100512230714.GA8407@chopin.edu.pl>

Terry Reedy dixit (2010-05-12, 14:26):

> On 5/12/2010 1:26 PM, Giampaolo Rodol? wrote:
> >2010/5/12 Gabriel Genellina:
> >>open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
> >>builtin open() + os.fdopen() from 2.x all merged together. It does different
> >>things depending on the type and quantity of its arguments, and even returns
> >>objects of different types.
> 
> The change actually happened, according to 'What's new', in 2.6 when
> 'open' was made a synonym for the new io.open.

It did happened in 3.0, not in 2.6.

Regards,
*j


From paul at boddie.org.uk  Wed May 12 19:15:16 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 16:15:16 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
Message-ID: <26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>

On 12 Mai, 20:29, Patrick Maupin  wrote:
>
> But nobody's whining about the strings attached to the software. ?Just
> pointing out why they sometimes won't use a particular piece of
> software, and pointing out that some other people (e.g. random Ubuntu
> users) might not understand the full cost of the software, and that
> that is because the cost of the software has been deliberately
> obscured by using unqualified terms like all-caps "Free Software."

Right. The "full cost" of software that probably cost them nothing
monetarily and which comes with all the sources, some through a chain
of distribution and improvement which could have led to proprietary
software had the earliest stages in the chain involved permissive
licensing. And that they can't sell a binary-only Ubuntu derivative.

[...]

> Oh, no wonder I didn't understand what you were getting at with the
> analogy. ?I'm not whining about people licensing stuff under the GPL,
> just about its apologists pretending there are never any negative
> consequences from it.

So, the "negative consequences" are that people can't make proprietary
editions of some software. When that's a deliberate choice in the
design of a licence, there's no pretending that the consequences
aren't there, just that they aren't perceived by everyone to be
negative.

[Sharing alike]

> I somehow knew that is how you would read my posts, but no. ?It's
> people like you putting words in my month that is objectionable.

Well, you effectively said that you didn't like being asked to "share
alike", which is what the GPL achieves, so why should I not assume
that you generally object to other, more obviously labelled licences
like the CC-*-SA licences which make it clear what is expected of that
hapless recipient of a work who doesn't bother reading the licence?

[Obligations after joining a scheme]

> Sorry, that is absolutely no different than what I originally said
> when I was first defending Aahz's use of the word "force" to Ben
> Finney back on the 7th:
>
> "Perhaps you feel "forces" is too loaded of a word. ?There is no
> question, however, that a copyright license can require that if you do
> "X" with some code, you must also do "Y". ?There is also no question
> that the GPL uses this capability in copyright law to require anybody
> who distributes a derivative work to provide the source. ?Thus,
> "forced to contribute back any changes" is definitely what happens
> once the decision is made to distribute said changes in object form."
>
> Both your "make" and my "force" mean "to compel." ?We've come full
> circle. ?The English language makes no real distinction between
> "making everyone commit" and "forcing everyone [to] commit".

Yes, but you have to choose to do something ("X") to start with. Which
is actually what you wrote later in that exchange:

"Again, the force is applied once you choose to do a particular thing
with the software -- is is really that hard to understand that
concept?"

But you're virtually claiming that people stumble into a situation
where they have to do something they don't like or didn't anticipate,
when in fact they've actually entered into an agreement.

[...]

> My problem, exactly, is that bothering Mepis, yet not bothering Joe
> Blow when he gives a copy to his friend, is exactly the kind of
> selective enforcement of copyright rights that Microsoft is accused of
> when they turn a blind eye to piracy in third-world countries.

Nonsense. If anything, it's a matter of priorities, and completely
absurd to claim that the FSF and all the other copyright holders for
GPL-licensed software on Ubuntu installation media are all conspiring
together to "seed" the planet with "unlicensed wares" in order to reap
some kind of monetary reward afterwards, which is what Microsoft has
been accused of.

[...]

> Despite your opinion, there is nothing legally or morally wrong with
> me using GPL software (and not redistributing it) just because I

I never said there was. I said that if you don't like the licence,
don't incorporate works which use it into your own projects. But don't
say that it's not fair that people are releasing stuff under terms you
don't like, or say that they're being "pathetic" or petty or
ridiculous by doing so, or are imposing their agenda on you.

> happen to feel that (a) for my purposes, for most stuff I write, it
> happens to be the wrong license, (b) (especially historically) some of
> the practices used to insure proliferation of the GPL are ethically
> questionable, and (c) whenever these ethically questionable practices
> are discussed, quasi-religious apologists will take these questionable
> practices to the next level, by selective quoting and bad analogies
> and hinting at things without actually coming out and saying them, and
> all sorts of other debate tactics designed to confuse rather than
> enlighten.

More name-calling and finger-pointing. Great stuff, there. Anything
else?

Paul


From paul at boddie.org.uk  Wed May 12 19:32:47 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 16:32:47 -0700 (PDT)
Subject: Picking a license
References: 
Message-ID: 

On 11 Mai, 14:12, Ed Keith  wrote:
> --- On Mon, 5/10/10, Ben Finney  wrote:
>
> > So I object to muddying the issue by misrepresenting the source of that
> > force. Whatever force there is in copyright comes from law, not any free
> > software license.
>
> You are the one muddying the waters. It does not mater whether you break my
> kneecaps, or hire someone else to break my kneecaps, either way my kneecaps
> are broken.

Nice analogy. In fact, the "force" mentioned above is nothing more
than the thing which makes these licensing agreements binding. All the
talk about the GPL "forcing" people to do stuff, when the stuff is
actually one side of a bargain or the obligations of a party in an
agreement, is great theatre but nothing more.

> You can use any license you want, but the simple fact is that if there are
> fewer restrictions in the license then the user has more freedom in how he
> uses the licensed code.

Yes, the recipient of that code as issued by you has fewer
restrictions on their actions and thus more privileges. However,
recipients of the extended work may be denied any or nearly all of
these privileges.

> If there are more restrictions he/she has less freedom in how he/she uses
> the licensed code.

Yes, that recipient does not get to exercise certain privileges.
However, recipients of the extended work retain the same set of
privileges. As do recipients of the work upon subsequent
redistribution.

> We can debate which is better (whether a man should be free to sell
> himself into slavery) but to claim that putting more restrictions on
> someone give them more freedom is pure Orwellian double speak.

It may provide fewer privileges for initial recipients but may grant
those privileges more widely.

> Sophistry is the last resort of those who have run out of good
> arguments. The more you engage in it the weaker you make your position.

Then I challenge you to dispute the statements of my last three
paragraphs without introducing a specific notion of "freedom" in order
to make your case.

> This thread is generating more heat than light, and probably should be dropped.

On this I don't necessarily disagree.

Paul


From pmaupin at gmail.com  Wed May 12 19:36:57 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 16:36:57 -0700 (PDT)
Subject: Picking a license
References: 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com>
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com> 
	<0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com> 
	<356d235e-63e3-4d36-bb7e-e436d9279f27@l28g2000yqd.googlegroups.com> 
	<845fc53a-5940-44fc-9189-a5a8ff56a95d@n15g2000yqf.googlegroups.com>
Message-ID: <5c1c0cce-f9f9-469b-ba3b-3eb9280c2bc9@g21g2000yqk.googlegroups.com>

On May 12, 5:41?pm, Paul Boddie  wrote:
> > Ahh, well done. ?You've sucked me into a meaningless side debate. ?If
> > I'm not distributing readline, then legally the license distribution
> > terms don't apply to me. ?End of story. ?(Morally, now we might get
> > into how trivial it is or isn't.)
>
> According to the FSF, whose opinions you don't trust, it doesn't
> matter if you do distribute readline or not:
>
> http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPLhttp://www.gnu.org/licenses/gpl-faq.html#IfLibraryIsGPL
>
> From version 3 of the GPL:
>
> "For example, Corresponding Source includes interface definition files
> associated with source files for the work, and the source code for
> shared libraries and dynamically linked subprograms that the work is
> specifically designed to require, such as by intimate data
> communication or control flow between those subprograms and other
> parts of the work."
>
> You may beg to differ. I would advise against doing so in a courtroom.

Well, it's unlikely anybody will get a chance in a courtroom, because
nobody's going to bring suit.

>
> > But you don't need to know anything else. ?RMS claimed clisp was a
> > derivative work of readline, even though readline wasn't even
> > distributed with clisp. ?That's just plain copyright misuse, and if it
> > had gone to court with good lawyers, RMS might have lost the copyright
> > protections for readline.
>
> Now that *is* a ridiculous statement. Just because a decision is made
> that one work is not derived from another does not mean that the
> claimed original work is no longer subject to copyright.

Well, it won't come to court because the FSF is just going to posture
on this issue, but never really sue anybody (certainly not any open
source project), because they would lose both in court and in public
opinion.  But if they did decide to sue, a few prior cases like Sega v
Accolade and Galoob v Nintendo, as well as the court's use of the
abstraction, filtration and comparison tests to strip functionality
away from copyrightable subject matter, would probably be dispositive
in determining that a substantial program like clisp that didn't
include readline, but which could use readline, is not, in fact, a
derivative of readline.

Once the court reaches that conclusion, it would only be a tiny step
to find that the FSF's attempt to claim that clisp infringes the
readline copyright to be a misuse of that same readline copyright.
See, e.g. LaserComb v Reynolds, where the defendant (IMHO) acted much
more egregiously than anybody who is delivering free software like
clisp is acting, and nevertheless won on that issue.

Regards,
Pat


From pmaupin at gmail.com  Wed May 12 19:58:15 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 16:58:15 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
Message-ID: <1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>

On May 12, 6:15?pm, Paul Boddie  wrote:
> On 12 Mai, 20:29, Patrick Maupin  wrote:
>
>
>
> > But nobody's whining about the strings attached to the software. ?Just
> > pointing out why they sometimes won't use a particular piece of
> > software, and pointing out that some other people (e.g. random Ubuntu
> > users) might not understand the full cost of the software, and that
> > that is because the cost of the software has been deliberately
> > obscured by using unqualified terms like all-caps "Free Software."
>
> Right. The "full cost" of software that probably cost them nothing
> monetarily and which comes with all the sources, some through a chain
> of distribution and improvement which could have led to proprietary
> software had the earliest stages in the chain involved permissive
> licensing. And that they can't sell a binary-only Ubuntu derivative.

Who's talking about selling a binary-only version -- there is a good
chance they can't even give away a binary CD without violating
copyright.

> [...]
>
> > Oh, no wonder I didn't understand what you were getting at with the
> > analogy. ?I'm not whining about people licensing stuff under the GPL,
> > just about its apologists pretending there are never any negative
> > consequences from it.
>
> So, the "negative consequences" are that people can't make proprietary
> editions of some software. When that's a deliberate choice in the
> design of a licence, there's no pretending that the consequences
> aren't there, just that they aren't perceived by everyone to be
> negative.

I gave an example earlier of svglib and rst2pdf.  Negative
consequences.  Nothing proprietary involved.

> > I somehow knew that is how you would read my posts, but no. ?It's
> > people like you putting words in my month that is objectionable.
>
> Well, you effectively said that you didn't like being asked to "share
> alike", which is what the GPL achieves.

I give away lots of software.  Free to all comers.  Come and get some.

> so why should I not assume
> that you generally object to other, more obviously labelled licences
> like the CC-*-SA licences which make it clear what is expected of that
> hapless recipient of a work who doesn't bother reading the licence?

Your assumptions are so far away from reality that there is really no
good reason why you shouldn't assume that I'm a 10 foot tall purple
monster.

> > Sorry, that is absolutely no different than what I originally said
> > when I was first defending Aahz's use of the word "force" to Ben
> > Finney back on the 7th:
>
> > "Perhaps you feel "forces" is too loaded of a word. ?There is no
> > question, however, that a copyright license can require that if you do
> > "X" with some code, you must also do "Y". ?There is also no question
> > that the GPL uses this capability in copyright law to require anybody
> > who distributes a derivative work to provide the source. ?Thus,
> > "forced to contribute back any changes" is definitely what happens
> > once the decision is made to distribute said changes in object form."
>
> > Both your "make" and my "force" mean "to compel." ?We've come full
> > circle. ?The English language makes no real distinction between
> > "making everyone commit" and "forcing everyone [to] commit".
>
> Yes, but you have to choose to do something ("X") to start with. Which
> is actually what you wrote later in that exchange:
>
> "Again, the force is applied once you choose to do a particular thing
> with the software -- is is really that hard to understand that
> concept?"

I didn't just write that later.  I wrote it in my very first post,
which you just quoted a few lines up, apparently without even
bothering to read it closely.  I agree with that.  But you only
grudgingly agree with that, if at all, and when you do you make it
look like I'm the one trying desperately not to agree with it, because
in order to agree with it, you have to agree that, in the limited
context that I used the word "force", it is accurate, and you really
don't want to do that.

> But you're virtually claiming that people stumble into a situation
> where they have to do something they don't like or didn't anticipate,
> when in fact they've actually entered into an agreement.

Some people (end users of Ubuntu) do stumble into a situation.  Some
people see and decide not to enter into an agreement and attempt to
warn others that there may be consequences -- that if they enter into
the agreement they will be "forced" to live with those consequences.
This latter group of people always winds up arguing with those who
think the GPL is always good and none of the consequences are ever
negative, and forced is a loaded word.

> > My problem, exactly, is that bothering Mepis, yet not bothering Joe
> > Blow when he gives a copy to his friend, is exactly the kind of
> > selective enforcement of copyright rights that Microsoft is accused of
> > when they turn a blind eye to piracy in third-world countries.
>
> Nonsense. If anything, it's a matter of priorities, and completely
> absurd to claim that the FSF and all the other copyright holders for
> GPL-licensed software on Ubuntu installation media are all conspiring
> together to "seed" the planet with "unlicensed wares" in order to reap
> some kind of monetary reward afterwards, which is what Microsoft has
> been accused of.

So, the FSF, which so carefully provides the most legalese-ish license
on the planet, which was in development for god-knows-how-long, which
maintains a carefully parsed FAQ of what you can and can't do, which
engages in all sorts of advocacy, can't find the time to explain to
Ubuntu that they really ought to explain how the licensing works on
their download page?  What have you been smoking and where can I get
some?

> > Despite your opinion, there is nothing legally or morally wrong with
> > me using GPL software (and not redistributing it) just because I
>
> I never said there was. I said that if you don't like the licence,
> don't incorporate works which use it into your own projects.

No, you said "If you don't like them, don't use GPL-licensed
software."

> But don't
> say that it's not fair that people are releasing stuff under terms you
> don't like, or say that they're being "pathetic" or petty or
> ridiculous by doing so, or are imposing their agenda on you.

The only time I mentioned pathetic and petty were for really small
libraries, which probably wouldn't merit copyright protection in any
case.

>
> More name-calling and finger-pointing. Great stuff, there. Anything
> else?

Yes, just that you keep selectively quoting both of us, and twisting
what we both said to meet your agenda.  But I'm done.  I think there
are enough pointers to original material here for others to go and do
whatever level of research they deem appropriate for their own
situations.

Regards,
Pat


From ldo at geek-central.gen.new_zealand  Wed May 12 20:29:08 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Thu, 13 May 2010 12:29:08 +1200
Subject: Is Python a functional programming language?
References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com>
	
	
	
Message-ID: 

In message , Nobody wrote:

> On Tue, 11 May 2010 23:13:10 +1200, Lawrence D'Oliveiro wrote:
> 
>>> But the beauty is that Python is multi-paradigm ...
>> 
>> The trouble with ?multi-paradigm? is that it offends the zealots on
>> all sides.
> 
> Is that how you view people who like languages to exhibit a degree of
> consistency?

Interesting, I never knew ?consistency? was a synonym for ?faith?...

> Some people would prefer to have a manageable set of rules
> rather than having to remember the results of all of the possible
> combinations of interactions between language features.

What are you accusing Python of, exactly?


From alan.isaac at gmail.com  Wed May 12 21:51:23 2010
From: alan.isaac at gmail.com (Alan G Isaac)
Date: Wed, 12 May 2010 21:51:23 -0400
Subject: documentation bug? (format spec mini language)
In-Reply-To: 
References: 	<4BE9ADD9.9030901@mrabarnett.plus.com>
	
Message-ID: <1Yidnfk7UJi8xnbWnZ2dnUVZ_h6dnZ2d@rcn.net>

On 5/11/2010 5:05 PM, Terry Reedy wrote:  
> http://bugs.python.org/issue8691

Thanks!

Alan




From Jess-198700987 at hotmail.com  Wed May 12 22:23:34 2010
From: Jess-198700987 at hotmail.com (Jess)
Date: Thu, 13 May 2010 10:23:34 +0800
Subject: How to test whether bit is set within a flag with Python ?
References: 
	
Message-ID: 

Cheap Chanel Watches for sale at: http://www.luxuryowner.net/

Chanel Watches collection: 
http://www.luxuryowner.net/replica-chanel-watches.html

Chanel J12 Automatic Watches: 
http://www.luxuryowner.net/Chanel-J12-Automatic-Watches.html

Chanel J12 Quartz Watches: 
http://www.luxuryowner.net/Chanel-J12-Quartz-Watches.html


"MRAB"  
??????:mailman.117.1273689672.32709.python-list at python.org...
> robert somerville wrote:
>> I am trying to determine how to test whether variors bits are set within 
>> a byte (or larger flag) , the python 'and' and 'or' do not seem to be 
>> doing what i want .. does anybody have some sample code showing how to do 
>> it ??
>>
>> e.g. (in "C")
>>
>> unsigned char a = 6;
>>
>> is 3rd bit set ??
>>
>> a & 4 =,  true in this case ....
>>
> 'and', 'or' and 'not' are Boolean.
>
> Python borrows its bitwise operators from C:
>
>     &     bitwise and
>     |     bitwise or
>     ^     bitwise xor
>     ~     bitwise not (ones' complement)
>     <<    shift left
>     >>    shift right
>
> You also need to remember that Python's integers are of (virtually)
> unlimited length. 




From Jess-198700987 at hotmail.com  Wed May 12 22:24:12 2010
From: Jess-198700987 at hotmail.com (Jess)
Date: Thu, 13 May 2010 10:24:12 +0800
Subject: Do any debuggers support "edit and continue?"
References: 
Message-ID: 

Cheap Chanel Watches for sale at: http://www.luxuryowner.net/

Chanel Watches collection: 
http://www.luxuryowner.net/replica-chanel-watches.html

Chanel J12 Automatic Watches: 
http://www.luxuryowner.net/Chanel-J12-Automatic-Watches.html

Chanel J12 Quartz Watches: 
http://www.luxuryowner.net/Chanel-J12-Quartz-Watches.html


"Joel Koltner"  
??????:cMBGn.281180$Up1.207371 at en-nntp-09.dc1.easynews.com...
> Just curious... in Microsoft's Visual Studio (and I would presume some 
> other tools), for many languages (both interpreted and compiled!) there's 
> an "edit and conitnue" option that, when you hit a breakpoint, allows you 
> to modify a line of code before it's actually executed.
>
> Does any Python debugger support this feature?  Being an interpreted 
> language it doesn't seem like it would necessarily be too onerous to 
> support?  It'd be quite handy in that, especially if you hit a breakpoint 
> due to the interpreter throwing an error, you could fix just the line in 
> question and keep going, rather than having to stop the entire program, 
> fix the line, and then run again and potentially kill a bunch of time 
> getting the program back into the same "state."
>
> Thanks,
> ---Joel Koltner
> 




From googler.1.webmaster at spamgourmet.com  Wed May 12 22:33:42 2010
From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3)
Date: Wed, 12 May 2010 19:33:42 -0700 (PDT)
Subject: buffer objects (C-API)
Message-ID: 

Hi at all,

is it possible that a buffer object deallocates the memory when the
object is destroyed? I want to wrap the buffer object around some
memory. Or is there any chance that the buffer object copies the
memory so it will be responsible when it will be destroyed?

Thanks in advance, bye.

moerchendiser2k3


From tjreedy at udel.edu  Wed May 12 23:04:41 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Wed, 12 May 2010 23:04:41 -0400
Subject: open(False) in python3
In-Reply-To: <20100512230714.GA8407@chopin.edu.pl>
References: 			
	<20100512230714.GA8407@chopin.edu.pl>
Message-ID: 

On 5/12/2010 7:07 PM, Jan Kaliszewski wrote:
> Terry Reedy dixit (2010-05-12, 14:26):
>
>> On 5/12/2010 1:26 PM, Giampaolo Rodol? wrote:
>>> 2010/5/12 Gabriel Genellina:
>>>> open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
>>>> builtin open() + os.fdopen() from 2.x all merged together. It does different
>>>> things depending on the type and quantity of its arguments, and even returns
>>>> objects of different types.
>>
>> The change actually happened, according to 'What's new', in 2.6 when
>> 'open' was made a synonym for the new io.open.
>
> It did happened in 3.0, not in 2.6.

I do not have 2.6 loaded to test and was judging from

What's New in Python 3.0 has a section

Changes Already Present In Python 2.6 which has an entry

"PEP 3116: New I/O Library. The io module is now the standard way of 
doing file I/O, and the initial values of sys.stdin, sys.stdout and 
sys.stderr are now instances of io.TextIOBase. The builtin open() 
function is now an alias for io.open() "

The 2.6.5 doc says
"io.open(file[, mode[, buffering[, encoding[, errors[, newline[, 
closefd=True]]]]]])?

     Open file and return a stream. If the file cannot be opened, an 
IOError is raised.

     file is either a string giving the name (and the path if the file 
isn?t in the current working directory) of the file to be opened or a 
file descriptor of the file to be opened. "

If you are right, then "The builtin open() function is now an alias for 
io.open() " is misleading and does not apply to 2.6 even though it 
appears in an entry on things backported to 2.6. I do not really care.

tjr









From pavlovevidence at gmail.com  Wed May 12 23:26:59 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Wed, 12 May 2010 20:26:59 -0700 (PDT)
Subject: buffer objects (C-API)
References: 
Message-ID: <5eebecfb-b76f-4101-b9de-02574f49f3fc@r11g2000yqa.googlegroups.com>

On May 12, 7:33?pm, moerchendiser2k3  wrote:
> Hi at all,
>
> is it possible that a buffer object deallocates the memory when the
> object is destroyed? I want to wrap the buffer object around some
> memory. Or is there any chance that the buffer object copies the
> memory so it will be responsible when it will be destroyed?


Objects that support the buffer protocol will only deallocate their
memory if they're programmed to.

If you're writing your own buffer type you can be assured the memory
won't be deallocated unless you do it yourself.

If you're referring to the Python 2.x "buffer" object, no it won't
deallocate the memory.  You should also be aware that it's deprecated
in 2.x and removed in 3.x.

Generally speaking, objects that allocate their own memory should also
deallocate it; objects that are passed pointers to existing memory
should leave it alone.  Most built-in types in Python that support
buffer protocol do allocate their own memory, so they also deallocate
it.  "buffer" doesn't, so it doesn't.

One other thing to consider is numpy, especially if your buffer is
numeric.  It might even have the operations you need already.
numpy.ndarray can allocate its own memory or accept a pointer (or
other buffer object), and will only delete the buffer if it allocated
it itself.


Carl Banks


From steven at REMOVE.THIS.cybersource.com.au  Wed May 12 23:29:00 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 13 May 2010 03:29:00 GMT
Subject: Limitation of os.walk
References: 
	
	
Message-ID: 

On Wed, 12 May 2010 19:04:47 +0000, kj wrote:

> In  Terry Reedy
>  writes:
> 
>>On 5/11/2010 3:49 PM, kj wrote:
>>> PS: I never understood why os.walk does not support hooks for key
>>> events during such a tree traversal.
> 
>>Either 1) it is intentionally simple, with the expectation that people
>>would write there own code for more complicated uses or 2) no one has
>>submitted a 'full-featured' version or 3) both.
> 
> I hope it's not (1): I want the language I use to include more
> "batteries" not fewer.

How many more? Ten? Twenty? A hundred? Ten thousand? Ten million? Where 
do you draw the line?

Every extra battery is (say) a hundred extra lines of code, which means 
fifty thousand more potential bugs. It means more burden on the 
maintainers, and more burden on people learning the language. More 
batteries can make it more, not less, difficult to code:

# Python 1.1
"I need a collection of values, should I use a list, a tuple or a dict?"

vs

# Python 5000:
"I need a collection of values, should I use a list, a tuple, a dict, an 
array, a bag, a SortedBag, a table, a SortedTable, a NamedTuple, a 
Record, a stack, a queue, a deque, a linked list, a HashTable, a doubly-
linked list, a set, a frozenset, a skip list, a jump list, a binary tree, 
a  B tree, a B+ tree, a SortedList, a red-black tree, an A* tree, a B* 
tree, a SortedList, a StringList, a CaseInsensitiveSortedStringList, a 
CaseInsensitiveRedBlackTree, a HashSet, a CaseInsensitiveHashSet, an 
ArrayList, a ConcurrentQueue, a ConcurrentStack, a KeyedCollection, an 
EnumerableBag, a MultiSet, a StringMultiSet, a SortedSet, a 
DoubleEndedQueue, a Buffer, a CircularQueue, a heap, a binary search 
tree, an AssociatedArray, a Vector, a SparseArray, an XOR-linked list, a 
weight-balanced tree, a RandomizedBinarySearchTree, a ThreadedBinaryTree, 
an AVL tree, a splay tree, a rope, a binomial heap, a fibonacci heap, a 
trie, a B-trie, a judy array, an and/or tree, an enfilade, a treap, a 
dancing tree, a queap, or a fusion tree?" (Whew!)


There's nothing wrong with the existence of all these data structures. If 
you need one, you can use it. But they don't all need to be included in 
the standard library. That just increases the cognitive load on 
programmers without really adding that much benefit. I've seen people 
stress over the choice of a tuple or a list.



> It seems that a similar "simplicity argument" was invoked to
> strip the cmp option from sort in Python 3.  Grrrr.  Simplicity is
> great, but when the drive for it starts causing useful functionality to
> be thrown out, then it is going too far.  Yes, I know that it is
> possible to do everything that sort's cmp option does through clever
> tricks with key, 

Not that clever. In general, key-based sorting is simpler than cmp-based 
sorting. In addition, the use of a key function is a basic technique 
which every coder should have in their mental toolbox, and it is 
applicable to more than just sorting. E.g. max() and min() also support 
key functions in Python 2.6 and better. On the other hand a cmp function 
is specific to sorting, and nothing but sorting.



> but grokking and coding this maneuver requires a *lot*
> more Python-fu than cmp did, which makes this functionality a lot less
> accessible to beginners that the intrinsic complexity of the problem
> warrants.

I disagree that key-based sorting requires any more Python-fu than cmp 
sorting. I believe they're equivalent. There are cmp functions you can 
write which aren't (easily?) convertible to key, but most of them (all?) 
aren't useful or sensible. E.g. they rely on side-effects, don't define a 
sensible sort order, or break stability of sorting:

>>> text = "here is a number of words in some order".split()
>>>
>>> sorted(text, cmp=lambda a,b: cmp(a.upper(), b.lower()))
['order', 'some', 'in', 'words', 'of', 'number', 'a', 'is', 'here']
>>>
>>> sorted(text[2:] + text[:2], cmp=lambda a,b: cmp(a.upper(), b.lower()))
['is', 'here', 'order', 'some', 'in', 'words', 'of', 'number', 'a']


Key-based sorting doesn't let you do this, but since I can't think of any 
application where you want the sort order to be dependent on the initial 
order, I believe this is a good thing. It is much harder to write buggy 
sorts using key than with cmp.



> And for what?  To get rid of an *option* that could be easily
> disregarded by anyone who found it too "complex"? It makes no sense to
> me.


It's not that cmp is too complex, but that it's mere existence adds 
complexity to the list data type, it is usually slow and inefficient, and 
it can introduce subtle sorting bugs.


In the past, I've suggested that if people really believe that there is a 
use-case for sorting with a comparison function, they should fork it from 
the built-in list object and release it on PyPI as a third-party package. 
I still believe this.



-- 
Steven


From tjreedy at udel.edu  Wed May 12 23:29:11 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Wed, 12 May 2010 23:29:11 -0400
Subject: Limitation of os.walk
In-Reply-To: 
References: 
		
	
Message-ID: 

On 5/12/2010 2:52 PM, kj wrote:
> In  Tim Chase writes:
>>   05/11/2010 09:07 PM, Terry Reedy wrote:
>>> If os.walk were rewritten, it should be as an iterator (generator).
>>> Directory entry and exit functions could still be added as params.
>
>> It *is* an iterator/generator.  However, I suspect you mean that
>> it should slurp the dirs/files iteratively instead of using
>> listdir() as was discussed on c.l.p a few months back.

Yes, I was thinking of that thread.
>
> Thanks for mentioning this thread.  Very interesting stuff.  Apropos
> the implementability of an iterative listdir, I wonder if some
> variation of glob.iglob() would fit the bill.  (Maybe it's too
> slow, though.)
>
>> I suspect if I thought about it much longer, only one would
>> really be needed, the other accommodated by the "topdown" parameter.
>
> Yeah, I think one only needs a post hook.  The fact that it's a
> generator obviates need for a pre hook, since the yield returns
> control to the calling function right around where the pre-hook
> would run anyway.  For the same reason, the post hook is needed
> only for the case topdown=True.

Once you have determined and tested the minimal needed change for 
greater functionality, you could either
a) post a suggestion and the revised os.walk to python-ideas
b) submit a feature request to the tracker and attach the revised 
function and, if possible, a diff patch
c) both.

I have no idea of the response.

Terry Jan Reedy



From ldo at geek-central.gen.new_zealand  Wed May 12 23:48:24 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Thu, 13 May 2010 15:48:24 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> ... but to claim that putting more restrictions on someone give them more
> freedom is pure Orwellian double speak.

What about the freedom to take away other people?s freedom? What tuple of 
speak would that be?


From timr at probo.com  Thu May 13 00:04:25 2010
From: timr at probo.com (Tim Roberts)
Date: Wed, 12 May 2010 21:04:25 -0700
Subject: win32com sql update problem
References: 
Message-ID: <18umu5dpt177lnr8t9hsfu3jd47mddnk9l@4ax.com>

Mark Carter  wrote:
>
>Consider the following snippet of code:
>
>import win32com.client
>
>DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=M:\\Finance\\camel\
>\camel.mdb;'
>conn.Open(DSN)
>cursor = conn.Execute("UPDATE tblInvoice SET InvComments='Python'
>WHERE InvBillingPeriod = 'April 2010' AND InvJobCode = '2169'")
>rows = cursor.Affected_Rows()
>print rows
>conn.Close()
>
>I am using Python 2.6.5, and pywin32. If I try to run it, I get the
>response:
>Traceback (most recent call last):
>  File "C:/Users/mcarter/tacc/pypms/post.py", line 79, in 
>    AdjustPms(d)
>  File "C:/Users/mcarter/tacc/pypms/post.py", line 64, in AdjustPms
>    cursor = conn.Execute("UPDATE tblInvoice SET InvComments='Python'
>WHERE InvBillingPeriod = 'April 2010' AND InvJobCode = '2169'")

Well, that's not the EXACT code, because that's clearly not line 64 in the
script above.  Do you actually have the file path hardcoded, as in your
example?  Or are you building it up from strings?

Does the net share exist at the time you run this?

You might print conn.ConnectionString just before the Execute.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.


From aahz at pythoncraft.com  Thu May 13 00:35:54 2010
From: aahz at pythoncraft.com (Aahz)
Date: 12 May 2010 21:35:54 -0700
Subject: Use of cmp() (was Re: Limitation of os.walk)
References: 
	
	
	
Message-ID: 

[nitpicking one specific point]

In article ,
Steven D'Aprano   wrote:
>
>On the other hand a cmp function is specific to sorting, and nothing
>but sorting.

Not quite.  cmp() is useful any time you have an expensive comparison
operation and you need to take three different codepaths depending on
the comparison result.  I don't know what the current code does, but I
used it in the first cut Decimal() class.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From pmaupin at gmail.com  Thu May 13 01:16:29 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 22:16:29 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: <155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>

On May 12, 10:48?pm, Lawrence D'Oliveiro  wrote:
> In message , Ed Keith
> wrote:
>
> > ... but to claim that putting more restrictions on someone give them more
> > freedom is pure Orwellian double speak.
>
> What about the freedom to take away other people?s freedom?

The freedom to take away other people's freedom is a very serious
power that should only be used sparingly.

> What tuple of speak would that be?

Well, if my friend has a slow internet connection, so I give him a
Linux CD which lets him get out of Windows hell (me taking advantage
of RMS's "freedom 2", and my friend taking advantage of RMS's "freedom
0"), and I don't give my friend all the source code (or a written
offer) because, frankly, he wouldn't know what to do with the source
anyway, and it doesn't fit on the CD, and I didn't even bother
downloading the source, at that point I would apparently be in
violation of the GPL license on hundreds of programs, because I would
be violating what the FSF calls "freedom 1".  Or more pedantically, I
would be in violation of section 6 of the GPL v3 license for those
programs on the CD licensed under v3, and in violation of section 3 of
the GPL v2 for those programs on the CD licensed under v2.  In the
case of GPL v3, for example, Ubuntu lets me download code under 6d, so
if I download it and burn it, I would have to use 6a or 6b; if I had
actually received a CD from Ubuntu, I might be able to use 6c, but not
if I downloaded it.

Now I know none of us would ever violate the license like this, but
if, hypothetically speaking, I had made such a CD for my friend, and
then someone came along and explained to me that, by helping wean my
friend from MS Windows in this fashion, I had taken away his freedom
(specifically RMS's "freedom 1"), I would probably conclude that the
person making this accusation was a moron, and that his words were so
meaningless that the only tuple that could possibly represent them was
the empty tuple.

Regards,
Pat


From joax.spec at gmail.com  Thu May 13 02:34:30 2010
From: joax.spec at gmail.com (Joax Spec)
Date: Thu, 13 May 2010 01:34:30 -0500
Subject: Fwd: fails to call python from jython for types, functools, csv 
	modules
In-Reply-To: 
References: 
Message-ID: 

Hello I'm very new to python/jython, and trying yo *call a program from
jython*, which works very good in python.
I got some issues which resolve as I expose here, but I think these are
unsatisfactory solutions.
If you want to reply please do it to my address.

thanks,
Jx

PD. both are great projects!!!

1. FIRST Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 1, in 
  File "C:\Python26\lib\re.py", line 283, in 
    import copy_reg
  File "C:\Python26\lib\copy_reg.py", line 7, in 
    from types import ClassType as _ClassType
  File "C:\Python26\lib\types.py", line 36, in 
    BufferType = buffer
NameError: name 'buffer' is not defined

*Solution --> comment in types.py   #BufferType = buffer (line 37)*

2. SECOND Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 3, in 
  File "C:\Python26\lib\csv.py", line 7, in 
    from functools import reduce
  File "C:\Python26\lib\functools.py", line 10, in 
    from _functools import partial, reduce
ImportError: cannot import name reduce

*Solution --> comment in functools.py   #, reduce (line 10)
Problem --> IDLE for windows doesn't work anymore, I mean I can lauch the
GUI, but I can still use python from command line*

3. THIRD Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 3, in 
  File "C:\Python26\lib\csv.py", line 7, in 
    from functools import reduce
ImportError: cannot import name reduce

*Solution --> comment in csv.py  #@fieldnames.setter (line 96)*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steven at REMOVE.THIS.cybersource.com.au  Thu May 13 03:58:34 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 13 May 2010 07:58:34 GMT
Subject: Picking a license
References: 
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
Message-ID: 

On Wed, 12 May 2010 22:16:29 -0700, Patrick Maupin wrote:

> On May 12, 10:48?pm, Lawrence D'Oliveiro  central.gen.new_zealand> wrote:
>> In message , Ed
>> Keith wrote:
>>
>> > ... but to claim that putting more restrictions on someone give them
>> > more freedom is pure Orwellian double speak.
>>
>> What about the freedom to take away other people?s freedom?
> 
> The freedom to take away other people's freedom is a very serious power
> that should only be used sparingly.
> 
>> What tuple of speak would that be?
> 
> Well, if my friend has a slow internet connection, so I give him a Linux
> CD which lets him get out of Windows hell (me taking advantage of RMS's
> "freedom 2", and my friend taking advantage of RMS's "freedom 0"), and I
> don't give my friend all the source code (or a written offer) because,
> frankly, he wouldn't know what to do with the source anyway, and it
> doesn't fit on the CD, and I didn't even bother downloading the source,
> at that point I would apparently be in violation of the GPL license on
> hundreds of programs, because I would be violating what the FSF calls
> "freedom 1". 

If you used an existing Linux distribution, then the offer to provide 
source code will already be there.

If you compiled the CD yourself, and failed to provide a written offer on 
the CD, then yes absolutely you would be in violation of the licence 
terms, and shame on you.

The GPL doesn't require you to force source code on those who don't want 
it, but it does require you to make it available if they ask, and for you 
to notify them appropriately of this fact. You don't even have to 
explicitly tell your friend he can have the source code. You just have to 
make sure that the written offer is available on the disk you give him.


> Now I know none of us would ever violate the license like this, but if,
> hypothetically speaking, I had made such a CD for my friend, and then
> someone came along and explained to me that, by helping wean my friend
> from MS Windows in this fashion, I had taken away his freedom
> (specifically RMS's "freedom 1"), I would probably conclude that the
> person making this accusation was a moron


Well, yes, you probably would draw that conclusion. Doesn't mean that you 
are right to do so, because quite frankly you would have taken away your 
friend's freedom (albeit in a very small fashion). Access to the source 
code is a freedom that the GPLed software on the disk *explicitly* grants 
to your friend, and by failing to pass the offer on, you have taken away 
that freedom in a very real sense.

We are talking about a small technical violation of the licence terms 
here, but imagine if everyone did it, if Red Hat and Debian and Ubuntu 
etc didn't bother passing on the source code (or a written offer). Only a 
tiny proportion of people would discover by their own efforts that the 
source code was available, and only a proportion of them would learn 
where it was available from. The result in practical terms would be a 
major decrease in the number of people granted the freedom to modify the 
source code, and a correspondingly larger decrease in the number of 
people both free and able to modify the source code.

It's not enough to be granted freedom to modify source code in theory, if 
you know about it, if you can find some hard-to-locate website which may 
or may not be running. The practicalities are equally important. In 
theoretical terms, everyone has the freedom to legally modify and 
distribute the source code to Microsoft Windows. All you have to do is 
buy 51% of the stock so as to become majority shareholder, then make 
sufficient changes to the board of directors so that the new board grants 
you a licence to do so, then fight off the lawsuits from the rest of the 
shareholders. Anyone could do it! Not.

Another, more practical example: here in Australia our government is hell-
bent on introducing an ineffective and expensive Internet censorship 
scheme. It seems that under Australian law, it will be completely legal 
to circumvent the filter, but our government is investigating ways to 
make it illegal to tell anyone how to circumvent it. In other words, 
Australians will have permission to circumvent the nanny filter, but 
since few people will know this, or know how to do so, it will be a 
meaningless freedom.

The GPL concerns itself with the *practical* freedom to gain access to 
source code, not merely the theoretical freedom represented by permission 
without opportunity. Failure to pass on the offer to provide source code 
impacts that freedom in a very real sense.

If you can't understand this, you have the freedom to think I'm a moron, 
and I have the freedom to be sure you are one too *wink*



-- 
Steven


From pavlovevidence at gmail.com  Thu May 13 04:10:09 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Thu, 13 May 2010 01:10:09 -0700 (PDT)
Subject: Queue.Queue() AttributeError exception
References: <201005101040516097598@ucweb.com>
	
Message-ID: 

On May 12, 11:50?pm, Dennis Lee Bieber  wrote:
> On Mon, 10 May 2010 10:40:51 +0800, "??????" 
> declaimed the following in gmane.comp.python.general:
>
> > I have a multi-thread program work with Queue.Queue(), sometimes put request to the work queue, but throw an exception as below traceback information, it will always throw the exception until restart program, cound please have any experience, your help will be greatly appreciated!
>
> > ? File "/usr/local/lib/python2.4/Queue.py", line 71, in put
> > ? ? self.not_full.acquire()
> > AttributeError: '_Condition' object has no attribute 'acquire'
>
> ? ? ? ? Off hand -- I'd wonder if somewhere in the code there may be a
> faulty/erroneous rebinding of the "not_full" attribute...

My impression too, that or _Condition.


Carl Banks


From motoom at xs4all.nl  Thu May 13 07:31:21 2010
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Thu, 13 May 2010 13:31:21 +0200
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 	<4beb15c5$0$1634$742ec2ed@news.sonic.net>
	
Message-ID: <4BEBE309.7090503@xs4all.nl>

On 2010-05-13 00:07, Joel Koltner wrote:

> Hey, a lot of people would argue that Python's lack of strong typing and
> data/member protection (from one class to another) encourages sloppy
> programming too.  :-)

You're being ironic, aren't you?

Python does have strong typing (many people confuse that with static 
typing), see http://www.artima.com/weblogs/viewpost.jsp?thread=7590

And for data member protection, there is the 'consenting adult' rule. 
Touch instance variables which start with an underscore on your own risk.

Greetings,

-- 
"Open-source projects are run by people who are self-selected to actually
care about the software, as opposed to resentful wage slaves for
whom control over their work product is minimal and development is
just another stretch of cubicle time." - ESR, http://esr.ibiblio.org


From ldo at geek-central.gen.new_zealand  Thu May 13 08:25:41 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:25:41 +1200
Subject: Picking a license
References: 
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
Message-ID: 

In message
<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5 at g21g2000yqk.googlegroups.com>, Patrick 
Maupin wrote:

> On May 12, 10:48 pm, Lawrence D'Oliveiro
>  wrote:
>
>> In message , Ed
>> Keith wrote:
>>
>> > ... but to claim that putting more restrictions on someone give them
>> > more freedom is pure Orwellian double speak.
>>
>> What about the freedom to take away other people?s freedom?
> 
> The freedom to take away other people's freedom is a very serious
> power that should only be used sparingly.

Given that the GPL restricts that power, then it must be all right.


From ldo at geek-central.gen.new_zealand  Thu May 13 08:30:50 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:30:50 +1200
Subject: PEP 3119 ABC - And how I learned to love the Abstract Bomb
References: 
Message-ID: 

In message , Hatem 
Nassrat wrote:

> 1. To create a YajlContentHandler class that forces all sub-classers
> to implement a certain set of methods. (Great, thats what ABC is for)
> 
> 2. Conditional Abstractness! if certain methods are not implemented
> then be able to require some method to be implemented.

You?re looking at it wrong. If you want to force people to do things in a 
certain way, use Java. Python is about enabling things, not forcing them.

Don?t use subclassing. Instead, let the caller pass you a duck-typed object 
that implements the methods you need.


From ldo at geek-central.gen.new_zealand  Thu May 13 08:35:01 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:35:01 +1200
Subject: Django as exemplary design
References: <2010050312243328275-tomfsessile@gmailcom>
	
	<2010050415342385304-tomfsessile@gmailcom>
	<746e8b47-bb35-47a1-9832-2babe0fec044@o8g2000yqo.googlegroups.com>
	<1273191529.196773.7.camel@paska>
	
Message-ID: 

In message , MRAB 
wrote:

> Albert Hopkins wrote:
>
>> On Thu, 2010-05-06 at 16:38 -0700, Patrick Maupin wrote:
>>
>>> I don't know how this applies to reading other peoples' code, but
>>> recent research shows we learn more from success than failure
>> 
>> That's good to learn, because for years I have been intentionally
>> failing in order to learn from it and become successful, and it hasn't
>> really worked out for me :|
>> 
> Failure just teaches you what you shouldn't do, not what you should...

But there are more different ways to fail than to succeed, therefore more to 
learn.


From ldo at geek-central.gen.new_zealand  Thu May 13 08:37:33 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:37:33 +1200
Subject: Django as exemplary design
References: <2010050312243328275-tomfsessile@gmailcom>
	
	<2010050619481239450-tomfsessile@gmailcom>
	
Message-ID: 

In message , Aahz wrote:

> My suspicion is that very very few medium/large systems are truly
> "well-designed".

Conway?s law applies: the product of any human endeavour reflects the 
organizational structure that produced it. If the individuals/groups writing 
the different parts of the software were in regular communication, and 
working towards a common goal rather than at odds with each other, that will 
be reflected in the way their contributions interact.


From ldo at geek-central.gen.new_zealand  Thu May 13 08:38:17 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:38:17 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> If, on the other hand you are releasing a library, to be incorporated into
> other products, If you release it under the GPL I will not take the time
> to learn it. I do not want to have to think about what took I can legally
> use for what job. Libraries with permissive licenses can be used in any
> project. Many contracts prohibit the use of GPL or LGPL code. So I do not
> waist my time learning to use libraries covered by restrictive licenses.
> So if you want me to even consider using your library do not use GPL, or
> LGPL.

What have you got against LGPL for this purpose?


From ldo at geek-central.gen.new_zealand  Thu May 13 08:41:19 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:41:19 +1200
Subject: Broken pipe
References: 
	
Message-ID: 

In message , Chris 
Rebert wrote:

> Also, please don't use semicolons in your code. It's bad style.

Wonder why they?re allowed, then.


From faltet at gmail.com  Thu May 13 08:48:38 2010
From: faltet at gmail.com (Francesc)
Date: Thu, 13 May 2010 05:48:38 -0700 (PDT)
Subject: Invoking setup.py in sub-packages
Message-ID: <6332d1a6-8f78-485b-a6cf-a9613d6be25d@b18g2000yqb.googlegroups.com>

Hi,

I'd like to setup a package that is make of other sub-packages,
modules and other extensions.  What I have is something like (this is
very simplified indeed):

/
    __init__.py
    setup.py
    foo1/
        __init__.py
        foo1.c
        [...]
    foo2/
        setup.py
        __init__.py
        foo2.c
        [...]

Now, I'd like to make a setup.py for package 'foo' that is able to
compile the 'foo1' extension directly, but invoke 'foo2/setup.py' in
order to generate the 'foo2' sub-package (which contains an extension
itself).

I'm currently trying:

setup(name = "foo",
      ...
      ext_modules = [ Extension( "foo.foo1", sources=["foo1.c"] ) ],
      packages = ["foo.foo1", "foo.foo2"],
      ...
      )

Of course, the foo2 package is not made at all.  Is there a way to get
the 'foo2/setup.py' invoked automagically and generate the desired
extensions?  Or all the instructions to generate the extension in
sub-packages have to be hard-wired in main 'foo/setup.py'?

Thanks!


From ldo at geek-central.gen.new_zealand  Thu May 13 08:50:44 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:50:44 +1200
Subject: Is there a better way to set a system clock in Python (on a Linux
	system)
References: 
Message-ID: 

In message , J wrote:

> Like I said, it works well, I just wonder if there is a cleaner way of
> setting the local clock to a different time in python without having
> to do all this.

How about one line in Bash:

    date -s $(date --rfc-3339=date -d "+1 hour")



From e_d_k at yahoo.com  Thu May 13 09:04:37 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 06:04:37 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <855698.98996.qm@web58704.mail.re1.yahoo.com>

--- On Wed, 5/12/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Wednesday, May 12, 2010, 11:48 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > ... but to claim that putting more restrictions on
> someone give them more
> > freedom is pure Orwellian double speak.
> 
> What about the freedom to take away other people?s
> freedom? What tuple of 
> speak would that be?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Assertion I:
   If person A is free to do more than person B, then person A has 
   more freedom then person B.

Assertion II:
   If person A is free do perform an action person B is not free to 
   perform then person A is free to do more than person B.

Assertion III:
  If person B is restricted in some way that person A is not them Person A 
  is free to do something Person B is not free to do.

Conclusion:
  If person B is more resticted than Peston A, Person A has mor freedom
  than person B.

Which step in this reasoning do you disagree with?

     -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From mrkafk at gmail.com  Thu May 13 09:14:09 2010
From: mrkafk at gmail.com (mk)
Date: Thu, 13 May 2010 15:14:09 +0200
Subject: Loading C extension from memory
Message-ID: 

Hello,

I wonder if there is a way to load C extension from in-memory object, 
not from the file on the disk?

I'm asking bc I would like to download C extensions over network and 
load them into Python interpreter (without storing the C extension in 
file on the disk).

I googled for this but there appear only methods of loading compiled 
Python (bytecode) modules.

Regards,
mk



From e_d_k at yahoo.com  Thu May 13 09:21:10 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 06:21:10 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <479178.94015.qm@web58705.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 8:25 AM
> In message
> <155f1683-9bfd-4a83-b63f-7fb0fc2f51c5 at g21g2000yqk.googlegroups.com>,
> Patrick 
> Maupin wrote:
> 
> > On May 12, 10:48 pm, Lawrence D'Oliveiro
> > 
> wrote:
> >
> >> In message ,
> Ed
> >> Keith wrote:
> >>
> >> > ... but to claim that putting more
> restrictions on someone give them
> >> > more freedom is pure Orwellian double speak.
> >>
> >> What about the freedom to take away other
> people?s freedom?
> > 
> > The freedom to take away other people's freedom is a
> very serious
> > power that should only be used sparingly.
> 
> Given that the GPL restricts that power, then it must be
> all right.
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

I do not think anyone is claiming it is not 'all right'. The claim is being made that it restricts freedom.

You are free to put any restrictions you want on your software. If you use the GPL on a library I will not use it because I need to make a living. I do not dispute your right to use the GPL. I just dispute your claim that you use it to give me 'more freedom'.

I do not know what your reason for using the GPL is, but most of the people I know who use it do so so that can charge a license fee to people who want to use the code with out the restrictions of the GPL. They do this so they can make a living, which is their right, and I do not hold it against them. If I ever develop a library I think people would be willing to pay to license, I'd to the same.

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Thu May 13 09:24:04 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 06:24:04 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <495778.64465.qm@web58702.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 8:38 AM
> In message ,
> Ed Keith 
> wrote:
> 
> > If, on the other hand you are releasing a library, to
> be incorporated into
> > other products, If you release it under the GPL I will
> not take the time
> > to learn it. I do not want to have to think about what
> took I can legally
> > use for what job. Libraries with permissive licenses
> can be used in any
> > project. Many contracts prohibit the use of GPL or
> LGPL code. So I do not
> > waist my time learning to use libraries covered by
> restrictive licenses.
> > So if you want me to even consider using your library
> do not use GPL, or
> > LGPL.
> 
> What have you got against LGPL for this purpose?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Most of my clients would not know how to relink a program if their life depended on it. And I do not want to put then in DLL hell. So I avoid the LGPL.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From jerome.delachienne at googlemail.com  Thu May 13 10:19:39 2010
From: jerome.delachienne at googlemail.com (jerome delachienne)
Date: Thu, 13 May 2010 07:19:39 -0700 (PDT)
Subject: jython and emacs on windows
Message-ID: <8b9b6ef9-4f7e-49a5-aaff-8d1edb181ba3@r11g2000yqa.googlegroups.com>

Hello,

i am trying to start a jython interpreter from emacs on windows from
several days and did not managed to do it.
I managed to start the jython interpreter from emacs on linux
I managed to start the python interpreter from emacs on windows.
with jython on windows i have the following problem: i can execute a
python script with the option -m but i can not interact with the
interpreter.
When i start from an eshell jython without the -i  option, nothing
happens as expected (like python)
When I start from an eshell the jython interpreter with -i option,  I
receive the "welcome" information and the prompt:
c:/Users/jerome $ jython -i
Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.6.0_20
Type "help", "copyright", "credits" or "license" for more information.
>>>
but then the interpreter does not react to any inputs
on the process explorer i can see that emacs has started a child
process cmd /c c:\jython2.5.1\jython.bat -i. this child process
started itself the jython interpreter which runs.but it seems that the
inputs are not passed from emacs to the jython interpreter.

has anyone an idea how i could solve this problem? Thanks for your
help !

jython 2.5.1
Jdk 1.6.0_20
emacs 22.3 and 21.3
windows xp and 7


From oxfordenergyservices at googlemail.com  Thu May 13 10:36:58 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 07:36:58 -0700 (PDT)
Subject: indexing lists/arrays question
Message-ID: 

this must be easy but its taken me a couple of hours already

i have

a=[2,3,3,4,5,6]

i want to know the indices where a==3 (ie 1 and 2)

then i want to reference these in a

ie what i would do in IDL is

b=where(a eq 3)
a1=a(b)

any ideas?

Thanks



From stefan_ml at behnel.de  Thu May 13 10:47:27 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Thu, 13 May 2010 16:47:27 +0200
Subject: indexing lists/arrays question
In-Reply-To: 
References: 
Message-ID: 

a, 13.05.2010 16:36:
> this must be easy but its taken me a couple of hours already
>
> i have
>
> a=[2,3,3,4,5,6]
>
> i want to know the indices where a==3 (ie 1 and 2)

   indices = [ i for i,item in enumerate(a) if item == 3 ]


> then i want to reference these in a

   print [ a[i] for i in indices ]

Stefan



From paul at boddie.org.uk  Thu May 13 10:53:10 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Thu, 13 May 2010 07:53:10 -0700 (PDT)
Subject: Picking a license
References: 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com>
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com> 
	<0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com> 
	<356d235e-63e3-4d36-bb7e-e436d9279f27@l28g2000yqd.googlegroups.com> 
	<845fc53a-5940-44fc-9189-a5a8ff56a95d@n15g2000yqf.googlegroups.com> 
	<5c1c0cce-f9f9-469b-ba3b-3eb9280c2bc9@g21g2000yqk.googlegroups.com>
Message-ID: <4f1c4723-a1c9-4b3d-aee3-d6475733066d@a34g2000yqn.googlegroups.com>

On 13 Mai, 01:36, Patrick Maupin  wrote:
>
> Once the court reaches that conclusion, it would only be a tiny step
> to find that the FSF's attempt to claim that clisp infringes the
> readline copyright to be a misuse of that same readline copyright.
> See, e.g. LaserComb v Reynolds, where the defendant (IMHO) acted much
> more egregiously than anybody who is delivering free software like
> clisp is acting, and nevertheless won on that issue.

In that very case you mention, LaserComb did not lose the copyright
protection on their work, were "free to bring an infringement suit
once it had cured the misuse" [1], and the clause which led to a
defence based on "copyright misuse" was one which forbade licensees
from making competing products.

Paul

[1] http://itlaw.wikia.com/wiki/Lasercomb_America_v._Reynolds#cite_ref-2


From matt at tplus1.com  Thu May 13 11:01:08 2010
From: matt at tplus1.com (Matthew Wilson)
Date: Thu, 13 May 2010 15:01:08 +0000 (UTC)
Subject: indexing lists/arrays question
References: 
Message-ID: 

On Thu 13 May 2010 10:36:58 AM EDT, a wrote:
> this must be easy but its taken me a couple of hours already
>
> i have
>
> a=[2,3,3,4,5,6]
>
> i want to know the indices where a==3 (ie 1 and 2)
>
> then i want to reference these in a
>
> ie what i would do in IDL is
>
> b=where(a eq 3)
> a1=a(b)


There's several solutions.  Here's one:

It is a recipe for madness to use a list of integers and then talk
about the position of those integers, so I renamed your list to use
strings.

    >>> a = ['two', 'three', 'three', 'four','five', 'six']

Now I'll use the enumerate function to iterate through each element and
get its position::

    >>> for position, element in enumerate(a):
    ...     print position, element
    ...
    0 two
    1 three
    2 three
    3 four
    4 five
    5 six

And now filter:

    >>> for position, element in enumerate(a):
    ...    if element == 'three':
    ...        print position, element

    1 three
    2 three

And now do something different besides printing:

    >>> b = []
    >>> for position, element in enumerate(a):
    ...     if element == 'three':
    ...         b.append(position)

And now we can rewrite the whole thing from scratch to use a list
comprehension:

    >>> [position for (position, element) in enumerate(a) if element == 'three']
    [1, 2]

HTH

Matt



From neilc at norwich.edu  Thu May 13 11:05:46 2010
From: neilc at norwich.edu (Neil Cerutti)
Date: 13 May 2010 15:05:46 GMT
Subject: indexing lists/arrays question
References: 
Message-ID: <852iqaFdj6U1@mid.individual.net>

On 2010-05-13, a  wrote:
> this must be easy but its taken me a couple of hours already
>
> i have
>
> a=[2,3,3,4,5,6]
>
> i want to know the indices where a==3 (ie 1 and 2)
>
> then i want to reference these in a
>
> ie what i would do in IDL is
>
> b=where(a eq 3)
> a1=a(b)
>
> any ideas?

For a sorted sequence the bisect module is a good start.

>>> start = bisect.bisect_left(a, 3)
>>> end = bisect.bisect_right(a, 3, bs)
>>> b = list(range(start, end))
>>> b
[1, 2]

If the list isn't necessarily sorted, try filter and enumerate.

>>> b = [a for a,b in filter(lambda x: x[1]==3, enumerate(a))]
>>> b
[1, 2]

-- 
Neil Cerutti
*** Your child was bitten by a Bat-Lizard. ***


From pmaupin at gmail.com  Thu May 13 11:06:52 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 08:06:52 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
Message-ID: <72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>

On May 13, 2:58?am, Steven D'Aprano
 wrote:
> On Wed, 12 May 2010 22:16:29 -0700, Patrick Maupin wrote:
> > On May 12, 10:48?pm, Lawrence D'Oliveiro  > central.gen.new_zealand> wrote:
> >> In message , Ed
> >> Keith wrote:
>
> >> > ... but to claim that putting more restrictions on someone give them
> >> > more freedom is pure Orwellian double speak.
>
> >> What about the freedom to take away other people?s freedom?
>
> > The freedom to take away other people's freedom is a very serious power
> > that should only be used sparingly.
>
> >> What tuple of speak would that be?
>
> > Well, if my friend has a slow internet connection, so I give him a Linux
> > CD which lets him get out of Windows hell (me taking advantage of RMS's
> > "freedom 2", and my friend taking advantage of RMS's "freedom 0"), and I
> > don't give my friend all the source code (or a written offer) because,
> > frankly, he wouldn't know what to do with the source anyway, and it
> > doesn't fit on the CD, and I didn't even bother downloading the source,
> > at that point I would apparently be in violation of the GPL license on
> > hundreds of programs, because I would be violating what the FSF calls
> > "freedom 1".
>
> If you used an existing Linux distribution, then the offer to provide
> source code will already be there.

No, there is no written offer, e.g. with Ubuntu, simply because they
take advantage of the ability to provide a download of the source from
the same place as a download of the object.  If I download an Ubuntu
ISO, burn it and give it away (let's say I give away 100 copies, just
to remove the fair use defense), then I have violated the GPL.  I
provided chapter and verse on this; go look it up.

> If you compiled the CD yourself, and failed to provide a written offer on
> the CD, then yes absolutely you would be in violation of the licence
> terms, and shame on you.

Not relevant.

> The GPL doesn't require you to force source code on those who don't want
> it, but it does require you to make it available if they ask, and for you
> to notify them appropriately of this fact. You don't even have to
> explicitly tell your friend he can have the source code. You just have to
> make sure that the written offer is available on the disk you give him.

There is no written offer on the disk, because I burned it from
Ubuntu's repository.  It really is that simple -- if I give away
copies I've made of Ubuntu, I've violated the GPL.  Unless you can
cite some authority that tells me I'm wrong and gives real reasons.  I
actually quoted chapter and verse from the license, but you chose to
ignore that and make unsubstantiated claims.

> > Now I know none of us would ever violate the license like this, but if,
> > hypothetically speaking, I had made such a CD for my friend, and then
> > someone came along and explained to me that, by helping wean my friend
> > from MS Windows in this fashion, I had taken away his freedom
> > (specifically RMS's "freedom 1"), I would probably conclude that the
> > person making this accusation was a moron
>
> Well, yes, you probably would draw that conclusion. Doesn't mean that you
> are right to do so, because quite frankly you would have taken away your
> friend's freedom (albeit in a very small fashion). Access to the source
> code is a freedom that the GPLed software on the disk *explicitly* grants
> to your friend, and by failing to pass the offer on, you have taken away
> that freedom in a very real sense.

I was going to say "moron" but you're obviously not, so I'll change my
opinion to "brainwashed." :-)

> We are talking about a small technical violation of the licence terms
> here.

No.  It's fundamental.  The license deliberately makes not sharing the
source *the* principal way to violate it.

> but imagine if everyone did it, if Red Hat and Debian and Ubuntu
> etc didn't bother passing on the source code (or a written offer).

Then somebody else would.  How does Apache work?

> Only a
> tiny proportion of people would discover by their own efforts that the
> source code was available

No, I tell my friends that source is available, and they can come and
see me if they want to know more.  This may have been a viable
argument in 1989 (doubtful) but it's extremely silly today.

>, and only a proportion of them would learn
> where it was available from. The result in practical terms would be a
> major decrease in the number of people granted the freedom to modify the
> source code, and a correspondingly larger decrease in the number of
> people both free and able to modify the source code.

I sincerely doubt your dystopian vision, which, like the GPL and many
laws, is predicated on some outmoded views about how humans interact.

The reason some people say that the GPL protects the "freedom of the
code" is because the GPL assumes that code needs to be nurtured,
instead of taking the viewpoint that, while there may be some
freeloaders, sharing code is obviously so valuable to most of humanity
that it will just happen.  We don't live in medieval Europe any more
where the rules of glassmaking are so secret that you'll be hunted
down like a dog if you try to leave.  We live in a world where "co-
opetition" has been shown to be so valuable we had to make up a word
for it, and even for those secrets that people are willing to kill to
keep, we have wikileaks.

Let's face it -- a software freeloader is not the most evil thing in
the world.  But whenever people assume that stopping bad behavior 'x'
is paramount, they have to make so many rules that everybody is in
violation of them all the time.  People love to share, but in general
people don't share things that others aren't interested in.  People
with source code will share with people who care about it.  Perhaps
making a special case for modified source code would be sufficient, if
you really care about what Linus calls "tit-for-tat."

> It's not enough to be granted freedom to modify source code in theory, if
> you know about it, if you can find some hard-to-locate website which may
> or may not be running. The practicalities are equally important.

That's another thing.  Even if I downloaded all the source from
Ubuntu, what assurances do I really have that I have all the source?
I could be in technical violation of the GPL without even knowing it,
even after wasting an extra two days grabbing the source.  Best to use
Gentoo to be sure, and even then, I need to build it twice running
strace just to make sure that I really built everything.

> In
> theoretical terms, everyone has the freedom to legally modify and
> distribute the source code to Microsoft Windows. All you have to do is
> buy 51% of the stock so as to become majority shareholder, then make
> sufficient changes to the board of directors so that the new board grants
> you a licence to do so, then fight off the lawsuits from the rest of the
> shareholders. Anyone could do it! Not.

So "everyone" could own 51% of Microsoft?  That means 100% of the
shares would be around 350,000,000,000%.  Wait, that can't be right,
what? :-)  Can you come up with a sillier analogy?

> Another, more practical example: here in Australia our government is hell-
> bent on introducing an ineffective and expensive Internet censorship
> scheme. It seems that under Australian law, it will be completely legal
> to circumvent the filter, but our government is investigating ways to
> make it illegal to tell anyone how to circumvent it. In other words,
> Australians will have permission to circumvent the nanny filter, but
> since few people will know this, or know how to do so, it will be a
> meaningless freedom.

Yes, that's basically how the DMCA works, and that's evil, and that's
one of the reasons I sometimes give money to the EFF.  But, you can't
seriously be comparing making speech a crime and making not speaking a
crime (or a copyright violation), can you?  Maybe you *did* manage to
come up with a sillier analogy...

> The GPL concerns itself with the *practical* freedom to gain access to
> source code, not merely the theoretical freedom represented by permission
> without opportunity.

No, the GPL is ideologically opposed to anything related to
practicality (although in practice, its adherents have to bend a bit
to avoid being made irrelevant, and Linux, the shining success, is led
by someone who arguably cares not one whit for GPL ideological
purity).

> Failure to pass on the offer to provide source code
> impacts that freedom in a very real sense.

The thing is, there is an offer.  It's just not written, and it may
not be that I will later be able to download the exact same source.
It doesn't meet the letter of the license.  Nonetheless, the offer is
*even better* than the one mandated by the GPL, because it comes with
an offer to teach.

But the GPL wording required to enforce what you call a practical
freedom imposes so many impractical costs that there are probably
millions of people in the world who have violated this license, in the
good-faith attempt to spread free software around.  As I mentioned to
Mr. Boddie, IMHO, the failure to bring any of these to justice is
deliberate, because suing someone who installed Ubuntu on his
grandmother's computer would give Free Software a huge public black
eye.

So the practicality is not in the *license*, but in the *selective
enforcement* of the license.  I view this sort of nod to practicality
to be exactly the same as Microsoft's implicit encouragement of piracy
in third-world countries.

Well, maybe not *exactly* the same, but to conclude that they are at
all different is to admit that *eventual* access to the source code is
moral enough and that enforced distribution of source code to
*everybody* is not really the best way to make the world a better
place.

> If you can't understand this, you have the freedom to think I'm a moron,
> and I have the freedom to be sure you are one too *wink*

Well, I don't think you are a moron, but I find some of your beliefs
not only ill-founded, but very negative -- based on the belief that so
few people will do the right thing absent onerous controls that the
only way to proceed is to impose those onerous controls and then look
the other way when the violation is not *too* egregious.

Also, it is obvious that you did not adequately research the legal
obligations of someone who downloads an Ubuntu ISO and make a few
copies to hand out, because you made completely unsupported statements
about how that works.

Regards,
Pat


From neilc at norwich.edu  Thu May 13 11:08:44 2010
From: neilc at norwich.edu (Neil Cerutti)
Date: 13 May 2010 15:08:44 GMT
Subject: indexing lists/arrays question
References: 
	
Message-ID: <852ivsFdj6U2@mid.individual.net>

On 2010-05-13, Stefan Behnel  wrote:
> a, 13.05.2010 16:36:
>> this must be easy but its taken me a couple of hours already
>>
>> i have
>>
>> a=[2,3,3,4,5,6]
>>
>> i want to know the indices where a==3 (ie 1 and 2)
>
>    indices = [ i for i,item in enumerate(a) if item == 3 ]

That form of list comprehension is preferable to my use of filter
posted elsewhere, but it didn't occur to me. Oops!

-- 
Neil Cerutti
*** Your child was bitten by a Bat-Lizard. ***


From oxfordenergyservices at googlemail.com  Thu May 13 11:15:30 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 08:15:30 -0700 (PDT)
Subject: indexing lists/arrays question
References: 
	
Message-ID: <91dbd493-bf48-443c-a2cf-93269baa25a8@24g2000yqy.googlegroups.com>

On 13 May, 15:47, Stefan Behnel  wrote:
> a, 13.05.2010 16:36:
>
> > this must be easy but its taken me a couple of hours already
>
> > i have
>
> > a=[2,3,3,4,5,6]
>
> > i want to know the indices where a==3 (ie 1 and 2)
>
> ? ?indices = [ i for i,item in enumerate(a) if item == 3 ]
>
> > then i want to reference these in a
>
> ? ?print [ a[i] for i in indices ]
>
> Stefan

thanks Stefan.  very useful.  I didn't get this from the python
documentation!


From e_d_k at yahoo.com  Thu May 13 11:18:25 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 08:18:25 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <495778.64465.qm@web58702.mail.re1.yahoo.com>
Message-ID: <929861.91577.qm@web58708.mail.re1.yahoo.com>

Consider the following scenario:

Three programmers, call them A, B & C, independently develop three different algorithms to perform a O(ln(n)) search. Each decide to release it for 'free'.

A decides to make it 'free', by publishing compiled object code for all major platforms and putting them in the public domain.

B decides to make it 'free' by publishing the source code under the GPL.

C decides to make it 'free' by publishing the source code under the Boost license.

Which library should be incorporated into the next Python release?, and why?

I vote for C, but would like to hear any arguments for another position.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From pmaupin at gmail.com  Thu May 13 11:18:52 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 08:18:52 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
Message-ID: <5c618134-bad9-456c-ace9-22bb082bc12d@i10g2000yqh.googlegroups.com>

On May 13, 7:25?am, Lawrence D'Oliveiro  wrote:
> In message
> <155f1683-9bfd-4a83-b63f-7fb0fc2f5... at g21g2000yqk.googlegroups.com>, Patrick
>
> Maupin wrote:
> > On May 12, 10:48 pm, Lawrence D'Oliveiro
> >  wrote:
>
> >> In message , Ed
> >> Keith wrote:
>
> >> > ... but to claim that putting more restrictions on someone give them
> >> > more freedom is pure Orwellian double speak.
>
> >> What about the freedom to take away other people?s freedom?
>
> > The freedom to take away other people's freedom is a very serious
> > power that should only be used sparingly.
>
> Given that the GPL restricts that power, then it must be all right.

But the freedom to take away other people's freedom to take away other
people's freedom is an even *more* serious power (as many communities
which have straight-jacketed their law enforcement officers have found
out), that should be used *very sparingly*, so your conclusion doesn't
necessarily follow.

Regards,
Pat



From python.list at tim.thechases.com  Thu May 13 11:19:05 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Thu, 13 May 2010 10:19:05 -0500
Subject: indexing lists/arrays question
In-Reply-To: 
References: 
Message-ID: <4BEC1869.1060204@tim.thechases.com>

On 05/13/2010 09:36 AM, a wrote:
> this must be easy but its taken me a couple of hours already
>
> i have
>
> a=[2,3,3,4,5,6]
>
> i want to know the indices where a==3 (ie 1 and 2)

indexes = [i for (i, v) in enumerate(a) where v==3]

> then i want to reference these in a

In a _what_?  You can then do things like

   for i in indexes:
     print a[i]

(but you already know these are "3", so it's not very exciting...)

-tkc




From aahz at pythoncraft.com  Thu May 13 11:27:27 2010
From: aahz at pythoncraft.com (Aahz)
Date: 13 May 2010 08:27:27 -0700
Subject: client to upload big files via https and get progress info
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
Message-ID: 

In article <4bea6b50$0$8925$426a74cc at news.free.fr>,
News123   wrote:
>
>I'd like to perform huge file uploads via https.
>I'd like to make sure,
>- that I can obtain upload progress info (sometimes the nw is very slow)
>- that (if the file exceeds a certain size) I don't have to
>  read the entire file into RAM.

Based on my experience with this, you really need to send multiple
requests (i.e. "chunking").  There are ways around this (you can look
into curl's resumable uploads), but you will need to maintain state no
matter what, and I think that chunking is the best/simplest.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From oxfordenergyservices at googlemail.com  Thu May 13 11:45:54 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 08:45:54 -0700 (PDT)
Subject: indexing lists/arrays question
References: 
	
Message-ID: 

On 13 May, 16:19, Tim Chase  wrote:
> On 05/13/2010 09:36 AM, a wrote:
>
> > this must be easy but its taken me a couple of hours already
>
> > i have
>
> > a=[2,3,3,4,5,6]
>
> > i want to know the indices where a==3 (ie 1 and 2)
>
> indexes = [i for (i, v) in enumerate(a) where v==3]
>
> > then i want to reference these in a
>
> In a _what_? ?You can then do things like
>
> ? ?for i in indexes:
> ? ? ?print a[i]
>
> (but you already know these are "3", so it's not very exciting...)
>
> -tkc

really its to get the indexes in 1 array where something equals
something then reference these in another array.


From pmaupin at gmail.com  Thu May 13 11:59:45 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 08:59:45 -0700 (PDT)
Subject: Picking a license
References: 
	
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com> 
	<0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com> 
	<356d235e-63e3-4d36-bb7e-e436d9279f27@l28g2000yqd.googlegroups.com> 
	<845fc53a-5940-44fc-9189-a5a8ff56a95d@n15g2000yqf.googlegroups.com> 
	<5c1c0cce-f9f9-469b-ba3b-3eb9280c2bc9@g21g2000yqk.googlegroups.com> 
	<4f1c4723-a1c9-4b3d-aee3-d6475733066d@a34g2000yqn.googlegroups.com>
Message-ID: 

On May 13, 9:53?am, Paul Boddie  wrote:
> On 13 Mai, 01:36, Patrick Maupin  wrote:
>
>
>
> > Once the court reaches that conclusion, it would only be a tiny step
> > to find that the FSF's attempt to claim that clisp infringes the
> > readline copyright to be a misuse of that same readline copyright.
> > See, e.g. LaserComb v Reynolds, where the defendant (IMHO) acted much
> > more egregiously than anybody who is delivering free software like
> > clisp is acting, and nevertheless won on that issue.
>
> In that very case you mention, LaserComb did not lose the copyright
> protection on their work, were "free to bring an infringement suit
> once it had cured the misuse" [1], and the clause which led to a
> defence based on "copyright misuse" was one which forbade licensees
> from making competing products.

Yes.  You make 3 points here, which I will address in order

1) They did not lose the copyright protection on their work.

To be clear, what I meant by losing copyright protection is not at all
the same as losing the copyright itself.  The loss of protections
simply means that you can't necessarily prevail in a lawsuit for
infringement against people who infringed while you were misusing the
copyright.  This could be true, even if while the copyright was being
misused, RMS attempted to sue someone else, and even if he had a solid
case.  From Lasercomb:  "However, again analogizing to patent misuse,
the defense of copyright misuse is available even if the defendants
themselves have not been injured by the misuse."  So, during the time
of the misuse, yes, they lost their copyright protections, but the
loss was only temporary and could be cured going forward by not
overreaching in their license agreement.

2) "Were free to bring an infringement suit once they cured the
misuse."

Yes, if you read the actual footnote you are referencing, it cites
United States Gypsum Co. v National Gypsum Co., which was a patent
case.  In that case, there was a price-fixing cartel based on patents,
and the cartel lost its ability to use the patents until they changed
their illegal patent licensing scheme.  Once they changed how they
licensed their patents to the court's satisfaction, they were then
free to go after patent infringers.  BUT, only for infringements that
occurred *after* they cured the infringement.  Curing the infringement
is not a magic wand that allows you a mulligan for your original cause
of action, otherwise the patent/copyright misuse defense would be
meaningless.

3) and the clause which led to a defence based on "copyright misuse"
was one which forbade licensees from making competing products.

Yes, but if you read the reasoning in the decision, almost any attempt
to stretch a copyright (or patent) to cover things it doesn't really
cover could be viewed as a misuse.  So, to the extent that the GPL
claims that the distribution of something that links to readline
violates readline's copyright by being a derivative work, if a court
finds this to be untrue, it could also find that the readline
copyright was being misused, at least until the license were modified
to make it clear that distributing a program that could use readline
(without distributing readline) did not impose any specific licensing
requirements on the readline-using program.

To follow this logic, all you have to do is to read the LaserComb
decision very carefully (it analogizes copyright misuse to patent
misuse), and then read the myriad ways it is possible to misuse
patents.

Regards,
Pat


From prologic at shortcircuit.net.au  Thu May 13 12:02:24 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 14 May 2010 02:02:24 +1000
Subject: client to upload big files via https and get progress info
In-Reply-To: <4bea6b50$0$8925$426a74cc@news.free.fr>
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
Message-ID: 

On Wed, May 12, 2010 at 6:48 PM, News123  wrote:
> Hi,
>
> I'd like to perform huge file uploads via https.
> I'd like to make sure,
> - that I can obtain upload progress info (sometimes the nw is very slow)
> - that (if the file exceeds a certain size) I don't have to
> ?read the entire file into RAM.
>
> I found Active states recipe 146306, which constructs the whole
> multipart message first in RAM and sends it then in one chunk.
>
>
> I found a server side solutions, that will write out the data file chunk
> wise ( http://webpython.codepoint.net/mod_python_publisher_big_file_upload
> )
>
>
>
> If I just wanted to have progress info, then I could probably
> just split line 16 of Active State's recipe ( h.send(body) )
> into multiple send, right?
>
> chunksize = 1024
> for i in range(0,len(body),chunksize):
> ? ?h.send(body[i:i+chunksize])
> ? ?show_progressinfo()
>
>
> But how could I create body step by step?
> I wouldn't know the content-length up front?
>
> thanks in advance

My suggestion is to find some tools that can
send multiple chucks of data. A non-blocking
i/o library/tool might be useful here (eg: twisted or similar).

cheers
James


From paul at boddie.org.uk  Thu May 13 12:19:25 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Thu, 13 May 2010 09:19:25 -0700 (PDT)
Subject: Picking a license
References:  <30aff350- 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
Message-ID: <2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>

On 13 Mai, 01:58, Patrick Maupin  wrote:
> On May 12, 6:15?pm, Paul Boddie  wrote:
> > Right. The "full cost" of software that probably cost them nothing
> > monetarily and which comes with all the sources, some through a chain
> > of distribution and improvement which could have led to proprietary
> > software had the earliest stages in the chain involved permissive
> > licensing. And that they can't sell a binary-only Ubuntu derivative.
>
> Who's talking about selling a binary-only version -- there is a good
> chance they can't even give away a binary CD without violating
> copyright.

People only have to honour requests for the corresponding source if
asked for it. They are not violating copyright by default. If you
think Ubuntu are exposing people to legal peril by advocating that
people make copies of Ubuntu for their friends, why don't you tell
Mark Shuttleworth about it?

[...]

> > So, the "negative consequences" are that people can't make proprietary
> > editions of some software. When that's a deliberate choice in the
> > design of a licence, there's no pretending that the consequences
> > aren't there, just that they aren't perceived by everyone to be
> > negative.
>
> I gave an example earlier of svglib and rst2pdf. ?Negative
> consequences. ?Nothing proprietary involved.

Negative consequences for people who don't want to touch GPL-licensed
software and who reserve the right to make proprietary versions of
rst2pdf.

[...]

> > Well, you effectively said that you didn't like being asked to "share
> > alike", which is what the GPL achieves.
>
> I give away lots of software. ?Free to all comers. ?Come and get some.

Yes, but you don't insist that people "share alike". I don't demand
that you insist that, either, but you clearly object to other people
putting that condition on their own works.

> > so why should I not assume
> > that you generally object to other, more obviously labelled licences
> > like the CC-*-SA licences which make it clear what is expected of that
> > hapless recipient of a work who doesn't bother reading the licence?
>
> Your assumptions are so far away from reality that there is really no
> good reason why you shouldn't assume that I'm a 10 foot tall purple
> monster.

Then you've done a very bad job communicating them. Laying off the
bizarre imagery might help remedy that somewhat.

[...]

> > Yes, but you have to choose to do something ("X") to start with. Which
> > is actually what you wrote later in that exchange:
>
> > "Again, the force is applied once you choose to do a particular thing
> > with the software -- is is really that hard to understand that
> > concept?"
>
> I didn't just write that later. ?I wrote it in my very first post,
> which you just quoted a few lines up, apparently without even
> bothering to read it closely.

I did read it closely. Now read your own comment closely and take
particular notice of the word "choose".

[...]

> So, the FSF, which so carefully provides the most legalese-ish license
> on the planet, which was in development for god-knows-how-long, which

Have you read the Mozilla Public License? Have you read through Sun's
JDK licence? You were complaining about Microsoft licensing earlier:
have you read those licences through to the end? (There are people who
refuse to accept them, incidentally, and are then refused any kind of
refund for the product. Next you'll be claiming that the FSF's
indiscretions are on the same level as this particular Microsoft-plus-
vendor scam, and yet accuse me of a lack of a sense of perspective.)

> maintains a carefully parsed FAQ of what you can and can't do, which
> engages in all sorts of advocacy, can't find the time to explain to
> Ubuntu that they really ought to explain how the licensing works on
> their download page?

I think Ubuntu can maybe see the case for moving their notice on their
"legal" page to the download page if you can make it successfully. Or
is your point that people have to be "warned" about that inconvenient
GPL licence?

>?What have you been smoking and where can I get some?

Yes, always ready with a pertinent response, I see.

[...]

> > I never said there was. I said that if you don't like the licence,
> > don't incorporate works which use it into your own projects.
>
> No, you said "If you don't like them, don't use GPL-licensed
> software."

In the context of developing and redistributing it. If you hate the
GPL so much, you might not feel comfortable even using the software,
either, but that's up to you. You're the one with the problem with the
GPL.

> > But don't
> > say that it's not fair that people are releasing stuff under terms you
> > don't like, or say that they're being "pathetic" or petty or
> > ridiculous by doing so, or are imposing their agenda on you.
>
> The only time I mentioned pathetic and petty were for really small
> libraries, which probably wouldn't merit copyright protection in any
> case.

And for you, libraries like readline are apparently not really worth
anything, either. It's always interesting to see the case made for
incorporating something into another system because it apparently has
little value relative to the entire system, but should the request be
made that the incorporated work be dropped and replaced by something
rewritten to do the same job, it is suddenly far too much work.

> > More name-calling and finger-pointing. Great stuff, there. Anything
> > else?
>
> Yes, just that you keep selectively quoting both of us, and twisting
> what we both said to meet your agenda. ?But I'm done. ?I think there
> are enough pointers to original material here for others to go and do
> whatever level of research they deem appropriate for their own
> situations.

All my position has ever been is this:

A copyrighted work denies recipients virtually all rights to do stuff
with that work, such as modify and redistribute it. Copyleft licences
grant some privileges and uphold some obligations in order to ensure
that these privileges are universally maintained in all forms and
extensions of the work. Permissive licences grant more privileges to
immediate recipients but do not uphold as many obligations.

You rejected the suggestion that people using permissive licences
afford users fewer privileges than those using copyleft licences, yet
on balance when considering all forms and extensions of the work, they
do. And the only such privilege that the copyleft licences withholds
from recipients is that of withholding any other privilege from others
who receive the work.

You objected to the suggestion that people using permissive licences
do not care about maintaining such privileges ("an uncaring bunch"),
yet it can be said that they surely do not actively care about the
matter of such privileges being maintained: I have encountered
proprietary variants of Apache technologies, and proprietary editions
of Python have been released from some vendors. If they had considered
it important enough, they would not have chosen licences which
permitted the delivery of their work (or extended versions thereof) to
people where many of the privileges normally afforded to users have
been withheld.

You made the point that some people don't want to touch GPL-licensed
software because it might affect the permissively licensed software
that they are writing. Since the only effect of combining both forms
of software occurs when offering that to a user, and that effect is to
uphold the copyleft obligations and maintain the corresponding set of
privileges, withholding only the privilege to deny recipients the
other privileges, this means that it becomes impossible to make the
combined work a proprietary one. You then tried to sow uncertainty
about the validity and effectiveness of the GPL to achieve its
objectives.

I can see why some people don't like the GPL. When the only notable
privilege it withholds is precisely that of taking the work of others
and making a proprietary product from it, all the claims about
coercion and ideology should be considered against this very function
of the licence. Then, the motivations of a number of its critics are
plain for all to see.

That some of those critics appeal to public outrage by using
references to terrorists, criminals and fundamentalists should hardly
be surprising, and I have come to expect no better in discussions of
this kind. Anything to accuse others of having an agenda - even better
if that agenda can be blended in the popular imagination with those
aforementioned kinds of undesirable people - while doing as much as
they can to conceal their own.

Paul


From lie.1296 at gmail.com  Thu May 13 12:35:09 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Fri, 14 May 2010 02:35:09 +1000
Subject: Broken pipe
In-Reply-To: 
References: 
	
	
Message-ID: <4bec2a9a$1@dnews.tpgi.com.au>

On 05/13/10 22:41, Lawrence D'Oliveiro wrote:
> In message , Chris 
> Rebert wrote:
> 
>> Also, please don't use semicolons in your code. It's bad style.
> 
> Wonder why they?re allowed, then.

they're there for line continuation, e.g.:

a = 40; foo(a)

but in many cases, putting two statements in a single line reduces
readability so use the semicolons extremely conservatively. But the
worst is the abuse of semicolons for end-of-line markers.


From news1234 at free.fr  Thu May 13 12:39:37 2010
From: news1234 at free.fr (News123)
Date: Thu, 13 May 2010 18:39:37 +0200
Subject: client to upload big files via https and get progress info
In-Reply-To: 
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	
Message-ID: <4BEC2B49.7060007@free.fr>

Hi Aaaz,

Aahz wrote:
> In article <4bea6b50$0$8925$426a74cc at news.free.fr>,
> News123   wrote:
>> I'd like to perform huge file uploads via https.
>> I'd like to make sure,
>> - that I can obtain upload progress info (sometimes the nw is very slow)
>> - that (if the file exceeds a certain size) I don't have to
>>  read the entire file into RAM.
> 
> Based on my experience with this, you really need to send multiple
> requests (i.e. "chunking").  There are ways around this (you can look
> into curl's resumable uploads), but you will need to maintain state no
> matter what, and I think that chunking is the best/simplest.
I agree I need  chunking. (the question is just on which level of the
protocol)

I just don't know how to make a chunkwise file upload or what library is
best.

Can you recommend any libraries or do you have a link to an example?


I'd like to avoid to make separate https post requests for the chunks
(at least if the underlying module does NOT support keep-alive connections)


I made some tests with high level chunking (separate sequential https
post requests).
What I noticed is a rather high penalty in data throughput.
The reason is probably, that each request makes its own https connection
and that either the NW driver or the TCP/IP stack doesn't allocate
enough band width to my request.

Therefore I'd like to do the chunking on a 'lower' level.
One option would be to have a https module, which supports keep-alive,

the other would be  to have a library, which creates a http post body
chunk by chunk.


What do others do for huge file uploads
The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )

N


From carey.tilden at gmail.com  Thu May 13 12:41:46 2010
From: carey.tilden at gmail.com (Carey Tilden)
Date: Thu, 13 May 2010 09:41:46 -0700
Subject: indexing lists/arrays question
In-Reply-To: 
References: 
	
	
Message-ID: 

On Thu, May 13, 2010 at 8:45 AM, a  wrote:
> On 13 May, 16:19, Tim Chase  wrote:
>> On 05/13/2010 09:36 AM, a wrote:
>>
>> > this must be easy but its taken me a couple of hours already
>>
>> > i have
>>
>> > a=[2,3,3,4,5,6]
>>
>> > i want to know the indices where a==3 (ie 1 and 2)
>>
>> indexes = [i for (i, v) in enumerate(a) where v==3]
>>
>> > then i want to reference these in a
>>
>> In a _what_? ?You can then do things like
>>
>> ? ?for i in indexes:
>> ? ? ?print a[i]
>>
>> (but you already know these are "3", so it's not very exciting...)
>>
>> -tkc
>
> really its to get the indexes in 1 array where something equals
> something then reference these in another array.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Out of curiosity, why are you using two arrays?  Have you considered a
dict?  There are of course good reasons not to use a dict in this
situation, but you haven't said one way or another.

Carey


From python.list at tim.thechases.com  Thu May 13 13:18:39 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Thu, 13 May 2010 12:18:39 -0500
Subject: indexing lists/arrays question
In-Reply-To: 
References: 	
	
Message-ID: <4BEC346F.3020901@tim.thechases.com>

On 05/13/2010 10:45 AM, a wrote:
>>> a=[2,3,3,4,5,6]
>>
>>> i want to know the indices where a==3 (ie 1 and 2)
>>
>> indexes = [i for (i, v) in enumerate(a) where v==3]
>>
>>> then i want to reference these in a
>>
>> In a _what_?  You can then do things like
>>
>>     for i in indexes:
>>       print a[i]
>>
>> (but you already know these are "3", so it's not very exciting...)
>>
>> -tkc
>
> really its to get the indexes in 1 array where something equals
> something then reference these in another array.

If your two arrays are of the same length, you can do things like

   a = [2,3,3,4,5,6]
   b = ['a', 'b', 'c', 'd', 'e', 'f']

   print [m for (n,m) in zip(a,b) if n == 3]

and skip the indexes altogether.

-tkc






From oxfordenergyservices at googlemail.com  Thu May 13 13:48:42 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 10:48:42 -0700 (PDT)
Subject: indexing lists/arrays question
References: 
	
	
	
Message-ID: <47754dc9-dcfa-4a3b-b171-3a342f42e5fe@o14g2000yqb.googlegroups.com>

On 13 May, 17:41, Carey Tilden  wrote:
> On Thu, May 13, 2010 at 8:45 AM, a  wrote:
> > On 13 May, 16:19, Tim Chase  wrote:
> >> On 05/13/2010 09:36 AM, a wrote:
>
> >> > this must be easy but its taken me a couple of hours already
>
> >> > i have
>
> >> > a=[2,3,3,4,5,6]
>
> >> > i want to know the indices where a==3 (ie 1 and 2)
>
> >> indexes = [i for (i, v) in enumerate(a) where v==3]
>
> >> > then i want to reference these in a
>
> >> In a _what_? ?You can then do things like
>
> >> ? ?for i in indexes:
> >> ? ? ?print a[i]
>
> >> (but you already know these are "3", so it's not very exciting...)
>
> >> -tkc
>
> > really its to get the indexes in 1 array where something equals
> > something then reference these in another array.
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Out of curiosity, why are you using two arrays? ?Have you considered a
> dict? ?There are of course good reasons not to use a dict in this
> situation, but you haven't said one way or another.
>
> Carey

i am reading a 2,n array from one website, column1=times,
column2=values
then another 2,n array from another website, column1=times,
column2=values

the times are different but may (or may not) coincide in places

i need to make a 3rd array, 2,n where the first column are column2
values from array1 and the second column are column2 values from array
2 #where the timestamps agree#

i'm an idl programmer and doing this would be second nature but i need
to make an application which does something along the lines of the
above then plots column2 vs column2 for the above array3 (plus some
other maths).  needs to be non-proprietary and work on different
platforms.  i just started with python, not even sure if it's the best
thing.  the plotting routines seem not to come wrapped with standard
python which is a bit of a pain.

the routine i use most in idl is 'where' and though i managed to write
a def which worked, i couldn't then dereference the list of those
indexes.  i'm a bit old to be learning new languages

thanks for your help!



From oxfordenergyservices at googlemail.com  Thu May 13 13:51:13 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 10:51:13 -0700 (PDT)
Subject: indexing lists/arrays question
References: 
	
	
	
Message-ID: <994e3852-637d-4bfd-96db-dd2e74c12cd2@e2g2000yqn.googlegroups.com>

On 13 May, 18:18, Tim Chase  wrote:
> On 05/13/2010 10:45 AM, a wrote:
>
>
>
>
>
> >>> a=[2,3,3,4,5,6]
>
> >>> i want to know the indices where a==3 (ie 1 and 2)
>
> >> indexes = [i for (i, v) in enumerate(a) where v==3]
>
> >>> then i want to reference these in a
>
> >> In a _what_? ?You can then do things like
>
> >> ? ? for i in indexes:
> >> ? ? ? print a[i]
>
> >> (but you already know these are "3", so it's not very exciting...)
>
> >> -tkc
>
> > really its to get the indexes in 1 array where something equals
> > something then reference these in another array.
>
> If your two arrays are of the same length, you can do things like
>
> ? ?a = [2,3,3,4,5,6]
> ? ?b = ['a', 'b', 'c', 'd', 'e', 'f']
>
> ? ?print [m for (n,m) in zip(a,b) if n == 3]
>
> and skip the indexes altogether.
>
> -tkc

mmm, that's clever, thanks.  although i don't know why it works yet.
at least i found a good user group!


From albertkao3 at gmail.com  Thu May 13 13:58:44 2010
From: albertkao3 at gmail.com (albert kao)
Date: Thu, 13 May 2010 10:58:44 -0700 (PDT)
Subject: walk directory & ignore all files/directories begin with '.'
Message-ID: 

I want to walk a directory and ignore all the files or directories
which names begin in '.' (e.g. '.svn').
Then I will process all the files.
My test program walknodot.py does not do the job yet.
Python version is 3.1 on windows XP.
Please help.

[code]
#!c:/Python31/python.exe -u
import os
import re

path = "C:\\test\\com.comp.hw.prod.proj.war\\bin"
for dirpath, dirs, files in os.walk(path):
    print ("dirpath " + dirpath)
    p = re.compile('\\\.(\w)+$')
    if p.match(dirpath):
        continue
    print ("dirpath " + dirpath)
    for dir in dirs:
        print ("dir " + dir)
        if dir.startswith('.'):
            continue

        print (files)
        for filename in files:
            print ("filename " + filename)
            if filename.startswith('.'):
                continue
            print ("dirpath filename " + dirpath + "\\" + filename)
    	    # process the files here
[/code]

C:\python>walknodot.py
dirpath C:\test\com.comp.hw.prod.proj.war\bin
dirpath C:\test\com.comp.hw.prod.proj.war\bin
dir .svn
dir com
[]
dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
...

I do not expect C:\test\com.comp.hw.prod.proj.war\bin\.svn to appear
twice.
Please help.


From python at mrabarnett.plus.com  Thu May 13 15:10:52 2010
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 13 May 2010 20:10:52 +0100
Subject: walk directory & ignore all files/directories begin with '.'
In-Reply-To: 
References: 
Message-ID: <4BEC4EBC.7010107@mrabarnett.plus.com>

albert kao wrote:
> I want to walk a directory and ignore all the files or directories
> which names begin in '.' (e.g. '.svn').
> Then I will process all the files.
> My test program walknodot.py does not do the job yet.
> Python version is 3.1 on windows XP.
> Please help.
> 
> [code]
> #!c:/Python31/python.exe -u
> import os
> import re
> 
> path = "C:\\test\\com.comp.hw.prod.proj.war\\bin"
> for dirpath, dirs, files in os.walk(path):
>     print ("dirpath " + dirpath)
>     p = re.compile('\\\.(\w)+$')
>     if p.match(dirpath):
>         continue
>     print ("dirpath " + dirpath)
>     for dir in dirs:
>         print ("dir " + dir)
>         if dir.startswith('.'):
>             continue
> 
>         print (files)
>         for filename in files:
>             print ("filename " + filename)
>             if filename.startswith('.'):
>                 continue
>             print ("dirpath filename " + dirpath + "\\" + filename)
>     	    # process the files here
> [/code]
> 
> C:\python>walknodot.py
> dirpath C:\test\com.comp.hw.prod.proj.war\bin
> dirpath C:\test\com.comp.hw.prod.proj.war\bin
> dir .svn
> dir com
> []
> dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> ...
> 
> I do not expect C:\test\com.comp.hw.prod.proj.war\bin\.svn to appear
> twice.
> Please help.

The problem is with your use of the 'match' method, which will look for 
a match only at the start of the string. You need to use the 'search'
method instead.

The regular expression is also incorrect. The string literal:

     '\\\.(\w)+$'

passes the characters:

     \\.(\w)+$

to the re module as the regular expression, which will match a
backslash, then any character, then a word, then the end of the string.
What you want is:

     \\\.\w+$

(you don't need the parentheses) which is best expressed as the 'raw'
string literal:

     r'\\\.\w+$'


From pmaupin at gmail.com  Thu May 13 16:10:04 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 13:10:04 -0700 (PDT)
Subject: Picking a license
References: 
	 
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com> 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
Message-ID: <7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>

On May 13, 11:19?am, Paul Boddie  wrote:
> People only have to honour requests for the corresponding source if
> asked for it. They are not violating copyright by default.

Well, the gospel according to the FSF says otherwise:

http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary

> If you
> think Ubuntu are exposing people to legal peril by advocating that
> people make copies of Ubuntu for their friends, why don't you tell
> Mark Shuttleworth about it?

Because I don't really think the peril is real -- a) nobody's going to
sue because of the negative PR consequences; and b) fair use would nip
the lawsuit in the bud.  In fact, the very *lack* of warning on the
Ubuntu site would help the end user in the lawsuit.

> Negative consequences for people who don't want to touch GPL-licensed
> software and who reserve the right to make proprietary versions of
> rst2pdf.

Negative consequences for people who don't want to tell other people
what to do.

> > > Well, you effectively said that you didn't like being asked to "share
> > > alike", which is what the GPL achieves.
>
> > I give away lots of software. ?Free to all comers. ?Come and get some.
>
> Yes, but you don't insist that people "share alike". I don't demand
> that you insist that, either, but you clearly object to other people
> putting that condition on their own works.

You're still not paying attention.  I think it's fine if people want
to do that, but I still think there is "force" involved, and that it
is not the best solution for all situations.  I also believe that
legally, the GPL license tries to overreach in its control of other
people's software, but that morally that may not matter, because the
intentions of the license's author are clear.

> > Your assumptions are so far away from reality that there is really no
> > good reason why you shouldn't assume that I'm a 10 foot tall purple
> > monster.
>
> Then you've done a very bad job communicating them. Laying off the
> bizarre imagery might help remedy that somewhat.

I didn't start off with bizarre imagery.  That only came about when
people started trying to use really lame excuses about why my initial
statement was wrong.
>
> [...]
>
> > > Yes, but you have to choose to do something ("X") to start with. Which
> > > is actually what you wrote later in that exchange:
>
> > > "Again, the force is applied once you choose to do a particular thing
> > > with the software -- is is really that hard to understand that
> > > concept?"
>
> > I didn't just write that later. ?I wrote it in my very first post,
> > which you just quoted a few lines up, apparently without even
> > bothering to read it closely.
>
> I did read it closely. Now read your own comment closely and take
> particular notice of the word "choose".

In my initial post, I mentioned that the force kicks in "once the
decision is made..."  That implies a choice.  Knowingly or not, you
have finally acknowledged that my initial post on this issue is
reasonably accurate, but even in so doing, you keep pointing to
specific words there to try to show that I'm contradicting myself.
Which, if I am, is only because I'm overreaching to try to combat the
overreaching on the other side.  I fully stand by my first post on
this issue, and most of the posting since then has been to correct
misunderstandings and apparently willful misinterpretations of that.

> I think Ubuntu can maybe see the case for moving their notice on their
> "legal" page to the download page if you can make it successfully.

The point, which I have made in another post, is that a fairly normal
way of acquiring Ubuntu -- giving a friend a CD -- violates the GPL as
written, and this is by design.  The goal is to get more free software
users even if they are abusing the license, and only punish those who
are abusing the license in particular ways.  BTW, there is nothing
even on Ubuntu's legal page warning about this possible consequence
for sharing a CD, or at least not in a very clear fashion.

> Or
> is your point that people have to be "warned" about that inconvenient
> GPL licence?

I don't think that would be a bad idea at all.  Say what you want
about Microsoft; if you install Windows, their software is quick to
explain all the licensing terms in gory detail.  Mind you, even that's
not really in English, but they get more points for the attempt than
Ubuntu.

> >?What have you been smoking and where can I get some?
>
> Yes, always ready with a pertinent response, I see.

I am ready with pertinent responses to well thought-out arguments, and
with impertinent responses to silly arguments.  From a practical
perspective, Microsoft turning a blind eye to increase market share,
and GPL authors turning a blind eye to increase market share and/or
goodwill are identical.  The fact that money is involved in one
instance and not in the other is immaterial.  The fact that you
believe in the goals of one and not the goals of the other is
immaterial.  The true fact is that, in both cases, copyright law in
conjunction with the license would allow the author to go after
several individuals for license violations, and (IMHO) a deliberate
decision has been made not to do so.  There have been numerous well-
publicized instances of people giving away copies they burned of
Ubuntu without corresponding source or a written offer, and no
negative consequences that I can see.

> [...]
>
> > > I never said there was. I said that if you don't like the licence,
> > > don't incorporate works which use it into your own projects.
>
> > No, you said "If you don't like them, don't use GPL-licensed
> > software."
>
> In the context of developing and redistributing it. If you hate the
> GPL so much, you might not feel comfortable even using the software,
> either, but that's up to you. You're the one with the problem with the
> GPL.

The context was right after talking about Mepis getting slapped, and
how all the clauses of the GPL were there for a reason, and if you
don't like the clauses, don't use the software.  I did not read it
with the contextual limitations you are now claiming for it.  You,
either deliberately or carelessly, have written several thing like
this that could easily be misconstrued, and this sometimes exasperates
me to the point where I write impertinent responses.

> > > But don't
> > > say that it's not fair that people are releasing stuff under terms you
> > > don't like, or say that they're being "pathetic" or petty or
> > > ridiculous by doing so, or are imposing their agenda on you.
>
> > The only time I mentioned pathetic and petty were for really small
> > libraries, which probably wouldn't merit copyright protection in any
> > case.
>
> And for you, libraries like readline are apparently not really worth
> anything, either. It's always interesting to see the case made for
> incorporating something into another system because it apparently has
> little value relative to the entire system, but should the request be
> made that the incorporated work be dropped and replaced by something
> rewritten to do the same job, it is suddenly far too much work.

No, you are absolutely misreading.  The case is for *not*
incorporating something into another system, because it's really *not*
that much work, even though the replicated effort is a bit of a shame
in some cases.

> > > More name-calling and finger-pointing. Great stuff, there. Anything
> > > else?
>
> > Yes, just that you keep selectively quoting both of us, and twisting
> > what we both said to meet your agenda. ?But I'm done. ?I think there
> > are enough pointers to original material here for others to go and do
> > whatever level of research they deem appropriate for their own
> > situations.
>
> All my position has ever been is this:
>
> A copyrighted work denies recipients virtually all rights to do stuff
> with that work, such as modify and redistribute it.

Translation:  Copyright law gives the author a monopoly on
distribution and derivative works,  and absent an explicit license to
make a derivative work or distribute a copy, the author can sue you
for making the derivative work or distributing the copy.  Nobody
forces the author to do that; it is his choice alone, but if he makes
it, government might back him up in his attempt to damage you.  Also,
in choosing a commercial license such as the GPL, the author is making
clear his intent to assert his rights, so you should take this very
seriously.

> Copyleft licences
> grant some privileges and uphold some obligations in order to ensure
> that these privileges are universally maintained in all forms and
> extensions of the work.

Translation:

Copyleft licences are a way for the author to communicate that he will
not sue you for making a derivative work or distributing a copy as
long as you distribute source code.  In reality, the author probably
will not sue you even if you don't distribute source code with that
Ubuntu CD, but you really can't be sure about that, because he has
made it clear that he *really* wants you to give out the source code.
In fact, on the FSF website, they make it clear in several places that
the author really wants you to give away your *own* source code if it
could interoperate with the author's source code, *even if* you're not
actually giving away the author's source code.

> Permissive licences grant more privileges to
> immediate recipients but do not uphold as many obligations.

Translation:

Software with a permissive license is more of a gift.  No quid-pro-quo
required, and the license does not attempt to claim rights over
anything except the actual licensed work.

> You rejected the suggestion that people using permissive licences
> afford users fewer privileges than those using copyleft licences,

That is correct.  All "privileges" as you put it are merely things
that a user can do with the code without fear of a lawsuit by the
author, and when an author uses a permissive license, he indicates
that the things that he could possibly find egregious enough to sue
over are very few.  For example, if you give an Ubuntu CD to your
friend without giving source code or a written offer of source code,
you have violated the license on quite a few of the programs on the
CD, but not, for example, on Python or Apache, because these licenses
do not attempt to forbid you from doing this.

> yet on balance when considering all forms and
> extensions of the work, they do.

Translation:

An author using the GPL is using the threat of lawsuits against *other
authors* to force the other authors to make their work also available
under the GPL.  Some authors attempt use this threat even against the
authors of works which a user could conveniently link against a GPLed
work, even when the authors of these other works have not copied or
distributed the GPL work themselves.  Some people, including Mr.
Boddie, feel that the public benefits of this license pyramid scheme
greatly outweigh any negative consequences of this scheme, in part by
equating the scheme itself with freedom and morality, and then using
the tautological logic that anybody who feels the negative
consequences must be immorally against freedom.

> And the only such privilege that the copyleft licences withholds
> from recipients is that of withholding any other privilege from others
> who receive the work.

Translation:

We really are serious about suing people who violate the license in
some cases.  Even though the stated purpose of the license is to
encourage sharing, the only really safe thing to do is to not share
that Ubuntu CD, because if you don't give out the exact source to the
exact object on the CD to everybody you give the CD to, you could be a
target.  Well, not really.  That would be bad PR.  But to protect your
rights, we have to design the license in such a way that we do reserve
the right to sue you under these conditions.  Just so you know.

> You objected to the suggestion that people using permissive licences
> do not care about maintaining such privileges ("an uncaring bunch"),
> yet it can be said that they surely do not actively care about the
> matter of such privileges being maintained:

Oh?  They take down their source archives on a whim?

> I have encountered
> proprietary variants of Apache technologies, and proprietary editions
> of Python have been released from some vendors.

Oh, I see.  Once someone releases a proprietary version of Python,
it's game over -- the PSF people realize they're outnumbered and
that's when take down their repository, so that's how privileges
disappear.

Seriously, to the extent there is nothing new in the proprietary
version, it's no big deal -- get it from the original source (probably
fewer viruses anyway).  To the extent there are additional features in
the proprietary version, guess what?  They were written by somebody
else and they don't belong to the PSF people.  To the extent there are
bug fixes in the proprietary version that aren't in the mainline
Python distribution -- hah!  that's extremely unlikely.

> If they had considered
> it important enough, they would not have chosen licences which
> permitted the delivery of their work (or extended versions thereof) to
> people where many of the privileges normally afforded to users have
> been withheld.

"Normally afforded to users."  Normalcy, in the software world, is
what Microsoft does.  Sure, that's changing, and that's good, but I
don't think that word means what you think it does.  But in any case,
you're right -- they didn't consider it important enough.  Hint:  that
doesn't make them uncaring.

> You made the point that some people don't want to touch GPL-licensed
> software because it might affect the permissively licensed software
> that they are writing.

Correct.

> Since the only effect of combining both forms
> of software occurs when offering that to a user,

No, according to the FSF, the effect can happen even before the
software is combined, when non-GPLed software is offered to the user,
if that non-GPLed software can interact in certain ways with GPLed
software.

> and that effect is to
> uphold the copyleft obligations and maintain the corresponding set of
> privileges, withholding only the privilege to deny recipients the
> other privileges,

Translation:

The effect is to try to force licensing terms on software that the
author didn't write.

> this means that it becomes impossible to make the
> combined work a proprietary one.

That's obviously the strongly desired effect.

> You then tried to sow uncertainty
> about the validity and effectiveness of the GPL to achieve its
> objectives.

The GPL is certainly effective in achieving some of its objectives.  I
disagree how useful some of those are to society, sure.  In terms of
the validity of the license, I believe that the selective enforcement
of the GPL will only target those actors who everybody can agree is
bad, but that the literal writing of the GPL and, especially the FSF's
FAQ about the GPL, is unsupportably overbroad.  For example, a literal
reading really does require you to give grandma source or a written
offer if you install Ubuntu on her computer, but fair use would
decimate that claim in a heartbeat.  Nonetheless, on a few of the
overbroad claims, the FSF prefers to promulgate FUD about how, for
example, it would not be possible for a proprietary program to
dynamically link to readline.  The wouldn't actually file a lawsuit on
that issue, because the possibility they would lose is too great.

> I can see why some people don't like the GPL.

Yes, you see, but you don't understand.

> When the only notable
> privilege it withholds is precisely that of taking the work of others
> and making a proprietary product from it.

No, it theoretically keeps me from burning a Ubuntu CD and then
putting it on my grandmother's computer without also downloading a
bunch of source code.  A literal reading of the license shows that the
restrictions really are that onerous.

> all the claims about
> coercion and ideology should be considered against this very function
> of the licence. Then, the motivations of a number of its critics are
> plain for all to see.

Here, we absolutely agree.  Just want to be sure that we also agree
that the GPL license is *so* picky about how it goes about its
business that you can't even link GPL v2-only code with GPL v3 code
without incurring a license violation.  It's really tough to innovate
on licensing when one of the major functions of the license is to
propagate exact copies of itself.

> That some of those critics appeal to public outrage by using
> references to terrorists, criminals and fundamentalists should hardly
> be surprising, and I have come to expect no better in discussions of
> this kind.

When the leader of your religion bandies terms like "freedom" and
"evil" about, what do you expect?  Seriously?

> Anything to accuse others of having an agenda

So now you're claiming RMS doesn't have an agenda?  That's really
interesting.  I think even he would disagree.

> - even better
> if that agenda can be blended in the popular imagination with those
> aforementioned kinds of undesirable people - while doing as much as
> they can to conceal their own.

My primary agenda is to explain that RMS does, in fact, have an
agenda, and the GPL was designed as a tool in furtherance of that
agenda, and that while the agenda does have some arguably noble goals,
before using the GPL people should understand its consequences both
for good and bad, and make their own determination about whether it's
the right license for their project.

Regards,
Pat


From albertkao3 at gmail.com  Thu May 13 16:10:30 2010
From: albertkao3 at gmail.com (albert kao)
Date: Thu, 13 May 2010 13:10:30 -0700 (PDT)
Subject: walk directory & ignore all files/directories begin with '.'
References: 
	
Message-ID: <6069b900-88a5-4cc7-ab82-bfe8ccabd68b@d27g2000yqc.googlegroups.com>

On May 13, 3:10?pm, MRAB  wrote:
> albert kao wrote:
> > I want to walk a directory and ignore all the files or directories
> > which names begin in '.' (e.g. '.svn').
> > Then I will process all the files.
> > My test program walknodot.py does not do the job yet.
> > Python version is 3.1 on windows XP.
> > Please help.
>
> > [code]
> > #!c:/Python31/python.exe -u
> > import os
> > import re
>
> > path = "C:\\test\\com.comp.hw.prod.proj.war\\bin"
> > for dirpath, dirs, files in os.walk(path):
> > ? ? print ("dirpath " + dirpath)
> > ? ? p = re.compile('\\\.(\w)+$')
> > ? ? if p.match(dirpath):
> > ? ? ? ? continue
> > ? ? print ("dirpath " + dirpath)
> > ? ? for dir in dirs:
> > ? ? ? ? print ("dir " + dir)
> > ? ? ? ? if dir.startswith('.'):
> > ? ? ? ? ? ? continue
>
> > ? ? ? ? print (files)
> > ? ? ? ? for filename in files:
> > ? ? ? ? ? ? print ("filename " + filename)
> > ? ? ? ? ? ? if filename.startswith('.'):
> > ? ? ? ? ? ? ? ? continue
> > ? ? ? ? ? ? print ("dirpath filename " + dirpath + "\\" + filename)
> > ? ? ? ? ? ? ? ?# process the files here
> > [/code]
>
> > C:\python>walknodot.py
> > dirpath C:\test\com.comp.hw.prod.proj.war\bin
> > dirpath C:\test\com.comp.hw.prod.proj.war\bin
> > dir .svn
> > dir com
> > []
> > dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> > dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> > ...
>
> > I do not expect C:\test\com.comp.hw.prod.proj.war\bin\.svn to appear
> > twice.
> > Please help.
>
> The problem is with your use of the 'match' method, which will look for
> a match only at the start of the string. You need to use the 'search'
> method instead.
>
> The regular expression is also incorrect. The string literal:
>
> ? ? ?'\\\.(\w)+$'
>
> passes the characters:
>
> ? ? ?\\.(\w)+$
>
> to the re module as the regular expression, which will match a
> backslash, then any character, then a word, then the end of the string.
> What you want is:
>
> ? ? ?\\\.\w+$
>
> (you don't need the parentheses) which is best expressed as the 'raw'
> string literal:
>
> ? ? ?r'\\\.\w+$'
Following your advice and add the case for C:\test
\com.comp.hw.prod.proj.war\bin\.svn\tmp
    p = re.compile(r'\\\.\w+$')
    if p.search(dirpath):
        continue
    p = re.compile(r'\\\.\w+\\')
    if p.search(dirpath):
        continue

Problem is solved.
Thanks.


From albertkao3 at gmail.com  Thu May 13 16:12:40 2010
From: albertkao3 at gmail.com (albert kao)
Date: Thu, 13 May 2010 13:12:40 -0700 (PDT)
Subject: use only files but ignore directories on Windows
Message-ID: <1f3324a2-009b-4fac-b900-ffbfedae3d9a@24g2000yqy.googlegroups.com>

My program plan to use only files but ignore directories on Windows.
I google but do not find some functions like
bool isFile(string)
bool isDirectory(string)
Please help.


From malaclypse2 at gmail.com  Thu May 13 16:30:47 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Thu, 13 May 2010 16:30:47 -0400
Subject: use only files but ignore directories on Windows
In-Reply-To: <1f3324a2-009b-4fac-b900-ffbfedae3d9a@24g2000yqy.googlegroups.com>
References: <1f3324a2-009b-4fac-b900-ffbfedae3d9a@24g2000yqy.googlegroups.com>
Message-ID: 

On Thu, May 13, 2010 at 4:12 PM, albert kao  wrote:
> My program plan to use only files but ignore directories on Windows.
> I google but do not find some functions like
> bool isFile(string)
> bool isDirectory(string)
> Please help.

You're looking for the functions os.path.isfile() and os.path.isdir()

See http://docs.python.org/library/os.path.html for details.

-- 
Jerry


From prologic at shortcircuit.net.au  Thu May 13 16:30:51 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 14 May 2010 06:30:51 +1000
Subject: use only files but ignore directories on Windows
In-Reply-To: <1f3324a2-009b-4fac-b900-ffbfedae3d9a@24g2000yqy.googlegroups.com>
References: <1f3324a2-009b-4fac-b900-ffbfedae3d9a@24g2000yqy.googlegroups.com>
Message-ID: 

On Fri, May 14, 2010 at 6:12 AM, albert kao  wrote:
> My program plan to use only files but ignore directories on Windows.
> I google but do not find some functions like
> bool isFile(string)
> bool isDirectory(string)
> Please help.

Try looking up the os module.

cheers
James


From oxfordenergyservices at googlemail.com  Thu May 13 17:00:02 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 14:00:02 -0700 (PDT)
Subject: stopping execution window on error - newbie
Message-ID: <101459d0-92cb-40d4-ad6d-6f82a70b167d@l31g2000yqm.googlegroups.com>

I'm coding on an old windows laptop

i write the code and double click the icon.  it runs the program and
writes results to a window.

when the code finishes, the window closes, i do a time.sleep(10) to
see what has happened.

unfortunately when there is an error it just closes the window.
anyway of seeing the error messages?

thanks

a


From landimatte at gmail.com  Thu May 13 17:12:00 2010
From: landimatte at gmail.com (Matteo Landi)
Date: Thu, 13 May 2010 23:12:00 +0200
Subject: stopping execution window on error - newbie
In-Reply-To: <101459d0-92cb-40d4-ad6d-6f82a70b167d@l31g2000yqm.googlegroups.com>
References: <101459d0-92cb-40d4-ad6d-6f82a70b167d@l31g2000yqm.googlegroups.com>
Message-ID: 

Place a try .. except surrounding the body of your program, and finally call
the input() function.

On Thu, May 13, 2010 at 11:00 PM, a wrote:

> I'm coding on an old windows laptop
>
> i write the code and double click the icon.  it runs the program and
> writes results to a window.
>
> when the code finishes, the window closes, i do a time.sleep(10) to
> see what has happened.
>
> unfortunately when there is an error it just closes the window.
> anyway of seeing the error messages?
>
> thanks
>
> a
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From mark.engelberg at gmail.com  Thu May 13 18:19:41 2010
From: mark.engelberg at gmail.com (puzzler)
Date: Thu, 13 May 2010 15:19:41 -0700 (PDT)
Subject: Tkinter - paste from clipboard not working
Message-ID: 

I have written a very simple GUI in Python / Tkinter, running under
Python 2.5.4 on Windows.

The GUI is essentially a big Tix.ScrolledText area, where you can
enter some text, and a button underneath to process the text.  (The
button causes the text to be looked up in a SQLite database, and some
stats are generated and displayed in a web browser).

One of my users is reporting to me that intermittently, he loses the
ability to paste text into the Tix.ScrolledText area.  He says that
copy and paste works in all his other applications, but suddenly it
will not work in my app's text widget.  Even weirder, he says that
once the ability to paste goes away, it will not work *until he
reboots his computer*.

Even if there's some sort of bug with my app, I can't think of any way
that this problem could persist across stopping and starting the
program.  Seems like restarting the program should put things back
into a pristine state.  So I'm beginning to wonder if there's some
sort of deeper bug with Tkinter or Tix?  How could this bug persist
until a reboot?  Does Python run some background service to handle Tk
calls that remains running across Python instantiations?

Any ideas or suggestions would be most appreciated.  Thanks!


From mensanator at aol.com  Thu May 13 19:14:32 2010
From: mensanator at aol.com (Mensanator)
Date: Thu, 13 May 2010 16:14:32 -0700 (PDT)
Subject: stopping execution window on error - newbie
References: <101459d0-92cb-40d4-ad6d-6f82a70b167d@l31g2000yqm.googlegroups.com>
Message-ID: <3fd705f1-2b3b-4b2b-b48d-06a6700a76be@g21g2000yqk.googlegroups.com>

On May 13, 4:00?pm, a  wrote:
> I'm coding on an old windows laptop
>
> i write the code and double click the icon. ?

Don't do that.

> it runs the program and
> writes results to a window.
>
> when the code finishes, the window closes, i do a time.sleep(10) to
> see what has happened.
>
> unfortunately when there is an error it just closes the window.
> anyway of seeing the error messages?

Go to the windows [Start] button. Select [Run...] and in the popup
box,
type "cmd" as the program to run. This will open a DOS shell window (a
text window.)

Then you can run your Python script from the window prompt and it
won't
close until you manually close it, even if the program crashes.

For example, once I open the DOS shell...


Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

H:\>C:

C:\>cd python31\user\lotto

C:\Python31\user\lotto>dir
 Volume in drive C has no label.
 Volume Serial Number is 06DE-55B4

 Directory of C:\Python31\user\lotto

05/13/2010  05:53 PM              .
05/13/2010  05:53 PM              ..
08/19/2009  07:08 PM             3,334 lotto.py
05/13/2010  05:56 PM             6,068 lotto_2010.py
               2 File(s)          9,402 bytes
               2 Dir(s)  102,247,440,384 bytes free

C:\Python31\user\lotto>..\..\python lotto_2010.py

{1: 2, 2: 3, 3: 2, 4: 1, 5: 2, 6: 1, 7: 2, 8: 1, 9: 1, 10: 2, 11: 2,
13: 1, 14: 2, 17: 1, 18: 2, 19: 1, 20: 1, 21: 1, 22: 1, 24: 1, 25: 1,
26: 3, 27: 1, 28: 2, 29: 2, 30: 1, 31: 1, 32: 1, 34: 1, 35: 1, 37: 2,
38: 2, 39: 2, 40: 1, 42: 2, 43: 1, 44: 2, 46: 2, 47: 1, 48: 1, 50: 1,
51: 2, 52: 3}

 1  2 **
 2  3 ***
 3  2 **
 4  1 *
 5  2 **
 6  1 *
 7  2 **
 8  1 *
 9  1 *
10  2 **
11  2 **
12
13  1 *
14  2 **
15
16
17  1 *
18  2 **
19  1 *
20  1 *
21  1 *
22  1 *
23
24  1 *
25  1 *
26  3 ***
27  1 *
28  2 **
29  2 **
30  1 *
31  1 *
32  1 *
33
34  1 *
35  1 *
36
37  2 **
38  2 **
39  2 **
40  1 *
41
42  2 **
43  1 *
44  2 **
45
46  2 **
47  1 *
48  1 *
49
50  1 *
51  2 **
52  3 ***


(7, 21, 50, 36, 26, 3)
(7, 21, 50, 36, 26, 17)
(7, 21, 50, 36, 26, 52)
(7, 21, 50, 36, 3, 17)
(7, 21, 50, 36, 3, 52)
(7, 21, 50, 36, 17, 52)
(7, 21, 50, 26, 3, 17)
(7, 21, 50, 26, 3, 52)
(7, 21, 50, 26, 17, 52)
(7, 21, 50, 3, 17, 52)
(7, 21, 36, 26, 3, 17)
(7, 21, 36, 26, 3, 52)
(7, 21, 36, 26, 17, 52)
(7, 21, 36, 3, 17, 52)
(7, 21, 26, 3, 17, 52)
(7, 50, 36, 26, 3, 17)
(7, 50, 36, 26, 3, 52)
(7, 50, 36, 26, 17, 52)
(7, 50, 36, 3, 17, 52)
(7, 50, 26, 3, 17, 52)
(7, 36, 26, 3, 17, 52)
(21, 50, 36, 26, 3, 17)
(21, 50, 36, 26, 3, 52)
(21, 50, 36, 26, 17, 52)
(21, 50, 36, 3, 17, 52)
(21, 50, 26, 3, 17, 52)
(21, 36, 26, 3, 17, 52)
(50, 36, 26, 3, 17, 52)


 8  9 32 38 40 48
13 22 28 39 42 43
 1  2  5 11 18 52 +
 2  3 26 44 51 52 +++
 4  7 14 26 35 52 +++
 2  7 10 19 42 47 +
 5 20 31 34 50 51 +
 1 28 29 37 39 46
10 11 27 37 38 46
 6 21 24 29 30 44 +
 3 14 17 18 25 26 +++
 7 10 39 42 45 46 +
15 17 23 36 38 44 ++
16 19 23 27 41 49
15 25 32 36 44 47 +
16 19 24 29 38 41
 3  4  8 13 43 49 +
 2 11 17 19 22 50 ++
14 21 22 28 30 45 +
 4 15 21 34 47 49 +
19 34 38 39 40 48
 4 16 24 33 37 48
 8 16 17 18 39 40 +
 1 24 27 30 31 47
 1  7 11 21 30 43 ++
 1  8 13 18 32 36 +
 5 10 12 16 20 21 +
 7 11 23 24 26 35 ++
 7  8 11 13 42 49 +
 1  8 17 34 40 50 ++
 1 24 29 35 41 45
15 17 24 32 44 52 ++
 4 12 21 26 33 38 ++
 2 13 15 41 48 50 +
 2  7  9 27 45 52 ++
24 25 35 36 39 42 +
 8 22 39 40 42 48
16 18 29 30 34 43
 7 21 28 36 45 50 ++++
 4  8 30 35 39 42
 2 11 15 23 40 51
 2  7 14 18 23 34 +
 1 11 22 37 41 50 +
 4 34 40 44 50 52 ++
12 28 33 39 40 52 +
14 18 25 36 38 39 +
 4 11 16 17 27 37 +
 1 11 16 28 31 36 +
 8 16 31 34 36 52 ++
 7 10 15 21 35 36 +++
 2  9 21 23 29 30 +
15 29 33 41 46 47
 2  5 18 34 36 39 +
 7 15 21 31 45 50 +++
12 17 20 28 39 51 +
 3  7 22 26 50 52 +++++
 1  5 21 27 31 39 +
 2  8 10 23 34 50 +
 1 11 24 26 32 52 ++
 1 18 20 38 41 42
12 33 36 42 45 48 +
 1  6 21 28 37 39 +
16 18 19 22 33 35
 2  7 17 27 29 47 ++
15 19 20 25 42 45
 2  6 17 19 20 41 +
 1 13 34 42 43 46
16 29 30 31 34 47
 5  7 26 29 36 46 +++
 1 27 28 30 31 49
 8 17 19 47 49 52 ++
 5 23 32 41 42 45
11 13 22 29 40 46
16 17 18 20 41 43 +
 3 17 26 38 45 52 ++++
13 18 21 38 39 41 +
14 19 28 40 44 51
 4  8  9 36 43 47 +
 1  9 15 24 36 39 +
 4 31 37 41 42 43
 7 12 18 27 36 42 ++
 3  4 26 27 35 51 ++
 7 12 19 23 26 45 ++
19 28 36 39 42 52 ++
 8 17 21 44 46 51 ++
 2  4 18 19 36 49 +
 1  4 11 16 22 35
13 14 17 18 41 46 +
 8 16 23 29 43 48
 1  8 25 36 37 44 +
 7 20 21 23 36 50 ++++
 3  7 23 27 39 43 ++
 4 10 21 37 38 48 +
 6 18 30 35 36 42 +
 3 14 23 43 46 48 +
10 11 19 26 42 46 +
 1  5 27 34 42 45
 1 16 29 33 40 46
32 41 43 45 48 51
 1 13 23 24 46 49
24 25 28 30 32 40
 8 14 20 33 50 52 ++
 2 16 27 28 33 39
13 17 19 32 43 52 ++
10 11 16 43 45 49
 2  4 20 22 35 44
 1 12 18 36 37 40 +
 8 10 16 22 35 47
 8 11 16 31 45 46
11 13 22 25 26 27 +
 3 17 25 26 29 40 +++
 7 10 27 37 46 47 +
 3  5  7 27 33 40 ++
 4 14 28 37 40 44
18 22 25 33 43 48
11 19 26 30 44 50 ++
 3 11 22 42 46 51 +
 7  8 21 26 30 50 ++++
 6 13 15 23 37 39
12 17 31 37 43 47 +
 2  7 11 21 33 42 ++
 2 21 26 37 39 50 +++
 6 26 37 38 42 46 +
18 19 24 34 40 49
 2  9 12 17 31 42 +
 5 14 30 32 34 49
 7 14 29 41 49 50 ++
 3  7 43 45 46 47 ++
12 22 31 37 40 51
 1  3  5 11 28 46 +
 6  7 12 22 30 32 +
13 18 20 25 26 49 +
14 19 22 41 49 50 +
 3  4 12 20 39 42 +
 9 18 31 44 46 49
 9 20 24 27 41 45
 6  8 27 31 45 52 +
22 34 35 40 41 42
 1  8 15 37 38 45
 6  9 13 16 35 51
 6 14 17 30 33 52 ++
14 27 31 34 40 51
 2 11 21 34 36 46 ++
 1  3 12 15 47 51 +
 4  5 26 30 32 37 +
 4 10 18 29 37 51
 8 33 35 36 39 43 +
 9 17 22 23 40 52 ++
 3 31 34 38 47 50 ++
21 26 27 33 41 50 +++
 1 10 15 26 40 43 +
 9 15 17 25 40 42 +
 6 11 23 26 30 45 +
 1  5  9 33 44 51
13 15 20 22 27 48
 3  5 10 11 17 32 ++

C:\Python31\user\lotto>


Now I can study the output for as long as I want.

Also, I could have done this:

    C:\Python31\user\lotto>..\..\python lotto_2010.py >
lotto_output.txt

and directed the output to a file for editing and/or printing.

>
> thanks
>
> a



From 007brendan at gmail.com  Thu May 13 19:30:35 2010
From: 007brendan at gmail.com (Brendan Abel)
Date: Thu, 13 May 2010 16:30:35 -0700 (PDT)
Subject: Picking a license
References: 
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
Message-ID: <7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>

While I think most of the disagreement in this long thread results
from different beliefs in what "freedom" means, I wanted to add, that
most of the responses that argue that the MIT license permits the user
more freedom than the GPL, suffer from the broken window fallacy.
This fallacy results from the short-sided-ness of the user base, as it
is only considering the first generation of derivative works.

I agree, that under an MIT license, the first generation of derivative
works have more freedom.  But any extra freedom gained here comes at
the direct expense of all future generations of derivative software.

Under a GPL license, it is true that the first generation will have
less freedom to distribute their software as they would like.  But it
also ensures that all subsequent generations of derivative works have
the freedom to access all previous derivative works.

I also want to add that I think the GPL v3 has exceeded this
fundamental concept.  GPL v2 really embodies this meaning of "freedom".


From steven at REMOVE.THIS.cybersource.com.au  Thu May 13 19:39:42 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 13 May 2010 23:39:42 GMT
Subject: Picking a license
References: 
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
Message-ID: 

On Thu, 13 May 2010 08:06:52 -0700, Patrick Maupin wrote:

> If I download an Ubuntu
> ISO, burn it and give it away (let's say I give away 100 copies, just to
> remove the fair use defense), then I have violated the GPL.  I provided
> chapter and verse on this; go look it up.

I'm sorry, I can't see where you have provided "chapter and verse", or 
even a URL.


>> If you compiled the CD yourself, and failed to provide a written offer
>> on the CD, then yes absolutely you would be in violation of the licence
>> terms, and shame on you.
> 
> Not relevant.

You didn't specify whether the "Linux CD" you were distributing was a 
mere copy of an existing CD , or one you created yourself, so you will 
pardon me for covering both possibilities.


>> The GPL doesn't require you to force source code on those who don't
>> want it, but it does require you to make it available if they ask, and
>> for you to notify them appropriately of this fact. You don't even have
>> to explicitly tell your friend he can have the source code. You just
>> have to make sure that the written offer is available on the disk you
>> give him.
> 
> There is no written offer on the disk, because I burned it from Ubuntu's
> repository.  It really is that simple -- if I give away copies I've made
> of Ubuntu, I've violated the GPL.

No, I think this use-case would count as "propagation without conveying", 
since you are merely acting as a mechanical proxy between your friend(s) 
and Ubuntu.

I will admit that the GPL FAQs are not as clear about this matter as they 
should be.



> Unless you can cite some authority
> that tells me I'm wrong and gives real reasons.  I actually quoted
> chapter and verse from the license, but you chose to ignore that and
> make unsubstantiated claims.

I'm sorry, I can't find where you have quoted "chapter and verse" from 
the licence, so I can't comment.



[snip]
>> but imagine if everyone did it, if Red Hat and Debian and Ubuntu etc
>> didn't bother passing on the source code (or a written offer).
> 
> Then somebody else would.  How does Apache work?

Apache is niche software, and sadly its popularity is falling 
significantly. (~200 million webservers is a large niche, but it's still 
a niche.) The scales on the Netcraft graph are useless, so I can't read 
accurate numbers, but it looks like it has fallen from approximately a 
75% market share to under 55%.

http://news.netcraft.com/archives/web_server_survey.html

Perhaps the Apache model doesn't work quite as well as you think?

As far as not-so-niche software goes, the GPLed Linux OS is far more 
popular on the desktop than FreeBSD and OpenBSD together, and about equal 
in popularity to Mac OS. I'm not suggesting that the popularity of an OS 
is *entirely* dependent on the licence, but it may be a factor.



>> Only a
>> tiny proportion of people would discover by their own efforts that the
>> source code was available
> 
> No, I tell my friends that source is available, and they can come and
> see me if they want to know more.

That doesn't scale to distributing hundreds of copies of the CD, let 
alone tens of thousands. If you're handing over a single copy to a friend 
(which is the example you gave earlier) then a verbal offer works well, 
and is only a technical breach of the GPL. If you're distributing 
hundreds of copies, I don't believe any such verbal offer is practical.


> This may have been a viable argument
> in 1989 (doubtful) but it's extremely silly today.

So you say.


>>, and only a proportion of them would learn
>> where it was available from. The result in practical terms would be a
>> major decrease in the number of people granted the freedom to modify
>> the source code, and a correspondingly larger decrease in the number of
>> people both free and able to modify the source code.
> 
> I sincerely doubt your dystopian vision, which, like the GPL and many
> laws, is predicated on some outmoded views about how humans interact.
> 
> The reason some people say that the GPL protects the "freedom of the
> code" is because the GPL assumes that code needs to be nurtured, instead
> of taking the viewpoint that, while there may be some freeloaders,
> sharing code is obviously so valuable to most of humanity that it will
> just happen.  We don't live in medieval Europe any more where the rules
> of glassmaking are so secret that you'll be hunted down like a dog if
> you try to leave.  We live in a world where "co- opetition" has been
> shown to be so valuable we had to make up a word for it, and even for
> those secrets that people are willing to kill to keep, we have
> wikileaks.

I admire your optimism, but don't share it.


> Let's face it -- a software freeloader is not the most evil thing in the
> world.  

*A* software freeloader certainly isn't a big problem. Cutting down *a* 
tree is no big deal either, but consider what happened to the people of 
Easter Island, Ethiopia and Haiti when *everyone* did so. The terms of 
the GPL exist to discourage freeloaders, lest everyone does so. The 
obligations it imposes are not onerous by any stretch of the exaggeration.


>> It's not enough to be granted freedom to modify source code in theory,
>> if you know about it, if you can find some hard-to-locate website which
>> may or may not be running. The practicalities are equally important.
> 
> That's another thing.  Even if I downloaded all the source from Ubuntu,
> what assurances do I really have that I have all the source? I could be
> in technical violation of the GPL without even knowing it, even after
> wasting an extra two days grabbing the source.  Best to use Gentoo to be
> sure, and even then, I need to build it twice running strace just to
> make sure that I really built everything.

That's a silly objection to the GPL. When you include an MIT-licenced 
library in your project, you can't be sure that the library wasn't stolen 
from Microsoft and you've therefore accidentally infringed Microsoft's 
copyright. This isn't an argument against the MIT licence any more than 
your hypothetical is an argument against the GPL.



>> In
>> theoretical terms, everyone has the freedom to legally modify and
>> distribute the source code to Microsoft Windows. All you have to do is
>> buy 51% of the stock so as to become majority shareholder, then make
>> sufficient changes to the board of directors so that the new board
>> grants you a licence to do so, then fight off the lawsuits from the
>> rest of the shareholders. Anyone could do it! Not.
> 
> So "everyone" could own 51% of Microsoft?  That means 100% of the shares
> would be around 350,000,000,000%.  Wait, that can't be right, what? :-) 

Obviously not all at once, silly. But "in theory", everyone could become 
the majority shareholder -- there is no law or physical law of nature 
that says "Patrick Maupin is prohibited from being majority shareholder 
of Microsoft".

Anti-competition laws or similar may prevent a person from becoming 
majority shareholder unless they (e.g.) gave up their shares in another 
company, but again, there's nothing stopping them from doing so, if they 
wished.


> Can you come up with a sillier analogy?

I'm sure I could, but you seem to have entirely missed the point that 
such theoretical "freedom" is entirely illusionary, since *in practice* 
very few people actually can partake in it.

 
>> Another, more practical example: here in Australia our government is
>> hell- bent on introducing an ineffective and expensive Internet
>> censorship scheme. It seems that under Australian law, it will be
>> completely legal to circumvent the filter, but our government is
>> investigating ways to make it illegal to tell anyone how to circumvent
>> it. In other words, Australians will have permission to circumvent the
>> nanny filter, but since few people will know this, or know how to do
>> so, it will be a meaningless freedom.
> 
> Yes, that's basically how the DMCA works, and that's evil, and that's
> one of the reasons I sometimes give money to the EFF.  But, you can't
> seriously be comparing making speech a crime and making not speaking a
> crime (or a copyright violation), can you?  Maybe you *did* manage to
> come up with a sillier analogy...

There are situations where not speaking is a crime. If you witness a 
crime, and fail to report it, there are circumstances where you may be 
liable to be persecuted for aiding and abetting.



>> The GPL concerns itself with the *practical* freedom to gain access to
>> source code, not merely the theoretical freedom represented by
>> permission without opportunity.
> 
> No, the GPL is ideologically opposed to anything related to practicality
> (although in practice, its adherents have to bend a bit to avoid being
> made irrelevant, and Linux, the shining success, is led by someone who
> arguably cares not one whit for GPL ideological purity).

And yet Linux is distributed under the GPL, which pretty much sinks your 
argument.


[...]
> But the GPL wording required to enforce what you call a practical
> freedom imposes so many impractical costs that there are probably
> millions of people in the world who have violated this license, in the
> good-faith attempt to spread free software around.

As I admitted earlier, there is an apparent grey area there, at least 
according to the FAQs, but I don't think it is anywhere near as obvious 
as you claim that it is a licence violation.




-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Thu May 13 19:41:47 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 13 May 2010 23:41:47 GMT
Subject: Picking a license
References: 
Message-ID: 

On Thu, 13 May 2010 06:24:04 -0700, Ed Keith wrote:

> --- On Thu, 5/13/10, Lawrence D'Oliveiro
>  wrote:
>>
>> What have you got against LGPL for this purpose? --
>> 
> Most of my clients would not know how to relink a program if their life
> depended on it. And I do not want to put then in DLL hell. So I avoid
> the LGPL.


Are you implying that by distributing your libraries under the MIT or 
Apache licence, no linking is required? That's a cool trick, can you 
explain how it works please?



-- 
Steven


From ethan at stoneleaf.us  Thu May 13 20:12:48 2010
From: ethan at stoneleaf.us (Ethan Furman)
Date: Thu, 13 May 2010 17:12:48 -0700
Subject: Picking a license
In-Reply-To: 
References: 
	
Message-ID: <4BEC9580.1030900@stoneleaf.us>

Steven D'Aprano wrote:
> On Thu, 13 May 2010 06:24:04 -0700, Ed Keith wrote:
> 
>> --- On Thu, 5/13/10, Lawrence D'Oliveiro
>>  wrote:
>>> What have you got against LGPL for this purpose? --
>>>
>> Most of my clients would not know how to relink a program if their life
>> depended on it. And I do not want to put then in DLL hell. So I avoid
>> the LGPL.
> 
> 
> Are you implying that by distributing your libraries under the MIT or 
> Apache licence, no linking is required? That's a cool trick, can you 
> explain how it works please?

I believe he is implying that with MIT or Apache, he is able to do all 
the compiling/linking/generating himself, thus saving his customers the 
effort.

You're a smart man, Steven, surely you could have figured that out?  ;)

~Ethan~


From ethan at stoneleaf.us  Thu May 13 20:12:54 2010
From: ethan at stoneleaf.us (Ethan Furman)
Date: Thu, 13 May 2010 17:12:54 -0700
Subject: Picking a license
In-Reply-To: <7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
References: 	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
Message-ID: <4BEC9586.3070302@stoneleaf.us>

Brendan Abel wrote:
> While I think most of the disagreement in this long thread results
> from different beliefs in what "freedom" means, I wanted to add, that
> most of the responses that argue that the MIT license permits the user
> more freedom than the GPL, suffer from the broken window fallacy.
> This fallacy results from the short-sided-ness of the user base, as it
> is only considering the first generation of derivative works.
> 
> I agree, that under an MIT license, the first generation of derivative
> works have more freedom.  But any extra freedom gained here comes at
> the direct expense of all future generations of derivative software.

You are assuming that _all_ future generations become propriety, then? 
How pessimistic.


> Under a GPL license, it is true that the first generation will have
> less freedom to distribute their software as they would like.  But it
> also ensures that all subsequent generations of derivative works have
> the freedom to access all previous derivative works.

Just because you have the code for the _current_ version of something, 
doesn't mean you have the code for that something three versions ago... 
after all, it may have been modified.


~Ethan~


From info at wingware.com  Thu May 13 20:17:40 2010
From: info at wingware.com (Wingware)
Date: Thu, 13 May 2010 20:17:40 -0400
Subject: ANN: Wing IDE 3.2.7 released
Message-ID: <4BEC96A4.2040905@wingware.com>

Hi,

Wingware has released version 3.2.7 of Wing IDE, an integrated development
environment designed specifically for the Python programming language.

Wing IDE is a cross-platform Python IDE that provides a professional code
editor with vi, emacs, and other key bindings, auto-completion, call tips,
a powerful graphical debugger, version control, unit testing, search, and
many other features.

This release includes the following minor features and improvements:

* Added preference to control mini-search case sensitivity
* Added Debug to Here editor context menu item and Alt-F5 binding
* Fixed parsing of "from package.module import *" statements
* Fixed shared perspectives
* Improved default extension set in Windows file dialogs
* Several VI mode improvements (details in change log)
* Several Templates tool fixes (details in change log)
* Confirm close of Feedback and Bug Report windows
* Fix up and down arrow keys in Debug I/O tool
* Several other minor bug fixes

See the change log at http://wingware.com/pub/wingide/3.2.7/CHANGELOG.txt
for details

*Downloads*

Wing IDE Professional and Wing IDE Personal are commercial software and
require a license to run.  A free trial license can be obtained directly 
from
the product when launched.  Wing IDE 101 can be used free of charge.

Wing IDE Pro 3.2.7        http://wingware.com/downloads/wingide/3.2

Wing IDE Personal 3.2.7   http://wingware.com/downloads/wingide-personal/3.2

Wing IDE 101 3.2.7        http://wingware.com/downloads/wingide-101/3.2

*About Wing IDE*

Wing IDE is an integrated development environment designed specifically for
the Python programming language. It provides powerful editing, testing, and
debugging features that help reduce development and debugging time, cut down
on coding errors, and make it easier to understand and navigate Python code.
Wing IDE can be used to develop Python code for web, GUI, and embedded
scripting applications.

Wing IDE is available in three product levels:  Wing IDE Professional is
the full-featured Python IDE, Wing IDE Personal offers a reduced feature
set at a low price, and Wing IDE 101 is a free simplified version designed
for teaching entry level programming courses with Python.

Version 3.2 of Wing IDE Professional includes the following major features:

* Professional quality code editor with vi, emacs, and other keyboard 
personalities
* Code intelligence for Python:  Auto-completion, call tips, 
goto-definition,
  error indicators, smart indent and rewrapping, and source navigation
* Advanced multi-threaded debugger with graphical UI, command line 
interaction,
  conditional breakpoints, data value tooltips over code, watch tool, and
  externally launched and remote debugging
* Powerful search and replace options including keyboard driven and 
graphical
  UIs, multi-file, wild card, and regular expression search and replace
* Version control integration for Subversion, CVS, Bazaar, git, 
Mercurial, and
  Perforce
* Integrated unit testing with unittest, nose, and doctest frameworks
* Many other features including project manager, bookmarks, code snippets,
  OS command integration, indentation manager, PyLint integration, and 
perspectives
* Extremely configurable and may be extended with Python scripts

Please refer to the feature list at http://wingware.com/wingide/features for
a detailed listing of features by product level.

System requirements are Windows 2000 or later, OS X 10.3.9 or later for 
PPC or
Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit).
Wing IDE supports Python versions 2.0.x through 3.1.x and Stackless Python.

For more information, see http://wingware.com/products

*Purchasing and Upgrading*

Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Version 2.x
licenses cost 1/2 the normal price to upgrade.

Upgrade a 2.x license:     https://wingware.com/store/upgrade

Purchase a 3.x license:    https://wingware.com/store/purchase

-- 

The Wingware Team
Wingware | Python IDE
Advancing Software Development

www.wingware.com



From python.list at tim.thechases.com  Thu May 13 20:18:16 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Thu, 13 May 2010 19:18:16 -0500
Subject: indexing lists/arrays question
In-Reply-To: <994e3852-637d-4bfd-96db-dd2e74c12cd2@e2g2000yqn.googlegroups.com>
References: 			
	<994e3852-637d-4bfd-96db-dd2e74c12cd2@e2g2000yqn.googlegroups.com>
Message-ID: <4BEC96C7.2010602@tim.thechases.com>

On 05/13/2010 12:51 PM, a wrote:
>> If your two arrays are of the same length, you can do things like
>>
>>     a = [2,3,3,4,5,6]
>>     b = ['a', 'b', 'c', 'd', 'e', 'f']
>>
>>     print [m for (n,m) in zip(a,b) if n == 3]
>>
>> and skip the indexes altogether.
>
> mmm, that's clever, thanks.  although i don't know why it works yet.
> at least i found a good user group!

the zip() function takes its parameters and returns a list 
containing paired items from each list:

 >>> print zip(a,b) # using the above-defined a/b
[(2, 'a'), (3, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f')]

The list comprehension then iterates over the elements of that 
list, assigned as (n,m), testing "n" (the numeric value you want 
to test) and returning "m" (the corresponding value in "b")

-tkc





From pavlovevidence at gmail.com  Thu May 13 20:18:47 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Thu, 13 May 2010 17:18:47 -0700 (PDT)
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
Message-ID: <59194ade-46dc-4178-8b76-36038808109b@k2g2000yqe.googlegroups.com>

On May 13, 4:30?pm, Brendan Abel <007bren... at gmail.com> wrote:
> While I think most of the disagreement in this long thread results
> from different beliefs in what "freedom" means, I wanted to add, that
> most of the responses that argue that the MIT license permits the user
> more freedom than the GPL, suffer from the broken window fallacy.
> This fallacy results from the short-sided-ness of the user base, as it
> is only considering the first generation of derivative works.
>
> I agree, that under an MIT license, the first generation of derivative
> works have more freedom. ?But any extra freedom gained here comes at
> the direct expense of all future generations of derivative software.
>
> Under a GPL license, it is true that the first generation will have
> less freedom to distribute their software as they would like. ?But it
> also ensures that all subsequent generations of derivative works have
> the freedom to access all previous derivative works.

I believe the you have the fallacy backwards.

The thing you GPL fanbois refuse to understand or accept is that, in
the real world, a person or company who doesn't want to open source
their "derivative work" will only rarely be forced to by the GPL.
They'll work around it instead, vast majority of the time.  They
could:

1. Derive their work from a project with a license that grants the
user more freedom
2. Reimplment the functionality seperately (*cough* PySide)
3. Ignore the license

And no, a small number of anecdotal counterexamples is not any strong
evidence to the contrary.

On the other hand, those who intended to release their work as open
source are going to do it even if the license is permissive.  The way
some of you GPL fanbois talk you'd think the MIT license prohibitied
open source derivatives.

So, you see, the rights given to users of first generation works (as
you say) are far more important than requiring people who create
"derivatives" to also offer those rights.  Those who intend to do that
will anyways, those who don't intend to will find a way not to.


Carl Banks

PS The word "derivative" is quoted throught because the GPL's
definition of "derivative" is ludicrous and not in accordance any
common defintion of the word.


From python.list at tim.thechases.com  Thu May 13 20:35:59 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Thu, 13 May 2010 19:35:59 -0500
Subject: walk directory & ignore all files/directories begin with '.'
In-Reply-To: 
References: 
Message-ID: <4BEC9AEF.1080907@tim.thechases.com>

On 05/13/2010 12:58 PM, albert kao wrote:
> I want to walk a directory and ignore all the files or directories
> which names begin in '.' (e.g. '.svn').
> Then I will process all the files.
> My test program walknodot.py does not do the job yet.
> Python version is 3.1 on windows XP.
> Please help.
>
> [code]
> #!c:/Python31/python.exe -u
> import os
> import re
>
> path = "C:\\test\\com.comp.hw.prod.proj.war\\bin"
> for dirpath, dirs, files in os.walk(path):
>      print ("dirpath " + dirpath)
>      p = re.compile('\\\.(\w)+$')
>      if p.match(dirpath):
>          continue
>      print ("dirpath " + dirpath)
>      for dir in dirs:
>          print ("dir " + dir)
>          if dir.startswith('.'):
>              continue
>
>          print (files)
>          for filename in files:
>              print ("filename " + filename)
>              if filename.startswith('.'):
>                  continue
>              print ("dirpath filename " + dirpath + "\\" + filename)
>      	    # process the files here
> [/code]
>
> C:\python>walknodot.py
> dirpath C:\test\com.comp.hw.prod.proj.war\bin
> dirpath C:\test\com.comp.hw.prod.proj.war\bin
> dir .svn
> dir com
> []
> dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> ...
>
> I do not expect C:\test\com.comp.hw.prod.proj.war\bin\.svn to appear
> twice.

Note that the first time .svn appears, it's as "dir .svn" while 
the second time it appears, it's via "dirpath ...\.svn"

If you don't modify the list of dirs in place, os.walk will 
descend into all the dirs by default.  (Also, you shouldn't mask 
the built-in dir() function by naming your variables "dir")

While it can be detected with regexps, I like the clarity of just 
using ".startswith()" on the strings, producing something like:

   for curdir, dirs, files in os.walk(root):
     # modify "dirs" in place to prevent
     # future code in os.walk from seeing those
     # that start with "."
     dirs[:] = [d for d in dirs if not d.startswith('.')]

     print curdir
     for f in files:
       if f.startswith('.'): continue
       print (os.path.join(curdir, f))

-tkc





From e_d_k at yahoo.com  Thu May 13 21:26:17 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 18:26:17 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <737293.15031.qm@web58702.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Steven D'Aprano  wrote:

> From: Steven D'Aprano 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 7:41 PM
> On Thu, 13 May 2010 06:24:04 -0700,
> Ed Keith wrote:
> 
> > --- On Thu, 5/13/10, Lawrence D'Oliveiro
> > 
> wrote:
> >>
> >> What have you got against LGPL for this purpose?
> --
> >> 
> > Most of my clients would not know how to relink a
> program if their life
> > depended on it. And I do not want to put then in DLL
> hell. So I avoid
> > the LGPL.
> 
> 
> Are you implying that by distributing your libraries under
> the MIT or 
> Apache licence, no linking is required? That's a cool
> trick, can you 
> explain how it works please?
> 
> 
> 
> -- 
> Steven
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Normally I link it for them. As I read the LGPL, if I use any LGPLed code I need to teach the client how to link the software against any possible future version of the LGPLed library. 

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Thu May 13 21:32:31 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 18:32:31 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <59194ade-46dc-4178-8b76-36038808109b@k2g2000yqe.googlegroups.com>
Message-ID: <444360.64811.qm@web58705.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Carl Banks  wrote:

> 
> The thing you GPL fanbois refuse to understand or accept is
> that, in
> the real world, a person or company who doesn't want to
> open source
> their "derivative work" will only rarely be forced to by
> the GPL.
> They'll work around it instead, vast majority of the
> time.? They
> could:
> 
> 1. Derive their work from a project with a license that
> grants the
> user more freedom
> 2. Reimplment the functionality seperately (*cough*
> PySide)
> 3. Ignore the license

I think you have over looked the most common, keep the software in house and not let anyone else use it. This way you are in full compliance with the GPL. If you let someone else use the software that you need to talk to a lawyer, or GPL your software.

> 
> And no, a small number of anecdotal counterexamples is not
> any strong
> evidence to the contrary.
> 
> On the other hand, those who intended to release their work
> as open
> source are going to do it even if the license is
> permissive.? The way
> some of you GPL fanbois talk you'd think the MIT license
> prohibitied
> open source derivatives.

If I use MIT licensed code, I can give someone else access to the program with out binding them to the legal restrictions of the GPL. 

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com


 


      


From e_d_k at yahoo.com  Thu May 13 21:37:31 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 18:37:31 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
Message-ID: <925552.63628.qm@web58705.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Brendan Abel <007brendan at gmail.com> wrote:

> From: Brendan Abel <007brendan at gmail.com>
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 7:30 PM
> While I think most of the
> disagreement in this long thread results
> from different beliefs in what "freedom" means, I wanted to
> add, that
> most of the responses that argue that the MIT license
> permits the user
> more freedom than the GPL, suffer from the broken window
> fallacy.
> This fallacy results from the short-sided-ness of the user
> base, as it
> is only considering the first generation of derivative
> works.
> 
> I agree, that under an MIT license, the first generation of
> derivative
> works have more freedom.? But any extra freedom gained
> here comes at
> the direct expense of all future generations of derivative
> software.
> 
> Under a GPL license, it is true that the first generation
> will have
> less freedom to distribute their software as they would
> like.? But it
> also ensures that all subsequent generations of derivative
> works have
> the freedom to access all previous derivative works.
> 
> I also want to add that I think the GPL v3 has exceeded
> this
> fundamental concept.? GPL v2 really embodies this
> meaning of "freedom".
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I ALWAYS give my client my source code. But I do not want to bind them to the requirements of the GPL, I want them to be free do do what they want with the program, so I never incorporate any GPLed code in my projects.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From aahz at pythoncraft.com  Thu May 13 21:56:28 2010
From: aahz at pythoncraft.com (Aahz)
Date: 13 May 2010 18:56:28 -0700
Subject: Picking a license
References: 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-b
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
Message-ID: 

In article <2d625c61-7a94-4c71-8953-69c3b3c76d07 at k29g2000yqh.googlegroups.com>,
Paul Boddie   wrote:
>
>All my position has ever been is this:
>
>A copyrighted work denies recipients virtually all rights to do stuff
>with that work, such as modify and redistribute it. Copyleft licences
>grant some privileges and uphold some obligations in order to ensure
>that these privileges are universally maintained in all forms and
>extensions of the work. Permissive licences grant more privileges to
>immediate recipients but do not uphold as many obligations.
>
>You rejected the suggestion that people using permissive licences
>afford users fewer privileges than those using copyleft licences, yet
>on balance when considering all forms and extensions of the work, they
>do. And the only such privilege that the copyleft licences withholds
>from recipients is that of withholding any other privilege from others
>who receive the work.

IMO this only makes sense if one agrees that people should not be allowed
to sell software for money.  Absent that agreement, your argument about
freedom seems rather limited.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From pmaupin at gmail.com  Thu May 13 22:10:09 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 19:10:09 -0700 (PDT)
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
Message-ID: 

On May 13, 6:30?pm, Brendan Abel <007bren... at gmail.com> wrote:
> While I think most of the disagreement in this long thread results
> from different beliefs in what "freedom" means, I wanted to add, that
> most of the responses that argue that the MIT license permits the user
> more freedom than the GPL, suffer from the broken window fallacy.
> This fallacy results from the short-sided-ness of the user base, as it
> is only considering the first generation of derivative works.

The broken window fallacy is about labor that could have been spent
elsewhere if someone else had done something differently.  The only
time that comes into play in my programming life is when I have to
recode something that is nominally available under the GPL, so I'm not
sure this is really making the point you think it is.

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 22:12:29 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 19:12:29 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
Message-ID: 

On May 13, 6:39 pm, Steven D'Aprano
 wrote:
> On Thu, 13 May 2010 08:06:52 -0700, Patrick Maupin wrote:
> > If I download an Ubuntu
> > ISO, burn it and give it away (let's say I give away 100 copies, just to
> > remove the fair use defense), then I have violated the GPL.  I provided
> > chapter and verse on this; go look it up.
>
> I'm sorry, I can't see where you have provided "chapter and verse", or
> even a URL.

In the original message, I wrote "In the case of GPL v3, for example,
Ubuntu lets me download code under 6d, so if I download it and burn
it, I would have to use 6a or 6b; if I had actually received a CD from
Ubuntu, I might be able to use 6c, but not if I downloaded it."  I
thought it was clear those were references to the license clauses.

> >> If you compiled the CD yourself, and failed to provide a written offer
> >> on the CD, then yes absolutely you would be in violation of the licence
> >> terms, and shame on you.
>
> > Not relevant.
>
> You didn't specify whether the "Linux CD" you were distributing was a
> mere copy of an existing CD , or one you created yourself, so you will
> pardon me for covering both possibilities.

Well, in the section I just quoted, I did mention "Ubuntu"...

> >> The GPL doesn't require you to force source code on those who don't
> >> want it, but it does require you to make it available if they ask, and
> >> for you to notify them appropriately of this fact. You don't even have
> >> to explicitly tell your friend he can have the source code. You just
> >> have to make sure that the written offer is available on the disk you
> >> give him.
>
> > There is no written offer on the disk, because I burned it from Ubuntu's
> > repository.  It really is that simple -- if I give away copies I've made
> > of Ubuntu, I've violated the GPL.
>
> No, I think this use-case would count as "propagation without conveying",
> since you are merely acting as a mechanical proxy between your friend(s)
> and Ubuntu.

No, I'm actually creating a copy and distributing it (in GPL v3
terminology, conveying it), especially since my friends don't
specifically ask for Ubuntu, and I'm foisting it off on them
(especially if I burn 10 CDs at a time so I have one if I need it).
GPL v2 also has similar rules, and there's lots of v2 licensed
software on the Ubuntu CD.

> I will admit that the GPL FAQs are not as clear about this matter as they
> should be.

I think it's quite clear, although a bit of a tedious slog.  But since
you want a URL, try this:  http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary

> > Unless you can cite some authority
> > that tells me I'm wrong and gives real reasons.  I actually quoted
> > chapter and verse from the license, but you chose to ignore that and
> > make unsubstantiated claims.
>
> I'm sorry, I can't find where you have quoted "chapter and verse" from
> the licence, so I can't comment.

Well, I just re-copied what I posted, and added a URL from the FAQ.

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 22:49:33 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 19:49:33 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
Message-ID: <89297458-28f7-4324-a804-8d2897477ee9@k2g2000yqe.googlegroups.com>

On May 13, 6:39 pm, Steven D'Aprano
 wrote:
> On Thu, 13 May 2010 08:06:52 -0700, Patrick Maupin wrote:

[...]

> >> Only a
> >> tiny proportion of people would discover by their own efforts that the
> >> source code was available
>
> > No, I tell my friends that source is available, and they can come and
> > see me if they want to know more.
>
> That doesn't scale to distributing hundreds of copies of the CD, let
> alone tens of thousands.

Sure it does.  Each one of those CD distributions is friend-to-
friend.  And if my friend gives a CD to someone interested in
programming, I might wind up with a new friend.

> If you're handing over a single copy to a friend
> (which is the example you gave earlier) then a verbal offer works well,
> and is only a technical breach of the GPL. If you're distributing
> hundreds of copies, I don't believe any such verbal offer is practical.

Right.  And lots of Linux Users Groups are in breach of the GPL on
many software packages.  But guess what?  It really doesn't matter,
because the source is sitting there on the internet, for the taking.

> > This may have been a viable argument
> > in 1989 (doubtful) but it's extremely silly today.
>
> So you say.

Yes, that what's I believe.  More anon.

>
> >>, and only a proportion of them would learn
> >> where it was available from. The result in practical terms would be a
> >> major decrease in the number of people granted the freedom to modify
> >> the source code, and a correspondingly larger decrease in the number of
> >> people both free and able to modify the source code.
>
> > I sincerely doubt your dystopian vision, which, like the GPL and many
> > laws, is predicated on some outmoded views about how humans interact.
>
> > The reason some people say that the GPL protects the "freedom of the
> > code" is because the GPL assumes that code needs to be nurtured, instead
> > of taking the viewpoint that, while there may be some freeloaders,
> > sharing code is obviously so valuable to most of humanity that it will
> > just happen.  We don't live in medieval Europe any more where the rules
> > of glassmaking are so secret that you'll be hunted down like a dog if
> > you try to leave.  We live in a world where "co- opetition" has been
> > shown to be so valuable we had to make up a word for it, and even for
> > those secrets that people are willing to kill to keep, we have
> > wikileaks.
>
> I admire your optimism, but don't share it.

I understand that.  There are a lot of people out there who will
attempt to profit off of other peoples' labor without any value-add.
But it's getting more difficult to do that.  A key element in any kind
of arbitrage is imperfect communications, and the internet is rapidly
perfecting almost all communications.

> > Let's face it -- a software freeloader is not the most evil thing in the
> > world.
>
> *A* software freeloader certainly isn't a big problem. Cutting down *a*
> tree is no big deal either, but consider what happened to the people of
> Easter Island, Ethiopia and Haiti when *everyone* did so.

In a different context, you would probably be arguing about how
software is not like physical goods, and nobody is made poorer if I
make my own copy of it.

> The terms of
> the GPL exist to discourage freeloaders, lest everyone does so. The
> obligations it imposes are not onerous by any stretch of the exaggeration.

Well, you still don't believe that if I download a CD and give it to a
friend I legally have to download a DVD's worth of source to go with
it :-)  (Mind you, I don't believe for a minute anybody would be
stupid enough to try to sue over that, or that copying a few CDs
wouldn't be covered by fair use, but I *do* believe that the license
attempts to require the source to be distributed.)

> >> It's not enough to be granted freedom to modify source code in theory,
> >> if you know about it, if you can find some hard-to-locate website which
> >> may or may not be running. The practicalities are equally important.
>
> > That's another thing.  Even if I downloaded all the source from Ubuntu,
> > what assurances do I really have that I have all the source? I could be
> > in technical violation of the GPL without even knowing it, even after
> > wasting an extra two days grabbing the source.  Best to use Gentoo to be
> > sure, and even then, I need to build it twice running strace just to
> > make sure that I really built everything.
>
> That's a silly objection to the GPL. When you include an MIT-licenced
> library in your project, you can't be sure that the library wasn't stolen
> from Microsoft and you've therefore accidentally infringed Microsoft's
> copyright. This isn't an argument against the MIT licence any more than
> your hypothetical is an argument against the GPL.

Well, OK, it's a bit silly, but not really the same as your example,
and certainly much more likely.  I have never downloaded any FOSS that
had any licensing issues I know of (and trust me, SCO tried really
hard on that front :-), but I have often downloaded .deb files and
tried to build something, but the dependencies were foobar.  All I'm
saying is that, to follow the letter of the license I'm handed (not
some theoretical other license that someone upstream violated) along
with the code is easy with MIT, but might be technically practically
impossible with a binary distribution of GPLed code, as with Ubuntu.

>
> >> In
> >> theoretical terms, everyone has the freedom to legally modify and
> >> distribute the source code to Microsoft Windows. All you have to do is
> >> buy 51% of the stock so as to become majority shareholder, then make
> >> sufficient changes to the board of directors so that the new board
> >> grants you a licence to do so, then fight off the lawsuits from the
> >> rest of the shareholders. Anyone could do it! Not.
>
> > So "everyone" could own 51% of Microsoft?  That means 100% of the shares
> > would be around 350,000,000,000%.  Wait, that can't be right, what? :-)
>
> Obviously not all at once, silly. But "in theory", everyone could become
> the majority shareholder -- there is no law or physical law of nature
> that says "Patrick Maupin is prohibited from being majority shareholder
> of Microsoft".

Yeah, but I think if I put my lonely little projects out there, that
practically speaking, everybody has a better chance of being able to
download the code to those, no matter what the license, than I have a
chance of coming up with the scratch to buy Microsoft :-)

> Anti-competition laws or similar may prevent a person from becoming
> majority shareholder unless they (e.g.) gave up their shares in another
> company, but again, there's nothing stopping them from doing so, if they
> wished.
>
> > Can you come up with a sillier analogy?
>
> I'm sure I could, but you seem to have entirely missed the point that
> such theoretical "freedom" is entirely illusionary, since *in practice*
> very few people actually can partake in it.

No, I saw your point, and completely disagree with it.  My code is out
there.  Sure, people can wrap *their* proprietary stuff around it, but
other people can still get *my* stuff, so I really, truly, don't see
the problem here.  Again, it would be different if *my* stuff were so
fantastically important that I was going to make a mint off of it, but
frankly if I don't see that it is, but someone else sees some
intrinsic value and manages to make a mint off it, perhaps the world
is a better place.

> >> Another, more practical example: here in Australia our government is
> >> hell- bent on introducing an ineffective and expensive Internet
> >> censorship scheme. It seems that under Australian law, it will be
> >> completely legal to circumvent the filter, but our government is
> >> investigating ways to make it illegal to tell anyone how to circumvent
> >> it. In other words, Australians will have permission to circumvent the
> >> nanny filter, but since few people will know this, or know how to do
> >> so, it will be a meaningless freedom.
>
> > Yes, that's basically how the DMCA works, and that's evil, and that's
> > one of the reasons I sometimes give money to the EFF.  But, you can't
> > seriously be comparing making speech a crime and making not speaking a
> > crime (or a copyright violation), can you?  Maybe you *did* manage to
> > come up with a sillier analogy...
>
> There are situations where not speaking is a crime. If you witness a
> crime, and fail to report it, there are circumstances where you may be
> liable to be persecuted for aiding and abetting.

Usually, you have to take active measures to conceal the crime, not
just "not speak" about it:  http://en.wikipedia.org/wiki/Misprision_of_felony

> >> The GPL concerns itself with the *practical* freedom to gain access to
> >> source code, not merely the theoretical freedom represented by
> >> permission without opportunity.
>
> > No, the GPL is ideologically opposed to anything related to practicality
> > (although in practice, its adherents have to bend a bit to avoid being
> > made irrelevant, and Linux, the shining success, is led by someone who
> > arguably cares not one whit for GPL ideological purity).
>
> And yet Linux is distributed under the GPL, which pretty much sinks your
> argument.

Not sure how you come to that conclusion.  For example, while Linux is
arguably strong enough to start kicking out binary drivers now, at the
beginning that would have been its death-knell, and that's probably
how RMS would have proceeded.  The point is, Torvalds views the
license as a good starting point for a set of behaviors, but he made
very clear the kind of behaviors he was interested in enforcing.  See,
for example:  http://www.linuxfordevices.com/c/a/News/Torvalds-quashes-binary-kernel-module-revolt/

Interestingly, one of the problems with Linux that has more to do with
the size of the project and pace of development than anything else, is
that people are more worried that their contributions aren't going to
make it into the kernel, rather than that they have to give them back
to the kernel.

>
> [...]
>
> > But the GPL wording required to enforce what you call a practical
> > freedom imposes so many impractical costs that there are probably
> > millions of people in the world who have violated this license, in the
> > good-faith attempt to spread free software around.
>
> As I admitted earlier, there is an apparent grey area there, at least
> according to the FAQs, but I don't think it is anywhere near as obvious
> as you claim that it is a licence violation.

Well, take another look.  I would be interested in any evidence you
can find that shows otherwise.

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 22:58:16 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 19:58:16 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
Message-ID: <84a26d03-03b3-47d9-a1f9-107470b87c75@k2g2000yqe.googlegroups.com>

On May 13, 6:39 pm, Steven D'Aprano
 wrote:
> On Thu, 13 May 2010 08:06:52 -0700, Patrick Maupin wrote:

> Perhaps the Apache model doesn't work quite as well as you think?

Apparently it's 66 percent of the web servers for the million busiest
sites,  and presumably 65 for the next million, etc...

When I look at the netcraft graphs, the only thing that seemed to
cause a decline before last year was Microsoft and their marketing
muscle.  For example, they incentivize godaddy and others to run all
the parked sites on IIS.

In the graphs, there was a sudden spike in "other" at the beginning of
last year. My gut tells me this is ROR, django, and other similarly
permissively licensed software.  In any case, back when GPL take-up
was quite small, RMS was very dismissive of market numbers, but I
really have to ask:  where are all the GPL-licensed web servers?

> As far as not-so-niche software goes, the GPLed Linux OS is far more
> popular on the desktop than FreeBSD and OpenBSD together, and about equal
> in popularity to Mac OS. I'm not suggesting that the popularity of an OS
> is *entirely* dependent on the licence, but it may be a factor.

Well, despite what others have said here, I think the lingering
effects of the Unix lawsuit helped give Linux a push.  Torvalds
himself was a huge factor, and I'm willing to concede that the GPL
didn't hinder the quest for contributors.

The fact is that, in reality (Darwinian competition to determine the
best architecture aside) it's very nice to have a single primary point
of focus for an OS, and Unix was perceived to be hopelessly fragmented
by many would-be contributors who wouldn't know where to start.

I also firmly believe, as I have stated before, that the GPL is a much
more commercial license.  If you want to make money off something,
then, no doubt, GPL keeps your competitors from being able to take
what you wrote and redistribute it as closed source.  But, frankly I
view that as more of a business issue than a moral issue.

In any case, if you want to look, as a marketer would, at TAM (Total
Available Market), free software is completely floundering in the OS
space, and permissively licensed software owns the serious web server
space.

Regards,
Pat


From ldo at geek-central.gen.new_zealand  Thu May 13 23:03:32 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 15:03:32 +1200
Subject: Picking a license
References: 
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
Message-ID: 

In message <72888d2c-4b1a-4b08-a3aa-
f4021d2ed646 at e2g2000yqn.googlegroups.com>, Patrick Maupin wrote:

> If I download an Ubuntu ISO, burn it and give it away (let's say I give
> away 100 copies, just to remove the fair use defense), then I have
> violated the GPL.  I provided chapter and verse on this; go look it up.

I have looked it up , and sections 
3b or 3c would seem to apply. Or alternatively 
, 6b or 6c. If the source you got it 
from didn?t violate the GPL, then obviously you didn?t either.


From ldo at geek-central.gen.new_zealand  Thu May 13 23:04:57 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 15:04:57 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> The claim is being made that [the GPL] restricts freedom.

What about the ?freedom? to restrict other people?s freedom? Should that be 
restricted or not?


From ldo at geek-central.gen.new_zealand  Thu May 13 23:06:08 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 15:06:08 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> Assertion I:
>    If person A is free to do more than person B, then person A has
>    more freedom then person B.
> 
> Assertion II:
>    If person A is free do perform an action person B is not free to
>    perform then person A is free to do more than person B.
> 
> Assertion III:
>   If person B is restricted in some way that person A is not them Person A
>   is free to do something Person B is not free to do.
> 
> Conclusion:
>   If person B is more resticted than Peston A, Person A has mor freedom
>   than person B.
> 
> Which step in this reasoning do you disagree with?

Under the GPL, everybody has exactly the same freedoms. So which of your 
assertions is supposedly a criticism of the GPL?


From ldo at geek-central.gen.new_zealand  Thu May 13 23:07:26 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 15:07:26 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> On Thu, 5/13/10, Lawrence D'Oliveiro
>  wrote:
> 
>> In message ,
>> Ed Keith wrote:
>> 
>>> So if you want me to even consider using your library
>>> do not use GPL, or LGPL.
>> 
>> What have you got against LGPL for this purpose?
> 
> Most of my clients would not know how to relink a program if their life
> depended on it. And I do not want to put then in DLL hell. So I avoid the
> LGPL.

How exactly does the LGPL lead to a requirement to ?relink??


From pmaupin at gmail.com  Thu May 13 23:35:25 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 20:35:25 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: <1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>

On May 13, 10:07?pm, Lawrence D'Oliveiro  wrote:

> How exactly does the LGPL lead to a requirement to ?relink??

I think this might be a misconception, but I'm not 100% sure.  Since
Ed gives his customers full source code, there may not be the
requirement to directly provide the ability to relink, because "The
?Corresponding Application Code? for a Combined Work means the object
code and/or source code for the Application." and section 4d0 requires
you to "permit the user to recombine or relink" where "recombine"
isn't defined directly (perhaps in the underlying GPL?)

Nonetheless, all the dotting of i's and crossing of t's to satisfy
section 4 and the underlying GPL probably require a lawyer to check
your source code distribution.  For example, what is "prominent
notice"?

And I love the gem at 4e:  "Provide Installation Information, but only
if you would otherwise be required to provide such information under
section 6 of the GNU GPL, and only to the extent that such information
is necessary to install and execute a modified version of the Combined
Work produced by recombining or relinking the Application with a
modified version of the Linked Version. (If you use option 4d0, the
Installation Information must accompany the Minimal Corresponding
Source and Corresponding Application Code. If you use option 4d1, you
must provide the Installation Information in the manner specified by
section 6 of the GNU GPL for conveying Corresponding Source.)"

I mean, it's in English and very technically precise, but if you
follow all the references, you quickly come to realize that the
license is a "patch" to the GPL.  It was deliberately made in patch
format to make it smaller, but as we all know, reading source code and
the accompanying patch is almost always more difficult than reading
the patched source.

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 23:39:54 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 20:39:54 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
Message-ID: 

On May 13, 10:03?pm, Lawrence D'Oliveiro  wrote:
> In message <72888d2c-4b1a-4b08-a3aa-
>
> f4021d2ed... at e2g2000yqn.googlegroups.com>, Patrick Maupin wrote:
> > If I download an Ubuntu ISO, burn it and give it away (let's say I give
> > away 100 copies, just to remove the fair use defense), then I have
> > violated the GPL. ?I provided chapter and verse on this; go look it up.
>
> I have looked it up , and sections
> 3b or 3c would seem to apply. Or alternatively
> , 6b or 6c. If the source you got it
> from didn?t violate the GPL, then obviously you didn?t either.

I don't think that's necessarily true.  As I've posted before:  "In
the
case of GPL v3, for example, Ubuntu lets me download code under 6d, so
if I download it and burn it, I would have to use 6a or 6b; if I had
actually received a CD from Ubuntu, I might be able to use 6c, but not
if I downloaded it."

That's because to use 6c, the initial underlying distribution had to
be done with 6b, not 6d.  Also the FAQ is very clear:
http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 23:43:44 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 20:43:44 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: <2ff3643b-6ef1-4471-8438-dcba0dc93c24@a21g2000yqn.googlegroups.com>

On May 13, 10:04?pm, Lawrence D'Oliveiro  wrote:
> In message , Ed Keith
> wrote:
>
> > The claim is being made that [the GPL] restricts freedom.
>
> What about the ?freedom? to restrict other people?s freedom? Should that be
> restricted or not?

It's interesting that some people don't like the comparison of the
Free Software movement to a religion, yet the main argument of the
movement, and the deliberate co-opting of words like "Free" and "Free
Software" are done in an attempt to guilt others into accepting RMS's
vision of morality.

He's perfectly welcome have that vision.  But I don't let it affect my
own moral compass -- I reject it as just another post-modern religion,
AKA cult.

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 23:45:07 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 20:45:07 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: <2b17ee77-0e49-4a97-994c-7582f86c0ba9@r34g2000yqj.googlegroups.com>

On May 13, 10:06?pm, Lawrence D'Oliveiro  wrote:
> In message , Ed Keith
> wrote:
>
>
>
> > Assertion I:
> > ? ?If person A is free to do more than person B, then person A has
> > ? ?more freedom then person B.
>
> > Assertion II:
> > ? ?If person A is free do perform an action person B is not free to
> > ? ?perform then person A is free to do more than person B.
>
> > Assertion III:
> > ? If person B is restricted in some way that person A is not them Person A
> > ? is free to do something Person B is not free to do.
>
> > Conclusion:
> > ? If person B is more resticted than Peston A, Person A has mor freedom
> > ? than person B.
>
> > Which step in this reasoning do you disagree with?
>
> Under the GPL, everybody has exactly the same freedoms. So which of your
> assertions is supposedly a criticism of the GPL?

That's absolutely not true.  For a start, the original author can dual-
license.  This is not a theoretical issue -- it is a multi-million
dollar issue.

Regards,
Pat


From half.italian at gmail.com  Fri May 14 00:54:11 2010
From: half.italian at gmail.com (Sean DiZazzo)
Date: Thu, 13 May 2010 21:54:11 -0700 (PDT)
Subject: client to upload big files via https and get progress info
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	 <4BEC2B49.7060007@free.fr>
Message-ID: <4cbd946d-5b24-46dd-acdc-d19414fa7ffc@11g2000prw.googlegroups.com>

On May 13, 9:39?am, News123  wrote:
> Hi Aaaz,
>
> Aahz wrote:
> > In article <4bea6b50$0$8925$426a7... at news.free.fr>,
> > News123 ? wrote:
> >> I'd like to perform huge file uploads via https.
> >> I'd like to make sure,
> >> - that I can obtain upload progress info (sometimes the nw is very slow)
> >> - that (if the file exceeds a certain size) I don't have to
> >> ?read the entire file into RAM.
>
> > Based on my experience with this, you really need to send multiple
> > requests (i.e. "chunking"). ?There are ways around this (you can look
> > into curl's resumable uploads), but you will need to maintain state no
> > matter what, and I think that chunking is the best/simplest.
>
> I agree I need ?chunking. (the question is just on which level of the
> protocol)
>
> I just don't know how to make a chunkwise file upload or what library is
> best.
>
> Can you recommend any libraries or do you have a link to an example?
>
> I'd like to avoid to make separate https post requests for the chunks
> (at least if the underlying module does NOT support keep-alive connections)
>
> I made some tests with high level chunking (separate sequential https
> post requests).
> What I noticed is a rather high penalty in data throughput.
> The reason is probably, that each request makes its own https connection
> and that either the NW driver or the TCP/IP stack doesn't allocate
> enough band width to my request.
>
> Therefore I'd like to do the chunking on a 'lower' level.
> One option would be to have a https module, which supports keep-alive,
>
> the other would be ?to have a library, which creates a http post body
> chunk by chunk.
>
> What do others do for huge file uploads
> The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )
>
> N

You could also just send the file in one big chunk and give yourself
another avenue to read the size of the file on the server.  Maybe a
webservice that you call with the name of the file that returns it's
percent complete, or it could just return bytes on disk and you do the
math on the client side.  Then you just forget about the transfer and
query the file size whenever you want to know...or on a schedule.

~Sean


From half.italian at gmail.com  Fri May 14 01:01:55 2010
From: half.italian at gmail.com (Sean DiZazzo)
Date: Thu, 13 May 2010 22:01:55 -0700 (PDT)
Subject: client to upload big files via https and get progress info
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	 <4BEC2B49.7060007@free.fr>
	<4cbd946d-5b24-46dd-acdc-d19414fa7ffc@11g2000prw.googlegroups.com>
Message-ID: 

On May 13, 9:54?pm, Sean DiZazzo  wrote:
> On May 13, 9:39?am, News123  wrote:
>
>
>
> > Hi Aaaz,
>
> > Aahz wrote:
> > > In article <4bea6b50$0$8925$426a7... at news.free.fr>,
> > > News123 ? wrote:
> > >> I'd like to perform huge file uploads via https.
> > >> I'd like to make sure,
> > >> - that I can obtain upload progress info (sometimes the nw is very slow)
> > >> - that (if the file exceeds a certain size) I don't have to
> > >> ?read the entire file into RAM.
>
> > > Based on my experience with this, you really need to send multiple
> > > requests (i.e. "chunking"). ?There are ways around this (you can look
> > > into curl's resumable uploads), but you will need to maintain state no
> > > matter what, and I think that chunking is the best/simplest.
>
> > I agree I need ?chunking. (the question is just on which level of the
> > protocol)
>
> > I just don't know how to make a chunkwise file upload or what library is
> > best.
>
> > Can you recommend any libraries or do you have a link to an example?
>
> > I'd like to avoid to make separate https post requests for the chunks
> > (at least if the underlying module does NOT support keep-alive connections)
>
> > I made some tests with high level chunking (separate sequential https
> > post requests).
> > What I noticed is a rather high penalty in data throughput.
> > The reason is probably, that each request makes its own https connection
> > and that either the NW driver or the TCP/IP stack doesn't allocate
> > enough band width to my request.
>
> > Therefore I'd like to do the chunking on a 'lower' level.
> > One option would be to have a https module, which supports keep-alive,
>
> > the other would be ?to have a library, which creates a http post body
> > chunk by chunk.
>
> > What do others do for huge file uploads
> > The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )
>
> > N
>
> You could also just send the file in one big chunk and give yourself
> another avenue to read the size of the file on the server. ?Maybe a
> webservice that you call with the name of the file that returns it's
> percent complete, or it could just return bytes on disk and you do the
> math on the client side. ?Then you just forget about the transfer and
> query the file size whenever you want to know...or on a schedule.
>
> ~Sean

oops...that doesn't help with the other requirements.  My suggestion
is to not use https.  I don't think it was created to move around
large pieces of data.  Lots of small pieces rather.  SFTP?


From user at example.net  Fri May 14 01:37:38 2010
From: user at example.net (J.O. Aho)
Date: Fri, 14 May 2010 07:37:38 +0200
Subject: client to upload big files via https and get progress info
In-Reply-To: <4BEC2B49.7060007@free.fr>
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	 <4BEC2B49.7060007@free.fr>
Message-ID: <8545t3F8mtU1@mid.individual.net>

News123   wrote:

> What do others do for huge file uploads
> The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )

Those cases where I have had to move big files it's been scp on those cases
where you just have to push a new file, in cases where it's a question of
keeping two directories synced, then it's rsync over ssh.
The later one I have never done in python.


-- 

  //Aho


From steve at REMOVE-THIS-cybersource.com.au  Fri May 14 01:59:04 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 14 May 2010 05:59:04 GMT
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
	<59194ade-46dc-4178-8b76-36038808109b@k2g2000yqe.googlegroups.com>
Message-ID: <4bece6a8$0$8761$c3e8da3@news.astraweb.com>

On Thu, 13 May 2010 17:18:47 -0700, Carl Banks wrote:

> The thing you GPL fanbois refuse to understand or accept is that, in the
> real world, a person or company who doesn't want to open source their
> "derivative work" will only rarely be forced to by the GPL. They'll work
> around it instead, vast majority of the time.  They could:
> 
> 1. Derive their work from a project with a license that grants the user
> more freedom
> 2. Reimplment the functionality seperately (*cough* PySide) 

Yes. So what? In what possible way is this an argument against the GPL?

If I offer to mow your lawn for $20, and you refuse, I don't have to 
force my services onto you. You can mow your lawn yourself, or find 
somebody who will do it for $10, or find some kind generous soul who will 
do it for free under an MIT licence.

If you don't want the obligations of the GPL, nobody is going to force 
you to distribute or derive from the GPLed software. If you're not 
willing to meet my conditions to use my software, then I don't want you 
using my software. Go write your own, or find somebody else who will do 
it for a fee, or for free. What you see as a disadvantage of the GPL is a 
feature, not a bug.

You seem to be under the impression that the only public good developers 
should care about is maximising the number of people who create 
derivative works from your project. That's obviously not so in the real 
world, where vast numbers of developers release software under closed-
source licences, or don't release it to the public at all, and it's 
certainly not the case for people who use the GPL. The FSF even has a FAQ 
about that exact point.



> 3. Ignore the license

This is a crime under copyright law, and there have been many instances 
of companies who thought they could ignore the GPL learning different.


-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Fri May 14 02:08:30 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 14 May 2010 06:08:30 GMT
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
	
Message-ID: <4bece8de$0$8761$c3e8da3@news.astraweb.com>

On Thu, 13 May 2010 19:10:09 -0700, Patrick Maupin wrote:

> The broken window fallacy is about labor that could have been spent
> elsewhere if someone else had done something differently.  The only time
> that comes into play in my programming life is when I have to recode
> something that is nominally available under the GPL, so I'm not sure
> this is really making the point you think it is.

You've never had to recode something because it was nominally available 
under a proprietary licence that you (or your client) was unwilling to 
use? Lucky you!

The GPL ensures that once software has entered the commons (and therefore 
available for all), it can never be removed from the commons. The MIT 
licence does not. Now, you might argue that in practice once software is 
released under an MIT licence, it is unlikely to ever disappear from the 
commons. Well, perhaps, but if so, that's despite and not because of the 
licence.

In practice, I believe most MIT-licenced code never even makes it into 
the commons in the first place. I'm willing to predict that the majority 
of code you've written for paying customers (as opposed to specifically 
for open source projects) has disappeared into their code base, never to 
be seen by anyone outside of the company. Am I right?


-- 
Steven


From pavlovevidence at gmail.com  Fri May 14 03:08:06 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 14 May 2010 00:08:06 -0700 (PDT)
Subject: Picking a license
References: 
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com> 
	<59194ade-46dc-4178-8b76-36038808109b@k2g2000yqe.googlegroups.com> 
	<4bece6a8$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <804512fb-e9ac-4284-a577-84e609531e06@s4g2000prh.googlegroups.com>

On May 13, 10:59?pm, Steven D'Aprano  wrote:
> On Thu, 13 May 2010 17:18:47 -0700, Carl Banks wrote:
> > The thing you GPL fanbois refuse to understand or accept is that, in the
> > real world, a person or company who doesn't want to open source their
> > "derivative work" will only rarely be forced to by the GPL. They'll work
> > around it instead, vast majority of the time. ?They could:
>
> > 1. Derive their work from a project with a license that grants the user
> > more freedom
> > 2. Reimplment the functionality seperately (*cough* PySide)
>
> Yes. So what? In what possible way is this an argument against the GPL?

[snip a bunch of crap I don't care about]


It's not.  It's an argument that the GPL doesn't do much good.

Arguments against the GPL are found elsewhere in this thread, I don't
need to repeat them here.


Carl Banks


From news1234 at free.fr  Fri May 14 03:19:20 2010
From: news1234 at free.fr (News123)
Date: Fri, 14 May 2010 09:19:20 +0200
Subject: client to upload big files via https and get progress info
In-Reply-To: 
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	 <4BEC2B49.7060007@free.fr>
	<4cbd946d-5b24-46dd-acdc-d19414fa7ffc@11g2000prw.googlegroups.com>
	
Message-ID: <4becf979$0$2854$426a34cc@news.free.fr>

Hi Sean,




Sean DiZazzo wrote:
> On May 13, 9:54 pm, Sean DiZazzo  wrote:
>> On May 13, 9:39 am, News123  wrote:
>>
>>
>>
>>> Hi Aaaz,
>>> Aahz wrote:
>>>> In article <4bea6b50$0$8925$426a7... at news.free.fr>,
>>>> News123   wrote:
>>>>> I'd like to perform huge file uploads via https.
>>>>> I'd like to make sure,

> 
> oops...that doesn't help with the other requirements.  My suggestion
> is to not use https.  I don't think it was created to move around
> large pieces of data.  Lots of small pieces rather.  SFTP?


I had to check, but I guess sftp is not exactly suitable for my usecase.

My problem
- the whole communication is to be intended to work like a drop box.
  - one can upload files
  - one can not see, what one has uploaded before
  - no way to accidentally overwrite a previous upload, etc.
- I don't know enough about sftp servers to know how I could configure
it to act as a drop box.


That's much easier to hide behind an https server than behind an out of
the box sftp server.



N


From news1234 at free.fr  Fri May 14 03:22:01 2010
From: news1234 at free.fr (News123)
Date: Fri, 14 May 2010 09:22:01 +0200
Subject: client to upload big files via https and get progress info
In-Reply-To: 
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	
Message-ID: <4becfa19$0$2854$426a34cc@news.free.fr>

Hi James,

James Mills wrote:
> On Wed, May 12, 2010 at 6:48 PM, News123  wrote:
>> Hi,
>>
>> I'd like to perform huge file uploads via https.
>> I'd like to make sure,
>> - that I can obtain upload progress info (sometimes the nw is very slow)
>> - that (if the file exceeds a certain size) I don't have to
>>  read the entire file into RAM.
>>
> 
> My suggestion is to find some tools that can
> send multiple chucks of data. A non-blocking
> i/o library/tool might be useful here (eg: twisted or similar).
> 

I never used twisted so far.
Perhaps the time to look at it.


bye


N


From news1234 at free.fr  Fri May 14 03:23:59 2010
From: news1234 at free.fr (News123)
Date: Fri, 14 May 2010 09:23:59 +0200
Subject: client to upload big files via https and get progress info
In-Reply-To: <8545t3F8mtU1@mid.individual.net>
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	 <4BEC2B49.7060007@free.fr>
	<8545t3F8mtU1@mid.individual.net>
Message-ID: <4becfa8f$0$2854$426a34cc@news.free.fr>

Hi J,


J.O. Aho wrote:
> News123   wrote:
> 
>> What do others do for huge file uploads
>> The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )
> 
> Those cases where I have had to move big files it's been scp on those cases
> where you just have to push a new file, in cases where it's a question of
> keeping two directories synced, then it's rsync over ssh.
> The later one I have never done in python.


I agree. From home this is also what I do.
scp / rsync.


However I'd like to use https, as http/https are the two ports, that are
almost everywhere accessible (eve with proxies / firewalls, etc.)



N


From hkiridis at yahoo.com.au  Fri May 14 04:19:24 2010
From: hkiridis at yahoo.com.au (harry k)
Date: Fri, 14 May 2010 08:19:24 -0000
Subject: help need to write a python spell checker
Message-ID: 

Write a spell checking tool that will identify all misspelled word in a text file using a provided dictionary.


The program will accept either one or two command line parameters.
1.	The first command line parameter is the name of the text file that will be checked.
2.	The optional second command line parameter is the name of the dictionary file ? a file of words with one word per line.  The default dictionary file is ref.txt.
The program will write out the misspelled words, one per line, in alphabetical order.

Extend the spell checking tool so that as well as identifying all misspelled words,  the program will list the line numbers in the file where the incorrect spelling occurs.

The program will write out the misspelled words (one per line, in alphabetical order), followed by a tab character, followed by the list of line numbers that word is misspelled in,in ascending order, on the same line, separated by a single space.


Extend the spell-checking tool so that the program will also print out a list of possible correct spellings for the words.

The program will write out the misspelled words (one per line, in alphabetic order), followed (on the same line) by a single space, followed by the list of line numbers in ascending order, each separated by a single space, followed by a single space, then the list of possible correct spellings, each separated by a single space.

Find the alternate spellings by considering:
a.	Words in the dictionary that are the same length but:
a.	Have a pair of characters interchanged
b.	Differ by one character from the misspelled word
b.	Words that are one character longer or one character shorter, but otherwise match the misspelled word.



From oxfordenergyservices at googlemail.com  Fri May 14 04:23:40 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Fri, 14 May 2010 01:23:40 -0700 (PDT)
Subject: stopping execution window on error - newbie
References: <101459d0-92cb-40d4-ad6d-6f82a70b167d@l31g2000yqm.googlegroups.com>
	<3fd705f1-2b3b-4b2b-b48d-06a6700a76be@g21g2000yqk.googlegroups.com>
Message-ID: 

On 14 May, 00:14, Mensanator  wrote:
> On May 13, 4:00?pm, a  wrote:
>
> > I'm coding on an old windows laptop
>
> > i write the code and double click the icon. ?
>
> Don't do that.
>
> > it runs the program and
> > writes results to a window.
>
> > when the code finishes, the window closes, i do a time.sleep(10) to
> > see what has happened.
>
> > unfortunately when there is an error it just closes the window.
> > anyway of seeing the error messages?
>
> Go to the windows [Start] button. Select [Run...] and in the popup
> box,
> type "cmd" as the program to run. This will open a DOS shell window (a
> text window.)
>
> Then you can run your Python script from the window prompt and it
> won't
> close until you manually close it, even if the program crashes.
>
> For example, once I open the DOS shell...
>
> 
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
>
> H:\>C:
>
> C:\>cd python31\user\lotto
>
> C:\Python31\user\lotto>dir
> ?Volume in drive C has no label.
> ?Volume Serial Number is 06DE-55B4
>
> ?Directory of C:\Python31\user\lotto
>
> 05/13/2010 ?05:53 PM ? ? ? ? ? ? ?.
> 05/13/2010 ?05:53 PM ? ? ? ? ? ? ?..
> 08/19/2009 ?07:08 PM ? ? ? ? ? ? 3,334 lotto.py
> 05/13/2010 ?05:56 PM ? ? ? ? ? ? 6,068 lotto_2010.py
> ? ? ? ? ? ? ? ?2 File(s) ? ? ? ? ?9,402 bytes
> ? ? ? ? ? ? ? ?2 Dir(s) ?102,247,440,384 bytes free
>
> C:\Python31\user\lotto>..\..\python lotto_2010.py
>
> {1: 2, 2: 3, 3: 2, 4: 1, 5: 2, 6: 1, 7: 2, 8: 1, 9: 1, 10: 2, 11: 2,
> 13: 1, 14: 2, 17: 1, 18: 2, 19: 1, 20: 1, 21: 1, 22: 1, 24: 1, 25: 1,
> 26: 3, 27: 1, 28: 2, 29: 2, 30: 1, 31: 1, 32: 1, 34: 1, 35: 1, 37: 2,
> 38: 2, 39: 2, 40: 1, 42: 2, 43: 1, 44: 2, 46: 2, 47: 1, 48: 1, 50: 1,
> 51: 2, 52: 3}
>
> ?1 ?2 **
> ?2 ?3 ***
> ?3 ?2 **
> ?4 ?1 *
> ?5 ?2 **
> ?6 ?1 *
> ?7 ?2 **
> ?8 ?1 *
> ?9 ?1 *
> 10 ?2 **
> 11 ?2 **
> 12
> 13 ?1 *
> 14 ?2 **
> 15
> 16
> 17 ?1 *
> 18 ?2 **
> 19 ?1 *
> 20 ?1 *
> 21 ?1 *
> 22 ?1 *
> 23
> 24 ?1 *
> 25 ?1 *
> 26 ?3 ***
> 27 ?1 *
> 28 ?2 **
> 29 ?2 **
> 30 ?1 *
> 31 ?1 *
> 32 ?1 *
> 33
> 34 ?1 *
> 35 ?1 *
> 36
> 37 ?2 **
> 38 ?2 **
> 39 ?2 **
> 40 ?1 *
> 41
> 42 ?2 **
> 43 ?1 *
> 44 ?2 **
> 45
> 46 ?2 **
> 47 ?1 *
> 48 ?1 *
> 49
> 50 ?1 *
> 51 ?2 **
> 52 ?3 ***
>
> (7, 21, 50, 36, 26, 3)
> (7, 21, 50, 36, 26, 17)
> (7, 21, 50, 36, 26, 52)
> (7, 21, 50, 36, 3, 17)
> (7, 21, 50, 36, 3, 52)
> (7, 21, 50, 36, 17, 52)
> (7, 21, 50, 26, 3, 17)
> (7, 21, 50, 26, 3, 52)
> (7, 21, 50, 26, 17, 52)
> (7, 21, 50, 3, 17, 52)
> (7, 21, 36, 26, 3, 17)
> (7, 21, 36, 26, 3, 52)
> (7, 21, 36, 26, 17, 52)
> (7, 21, 36, 3, 17, 52)
> (7, 21, 26, 3, 17, 52)
> (7, 50, 36, 26, 3, 17)
> (7, 50, 36, 26, 3, 52)
> (7, 50, 36, 26, 17, 52)
> (7, 50, 36, 3, 17, 52)
> (7, 50, 26, 3, 17, 52)
> (7, 36, 26, 3, 17, 52)
> (21, 50, 36, 26, 3, 17)
> (21, 50, 36, 26, 3, 52)
> (21, 50, 36, 26, 17, 52)
> (21, 50, 36, 3, 17, 52)
> (21, 50, 26, 3, 17, 52)
> (21, 36, 26, 3, 17, 52)
> (50, 36, 26, 3, 17, 52)
>
> ?8 ?9 32 38 40 48
> 13 22 28 39 42 43
> ?1 ?2 ?5 11 18 52 +
> ?2 ?3 26 44 51 52 +++
> ?4 ?7 14 26 35 52 +++
> ?2 ?7 10 19 42 47 +
> ?5 20 31 34 50 51 +
> ?1 28 29 37 39 46
> 10 11 27 37 38 46
> ?6 21 24 29 30 44 +
> ?3 14 17 18 25 26 +++
> ?7 10 39 42 45 46 +
> 15 17 23 36 38 44 ++
> 16 19 23 27 41 49
> 15 25 32 36 44 47 +
> 16 19 24 29 38 41
> ?3 ?4 ?8 13 43 49 +
> ?2 11 17 19 22 50 ++
> 14 21 22 28 30 45 +
> ?4 15 21 34 47 49 +
> 19 34 38 39 40 48
> ?4 16 24 33 37 48
> ?8 16 17 18 39 40 +
> ?1 24 27 30 31 47
> ?1 ?7 11 21 30 43 ++
> ?1 ?8 13 18 32 36 +
> ?5 10 12 16 20 21 +
> ?7 11 23 24 26 35 ++
> ?7 ?8 11 13 42 49 +
> ?1 ?8 17 34 40 50 ++
> ?1 24 29 35 41 45
> 15 17 24 32 44 52 ++
> ?4 12 21 26 33 38 ++
> ?2 13 15 41 48 50 +
> ?2 ?7 ?9 27 45 52 ++
> 24 25 35 36 39 42 +
> ?8 22 39 40 42 48
> 16 18 29 30 34 43
> ?7 21 28 36 45 50 ++++
> ?4 ?8 30 35 39 42
> ?2 11 15 23 40 51
> ?2 ?7 14 18 23 34 +
> ?1 11 22 37 41 50 +
> ?4 34 40 44 50 52 ++
> 12 28 33 39 40 52 +
> 14 18 25 36 38 39 +
> ?4 11 16 17 27 37 +
> ?1 11 16 28 31 36 +
> ?8 16 31 34 36 52 ++
> ?7 10 15 21 35 36 +++
> ?2 ?9 21 23 29 30 +
> 15 29 33 41 46 47
> ?2 ?5 18 34 36 39 +
> ?7 15 21 31 45 50 +++
> 12 17 20 28 39 51 +
> ?3 ?7 22 26 50 52 +++++
> ?1 ?5 21 27 31 39 +
> ?2 ?8 10 23 34 50 +
> ?1 11 24 26 32 52 ++
> ?1 18 20 38 41 42
> 12 33 36 42 45 48 +
> ?1 ?6 21 28 37 39 +
> 16 18 19 22 33 35
> ?2 ?7 17 27 29 47 ++
> 15 19 20 25 42 45
> ?2 ?6 17 19 20 41 +
> ?1 13 34 42 43 46
> 16 29 30 31 34 47
> ?5 ?7 26 29 36 46 +++
> ?1 27 28 30 31 49
> ?8 17 19 47 49 52 ++
> ?5 23 32 41 42 45
> 11 13 22 29 40 46
> 16 17 18 20 41 43 +
> ?3 17 26 38 45 52 ++++
> 13 18 21 38 39 41 +
> 14 19 28 40 44 51
> ?4 ?8 ?9 36 43 47 +
> ?1 ?9 15 24 36 39 +
> ?4 31 37 41 42 43
> ?7 12 18 27 36 42 ++
> ?3 ?4 26 27 35 51 ++
> ?7 12 19 23 26 45 ++
> 19 28 36 39 42 52 ++
> ?8 17 21 44 46 51 ++
> ?2 ?4 18 19 36 49 +
> ?1 ?4 11 16 22 35
> 13 14 17 18 41 46 +
> ?8 16 23 29 43 48
> ?1 ?8 25 36 37 44 +
> ?7 20 21 23 36 50 ++++
> ?3 ?7 23 27 39 43 ++
> ?4 10 21 37 38 48 +
> ?6 18 30 35 36 42 +
> ?3 14 23 43 46 48 +
> 10 11 19 26 42 46 +
> ?1 ?5 27 34 42 45
> ?1 16 29 33 40 46
> 32 41 43 45 48 51
> ?1 13 23 24 46 49
> 24 25 28 30 32 40
> ?8 14 20 33 50 52 ++
> ?2 16 27 28 33 39
> 13 17 19 32 43 52 ++
> 10 11 16 43 45 49
> ?2 ?4 20 22 35 44
> ?1 12 18 36 37 40 +
> ?8 10 16 22 35 47
> ?8 11 16 31 45 46
> 11 13 22 25 26 27 +
> ?3 17 25 26 29 40 +++
> ?7 10 27 37 46 47 +
> ?3 ?5 ?7 27 33 40 ++
> ?4 14 28 37 40 44
> 18 22 25 33 43 48
> 11 19 26 30 44 50 ++
> ?3 11 22 42 46 51 +
> ?7 ?8 21 26 30 50 ++++
> ?6 13 15 23 37 39
> 12 17 31 37 43 47 +
> ?2 ?7 11 21 33 42 ++
> ?2 21 26 37 39 50 +++
> ?6 26 37 38 42 46 +
> 18 19 24 34 40 49
> ?2 ?9 12 17 31 42 +
> ?5 14 30 32 34 49
> ?7 14 29 41 49 50 ++
> ?3 ?7 43 45 46 47 ++
> 12 22 31 37 40 51
> ?1 ?3 ?5 11 28 46 +
> ?6 ?7 12 22 30 32 +
> 13 18 20 25 26 49 +
> 14 19 22 41 49 50 +
> ?3 ?4 12 20 39 42 +
> ?9 18 31 44 46 49
> ?9 20 24 27 41 45
> ?6 ?8 27 31 45 52 +
> 22 34 35 40 41 42
> ?1 ?8 15 37 38 45
> ?6 ?9 13 16 35 51
> ?6 14 17 30 33 52 ++
> 14 27 31 34 40 51
> ?2 11 21 34 36 46 ++
> ?1 ?3 12 15 47 51 +
> ?4 ?5 26 30 32 37 +
> ?4 10 18 29 37 51
> ?8 33 35 36 39 43 +
> ?9 17 22 23 40 52 ++
> ?3 31 34 38 47 50 ++
> 21 26 27 33 41 50 +++
> ?1 10 15 26 40 43 +
> ?9 15 17 25 40 42 +
> ?6 11 23 26 30 45 +
> ?1 ?5 ?9 33 44 51
> 13 15 20 22 27 48
> ?3 ?5 10 11 17 32 ++
>
> C:\Python31\user\lotto>
> 
>
> Now I can study the output for as long as I want.
>
> Also, I could have done this:
>
> ? ? C:\Python31\user\lotto>..\..\python lotto_2010.py >
> lotto_output.txt
>
> and directed the output to a file for editing and/or printing.
>
Thanks!


From darragh.ssa at gmail.com  Fri May 14 05:33:23 2010
From: darragh.ssa at gmail.com (darragh)
Date: Fri, 14 May 2010 02:33:23 -0700 (PDT)
Subject: d-cm Controll Manager
Message-ID: 

Hey,
I'm developing d-cm, it's a program for web-developers that often need
a text-editor,file-manager,sql-manager,ftp-manager.  d-cm combines all
of them in one easy to use program.

i'm looking for people that would like to help developing or to test
the program.
http://code.google.com/p/d-cm


From jackie.space at gmail.com  Fri May 14 05:40:40 2010
From: jackie.space at gmail.com (Jackie Lee)
Date: Fri, 14 May 2010 02:40:40 -0700 (PDT)
Subject: write a 20GB file
Message-ID: 

Hello there,

I have a 22 GB binary file, a want to change values of specific
positions. Because of the volume of the file, I doubt my code a
efficient one:

#! /usr/bin/env python
#coding=utf-8
import sys
import struct

try:
        f=open(sys.argv[1],'rb+')
except (IOError,Exception):
    print '''usage:
        scriptname segyfilename
'''
    sys.exit(1)

#skip EBCDIC header
try:
    f.seek(3200)
except Exception:
    print 'Oops! your file is broken..'

#read binary header
binhead = f.read(400)
ns = struct.unpack('>h',binhead[20:22])[0]
if ns < 0:
    print 'file read error'
    sys.exit(1)

#read trace header
while True:
    f.seek(28,1)
    f.write(struct.pack('>h',1))
    f.seek(212,1)
    f.seek(ns*4,1)

f.close()


From bruno.42.desthuilliers at websiteburo.invalid  Fri May 14 06:14:57 2010
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Fri, 14 May 2010 12:14:57 +0200
Subject: How to add callbacks that is the same function with different
	argument in Tkinter python26?
In-Reply-To: 
References: 
	
Message-ID: <4bed22a1$0$9131$426a34cc@news.free.fr>

Jean-Michel Pichavant a ?crit :
> chen zeguang wrote:
>> code is in the end.
>> I want to print different number when pressing different button.
>> Yet the program outputs 8 no matter which button is pressed.
>> I guess it's because the callback function is not established untill 
>> the button is pressed, and i has already reached to 8.

[answering to the op]
The key here is that the current value of 'i' is not captured when the 
lambda function is created. To make it work, you'd have to capture the 
current value of 'i', which is usually done using a default argument ie:

for i in range(9):
     func_en.append(lambda i=i:func(i))

Now there are other solutions...

> 
> def func(x):
>    def _printme():
>        print x
>    return _printme
> 
> for i in range(9):
>    Button(root, text='%d'%i, command=func(i)).pack()
> 
> Surely someone will explain why your code was not working,

done !-)

> I can't 
> 'cause I don't use lambda, it brings more problems than it solves (maybe 
> I'm not talented enough).
> Above is how I would have written the code, I tested it, looks like it's 
> working.

FWIW, there's now (since 2.5 IIRC) a stdlib way to solve this kind of 
problems:

from functools import partial

def printme(x):
     print x

for i in range(9):
    Button(root, text='%d'%i, command=partial(printme,i)).pack()

HTH


From kaklis at gmail.com  Fri May 14 06:46:13 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Fri, 14 May 2010 03:46:13 -0700 (PDT)
Subject: cmd app and xml
Message-ID: <5363cc2f-04c7-469e-a3d3-a21813c48bbb@i10g2000yqh.googlegroups.com>

Hi there,
i'm writing a console app using the cmd library. I also use
xml.dom.minidom to parse an xml file that i get as a response to an
HTTP Post request.
with
data = response.read()
i get the xml response from the server.
i then feed the parser with that data.
myDoc = parse(data)
but it doesn't work.
To make it work i open an xml file and the save the data to that file.
myDoc = parse('test.xml')
that worked.
But i don't want to use the local xml file?
What am i doing wrong?

Thanks in advance
A.


From davea at ieee.org  Fri May 14 07:04:37 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 14 May 2010 07:04:37 -0400
Subject: write a 20GB file
In-Reply-To: 
References: 
Message-ID: <4BED2E45.6060301@ieee.org>

Jackie Lee wrote:
> Hello there,
>
> I have a 22 GB binary file, a want to change values of specific
> positions. Because of the volume of the file, I doubt my code a
> efficient one:
>
> #! /usr/bin/env python
> #coding=utf-8
> import sys
> import struct
>
> try:
>         f=open(sys.argv[1],'rb+')
> except (IOError,Exception):
>     print '''usage:
>         scriptname segyfilename
> '''
>     sys.exit(1)
>
> #skip EBCDIC header
> try:
>     f.seek(3200)
> except Exception:
>     print 'Oops! your file is broken..'
>
> #read binary header
> binhead = f.read(400)
> ns = struct.unpack('>h',binhead[20:22])[0]
> if ns < 0:
>     print 'file read error'
>     sys.exit(1)
>
> #read trace header
> while True:
>     f.seek(28,1)
>     f.write(struct.pack('>h',1))
>     f.seek(212,1)
>     f.seek(ns*4,1)
>
> f.close()
>
>   
I don't see a question anywhere.  So perhaps you just want comments on 
your code.

1) How do you plan to test this?
2) Consider doing a lot more checking to see that you have in fact a 
file of the right type.
3) Fix indentation - perhaps you've accidentally used a tab in the source.
4) Provide a termination condition for the while True loop, which 
currently will (I think) go forever, or perhaps until the disk fills up.
5) Depending on the purpose of this file, you should consider making the 
changes on a copy, then deleting and renaming.  As it stands, if the 
program gets aborted part way through, there's no way to know how far it 
got.  Since it's just clobbering bytes, it would be safe to rerun the 
same program again, but many times that's not the case.  And this 
program clearly isn't finished yet, so perhaps it's not true here either.
6) I don't see anything inefficient about it.  The nature of the problem 
is going to be very slow (for small values of ns), but I don't know what 
your code could do to speed it up.  Perhaps make sure the file is on a 
fast drive, and not RAID 5.

DaveA



From stefan_ml at behnel.de  Fri May 14 07:10:50 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 14 May 2010 13:10:50 +0200
Subject: cmd app and xml
In-Reply-To: <5363cc2f-04c7-469e-a3d3-a21813c48bbb@i10g2000yqh.googlegroups.com>
References: <5363cc2f-04c7-469e-a3d3-a21813c48bbb@i10g2000yqh.googlegroups.com>
Message-ID: 

kaklis at gmail.com, 14.05.2010 12:46:
> Hi there,
> i'm writing a console app using the cmd library. I also use
> xml.dom.minidom to parse an xml file that i get as a response to an
> HTTP Post request.
> with
> data = response.read()
> i get the xml response from the server.
> i then feed the parser with that data.
> myDoc = parse(data)
> but it doesn't work.

Note that "it doesn't work" is not a very complete description of the 
actual problem.


> To make it work i open an xml file and the save the data to that file.
> myDoc = parse('test.xml')
> that worked.
> But i don't want to use the local xml file?
> What am i doing wrong?

Not reading the docs?

http://docs.python.org/library/xml.dom.minidom.html

There is a parseString() function that does what you want.

Stefan



From ldo at geek-central.gen.new_zealand  Fri May 14 07:12:37 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 23:12:37 +1200
Subject: Picking a license
References: 
	
	<2ff3643b-6ef1-4471-8438-dcba0dc93c24@a21g2000yqn.googlegroups.com>
Message-ID: 

In message <2ff3643b-6ef1-4471-8438-
dcba0dc93c24 at a21g2000yqn.googlegroups.com>, Patrick Maupin wrote:

> On May 13, 10:04 pm, Lawrence D'Oliveiro
>  wrote:
>
>> In message , Ed
>> Keith wrote:
>>
>>> The claim is being made that [the GPL] restricts freedom.
>>
>> What about the ?freedom? to restrict other people?s freedom? Should that
>> be restricted or not?
> 
> It's interesting that some people don't like the comparison of the
> Free Software movement to a religion, yet the main argument of the
> movement, and the deliberate co-opting of words like "Free" and "Free
> Software" ...

Haven?t you ?co-opted? those words yourself?


From ldo at geek-central.gen.new_zealand  Fri May 14 07:13:32 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 23:13:32 +1200
Subject: Picking a license
References: 
	
	<2b17ee77-0e49-4a97-994c-7582f86c0ba9@r34g2000yqj.googlegroups.com>
Message-ID: 

In message 
<2b17ee77-0e49-4a97-994c-7582f86c0ba9 at r34g2000yqj.googlegroups.com>, Patrick 
Maupin wrote:

> On May 13, 10:06 pm, Lawrence D'Oliveiro
>  wrote:
>
>> Under the GPL, everybody has exactly the same freedoms.
> 
> That's absolutely not true.  For a start, the original author can dual-
> license.

That?s nothing to do with the GPL.


From jackie.space at gmail.com  Fri May 14 07:32:15 2010
From: jackie.space at gmail.com (Jackie Lee)
Date: Fri, 14 May 2010 18:32:15 +0700
Subject: write a 20GB file
In-Reply-To: <4BED2E45.6060301@ieee.org>
References: 
	<4BED2E45.6060301@ieee.org>
Message-ID: 

Thx, Dave,

The code works fine. I just don't know how f.write works. It says that
file.write won't write the file until file.close or file.flush. So I
don't know if the following one is more efficient (sorry I forget to
add condition to break the loop):

#! /usr/bin/env python
#coding=utf-8
import sys
import struct

try:
        f=open(sys.argv[1],'rb+')
except (IOError,Exception):
    print '''usage:
        scriptname segyfilename
'''
    sys.exit(1)

#skip EBCDIC header
try:
    f.seek(3200)
except Exception:
    print 'Oops! your file is broken..'

#read binary header
binhead = f.read(400)
ns = struct.unpack('>h',binhead[20:22])[0]
if ns < 0:
    print 'file read error'
    sys.exit(1)

#read trace header
while True:
    f.seek(28,1)
    if f.read(2) == '':
        break
    f.seek(-2,1)
    f.write(struct.pack('>h',1))
    f.seek(210,1)
    f.seek(ns*4,1)

f.close()


On Fri, May 14, 2010 at 6:04 PM, Dave Angel  wrote:
> Jackie Lee wrote:
>>
>> Hello there,
>>
>> I have a 22 GB binary file, a want to change values of specific
>> positions. Because of the volume of the file, I doubt my code a
>> efficient one:
>>
>> #! /usr/bin/env python
>> #coding=utf-8
>> import sys
>> import struct
>>
>> try:
>> ? ? ? ?f=open(sys.argv[1],'rb+')
>> except (IOError,Exception):
>> ? ?print '''usage:
>> ? ? ? ?scriptname segyfilename
>> '''
>> ? ?sys.exit(1)
>>
>> #skip EBCDIC header
>> try:
>> ? ?f.seek(3200)
>> except Exception:
>> ? ?print 'Oops! your file is broken..'
>>
>> #read binary header
>> binhead = f.read(400)
>> ns = struct.unpack('>h',binhead[20:22])[0]
>> if ns < 0:
>> ? ?print 'file read error'
>> ? ?sys.exit(1)
>>
>> #read trace header
>> while True:
>> ? ?f.seek(28,1)
>> ? ?f.write(struct.pack('>h',1))
>> ? ?f.seek(212,1)
>> ? ?f.seek(ns*4,1)
>>
>> f.close()
>>
>>
>
> I don't see a question anywhere. ?So perhaps you just want comments on your
> code.
>
> 1) How do you plan to test this?
> 2) Consider doing a lot more checking to see that you have in fact a file of
> the right type.
> 3) Fix indentation - perhaps you've accidentally used a tab in the source.
> 4) Provide a termination condition for the while True loop, which currently
> will (I think) go forever, or perhaps until the disk fills up.
> 5) Depending on the purpose of this file, you should consider making the
> changes on a copy, then deleting and renaming. ?As it stands, if the program
> gets aborted part way through, there's no way to know how far it got. ?Since
> it's just clobbering bytes, it would be safe to rerun the same program
> again, but many times that's not the case. ?And this program clearly isn't
> finished yet, so perhaps it's not true here either.
> 6) I don't see anything inefficient about it. ?The nature of the problem is
> going to be very slow (for small values of ns), but I don't know what your
> code could do to speed it up. ?Perhaps make sure the file is on a fast
> drive, and not RAID 5.
>
> DaveA
>
>



-- 
Jackie


From kaklis at gmail.com  Fri May 14 08:14:00 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Fri, 14 May 2010 05:14:00 -0700 (PDT)
Subject: cmd app and xml
References: <5363cc2f-04c7-469e-a3d3-a21813c48bbb@i10g2000yqh.googlegroups.com>
	
Message-ID: <41cb09f0-f603-4d83-8315-965bfc2d58f2@j35g2000yqm.googlegroups.com>

On May 14, 7:10?am, Stefan Behnel  wrote:
> kak... at gmail.com, 14.05.2010 12:46:
>
> > Hi there,
> > i'm writing a console app using the cmd library. I also use
> > xml.dom.minidom to parse an xml file that i get as a response to an
> > HTTP Post request.
> > with
> > data = response.read()
> > i get the xml response from the server.
> > i then feed the parser with that data.
> > myDoc = parse(data)
> > but it doesn't work.
>
> Note that "it doesn't work" is not a very complete description of the
> actual problem.
>
> > To make it work i open an xml file and the save the data to that file.
> > myDoc = parse('test.xml')
> > that worked.
> > But i don't want to use the local xml file?
> > What am i doing wrong?
>
> Not reading the docs?
>
> http://docs.python.org/library/xml.dom.minidom.html
>
> There is a parseString() function that does what you want.
>
> Stefan

ok, i missed that function.
Thank you so much!!
Antonis


From ethan at stoneleaf.us  Fri May 14 09:04:52 2010
From: ethan at stoneleaf.us (Ethan Furman)
Date: Fri, 14 May 2010 06:04:52 -0700
Subject: Picking a license
In-Reply-To: <4bece8de$0$8761$c3e8da3@news.astraweb.com>
References: 	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>			<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>	
	<4bece8de$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <4BED4A74.6060203@stoneleaf.us>

Steven D'Aprano wrote:
> On Thu, 13 May 2010 19:10:09 -0700, Patrick Maupin wrote:
>>The only time
>>that comes into play in my programming life is *when I have to recode*
>>something that is nominally available under the GPL,
> 
> You've never had to recode something because it was nominally available 
> under a proprietary licence that you (or your client) was unwilling to 
> use? Lucky you!

Steven, did you actually read what he wrote?  If you did, why would you 
say something so stupid?

~Ethan~


From saharabear at gmail.com  Fri May 14 09:18:28 2010
From: saharabear at gmail.com (Haulyn Jason)
Date: Fri, 14 May 2010 21:18:28 +0800
Subject: Data store solution need help
Message-ID: <4BED4DA4.8050604@gmail.com>

Hi, all:

I am a Java programmer, now I am working on a Python program. At the 
moment, I need to store some data from user's input, no database, no 
xml, no txt(we can not make users open the data file by vim or other 
text editor).

Any suggestions or reference url? Is there a lib should do this or I 
need to implement it myself?

PS: if I want to implement it myself, which part of python document I 
need to learn? I know how to write txt files now, but not further for me.

-- 
Thanks!

VVThumb Microproduction

Location:Room 807,QiLuRuanJianDaSha Qilu Software Park
          No. 1 Shunhua Rd High-Tech Development Zone
          Jinan, China 250101
Website: http://www.haulynjason.net/haulyn
Mobile: +86 15854103759

Haulyn Jason



From paul at boddie.org.uk  Fri May 14 09:26:14 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 06:26:14 -0700 (PDT)
Subject: Picking a license
References: 
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
Message-ID: 

On 13 Mai, 22:10, Patrick Maupin  wrote:
>

[...]

Just to deal with your Ubuntu "high horse" situation first, you should
take a look at the following for what people regard to be the best
practices around GPL-licensed software distribution:

http://www.softwarefreedom.org/resources/2008/compliance-guide.html

If you still think Ubuntu are violating the GPL or encouraging others
to do so, feel free to contact their lawyers who I'm sure will be very
interested to hear from you.

> When the leader of your religion bandies terms like "freedom" and
> "evil" about, what do you expect? ?Seriously?

I thought you were "done". I guess you are: again, we have the usual
courting of public outrage by labelling stuff you don't like as
"religion" - presumably not the "right one", either - when it is no
such thing.

[...]

> My primary agenda is to explain that RMS does, in fact, have an
> agenda, and the GPL was designed as a tool in furtherance of that
> agenda, and that while the agenda does have some arguably noble goals,
> before using the GPL people should understand its consequences both
> for good and bad, and make their own determination about whether it's
> the right license for their project.

Reading through your "translations" of what are effectively honest
summaries, one gets the impression that you have quite a chip on your
shoulder about the FSF and RMS. Referring to the GPL as a "commercial"
licence and stating that it (as opposed to any other licence or even
the word "copyright" followed by a name) is a threat to sue people,
presumably appealing to the libertarian crowd with a judicious mention
of "government" just to fan the flames of supposed injustice, really
does triangulate where you are coming from. So, yes, we're now rather
more aware of what your agenda is, I think.

And I don't think it improves any argument you may have by projecting
notions of "morality" or "immorality" onto what I have written,
especially when I have deliberately chosen to use other terms which
avoid involving such notions, or by equating the copyleft licences
with criminal enterprises ("pyramid scheme"), or by suggesting that I
endorse criminal endeavours. But if that's what you have left to say
at this point, then I think you probably are "done".

Paul


From paul at boddie.org.uk  Fri May 14 09:35:16 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 06:35:16 -0700 (PDT)
Subject: Picking a license
References: 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-b
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	
Message-ID: 

On 14 Mai, 03:56, a... at pythoncraft.com (Aahz) wrote:
>
> IMO this only makes sense if one agrees that people should not be allowed
> to sell software for money. ?Absent that agreement, your argument about
> freedom seems rather limited.

You'll have to explain this to me because I don't quite follow your
assertion. You can sell copyleft-licensed software, although I accept
that you can't set an arbitrarily high price on the sources for
someone who has already acquired a binary distribution.

Paul


From e_d_k at yahoo.com  Fri May 14 09:39:05 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 06:39:05 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <779006.76311.qm@web58707.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 11:06 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > Assertion I:
> >? ? If person A is free to do more than
> person B, then person A has
> >? ? more freedom then person B.
> > 
> > Assertion II:
> >? ? If person A is free do perform an action
> person B is not free to
> >? ? perform then person A is free to do more
> than person B.
> > 
> > Assertion III:
> >???If person B is restricted in some way
> that person A is not them Person A
> >???is free to do something Person B is
> not free to do.
> > 
> > Conclusion:
> >???If person B is more resticted than
> Peston A, Person A has mor freedom
> >???than person B.
> > 
> > Which step in this reasoning do you disagree with?
> 
> Under the GPL, everybody has exactly the same freedoms. So
> which of your 
> assertions is supposedly a criticism of the GPL?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Yes, under the GPL every one has one set of freedoms, under the MIT or Boost license every one has more freedoms. Under other licenses they have fewer freedoms. 

None of my point criticize the GPL, they merely defend my claim that a more permissive license grants more freedom. You claimed the contrary. 

Are you withdrawing your previous claim, or will you directly refute my arguments?

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From bruno.42.desthuilliers at websiteburo.invalid  Fri May 14 09:42:00 2010
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Fri, 14 May 2010 15:42:00 +0200
Subject: Data store solution need help
In-Reply-To: 
References: 
Message-ID: <4bed5326$0$27708$426a74cc@news.free.fr>

Haulyn Jason a ?crit :
> Hi, all:
> 
> I am a Java programmer, now I am working on a Python program. At the 
> moment, I need to store some data from user's input, no database, no 
> xml, no txt(we can not make users open the data file by vim or other 
> text editor).
> 
> Any suggestions or reference url? Is there a lib should do this or I 
> need to implement it myself?
> 
> PS: if I want to implement it myself, which part of python document I 
> need to learn? I know how to write txt files now, but not further for me.
> 

Not sure I really understand whether you want to store your data in just 
any format or if it need to be a "binary" format or else... And you 
don't tell much about how your data structure and how it will be used.

Anyway: two possible solutions are csv or serialization.

For the first option, see the csv module
http://docs.python.org/library/csv.html#module-csv

For the second, look at pickle and shelve modules:
http://docs.python.org/library/pickle.html#module-pickle
http://docs.python.org/library/shelve.html#module-shelve


If none of this fits your needs, please provide more details !-)
HTH


From e_d_k at yahoo.com  Fri May 14 09:42:31 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 06:42:31 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <440135.15702.qm@web58708.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 11:07 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > On Thu, 5/13/10, Lawrence D'Oliveiro
> > 
> wrote:
> > 
> >> In message ,
> >> Ed Keith wrote:
> >> 
> >>> So if you want me to even consider using your
> library
> >>> do not use GPL, or LGPL.
> >> 
> >> What have you got against LGPL for this purpose?
> > 
> > Most of my clients would not know how to relink a
> program if their life
> > depended on it. And I do not want to put then in DLL
> hell. So I avoid the
> > LGPL.
> 
> How exactly does the LGPL lead to a requirement to
> ?relink??
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

I am not a lawyer, but as I understand the LGPL, If I give someone something that used any LGPLed code I must give them the ability to relink it with any future releases of the LGPLed code. I think that means that I need to give them a linker and teach them how to use it, and I do not want to go there.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From e_d_k at yahoo.com  Fri May 14 09:47:11 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 06:47:11 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <2b17ee77-0e49-4a97-994c-7582f86c0ba9@r34g2000yqj.googlegroups.com>
Message-ID: <125692.28959.qm@web58703.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Patrick Maupin  wrote:

> From: Patrick Maupin 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 11:45 PM
> On May 13, 10:06?pm, Lawrence
> D'Oliveiro  central.gen.new_zealand> wrote:
> > In message ,
> Ed Keith
> > wrote:
> >
> >
> >
> > > Assertion I:
> > > ? ?If person A is free to do more than person
> B, then person A has
> > > ? ?more freedom then person B.
> >
> > > Assertion II:
> > > ? ?If person A is free do perform an action
> person B is not free to
> > > ? ?perform then person A is free to do more
> than person B.
> >
> > > Assertion III:
> > > ? If person B is restricted in some way that
> person A is not them Person A
> > > ? is free to do something Person B is not free
> to do.
> >
> > > Conclusion:
> > > ? If person B is more resticted than Peston A,
> Person A has mor freedom
> > > ? than person B.
> >
> > > Which step in this reasoning do you disagree
> with?
> >
> > Under the GPL, everybody has exactly the same
> freedoms. So which of your
> > assertions is supposedly a criticism of the GPL?
> 
> That's absolutely not true.? For a start, the original
> author can dual-
> license.? This is not a theoretical issue -- it is a
> multi-million
> dollar issue.
> 
> Regards,
> Pat
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Everyone I personally know who has released code under the GPL either dual-licenses, or hopes to.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From python.list at tim.thechases.com  Fri May 14 09:47:13 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Fri, 14 May 2010 08:47:13 -0500
Subject: Data store solution need help
In-Reply-To: <4BED4DA4.8050604@gmail.com>
References: <4BED4DA4.8050604@gmail.com>
Message-ID: <4BED5461.9010806@tim.thechases.com>

On 05/14/2010 08:18 AM, Haulyn Jason wrote:
> I am a Java programmer, now I am working on a Python program. At the
> moment, I need to store some data from user's input, no database, no
> xml, no txt(we can not make users open the data file by vim or other
> text editor).

You don't mention what type of data you want to store?  Is it a 
single string?  Multiple strings?  Complex nested data?

And how do you want to access it?

Python provides you any number of options:

- you can use standard Python file objects to read/write content 
in a file format of your own definition

- you can use the ConfigParser module to read/write an old-school 
.INI style file (which can also be edited in a text editor, but 
doesn't have to be)

- you can use the "anydbm" module to store key/value pairs of 
strings with an internal user-interface much like a dictionary

- you can use the "pickle" module to persist Python objects into 
files

- you can use the "shelve" module to combine the "pickle" 
persistence with the DBM layer

- you can use the built-in (as of Python2.5) "sqlite3" module for 
a single-file database with full SQL capabilities without the 
need to install a SQL server (MySQL, PostgreSQL, MS SQL Server, etc)

- you can persist to cloud storage or to your own web-server 
using the urllib/urllib2 modules


But without knowing what you want to store or how you want to 
access it, it's hard to offer more concrete advice.

-tkc








From paul at boddie.org.uk  Fri May 14 09:47:30 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 06:47:30 -0700 (PDT)
Subject: Picking a license
References:  
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
Message-ID: <9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com>

On 14 Mai, 05:35, Patrick Maupin  wrote:
>
> I mean, it's in English and very technically precise, but if you
> follow all the references, you quickly come to realize that the
> license is a "patch" to the GPL.

It is a set of exceptions applied to version 3 of the GPL, done this
way so that the exceptions machinery of the GPL can be used to remove
them if desired, as opposed to getting into the business of allowing
people to relicense works from the LGPL to the GPL, as was the case
with previous versions of these licences. You don't even have to read
as far as the first clause of the LGPL terms to be told this, but I
guess there's more "sport" in taking cheap shots at the authors than
reading three lines down from the top of the text.

Paul


From e_d_k at yahoo.com  Fri May 14 09:53:54 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 06:53:54 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <4bece8de$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <967692.89720.qm@web58707.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Steven D'Aprano  wrote:
> 
> The GPL ensures that once software has entered the commons
> (and therefore 
> available for all), it can never be removed from the
> commons. The MIT 
> licence does not. Now, you might argue that in practice
> once software is 
> released under an MIT licence, it is unlikely to ever
> disappear from the 
> commons. Well, perhaps, but if so, that's despite and not
> because of the 
> licence.

Why is MIT licensed code any more likely to dispersal from the common that GPLed code? Does using the GPL somehow grantee that my server will never crash?


> 
> In practice, I believe most MIT-licenced code never even
> makes it into 
> the commons in the first place. I'm willing to predict that
> the majority 
> of code you've written for paying customers (as opposed to
> specifically 
> for open source projects) has disappeared into their code
> base, never to 
> be seen by anyone outside of the company. Am I right?

Yes, but it was licensed to the client, and never enter into the commons, That which never enters into the commons can never be removed.

Any MIT licensed code that I may have used is still in the common. My using it did not reomove it from the common. 

Has the fact that Python has been used for many commercial/propitiatory projects reduced your ability to make use of it? If so how?

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From mehgcap at gmail.com  Fri May 14 09:56:02 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Fri, 14 May 2010 09:56:02 -0400
Subject: Data store solution need help
In-Reply-To: <4bed5326$0$27708$426a74cc@news.free.fr>
References: 
	<4bed5326$0$27708$426a74cc@news.free.fr>
Message-ID: 

An important question is: will you need this input stored across
multiple runs of the program? What I mean is, do you want the user to
set the data, then have those same settings even after closing and
re-opening the program?

On 5/14/10, Bruno Desthuilliers
 wrote:
> Haulyn Jason a ?crit :
>> Hi, all:
>>
>> I am a Java programmer, now I am working on a Python program. At the
>> moment, I need to store some data from user's input, no database, no
>> xml, no txt(we can not make users open the data file by vim or other
>> text editor).
>>
>> Any suggestions or reference url? Is there a lib should do this or I
>> need to implement it myself?
>>
>> PS: if I want to implement it myself, which part of python document I
>> need to learn? I know how to write txt files now, but not further for me.
>>
>
> Not sure I really understand whether you want to store your data in just
> any format or if it need to be a "binary" format or else... And you
> don't tell much about how your data structure and how it will be used.
>
> Anyway: two possible solutions are csv or serialization.
>
> For the first option, see the csv module
> http://docs.python.org/library/csv.html#module-csv
>
> For the second, look at pickle and shelve modules:
> http://docs.python.org/library/pickle.html#module-pickle
> http://docs.python.org/library/shelve.html#module-shelve
>
>
> If none of this fits your needs, please provide more details !-)
> HTH
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


From utente at esempio.net  Fri May 14 10:02:19 2010
From: utente at esempio.net (superpollo)
Date: Fri, 14 May 2010 16:02:19 +0200
Subject: Data store solution need help
In-Reply-To: 
References: 
Message-ID: <4bed57ec$0$18997$4fafbaef@reader5.news.tin.it>

Haulyn Jason ha scritto:
> Hi, all:
> 
> I am a Java programmer, now I am working on a Python program. At the 
> moment, I need to store some data from user's input, no database, no 
> xml, no txt(we can not make users open the data file by vim or other 
> text editor).

security thru obscurity? mmmhhh...


From e_d_k at yahoo.com  Fri May 14 10:10:50 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 07:10:50 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
Message-ID: <375036.32165.qm@web58706.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Patrick Maupin  wrote:

> From: Patrick Maupin 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 11:35 PM
> On May 13, 10:07?pm, Lawrence
> D'Oliveiro  central.gen.new_zealand> wrote:
> 
> > How exactly does the LGPL lead to a requirement to
> ?relink??
> 
> I think this might be a misconception, but I'm not 100%
> sure.? Since
> Ed gives his customers full source code, there may not be
> the
> requirement to directly provide the ability to relink,
> because "The
> ?Corresponding Application Code? for a Combined Work
> means the object
> code and/or source code for the Application." and section
> 4d0 requires
> you to "permit the user to recombine or relink" where
> "recombine"
> isn't defined directly (perhaps in the underlying GPL?)

But if my client give someone else a copy of the binary I gave them, they are now in violation. I do not want to put my client in this position. 

When using the GPL or LGPL you can do anything you want as long as you do not let anyone else use your work, but if you let someone else have a copy of you work you are putting them in a position where that can easily/inadvertently violate the law. I do not want to put clients in legal jeopardy, so I do not use GPL, or LGPLed code.

I do not claim that using the GLP is immoral, nor deny others right to use it. I just feel the risks out way the benefits for me.

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Fri May 14 10:28:06 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 07:28:06 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <4bece8de$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <157842.21043.qm@web58707.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Steven D'Aprano  wrote:

> The GPL ensures that once software has entered the commons
> (and therefore 
> available for all), it can never be removed from the
> commons. The MIT 
> licence does not. Now, you might argue that in practice
> once software is 
> released under an MIT licence, it is unlikely to ever
> disappear from the 
> commons. Well, perhaps, but if so, that's despite and not
> because of the 
> licence.


Several years ago I released a C++ library under the Boost license. I put it up on a small free server. Later my hard drive crashed, both my backup copies were corrupted, and when I went to retrieve it from the site I found it no longer existed.

I am recreating the code, and it will be MUCH better this time, and it is on three web sites, but are you telling me that of I have used the GPL instead of Boost I would not have had this problem?

I use the Boost Libraries (http://www.boost.org/) in most of my code. Do you believe they are likely to disappear because they are not covered by the GPL?

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From aonlazio at gmail.com  Fri May 14 10:32:39 2010
From: aonlazio at gmail.com (AON LAZIO)
Date: Fri, 14 May 2010 10:32:39 -0400
Subject: Setup global variables settings for the entire applications
Message-ID: 

Hi,
   Say I have an application which requires a global settings for the user.
When the user finishes setting those global variables for the app. Any class
can use that variables (which are the same for all), something like that.
What is the suitable mechanism for this solution?
   Thanks in advance

Aonlazio

-- 
Passion is my style
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From dreadpiratejeff at gmail.com  Fri May 14 10:50:49 2010
From: dreadpiratejeff at gmail.com (J)
Date: Fri, 14 May 2010 10:50:49 -0400
Subject: write a 20GB file
In-Reply-To: 
References: 
	<4BED2E45.6060301@ieee.org>
	
Message-ID: 

On Fri, May 14, 2010 at 07:32, Jackie Lee  wrote:
> Thx, Dave,
>
> The code works fine. I just don't know how f.write works. It says that
> file.write won't write the file until file.close or file.flush. So I
> don't know if the following one is more efficient (sorry I forget to
> add condition to break the loop):

someone smarter than me can correct me, but file.write() will write
when it's buffer is filled, or close() or flush() are called.
I don't know what the default buffer size for file.write() is though.
close() flushes the buffer before closing the file, and flush()
flushes the buffer and leaves the file open for further writing.

> try:
> ? ? ? ?f=open(sys.argv[1],'rb+')
> except (IOError,Exception):
> ? ?print '''usage:
> ? ? ? ?scriptname segyfilename
> '''

You can just add a f.flush() every time you write to the file, but, I
tend to open files with 0 buffer size like this:

f = open(filename,"rb+",0)

Then again, I don't deal with files of that size, so there could be a
problem with my way once you start scaling up to the 20GB or larger
that you're working with.

Again, I could be wrong about all of that, so if so, I hope someone
will correct me and fix my understanding...

Cheers,

Jeff


From albertkao3 at gmail.com  Fri May 14 10:53:18 2010
From: albertkao3 at gmail.com (albert kao)
Date: Fri, 14 May 2010 07:53:18 -0700 (PDT)
Subject: recursively remove all the directories and files which begin with '.'
Message-ID: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>

How do I recursively remove all the directories and files which begin
with '.'?
My test program rmdir.py does not do the job yet.
Please help.
[code]
#!c:/Python31/python.exe -u
import os
from shutil import *

root = "C:\\test\\com.comp.hw.prod.proj.war\\bin"

for curdir, dirs, files in os.walk(root):
  print (curdir)
  print (dirs)
  for d in dirs:
    print ("d " + d)
    if d.startswith('.'):
      print ("dotd " + os.path.join(curdir, d))
      rmtree(os.path.join(curdir, d))
[/code]

C:\python>rmdir.py
C:\test\com.comp.hw.prod.proj.war\bin
['.svn', 'com']
d .svn
dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
Traceback (most recent call last):
  File "C:\python\rmdir.py", line 14, in 
    rmtree(os.path.join(curdir, d))
  File "C:\Python31\lib\shutil.py", line 235, in rmtree
    onerror(os.remove, fullname, sys.exc_info())
  File "C:\Python31\lib\shutil.py", line 233, in rmtree
    os.remove(fullname)
WindowsError: [Error 5] Access is denied: 'C:\\test\
\com.comp.hw.prod.proj.war\\bin\\.svn\\entries'



From pmaupin at gmail.com  Fri May 14 10:56:09 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 07:56:09 -0700 (PDT)
Subject: Picking a license
References:  
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
	<9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com>
Message-ID: <548024fc-dd56-48b9-907d-3aa6a722b43c@l31g2000yqm.googlegroups.com>

On May 14, 8:47?am, Paul Boddie  wrote:
> On 14 Mai, 05:35, Patrick Maupin  wrote:
>
>
>
> > I mean, it's in English and very technically precise, but if you
> > follow all the references, you quickly come to realize that the
> > license is a "patch" to the GPL.
>
> It is a set of exceptions applied to version 3 of the GPL, done this
> way so that the exceptions machinery of the GPL can be used to remove
> them if desired, as opposed to getting into the business of allowing
> people to relicense works from the LGPL to the GPL, as was the case
> with previous versions of these licences. You don't even have to read
> as far as the first clause of the LGPL terms to be told this, but I
> guess there's more "sport" in taking cheap shots at the authors than
> reading three lines down from the top of the text.
>
> Paul

That's not a cheap shot.  It's a (programmer) technical description of
how the licenses interact, along with an opinion that it would be
easier to read otherwise, along with a quoted snippet that shows (at
least to me) that these are really quite complicated licenses.  The
confusion that some are showing in this thread about whether source
must be distributed certainly helps to show that as well.  Now, it may
well be, and probably is, that the licenses are as simple as they can
be for the desired effect, but that doesn't make them simple.

Regards,
Pat


From pmaupin at gmail.com  Fri May 14 10:57:25 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 07:57:25 -0700 (PDT)
Subject: Picking a license
References: 
Message-ID: <578ec00e-86ac-46d3-8ae9-d26d43068652@r11g2000yqa.googlegroups.com>

On May 14, 9:10?am, Ed Keith  wrote:
> --- On Thu, 5/13/10, Patrick Maupin  wrote:
>
>
>
> > From: Patrick Maupin 
> > Subject: Re: Picking a license
> > To: python-l... at python.org
> > Date: Thursday, May 13, 2010, 11:35 PM
> > On May 13, 10:07?pm, Lawrence
> > D'Oliveiro  > central.gen.new_zealand> wrote:
>
> > > How exactly does the LGPL lead to a requirement to
> > ?relink??
>
> > I think this might be a misconception, but I'm not 100%
> > sure.? Since
> > Ed gives his customers full source code, there may not be
> > the
> > requirement to directly provide the ability to relink,
> > because "The
> > ?Corresponding Application Code? for a Combined Work
> > means the object
> > code and/or source code for the Application." and section
> > 4d0 requires
> > you to "permit the user to recombine or relink" where
> > "recombine"
> > isn't defined directly (perhaps in the underlying GPL?)
>
> But if my client give someone else a copy of the binary I gave them, they are now in violation. I do not want to put my client in this position.
>
> When using the GPL or LGPL you can do anything you want as long as you do not let anyone else use your work, but if you let someone else have a copy of you work you are putting them in a position where that can easily/inadvertently violate the law. I do not want to put clients in legal jeopardy, so I do not use GPL, or LGPLed code.

Good point.  I guess I haven't distributed something linked in a while
(really just Python), so I tend to forget that aspect of it.

Regards,
Pat



From kaklis at gmail.com  Fri May 14 10:57:48 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Fri, 14 May 2010 07:57:48 -0700 (PDT)
Subject: parsing XML
Message-ID: 

Hi to all, let's say we have the following Xml

  
    17.1
    6.4
  
  
    15.5
    7.8
  


How can i get the players name, age and height?
DOM or SAX and how

Thanks
Antonis


From dreadpiratejeff at gmail.com  Fri May 14 11:01:22 2010
From: dreadpiratejeff at gmail.com (J)
Date: Fri, 14 May 2010 11:01:22 -0400
Subject: recursively remove all the directories and files which begin with
	'.'
In-Reply-To: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>
References: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>
Message-ID: 

On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>
> C:\python>rmdir.py
> C:\test\com.comp.hw.prod.proj.war\bin
> ['.svn', 'com']
> d .svn
> dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
> Traceback (most recent call last):
> ?File "C:\python\rmdir.py", line 14, in 
> ? ?rmtree(os.path.join(curdir, d))
> ?File "C:\Python31\lib\shutil.py", line 235, in rmtree
> ? ?onerror(os.remove, fullname, sys.exc_info())
> ?File "C:\Python31\lib\shutil.py", line 233, in rmtree
> ? ?os.remove(fullname)
> WindowsError: [Error 5] Access is denied: 'C:\\test\
> \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

You don't have permissions to remove the subdir or file entries in the
.svn directory...

Maybe that file is still open, or still has a lock attached to it?


From pmaupin at gmail.com  Fri May 14 11:04:53 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 08:04:53 -0700 (PDT)
Subject: Picking a license
References: 
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com> 
	 
	<4bece8de$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <79811fa0-f8bb-4ec8-acc3-a4a1727a8e78@k42g2000yqb.googlegroups.com>

On May 14, 1:08?am, Steven D'Aprano  wrote:
> On Thu, 13 May 2010 19:10:09 -0700, Patrick Maupin wrote:
> > The broken window fallacy is about labor that could have been spent
> > elsewhere if someone else had done something differently. ?The only time
> > that comes into play in my programming life is when I have to recode
> > something that is nominally available under the GPL, so I'm not sure
> > this is really making the point you think it is.
>
> You've never had to recode something because it was nominally available
> under a proprietary licence that you (or your client) was unwilling to
> use? Lucky you!

Don't be silly.  That's why I started writing open source software in
the first place.  But if I start writing stuff to put in the commons
with strings removed, why would I bother with a license that just adds
some strings back?

> The GPL ensures that once software has entered the commons (and therefore
> available for all), it can never be removed from the commons.

No it doesn't.  It just insures that if people actually *distribute*
the software to others, they have to distribute the source.  In any
case, for software to remain in the commons, it has to be available
where people can get to it.  Somebody has to care enough to maintain a
repository, or it has to be good enough for people to distribute.

> The MIT licence does not.

The only difference is that somebody has to care enough to maintain a
repository, or it has to be good enough for people to distribute
*along with source*.

> Now, you might argue that in practice once software is
> released under an MIT licence, it is unlikely to ever disappear from the
> commons.

Depends on the software.  See above.

> Well, perhaps, but if so, that's despite and not because of the
> licence.

Same thing for GPLed software.  See above.

> In practice, I believe most MIT-licenced code never even makes it into
> the commons in the first place.

Interesting assertion.

> I'm willing to predict that the majority
> of code you've written for paying customers (as opposed to specifically
> for open source projects) has disappeared into their code base, never to
> be seen by anyone outside of the company. Am I right?

That's true, but what on earth does that have to do with the MIT
license?

Regards,
Pat


From martin at v.loewis.de  Fri May 14 11:07:01 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Fri, 14 May 2010 17:07:01 +0200
Subject: write a 20GB file
In-Reply-To: 
References: 	<4BED2E45.6060301@ieee.org>
	
Message-ID: <4BED6715.1000106@v.loewis.de>

> The code works fine. I just don't know how f.write works. It says that
> file.write won't write the file until file.close or file.flush.

You are misinterpreting the documentation. It certainly won't keep the
entire file in memory. Instead, it has a fixed-size buffer (something
like 8kiB or 32kiB) in which it writes and which it flushes when that
buffer is full.

The comment about flush and close merely refers to the problem that some
data may still be in the buffer at any point in time, unless you just
called close or flush.

HTH,
Martin


From martin at v.loewis.de  Fri May 14 11:07:01 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Fri, 14 May 2010 17:07:01 +0200
Subject: write a 20GB file
In-Reply-To: 
References: 	<4BED2E45.6060301@ieee.org>
	
Message-ID: <4BED6715.1000106@v.loewis.de>

> The code works fine. I just don't know how f.write works. It says that
> file.write won't write the file until file.close or file.flush.

You are misinterpreting the documentation. It certainly won't keep the
entire file in memory. Instead, it has a fixed-size buffer (something
like 8kiB or 32kiB) in which it writes and which it flushes when that
buffer is full.

The comment about flush and close merely refers to the problem that some
data may still be in the buffer at any point in time, unless you just
called close or flush.

HTH,
Martin


From martin at v.loewis.de  Fri May 14 11:15:07 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Fri, 14 May 2010 17:15:07 +0200
Subject: parsing XML
In-Reply-To: 
References: 
Message-ID: 

kaklis at gmail.com wrote:
> Hi to all, let's say we have the following Xml
> 
>   
>     17.1
>     6.4
>   
>   
>     15.5
>     7.8
>   
> 
> 
> How can i get the players name, age and height?
> DOM or SAX and how

Homework?

Martin


From paul at boddie.org.uk  Fri May 14 11:20:06 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 08:20:06 -0700 (PDT)
Subject: Picking a license
References: 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com> 
	<59194ade-46dc-4178-8b76-36038808109b@k2g2000yqe.googlegroups.com> 
	<4bece6a8$0$8761$c3e8da3@news.astraweb.com>
	<804512fb-e9ac-4284-a577-84e609531e06@s4g2000prh.googlegroups.com>
Message-ID: 

On 14 Mai, 09:08, Carl Banks  wrote:
> On May 13, 10:59?pm, Steven D'Aprano  wrote:
> > On Thu, 13 May 2010 17:18:47 -0700, Carl Banks wrote:
> > > 2. Reimplment the functionality seperately (*cough* PySide)
>
> > Yes. So what? In what possible way is this an argument against the GPL?

[...]

> It's not. ?It's an argument that the GPL doesn't do much good.

Right. So nobody got the benefit from Qt under the GPL or PyQt under
the GPL? Even the PySide developers seem hell-bent on picking over the
work of the PyQt developers for ideas, although they obviously won't
touch the code. Nokia seem to have accrued tremendous benefit from the
existence of PyQt because I rather doubt that anyone would have
bothered rolling a set of mature, usable Python bindings for Qt now
had some not existed already and proved that dynamic languages are
worth supporting.

> Arguments against the GPL are found elsewhere in this thread, I don't
> need to repeat them here.

Yes, don't bother. They fit in rather well with the comment you made
above.

Paul


From stefan_ml at behnel.de  Fri May 14 11:22:47 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 14 May 2010 17:22:47 +0200
Subject: parsing XML
In-Reply-To: 
References: 
Message-ID: 

kaklis at gmail.com, 14.05.2010 16:57:
> Hi to all, let's say we have the following Xml
> 
>    
>      17.1
>      6.4
>    
>    
>      15.5
>      7.8
>    
> 
>
> How can i get the players name, age and height?

Here's an overly complicated solution, but I thought that an object 
oriented design would help here.


   import xml.etree.ElementTree as ET

   class Player(object):
      def __init__(self, name, age, height):
          self.name, self.age, self.height = name, age, height

   attributes = ['name', 'age', 'height']

   players = []
   for _, element in ET.iterparse("teamfile.xml"):
       if element.tag == 'player':
           players.append(
               Player(*[ element.get(attr) for attr in attributes ]))

   for player in players:
       print player.name, player.age, player.height


Stefan



From gberbeglia at gmail.com  Fri May 14 11:24:24 2010
From: gberbeglia at gmail.com (gerardob)
Date: Fri, 14 May 2010 08:24:24 -0700 (PDT)
Subject: an element from a set
Message-ID: <28560792.post@talk.nabble.com>


Hello, let S be a python set which is not empty
(http://docs.python.org/library/sets.html)

i would like to obtain one element (anyone, it doesn't matter which one) and
assign it to a variable.

How can i do this? 

Thanks.

-- 
View this message in context: http://old.nabble.com/an-element-from-a-set-tp28560792p28560792.html
Sent from the Python - python-list mailing list archive at Nabble.com.



From albertkao3 at gmail.com  Fri May 14 11:27:50 2010
From: albertkao3 at gmail.com (albert kao)
Date: Fri, 14 May 2010 08:27:50 -0700 (PDT)
Subject: recursively remove all the directories and files which begin with
	'.'
References: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>
	
Message-ID: <67827508-ddda-44e8-8b88-aae4f78e23da@o8g2000yqo.googlegroups.com>

On May 14, 11:01?am, J  wrote:
> On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>
> > C:\python>rmdir.py
> > C:\test\com.comp.hw.prod.proj.war\bin
> > ['.svn', 'com']
> > d .svn
> > dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
> > Traceback (most recent call last):
> > ?File "C:\python\rmdir.py", line 14, in 
> > ? ?rmtree(os.path.join(curdir, d))
> > ?File "C:\Python31\lib\shutil.py", line 235, in rmtree
> > ? ?onerror(os.remove, fullname, sys.exc_info())
> > ?File "C:\Python31\lib\shutil.py", line 233, in rmtree
> > ? ?os.remove(fullname)
> > WindowsError: [Error 5] Access is denied: 'C:\\test\
> > \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> You don't have permissions to remove the subdir or file entries in the
> .svn directory...
>
> Maybe that file is still open, or still has a lock attached to it?

I reboot my windows computer and run this script as administrator.
Do my script has a bug?


From pmaupin at gmail.com  Fri May 14 11:37:14 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 08:37:14 -0700 (PDT)
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	
Message-ID: <94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com>

On May 14, 8:26?am, Paul Boddie  wrote:
> On 13 Mai, 22:10, Patrick Maupin  wrote:
> Just to deal with your Ubuntu "high horse" situation first, you should
> take a look at the following for what people regard to be the best
> practices around GPL-licensed software distribution:
>
> http://www.softwarefreedom.org/resources/2008/compliance-guide.html

Before, you were busy pointing me at the GPL FAQ as authoritative.
When I show where the FAQ says that you should distribute source if
you give somebody a CD, you point me at a document which is obviously
designed for the Ciscos of the world.

> If you still think Ubuntu are violating the GPL or encouraging others
> to do so, feel free to contact their lawyers who I'm sure will be very
> interested to hear from you.

Did I *ever* say that Ubuntu was violating the GPL.  No.  Do I believe
that the practices of any binary Linux distribution that fits on a
single CD make it easy for the downloader/burner to violate the GPL.
Yes.
>
> > When the leader of your religion bandies terms like "freedom" and
> > "evil" about, what do you expect? ?Seriously?
>
> I thought you were "done". I guess you are: again, we have the usual
> courting of public outrage by labelling stuff you don't like as
> "religion" - presumably not the "right one", either - when it is no
> such thing.

Well, you conveniently ignore sections of your bible (for example, the
part of the FAQ where it says you should distribute source with
binary) and reach for more obscure scrolls whenever the real world
gets in the way of your fantasy.  Even here, you don't bother to quote
what you wrote, which would show I am just responding to your outrage.

> > My primary agenda is to explain that RMS does, in fact, have an
> > agenda, and the GPL was designed as a tool in furtherance of that
> > agenda, and that while the agenda does have some arguably noble goals,
> > before using the GPL people should understand its consequences both
> > for good and bad, and make their own determination about whether it's
> > the right license for their project.
>
> Reading through your "translations" of what are effectively honest
> summaries.

There are multiple sides to every discussion, and everybody comes to
the table with biases.  If you honestly think that you are not biased,
then you are deluding yourself.  If you realize that you are biased,
then you will also come to realize that my translations are equally
honest.

> one gets the impression that you have quite a chip on your
> shoulder about the FSF and RMS.

I can take them or leave them until they and their followers start
spouting damaging nonsense.  Many businesses were scared to death of
FOSS for many years, and I lay the blame squarely on RMS's shoulders.
You see only the good he has done; it is tempered by quite a bit of
bad.

> Referring to the GPL as a "commercial"
> licence and stating that it (as opposed to any other licence or even
> the word "copyright" followed by a name) is a threat to sue people,
> presumably appealing to the libertarian crowd with a judicious mention
> of "government" just to fan the flames of supposed injustice, really
> does triangulate where you are coming from. So, yes, we're now rather
> more aware of what your agenda is, I think.

I'm not the one who keeps spouting that it "gives" freedoms (or even
privileges) that copyright would have taken away.  That's complete
bullshit.  As I said, copyright *allows* the author to control various
aspects of his work ("take away freedoms" in GPL-speak), and all
licenses (including the GPL) explicitly state which aspects the author
plans to control.  The only way the author can really exert control is
to sue or credibly threaten to sue.  I can actually point to multiple
instances of GPL authors suing, and people like you crowing about how
great it is that the GPL stands up in court, but I don't actually
recall any suits about violations of the MIT or Apache licenses.  So,
yes, I firmly believe that when somebody slaps a GPL license on their
software (and especially if they sign the copyrights over to the FSF)
they are trying to signal that they are willing to go to court to
protect their rights.  This is no different than when Microsoft sues
an infringer, and is not an evil thing, but it is definitely something
to be aware of.  The easiest way to not get tangled in that kind of
lawsuit is to just make sure that you never distribute any software
with a commercial-type license on it (including the GPL).

> And I don't think it improves any argument you may have by projecting
> notions of "morality" or "immorality" onto what I have written,

But you're arguing from a moral standpoint.

> especially when I have deliberately chosen to use other terms which
> avoid involving such notions

Yes, but you're making exactly the same arguments as others, just
changing the name.

> or by equating the copyleft licences
> with criminal enterprises ("pyramid scheme"),

Well, that may be a bit OTT.  What I really should say is that the GPL
license has a "selfish gene."  It tries really hard to propagate
itself, at the expense of the genes of other licenses.

> or by suggesting that I
> endorse criminal endeavours.

Hmmm, don't recall doing that.  If I did, I certainly apologize.

> But if that's what you have left to say
> at this point, then I think you probably are "done".

Well, I thought I was before, but then the discussion about
downloading an ISO and burning it and giving it to a friend came up.
This may be technically allowable under the license, but nothing you
or anybody else has written has yet proved that to me.

Regards,
Pat



From pmaupin at gmail.com  Fri May 14 11:42:56 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 08:42:56 -0700 (PDT)
Subject: Picking a license
References:  
	
	<2ff3643b-6ef1-4471-8438-dcba0dc93c24@a21g2000yqn.googlegroups.com>
	
Message-ID: 

On May 14, 6:12?am, Lawrence D'Oliveiro  wrote:
> In message <2ff3643b-6ef1-4471-8438-
>
>
>
> dcba0dc93... at a21g2000yqn.googlegroups.com>, Patrick Maupin wrote:
> > On May 13, 10:04 pm, Lawrence D'Oliveiro
> >  wrote:
>
> >> In message , Ed
> >> Keith wrote:
>
> >>> The claim is being made that [the GPL] restricts freedom.
>
> >> What about the ?freedom? to restrict other people?s freedom? Should that
> >> be restricted or not?
>
> > It's interesting that some people don't like the comparison of the
> > Free Software movement to a religion, yet the main argument of the
> > movement, and the deliberate co-opting of words like "Free" and "Free
> > Software" ...
>
> Haven?t you ?co-opted? those words yourself?

Only in response.  But hey, it's not just me; even Stallman says that
MIT-licensed software is "free software", just not "Free Software".

Regards,
Pat


From pmaupin at gmail.com  Fri May 14 11:47:53 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 08:47:53 -0700 (PDT)
Subject: Picking a license
References:  
	
	<2b17ee77-0e49-4a97-994c-7582f86c0ba9@r34g2000yqj.googlegroups.com>
	
Message-ID: <5e719bcd-5405-4c34-870b-13e64ef1f818@k29g2000yqh.googlegroups.com>

On May 14, 6:13?am, Lawrence D'Oliveiro  wrote:
> In message
> <2b17ee77-0e49-4a97-994c-7582f86c0... at r34g2000yqj.googlegroups.com>, Patrick
>
> Maupin wrote:
> > On May 13, 10:06 pm, Lawrence D'Oliveiro
> >  wrote:
>
> >> Under the GPL, everybody has exactly the same freedoms.
>
> > That's absolutely not true. ?For a start, the original author can dual-
> > license.
>
> That?s nothing to do with the GPL.

If you mean "that's out of the control of the GPL" I agree.  But the
whole point of the discussion has been about how people can't take GPL
licensed code proprietary, making enhancements, etc. and I'm just
pointing out that this doesn't apply to the original author.  Someone
can decide they aren't making enough money under the GPL and stop
distributing that way, and make all their enhancements proprietary, if
they are the original author.

Regards,
Pat


From mrkafk at gmail.com  Fri May 14 11:52:34 2010
From: mrkafk at gmail.com (mk)
Date: Fri, 14 May 2010 17:52:34 +0200
Subject: Picking a license
In-Reply-To: 
References: 
	
Message-ID: 

Steven D'Aprano wrote:
> Are you implying that by distributing your libraries under the MIT or 
> Apache licence, no linking is required? That's a cool trick, can you 
> explain how it works please?

Err.. Linking statically with library in question? Which excludes LGPL 
for legal reasons and doesn't exclude MIT/Apache license for legal reasons?

(this is obviously orthogonal to a technical question why static linking 
should be used sparringly if at all)


Regards,
mk



From toby at rcsreg.com  Fri May 14 11:59:38 2010
From: toby at rcsreg.com (Tobiah)
Date: Fri, 14 May 2010 15:59:38 GMT
Subject: Picking a license
References: 
Message-ID: 


> Assertion II:
>    If person A is free do perform an action person B is not free to
>    perform then person A is free to do more than person B.

This does not hold water.  Let's say there are only 10 activities
available.  Person A can do number 1 and person B can not.  Person
B can do activities 2 through 10, while person A can not.  Therefore,
Person A is indeed free to perform an action that person B is not
free to perform, but person a is *not* free to do more than person B.

Tobiah


From e_d_k at yahoo.com  Fri May 14 12:18:09 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 09:18:09 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <5e719bcd-5405-4c34-870b-13e64ef1f818@k29g2000yqh.googlegroups.com>
Message-ID: <966161.19793.qm@web58707.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Patrick Maupin  wrote:

> From: Patrick Maupin 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 11:47 AM
> On May 14, 6:13?am, Lawrence
> D'Oliveiro  central.gen.new_zealand> wrote:
> > In message
> > <2b17ee77-0e49-4a97-994c-7582f86c0... at r34g2000yqj.googlegroups.com>,
> Patrick
> >
> > Maupin wrote:
> > > On May 13, 10:06 pm, Lawrence D'Oliveiro
> > > 
> wrote:
> >
> > >> Under the GPL, everybody has exactly the same
> freedoms.
> >
> > > That's absolutely not true. ?For a start, the
> original author can dual-
> > > license.
> >
> > That?s nothing to do with the GPL.
> 
> If you mean "that's out of the control of the GPL" I
> agree.? But the
> whole point of the discussion has been about how people
> can't take GPL
> licensed code proprietary, making enhancements, etc. and
> I'm just
> pointing out that this doesn't apply to the original
> author.? Someone
> can decide they aren't making enough money under the GPL
> and stop
> distributing that way, and make all their enhancements
> proprietary, if
> they are the original author.
> 

That is one good reason for choosing to use the GPL, instead of a less 
restrictive license. You can license it, for a fee, to someone who wants to use it in some way that is not allowed under the GPL. If you use a less 
restrictive license that is not an option. Of course you still could put 
restrictions on future enhancements, but the the original code cannot have 
new restrictions put on it, only taken off. If I release code under the GPL today, I can change my mind and release the same code under the Boost 
license tomorrow. But if I release it with the Boost license, while 
technically I can release it with the GPL tomorrow, in practice everyone 
will use the previously released Boost licensed version.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Fri May 14 12:28:30 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 09:28:30 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <980293.99579.qm@web58702.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Tobiah  wrote:

> From: Tobiah 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 11:59 AM
> 
> > Assertion II:
> >? ? If person A is free do perform an action
> person B is not free to
> >? ? perform then person A is free to do more
> than person B.
> 
> This does not hold water.? Let's say there are only 10
> activities
> available.? Person A can do number 1 and person B can
> not.? Person
> B can do activities 2 through 10, while person A can
> not.? Therefore,
> Person A is indeed free to perform an action that person B
> is not
> free to perform, but person a is *not* free to do more than
> person B.

THat argument is valid if and only if the rights of B are not a strict subset of the rights of A. As far as I can tell, the rights granted by the GPL are a strict subset of the right granted by the Boost license. So your argument does not work.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From bryanjugglercryptographer at yahoo.com  Fri May 14 12:33:10 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Fri, 14 May 2010 09:33:10 -0700 (PDT)
Subject: Iterating over dict and removing some elements
References: 
Message-ID: <1e19af7b-226a-4cae-a407-e6285344a28c@6g2000prg.googlegroups.com>

Adi Eyal  wrote:
> > Bryan:
> > Terry Reedy wrote:
> > [...]
> >> for k in [k for k in d if d[k] == 'two']:
> >> ? ? ? ? ?d.pop(k)
>
> > We have a winner.
>
> also
>
> foo = lambda k, d : d[k] == "two"
> d = dict([(k, d[k]) for k in d.keys() if not foo(k, d)])
>
> incidentally, this is marginally slower than pops and dels but has the
> benefit of not modifying the original dict if that's what you need.

Well, I guess, sure. The original problem in this tread was about
modifying the dict over which we are iterating. If you create a new
dict instead, that problem just goes away.

In Python 3.X, and in Python 2.X starting with 2.4, you can drop the
square brackets and avoid creating an extra temporary list:

d = dict((k, d[k]) for k in d.keys() if not foo(k, d))

You can also drop .keys() in Python 3.X or current Python 2.X:

d = dict((k, d[k]) for k in d if not foo(k, d))

Passing the dict to foo() seems inelegant. You could use:

foo = lambda val: val == "two"
d = dict((k, d[k]) for k in d if not foo(d[k]))

I'm sticking with my call of Terry Reedy's last solution as winner. It
solves the originally-stated problem, works correctly and efficiently
in both Python 3.X and current Python 2.X, and there is not a bracket
in it that does not need to be there.

--
--Bryan


From tjreedy at udel.edu  Fri May 14 12:39:43 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Fri, 14 May 2010 12:39:43 -0400
Subject: an element from a set
In-Reply-To: <28560792.post@talk.nabble.com>
References: <28560792.post@talk.nabble.com>
Message-ID: 

On 5/14/2010 11:24 AM, gerardob wrote:
>
> Hello, let S be a python set which is not empty
> (http://docs.python.org/library/sets.html)
>
> i would like to obtain one element (anyone, it doesn't matter which one) and
> assign it to a variable.
>
> How can i do this?

Depends on whether or not you want the element removed from the set

#3.1
 >>> s=set(range(10))
 >>> s
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
 >>> x=next(iter(s))
 >>> x
0
 >>> s
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
 >>> x = s.pop()
 >>> x
0
 >>> s
{1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed

The choice of 0 is an implementation artifact. It could have been any 
member.

Terry Jan Reedy





From paul at boddie.org.uk  Fri May 14 12:48:59 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 09:48:59 -0700 (PDT)
Subject: Picking a license
References: 
	
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com>
Message-ID: <3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com>

On 14 Mai, 17:37, Patrick Maupin  wrote:
>
> Before, you were busy pointing me at the GPL FAQ as authoritative.

No, the licence is the authority, although the FAQ would probably be
useful to clarify the licence author's intent in a litigation
environment.

[Fast-forward through the usual tirade, this time featuring words like
"bible", "moral", "evil"...]

> Well, I thought I was before, but then the discussion about
> downloading an ISO and burning it and giving it to a friend came up.
> This may be technically allowable under the license, but nothing you
> or anybody else has written has yet proved that to me.

Section 3 of GPLv2 (and section 6(d) of GPLv3 reads similarly): "If
distribution of executable or object code is made by offering access
to copy from a designated place, then offering equivalent access to
copy the source code from the same place counts as distribution of the
source code, even though third parties are not compelled to copy the
source along with the object code."

And here's that FAQ entry which clarifies the intent:

http://www.gnu.org/licenses/gpl-faq.html#DistributeWithSourceOnInternet

Like I said, if you really have a problem with Ubuntu shipping CDs and
exposing others to copyright infringement litigation - or even
themselves, since they (and all major distributions) are actively
distributing binaries but not necessarily sources in the very same
download or on the very same disc - then maybe you should take it up
with them.

Paul


From pmaupin at gmail.com  Fri May 14 13:00:47 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 10:00:47 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com
Message-ID: 

On May 14, 10:20?am, Paul Boddie  wrote:
> On 14 Mai, 09:08, Carl Banks  wrote:
>
> > On May 13, 10:59?pm, Steven D'Aprano  wrote:
> > > On Thu, 13 May 2010 17:18:47 -0700, Carl Banks wrote:
> > > > 2. Reimplment the functionality seperately (*cough* PySide)
>
> > > Yes. So what? In what possible way is this an argument against the GPL?
>
> [...]
>
> > It's not. ?It's an argument that the GPL doesn't do much good.
>
> Right. So nobody got the benefit from Qt under the GPL or PyQt under
> the GPL? Even the PySide developers seem hell-bent on picking over the
> work of the PyQt developers for ideas, although they obviously won't
> touch the code. Nokia seem to have accrued tremendous benefit from the
> existence of PyQt because I rather doubt that anyone would have
> bothered rolling a set of mature, usable Python bindings for Qt now
> had some not existed already and proved that dynamic languages are
> worth supporting.

Perhaps he should have said "the GPL doesn't do any more good than any
other commercial license."

After all, lots of software ideas proved their worth in proprietary
systems, and then were later cloned by FOSS developers.  In many
cases, these clones are, functionally, almost exact copies.  That's
why all the really proprietary people are hell-bent on trying to get
or maintain patent protection -- copyright doesn't protect
"inventions".

Would you have agreed had he had said that "MatLab's license doesn't
do much good" and assigned the same sort of meaning to that statement,
namely that the MatLab license prevented enough motivated people from
freely using MatLab in ways that were important to them?  Obviously,
it was important enough to enough people that they went and built the
GPLed Octave software, which now emulates MatLab very closely.  As I
think both Ed and I have said before, the GPL can be a great license
for a full-blown *program* (like Octave) that people can just download
and use, but is not always so great for program *pieces* that are
designed to be used in the programmatic equivalent of a "mash-up",
like PyQt/PySide, so the cloning of PyQt into PySide is as inevitable
as the cloning of MatLab into Octave, or Unix/Minix into Linux.  As
far as your comments about PyQt proving out the concept, well duh!
Just as there are a lot of proprietary programs that are relatively
useless and *won't* have any GPLed versions written, nobody's going to
waste time rewriting a marginally useful GPLed library just to put a
permissive license on it, either.  They are either going to write
something completely different in the hopes that their vision is
correct, or are going to copy at least some parts of the design and/or
vision of something that is popular and useful.  And that's a great
thing.  It would have been horribly unproductive if the Linux API
weren't at least reasonably close to the Unix API, for example.

It's an interesting tension between the licenses.  Nobody rewrites
permissively licensed software as GPL simply because the license is
unacceptable, but just as people will rewrite proprietary programs and
libraries as GPL because the license is unacceptable, so will some
rewrite GPLed libraries as permissive because the license is
unacceptable.

Regards,
Pat


From switch2mathan at gmail.com  Fri May 14 13:15:36 2010
From: switch2mathan at gmail.com (MathanK)
Date: Fri, 14 May 2010 05:15:36 -1200
Subject: Alternate string object type for PyStringObject(available Python
	2.x) in python 3.x?
Message-ID: <12897d06413.515885629628951451.7220101516557890617@gmail.com>

What is the replacement in python 3.x for PyStringObject which is available in python 2.x?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From pmaupin at gmail.com  Fri May 14 13:15:51 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 10:15:51 -0700 (PDT)
Subject: Picking a license
References: 
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com>
Message-ID: <29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com>

On May 14, 11:48?am, Paul Boddie  wrote:
> On 14 Mai, 17:37, Patrick Maupin  wrote:
>
>
>
> > Before, you were busy pointing me at the GPL FAQ as authoritative.
>
> No, the licence is the authority, although the FAQ would probably be
> useful to clarify the licence author's intent in a litigation
> environment.

Agreed.

> Section 3 of GPLv2 (and section 6(d) of GPLv3 reads similarly): "If
> distribution of executable or object code is made by offering access
> to copy from a designated place, then offering equivalent access to
> copy the source code from the same place counts as distribution of the
> source code, even though third parties are not compelled to copy the
> source along with the object code."
>
> And here's that FAQ entry which clarifies the intent:
>
> http://www.gnu.org/licenses/gpl-faq.html#DistributeWithSourceOnInternet

That entry, along with the written offer, certainly covers Ubuntu when
they distribute a CD.

But if I *download* an ISO, burn it on a CD, and give it away, *I* am
the one distributing the physical copy, not Ubuntu, and I am not going
to put up an FTP server just so my friend can get source from it.  And
as section 6 of GPL v3 makes clear, I am not allowed to piggyback on
Ubuntu's source offer.  My situation *really is* covered by the FAQ
entry I referred you to:

http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary

> Like I said, if you really have a problem with Ubuntu shipping CDs and
> exposing others to copyright infringement litigation.

So, deliberately or not, you're trying to change the discussion
again.  I *never* discussed Ubuntu shipping a physical CD, and never
intimated that that was a problem.  My discussion was *always* about
an individual *downloading* an ISO and *burning* a CD himself, then
*distributing* the CD to someone else.

> - or even
> themselves, since they (and all major distributions) are actively
> distributing binaries but not necessarily sources in the very same
> download or on the very same disc - then maybe you should take it up
> with them.

Again, I never intimated this.  Please read more carefully in the
future before you reply, and then perhaps you will actually make
cogent replies that address my points, and then I won't be so
frustrated that I make snide comments you take offense at, OK?  This
has happened on at least 4 separate occasions in this thread, and
sometimes a single misunderstanding goes on for quite a few posts, so
I'm starting to wonder if it's deliberate.

Regards,
Pat


From mannu_0523 at rediffmail.com  Fri May 14 13:22:37 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 14 May 2010 17:22:37 -0000
Subject: =?utf-8?B?am9pbmluZyB0d28gY29sdW1u?=
Message-ID: <20100514172237.23776.qmail@f4mail-235-238.rediffmail.com>

Hi,

I have two different file 

file1:

a1 a2
a3 a4
a5 a6
a7 a8
 
file2:

b1 b2
b3 b4 
b5 b6
b7 b8

and I want to join them so the output should look like this:

a1 a2 b1 b2
a3 a4 b3 b4
a5 a6 b5 b6
a7 a8 b7 b8

how to do that?




-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From albert at spenarnc.xs4all.nl  Fri May 14 13:36:20 2010
From: albert at spenarnc.xs4all.nl (Albert van der Horst)
Date: 14 May 2010 17:36:20 GMT
Subject: Picking a license
References: 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com>
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g20
	<4be95545$1@dnews.tpgi.com.au>
Message-ID: 

In article <4be95545$1 at dnews.tpgi.com.au>,
Lie Ryan   wrote:



>
>Come on, 99%  of the projects released under GPL did so because they
>don't want to learn much about the law; they just need to release it
>under a certain license so their users have some legal certainty. Most
>programmers are not lawyers and don't care about the law and don't care
>about the GPL; if a commercial programmer want to use the GPL-code in an
>incompatible licensed program, and he comes up asking, many would just
>be happy to say yes.

This is a big reason for me to release everything (see my website,
it is a *lot*) under GPL. If someone wants to use it they can,
if someone wants to use it commercially, they can too, as long
as they pay me a little bit too. Really, I'm reasonable.

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst



From prologic at shortcircuit.net.au  Fri May 14 13:55:38 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sat, 15 May 2010 03:55:38 +1000
Subject: joining two column
In-Reply-To: <20100514172237.23776.qmail@f4mail-235-238.rediffmail.com>
References: <20100514172237.23776.qmail@f4mail-235-238.rediffmail.com>
Message-ID: 

On Sat, May 15, 2010 at 3:22 AM, mannu jha  wrote:
> Hi,
>
> I have two different file
>
> file1:
>
> a1 a2
> a3 a4
> a5 a6
> a7 a8
>
> file2:
>
> b1 b2
> b3 b4
> b5 b6
> b7 b8
>
> and I want to join them so the output should look like this:
>
> a1 a2 b1 b2
> a3 a4 b3 b4
> a5 a6 b5 b6
> a7 a8 b7 b8
>
> how to do that?

This is completely untested, but this "should" (tm) work:

from itertools import chain

input1 = open("input1.txt", "r").readlines()
input2 = open("input2.txt", "r").readlines()
open("output.txt", "w").write("".join(chain(input1, input2)))

cheers
James


From paul at boddie.org.uk  Fri May 14 14:07:38 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 11:07:38 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
Message-ID: 

On 14 Mai, 19:00, Patrick Maupin  wrote:
>
> Would you have agreed had he had said that "MatLab's license doesn't
> do much good" and assigned the same sort of meaning to that statement,
> namely that the MatLab license prevented enough motivated people from
> freely using MatLab in ways that were important to them? ?Obviously,
> it was important enough to enough people that they went and built the
> GPLed Octave software, which now emulates MatLab very closely.

I don't need to answer your question. It's obvious that the licence
doesn't do much good when people seek to create a platform which is
genuinely and irrevocably open as a response. That they have done so
using the GPL pretty much sinks the previous ridiculous statement
about the GPL, too, unless Octave is somehow a bad thing (which is
what a certain vendor of proprietary statistics software would have
you believe about a certain widely-used statistical analysis tool).
Although people can argue that usage of the GPL prevents people from
potentially contributing because they would not be able to sell
proprietary versions of the software, it has been in no way
demonstrated to be universally true that such contributors would
contribute more than those who do so because of the copyleft
licensing. The creators of Octave are obviously not willing to create
(or help create) another system with all the proprietary limitations
of MatLab, and why should they be willing? The production of a
different "proprietary flavour" of MatLab wouldn't be beneficial to
them at all - it might even be detrimental to their project - and
might only be marginally beneficial, at best, to existing MatLab
customers.

[PySide]

> Just as there are a lot of proprietary programs that are relatively
> useless and *won't* have any GPLed versions written, nobody's going to
> waste time rewriting a marginally useful GPLed library just to put a
> permissive license on it, either.

Unless they really want to release (or encourage the creation of)
proprietary software, which is precisely what PySide is all about.
(And PyQt is not "marginally useful" - it is a widely-used and widely
well-regarded library.) And this apparent overriding need to support
proprietary solutions results in different strategies, such as with
the Chandler project: because the OSAF wanted to be able to sell
proprietary solutions but didn't own all the code, they decided to
pick only permissively licensed software for the components of the
solution, resulting in a lot of extra effort expended in getting their
user interface toolkit up to scratch. You can make your own mind up
about whether that was a sensible strategy.

Usually, however, most people wanting to write proprietary software
cannot be bothered to do the work to replicate an existing GPL-
licensed solution (or even to significantly improve permissively
licensed solutions). They instead appeal to people to release already-
mature permissively licensed software, typically waiting for someone
with enough money or manpower to do most of the work for them. Again,
this is precisely why PySide appeals to a certain audience.

Paul


From e_d_k at yahoo.com  Fri May 14 14:11:27 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 11:11:27 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <82399.84016.qm@web58705.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Albert van der Horst  wrote:
 
> This is a big reason for me to release everything (see my
> website,
> it is a *lot*) under GPL. If someone wants to use it they
> can,
> if someone wants to use it commercially, they can too, as
> long
> as they pay me a little bit too. Really, I'm reasonable.

I have no problem with that. 

I have played with your forth assembler a bit. It is good work, and the 
best part is that I can read the source and learn from it. Putting it out 
under GPL allows me to learn from it, and you to profit from it, a real 
win/win. Thank you very much for making it available.

I'm working on an assembler myself. I may steal your ideas, but I will not 
steal your code. I'm writing it in ocaml, your forth code would not be 
easy to translate. When/if I finish I'll publish it under a less restrictive open source license, because I do not think I would be able to 
persuade anyone else to pay for a commercial license. But I do not fault 
you if you think you can. 

If I did use your code I would either publish under the GPL or not publish 
at all depending on the exact circumstances. I have been know, on rare occasions, to use GPLed code in my own work (mostly plug-ins for GPLed applications). I just refuse to use it in any code for a client, because I do not want to require someone who does not know source code from Morse code code to figure out what they need to do to avoid violating the license. When I deliver my code to the client they are always free to do whatever they want with it. 

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com



      


From kaklis at gmail.com  Fri May 14 14:23:52 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Fri, 14 May 2010 11:23:52 -0700 (PDT)
Subject: parsing XML
References: 
	
Message-ID: <620efb1b-9c7c-46dc-8bfb-477daa67692c@o14g2000yqb.googlegroups.com>

On May 14, 6:22?pm, Stefan Behnel  wrote:
> kak... at gmail.com, 14.05.2010 16:57:
>
> > Hi to all, let's say we have the following Xml
> > 
> > ? ?
> > ? ? ?17.1
> > ? ? ?6.4
> > ? ?
> > ? ?
> > ? ? ?15.5
> > ? ? ?7.8
> > ? ?
> > 
>
> > How can i get the players name, age and height?
>
> Here's an overly complicated solution, but I thought that an object
> oriented design would help here.
>
> ? ?import xml.etree.ElementTree as ET
>
> ? ?class Player(object):
> ? ? ? def __init__(self, name, age, height):
> ? ? ? ? ? self.name, self.age, self.height = name, age, height
>
> ? ?attributes = ['name', 'age', 'height']
>
> ? ?players = []
> ? ?for _, element in ET.iterparse("teamfile.xml"):
> ? ? ? ?if element.tag == 'player':
> ? ? ? ? ? ?players.append(
> ? ? ? ? ? ? ? ?Player(*[ element.get(attr) for attr in attributes ]))
>
> ? ?for player in players:
> ? ? ? ?print player.name, player.age, player.height
>
> Stefan

Thanks stefan!

A.K.


From pmaupin at gmail.com  Fri May 14 14:36:54 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 11:36:54 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
	
Message-ID: 

On May 14, 1:07?pm, Paul Boddie  wrote:
> On 14 Mai, 19:00, Patrick Maupin  wrote:

> > Would you have agreed had he had said that "MatLab's license doesn't
> > do much good" and assigned the same sort of meaning to that statement,
> > namely that the MatLab license prevented enough motivated people from
> > freely using MatLab in ways that were important to them? ?Obviously,
> > it was important enough to enough people that they went and built the
> > GPLed Octave software, which now emulates MatLab very closely.
>
> I don't need to answer your question. It's obvious that the licence
> doesn't do much good when people seek to create a platform which is
> genuinely and irrevocably open as a response. That they have done so
> using the GPL pretty much sinks the previous ridiculous statement
> about the GPL, too.

That statement was made in the context of why Carl doesn't use GPL-
licensed *libraries*.  He and I have both explained the difference
between libraries and programs multiple times, not that you care.

> unless Octave is somehow a bad thing (which is
> what a certain vendor of proprietary statistics software would have
> you believe about a certain widely-used statistical analysis tool).
> Although people can argue that usage of the GPL prevents people from
> potentially contributing because they would not be able to sell
> proprietary versions of the software, it has been in no way
> demonstrated to be universally true that such contributors would
> contribute more than those who do so because of the copyleft
> licensing.

As I have said before, the availability of multiple (but not too
many!) licenses is a great thing, because each contributor can decide
how he wants to license his creation.  Finding the right license to
contribute under can only enhance the commons.

> The creators of Octave are obviously not willing to create
> (or help create) another system with all the proprietary limitations
> of MatLab, and why should they be willing?

I don't presume to know their motivations, or how the license got
chosen.  However, once it was under the GPL and there were multiple
contributors, it would certainly be difficult to relicense any other
way.

> The production of a
> different "proprietary flavour" of MatLab wouldn't be beneficial to
> them at all - it might even be detrimental to their project - and
> might only be marginally beneficial, at best, to existing MatLab
> customers.

I personally can't see any realistic chance of detriment.  How could a
proprietary clone hope to compete against free software on one side
and real matlab on the other side?  That's a no-win position, so I
wouldn't expect to see any proprietary clones.

> [PySide]
>
> > Just as there are a lot of proprietary programs that are relatively
> > useless and *won't* have any GPLed versions written, nobody's going to
> > waste time rewriting a marginally useful GPLed library just to put a
> > permissive license on it, either.
>
> Unless they really want to release (or encourage the creation of)
> proprietary software.

How does recreating something marginally useful encourage proprietary
software?  That's very confusing.

> which is precisely what PySide is all about.

No, PySide is about non-GPL software, and is released under a license
that even RMS recognizes as "free", and it is certainly not of
marginal utility.

> (And PyQt is not "marginally useful" - it is a widely-used and widely
> well-regarded library.)

Well, we agree on that.  But I don't know why you're trying to claim I
said PyQt was only marginally useful.

> And this apparent overriding need to support
> proprietary solutions results in different strategies, such as with
> the Chandler project: because the OSAF wanted to be able to sell
> proprietary solutions but didn't own all the code, they decided to
> pick only permissively licensed software for the components of the
> solution, resulting in a lot of extra effort expended in getting their
> user interface toolkit up to scratch. You can make your own mind up
> about whether that was a sensible strategy.

Large, high-risk projects are often going to fail and there will
always be some decisions that are easy to second-guess, correctly or
not.  In any case, if the goal was a particular method to get a ROI,
it may have been that they wouldn't have been able to do that at all
with the GPL, either.

> Usually, however, most people wanting to write proprietary software
> cannot be bothered to do the work to replicate an existing GPL-
> licensed solution (or even to significantly improve permissively
> licensed solutions).

Usually, most people wanting to write software can't be bothered to do
the work.  That's nothing new.  Yet occasionally people do some work,
and some projects make progress.

> They instead appeal to people to release already-
> mature permissively licensed software, typically waiting for someone
> with enough money or manpower to do most of the work for them.

Well, personally, I'm still waiting for someone to finish the Hurd,
but I've always been led to believe that laziness is a virtue in a
programmer.

> Again,
> this is precisely why PySide appeals to a certain audience.

Certainly, the audience for a library is going to be people who both
find it interesting and find that it meets their licensing
requirements.  Nothing new about that.

Regards,
Pat


From paul at boddie.org.uk  Fri May 14 14:38:07 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 11:38:07 -0700 (PDT)
Subject: Picking a license
References: 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com>
Message-ID: 

On 14 Mai, 19:15, Patrick Maupin  wrote:
> On May 14, 11:48?am, Paul Boddie  wrote:
> > Section 3 of GPLv2 (and section 6(d) of GPLv3 reads similarly): "If
> > distribution of executable or object code is made by offering access
> > to copy from a designated place, then offering equivalent access to
> > copy the source code from the same place counts as distribution of the
> > source code, even though third parties are not compelled to copy the
> > source along with the object code."
>
> > And here's that FAQ entry which clarifies the intent:
>
> >http://www.gnu.org/licenses/gpl-faq.html#DistributeWithSourceOnInternet

[...]

> http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary

We're all aware of the obligation to provide source code. You've spent
the last few days complaining about it.

> > Like I said, if you really have a problem with Ubuntu shipping CDs and
> > exposing others to copyright infringement litigation.
>
> So, deliberately or not, you're trying to change the discussion
> again. ?I *never* discussed Ubuntu shipping a physical CD, and never
> intimated that that was a problem. ?My discussion was *always* about
> an individual *downloading* an ISO and *burning* a CD himself, then
> *distributing* the CD to someone else.

I am not changing the discussion at all. You are describing a
situation where someone gets the binaries but not the sources, but
according to the licence they should get both of those things
(ignoring written offers and the like), and this does apply to Ubuntu
since precisely this act of distribution (to use the older term) is
performed by them. That you then pass on the binaries without the
sources is an equivalent situation, ignoring for the moment that you
do not yourself have the sources either.

So, what are you supposed to do when the recipient "calls" you on the
lack of sources? (And, yes, clearly the FSF anticipates that not
everyone will request the sources because it is written in that very
excerpt I provide above.) If the recipient is strict about exact
compliance, you will have to provide the sources on CD to them. And
this makes sense: if they can only make use of the binaries if
provided on CD (and not, say, on an FTP site because they don't have
an Internet connection, for example), then they will need to receive
the sources in the same manner. Of course, the recipient may only
demand certain sources, not wishing to avail themself of the sources
for all copyleft-licensed packages in the binary distribution.

Now we return to the matter of getting the Ubuntu sources. If you
ordered a CD from Ubuntu via their ShipIt service, it is at this point
that you can demand a CD of corresponding sources. If they cannot
provide one, then obviously it poses a problem for your compliance
(and theirs, and you should see once again why Ubuntu's activities do
matter), but naturally Ubuntu provide parallel binary and source
repositories for all their packages. So, even if they were found not
to be in compliance according to the strictest interpretation of the
licence, it is technically possible for you to acquire the
corresponding sources and make them available to the person who was
given the CD. If you downloaded an ISO file, Ubuntu could (and do)
obviously provide source packages from the same location: their Web
site and various mirrors.

Really, if at this point you think I'm playing games with you, then
you really need to stop taking score and formulate the exact problem
you have with the distribution of Ubuntu-style media, because I'm
starting to think that the only real problem here is the one you have
with people using copyleft-style licences for their works. Since we've
had to hear about that over several days, I don't think that
articulating that particular problem once again really brings anything
more to the discussion.

Paul


From python.list at tim.thechases.com  Fri May 14 14:46:55 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Fri, 14 May 2010 13:46:55 -0500
Subject: joining two column
In-Reply-To: 
References: <20100514172237.23776.qmail@f4mail-235-238.rediffmail.com>
	
Message-ID: <4BED9A9F.5040708@tim.thechases.com>

On 05/14/2010 12:55 PM, James Mills wrote:
>> file1:
>> a1 a2
>> a3 a4
>> a5 a6
>> a7 a8
>>
>> file2:
>> b1 b2
>> b3 b4
>> b5 b6
>> b7 b8
>>
>> and I want to join them so the output should look like this:
>>
>> a1 a2 b1 b2
>> a3 a4 b3 b4
>> a5 a6 b5 b6
>> a7 a8 b7 b8
>
> This is completely untested, but this "should" (tm) work:
>
> from itertools import chain
>
> input1 = open("input1.txt", "r").readlines()
> input2 = open("input2.txt", "r").readlines()
> open("output.txt", "w").write("".join(chain(input1, input2)))

I think you meant izip() instead of chain() ... the OP wanted to 
be able to join the two lines together, so I suspect it would 
look something like

   # OPTIONAL_DELIMITER = " "
   f1 = file("input1.txt")
   f2 = file("input2.txt")
   out = open("output.txt", 'w')
   for left, right in itertools.izip(f1, f2):
     out.write(left.rstrip('\r\n'))
     # out.write(OPTIONAL_DELIMITER)
     out.write(right)
   out.close()

This only works if the two files are the same length, or (if 
they're of differing lengths) you want the shorter version.  The 
itertools lib also includes an izip_longest() function with 
optional fill, as of Python2.6 which you could use instead if you 
need all the lines

-tkc






From nobody at nowhere.com  Fri May 14 15:08:52 2010
From: nobody at nowhere.com (Nobody)
Date: Fri, 14 May 2010 20:08:52 +0100
Subject: Is Python a functional programming language?
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
	<7xvdau8pzl.fsf@ruckus.brouhaha.com>
	
	<7xr5lhaotk.fsf@ruckus.brouhaha.com>
Message-ID: 

On Tue, 11 May 2010 18:31:03 -0700, Paul Rubin wrote:

>>> is called an "equation" rather than an "assignment".  It declares "x is
>>> equal to 3", rather than directing x to be set to 3.  If someplace else
>>> in the program you say "x = 4", that is an error, normally caught by
>>> the compiler, since x cannot be equal to both 3 and 4.
>>
>> In both ML and Haskell, bindings are explicitly scoped, i.e.
>> 	let x = 3 in ...	(Haskell)
> 
> I'm not talking about nested bindings.  I'm talking about two different
> bindings of the same symbol in the same scope:
> 
>     $ cat meow.hs
>     x = 3
>     x = 4
>     $ ghc meow.hs
> 
>     meow.hs:2:0:
>         Multiple declarations of `Main.x'
>         Declared at: meow.hs:1:0
>                      meow.hs:2:0

It may be worth noting the interactive behaviour:

	$ ghci
	GHCi, version 6.8.2: http://www.haskell.org/ghc/  :? for help
	Loading package base ... linking ... done.
	Prelude> let x = 7
	Prelude> let f y = x + y
	Prelude> f 3
	10
	Prelude> let x = 5
	Prelude> f 3
	10

The main point is that variables aren't mutable state.

An important secondary point is that, unlike Python, free (global)
variables in a function body are substituted when the function is defined,
not when it's called.



From pmaupin at gmail.com  Fri May 14 15:14:18 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 12:14:18 -0700 (PDT)
Subject: Picking a license
References: 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com> 
	
Message-ID: <41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com>

On May 14, 1:38?pm, Paul Boddie  wrote:
> On 14 Mai, 19:15, Patrick Maupin  wrote:
>
> > On May 14, 11:48?am, Paul Boddie  wrote:
> > > Section 3 of GPLv2 (and section 6(d) of GPLv3 reads similarly): "If
> > > distribution of executable or object code is made by offering access
> > > to copy from a designated place, then offering equivalent access to
> > > copy the source code from the same place counts as distribution of the
> > > source code, even though third parties are not compelled to copy the
> > > source along with the object code."
>
> > > And here's that FAQ entry which clarifies the intent:
>
> > >http://www.gnu.org/licenses/gpl-faq.html#DistributeWithSourceOnInternet
>
> [...]
>
> >http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary
>
> We're all aware of the obligation to provide source code. You've spent
> the last few days complaining about it.
>
> > > Like I said, if you really have a problem with Ubuntu shipping CDs and
> > > exposing others to copyright infringement litigation.
>
> > So, deliberately or not, you're trying to change the discussion
> > again. ?I *never* discussed Ubuntu shipping a physical CD, and never
> > intimated that that was a problem. ?My discussion was *always* about
> > an individual *downloading* an ISO and *burning* a CD himself, then
> > *distributing* the CD to someone else.
>
> I am not changing the discussion at all. You are describing a
> situation where someone gets the binaries but not the sources, but
> according to the licence they should get both of those things
> (ignoring written offers and the like), and this does apply to Ubuntu
> since precisely this act of distribution (to use the older term) is
> performed by them. That you then pass on the binaries without the
> sources is an equivalent situation, ignoring for the moment that you
> do not yourself have the sources either.

If Joe downloads and burns a CD for his friend, he may not have the
sources and may not have any intention of getting them, and probably
didn't provide a "written offer."  What you're "ignoring for the
moment" is my whole point, that unlike Ubuntu, Joe is now in violation
of the GPL license, because he provided neither a written offer nor
source on CD, nor his own download site.

> So, what are you supposed to do when the recipient "calls" you on the
> lack of sources?

There is possibly no "calling".  Since no source and no written offer
was delivered, Joe's friend may not know about the issue.  Even Joe
himself just saw it was "free software" and didn't read the fine
print, so he may not have a clue how to get the source.


>(And, yes, clearly the FSF anticipates that not
> everyone will request the sources because it is written in that very
> excerpt I provide above.)

Which Joe doesn't know about and didn't adhere to in any case.

> If the recipient is strict about exact
> compliance, you will have to provide the sources on CD to them.

That could be a year later, and Joe, who doesn't really even know
anything about source, is really going to have a hard time figuring
out exactly which sources went into the CD he downloaded that long
ago.

> And
> this makes sense: if they can only make use of the binaries if
> provided on CD (and not, say, on an FTP site because they don't have
> an Internet connection, for example), then they will need to receive
> the sources in the same manner.

To an extent it makes sense.  That's why I explained that I thought it
would be nice of Ubuntu to put a warning to Joe on their site
explaining the consequences of helping his friend out.  Of course,
since the warning would only serve to decrease object downloads, and
since Joe's friend doesn't really want the source anyway, there is no
real point.  That doesn't alter the fact that Joe is immediately in
violation of the GPL once he delivers the CD to his friend without the
written offer.

> Of course, the recipient may only
> demand certain sources, not wishing to avail themself of the sources
> for all copyleft-licensed packages in the binary distribution.

[ Stuff about ShipIt snipped because I was never discussing that.]

> Really, if at this point you think I'm playing games with you.

I don't know what to think about that.  Even after I've explicitly
said multiple times I'm not discussing when Ubuntu ships a CD, you
still felt compelled to include a big paragraph about ShipIt.  Is it
to confuse?  Or because have OCD?  I don't really know.

> then
> you really need to stop taking score and formulate the exact problem
> you have with the distribution of Ubuntu-style media,

I explained it fully multiple times.

> because I'm
> starting to think that the only real problem here is the one you have
> with people using copyleft-style licences for their works.

Well, as I have tried to explain, there are tradeoffs with any
license, including the GPL.  With the GPL, you can easily adhere to
the letter of the license by shipping source with object.  But
sometimes the source is so huge, people take shortcuts to get around
that.  The license allows this, via a requirement to provide source
later, that could actually fall on people who really don't understand
that that is required of them (perhaps not very often in practice, but
certainly in theory).

> Since we've
> had to hear about that over several days, I don't think that
> articulating that particular problem once again really brings anything
> more to the discussion.

Probably not, but you've still never addressed how easy it is for a
complete neophyte to go to, e.g. the Ubuntu site, be told do a
download, try it out, get excited, burn CDs for his friends, and then
be in violation of the GPL.  As I have said, I don't view this as a
*practical* issue, but it is an example of how those in the GPL
community turn a blind eye to innocent infringement, just like
Microsoft.

After all, the Ubuntu download page says "When the CD is ready, simply
put it in your CD drive, restart your computer and follow the
instructions that will appear on your screen. Don't forget that you
can create more copies and pass the CD to as many people as you like."
without mentioning *anything* about source code.

Regards,
Pat


From clp2 at rebertia.com  Fri May 14 15:15:32 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Fri, 14 May 2010 12:15:32 -0700
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
	<7xvdau8pzl.fsf@ruckus.brouhaha.com>
	
	<7xr5lhaotk.fsf@ruckus.brouhaha.com>
	
Message-ID: 

On Fri, May 14, 2010 at 12:08 PM, Nobody  wrote:
> On Tue, 11 May 2010 18:31:03 -0700, Paul Rubin wrote:
>>>> is called an "equation" rather than an "assignment". ?It declares "x is
>>>> equal to 3", rather than directing x to be set to 3. ?If someplace else
>>>> in the program you say "x = 4", that is an error, normally caught by
>>>> the compiler, since x cannot be equal to both 3 and 4.
>>>
>>> In both ML and Haskell, bindings are explicitly scoped, i.e.
>>> ? ? ?let x = 3 in ... ? ? ? ?(Haskell)
>>
>> I'm not talking about nested bindings. ?I'm talking about two different
>> bindings of the same symbol in the same scope:
>>
>> ? ? $ cat meow.hs
>> ? ? x = 3
>> ? ? x = 4
>> ? ? $ ghc meow.hs
>>
>> ? ? meow.hs:2:0:
>> ? ? ? ? Multiple declarations of `Main.x'
>> ? ? ? ? Declared at: meow.hs:1:0
>> ? ? ? ? ? ? ? ? ? ? ?meow.hs:2:0
>
> It may be worth noting the interactive behaviour:
>
> ? ? ? ?$ ghci
> ? ? ? ?GHCi, version 6.8.2: http://www.haskell.org/ghc/ ?:? for help
> ? ? ? ?Loading package base ... linking ... done.
> ? ? ? ?Prelude> let x = 7
> ? ? ? ?Prelude> let f y = x + y
> ? ? ? ?Prelude> f 3
> ? ? ? ?10
> ? ? ? ?Prelude> let x = 5
> ? ? ? ?Prelude> f 3
> ? ? ? ?10

Ahem (emphasis mine):
"""
==This syntax is *ghci-specific*==
The syntax for 'let' that ghci accepts is not the same as we would use
at the ?top level? of a normal Haskell program.
"""
-- http://book.realworldhaskell.org/read/getting-started.html

Cheers,
Chris
--
http://blog.rebertia.com


From nobody at nowhere.com  Fri May 14 15:16:36 2010
From: nobody at nowhere.com (Nobody)
Date: Fri, 14 May 2010 20:16:36 +0100
Subject: Is Python a functional programming language?
References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com>
	
	
	
	
Message-ID: 

On Thu, 13 May 2010 12:29:08 +1200, Lawrence D'Oliveiro wrote:

>> Some people would prefer to have a manageable set of rules rather than
>> having to remember the results of all of the possible combinations of
>> interactions between language features.
> 
> What are you accusing Python of, exactly?

I'm not accusing it of anything, exactly. I'm just pointing out that there
are entirely pragmatic reasons for disliking "multi-paradigm" languages.



From e_d_k at yahoo.com  Fri May 14 15:18:43 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 12:18:43 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <391086.53182.qm@web58702.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Paul Boddie  wrote:


<<< lots of stuff snipped >>>

> > > Like I said, if you really have a problem with
> Ubuntu shipping CDs and
> > > exposing others to copyright infringement
> litigation.


<<< A lot more stuff snipped >>>

Everyone is assuming a certain degree of computer savvy.

I have not installed Ubuntu, but I understand that they strive for ease of 
use, so I assume that if ant now, at some time in the near future, my 
farther, who knows very little about computers, could install it if I gave 
him a CD with it on it (He would never be able to burn it himself).

Supposes download the ISO image and burn a CD and give it to my father. 
(As I understand it I am now in violation of the GPL, but I may not be). 
My father installs it. He likes it, he gives it to a friend. 

Now suppose, just for the sake of argument, that Ubuntu forgets to renew 
their domain name and it gets taken over by a porn site (It happens to Web 
mechanic, it could happen to anyone). If my father's friend's teenage son 
wants the source code, he can not get it from his father, who does not 
even know what source code is. He does not know that I exist, because his 
father forgot where he got the disk. He can not get the source from the 
porn site. 

Clearly someone has violated the GPL, but I'm not sure who, I think it was me, but I may be wrong. If not me who? My father for giving the disk I gave him to a friend? My father's friend for not keeping track of who gave him the disk? Ubuntu, for not including the source in the ISO image I downloaded? or for allowing a porn site to take over their domain name?

It is questions like this that make me steer clear of the GPL. If I give 
my father a CD of Microsoft software, I know I'm breaking the law. If I 
give my father a CD of BSD software licensed software I'm on firm legal 
ground. If I give my father a CD of GPLed software, I'm on shaky ground 
unless I include all the source, which he has no use for, on a second 
disk. And if he give his friend the binary disk, but not the source disk 
(which is of no value to him or his friend), then he is in violation of 
the law, and he cannot even understand why.

The GPL is fine when all parties concern understand what source code is 
and what to do with it. But when you add people like my father to the loop 
if gets very ugly very fast.

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com



      


From nobody at nowhere.com  Fri May 14 15:23:51 2010
From: nobody at nowhere.com (Nobody)
Date: Fri, 14 May 2010 20:23:51 +0100
Subject: write a 20GB file
References: 
	<4BED2E45.6060301@ieee.org>
	
	
Message-ID: 

On Fri, 14 May 2010 10:50:49 -0400, J wrote:

> someone smarter than me can correct me, but file.write() will write when
> it's buffer is filled, or close() or flush() are called.

And, in all probability, seek() will either flush it immediately or cause
the next write() to flush it before writing anything.




From paul at boddie.org.uk  Fri May 14 15:26:34 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 12:26:34 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
	 
	
Message-ID: 

On 14 Mai, 20:36, Patrick Maupin  wrote:
>
> That statement was made in the context of why Carl doesn't use GPL-
> licensed *libraries*. ?He and I have both explained the difference
> between libraries and programs multiple times, not that you care.

Saying that GPL-licensed applications are acceptable is a minor
concession to the use of copyleft licensing if one advocates
permissive licensing for all things which are not perceived to be
finished products: things that one isn't looking to re-use somehow.
Saying that one likes Octave and that it uses the GPL, too, is really
damning it with faint praise if one were then to say that its parts
should be permissively licensed so that one can incorporate its
functionality into something else. No, I don't care if you have a
problem with GPL-licensed libraries because it is, as we have
established repeatedly, your problem not mine.

[...]

> > The production of a
> > different "proprietary flavour" of MatLab wouldn't be beneficial to
> > them at all - it might even be detrimental to their project - and
> > might only be marginally beneficial, at best, to existing MatLab
> > customers.
>
> I personally can't see any realistic chance of detriment. ?How could a
> proprietary clone hope to compete against free software on one side
> and real matlab on the other side? ?That's a no-win position, so I
> wouldn't expect to see any proprietary clones.

Well, only permissively licensed software would encourage such clones.
At that point, there are incentives for people to develop
functionality for proprietary deployment instead of for the upstream
project.

[PySide and proprietary software]

> No, PySide is about non-GPL software, and is released under a license
> that even RMS recognizes as "free", and it is certainly not of
> marginal utility.

No, PySide is about permitting the development of proprietary
applications by providing a solution to the all-important "ISVs" which
lets them develop and deploy proprietary software. Do you really think
a platform vendor whose "ISVs" routinely ship proprietary software on
their platform and on other platforms, and who will demand the ability
to continue to do so, now expects all these "ISVs" to provide their
applications under the modified BSD licence? Sure, other developers
can use the software - even people releasing GPL-licensed software -
but that is highly unlikely to be the primary business motivation. If
you think the mobile telephony vendors are a bunch of fluffy bunny
rabbits playing with each other in sugary meadows of niceness, I don't
want to be present when someone directly and finally disabuses you of
this belief. It's all about people selling stuff to "consumers" over
and over again, preferably with the "consumers" rarely if ever being
able to opt-out and do things their own way.

> > (And PyQt is not "marginally useful" - it is a widely-used and widely
> > well-regarded library.)
>
> Well, we agree on that. ?But I don't know why you're trying to claim I
> said PyQt was only marginally useful.

Because you followed on from writing about PyQt by introducing the
topic of "marginally useful" libraries, thus giving the impression
that you regarded PyQt as "marginally useful".

Paul


From aaron.hildebrandt at gmail.com  Fri May 14 15:27:02 2010
From: aaron.hildebrandt at gmail.com (Aaron Scott)
Date: Fri, 14 May 2010 12:27:02 -0700 (PDT)
Subject: Including a remote file -- permission denied?
Message-ID: 

I have a Python script running on the default OSX webserver, stored
in /Library/WebServer/CGI-Executables. That script spits out a list of
files on a network drive, a la "os.listdir('/Volumes/code/
directory/')". If I just execute this from the terminal, it works as
expected, but when I try to access it through a browser
(computer.local/cgi-bin/test.py), I get a permissions error (: [Errno 13] Permission denied: '/Volumes/code/
directory').

Is there any way to give the script permission to access the network
when accessed via CGI?


From prologic at shortcircuit.net.au  Fri May 14 15:28:46 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sat, 15 May 2010 05:28:46 +1000
Subject: joining two column
In-Reply-To: <4BED9A9F.5040708@tim.thechases.com>
References: <20100514172237.23776.qmail@f4mail-235-238.rediffmail.com> 
	 
	<4BED9A9F.5040708@tim.thechases.com>
Message-ID: 

On Sat, May 15, 2010 at 4:46 AM, Tim Chase
 wrote:
> I think you meant izip() instead of chain() ... the OP wanted to be able to
> join the two lines together, so I suspect it would look something like

You're quite right! My mistake :)

--James


From e_d_k at yahoo.com  Fri May 14 16:05:59 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 13:05:59 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <994222.78014.qm@web58703.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Paul Boddie  wrote:


<<<>>
> 
> No, PySide is about permitting the development of
> proprietary
> applications by providing a solution to the all-important
> "ISVs" which
> lets them develop and deploy proprietary software. Do you
> really think
> a platform vendor whose "ISVs" routinely ship proprietary
> software on
> their platform and on other platforms, and who will demand
> the ability
> to continue to do so, now expects all these "ISVs" to
> provide their
> applications under the modified BSD licence? Sure, other
> developers
> can use the software - even people releasing GPL-licensed
> software -
> but that is highly unlikely to be the primary business
> motivation. If
> you think the mobile telephony vendors are a bunch of
> fluffy bunny
> rabbits playing with each other in sugary meadows of
> niceness, I don't
> want to be present when someone directly and finally
> disabuses you of
> this belief. It's all about people selling stuff to
> "consumers" over
> and over again, preferably with the "consumers" rarely if
> ever being
> able to opt-out and do things their own way.

Do you feel the same way about Python? It is released under a 
nonrestrictive license, since you are on this list I assume you use it.

If you want, I think you could use the existing Python code base to create 
a GPLed version of Python, I think the license is permissive enough to 
allow that. If you did, do you think more people would use the GPLed 
version? 

Personally, I would use the version with the more permissive license, unless the GPLed version offered a significant advantage of some kind.

     -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From pmaupin at gmail.com  Fri May 14 16:12:41 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 13:12:41 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
	 
	 
	
Message-ID: 

On May 14, 2:26?pm, Paul Boddie  wrote:
> On 14 Mai, 20:36, Patrick Maupin  wrote:
>
>
>
> > That statement was made in the context of why Carl doesn't use GPL-
> > licensed *libraries*. ?He and I have both explained the difference
> > between libraries and programs multiple times, not that you care.
>
> Saying that GPL-licensed applications are acceptable is a minor
> concession to the use of copyleft licensing if one advocates
> permissive licensing for all things which are not perceived to be
> finished products: things that one isn't looking to re-use somehow.

I am only "advocating" to the extent of explaining why I license stuff
permissively, and why, whenever I incorporate other stuff, it has to
be licensed permissively as well.  How you license your stuff is your
business.

> Saying that one likes Octave and that it uses the GPL

I don't recall saying I liked Octave.  I have no opinion.  I have
never used it.  Just threw it out there as an example of how people
rewrite proprietary software to counter your indignation that somebody
would rewrite PyQt.

> damning it with faint praise if one were then to say that its parts
> should be permissively licensed so that one can incorporate its
> functionality into something else.

I'm not operating a chop shop.  Never even had cause to look at the
source.  I really don't care about it.

> No, I don't care if you have a
> problem with GPL-licensed libraries because it is, as we have
> established repeatedly, your problem not mine.

Sure, the problems that I see with the GPL lead me to choose non-GPL
solutions for libraries.  And I never asked you to care.  I had a
brief moment of hope that you could see that my concerns were valid,
if personal, but apparently you can only concede that if you attribute
some sort of selfish ill-will to me.

> > I personally can't see any realistic chance of detriment. ?How could a
> > proprietary clone hope to compete against free software on one side
> > and real matlab on the other side? ?That's a no-win position, so I
> > wouldn't expect to see any proprietary clones.
>
> Well, only permissively licensed software would encourage such clones.

See, there you go with choice of language again.  Remember, we're both
biased with different viewpoints.  You say "encourage"; I say
"allow."  I further argued that it's immaterial that it's allowed,
nobody sane would do it.

> At that point, there are incentives for people to develop
> functionality for proprietary deployment instead of for the upstream
> project.

What incentives?  The incentives that the original matlab team will
keep outcompeting you from the top, or the incentives that the open
source octave team will keep outcompeting you from the bottom?

> [PySide and proprietary software]
>
> > No, PySide is about non-GPL software, and is released under a license
> > that even RMS recognizes as "free", and it is certainly not of
> > marginal utility.
>
> No, PySide is about permitting the development of proprietary
> applications by providing a solution to the all-important "ISVs" which
> lets them develop and deploy proprietary software.

That's an interesting viewpoint.  Originally, both Qt and PyQt were
available dual-licensed under the GPL or proprietary licenses.  For
anybody serious about proprietary development, the proprietary
licensed versions were actually quite reasonably priced.  Really the
major advantage I see in PySide licensing is for somebody like Ed or
Carl or me, who simply wants to be able to deliver programs with no
strings attached.  That was not possible under the GPL-licensed
version (because of the strings attaching to the customer that Ed has
talked about) or the commercial version (because then Ed couldn't even
give his customer the source to PyQt).  PySide is LGPL, which Ed still
might not touch, but at least any "linking" required between that and
code that uses it is really just an import statement, so then again,
he might be OK with that.

Of course, the fact that Qt and PySide are now both free of cost for
non-GPL customers certainly helps Nokia in their push to get people to
take them.

> Do you really think
> a platform vendor whose "ISVs" routinely ship proprietary software on
> their platform and on other platforms, and who will demand the ability
> to continue to do so, now expects all these "ISVs" to provide their
> applications under the modified BSD licence?

Not at all.  But they have now *enabled* ISVs to do that.  Before,
with QT and PyQt, it was GPL or proprietary.

> Sure, other developers
> can use the software - even people releasing GPL-licensed software -
> but that is highly unlikely to be the primary business motivation.

I think the motivation was to remove all impediments to using it on
the platform, and I see nothing wrong with that motivation.  They
already spent a lot on Qt, and they really want to leverage that.

> If
> you think the mobile telephony vendors are a bunch of fluffy bunny
> rabbits playing with each other in sugary meadows of niceness, I don't
> want to be present when someone directly and finally disabuses you of
> this belief.

I don't recall writing anything that would give you that impression,
but whatever.

> It's all about people selling stuff to "consumers" over
> and over again, preferably with the "consumers" rarely if ever being
> able to opt-out and do things their own way.

Nokia is locked in a tight battle with multiple players.  Developments
like Nokia using Qt and PyQt (which give small developers a chance to
play easily on that platform) and Google handing out Android to
whoever wants it are going to make the selling over-and-over
increasingly harder to do.  (Not that they won't do if if they can.  I
just think they are increasingly going to have a hard time playing
that game.)

>
> > > (And PyQt is not "marginally useful" - it is a widely-used and widely
> > > well-regarded library.)
>
> > Well, we agree on that. ?But I don't know why you're trying to claim I
> > said PyQt was only marginally useful.
>
> Because you followed on from writing about PyQt by introducing the
> topic of "marginally useful" libraries, thus giving the impression
> that you regarded PyQt as "marginally useful".

Well, it's pretty obvious to anyone paying attention that PySide was
written for the sole purpose of creating something with similar
functionality as PyQt, but under a permissive license, so when I wrote
"nobody's going to waste time rewriting a marginally useful GPLed
library just to put a permissive license on it, either." I *obviously*
was explaining that projects which *aren't* marginal, such as PyQt and
MatLab, are the *only* kinds of projects that would be rewritten for a
simple license change.  You really should slow down and read a bit
more carefully.

Regards,
Pat


From stefan_ml at behnel.de  Fri May 14 16:17:52 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 14 May 2010 22:17:52 +0200
Subject: parsing XML
In-Reply-To: 
References: 
	
Message-ID: 

Martin v. Loewis, 14.05.2010 17:15:
> kaklis at gmail.com wrote:
>> Hi to all, let's say we have the following Xml
>> 
>>    
>>      17.1
>>      6.4
>>    
>>    
>>      15.5
>>      7.8
>>    
>> 
>>
>> How can i get the players name, age and height?
>> DOM or SAX and how
>
> Homework?

I would hope that every school teacher who teaches Python is able to skip 
through c.l.py and the python-tutor list before accepting a homework result.

Stefan



From no.email at nospam.invalid  Fri May 14 16:19:59 2010
From: no.email at nospam.invalid (Paul Rubin)
Date: Fri, 14 May 2010 13:19:59 -0700
Subject: Iterating over dict and removing some elements
References: 
	<1e19af7b-226a-4cae-a407-e6285344a28c@6g2000prg.googlegroups.com>
Message-ID: <7xsk5u1bio.fsf@ruckus.brouhaha.com>

Bryan  writes:
> In Python 3.X, and in Python 2.X starting with 2.4, you can drop the
> square brackets and avoid creating an extra temporary list:
>
> d = dict((k, d[k]) for k in d.keys() if not foo(k, d))

In 2.x, I think you want d.iterkeys() rather than d.keys() to avoid
making a list with all the keys.  Or you can just say

  d = dict((k, d[k]) for k in d if not foo(k, d))


From awilliam at whitemice.org  Fri May 14 16:44:48 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Fri, 14 May 2010 16:44:48 -0400
Subject: parsing XML
In-Reply-To: 
References: 
	  
Message-ID: <1273869888.12194.11.camel@linux-yu4c.site>

On Fri, 2010-05-14 at 22:17 +0200, Stefan Behnel wrote:
> >> 
> >>    
> >>      17.1
> >>      6.4
> >>    
> >>    
> >>      15.5
> >>      7.8
> >>    
> >>  

from lxml import etree
handle = open('file', 'rb')
doc = etree.parse(handle)
handle.close()
players = [ ]
for player in doc.xpath('/team/player'):
  players.append({ 'name': player.xpath('./@name')[0],
                   'age': player.xpath('./@age')[0],
                   'height': player.xpath('./@height')[0] } )
print players
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba



From martin at v.loewis.de  Fri May 14 17:23:06 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Fri, 14 May 2010 23:23:06 +0200
Subject: Loading C extension from memory
In-Reply-To: 
References: 
Message-ID: <4BEDBF3A.3030906@v.loewis.de>


> I wonder if there is a way to load C extension from in-memory object,
> not from the file on the disk?
> 
> I'm asking bc I would like to download C extensions over network and
> load them into Python interpreter (without storing the C extension in
> file on the disk).
> 
> I googled for this but there appear only methods of loading compiled
> Python (bytecode) modules.

First, it depends on your operating system. None of the standard
operating systems supports loading shared libraries from memory; they
all need a file name.

Of course, your operating system may provide support for RAM disks. So
if you store the extension onto a RAM disk, you can load it from there -
from memory.

It may be possible to extend the Python interpreter to not rely on
shared libraries anymore for extension modules. Such an interpreter
likely wouldn't use standard shared libraries anymore, so you might
then have to recompile the extensions to make them loadable from memory.
However, it also might be possible to reimplement the shared library
loader of the operating system, in which case you could then run
regular extension modules directly from memory.

Regards,
Martin


From martin at v.loewis.de  Fri May 14 17:46:25 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Fri, 14 May 2010 23:46:25 +0200
Subject: parsing XML
In-Reply-To: 
References: 	
	
Message-ID: <4BEDC4B1.3080104@v.loewis.de>

>>> Hi to all, let's say we have the following Xml
>>> 
>>>    
>>>      17.1
>>>      6.4
>>>    
>>>    
>>>      15.5
>>>      7.8
>>>    
>>> 
>>>
>>> How can i get the players name, age and height?
>>> DOM or SAX and how
>>
>> Homework?
> 
> I would hope that every school teacher who teaches Python is able to
> skip through c.l.py and the python-tutor list before accepting a
> homework result.

If he uses your proposed solution, it probably wouldn't pass, anyway,
because it's neither DOM nor SAX. If he's really interested in a
solution to the original problem, then ElementTree is fine, of course.

As for teachers scanning relevant forums: that's often impractical.
For example, for an XML lecture, choice of programming language may be
to the student. You then have to search web forums, mailing lists, and
newsgroups for Java, Python, C#, Ruby, Scala, plus StackOverflow.

Solutions copied from the net often show a level of cuteness beyond
what you'd expect from a student (like your solution: who'd be using
reflection to access three attributes?). So you rather take these clues
as the starting point for an investigation (and then hope that Google
comes up with the specific source code).

Of course, it may also be that getting help is explicitly allowed.

Regards,
Martin


From dreadpiratejeff at gmail.com  Fri May 14 18:38:55 2010
From: dreadpiratejeff at gmail.com (J)
Date: Fri, 14 May 2010 18:38:55 -0400
Subject: write a 20GB file
In-Reply-To: 
References: 
	<4BED2E45.6060301@ieee.org>
	 
	
	
Message-ID: 

On Fri, May 14, 2010 at 15:23, Nobody  wrote:
> On Fri, 14 May 2010 10:50:49 -0400, J wrote:
>
>> someone smarter than me can correct me, but file.write() will write when
>> it's buffer is filled, or close() or flush() are called.
>
> And, in all probability, seek() will either flush it immediately or cause
> the next write() to flush it before writing anything.

Ahhh... I didn't know that... I thought seek() just moved the pointer
through the file a little further....

Cool.


From clp2 at rebertia.com  Fri May 14 19:02:11 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Fri, 14 May 2010 16:02:11 -0700
Subject: Alternate string object type for PyStringObject(available Python 
	2.x) in python 3.x?
In-Reply-To: <12897d06413.515885629628951451.7220101516557890617@gmail.com>
References: <12897d06413.515885629628951451.7220101516557890617@gmail.com>
Message-ID: 

On Fri, May 14, 2010 at 10:15 AM, MathanK  wrote:
> What is the replacement in python 3.x for PyStringObject which is available
> in python 2.x?

PyUnicodeObject or PyBytesObject depending on your use case.

Cheers,
Chris
--
http://blog.rebertia.com


From paul at boddie.org.uk  Fri May 14 19:42:34 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 16:42:34 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
	 
	 
	 
	
Message-ID: 

On 14 Mai, 22:12, Patrick Maupin  wrote:
>
> I *obviously*
> was explaining that projects which *aren't* marginal, such as PyQt and
> MatLab, are the *only* kinds of projects that would be rewritten for a
> simple license change.

"As far as your comments about PyQt proving out the concept, well duh!
Just as there are a lot of proprietary programs that are relatively
useless and *won't* have any GPLed versions written, nobody's going to
waste time rewriting a marginally useful GPLed library just to put a
permissive license on it, either."

This being the sudden introduction of this notion of a "marginally
useful" library. And for a long time no-one did rewrite PyQt for the
purpose of having a permissively licensed library, so it's quite
natural to assume that you're saying that until PySide came along, the
reasons for which I have already noted, PyQt was a "marginally useful"
library, not worth rewriting.

> You really should slow down and read a bit more carefully.

You might want to tone down the condescension.

Paul


From paul at boddie.org.uk  Fri May 14 19:52:28 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 16:52:28 -0700 (PDT)
Subject: Picking a license
References: 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com> 
	 
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com>
Message-ID: <47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com>

On 14 Mai, 21:14, Patrick Maupin  wrote:
>
> If Joe downloads and burns a CD for his friend, he may not have the
> sources and may not have any intention of getting them, and probably
> didn't provide a "written offer." ?What you're "ignoring for the
> moment" is my whole point, that unlike Ubuntu, Joe is now in violation
> of the GPL license, because he provided neither a written offer nor
> source on CD, nor his own download site.

Now, wait a moment! Your point is that just by giving the binary CD to
someone, you are now in violation of the licence. What I tried to
explain is that this situation is anticipated - that the FSF
acknowledges that the recipient won't have received the sources at the
same time in all situations - and that the same distributor is
responsible for providing the sources. As long as they don't deny the
recipient access to the sources, by the same means, they are not
violating the licence.

You have a point about recipients not being immediately and obviously
informed of the things they are entitled to, but that is a matter for
the distributing parties to remedy: that is arguably what happens
when, upon loud squealing about matters of "ideology", distributors
decide to de-emphasise the Free Software aspect of their
distributions. Nevertheless, it is my understanding that anyone
attempting to use or install such distributions do get to see a
summary of the licences; only people who pass on the software without
inspecting it (which would involve actually inserting the CD and
booting from it) will be unaware of its contents, and they could only
be held responsible as reasonably as one's Internet service provider
if that party were asked to provide source packages for "that Linux
distro I downloaded last year".

You also have a point about whether people are able to provide sources
at a later date, which might be troublesome if someone gave someone
else a CD with an old version of Ubuntu on it and then were asked to
provide the source packages. Naturally, the FSF have attempted to
address these points in version 3 of the GPL. I would be interested to
hear the opinion of the FSF and distributors on this matter, but I
think it's absurd to accuse the FSF as operating as you allege
Microsoft do, especially as the distributors are the ones who
encourage the sharing of the installation media.

Really, if you think distributions should do a better job at educating
their users and helping them uphold any obligations that may apply to
them, you should talk to them about it. But when I attempt to work
though the issues in a thorough manner in order to thrash out what it
is you really object to - and in practice, the only objections you can
seriously have lie in those two points I mention above (not this
"instant violation" situation, discussed in more detail elsewhere [*])
- and all you can do is suggest that other people are trying to
mislead you, I struggle to feel inclined to indulge you further.

And suggesting that people have behavioural disorders ("Or because
have OCD?") might be a source of amusement to you, or may be a neat
debating trick in certain circles you admire, but rest assured that I
am neither amused nor impressed, nor are others likely to be.

Paul

[*] http://www.mail-archive.com/debian-legal at lists.debian.org/msg31466.html


From paul at boddie.org.uk  Fri May 14 20:12:04 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 17:12:04 -0700 (PDT)
Subject: Picking a license
References: 
Message-ID: <93d67bd9-6721-4759-a3de-412b95b29a93@c11g2000vbe.googlegroups.com>

On 14 Mai, 21:18, Ed Keith  wrote:
>
> The GPL is fine when all parties concern understand what source code is
> and what to do with it. But when you add people like my father to the loop
> if gets very ugly very fast.

Sure, and when I'm not otherwise being accused of pushing one
apparently rather unpopular man's agenda, I am interested in knowing
what the best practices should be and how they can be followed more
widely.

Although Bill Gates once apparently claimed that no-one needs the
source code for their word processor or office suite, there are still
benefits in people like your father having access to the sources, even
if this obviously means that he isn't going to recompile it himself:
he can get others to fix things, particularly if his favourite version
is no longer widely supported; if you were from a part of the planet
where you were comfortable with a widely-spoken "global" language but
your father could only converse in a less widely-spoken "minority"
language not generally supported by such software, someone (perhaps
you) could undertake the task of translating that software.

Whether or not one is comfortable with copyleft-style licences, there
clearly is a benefit in providing access to software governed by those
licences. Being able to do so responsibly is obviously a prerequisite
to feeling comfortable about it.

Paul


From ron.eggler at gmail.com  Fri May 14 20:14:02 2010
From: ron.eggler at gmail.com (cerr)
Date: Fri, 14 May 2010 17:14:02 -0700 (PDT)
Subject: huh??? weird problem
Message-ID: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>

Hi There,

I got following code:
start=time.time()
print 'warnTimeout '+str(WarnTimeout)
print 'critTimeout '+str(CritTimeout)
print 'start',str(start)
while wait:
    passed =  time.time()-start
    print 'passed ',str(passed)
    if passed >= WarnTimeout:
      print ' Warning!'
 ...
...
...
which basically means that the loops should go until the warning time
has been reached and then i want it to print 'warning!' and execute
some warning code. But weirdly enough i get following screen output:
warnTimeout 3
critTimeout 5
start 1273882010.43
passed  7.60555267334e-05
passed  0.998471975327
passed  1.99847102165
passed  2.9984691143
passed  3.99847006798
passed  4.998472929
...
...
any one a clue why after 3 seconds it doesn't go into the the if an
print 'Warning!'? That's odd... :o Crazy, what am i not seeing? :(


From tjreedy at udel.edu  Fri May 14 20:24:56 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Fri, 14 May 2010 20:24:56 -0400
Subject: Picking a license
In-Reply-To: <47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com>
References: 	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com>
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com>
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com>
	
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com>
	<47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com>
Message-ID: 

The following lines from

http://www.softwarefreedom.org/resources/2008/compliance-guide.html

seem to cover the case of someone who casually redistributes, for free, 
Ubuntu or whatever. Such can refer people back to the Ubuntu site. They 
should, perhaps, be familiar with the url, but I would expect that the 
binary Ubuntu distribution CDs have the appropriate offer and details on 
that disk. Someone who casually distributes, for free, a subset should 
also be covered. Under 4.1.2  Option (b): The Offer,

"The option to provide an offer for source rather than direct source 
distribution is a special benefit to companies equipped to handle a 
fulfillment process. GPLv2 ? 3(c) and GPLv3 ? 6(c) avoid burdening 
noncommercial, occasional redistributors with fulfillment request 
obligations by allowing them to pass along the offer for source as they 
received it.

Note that commercial redistributors cannot avail themselves of the 
option (c) exception, and so while your offer for source must be good to 
anyone who receives the offer (under v2) or the object code (under v3), 
it cannot extinguish the obligations of anyone who commercially 
redistributes your product. The license terms apply to anyone who 
distributes GPL?d software, "

Terry Jan Reedy




From awilliam at whitemice.org  Fri May 14 20:27:18 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Fri, 14 May 2010 20:27:18 -0400
Subject: Puzzled by code pages
Message-ID: <1273883238.3929.8.camel@linux-yu4c.site>

I'm trying to process OpenStep plist files in Python.  I have a parser
which works, but only for strict ASCII.  However plist files may contain
accented characters - equivalent to ISO-8859-2 (I believe).  For example
I read in the line:

>>> handle = open('file.txt', 'rb')
>>> data = handle.read()
>>> handle.close()
>>> data
'    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
NSFileName;\n'

What is the correct way to re-encode this data into UTF-8 so I can use
unicode strings, and then write the output back to ISO8859-?

I can read the file using codecs as ISO8859-2, but it still doesn't seem
correct.

>>> handle = codecs.open('file.txt', 'rb', encoding='iso8859-2')
>>> data = handle.read()
>>> handle.close()
>>> data
u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
NSFileName;\n'




From pavlovevidence at gmail.com  Fri May 14 20:28:57 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 14 May 2010 17:28:57 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com
Message-ID: <5cbfb2c3-6d39-4878-88a3-44c206a9ecdd@k25g2000prh.googlegroups.com>

On May 14, 8:20?am, Paul Boddie  wrote:
> On 14 Mai, 09:08, Carl Banks  wrote:
>
> > On May 13, 10:59?pm, Steven D'Aprano  wrote:
> > > On Thu, 13 May 2010 17:18:47 -0700, Carl Banks wrote:
> > > > 2. Reimplment the functionality seperately (*cough* PySide)
>
> > > Yes. So what? In what possible way is this an argument against the GPL?
>
> [...]
>
> > It's not. ?It's an argument that the GPL doesn't do much good.
>
> Right. So nobody got the benefit from Qt under the GPL or PyQt under
> the GPL?

[Snip a bunch of crap I don't care about]

The community as a whole benefited from PyQt because it was free, not
because it was GPL.  The community as whole suffered because it was
GPL instead of a more permissive license.

Now that we have PySide the community as a whole will benefit much,
much more than it could with only a GPLed PyQt.


Carl Banks


From clp2 at rebertia.com  Fri May 14 20:29:55 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Fri, 14 May 2010 17:29:55 -0700
Subject: huh??? weird problem
In-Reply-To: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
References: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
Message-ID: 

On Fri, May 14, 2010 at 5:14 PM, cerr  wrote:
> Hi There,
>
> I got following code:
> start=time.time()
> print 'warnTimeout '+str(WarnTimeout)
> print 'critTimeout '+str(CritTimeout)
> print 'start',str(start)
> while wait:
> ? ?passed = ?time.time()-start
> ? ?print 'passed ',str(passed)
> ? ?if passed >= WarnTimeout:
> ? ? ?print ' Warning!'
> ?...
> ...
> ...
> which basically means that the loops should go until the warning time
> has been reached and then i want it to print 'warning!' and execute
> some warning code. But weirdly enough i get following screen output:
> warnTimeout 3
> critTimeout 5
> start 1273882010.43
> passed ?7.60555267334e-05
> passed ?0.998471975327
> passed ?1.99847102165
> passed ?2.9984691143
> passed ?3.99847006798
> passed ?4.998472929
> ...
> ...
> any one a clue why after 3 seconds it doesn't go into the the if an
> print 'Warning!'? That's odd... :o Crazy, what am i not seeing? :(

print type(WarnTimeout)

I suspect it won't be numerical. Where is WarnTimeout assigned its value?
Note that in Python 2.x, comparisons between e.g. numbers and strings
were allowed, but the ordering was arbitrary.
Python 3.x fixes this and instead raises TypeError for such
nonsensical comparisons.

Cheers,
Chris
--
http://blog.rebertia.com


From pmaupin at gmail.com  Fri May 14 20:33:56 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 17:33:56 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
	 
	 
	 
	 
	
Message-ID: <59713fd4-15a0-4b94-8fb0-c457ea27bf71@y12g2000vbg.googlegroups.com>

On May 14, 6:42?pm, Paul Boddie  wrote:

> > You really should slow down and read a bit more carefully.
>
> You might want to tone down the condescension.

I didn't start out condescending, and I agree I could have worded this
particular statement a bit more clearly, so I apologize for that, but
I can point to at least 5 or 6 occurrences of you misreading me when I
stated things very clearly.  It's really starting to get old.

Regards,
Pat


From mensanator at aol.com  Fri May 14 20:35:05 2010
From: mensanator at aol.com (Mensanator)
Date: Fri, 14 May 2010 17:35:05 -0700 (PDT)
Subject: huh??? weird problem
References: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
Message-ID: <289f06b9-aba0-4285-a29c-2ec676f63a2e@x1g2000vbo.googlegroups.com>

On May 14, 7:14?pm, cerr  wrote:
> Hi There,
>
> I got following code:
> start=time.time()
> print 'warnTimeout '+str(WarnTimeout)
> print 'critTimeout '+str(CritTimeout)
> print 'start',str(start)
> while wait:
> ? ? passed = ?time.time()-start
> ? ? print 'passed ',str(passed)
> ? ? if passed >= WarnTimeout:
> ? ? ? print ' Warning!'
> ?...
> ...
> ...
> which basically means that the loops should go until the warning time
> has been reached and then i want it to print 'warning!' and execute
> some warning code. But weirdly enough i get following screen output:
> warnTimeout 3
> critTimeout 5
> start 1273882010.43
> passed ?7.60555267334e-05
> passed ?0.998471975327
> passed ?1.99847102165
> passed ?2.9984691143
> passed ?3.99847006798
> passed ?4.998472929
> ...
> ...
> any one a clue why after 3 seconds it doesn't go into the the if an
> print 'Warning!'?

Works for me:

warnTimeout 3
critTimeout 5
start 1273883378.39
passed  1.0
passed  2.0
passed  3.0
 Warning!
passed  4.0
 Warning!
passed  5.0
 Warning!
passed  6.0
 Warning!
passed  7.0
 Warning!


> That's odd... :o Crazy, what am i not seeing? :(

Did you copy it right?



From awilliam at whitemice.org  Fri May 14 20:38:43 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Fri, 14 May 2010 20:38:43 -0400
Subject: Puzzled by code pages
In-Reply-To: <1273883238.3929.8.camel@linux-yu4c.site>
References: <1273883238.3929.8.camel@linux-yu4c.site>
Message-ID: <1273883923.3929.10.camel@linux-yu4c.site>

On Fri, 2010-05-14 at 20:27 -0400, Adam Tauno Williams wrote:
> I'm trying to process OpenStep plist files in Python.  I have a parser
> which works, but only for strict ASCII.  However plist files may contain
> accented characters - equivalent to ISO-8859-2 (I believe).  For example
> I read in the line:
> 
> >>> handle = open('file.txt', 'rb')
> >>> data = handle.read()
> >>> handle.close()
> >>> data
> '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
> NSFileName;\n'
> What is the correct way to re-encode this data into UTF-8 so I can use
> unicode strings, and then write the output back to ISO8859-?

Typical, 30 seconds after giving up and posting a message... I find the
problem.

Buried in the parser is a str(...) call.  Replacing that with
unicode(...) and now the OpenSTEP plist parser is working with Italian
plists.



From pmaupin at gmail.com  Fri May 14 20:51:35 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 17:51:35 -0700 (PDT)
Subject: Picking a license
References: 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com> 
	 
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com> 
	<47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com> 
	
Message-ID: <6fb754b4-20a9-4ab5-ae93-63571e6a119a@z17g2000vbd.googlegroups.com>

On May 14, 7:24?pm, Terry Reedy  wrote:
>
> "The option to provide an offer for source rather than direct source
> distribution is a special benefit to companies equipped to handle a
> fulfillment process. GPLv2 ? 3(c) and GPLv3 ? 6(c) avoid burdening
> noncommercial, occasional redistributors with fulfillment request
> obligations by allowing them to pass along the offer for source as they
> received it.

Paul Boddie already pointed out that document.  As I explained, that
document was written for the Ciscos of the world.  The FAQ, which was
written for you and me states very clearly "The general rule is, if
you distribute binaries, you must distribute the complete
corresponding source code too. The exception for the case where you
received a written offer for source code is quite limited." in answer
to the question "I downloaded just the binary from the net. If I
distribute copies, do I have to get the source and distribute that
too?"

As I have pointed out on at least 3 posts by now, this FAQ
interpretation derives directly from the actual license terms and
appears to reflect the terms correctly. If you actually *read* GPLv3 ?
6(c), it *only* applies if you received the object code in accordance
with GPLv3 ? 6(b).  But if you download an ISO from Ubuntu, that
happens under GPLv3 ? 6(d), *not* GPLv3 ? 6(b).

However, the distribution to your friend when you give him the CD that
you burned for him is under 6(b), so not only do you not have an
upstream to rely on, you are actually in violation of the license once
you give him the CD without your own written offer!  (At one level,
this makes sense -- if the 3 year window for source is to have any
teeth, then you can't give the poor guy a CD 2 years after you
downloaded it and expect Ubuntu to make good on the source 5 years
after you downloaded it.)

Now maybe there is some *other* way (besides the obvious ways I've
mentioned such as fair use and the fact that nobody's going to sue
because of the PR fallout from bothering some grandma for sharing a CD
that was advertised as "free") that this is not an issue, but nobody
on this thread has yet shown any credible evidence that the act of
just handing somebody a freshly burned Ubuntu CD with no written offer
is not a violation of the license.

As I have made clear, I do not view this as a direct practical
problem.  But I do view it as a huge problem that the license is so
complex that in a couple of days of conversing about it, several
people have asserted that there is no way my reading of the license is
correct, yet nobody has shown solid evidence that would back up an
alternate reading, and I also view it as the tip of the iceberg as far
as the issue of license compliance goes.

Regards,
Pat


From davea at ieee.org  Fri May 14 21:41:54 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 14 May 2010 21:41:54 -0400
Subject: huh??? weird problem
In-Reply-To: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
References: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
Message-ID: <4BEDFBE2.4090207@ieee.org>

cerr wrote:
> Hi There,
>
> I got following code:
> start=time.time()
> print 'warnTimeout '+str(WarnTimeout)
> print 'critTimeout '+str(CritTimeout)
> print 'start',str(start)
> while wait:
>     passed =  time.time()-start
>     print 'passed ',str(passed)
>     if passed >= WarnTimeout:
>       print ' Warning!'
>  ...
> ...
> ...
> which basically means that the loops should go until the warning time
> has been reached and then i want it to print 'warning!' and execute
> some warning code. But weirdly enough i get following screen output:
> warnTimeout 3
> critTimeout 5
> start 1273882010.43
> passed  7.60555267334e-05
> passed  0.998471975327
> passed  1.99847102165
> passed  2.9984691143
> passed  3.99847006798
> passed  4.998472929
> ...
> ...
> any one a clue why after 3 seconds it doesn't go into the the if an
> print 'Warning!'? That's odd... :o Crazy, what am i not seeing? :(
>
>   
we're not seeing all the relevant code.  While I can ignore the missing 
import, I don't see any creation of the variables WarnTimeout and 
CritTimeout.  Simplest explanation that fits your sample run is that 
they are not of type float.

DaveA



From pmaupin at gmail.com  Fri May 14 21:46:21 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 18:46:21 -0700 (PDT)
Subject: Picking a license
References: 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com> 
	 
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com> 
	<47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com>
Message-ID: 

On May 14, 6:52?pm, Paul Boddie  wrote:
> On 14 Mai, 21:14, Patrick Maupin  wrote:
>
> > If Joe downloads and burns a CD for his friend, he may not have the
> > sources and may not have any intention of getting them, and probably
> > didn't provide a "written offer." ?What you're "ignoring for the
> > moment" is my whole point, that unlike Ubuntu, Joe is now in violation
> > of the GPL license, because he provided neither a written offer nor
> > source on CD, nor his own download site.
>
> Now, wait a moment! Your point is that just by giving the binary CD to
> someone, you are now in violation of the licence.

Correct -- download an ISO, burn onto CD, hand CD to friend w/o
written offer = license violation.

> What I tried to
> explain is that this situation is anticipated - that the FSF
> acknowledges that the recipient won't have received the sources at the
> same time in all situations - and that the same distributor is
> responsible for providing the sources.

Right.  That distributor would be Joe.

> As long as they don't deny the
> recipient access to the sources, by the same means, they are not
> violating the licence.

But Joe didn't give a written offer, and he doesn't even know how to
download the source, and you still haven't showed why that's not a
problem for him.

> You have a point about recipients not being immediately and obviously
> informed of the things they are entitled to, but that is a matter for
> the distributing parties to remedy:

Well, Joe's the distributor to his friend.  He got the stuff from
Ubuntu, who will give him source and even have a legal page about it,
but Joe didn't bother reading all that stuff.

> that is arguably what happens
> when, upon loud squealing about matters of "ideology", distributors
> decide to de-emphasise the Free Software aspect of their
> distributions.

Yesterday, you were telling me I should inform Ubuntu that they didn't
have enough license information prominently available in the right
places.  Are you now claiming that that's simply because people like
me told Ubuntu that they were emphasizing the license information too
much?

In any case, Ubuntu prominently describes "The Ubuntu Promise" with a
link to more information from their front page.  Of course, the
download button is prominent as well.

> Nevertheless, it is my understanding that anyone
> attempting to use or install such distributions do get to see a
> summary of the licences;

Yes, and we all know that everybody has been trained to fully read and
understand every single license the click on when installing software.

> only people who pass on the software without
> inspecting it (which would involve actually inserting the CD and
> booting from it) will be unaware of its contents,

Well, to make what I said in my previous comment more clear, I believe
that Joe would have actually installed the software himself without
bothering to read the license.  This may be foolish of Joe, but he is
in excellent company -- in one recent unscientific yet (IMO) well-
constructed study, only 12% of users bothered to read the license at
all:

http://www.huffingtonpost.com/2010/04/17/gamestation-grabs-souls-o_n_541549.html

> and they could only
> be held responsible as reasonably as one's Internet service provider
> if that party were asked to provide source packages for "that Linux
> distro I downloaded last year".

You still haven't yet provided any credible evidence for this version
of the chain of responsibility.  But in any case, I suspect Joe would
have actually installed the software without bothering to read any
license information.

> You also have a point about whether people are able to provide sources
> at a later date, which might be troublesome if someone gave someone
> else a CD with an old version of Ubuntu on it and then were asked to
> provide the source packages.

Bingo!  My hypothetical Joe would be in serious hot water at this
point.

> Naturally, the FSF have attempted to
> address these points in version 3 of the GPL.

And I submit that they addressed the problem by making it really clear
that yes, it is Joe's responsibility, in section 6.

> I would be interested to
> hear the opinion of the FSF and distributors on this matter, but I
> think it's absurd to accuse the FSF as operating as you allege
> Microsoft do, especially as the distributors are the ones who
> encourage the sharing of the installation media.

Well, it's really the entire ecosystem. I have to believe that
everybody at the FSF knows how this works, and even though RMS is a
shrinking violet, I suspect that if he seriously cared about this, he
would work up the courage to address it publicly, much as it pains him
to share his opinions.

> Really, if you think distributions should do a better job at educating
> their users and helping them uphold any obligations that may apply to
> them, you should talk to them about it.

I seriously don't think they, or the FSF, are interested in this, and
I don't think they will harass Joe in any case.  My whole point is
that I believe they *could*, and if several people on this thread
can't either (1) understand and believe that; or (2) provide credible
reasons why I am mistaken, after umpteen posts on several days on this
issue, then the entire issue of actual compliance to the license in a
practical fashion (where I consider downloading and burning a DVD of
source to go along with every CD of object impractical) is really a
lot trickier than some people are making it out to be. This bolsters
my personal opinion that one rational response to this complexity is
to avoid the license when possible.

> But when I attempt to work
> though the issues in a thorough manner in order to thrash out what it
> is you really object to - and in practice, the only objections you can
> seriously have lie in those two points I mention above (not this
> "instant violation" situation, discussed in more detail elsewhere [*])

It's my opinion that the decision to let Joe off the hook is
strategic.  Nobody's going to bother Joe, but they *could*.  But
there's no percentage in it.  I don't actually object to the strategic
decision.  It's a marketing decision designed to increase the reach of
the software.  Yet instead of embracing the decision yourself, you not
only deny it, but accuse me of bad faith in even suggesting that it
could be a deliberate strategy.

> - and all you can do is suggest that other people are trying to
> mislead you, I struggle to feel inclined to indulge you further.

I'm suggesting that some other people should consider that perhaps my
viewpoint, while admittedly biased (as are all viewpoints) is not all
that inconsistent with reality.

> And suggesting that people have behavioural disorders ("Or because
> have OCD?") might be a source of amusement to you, or may be a neat
> debating trick in certain circles you admire, but rest assured that I
> am neither amused nor impressed, nor are others likely to be.

That was in an honest response to a question you asked "Really, if at
this point you think I'm playing games with you." where I explained
that I don't know what to think, because often, when you claimed to be
addressing my point, you would bring up other red herrings and spend
more time on those, and often assign positions to me that I never
took.  When I suggested maybe you don't read carefully enough, you
claimed that's not the root of the problem, so I really don't know
what it is, other than that maybe you need to calm down and reread
what I posted and what you are planning to respond with before pushing
"send".  It's really very annoying to be expected to defend positions
I didn't take and statements I didn't make and to have most of your
comments have a subtle dig at my motivations.  I honestly don't know
what makes you do that, but it certainly does not bring out the best
in me.  I will try to do better if you do too.  (BTW, IMO this was one
of your better posts in terms of tone and being on-point, etc., and I
appreciate that.)

Regards,
Pat


From ldo at geek-central.gen.new_zealand  Fri May 14 21:55:08 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 13:55:08 +1200
Subject: parsing XML
References: 
	
Message-ID: 

In message , Stefan 
Behnel wrote:

> Here's an overly complicated solution, but I thought that an object
> oriented design would help here.

How many times are you going to write the ?"name", "age", "height"? 
sequence? The next assignment question I would ask is: how easy would it be 
to add a fourth attribute?

>    attributes = ['name', 'age', 'height']

I would put this at the top.

Then this

>    class Player(object):
>       def __init__(self, name, age, height):
>           self.name, self.age, self.height = name, age, height

can become

    class Player(object):
       def __init__(self, **rest):
           for attr in attributes :
               setattr(self, attr, rest[attr])
           #end for
       #end __init__
    #end Player

and

>    for player in players:
>        print player.name, player.age, player.height

can become

    for player in players:
        print " ".join(getattr(player, attr) for attr in attributes)
    #end for



From ldo at geek-central.gen.new_zealand  Fri May 14 21:56:08 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 13:56:08 +1200
Subject: Broken pipe
References: 
	
	 <4bec2a9a$1@dnews.tpgi.com.au>
Message-ID: 

In message <4bec2a9a$1 at dnews.tpgi.com.au>, Lie Ryan wrote:

> On 05/13/10 22:41, Lawrence D'Oliveiro wrote:
>> In message , Chris
>> Rebert wrote:
>> 
>>> Also, please don't use semicolons in your code. It's bad style.
>> 
>> Wonder why they?re allowed, then.
> 
> they're there for line continuation, e.g.:
> 
> a = 40; foo(a)
> 
> but in many cases, putting two statements in a single line reduces
> readability so use the semicolons extremely conservatively. But the
> worst is the abuse of semicolons for end-of-line markers.

So why are they allowed, then?


From ldo at geek-central.gen.new_zealand  Fri May 14 21:57:58 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 13:57:58 +1200
Subject: Picking a license
References: 
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
	<84a26d03-03b3-47d9-a1f9-107470b87c75@k2g2000yqe.googlegroups.com>
Message-ID: 

In message <84a26d03-03b3-47d9-
a1f9-107470b87c75 at k2g2000yqe.googlegroups.com>, Patrick Maupin wrote:

> I also firmly believe, as I have stated before, that the GPL is a much
> more commercial license.  If you want to make money off something,
> then, no doubt, GPL keeps your competitors from being able to take
> what you wrote and redistribute it as closed source.  But, frankly I
> view that as more of a business issue than a moral issue.

Nevertheless, it?s probably a big factor in why the GPL has become the 
single most popular open-source licence.


From ldo at geek-central.gen.new_zealand  Fri May 14 21:58:48 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 13:58:48 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> Yes, under the GPL every one has one set of freedoms, under the MIT or
> Boost license every one has more freedoms. Under other licenses they have
> fewer freedoms.

But what about the ?freedom? to take away other people?s freedom? Is that 
really ?freedom??


From ldo at geek-central.gen.new_zealand  Fri May 14 22:02:07 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:02:07 +1200
Subject: Picking a license
References: 
	
	<2ff3643b-6ef1-4471-8438-dcba0dc93c24@a21g2000yqn.googlegroups.com>
	
	
Message-ID: 

In message
, Patrick 
Maupin wrote:

> On May 14, 6:12 am, Lawrence D'Oliveiro 
> wrote:
>
>> In message
>> <2ff3643b-6ef1-4471-8438-dcba0dc93... at a21g2000yqn.googlegroups.com>,
>> Patrick Maupin wrote:
>
>>> On May 13, 10:04 pm, Lawrence D'Oliveiro
>>>  wrote:
>>
>> >> In message , Ed
>> >> Keith wrote:
>>
>>>>> The claim is being made that [the GPL] restricts freedom.
>>>>
>>>> What about the ?freedom? to restrict other people?s freedom? Should
>>>> that be restricted or not?
>>
>>> It's interesting that some people don't like the comparison of the
>>> Free Software movement to a religion, yet the main argument of the
>>> movement, and the deliberate co-opting of words like "Free" and "Free
>>> Software" ...
>>
>> Haven?t you ?co-opted? those words yourself?
> 
> Only in response.

So it?s bad when others do it, but not when you do it?


From ldo at geek-central.gen.new_zealand  Fri May 14 22:04:05 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:04:05 +1200
Subject: Picking a license
References: 
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
	<9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com>
	<548024fc-dd56-48b9-907d-3aa6a722b43c@l31g2000yqm.googlegroups.com>
Message-ID: 

In message <548024fc-
dd56-48b9-907d-3aa6a722b43c at l31g2000yqm.googlegroups.com>, Patrick Maupin 
wrote:

> The confusion that some are showing in this thread about whether source
> must be distributed certainly helps to show that as well.

What ?confusion?? The GPL requires that source must always be offered in 
some form. Simple as that.


From ldo at geek-central.gen.new_zealand  Fri May 14 22:05:59 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:05:59 +1200
Subject: Picking a license
References: 
	
	<2b17ee77-0e49-4a97-994c-7582f86c0ba9@r34g2000yqj.googlegroups.com>
	
	<5e719bcd-5405-4c34-870b-13e64ef1f818@k29g2000yqh.googlegroups.com>
Message-ID: 

In message 
<5e719bcd-5405-4c34-870b-13e64ef1f818 at k29g2000yqh.googlegroups.com>, Patrick 
Maupin wrote:

> On May 14, 6:13 am, Lawrence D'Oliveiro  central.gen.new_zealand> wrote:
>
>> In message
>> <2b17ee77-0e49-4a97-994c-7582f86c0... at r34g2000yqj.googlegroups.com>,
>> Patrick Maupin wrote:
>>>
>>> On May 13, 10:06 pm, Lawrence D'Oliveiro
>>>  wrote:
>>
>>>> Under the GPL, everybody has exactly the same freedoms.
>>
>>> That's absolutely not true.  For a start, the original author can dual-
>>> license.
>>
>> That?s nothing to do with the GPL.
> 
> If you mean "that's out of the control of the GPL" I agree.  But the
> whole point of the discussion has been about how people can't take GPL
> licensed code proprietary, making enhancements, etc. and I'm just
> pointing out that this doesn't apply to the original author.  Someone
> can decide they aren't making enough money under the GPL and stop
> distributing that way, and make all their enhancements proprietary, if
> they are the original author.

That?s nothing to do with the GPL.


From ldo at geek-central.gen.new_zealand  Fri May 14 22:07:24 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:07:24 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> That is one good reason for choosing to use the GPL, instead of a less
> restrictive license. You can license it, for a fee, to someone who wants
> to use it in some way that is not allowed under the GPL.

Replace ?GPL? with ?? and your statement is no less (or more) 
true.

Funny how a lot of the arguments people keep trying to put forward about the 
GPL really have nothing to do with the GPL.


From pmaupin at gmail.com  Fri May 14 22:15:15 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:15:15 -0700 (PDT)
Subject: Picking a license
References:  
	
	<2ff3643b-6ef1-4471-8438-dcba0dc93c24@a21g2000yqn.googlegroups.com>
	
	
	
Message-ID: 

On May 14, 9:02?pm, Lawrence D'Oliveiro  wrote:
> In message
> , Patrick
>
>
>
> Maupin wrote:
> > On May 14, 6:12 am, Lawrence D'Oliveiro 
> > wrote:
>
> >> In message
> >> <2ff3643b-6ef1-4471-8438-dcba0dc93... at a21g2000yqn.googlegroups.com>,
> >> Patrick Maupin wrote:
>
> >>> On May 13, 10:04 pm, Lawrence D'Oliveiro
> >>>  wrote:
>
> >> >> In message , Ed
> >> >> Keith wrote:
>
> >>>>> The claim is being made that [the GPL] restricts freedom.
>
> >>>> What about the ?freedom? to restrict other people?s freedom? Should
> >>>> that be restricted or not?
>
> >>> It's interesting that some people don't like the comparison of the
> >>> Free Software movement to a religion, yet the main argument of the
> >>> movement, and the deliberate co-opting of words like "Free" and "Free
> >>> Software" ...
>
> >> Haven?t you ?co-opted? those words yourself?
>
> > Only in response.
>
> So it?s bad when others do it, but not when you do it?

I don't claim to have the vision that gave me the last word on
freedom, complete with the overarching power to enumerate all the
necessary freedoms on heaven and earth.  But even if I accept
Stallman's definitions of "freedom" it is apparently heretical of me
to point out that under other licenses, the original recipient of a
piece of software (for example, anybody who downloads any of my
software direct from google code) enjoys all four of the freedoms
relative to that particular piece of software, and has the additional
freedom of not having to worry too much about compliance.

BTW, RMS apparently stole "4 freedoms" from FDR.  But don't tell
anybody.

Regards,
Pat


From pmaupin at gmail.com  Fri May 14 22:17:20 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:17:20 -0700 (PDT)
Subject: Picking a license
References:  
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
	<9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com> 
	<548024fc-dd56-48b9-907d-3aa6a722b43c@l31g2000yqm.googlegroups.com> 
	
Message-ID: <6767a5ae-2aab-4532-8e18-8c445920624e@d3g2000vbr.googlegroups.com>

On May 14, 9:04?pm, Lawrence D'Oliveiro  wrote:
> In message <548024fc-
> dd56-48b9-907d-3aa6a722b... at l31g2000yqm.googlegroups.com>, Patrick Maupin
> wrote:
>
> > The confusion that some are showing in this thread about whether source
> > must be distributed certainly helps to show that as well.
>
> What ?confusion?? The GPL requires that source must always be offered in
> some form. Simple as that.

Right, but when I explained that that requirement also applies to Joe,
who downloaded an ISO from Ubuntu and burned a CD and gave it away, no
less than 3 people jumped in to "correct" me.

Regards,
Pat


From ldo at geek-central.gen.new_zealand  Fri May 14 22:17:23 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:17:23 +1200
Subject: Picking a license
References: 
Message-ID: 

In message
, Patrick 
Maupin wrote:

> After all, lots of software ideas proved their worth in proprietary
> systems, and then were later cloned by FOSS developers.

And vice versa. Everybody, whether working in closed or open environments, 
builds on the work of everybody else. Rsync pioneered the idea of doing 
transfers of incremental changes to a large file across a network without 
being able to have the two versions of the file on the same machine to do a 
direct side-by-side comparison; Microsoft copied the idea in more recent 
versions of its server software. Andrew Tridgell could easily have patented 
his idea, but he chose not to.

Apple pioneered the idea of using 3D graphics hardware to do window 
compositing on the desktop; the Compiz folks went on to figure out how to do 
this efficiently. Microsoft also copied the idea, but forgot the 
?efficiently? part.

Free Software also benefits from networking effects that are not available 
to proprietary developers. The resources available to proprietary developers 
are proportional to the size of the company they work for; typically they do 
not share software with competitors. Whereas the Free Software community is 
like one huge company in this regard, available to freely pass ideas and 
code back and forth. This has led to the creation of ideas that proprietary 
companies simply cannot match.


From ldo at geek-central.gen.new_zealand  Fri May 14 22:20:01 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:20:01 +1200
Subject: Picking a license
References: 
Message-ID: 

In message
, Paul 
Boddie wrote:

> Although people can argue that usage of the GPL prevents people from
> potentially contributing because they would not be able to sell
> proprietary versions of the software ...

It doesn?t prevent them from selling proprietary versions of their own 
contributions, any more than any other licence does.

The fact that their contribution may not be much use without the rest of 
that GPL?d code is entirely another matter. It was their choice to build on 
the work of others; they could have reinvented it from scratch themselves.


From ldo at geek-central.gen.new_zealand  Fri May 14 22:21:57 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:21:57 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> I just refuse to use [the GPL] in any code for a client, because I
> do not want to require someone who does not know source code from Morse
> code code to figure out what they need to do to avoid violating the
> license.

Why don?t you just put the source code on the same disc you send them, and 
tell them to pass copies of the entire disc to anyone they want?


From luxuryownerKelly at hotmail.com  Fri May 14 22:24:03 2010
From: luxuryownerKelly at hotmail.com (Kelly)
Date: Sat, 15 May 2010 10:24:03 +0800
Subject: Puzzled by code pages
References: 
Message-ID: 

Buy high quality TAG Heuer Tiger Woods Golf Watches at low price, you can 
not believe, but it is true.

There are two models on 
http://www.luxuryowner.net/Replica-TAG-Heuer-Tiger-Woods-Golf-Watches.html

White: Tag Heuer Tiger Woods Golf White Mens Watch WAE1112.FT6008:
http://www.luxuryowner.net/Replica-Tag-Heuer-Tiger-Woods-Golf-White-Mens-Watch-WAE1112.FT6008.html

Black: Tag Heuer Tiger Woods Golf Black Mens Watch WAE1111.FT6004
http://www.luxuryowner.net/Replica-Tag-Heuer-Tiger-Woods-Golf-Black-Mens-Watch-WAE1111.FT6004.html

More replica watches you can refer: http://www.luxuryowner.net/

"Adam Tauno Williams"  ????????????:mailman.193.1273883243.32709.python-list at python.org...
> I'm trying to process OpenStep plist files in Python.  I have a parser
> which works, but only for strict ASCII.  However plist files may contain
> accented characters - equivalent to ISO-8859-2 (I believe).  For example
> I read in the line:
>
>>>> handle = open('file.txt', 'rb')
>>>> data = handle.read()
>>>> handle.close()
>>>> data
> '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
> NSFileName;\n'
>
> What is the correct way to re-encode this data into UTF-8 so I can use
> unicode strings, and then write the output back to ISO8859-?
>
> I can read the file using codecs as ISO8859-2, but it still doesn't seem
> correct.
>
>>>> handle = codecs.open('file.txt', 'rb', encoding='iso8859-2')
>>>> data = handle.read()
>>>> handle.close()
>>>> data
> u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
> NSFileName;\n'
>
> 




From ldo at geek-central.gen.new_zealand  Fri May 14 22:30:55 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:30:55 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Paul Boddie wrote:

> If you think the mobile telephony vendors are a bunch of fluffy bunny
> rabbits playing with each other in sugary meadows of niceness, I don't
> want to be present when someone directly and finally disabuses you of
> this belief.

The rise to popularity of Free Software had nothing to do with meadows full 
of mobile bunny-meat, and everything to do with the hard realities of the 
marketplace. Vendors discovered that they could make hardware running a 
Linux kernel do more things than it could with proprietary alternatives. In 
the beginning they derided the GPL as ?business-unfriendly?, until they 
grudgingly accepted that, just as it prevented them from freeloading off 
their competitors, it stopped those same competitors from freeloading off 
them. The network effects translated into real profits.

> It's all about people selling stuff to "consumers" over
> and over again, preferably with the "consumers" rarely if ever being
> able to opt-out and do things their own way.

Interesting you should mention that. That is exactly how mobile phone 
networks have been operated right up until now. And Apple?s business model 
has fitted very well into that too, as witness the success of the iPhone.

But Google?s Android could represent a shift in that model. Yes, it does 
seem to be locked down in its way, but given that most of the source code is 
available, that hardly seems watertight. The phone networks may see it as 
just another phone platform that the plebs are happy to shell out their 
hard-earned for, but I think it could ultimately lead to a loss of their 
proprietary control.


From pmaupin at gmail.com  Fri May 14 22:31:21 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:31:21 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
	<84a26d03-03b3-47d9-a1f9-107470b87c75@k2g2000yqe.googlegroups.com>
	
Message-ID: 

On May 14, 8:57?pm, Lawrence D'Oliveiro  wrote:
> In message <84a26d03-03b3-47d9-
>
> a1f9-107470b87... at k2g2000yqe.googlegroups.com>, Patrick Maupin wrote:
> > I also firmly believe, as I have stated before, that the GPL is a much
> > more commercial license. ?If you want to make money off something,
> > then, no doubt, GPL keeps your competitors from being able to take
> > what you wrote and redistribute it as closed source. ?But, frankly I
> > view that as more of a business issue than a moral issue.
>
> Nevertheless, it?s probably a big factor in why the GPL has become the
> single most popular open-source licence.

Possibly.  I think a bigger factor is that the GPL is *designed* to
win license competitions.  If you view the license as part of the DNA
of a piece of software, then whenever two packages "breed" (are
combined) the resultant package will always have the GPL if either of
the source packages did.  In attempting to draw a biological parallel,
many have equated the GPL to a virus, but this analogy fails
miserably.  The "selfish gene" analogy has much to recommend it,
however:

http://en.wikipedia.org/wiki/The_Selfish_Gene#.22Selfish.22_genes

It's an interesting exercise to extend the analogy to show how the GPL
gene mutated in a way to allow it to mate with even *more* licenses
(and always come out on top).  So now there are two incompatible
selfish gene FOSS licenses in the ecosystem.  The license genes always
propagate whenever the host software mates, but in order to have that
genetic advantage, they avoid allowing their host software to mate
whenever they couldn't be the dominant license gene of the resultant
package.  One side effect of this is that the two major GPL variants
are unable to mate with each other.

Regards,
Pat


From steve at REMOVE-THIS-cybersource.com.au  Fri May 14 22:32:24 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 02:32:24 GMT
Subject: Picking a license
References: 
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
	
	<4bece8de$0$8761$c3e8da3@news.astraweb.com>
	<79811fa0-f8bb-4ec8-acc3-a4a1727a8e78@k42g2000yqb.googlegroups.com>
Message-ID: <4bee07b7$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 08:04:53 -0700, Patrick Maupin wrote:

> On May 14, 1:08?am, Steven D'Aprano  cybersource.com.au> wrote:
>> On Thu, 13 May 2010 19:10:09 -0700, Patrick Maupin wrote:
>> > The broken window fallacy is about labor that could have been spent
>> > elsewhere if someone else had done something differently. ?The only
>> > time that comes into play in my programming life is when I have to
>> > recode something that is nominally available under the GPL, so I'm
>> > not sure this is really making the point you think it is.
>>
>> You've never had to recode something because it was nominally available
>> under a proprietary licence that you (or your client) was unwilling to
>> use? Lucky you!
> 
> Don't be silly.  That's why I started writing open source software in
> the first place.  But if I start writing stuff to put in the commons
> with strings removed, why would I bother with a license that just adds
> some strings back?

To maximise the likelihood of it staying in the commons, of course.


>> The GPL ensures that once software has entered the commons (and
>> therefore available for all), it can never be removed from the commons.
> 
> No it doesn't.  It just insures that if people actually *distribute* the
> software to others, they have to distribute the source.  In any case,
> for software to remain in the commons, it has to be available where
> people can get to it.  Somebody has to care enough to maintain a
> repository, or it has to be good enough for people to distribute.

The reality is that most software never gets very far. There are millions 
of packages and libraries and applications which have few than a dozen 
users, thousands with a few hundred, and only one Microsoft Windows. 
Since web sites shut down and people lose interest, move on or die, 
software can disappear. This is a fact of life, and if you're looking for 
any guarantees, neither the GPL nor MIT-style licence will give you one.

But consider the case of Ed Keith, who posted some Boost-licenced 
software to the commons. (See his message in this thread, about 30 
minutes before yours.) The website he posted it to has shut down and he 
has lost his original code.

Obviously no licence can guarantee that people will want to use your 
software. Unpopular software will remain unpopular no matter what licence 
you use. But it is precisely the viral nature of the GPL that means that, 
*if* your software is useful enough for people to want to distribute it, 
it will remain in the commons even if you, the original author, are hit 
by a bus, your web server crashes, and you lose the original sources.

Under a MIT-style licence, it is possible for you to put a work into the 
commons, somebody else to copy it and distribute it as a proprietary 
work, then the original to disappear. For all we know, Ed's software has 
made it into a thousand different proprietary applications. Nevertheless, 
it has been lost from the commons, at least until such time as he 
recreates it.

Under the GPL, of course work can be lost from the commons if nobody 
distributes it and the original is lost. But the viral nature is designed 
so that *if* the software propagates legally, it remains in the commons 
and not out of it. This is different from MIT-style licences, which are 
indifferent to whether the software propagates in the commons or not, and 
proprietary licences, which typically prohibit it.


[...]
>> In practice, I believe most MIT-licenced code never even makes it into
>> the commons in the first place.
> 
> Interesting assertion.

I think it is a safe one. So far in the discussion, you and Ed (and 
possibly others, I may have forgotten) have repeatedly declared that you 
use the MIT licence for work you write for clients. This implies two 
obvious business models:

(1) You write open source software, put it on the Internet, and wait for 
the donations to come flooding in.

(2) Clients pay you to write software for them, which you then use a non-
GPL open source licence so that they don't need to release the source 
code if/when they distribute it further.

Given that you're able to pay for an Internet connection, chances are 
that your model is closer to #2. This implies that most of the software 
you write is bespoke software for clients, which means they're probably 
not distributing it as open source, simply because most software is still 
proprietary.



>> I'm willing to predict that the majority of code you've written for
>> paying customers (as opposed to specifically for open source projects)
>> has disappeared into their code base, never to be seen by anyone
>> outside of the company. Am I right?
> 
> That's true, but what on earth does that have to do with the MIT
> license?


The motive behind the GPL is to maximise the amount of code in the 
commons. The motive behind the MIT is to maximise the convenience, 
regardless of whether people keep your code in the commons or not. Unless 
people understand that the *motives* behind the models are different, all 
this talk of "freedoms" is just talking at cross-purposes. To those who 
want to maximise code in the commons, allowing people to take code out of 
the commons isn't a desirable freedom at all; and to those who want to 
maximise convenience, obliging people to distribute source code isn't 
desirable either.


It's strictly irrelevant to this discussion, but I'm curious why you 
choose to licence your work to your clients rather than just working for 
hire and assigning copyright to them.



-- 
Steven


From pmaupin at gmail.com  Fri May 14 22:36:13 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:36:13 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: 

On May 14, 9:21?pm, Lawrence D'Oliveiro  wrote:
> In message , Ed Keith
> wrote:
>
> > I just refuse to use [the GPL] in any code for a client, because I
> > do not want to require someone who does not know source code from Morse
> > code code to figure out what they need to do to avoid violating the
> > license.
>
> Why don?t you just put the source code on the same disc you send them, and
> tell them to pass copies of the entire disc to anyone they want?

What you would really have to tell them is "don't pass along the
program *unless* you copy the whole disk."  That's no longer a
courtesy -- that's a mandate.  By not using the GPL, Ed avoids having
to mandate to his customer how to treat the software he has delivered
to them.

Regards,
Pat


From steve at REMOVE-THIS-cybersource.com.au  Fri May 14 22:37:46 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 02:37:46 GMT
Subject: Picking a license
References: 
Message-ID: <4bee08f9$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 06:42:31 -0700, Ed Keith wrote:

> I am not a lawyer, but as I understand the LGPL, If I give someone
> something that used any LGPLed code I must give them the ability to
> relink it with any future releases of the LGPLed code. I think that
> means that I need to give them a linker and teach them how to use it,
> and I do not want to go there.

Surely you're joking? 

Does this mean that if they lose their hands in an accident, you have to 
come sit at their computer and do their typing?

The LGPL and GPL don't grant people "the ability" to do anything, since 
that's not within our power to grant. Some people don't want to, or 
can't, program, or don't have time. It's not like the LGPL is the bite of 
a radioactive spider that can grant superpowers. It is a licence which 
grants *permissions*.

In that regard, that's absolutely no different to the MIT licence, or 
proprietary software licences, which also deal in permissions (and 
restrictions). If I go to my local computer retailer and buy a copy of 
Windows, Microsoft doesn't grant me the ability to run the software. If I 
say "I don't actually have a computer, and the electricity has been shut 
off, so you have to pay to have the power turned back on and give me a 
computer", you won't get anywhere. The licence permits you to run one 
copy of Windows on one machine. Everything else is up to you.


-- 
Steven


From jackie.space at gmail.com  Fri May 14 22:45:06 2010
From: jackie.space at gmail.com (Jackie Lee)
Date: Sat, 15 May 2010 09:45:06 +0700
Subject: write a 20GB file
In-Reply-To: <4BED6715.1000106@v.loewis.de>
References: 
	<4BED2E45.6060301@ieee.org>
	 
	<4BED6715.1000106@v.loewis.de>
Message-ID: 

Thanks to y'all. I should have be more careful reading the documentation.

Cheers

On Fri, May 14, 2010 at 10:07 PM, Martin v. Loewis  wrote:
>> The code works fine. I just don't know how f.write works. It says that
>> file.write won't write the file until file.close or file.flush.
>
> You are misinterpreting the documentation. It certainly won't keep the
> entire file in memory. Instead, it has a fixed-size buffer (something
> like 8kiB or 32kiB) in which it writes and which it flushes when that
> buffer is full.
>
> The comment about flush and close merely refers to the problem that some
> data may still be in the buffer at any point in time, unless you just
> called close or flush.
>
> HTH,
> Martin
>



-- 
Jackie


From e_d_k at yahoo.com  Fri May 14 22:47:36 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 19:47:36 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <286192.2146.qm@web58708.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 9:58 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > Yes, under the GPL every one has one set of freedoms,
> under the MIT or
> > Boost license every one has more freedoms. Under other
> licenses they have
> > fewer freedoms.
> 
> But what about the ?freedom? to take away other
> people?s freedom? Is that 
> really ?freedom??
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Yes.

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Fri May 14 22:55:39 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 19:55:39 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <509872.33107.qm@web58703.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 10:07 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > That is one good reason for choosing to use the GPL,
> instead of a less
> > restrictive license. You can license it, for a fee, to
> someone who wants
> > to use it in some way that is not allowed under the
> GPL.
> 
> Replace ?GPL? with ?? and your
> statement is no less (or more) 
> true.
> 
> Funny how a lot of the arguments people keep trying to put
> forward about the 
> GPL really have nothing to do with the GPL.
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

I can not imagine anyone being stupid enough to pay me for rights to use code I had already published under the Boost License, which grants then the rights to do anything they want with it without paying me anything.

  -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From pmaupin at gmail.com  Fri May 14 22:55:54 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:55:54 -0700 (PDT)
Subject: Picking a license
References: 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com> 
	 
	<4bece8de$0$8761$c3e8da3@news.astraweb.com>
	<79811fa0-f8bb-4ec8-acc3-a4a1727a8e78@k42g2000yqb.googlegroups.com>
	<4bee07b7$0$8761$c3e8da3@news.astraweb.com>
Message-ID: 

On May 14, 9:32?pm, Steven D'Aprano  wrote:
> > Don't be silly. ?That's why I started writing open source software in
> > the first place. ?But if I start writing stuff to put in the commons
> > with strings removed, why would I bother with a license that just adds
> > some strings back?
>
> To maximise the likelihood of it staying in the commons, of course.

Well, it's your opinion that it would do that, and you have some
reasonably good reasons for that opinion, but I don't personally buy
into all of them.

[...]

> Obviously no licence can guarantee that people will want to use your
> software. Unpopular software will remain unpopular no matter what licence
> you use. But it is precisely the viral nature of the GPL that means that,
> *if* your software is useful enough for people to want to distribute it,
> it will remain in the commons even if you, the original author, are hit
> by a bus, your web server crashes, and you lose the original sources.

Sure, there's an additional guarantee.  But I don't believe there is a
real distinction.  I believe, for example, that all the major Linux
distributions don't try to save bandwidth or disk space by
discriminating against non-GPL packages.  For example, the Ubuntu
policy clearly states that to be in "main" rather than "restricted" a
package "must include source code."

> Under the GPL, of course work can be lost from the commons if nobody
> distributes it and the original is lost. But the viral nature is designed
> so that *if* the software propagates legally, it remains in the commons
> and not out of it. This is different from MIT-style licences, which are
> indifferent to whether the software propagates in the commons or not, and
> proprietary licences, which typically prohibit it.

While that is a theoretical difference, I don't believe it is a
practical one.  I don't download all the source for my Linux distro,
but they make all the source available.

> >> In practice, I believe most MIT-licenced code never even makes it into
> >> the commons in the first place.
>
> > Interesting assertion.
>
> I think it is a safe one. So far in the discussion, you and Ed (and
> possibly others, I may have forgotten) have repeatedly declared that you
> use the MIT licence for work you write for clients.

I think there is a serious misunderstanding there.  For me, there are
usually 3 types of licenses involved:

1) proprietary license or work-for-hire agreement for the customer's
secret sauce
2) Stuff that the author has put under a permissive license before, or
gets the customer to agree is not part of the secret sauce, and the
customer agrees to allow the author to put under a permissive license
after he writes it
3) Stuff that somebody else wrote under a permissive license

For most of my career, I've been an employee with a work-for-hire
clause, so pretty much all my writing falls under (1) unless I can
make a compelling argument for (2), which is finally starting to
happen a bit more.

> This implies two
> obvious business models:
>
> (1) You write open source software, put it on the Internet, and wait for
> the donations to come flooding in.
>
> (2) Clients pay you to write software for them, which you then use a non-
> GPL open source licence so that they don't need to release the source
> code if/when they distribute it further.

The bulk of the code is probably (3) Customer dictates the license.

[Snipped a bunch of stuff predicated on a misunderstanding of the way
things work for me]

> It's strictly irrelevant to this discussion, but I'm curious why you
> choose to licence your work to your clients rather than just working for
> hire and assigning copyright to them.

In the past, work-for-hire was practically the rule (during the times
I've been an employee).  I've been trying to release open stuff from
the workplace from over a decade with little traction, but it's
finally happening a bit.  There are multiple good reasons to open-
source, including the hope for coopetition, and the building of a
resume.  Given that other people who might cooperate with me on an
open source project are often similarly situated (working for
proprietary employers who wouldn't necessarily want to worry about the
GPL), using a permissive license makes great sense.

Regards,
Pat


From pmaupin at gmail.com  Fri May 14 22:58:40 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:58:40 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: <882f0f61-0139-4c13-bb2c-94a03b86f8d4@k31g2000vbu.googlegroups.com>

On May 14, 8:58?pm, Lawrence D'Oliveiro  wrote:
> In message , Ed Keith
> wrote:
>
> > Yes, under the GPL every one has one set of freedoms, under the MIT or
> > Boost license every one has more freedoms. Under other licenses they have
> > fewer freedoms.
>
> But what about the ?freedom? to take away other people?s freedom? Is that
> really ?freedom??

Only if they love or fear you enough to not try to overthrow you.
Otherwise, you have to be always on your guard.  It's still probably a
pretty good life.


From steve at REMOVE-THIS-cybersource.com.au  Fri May 14 22:59:00 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 02:59:00 GMT
Subject: Picking a license
References: 
Message-ID: <4bee0df4$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 06:39:05 -0700, Ed Keith wrote:

> Yes, under the GPL every one has one set of freedoms, under the MIT or
> Boost license every one has more freedoms. Under other licenses they
> have fewer freedoms.

I think this talk about freedoms is dangerously incomplete, and is 
confusing the issue rather than shedding more light. Both licences grant 
the same positive freedoms (freedom to do something). MIT-style licences 
grant permission to:

* make copies of the work;
* make derivative works based on the work; and
* distribute those derivative works to others.

The GPL grants precisely the same three rights. There is no difference in 
the rights granted.

The MIT licence imposes an obligation on the licencee:

* you must include a copy of the licence and copyright notice with the 
work and/or any derivative works.


The GPL adds a further obligation:

* any derivative works must also be licenced under the GPL.


If we want to talk about "freedoms", rather than rights and obligations, 
we need to distinguish between positive freedoms (freedom to do 
something) and negative freedoms (freedoms from something) and not just 
blithely mix them up.


-- 
Steven


From pmaupin at gmail.com  Fri May 14 23:00:40 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 20:00:40 -0700 (PDT)
Subject: Picking a license
References: 
	
Message-ID: <65b24889-3f55-4802-b7ea-dac471714bd6@d3g2000vbr.googlegroups.com>

On May 14, 9:17?pm, Lawrence D'Oliveiro  wrote:
> In message
> , Patrick
>
> Maupin wrote:
> > After all, lots of software ideas proved their worth in proprietary
> > systems, and then were later cloned by FOSS developers.
>
> And vice versa. Everybody, whether working in closed or open environments,
> builds on the work of everybody else. Rsync pioneered the idea of doing
> transfers of incremental changes to a large file across a network without
> being able to have the two versions of the file on the same machine to do a
> direct side-by-side comparison; Microsoft copied the idea in more recent
> versions of its server software. Andrew Tridgell could easily have patented
> his idea, but he chose not to.
>
> Apple pioneered the idea of using 3D graphics hardware to do window
> compositing on the desktop; the Compiz folks went on to figure out how to do
> this efficiently. Microsoft also copied the idea, but forgot the
> ?efficiently? part.
>
> Free Software also benefits from networking effects that are not available
> to proprietary developers. The resources available to proprietary developers
> are proportional to the size of the company they work for; typically they do
> not share software with competitors. Whereas the Free Software community is
> like one huge company in this regard, available to freely pass ideas and
> code back and forth. This has led to the creation of ideas that proprietary
> companies simply cannot match.

Well said.

Pat


From e_d_k at yahoo.com  Fri May 14 23:08:33 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 20:08:33 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <93d67bd9-6721-4759-a3de-412b95b29a93@c11g2000vbe.googlegroups.com>
Message-ID: <226966.24642.qm@web58705.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Paul Boddie  wrote:

> From: Paul Boddie 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 8:12 PM
> On 14 Mai, 21:18, Ed Keith 
> wrote:
> >
> > The GPL is fine when all parties concern understand
> what source code is
> > and what to do with it. But when you add people like
> my father to the loop
> > if gets very ugly very fast.
> 
> Sure, and when I'm not otherwise being accused of pushing
> one
> apparently rather unpopular man's agenda, I am interested
> in knowing
> what the best practices should be and how they can be
> followed more
> widely.
> 
> Although Bill Gates once apparently claimed that no-one
> needs the
> source code for their word processor or office suite, there
> are still
> benefits in people like your father having access to the
> sources, even
> if this obviously means that he isn't going to recompile it
> himself:
> he can get others to fix things, particularly if his
> favourite version
> is no longer widely supported; if you were from a part of
> the planet
> where you were comfortable with a widely-spoken "global"
> language but
> your father could only converse in a less widely-spoken
> "minority"
> language not generally supported by such software, someone
> (perhaps
> you) could undertake the task of translating that
> software.
> 
> Whether or not one is comfortable with copyleft-style
> licences, there
> clearly is a benefit in providing access to software
> governed by those
> licences. Being able to do so responsibly is obviously a
> prerequisite
> to feeling comfortable about it.
> 
> Paul
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

But if I license my software with a less restrictive license, like MIT, Boost or Apache, programmers can access the source code, and people like my father can give the executable to their friends without violating the law. IMHO that is better for everybody.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From aahz at pythoncraft.com  Fri May 14 23:55:14 2010
From: aahz at pythoncraft.com (Aahz)
Date: 14 May 2010 20:55:14 -0700
Subject: Picking a license
References: 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	
	
Message-ID: 

In article ,
Paul Boddie   wrote:
>On 14 Mai, 03:56, a... at pythoncraft.com (Aahz) wrote:
>>
>> IMO this only makes sense if one agrees that people should not be allowed
>> to sell software for money.  Absent that agreement, your argument about
>> freedom seems rather limited.
>
>You'll have to explain this to me because I don't quite follow your
>assertion. You can sell copyleft-licensed software, although I accept
>that you can't set an arbitrarily high price on the sources for
>someone who has already acquired a binary distribution.

You can't really sell Open Source software in any practical way; someone
will always undercut you once it's out in the wild.  You can only sell
support for the software, which is entirely different.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From aahz at pythoncraft.com  Sat May 15 00:00:53 2010
From: aahz at pythoncraft.com (Aahz)
Date: 14 May 2010 21:00:53 -0700
Subject: Picking a license
References: 
	<93d67bd9-6721-4759-a3de-412b95b29a93@c11g2000vbe.googlegroups.com>
Message-ID: 

In article <93d67bd9-6721-4759-a3de-412b95b29a93 at c11g2000vbe.googlegroups.com>,
Paul Boddie   wrote:
>
>Whether or not one is comfortable with copyleft-style licences, there
>clearly is a benefit in providing access to software governed by those
>licences. 

...and this newsgroup surely is evidence that there is benefit to Open
Source software that isn't copyleft.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From steve at REMOVE-THIS-cybersource.com.au  Sat May 15 00:19:33 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 04:19:33 GMT
Subject: Picking a license
References: 
Message-ID: <4bee20d5$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 07:10:50 -0700, Ed Keith wrote:

> But if my client give someone else a copy of the binary I gave them,
> they are now in violation. I do not want to put my client in this
> position.

If your client is distributing software without reading and obeying the 
licence terms, then they are either idiots, or unethical, or possibly 
both.

If you want to make life easier on them by reducing the consequences of 
such foolish and/or unethical behaviour, that of course is your right. 
There are good reasons for doing so, and equally good reasons for not. 
It's also their right to ask you to assign copyright to them, or to 
licence the work using the MIT licence (or similar), or to ask for an 
exclusive licence. Or even to ask you to sign a "no compete" agreement 
which prevents you from ever writing code again. It's your choice whether 
to say Yay or Nay, and if you agree, how much you will charge for it.


> When using the GPL or LGPL you can do anything you want as long as you
> do not let anyone else use your work, but if you let someone else have a
> copy of you work you are putting them in a position where that can
> easily/inadvertently violate the law. I do not want to put clients in
> legal jeopardy, so I do not use GPL, or LGPLed code.

You're not putting them in legal jeopardy, they are. It is their decision 
whether or not to violate the licence.


-- 
Steven


From pmaupin at gmail.com  Sat May 15 00:50:48 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 21:50:48 -0700 (PDT)
Subject: Picking a license
References:  
	<4bee0df4$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <7bfa5457-027d-4ee1-a54f-3c0baba45a55@e21g2000vbl.googlegroups.com>

On May 14, 9:59?pm, Steven D'Aprano  wrote:
> I think this talk about freedoms is dangerously incomplete, and is
> confusing the issue rather than shedding more light. Both licences grant
> the same positive freedoms (freedom to do something). MIT-style licences
> grant permission to:
>
> * make copies of the work;
> * make derivative works based on the work; and
> * distribute those derivative works to others.
>
> The GPL grants precisely the same three rights. There is no difference in
> the rights granted.
>
> The MIT licence imposes an obligation on the licencee:
>
> * you must include a copy of the licence and copyright notice with the
> work and/or any derivative works.
>
> The GPL adds a further obligation:
>
> * any derivative works must also be licenced under the GPL.
>
> If we want to talk about "freedoms", rather than rights and obligations,
> we need to distinguish between positive freedoms (freedom to do
> something) and negative freedoms (freedoms from something) and not just
> blithely mix them up.

That is well-put, and of course the whole purpose of the extra
obligation or "negative freedom" is to ensure the rights or "positive
freedoms" of downstream recipients of the software.

In theoretical terms, everybody who redistributes software under the
GPL has the same obligations imposed, but as I have shown in other
posts, this obligation is unevenly enforced, and probably by design.

In practical terms, the additional obligations of the GPL license are
imposed on those who distribute huge quantities of software (Ubuntu,
Red Hat) and those who distribute derivative works (by combining other
software with the GPLed software).

It is questionable whether distributors such as Ubuntu and Red Hat
truly see this as an obligation; certainly they also distribute source
for permissively-licensed programs, and certainly other parties
happily provide source for fully BSD-licensed distributions for free.
Nonetheless, some of the smaller derivative distributors undoubtedly
wind up paying for more bandwidth than they would like.

So, the bulk of the additional obligations fall squarely on people who
distribute derivative works.  This is by design.  It is what keeps the
Microsofts of this world from appropriating GPLed software.  As I have
said many times, for people who worry about this stuff, the GPL is
absolutely the right license, because any license that gets them
writing free software rather than worrying about freeloaders is a
great license.

But for someone (let's call him "Fred") who distributes derivative
works to a customer, the additional obligation you mention for the GPL
actually has 4 separate components:

1) Full source for the original program must be provided
2) Fred's own additional source code must also be provided
3) Fred can't link to any proprietary software at all.
4) Fred must be sure that his customer is OK with the resultant work
product being under the GPL.

Now, if Fred was going to provide source anyway, the only possible
sticking points are really #3 and #4.  But those can be very sticky.
Let's start with #3.

If the proprietary software that is being linked to is, for example,
Oracle, Fred can't legally use GPLed software.  Well, actually he
might be able to, if he writes the software as a work-for-hire (as a
contractor for the customer), because then there might not be a true
distribution of the final package.  So that might actually reduce the
amount of free software in the world -- if Fred writes it as work for
hire, he can't distribute it to anybody else, and the customer is not
about to make a distribution of any of the software, so this is a case
where, if Fred can find and leverage permissively licensed software
instead of GPLed software, the amount of free software available in
the world can actually go up.

Now for #4, where Fred just has to communicate with and educate the
customer.  Even if the customer is just going to use the software in-
house with no plans to ever distribute it, the act of merely *asking*
a customer if it is OK to use GPLed software in the solution can, in
some cases, mean the difference between being able to sign a contract
and get started right away, or needing a review by the lawyers that
won't conclude for a month and then being told "no" or, even worse,
that "business conditions have changed."

Obviously, if there were a GPLed solution already available that was
the best tool for the job, it might be a good tactic for Fred (if he
weren't too worried about the interminable lawyer review) to explain
that it will cost $X for a GPL solution, and $X+Y for a non-GPL
solution.  Or even a good tactic to precede that with a simple
question of if the customer ever uses GPL software, and if they
already do, do they have a policy.  (But that has to be asked in such
a way as to not provide an original research question for the lawyer.)

But if, starting out, there is no compelling GPLed solution, then
there is no good reason to even ask things like that of the customer
-- better to just start coding.  And if the climate is right to ask if
the customer minds if Fred reuses and shares the code, there is a good
chance that Fred will use a permissive license on any generic code, if
he wants to enable others like himself.

So, there are good reasons for both kinds of licenses, which I think
everybody on the pro-permissive side has been saying all along.  Of
course, "force" is a more inflammatory word that "obligation" in some
contexts, and that has been used in what I would admit on my part is a
knee-jerk reaction to my belief that "free" and "freedom" are more
inflammatory words than "rights" in the same contexts.

Regards,
Pat


From ben+python at benfinney.id.au  Sat May 15 00:57:35 2010
From: ben+python at benfinney.id.au (Ben Finney)
Date: Sat, 15 May 2010 14:57:35 +1000
Subject: Picking a license
References: 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	
	
	
Message-ID: <87r5ldbw3k.fsf@benfinney.id.au>

aahz at pythoncraft.com (Aahz) writes:

> You can't really sell Open Source software in any practical way;
> someone will always undercut you once it's out in the wild. You can
> only sell support for the software, which is entirely different.

Not at all. I've been selling all the software I write for clients for
the past ten years, and it's all free software. It's been very practical
for me and those I've worked with.

You can't sell free software like selling loaves of bread, but that's a
much more limited case and a far cry from your claim. Selling free
software is quite practical and a good way to fund development of
software that otherwise wouldn't be written as free software.

-- 
 \     ?Why am I an atheist? I ask you: Why is anybody not an atheist? |
  `\      Everyone starts out being an atheist.? ?Andy Rooney, _Boston |
_o__)                                                Globe_ 1982-05-30 |
Ben Finney


From stefan_ml at behnel.de  Sat May 15 01:17:47 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 15 May 2010 07:17:47 +0200
Subject: Picking a license
In-Reply-To: <87k4rgfutu.fsf@benfinney.id.au>
References: 		<4BE05D75.7030301@msn.com>
	 <87k4rgfutu.fsf@benfinney.id.au>
Message-ID: 

aahz at pythoncraft.com (Aahz) writes:
> Which license you use depends partly on your political philosophy.

Did they close down debian-legal, or why is this thread growing so long?

Ah, I forgot - Friday ...

Stefan



From pmaupin at gmail.com  Sat May 15 01:22:39 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 22:22:39 -0700 (PDT)
Subject: Picking a license
References:  
	<4bee20d5$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <8c45dd27-174d-495c-bf64-814f59fc6622@k31g2000vbu.googlegroups.com>

On May 14, 11:19?pm, Steven D'Aprano  wrote:
> On Fri, 14 May 2010 07:10:50 -0700, Ed Keith wrote:
> > But if my client give someone else a copy of the binary I gave them,
> > they are now in violation. I do not want to put my client in this
> > position.
>
> If your client is distributing software without reading and obeying the
> licence terms, then they are either idiots, or unethical, or possibly
> both.

How about just "ignorant."  Maybe even "blissfully ignorant" as in,
you just used permissively-licensed software, and since you're not
Microsoft and they paid you a fair amount of money for the software
and you both agreed on a handshake or a back of the napkin contract
that you could both do whatever you wanted with the software (except
stripping copyright notices), they go and do exactly that.

> If you want to make life easier on them by reducing the consequences of
> such foolish and/or unethical behaviour, that of course is your right.
> There are good reasons for doing so, and equally good reasons for not.

Well, for people who don't feel the imperative of the FSF's prime
directive, the only really good reason for "not" is if you found some
super-cool GPL-licensed software that will greatly reduce the cost of
the contract, *and* you can leverage some of the savings into your own
pocket.

> It's also their right to ask you to assign copyright to them, or to
> licence the work using the MIT licence (or similar), or to ask for an
> exclusive licence. Or even to ask you to sign a "no compete" agreement
> which prevents you from ever writing code again. It's your choice whether
> to say Yay or Nay, and if you agree, how much you will charge for it.

Sure, contracts can be made as simple or complex as the parties want.
In most cases, reuse of preexisting GPLed software certainly won't
simplify the negotiations, though.  In Texas, though, that particular
"no-compete" wouldn't fly.  I'll sign non-compete clauses like that in
the blink of an eye; it's the speciously more limited ones that you
have to watch out for because sometimes the courts will uphold at
least parts of those: http://www.texasnoncompetelaw.com/

> > When using the GPL or LGPL you can do anything you want as long as you
> > do not let anyone else use your work, but if you let someone else have a
> > copy of you work you are putting them in a position where that can
> > easily/inadvertently violate the law. I do not want to put clients in
> > legal jeopardy, so I do not use GPL, or LGPLed code.
>
> You're not putting them in legal jeopardy, they are. It is their decision
> whether or not to violate the licence.

Uh-huh.  If they're in legal jeopardy, you are too (at least in the
USA) because the first thing they are going to do is to cross-sue you
for failure to explain to them that you were using GPLed software.
Doesn't matter if it's not true.  Doesn't even matter if you have
signed contracts that prove it's not true.  It's still going to cost
you a pretty penny to get away from the lawsuit.

So, really, why go through all that unless it's going to save enough
on the contract to justify it?  Seriously, a software contract can be
less than half a page under some circumstances, and written so that
basically you and they can both do whatever you want, and neither is
going to sue the other.

Regards,
Pat


From steve at REMOVE-THIS-cybersource.com.au  Sat May 15 01:45:24 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 05:45:24 GMT
Subject: Picking a license
References: 
Message-ID: <4bee34f4$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 09:18:09 -0700, Ed Keith wrote:

> But if I release it with the Boost license, while technically I can
> release it with the GPL tomorrow, in practice everyone will use the
> previously released Boost licensed version.

That's a very interesting experiment to perform. Perhaps you should dual-
licence some library and see which gets more downloads and users?



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Sat May 15 01:50:57 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 05:50:57 GMT
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com>
Message-ID: <4bee3641$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 08:37:14 -0700, Patrick Maupin wrote:

> I don't actually
> recall any suits about violations of the MIT or Apache licenses.

The most obvious example was that the University of Berkley counter-sued 
Unix System Laboratories over USL's infringement of the BSD licence.

Admittedly this wasn't the MIT or Apache licence, and the circumstances 
were fairly special. It's a fairly safe bet that anyone who is 
distributing their software under such a licence is sending an implicit 
signal that they don't intend to sue. But it does demonstrate that MIT-
style licences aren't the same as public domain -- they do impose 
obligations on the recipient, even if those obligations are much lighter 
than those of the GPL.


-- 
Steven


From pmaupin at gmail.com  Sat May 15 01:56:37 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 22:56:37 -0700 (PDT)
Subject: Picking a license
References: 
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<4bee3641$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <9eee39f5-fd58-4187-a3bb-4971382f5ec6@t15g2000vbo.googlegroups.com>

On May 15, 12:50?am, Steven D'Aprano  wrote:
> On Fri, 14 May 2010 08:37:14 -0700, Patrick Maupin wrote:

> The most obvious example was that the University of Berkley counter-sued
> Unix System Laboratories over USL's infringement of the BSD licence.

Well, I specifically excluded BSD for this reason.  But in any case,
I'd be willing to place a small wager that it's the *only* (rather
than merely the "most obvious") example you can find...

> Admittedly this wasn't the MIT or Apache licence, and the circumstances
> were fairly special. It's a fairly safe bet that anyone who is
> distributing their software under such a licence is sending an implicit
> signal that they don't intend to sue.

Right.

> But it does demonstrate that MIT-
> style licences aren't the same as public domain -- they do impose
> obligations on the recipient, even if those obligations are much lighter
> than those of the GPL.

And I certainly have never deliberately attempted to mislead on this
point.

Regards,
Pat


From pavlovevidence at gmail.com  Sat May 15 02:23:19 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 14 May 2010 23:23:19 -0700 (PDT)
Subject: an element from a set
References: <28560792.post@talk.nabble.com>
	
Message-ID: <213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>

On May 14, 9:39?am, Terry Reedy  wrote:
> On 5/14/2010 11:24 AM, gerardob wrote:
>
>
>
> > Hello, let S be a python set which is not empty
> > (http://docs.python.org/library/sets.html)
>
> > i would like to obtain one element (anyone, it doesn't matter which one) and
> > assign it to a variable.
>
> > How can i do this?
>
> Depends on whether or not you want the element removed from the set
>
> #3.1
> ?>>> s=set(range(10))
> ?>>> s
> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
> ?>>> x=next(iter(s))
> ?>>> x
> 0
> ?>>> s
> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
> ?>>> x = s.pop()
> ?>>> x
> 0
> ?>>> s
> {1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed
>
> The choice of 0 is an implementation artifact. It could have been any
> member.

Which brings up an interesting question: how do you get a random
element from a set?

random.choice(list(s))

is the most straightforward way and will work a lot of the time, but
how would you avoid creating the list?  I can't think of a way off
hand.


Carl Banks



From shashank.sunny.singh at gmail.com  Sat May 15 02:32:59 2010
From: shashank.sunny.singh at gmail.com (Shashank Singh)
Date: Sat, 15 May 2010 12:02:59 +0530
Subject: an element from a set
In-Reply-To: <213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
References: <28560792.post@talk.nabble.com>
	 
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
Message-ID: 

On Sat, May 15, 2010 at 11:53 AM, Carl Banks wrote:

> On May 14, 9:39 am, Terry Reedy  wrote:
> > On 5/14/2010 11:24 AM, gerardob wrote:
> >
> >
> >
> > > Hello, let S be a python set which is not empty
> > > (http://docs.python.org/library/sets.html)
> >
> > > i would like to obtain one element (anyone, it doesn't matter which
> one) and
> > > assign it to a variable.
> >
> > > How can i do this?
> >
> > Depends on whether or not you want the element removed from the set
> >
> > #3.1
> >  >>> s=set(range(10))
> >  >>> s
> > {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
> >  >>> x=next(iter(s))
> >  >>> x
> > 0
> >  >>> s
> > {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
> >  >>> x = s.pop()
> >  >>> x
> > 0
> >  >>> s
> > {1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed
> >
> > The choice of 0 is an implementation artifact. It could have been any
> > member.
>
> Which brings up an interesting question: how do you get a random
> element from a set?
>
> random.choice(list(s))
>
> is the most straightforward way and will work a lot of the time, but
> how would you avoid creating the list?  I can't think of a way off
> hand.
>
> How about random.sample(s, 1)[0]? Is it inefficient?

>
> Carl Banks
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regards
Shashank Singh
Senior Undergraduate, Department of Computer Science and Engineering
Indian Institute of Technology Bombay
shashank.sunny.singh at gmail.com
http://www.cse.iitb.ac.in/~shashanksingh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Sat May 15 02:34:42 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 06:34:42 GMT
Subject: Picking a license
References: 
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
	<9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com>
	<548024fc-dd56-48b9-907d-3aa6a722b43c@l31g2000yqm.googlegroups.com>
	
	<6767a5ae-2aab-4532-8e18-8c445920624e@d3g2000vbr.googlegroups.com>
Message-ID: <4bee4081$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 19:17:20 -0700, Patrick Maupin wrote:

> On May 14, 9:04?pm, Lawrence D'Oliveiro  central.gen.new_zealand> wrote:
>> In message <548024fc-
>> dd56-48b9-907d-3aa6a722b... at l31g2000yqm.googlegroups.com>, Patrick
>> Maupin wrote:
>>
>> > The confusion that some are showing in this thread about whether
>> > source must be distributed certainly helps to show that as well.
>>
>> What ?confusion?? The GPL requires that source must always be offered
>> in some form. Simple as that.
> 
> Right, but when I explained that that requirement also applies to Joe,
> who downloaded an ISO from Ubuntu and burned a CD and gave it away, no
> less than 3 people jumped in to "correct" me.

The confusion is over what form that offer may be, and what counts as 
distribution.

Your claim seems plausible, but whether it is correct or not is not so 
obvious. I would say that, given the lack of any lawsuits against 
individuals and Linux User Groups, the *intention* of the GPL is to allow 
individuals to act as a proxy between the end-user and the actual 
distributor (in this case, Ubuntu) without taking on the obligation to 
provide source code.

Looking at the FAQs, my comments in square brackets:

http://www.gnu.org/licenses/gpl-faq.html#WhatDoesWrittenOfferValid

    If you commercially distribute binaries not accompanied with 
    source code [e.g. as Canonical does with Ubuntu], the GPL says
    you must provide a written offer to distribute the source code 
    later. [This is available on their website.] When users non-
    commercially redistribute the binaries they received from you, 
    [e.g. I download the Ubuntu install DVD and make a copy for
    my friend] they must pass along a copy of this written offer. 
    [I am obliged to tell my friend they can get the Ubuntu written
    offer from Ubuntu's website, and pass it on directly if asked]
    This means that people who did not get the binaries directly 
    from you can still receive copies of the source code, along 
    with the written offer.

    The reason we require the offer to be valid for any third party 
    is so that people who receive the binaries indirectly in that way
    can order the source code from you. [In other words, if I give
    Fred a copy of Ubuntu, it is Canonical and not me who is responsible
    for providing the source code to Fred if he asks for it.]


Okay, it's not the licence itself, but the FAQ pretty much makes the 
intention clear. Merely handing over an Ubuntu DVD to a friend is not a 
violation of the GPL.



-- 
Steven


From prologic at shortcircuit.net.au  Sat May 15 02:40:46 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sat, 15 May 2010 16:40:46 +1000
Subject: an element from a set
In-Reply-To: <213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
References: <28560792.post@talk.nabble.com>
	 
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
Message-ID: 

On Sat, May 15, 2010 at 4:23 PM, Carl Banks  wrote:
> Which brings up an interesting question: how do you get a random
> element from a set?
>
> random.choice(list(s))
>
> is the most straightforward way and will work a lot of the time, but
> how would you avoid creating the list? ?I can't think of a way off
> hand.

random.choice(...) requires that the object passed to it supports "sequencing".

This means it must implement: __getitem__ (which a list does).

I don't think there is a way to retrieve a random element from a set without
first turning it into a sequence (list) unless the underlying data of
a set were exposed.

--James


From clp2 at rebertia.com  Sat May 15 02:52:38 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Fri, 14 May 2010 23:52:38 -0700
Subject: an element from a set
In-Reply-To: <213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
References: <28560792.post@talk.nabble.com>
	
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
Message-ID: 

On Fri, May 14, 2010 at 11:23 PM, Carl Banks  wrote:
> On May 14, 9:39?am, Terry Reedy  wrote:
>> On 5/14/2010 11:24 AM, gerardob wrote:
>> > Hello, let S be a python set which is not empty
>> > (http://docs.python.org/library/sets.html)
>>
>> > i would like to obtain one element (anyone, it doesn't matter which one) and
>> > assign it to a variable.
>>
>> > How can i do this?
>>
>> Depends on whether or not you want the element removed from the set
>>
>> #3.1
>> ?>>> s=set(range(10))
>> ?>>> s
>> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>> ?>>> x=next(iter(s))
>> ?>>> x
>> 0
>> ?>>> s
>> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
>> ?>>> x = s.pop()
>> ?>>> x
>> 0
>> ?>>> s
>> {1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed
>>
>> The choice of 0 is an implementation artifact. It could have been any
>> member.
>
> Which brings up an interesting question: how do you get a random
> element from a set?
>
> random.choice(list(s))
>
> is the most straightforward way and will work a lot of the time, but
> how would you avoid creating the list? ?I can't think of a way off
> hand.

def random_set_elem(s):
    iterator = iter(s)
    n = random.randint(0, len(s)-1)
    for i in xrange(n):
        next(iterator)
    return next(iterator)

Avoids creating the list, but it's still O(M). If you're gonna pick
multiple times from the same set, you're better off just converting it
to a list.

Cheers,
Chris
--
http://blog.rebertia.com


From pmaupin at gmail.com  Sat May 15 03:01:58 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 00:01:58 -0700 (PDT)
Subject: Picking a license
References:  
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
	<9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com> 
	<548024fc-dd56-48b9-907d-3aa6a722b43c@l31g2000yqm.googlegroups.com> 
	
	<6767a5ae-2aab-4532-8e18-8c445920624e@d3g2000vbr.googlegroups.com>
	<4bee4081$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <2bb90c13-8f61-444d-8715-673da14bdad3@v18g2000vbc.googlegroups.com>

On May 15, 1:34?am, Steven D'Aprano  wrote:
> On Fri, 14 May 2010 19:17:20 -0700, Patrick Maupin wrote:
> > On May 14, 9:04?pm, Lawrence D'Oliveiro  > central.gen.new_zealand> wrote:
> >> In message <548024fc-
> >> dd56-48b9-907d-3aa6a722b... at l31g2000yqm.googlegroups.com>, Patrick
> >> Maupin wrote:
>
> >> > The confusion that some are showing in this thread about whether
> >> > source must be distributed certainly helps to show that as well.
>
> >> What ?confusion?? The GPL requires that source must always be offered
> >> in some form. Simple as that.
>
> > Right, but when I explained that that requirement also applies to Joe,
> > who downloaded an ISO from Ubuntu and burned a CD and gave it away, no
> > less than 3 people jumped in to "correct" me.
>
> The confusion is over what form that offer may be, and what counts as
> distribution.
>
> Your claim seems plausible, but whether it is correct or not is not so
> obvious.

Exactly.  And when people say it's obviously incorrect, they're
obviously incorrect, because if it were obvious, it would have been
answered correctly by now :-)

> I would say that, given the lack of any lawsuits against
> individuals and Linux User Groups, the *intention* of the GPL is to allow
> individuals to act as a proxy between the end-user and the actual
> distributor (in this case, Ubuntu) without taking on the obligation to
> provide source code.

Yes, and as I said, lawsuits against individuals would be bad for
business (as business is defined in the GPL world).

> Looking at the FAQs, my comments in square brackets:
>
> http://www.gnu.org/licenses/gpl-faq.html#WhatDoesWrittenOfferValid

Well, for one thing, that section is only *directly* relevant to GPL
v2.  For another thing, it is only directly relevant to Canonical's
obligations, not Joe's.

[Text snipped; part of d'Aprano interpretation left]

> ? ? [I am obliged to tell my friend they can get the Ubuntu written
> ? ? offer from Ubuntu's website, and pass it on directly if asked]

Sure, and that's *exactly* what I said isn't going to happen in a lot
of cases, because it takes a careful reading of the license and FAQ
for someone to realize that.  The download button at Ubuntu tells you
to make more copies (your "rights") without telling you about the
source code (your "obligations").  Which is perfectly legal, but
someone who isn't reading carefully could easily give a CD to a friend
without the offer of source.

> ? ? This means that people who did not get the binaries directly
> ? ? from you can still receive copies of the source code, along
> ? ? with the written offer.

More obligations on the part of Canonical;  note, however, that
Canonical's obligation to distribute source to a CD that you gave to a
friend may not even be long enough to cover 3 years after the time you
gave the CD to your friend.

> ? ? The reason we require the offer to be valid for any third party
> ? ? is so that people who receive the binaries indirectly in that way
> ? ? can order the source code from you. [In other words, if I give
> ? ? Fred a copy of Ubuntu, it is Canonical and not me who is responsible
> ? ? for providing the source code to Fred if he asks for it.]
>
> Okay, it's not the licence itself, but the FAQ pretty much makes the
> intention clear.

Yes, it does.  The FAQ part you quote is for Canonical and for v2.
The one for the user handing over the CD still says (for v3):

"I downloaded just the binary from the net. If I distribute copies, do
I have to get the source and distribute that too? Yes. The general
rule is, if you distribute binaries, you must distribute the complete
corresponding source code too. The exception for the case where you
received a written offer for source code is quite limited."

But, even if you fall under that limited exception, you *still* have
to make the written offer, and I stand by my assertion that even that
token act is not happening in lots of cases as we speak.

> Merely handing over an Ubuntu DVD to a friend is not a
> violation of the GPL.

... as long as you make the written offer.

Regards,
Pat


From contact at xavierho.com  Sat May 15 03:27:51 2010
From: contact at xavierho.com (Xavier Ho)
Date: Sat, 15 May 2010 17:27:51 +1000
Subject: help need to write a python spell checker
In-Reply-To: 
References: 
Message-ID: 

1) Welcome to Python-List!

2) Python-list doesn't like to do other people's homework.

3) What have you tried?

Cheers,
Xav

On Fri, May 14, 2010 at 6:19 PM, harry k  wrote:

> Write a spell checking tool that will identify all misspelled word in a
> text file using a provided dictionary.
>
>
> The program will accept either one or two command line parameters.
> 1.      The first command line parameter is the name of the text file that
> will be checked.
> 2.      The optional second command line parameter is the name of the
> dictionary file ? a file of words with one word per line.  The default
> dictionary file is ref.txt.
> The program will write out the misspelled words, one per line, in
> alphabetical order.
>
> Extend the spell checking tool so that as well as identifying all
> misspelled words,  the program will list the line numbers in the file where
> the incorrect spelling occurs.
>
> The program will write out the misspelled words (one per line, in
> alphabetical order), followed by a tab character, followed by the list of
> line numbers that word is misspelled in,in ascending order, on the same
> line, separated by a single space.
>
>
> Extend the spell-checking tool so that the program will also print out a
> list of possible correct spellings for the words.
>
> The program will write out the misspelled words (one per line, in
> alphabetic order), followed (on the same line) by a single space, followed
> by the list of line numbers in ascending order, each separated by a single
> space, followed by a single space, then the list of possible correct
> spellings, each separated by a single space.
>
> Find the alternate spellings by considering:
> a.      Words in the dictionary that are the same length but:
> a.      Have a pair of characters interchanged
> b.      Differ by one character from the misspelled word
> b.      Words that are one character longer or one character shorter, but
> otherwise match the misspelled word.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From prologic at shortcircuit.net.au  Sat May 15 03:30:09 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sat, 15 May 2010 17:30:09 +1000
Subject: help need to write a python spell checker
In-Reply-To: 
References: 
Message-ID: 

On Fri, May 14, 2010 at 6:19 PM, harry k  wrote:
> Write a spell checking tool that will identify all misspelled word in a text file using a provided dictionary.

Is this an assignment ? Sure looks like it!

I don't see a question anywhere.

--james


From lie.1296 at gmail.com  Sat May 15 03:33:16 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sat, 15 May 2010 17:33:16 +1000
Subject: Broken pipe
In-Reply-To: 
References: 
	
	 <4bec2a9a$1@dnews.tpgi.com.au>
	
Message-ID: <4bee4e98$1@dnews.tpgi.com.au>

On 05/15/10 11:56, Lawrence D'Oliveiro wrote:
> In message <4bec2a9a$1 at dnews.tpgi.com.au>, Lie Ryan wrote:
> 
>> On 05/13/10 22:41, Lawrence D'Oliveiro wrote:
>>> In message , Chris
>>> Rebert wrote:
>>>
>>>> Also, please don't use semicolons in your code. It's bad style.
>>>
>>> Wonder why they?re allowed, then.
>>
>> they're there for line continuation, e.g.:
>>
>> a = 40; foo(a)
>>
>> but in many cases, putting two statements in a single line reduces
>> readability so use the semicolons extremely conservatively. But the
>> worst is the abuse of semicolons for end-of-line markers.
> 
> So why are they allowed, then?

Convenience. I've sometimes, in the interactive interpreter, written
codes that looks like:

a = 0; ... other code ...

since I need to reset the variable 'a' every time 'other code' is run.
If there hasn't been the ;, then I'd have to press up, up, enter, up,
up, change, enter. Compare that to up, change, enter since I can "up"
two "lines" at once.

In the interactive interpreter these sort of conveniences is often useful.

Unless your "why are they allowed" is about why a blank continuation
(i.e. abusing ; as line ending) is allowed. In that case, I'd presume
it's just because conceptually:

foo();
bar

is just:

foo()

bar()


but probably you're right; maybe they should be strictly disallowed. But
it's too late for this kind of change, not until py4k.


From sumerc at gmail.com  Sat May 15 06:18:45 2010
From: sumerc at gmail.com (k3xji)
Date: Sat, 15 May 2010 03:18:45 -0700 (PDT)
Subject: yappi 0.51 released
Message-ID: <292fddf7-4cc4-4a2f-b10e-fc252fd47590@f14g2000vbn.googlegroups.com>

Hi all,

Yappi (Yet Another Python Profiler) 0.51 released. See the version
highlights:

    * OPTIMIZATION:Use per-pit cpc for better accuracy in different
timing_sample values. Now timing_sample is not linearly decreasing the
timing accuracy for most of the applications tested. We reduced the
runtime of the profiler from 3.2 secs to 0.7 by giving away ~%2 timing
accuracy. This means yappi can now run 4x-7x times faster than the
standart cProfile by increasing timing_sample values with very little
accuracy defect.
    * Python 2.6.5 gives import yappi Dll load failed error. This is
due to VC2008 compile. Unfortunately, we need to use VC Express Mingw
is not working because of MSVCR dll files on 2.6.5 on some machines.
    * Use snprintf for stat handling code. There may be some buffer
overflow situations. Use PyOS_snprintf for platform differences.
(Thanks to Dave Peticolas)
    * Format stat STRINGs from left, instead of right. (Thanks to Dave
Peticolas)
    * OPTIMIZATION:Move ctx calculation code to callback function.
Optimize call_XXX functions as much as possible.
    * Move timing calculation code from header to the C file.
    * MACRO defining code in setup.py is broken for some compilers,
use DEFINE_MACRO keyword.
    * OPTIMIZATION:Disable HASH table linked list swapping code, it is
not adapting to the profiler nature very well. Rollback to simple hash-
table-bucketing.

See below for more and download:
http://code.google.com/p/yappi/

Thanks,
twitter.com/sumercip


From lie.1296 at gmail.com  Sat May 15 06:30:31 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sat, 15 May 2010 20:30:31 +1000
Subject: Puzzled by code pages
In-Reply-To: 
References: 
Message-ID: <4bee7823$1@dnews.tpgi.com.au>

On 05/15/10 10:27, Adam Tauno Williams wrote:
> I'm trying to process OpenStep plist files in Python.  I have a parser
> which works, but only for strict ASCII.  However plist files may contain
> accented characters - equivalent to ISO-8859-2 (I believe).  For example
> I read in the line:
> 
>>>> handle = open('file.txt', 'rb')
>>>> data = handle.read()
>>>> handle.close()
>>>> data
> '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
> NSFileName;\n'

I presume you're using Python 2.x.

> What is the correct way to re-encode this data into UTF-8 so I can use
> unicode strings, and then write the output back to ISO8859-?
> 
> I can read the file using codecs as ISO8859-2, but it still doesn't seem
> correct.
> 
>>>> handle = codecs.open('file.txt', 'rb', encoding='iso8859-2')
>>>> data = handle.read()
>>>> handle.close()
>>>> data
> u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
> NSFileName;\n'

When printing in the interactive interpreter, python uses __repr__
representation by default. If you want to use __str__ representation use
"print data" (note, your terminal must support printing unicode
characters); either way, even though the string looks like '\u0102' when
printed on the terminal, the binary pattern inside the memory should
correctly represents the accented character.

f = codecs.open("in.txt", 'rb', encoding="iso8859-2")
f2 = codecs.open("out.txt", 'wb', encoding="utf-8")
s = f.read()
f2.write(s)
f.close()
f2.close()


From python.list at tim.thechases.com  Sat May 15 07:02:06 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Sat, 15 May 2010 06:02:06 -0500
Subject: help need to write a python spell checker
In-Reply-To: 
References: 
	
Message-ID: <4BEE7F2E.1020509@tim.thechases.com>

> 2) Python-list doesn't like to do other people's homework.


This could be fun... :)  For this problem, all you have to do is 
a big "if/elif/else" statement for every possible mis-spelling. 
If you want to get really fancy, you could put all the 
mis-spellings in a set() and then test the incoming word against 
the set for membership...For bonus points, you could use the 
anydbm module as a mapping from known-bad-spellings to the 
correct spelling so it can auto-correct for you...

Then you know if the word is mis-spelled.  The rest is pretty 
easy. ;-)

-tkc


(or maybe this only sounds amusing if you're sleep-deprived, up 
with your kid in the wee hours of the morning when you'd prefer 
to be snoozing)



From timoverbeek10 at gmail.com  Sat May 15 07:02:36 2010
From: timoverbeek10 at gmail.com (timo verbeek)
Date: Sat, 15 May 2010 04:02:36 -0700 (PDT)
Subject: Human word reader
Message-ID: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>

I'm planning to create a human word program
A human inputs a string
"Give me the weather for London please."
Then I will strip the string.
"weather for london"
Then I get the useful information.
what:"weather" where:"london"
After that I use the info.

I need help with getting the useful information how do I get the place
if I don't now how long the string is?


From contact at xavierho.com  Sat May 15 07:12:33 2010
From: contact at xavierho.com (Xavier Ho)
Date: Sat, 15 May 2010 21:12:33 +1000
Subject: Human word reader
In-Reply-To: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
Message-ID: 

On Sat, May 15, 2010 at 9:02 PM, timo verbeek wrote:

> I'm planning to create a human word program
>



>
> I need help with getting the useful information how do I get the place
> if I don't now how long the string is?
>
> Boy, that is a very hard problem. Are the inputs restricted to anything?
English only? Can the human user type in *anything*?

You need to have a very, very good set of heruistics and deterministic
functions to do that.

What have you got so far?

-

Otherwise,

"How do I get the position of a known word in a string if the length if
unknown?"

>>> input = 'Give me the weather for London please.'
>>> input.find('weather')
12

Cheers,
Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From contact at xavierho.com  Sat May 15 07:13:51 2010
From: contact at xavierho.com (Xavier Ho)
Date: Sat, 15 May 2010 21:13:51 +1000
Subject: Human word reader
In-Reply-To: 
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
Message-ID: 

On Sat, May 15, 2010 at 9:12 PM, Xavier Ho  wrote:

> You need to have a very, very good set of heruistics and deterministic
> functions to do that.
>
> "How do I get the position of a known word in a string if the length if
> unknown?"
>

And this is what I get for late night e-mailing.

is*

heuristic*

-Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From timoverbeek10 at gmail.com  Sat May 15 07:32:18 2010
From: timoverbeek10 at gmail.com (timo verbeek)
Date: Sat, 15 May 2010 04:32:18 -0700 (PDT)
Subject: Human word reader
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
Message-ID: 

On May 15, 1:02?pm, timo verbeek  wrote:
Place starts always with for



From e_d_k at yahoo.com  Sat May 15 07:40:43 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sat, 15 May 2010 04:40:43 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <4bee0df4$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <815851.26625.qm@web58705.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Steven D'Aprano  wrote:

> From: Steven D'Aprano 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 10:59 PM
> On Fri, 14 May 2010 06:39:05 -0700,
> Ed Keith wrote:
> 
> > Yes, under the GPL every one has one set of freedoms,
> under the MIT or
> > Boost license every one has more freedoms. Under other
> licenses they
> > have fewer freedoms.
> 
> I think this talk about freedoms is dangerously incomplete,
> and is 
> confusing the issue rather than shedding more light. Both
> licences grant 
> the same positive freedoms (freedom to do something).
> MIT-style licences 
> grant permission to:
> 
> * make copies of the work;
> * make derivative works based on the work; and
> * distribute those derivative works to others.
> 
> The GPL grants precisely the same three rights. There is no
> difference in 
> the rights granted.
> 
> The MIT licence imposes an obligation on the licencee:
> 
> * you must include a copy of the licence and copyright
> notice with the 
> work and/or any derivative works.
> 
> 
> The GPL adds a further obligation:
> 
> * any derivative works must also be licenced under the
> GPL.
> 
> 

That is why I prefer Boost, which adds very few obligations.



> If we want to talk about "freedoms", rather than rights and
> obligations, 
> we need to distinguish between positive freedoms (freedom
> to do 
> something) and negative freedoms (freedoms from something)
> and not just 
> blithely mix them up.
> 

Good point.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From ldo at geek-central.gen.new_zealand  Sat May 15 07:47:39 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 23:47:39 +1200
Subject: Do any debuggers support "edit and continue?"
References: 
Message-ID: 

In message , Joel 
Koltner wrote:

> Just curious... in Microsoft's Visual Studio (and I would presume some
> other tools), for many languages (both interpreted and compiled!) there's
> an "edit and conitnue" option that, when you hit a breakpoint, allows you
> to modify a line of code before it's actually executed.

Microsoft?s Visual Studio also has a reputation as a bloated and resource-
hungry study in software obesity.

Coincidence? Not if you can come up with a better example of the feature 
you?re touting as so wonderful...


From e_d_k at yahoo.com  Sat May 15 07:50:35 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sat, 15 May 2010 04:50:35 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <87r5ldbw3k.fsf@benfinney.id.au>
Message-ID: <238275.9816.qm@web58702.mail.re1.yahoo.com>

--- On Sat, 5/15/10, Ben Finney  wrote:

> From: Ben Finney 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Saturday, May 15, 2010, 12:57 AM
> aahz at pythoncraft.com
> (Aahz) writes:
> 
> > You can't really sell Open Source software in any
> practical way;
> > someone will always undercut you once it's out in the
> wild. You can
> > only sell support for the software, which is entirely
> different.
> 
> Not at all. I've been selling all the software I write for
> clients for
> the past ten years, and it's all free software. It's been
> very practical
> for me and those I've worked with.
> 
> You can't sell free software like selling loaves of bread,
> but that's a
> much more limited case and a far cry from your claim.
> Selling free
> software is quite practical and a good way to fund
> development of
> software that otherwise wouldn't be written as free
> software.
> 
> -- 
>  \? ????Why am I an atheist? I ask
> you: Why is anybody not an atheist? |
> ? `\? ? ? Everyone starts out being an
> atheist.? ?Andy Rooney, _Boston |
> _o__)? ? ? ? ? ? ?
> ? ? ? ? ? ? ? ?
> ? ? ? ? ? ? ? ?
> ? Globe_ 1982-05-30 |
> Ben Finney
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Why don't your own customers under cut you? If you sell someone GPLed 
software they have the right to redistribute it for less than you are 
distributing it for. That dose not strike me as a viable business model.

How do you make it work?

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From utente at esempio.net  Sat May 15 08:35:04 2010
From: utente at esempio.net (superpollo)
Date: Sat, 15 May 2010 14:35:04 +0200
Subject: Human word reader
In-Reply-To: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
Message-ID: <4bee94f8$0$18652$4fafbaef@reader3.news.tin.it>

timo verbeek ha scritto:
> I'm planning to create a human word program
> A human inputs a string
> "Give me the weather for London please."
> Then I will strip the string.
> "weather for london"
> Then I get the useful information.
> what:"weather" where:"london"
> After that I use the info.
> 
> I need help with getting the useful information how do I get the place
> if I don't now how long the string is?


 >>> query = "Give me the weather for London please."
 >>> what = query.strip("Give me the ").split()[0]
 >>> where = query.strip("Give me the " + what + " for ").split()[0]
 >>> print what, where
weather London
 >>>


From contact at xavierho.com  Sat May 15 08:38:01 2010
From: contact at xavierho.com (Xavier Ho)
Date: Sat, 15 May 2010 22:38:01 +1000
Subject: Human word reader
In-Reply-To: 
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
Message-ID: 

On Sat, May 15, 2010 at 9:32 PM, timo verbeek wrote:

> On May 15, 1:02 pm, timo verbeek  wrote:
> Place starts always with for
>

Okay, much better.

Given that constraint, it looks like regular expression can do the job. I'm
not very experienced with regex, though.

\w* matches a whole word composed of letters and numbers by default.

>>> result = re.search('for \w*', 'Give me the weather for London please.')
>>> result.group()
'for London'
>>> result.group().split()[1]
'London'

Cheers,
Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From promptc2 at hotmail.com  Sat May 15 08:47:56 2010
From: promptc2 at hotmail.com (www.promptc.com)
Date: Sat, 15 May 2010 05:47:56 -0700 (PDT)
Subject: www.promptc.com (only $36,free shipping)for 2010 newest Adidas 
	shoes--Paypal
Message-ID: <768c36c4-ae14-4cfe-8561-e9ce57430d60@31g2000prc.googlegroups.com>

Dear my Lady or Gentleman,

Great day!

  welcome to visit online shopping website  www.Promptc.com

We are professional in supplying nike shox,nike air max,nike
jordan,basketball shoes,adidas shoes,MBT shoes,Vibram-Fivefingers
etc.We do long term business and have high reputation in USA and
Europe country!

Some links of the adidas shoes :
1)    http://www.promptc.com/index.php?main_page=index&cPath=363_364
2)   http://www.promptc.com/index.php?main_page=index&cPath=363_365&sort=20a&page=2
3)http://www.promptc.com/index.php?
main_page=product_info&cPath=363_365&products_id=9776

Basic information:
1)Payment:Paypal,WU,TT etc
2)Delivery time:3-7 days door to door delivery by DHL,TNT,EMS etc
3)quality condition:1:1
4) full size for men and women
5)can do drop-ship to your customers!
6)more order more discount ! ! !
7)we would send out your order within 24 hours once confirmed your
Pyament and then send you the tracking number via email for you to
track the status of the goods.

Please just enter the web site for more details or please fee free to
contact us for any questions! Waitting for your early reply.Hope to
start business with each other soon!

Your sincerity


Megan Li

Promptc Co.,Ltd
www.promptc.com
earphone & headphone, microphone, mp3 player, radio, earphone, bose,
in ear, wireless networking equipment speaker, mobile phone
accessories, mobile phone parts, telephones & parts, adidas shoes, t-
mac shoes, 35th shoes, y3 shoes, timberland shoes, puma shoes, bape
shoes, rift shoes, prada shoes, gucci shoes, ice cream shoes, lv
shoes, lacoste clothing, juicy clothing, evisu clothing, d&g clothing,
polo clothing, bape clothing, red monkey jeans, antik jeans, bape
jeans, evisu jeans, seven jeans, d&g jeans, tluerelgion, jeans,
repuplic jeans, lv bags, chanel bags, gucci bags, juicy bags, chloe
bags, fendi bags, caps and hats, glasses, watches, red monkey jeans,
d&g jeans, citizens of humanity jeans, antik denim jeans, red monkey,
miss sixty, evisu, bbc, citizens for humanity, d&g, rock&republic,
seven, taverniti so jeans, true religion, hermes, chanel, gucci,
prada, mulberry, fendi, chloe, coach, louis vuitton, bag, bags,
handbag, handbags, dior, wallet, purse, balenciage, leather wallets,
womens wallets, ipodlaptop, plasma tv, ipod, psp, ps3, xbox 360,
digital camera, mobile phone, apple, mp3, mp4, nokia, motorola,
samsung, usb, memory card, laptops, ps2, digital samsung, sony, canon,
olympus, ibm, powerbook, ipod nano, ipod video, reebok jersey,
champion jersey, jersey, jerseys, nba jerseys, xxxxx, nfl. shoes,
sports shoes, nike air jordan, nike air force, nike air max, womens
jeans, evisu jeans, womens swimwear, wig, hair pices, jordan 3 clear,
clear jordan 3, lacoste shirts, lacoste t-shirt, lacoste, jordan 21,
jordanjordan shoes, nike shoes, adidas shoes, shoes, jordan, nike,
puma shoes, pumas shoes, sport shoes, casual shoes, addidas shoes,
prada shoes, footwear shoes, nike nike, adidas adidas, puma puma,
prada prada, timberland shoes, timberland timberlan, footwear nike
jordan, air force max, air force one shoes, air force one sneakers,
air force one nikes, men's athletic shoes, shoes sports, women's
athletic shoes, mens athletic shoes, mens sport shoes, air max, air
force one, bape, nike shox, converse, adidas, polo gucci, jimmy choo,
christain dior, lv, replicas sandals mirror image, balenciaga, kooba,
marc jacobs, replicas bags, knock off hermes, womens wallets hermes,
replica bag, wholesale bag, wholesales bag, wholesale gucci bag,
wholesale chanel bag, wholesale hermes bag, wallet soccer shoes,
athletic shoes, clip-in hair, jordan xxi jordan shoes, knock off
hermes, wallet red monkey jeans, bape&bbc jeans, antic jeans, rocawear
jeans, sean john jeans, abercrombie fitch jeans, true religion jeans,
seven jeans, akademiks jeans, levis jeans, diesel jeans, d gjeans, men
sunglasses, sport sunglasses, designer sunglasses, fashion sunglasses,
men black sunglasses, cool sunglasses, dolce gabbana sunglasses, dg
sunglasses, chanel handbag, tiffany jewelry, gucci sun glasses, new
rolex watch, sterling silver necklace, fendi handbag, tiffany
bracelet, wholesale gucci, womens watch, silver necklace pendant,
necklace, nfl.soccer shoes, silver neck, soccer shoes, jordan jordan
shoes, necklace pendant, fashion jewelry necklace, luggage silver tag,
jewel, watch, watches, watches rolex, gold rolex watches, watches
women, gift watches, brand watches, branded watches, women watches,
female watches, rolex, cartier, bvlgari, omega, gucci watch, longines,
soccer shoes, athletic shoes, sports shoes, nike air jordan, nike air
force, nike air max, womens jean jersey nfl, authentic jersey nfl,
jersey nfl youth, football jersey nfl, jersey nfl throwback, cheap
jersey nfl, jersey nfl replica, jersey nfl personalized, jersey kid
nfl, custom jersey nfl, jersey nfl womens, authentic cheap jersey nfl,
jersey nfl replica youth, discount jersey nfl, authentic jersey nfl,
jersey man nfl replica, custom football jersey, college football
jersey, nfl football jersey, nba jersey, mlb jersey, nhl jersey, nike
sneakers, jordan sneakers jersey nfl, authentic jersey nfl, jersey nfl
youth, football jersey nfl, jersey nfl throwback, cheap jersey nfl,
jersey nfl replica, jersey nfl personalized, jersey kid nfl, custom
jersey nfl, jersey nfl womens, authentic cheap jersey nfl, jersey nfl
replica youth, discount jersey nfl, authentic jersey nfl, jersey man
nfl replica, nokia mobile phone, cell phone, cellular phone, cdma,
vertu phone, business phone, vertu signature cell phone, samsung
mobile phone, original phone, telephone, used mobile phone, oem mobile
phone, nokia n series, samsung d900, nokia n75, nokia8800, ipod nano
3rd, ipods, ipod video, apple ipod video, wholesale apple ipod touch,
ipod classic, vertu, verpu, vx, apple ipod shuffle, n71, 72, n90, n91,
n92, n93, n76, motorol] nokia vertu, nokia 8800 sirocco, nokia 8600
luna, nokia 8800, nokia e90, nokia n800, nokia n80, nokia n83, nokia
n76, nokia n72, nokia n90, nokia n92, nokia n91, nokia n82, nokia
5700, motorola a1200, motorola z3, v3, v3i, v3x, v3xx, handphone]
mobile phone, cell phone, anthentic phone, real phone, copy phone,
apple iphone, nokia n95, motorola, samsung, sony, unlocked phone,
memory cards, bluetooth, charger, battery, headphones n95, n80, e90,
8800, n70, n72, n73, n75, n77, iphone, ipod nano 2, mp3, mp4, iphone,
dvd computer, mobile phone, cell phone, shoes, clothing, nike, jordan,
nokia, sony, ps3, psp, wii, xbox, nokia, nokia n95, nokia mobile,
nokia n95 mobile, wholesale nokia, wholesale nokia n95, wholesale
nokia mobile, nokia whole sale, nokia n95 whole sale, nokia mobile
whole sale, nokia wholesalers, nokia n93 wholesalers, nokia mobile
wholesalers, nokia n91 mobile wholesalers, nokia suppliers, nokia 95
suppliers, nokia n80 mobile suppliers, nokia mobile suppliers, nokia
exporters, motorola nokia mobilemotorola phone, samsung mobile, nokia
nseries, nokia 8800, nokia vertu, nokia n95, n93, n91, n80 n73, n72,
n71, n70, nokia 6300, motorola v3, motorola v3i, samsung d900, apple
macbook, iphone ipod, mp3 mp4, 60g video, dual sim card, lg mobile
phone, laptop, gps, sonyericosson pad, blackberry, nokia8800sirocco
gold, edition apple iphone, nokia n95, sumsung moto, crafts lithium
batteries, nickel hydride batteries, mobile phone batteries, mobile
phone chargers, lithium batteries, nickel hydride batteries, mobile
phone batteries, mobile phone accessories, mobile phone parts, mobile
phones, ipod, ps3, psp, apple, sony, clothes, apparel, jeans, shirts,
t-shirts, wallet, rolex, bape, bbc, lrg, hoody, jacket, nike air
jordans, air jordan 9, xxxxx, capping, handbag, ipod, shoes, silver
jewelry, jewellery, nike shoes, jordan, replicas, mp3, xbox, mobile
phone, ipod nano, lacoste, nokia, mp4, textile accessories, mobile
phones, mp3 player, adidas, footwear, mp3 player, bag, jordan 13,
jordan shoes, nokia 8800, profiles, nike tn, gucci, handbags, sport
shoes, used shoes, phone, air force one, watches, air jordan, jeanst
shirt, sock holders, bluetooth, fashion, xbox 360 premium, sony psp,
mp4 player, jordan 21, sell, airforce 1, air max, puma, air force 1,
sports shoes, nike jordan, air, chanel, jacket, pradareplica, bamboo,
louis vuitton, air force ones, air max plus, pu shoes, belt, nike shox
r4, nike air max, jordan 10, jordan 14, xbox360, jordans, for
footwear, jordan 5, sunglasses, brand, shirt, jordan 21 shoes,
garment, textile, nike jordan 21, digital camera, footwear shoes, nike
shox tl, t shirts, nike shox nz, dunk, leather shoes, samsung d600,
air max 90, rolex, max tn, jordan 4, air max 97, cell phones, jordan
11, nike af1, nike af1, caps, nike shox shoes, playstation 3, nike
jordan shoes, air ones, shox r4, air jordan shoes, jordan 1 21jordan
19, jordan 4.5, ice cream, jordan 6, jordan 18, ipod nano 4gb, nike
air force one, jordan 15, jordan 2, nike air force 1, shox nz, jordan
3, polypropylene, bape, brand new, tapioca, nike;shox, air jordan 7,
shoes, tn r4 nz nike, tn timberland, nike pu, jordan 7, clear jordan,
clear jordan 7, jordan nike, jordan 20, air max 95, nike r6, airmax,
jordan;adidas, jordan nike, mesh belt, nike jordan 6, air force, nike
timberland, air max 2004, new jordan ones, lv handbags, jordan;shox,
tn shoes, jordan;dunk, ecommerce, jordan gt;dubzero, jordan xx, nike
air max 97, air force1, handmade, shox tl, jordan x, fashion shoes,
jordan;air, adidas shoes, shoes nike, nike jordan 13, nikeshoes, shox
r4 tn, nike r5, jordans shoes, jordan, puma, nike air force one, nike
air jordan 21, nike jordan 1.2.3.4.5.6.7.19.20, rocawear, puma shoes,
jordan dub zero, jordan timberland, nike;adidas, jordan i xx, sell
nike shoes, buy nike shoes, nike tn shoes, tn shox, air jordan 13,
jordan;af1, jordan i xx shoes, seven jeans, nike 97, evisu, evisu
jeans, shox r5, nike air force, sell shoes, nike.jodan, nike jordan 1
21, air max shoes, air nike, timberland, prada, nike jordan 10, air
max shox tn, air jordan 3, nike footwear, air max 95 97 2003 2004 2005
tn, nike shoes tn, nike air oz, air jordan dz, nike tl, shox tn, shox
tl r4 nz, tn jordan, new adidas, shoes.air jordan, nike trainer, nike
shox eu, jordan13, air max 95 97 2003 2004 2005, nike air nz, tl3, air
jordan 4, jordan 16, timberland nike, nike air max 95, jordan ix, air
jordan 17, bape hoodies, tshirts, air jordan 20.5, nike shoes air
jordan 10, jordan21, air max 95 97 2003, nike air jordan 11, nike air
max tn, nike air max tn, shox tl, tl2, tl3, tshirt, shoes nike jordan,
air jordan 21, clear af1, clear air force one 1, sean john, machines,
jewelry, nike tn nike shox, bape jeans, redmonkey, football shoes, dub
zero, t.shirts, sunglass, polo t shirt, jordan 5.5, jordan 8, kids
shoes, mens shoes, womens shoes, basketball shoes, running
shoes]soccer shoes, athletic shoes, sports shoes, nike air jordan,
nike air force, nike air max, womens jeans, evisu jeans, red monkey
jeans, womens swimwear, wig, hair pices, jordan 3 clear, clear jordan
3, lacoste shirts, lacoste t-shirt, lacoste, jordan 21, jordanjordan
shoes, nike shoes, adidas shoes, shoes, jordan, nike, puma shoes,
pumas shoes, sport shoes, casual shoes, addidas shoes, prada shoes,
footwear shoes, nike nike, adidas adidas, puma puma, prada prada,
timberland shoes, timberland timberlan, footwear nike jordan, air
force max, air force one shoes, air force one sneakers, air force one
nikes, men's athletic shoes, shoes sports, women's athletic shoes,
mens athletic shoes, mens sport shoes, jordan, air max, air force one,
bape, nike shox, converse, adidas, prada, polo gucci, mulberry, chloe,
fendi, jimmy choo, christain dior, shoes, chanel, coach, lv, louis
vuitton, hermes, replicas sandals mirror image, balenciaga, kooba,
marc jacobs, replicas bags, knock off hermes, chanel, gucci, prada,
mulberry, fendi, chloe, coach, louis vuitton, bag, bags, handbag,
handbags, dior, wallet, purse, balenciage, leather wallets, womens
wallets hermes, chanel, gucci, prada, mulberry, fendi, chloe, coach,
louis vuitton, bag, bags, handbag, handbags, replica bag, wholesale
bag, wholesales bag, wholesale gucci bag, wholesale chanel bag,
wholesale hermes bag, purse, wallet soccer shoes, athletic shoes,
sports shoes, nike air jordan, nike air force, nike air max, womens
jeans, evisu jeans, red monkey jeans, womens swimwear, wig, hair
pices, clip-in hair, jordan 3 clear, clear jordan 3, lacoste shirts,
lacoste t-shirt, lacoste, jordan 21, jordan xxi jordan shoes, nike
shoes, adidas shoes, shoes, jordan, nike, puma shoes, pumas shoes,
sport shoes, casual shoes, addidas shoes, prada shoes, footwear shoes,
nike nike, adidas adidas, puma puma, prada prada, timberland shoes,
timberland timberlan, footwear nike jordan, air force max, air force
one shoes, air force one sneakers, air force one nikes, men's athletic
shoes, shoes sports, women's athletic shoes, mens athletic shoes, mens
sport shoes, jordan, air max, air force one, bape, nike shox,
converse, adidas, prada, polo gucci, mulberry, chloe, fendi, jimmy
choo, christain dior, shoes, chanel, coach, lv, louis vuitton, hermes,
replicas sandals mirror image, balenciaga, kooba, marc jacobs,
replicas bags, knock off hermes, chanel, gucci, prada, mulberry,
fendi, chloe, coach, louis vuitton, bag, bags, handbag, handbags,
dior, wallet, purse, balenciage, leather wallets, womens wallets
hermes, chanel, gucci, prada, mulberry, fendi, chloe, coach, louis
vuitton, bag, bags, handbag, handbags, replica bag, wholesale bag,
wholesales bag, wholesale gucci bag, wholesale chanel bag, wholesale
hermes bag, purse, wallet red monkey jeans, evisu jeans, bape&bbc
jeans, antic jeans, rocawear jeans, sean john jeans, abercrombie fitch
jeans, true religion jeans, seven jeans, akademiks jeans, levis jeans,
diesel jeans, d gjeans, men sunglasses, sport sunglasses, designer
sunglasses, fashion sunglasses, men black sunglasses, cool sunglasses,
dolce gabbana sunglasses, dg sunglasses, chanel handbag, tiffany
jewelry, gucci sun glasses, new rolex watch, sterling silver necklace,
fendi handbag, tiffany bracelet, wholesale gucci, womens watch, silver
necklace pendant, necklace pendant, fashion jewelry necklace, luggage
silver tag, jewelry silver tag, jewelry necklace, bracelets jewelry,
fashion jewelry, silver earrings, silver jewellery hats, caps, new
era. fashion accessory, fashion belts, fashion belt buckles, womens
fashion belt, wholesale fashion belt, lady fashion belt, beaded
fashion belt, woman fashion belt, wholesale fashion accessories
tiffany, ring, necklace, bracelet, earring, sterling sliver, jewelry,
jewellery, fashion jewelry, wholesales tiffany, wholesale tiffany,
wholesale tiffany jewelry, wholesale tiffany jewellery, bvlgari
jerseys, nba jersey, nfl jersey, soccer jersey, sports wear reebok
jersey, champion jersey, jersey, jerseys, nba shoes women, bape,
pendel, shox r5 energia women, air jordan 12 men, air force 1 women,
air jordan 9 men, dunk mid men, skirt, air jordan 15 men, levi's, air
jordan 13 kids, la, citizen, air max 2003 men, frankie b, loewe,
tod's, air jordan 19 men, akademiks, women, rado, shox rival men, long
women, shox tl3 men, shox r5 energia women, city men, dunk women, g
star, long sleeve men, air jordan 10 men, escada sports, mqueen, air
jordan 6 women, shox r4 women, air jordan 18 men, skirt, long sleeve
men, ice cream, shox tl3 men, air jordan 11 women, wallets, with bra
cup women, converse, solid color men, chloe, chloe, jacket, 2gb, air
jordan 6 women, air jordan 6.5 men, air jordan 7 women, loewe, solid
color men, air max 97 women, superstar 35th women, sweater, jimmy
choo, air max tn5 men, necklace women, air jordan 17 men, air jordan
11 women, bape, chloe, shox tl2 men, 1gb, new era, ipod, sixty, bikkem
bergs, energie, underwear(bikili), rift men, air max 90 men, 2gb,
necklace women, jeans, long sleeve men, new era, turdo, hoody,
christian dior, shox r4 men, jacobs, air jordan 5.5 men, air jordan
3.5 men, nba men, air max tn6 men, ray ban, pants, y-3 men, prada,
short sleeve men, dolce&gabbana, jack jones, g star, big polo women,
air jordan 21.5 men, gino green global, tiffany, air max 95 men, long
women, shox tl3 men, vogue, paul smith, kooda, gino green global,
louis vuitton, others men, ugg, hats(caps), short women, adicolor
women, air jordan 8 men, mp3/mp4, mac jacobs, ice cream, air jordan 11
women, shox nz women, ralph lauren(polo), underwear(bikili), air max
2003 men, air jordan 11 kids, gino green global, air jordan 11 men,
air jordan 17 men, shox r5 energia women, frankie b, shox r5 energia
women, dunhill, coach, jacobs, hoody, short men, billionaire boys
club, tod's, air jordan 7.5 men, armani, sandal, hermes, adicolor
women, citizen, shox tl men, ray ban, 4gb, air jordan 1 men, dunk
women, diesel, spyder, apple ipod, ipod mini, apple ipod nano, ipod
nanos, apple ipod shuffle, apple iphone, nokia n95, nokia n93,
nintendo wii, buy wii, wii console, digital camera, mobile phones,
home security systems, vacuum cleaners, dvd players, wii accessories,
wii controllers, nintendo wii controller, xbox controller, ps2


 high heels, dansko clogs, novelty slippers, womens slippers, bridal
flip flops, travel slippers, birkenstock clogs, nursing clogs, garden
clogs, mens clogs


From duncan.booth at invalid.invalid  Sat May 15 08:52:03 2010
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 15 May 2010 12:52:03 GMT
Subject: Picking a license
References: 
Message-ID: 

Ed Keith  wrote:

> I can not imagine anyone being stupid enough to pay me for rights to
> use code I had already published under the Boost License, which grants
> then the rights to do anything they want with it without paying me
> anything. 
>   -EdK
> 
Really?

The Boost License says, amongst other things:

> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
> NON-INFRINGEMENT. 

Are you sure you can't imagine anyone offering to pay you for an 
alternative license that came with some kind of warranty or support?



From utente at esempio.net  Sat May 15 08:55:20 2010
From: utente at esempio.net (superpollo)
Date: Sat, 15 May 2010 14:55:20 +0200
Subject: Human word reader
In-Reply-To: <4bee94f8$0$18652$4fafbaef@reader3.news.tin.it>
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	<4bee94f8$0$18652$4fafbaef@reader3.news.tin.it>
Message-ID: <4bee99c3$0$18661$4fafbaef@reader3.news.tin.it>

superpollo ha scritto:
> timo verbeek ha scritto:
>> I'm planning to create a human word program
>> A human inputs a string
>> "Give me the weather for London please."
>> Then I will strip the string.
>> "weather for london"
>> Then I get the useful information.
>> what:"weather" where:"london"
>> After that I use the info.
>>
>> I need help with getting the useful information how do I get the place
>> if I don't now how long the string is?
> 
> 
>  >>> query = "Give me the weather for London please."
>  >>> what = query.strip("Give me the ").split()[0]
>  >>> where = query.strip("Give me the " + what + " for ").split()[0]
>  >>> print what, where
> weather London
>  >>>

maybe better not with strip, fot it might not do what i intended (see 
docs); maybe preferable to use "partition" method:

 >>> query = "Give me the weather for London please."
 >>> what  = query.partition("Give me the ")[2].split()[0]
 >>> where = query.partition(" for ")[2].split()[0]
 >>> print what, where
weather London
 >>>


From e_d_k at yahoo.com  Sat May 15 09:30:56 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sat, 15 May 2010 06:30:56 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <872403.90739.qm@web58705.mail.re1.yahoo.com>

--- On Sat, 5/15/10, Duncan Booth  wrote:

> From: Duncan Booth 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Saturday, May 15, 2010, 8:52 AM
> Ed Keith 
> wrote:
> 
> > I can not imagine anyone being stupid enough to pay me
> for rights to
> > use code I had already published under the Boost
> License, which grants
> > then the rights to do anything they want with it
> without paying me
> > anything. 
> >???-EdK
> > 
> Really?
> 
> The Boost License says, amongst other things:
> 
> > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
> ANY KIND,
> > EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
> WARRANTIES OF
> > MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
> TITLE AND
> > NON-INFRINGEMENT. 
> 
> Are you sure you can't imagine anyone offering to pay you
> for an 
> alternative license that came with some kind of warranty or
> support?
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Would that be a license or a support contract?

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From nobody at nowhere.com  Sat May 15 10:05:30 2010
From: nobody at nowhere.com (Nobody)
Date: Sat, 15 May 2010 15:05:30 +0100
Subject: write a 20GB file
References: 
	<4BED2E45.6060301@ieee.org>
	
	
	
	
Message-ID: 

On Fri, 14 May 2010 18:38:55 -0400, J wrote:

>>> someone smarter than me can correct me, but file.write() will write when
>>> it's buffer is filled, or close() or flush() are called.
>>
>> And, in all probability, seek() will either flush it immediately or cause
>> the next write() to flush it before writing anything.
> 
> Ahhh... I didn't know that... I thought seek() just moved the pointer
> through the file a little further....

Think about how this affects buffering. write() writes at the current file
position. If you write, then seek, then write, it can't just concatenate
the two sets of data, as that would "lose" the seek.

Either the buffer has to contain multiple, distinct sets of data, each
with an associated position, or (far more likely), the original data must
be written to the correct location before the second set of data can be
stored.



From gehan.ameresekere at gmail.com  Sat May 15 10:05:37 2010
From: gehan.ameresekere at gmail.com (train)
Date: Sat, 15 May 2010 07:05:37 -0700 (PDT)
Subject: Pyinstaller on WINE - cannot install pywin32
Message-ID: <250f5073-8494-4c3c-a4bc-cd53f7e4e66d@e34g2000pra.googlegroups.com>

Pyinstaller works fine on Windows XP. I am trying to get it working on
WINE. Running
configure.py results in asking for pywin32, however pywin 32 will not
install

C:\pywin32-214>c:\python26\python setup.py
Building pywin32 2.6.214.0
This is a distutils setup-script for the pywin32 extensions

To build the pywin32 extensions, simply execute:
  python setup.py -q build
or
  python setup.py -q install
to build and install into your current Python installation.

These extensions require a number of libraries to build, some of which
may
require you to install special SDKs or toolkits.  This script will
attempt
to build as many as it can, and at the end of the build will report
any
extension modules that could not be built and why.
Currently, the Vista SDK and DirectX SDK are required to successfully
build
all extension modules - note that using the Vista SDK doesn't force
you to
use Vista as your build environment.  Please use google to find the
SDK -
links to microsoft.com seem to only stay current for a short time.
Also note
that the SDK that comes with VS2008 is not good enough to compile
earlier
versions.  If you installed VS2008 after the Vista SDK, try doing a
'repair'
on your SDK install.

Early versions of certain Windows headers/SDK versions will also cause
certain modules to be skipped. If you don't use the extensions that
fail to
build, you can ignore these warnings; if you do use them, you must
install
the correct libraries.

The 'exchange' extensions require headers that are no longer in any
current
SDKs, so these fail to build, but the 'mapi' extension should still
build.

Building:
---------

To install the pywin32 extensions, execute:
  python setup.py -q install

This will install the built extensions into your site-packages
directory,
create an appropriate .pth file, and should leave everything ready to
use.
There is no need to modify the registry.

To build or install debug (_d) versions of these extensions, ensure
you have
built or installed a debug version of Python itself, then pass the "--
debug"
flag to the build command - eg:
  python setup.py -q build --debug
or to build and install a debug version:
  python setup.py -q build --debug install

To build 64bit versions of this:

* py2.5 and earlier - sorry, I've given up in disgust.  Using VS2003
with
  the Vista SDK is just too painful to make work, and VS2005 is not
used for
  any released versions of Python. See revision 1.69 of this file for
the
  last version that attempted to support and document this process.

*  2.6 and later: On a 64bit OS, just build as you would on a 32bit
platform.
   On a 32bit platform (ie, to cross-compile), you must use VS2008 to
   cross-compile Python itself. Note that by default, the 64bit tools
are not
   installed with VS2008, so you may need to adjust your VS2008 setup.
Then
   use:

      setup.py build --plat-name=win-amd64

   see the distutils cross-compilation documentation for more details.

Standard usage information follows:
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

error: no commands supplied
C:\pywin32-214>c:\python26\python setup.py -q install
Building pywin32 2.6.214.0
error: Unable to find vcvarsall.bat
C:\pywin32-214>



From awilliam at whitemice.org  Sat May 15 10:12:40 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sat, 15 May 2010 10:12:40 -0400
Subject: Puzzled by code pages
In-Reply-To: <4bee7823$1@dnews.tpgi.com.au>
References: 
	<4bee7823$1@dnews.tpgi.com.au>
Message-ID: <1273932760.3929.18.camel@linux-yu4c.site>

On Sat, 2010-05-15 at 20:30 +1000, Lie Ryan wrote:
> On 05/15/10 10:27, Adam Tauno Williams wrote:
> > I'm trying to process OpenStep plist files in Python.  I have a parser
> > which works, but only for strict ASCII.  However plist files may contain
> > accented characters - equivalent to ISO-8859-2 (I believe).  For example
> > I read in the line:
> >>>> handle = open('file.txt', 'rb')
> >>>> data = handle.read()
> >>>> handle.close()
> >>>> data
> > '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
> > NSFileName;\n'
> I presume you're using Python 2.x.

Yes.  But the days of all-unicode-strings will be wonderful when it
comes. :)

> > What is the correct way to re-encode this data into UTF-8 so I can use
> > unicode strings, and then write the output back to ISO8859-?
> > I can read the file using codecs as ISO8859-2, but it still doesn't seem
> > correct.
> >>>> handle = codecs.open('file.txt', 'rb', encoding='iso8859-2')
> >>>> data = handle.read()
> >>>> handle.close()
> >>>> data
> > u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
> > NSFileName;\n'
> When printing in the interactive interpreter, python uses __repr__
> representation by default. If you want to use __str__ representation use
> "print data" (note, your terminal must support printing unicode
> characters); 

Using GNOME Terminal, so Unicode characters should display correctly.
And I do see the characters when I 'cat' the file.

> either way, even though the string looks like '\u0102' when
> printed on the terminal, the binary pattern inside the memory should
> correctly represents the accented character.

Yep.  But in the interpreter both unicode() and repr() produce the same
output.  Nothing displays the accented character.

h = codecs.open('file.txt', 'rb', encoding='iso8859-2')
data = h.read()
h.close()
str(data)

'ascii' codec can't encode characters in position 33-34: ordinal not in
range(128)

unicode(data)
u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
NSFileName;\n'

repr(data)
'u\'    "skyp4_filelist_10201/localit\\u0102\\xa0 termali_sortfield" =
NSFileName;\\n\''

I think I'm getting close.  Parsing the file seems to work, and while
writing it out does not error, rereading my own output fails. :(
Possibly I'm 'accidentally' writing the output as UTF-8 and not
ISO8859-2.  I need the internal data to be UTF-8 but read as ISO8859-2
and rewritten back to ISO8859-2 [at least that is what I believe from
the OpenStep files I'm seeing].

What is the 'official' way to encode something from UTF-8 to another
code page.  I *assumed* that if I wrote a unicode stream back through:

h = codecs.open(output_filename, 'wb', encoding='iso8859-2')
data = writer.store(defaults)
h.write(data)
h.close()

that is would be re-encoded [word?].  But maybe not?



> f = codecs.open("in.txt", 'rb', encoding="iso8859-2")
> f2 = codecs.open("out.txt", 'wb', encoding="utf-8")
> s = f.read()
> f2.write(s)
> f.close()
> f2.close()

-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba
-------------- next part --------------
    "skyp4_filelist_10201/localit? termali_sortfield" = NSFileName;

From mannu_0523 at rediffmail.com  Sat May 15 10:20:34 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 15 May 2010 14:20:34 -0000
Subject: =?utf-8?B?UmU6IFJlOiBqb2luaW5nIHR3byBjb2x1bW4=?=
In-Reply-To: <4BED9A9F.5040708@tim.thechases.com>
Message-ID: <1273862645.S.6081.40691.H.TlRpbSBDaGFzZQBSZTogam9pbmluZyB0d28gY29sdW1u.f4-234-202.old.1273933234.29073@webmail.rediffmail.com>



On Sat, 15 May 2010 00:14:05 +0530  wrote
>On 05/14/2010 12:55 PM, James Mills wrote:

>> file1:

>> a1 a2

>> a3 a4

>> a5 a6

>> a7 a8

>>

>> file2:

>> b1 b2

>> b3 b4

>> b5 b6

>> b7 b8

>>

>> and I want to join them so the output should look like this:

>>

>> a1 a2 b1 b2

>> a3 a4 b3 b4

>> a5 a6 b5 b6

>> a7 a8 b7 b8

>

> This is completely untested, but this "should" (tm) work:

>

> from itertools import chain

>

> input1 = open("input1.txt", "r").readlines()

> input2 = open("input2.txt", "r").readlines()

> open("output.txt", "w").write("".join(chain(input1, input2)))



I think you meant izip() instead of chain() ... the OP wanted to 

be able to join the two lines together, so I suspect it would 

look something like



  # OPTIONAL_DELIMITER = " "

  f1 = file("input1.txt")

  f2 = file("input2.txt")

  out = open("output.txt", 'w')

  for left, right in itertools.izip(f1, f2):

   out.write(left.rstrip('\r\n'))

   # out.write(OPTIONAL_DELIMITER)

   out.write(right)

  out.close()



This only works if the two files are the same length, or (if 

they're of differing lengths) you want the shorter version. The 

itertools lib also includes an izip_longest() function with 

optional fill, as of Python2.6 which you could use instead if you 

need all the lines



-tkc









-- 

with this 
from itertools import chain
# OPTIONAL_DELIMITER = " "
f1 = file("input1.txt")
f2 = file("input2.txt")
out = open("output.txt", 'w')
for left, right in itertools.izip(f1, f2):
  out.write(left.rstrip('\r\n'))
    # out.write(OPTIONAL_DELIMITER)
  out.write(right)
out.close()

it is showing error:
ph08001 at linux-af0n:~> python join.py
Traceback (most recent call last):
  File "join.py", line 6, in 
    for left, right in itertools.izip(f1, f2):
NameError: name 'itertools' is not defined
ph08001 at linux-af0n:~>



-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nathan.alexander.rice at gmail.com  Sat May 15 10:37:59 2010
From: nathan.alexander.rice at gmail.com (Nathan Rice)
Date: Sat, 15 May 2010 10:37:59 -0400
Subject: write a 20GB file
In-Reply-To: 
References: 
	<4BED2E45.6060301@ieee.org>
	
	
	
	
	
Message-ID: 

This is precisely the situation mmap was made for :)  It has almost the same
methods as a file so it should be an easy replacement.

On Sat, May 15, 2010 at 10:05 AM, Nobody  wrote:

> On Fri, 14 May 2010 18:38:55 -0400, J wrote:
>
> >>> someone smarter than me can correct me, but file.write() will write
> when
> >>> it's buffer is filled, or close() or flush() are called.
> >>
> >> And, in all probability, seek() will either flush it immediately or
> cause
> >> the next write() to flush it before writing anything.
> >
> > Ahhh... I didn't know that... I thought seek() just moved the pointer
> > through the file a little further....
>
> Think about how this affects buffering. write() writes at the current file
> position. If you write, then seek, then write, it can't just concatenate
> the two sets of data, as that would "lose" the seek.
>
> Either the buffer has to contain multiple, distinct sets of data, each
> with an associated position, or (far more likely), the original data must
> be written to the correct location before the second set of data can be
> stored.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From python.list at tim.thechases.com  Sat May 15 10:40:15 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Sat, 15 May 2010 09:40:15 -0500
Subject: joining two column
In-Reply-To: <1273862645.S.6081.40691.H.TlRpbSBDaGFzZQBSZTogam9pbmluZyB0d28gY29sdW1u.f4-234-202.old.1273933234.29073@webmail.rediffmail.com>
References: <1273862645.S.6081.40691.H.TlRpbSBDaGFzZQBSZTogam9pbmluZyB0d28gY29sdW1u.f4-234-202.old.1273933234.29073@webmail.rediffmail.com>
Message-ID: <4BEEB24F.5010605@tim.thechases.com>

On 05/15/2010 09:20 AM, mannu jha wrote:

BTW: your mailer makes an absolute mess of plain-text emails, 
putting multiple spaces



between


every


single


line


which


makes


it


very


hard


to


read.

Please fix it, use a real mailer, or risk getting ignored (or 
worse, plonked).  Fortunately, Vim makes it modestly easy to 
unmung the rubbishy format.

 >>    # OPTIONAL_DELIMITER = " "
 >>    f1 = file("input1.txt")
 >>    f2 = file("input2.txt")
 >>    out = open("output.txt", 'w')
 >>    for left, right in itertools.izip(f1, f2):
 >>     out.write(left.rstrip('\r\n'))
 >>     # out.write(OPTIONAL_DELIMITER)
 >>     out.write(right)
 >>    out.close()
 >> This only works if the two files are the same length, or (if
 >> they're of differing lengths) you want the shorter version. The
 >> itertools lib also includes an izip_longest() function with
 >> optional fill, as of Python2.6 which you could use instead if you
 >> need all the lines
 >
 > with this
 >
 > from itertools import chain
 > # OPTIONAL_DELIMITER = " "
 > f1 = file("input1.txt")
 > f2 = file("input2.txt")
 > out = open("output.txt", 'w')
 > for left, right in itertools.izip(f1, f2):
 >   out.write(left.rstrip('\r\n'))
 >     # out.write(OPTIONAL_DELIMITER)
 >   out.write(right)
 > out.close()
 > it is showing error:
 > ph08001 at linux-af0n:~> python join.py
 > Traceback (most recent call last):
 >   File "join.py", line 6, in
 >     for left, right in itertools.izip(f1, f2):
 > NameError: name 'itertools' is not defined

That's because you're not importing itertools, but you're just 
importing "chain" from within it.  So of course when you try to 
use "itertools.izip", itertools doesn't exist.  You can either use

   import itertools
   #...
   for left, right in itertools.izip(f1,f2):

or

   from itertools import izip
   #...
   for left, right in izip(f1,f2):

-tkc






From switch2mathan at gmail.com  Sat May 15 10:50:22 2010
From: switch2mathan at gmail.com (MathanK)
Date: Sat, 15 May 2010 02:50:22 -1200
Subject: Is there conversion method to convert pyunicodeobject to pybyteobject?
Message-ID: <1289c71c8d7.-2177546074900212455.7511215933185914503@gmail.com>

Hi All,

A variable whose data type is PyUnicodeObject is to be assigned to varioable of PyBytesObject type 

example :

PyUnicodeObject *p = ...whatever...; 
function( (PyByteObject*p)); 

compiled and got a Bus Error.

Cheers,
Mathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From robin.garen at gmail.com  Sat May 15 10:56:31 2010
From: robin.garen at gmail.com (technocake)
Date: Sat, 15 May 2010 07:56:31 -0700 (PDT)
Subject: platform-independent image copy/paste with Tkinter?
Message-ID: 

Hi.

Is there a good way to copy from or paste to the clipboard on all
systems running python using Tkinter?
started a small road too it here:

#!/usr/bin/python
__author__="technocake"
__date__ ="$15.mai.2010 15:53:39$"

from Tkinter import *

if __name__ == "__main__":

    def displayClipboard(event):
        try:
            data = event.widget.clipboard_get(type="STRING")
        except :
            #Need a method for displaying a image here..
            data = "Image" #
        finally: #Updates the textlabel
            lbl.config(text=data)

    root = Tk()
    lbl= Label(root, width=20)
    lbl.bind("", displayClipboard) #binding to leftclick
    lbl.pack()

    root.mainloop()



From aahz at pythoncraft.com  Sat May 15 11:24:58 2010
From: aahz at pythoncraft.com (Aahz)
Date: 15 May 2010 08:24:58 -0700
Subject: Picking a license
References: 
	 <87k4rgfutu.fsf@benfinney.id.au>
	
Message-ID: 

In article ,
Stefan Behnel   wrote:
>aahz at pythoncraft.com (Aahz) writes:
>>
>> Which license you use depends partly on your political philosophy.
>
>Did they close down debian-legal, or why is this thread growing so long?

Mea culpa, mea culpa, mea maxima culpa  ;-)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From aahz at pythoncraft.com  Sat May 15 11:28:37 2010
From: aahz at pythoncraft.com (Aahz)
Date: 15 May 2010 08:28:37 -0700
Subject: Picking a license
References: 
	<4bee0df4$0$8761$c3e8da3@news.astraweb.com>
	<7bfa5457-027d-4ee1-a54f-3c0baba45a55@e21g2000vbl.googlegroups.com>
Message-ID: 

In article <7bfa5457-027d-4ee1-a54f-3c0baba45a55 at e21g2000vbl.googlegroups.com>,
Patrick Maupin   wrote:
>
>So, there are good reasons for both kinds of licenses, which I think
>everybody on the pro-permissive side has been saying all along.  Of
>course, "force" is a more inflammatory word that "obligation" in some
>contexts, and that has been used in what I would admit on my part is a
>knee-jerk reaction to my belief that "free" and "freedom" are more
>inflammatory words than "rights" in the same contexts.

Yes, exactly.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From utente at esempio.net  Sat May 15 12:08:40 2010
From: utente at esempio.net (superpollo)
Date: Sat, 15 May 2010 18:08:40 +0200
Subject: parsing XML
In-Reply-To: 
References: 
Message-ID: <4beec709$0$18653$4fafbaef@reader3.news.tin.it>

kaklis at gmail.com ha scritto:
> Hi to all, let's say we have the following Xml
> 
>   
>     17.1
>     6.4
>   
>   
>     15.5
>     7.8
>   
> 
> 
> How can i get the players name, age and height?
> DOM or SAX and how
> 
> Thanks
> Antonis

another minimal xml.etree.ElementTree solution:

 >>> print document

   
     17.1
     6.4
   
   
     15.5
     7.8
   

 >>> import xml.etree.ElementTree as ET
 >>> team = ET.XML(document)
 >>> for player in team:
...     print player.attrib["name"]
...     print player.attrib["age"]
...     print player.attrib["height"]
...     print
...
Mick Fowler
27
1.96m

Ivan Ivanovic
29
2.04m

 >>>

bye


From lie.1296 at gmail.com  Sat May 15 12:20:58 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 16 May 2010 02:20:58 +1000
Subject: Puzzled by code pages
In-Reply-To: 
References: 	<4bee7823$1@dnews.tpgi.com.au>
	
Message-ID: <4beeca46$1@dnews.tpgi.com.au>

On 05/16/10 00:12, Adam Tauno Williams wrote:
> On Sat, 2010-05-15 at 20:30 +1000, Lie Ryan wrote:
>> On 05/15/10 10:27, Adam Tauno Williams wrote:
>>> I'm trying to process OpenStep plist files in Python.  I have a parser
>>> which works, but only for strict ASCII.  However plist files may contain
>>> accented characters - equivalent to ISO-8859-2 (I believe).  For example
>>> I read in the line:
>>>>>> handle = open('file.txt', 'rb')
>>>>>> data = handle.read()
>>>>>> handle.close()
>>>>>> data
>>> '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
>>> NSFileName;\n'
>> I presume you're using Python 2.x.
> 
> Yes.  But the days of all-unicode-strings will be wonderful when it
> comes. :)
> 
>>> What is the correct way to re-encode this data into UTF-8 so I can use
>>> unicode strings, and then write the output back to ISO8859-?
>>> I can read the file using codecs as ISO8859-2, but it still doesn't seem
>>> correct.
>>>>>> handle = codecs.open('file.txt', 'rb', encoding='iso8859-2')
>>>>>> data = handle.read()
>>>>>> handle.close()
>>>>>> data
>>> u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
>>> NSFileName;\n'
>> When printing in the interactive interpreter, python uses __repr__
>> representation by default. If you want to use __str__ representation use
>> "print data" (note, your terminal must support printing unicode
>> characters); 
> 
> Using GNOME Terminal, so Unicode characters should display correctly.
> And I do see the characters when I 'cat' the file.

'cat' works because 'cat' works in bytes and doesn't try to interpret
the stream it is writing. You can tell python to output string instead
of unicode to get the same effect.

> h = codecs.open('file.txt', 'rb', encoding='iso8859-2')
> data = h.read()
> h.close()
> str(data)
> 
> 'ascii' codec can't encode characters in position 33-34: ordinal not in
> range(128)

this means either your terminal can't print unicode or python for some
reason thinks that the terminal is ascii terminal. You can encode the
string manually, e.g.:

print u'\u0102\xa0'.encode('utf-8')

or you should figure out a way to set your terminal properly so python
recognizes it as utf-8 terminal, see
http://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/

when python tries to print unicode object, python first needs to encode
that 'unicode' object into 'str'; by default python uses
sys.stdout.encoding to determine the encoding to use when printing
unicode object.

> unicode(data)
> u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
> NSFileName;\n'

If data is a 'unicode', this is not surprising, as 'unicode(data)'
simply returns 'data'.

> I think I'm getting close.  Parsing the file seems to work, and while
> writing it out does not error, rereading my own output fails. :(
> Possibly I'm 'accidentally' writing the output as UTF-8 and not
> ISO8859-2.  I need the internal data to be UTF-8 but read as ISO8859-2
> and rewritten back to ISO8859-2 [at least that is what I believe from
> the OpenStep files I'm seeing].

unicode string doesn't have encoding (well, python needs some encoding
to store the unicode data in RAM, but that's implementation detail).
unicode string is not a stream of bytes encoded in specific way, it's an
encoding-agnostic block of text.

> What is the 'official' way to encode something from UTF-8 to another
> code page.  I *assumed* that if I wrote a unicode stream back through:
> 
> h = codecs.open(output_filename, 'wb', encoding='iso8859-2')
> data = writer.store(defaults)
> h.write(data)
> h.close()

what's "writer.store(defaults)"? It should return a 'unicode' if you
want h.write() to work properly. Otherwise, if data is 'str', h.write
will try to decode the 'str' to 'unicode' using the default decoder
(usually ascii), then encode that 'unicode' to 'iso8859-2'.


From utente at esempio.net  Sat May 15 12:25:05 2010
From: utente at esempio.net (superpollo)
Date: Sat, 15 May 2010 18:25:05 +0200
Subject: parsing XML
In-Reply-To: <4beec709$0$18653$4fafbaef@reader3.news.tin.it>
References: 
	<4beec709$0$18653$4fafbaef@reader3.news.tin.it>
Message-ID: <4beecaf1$0$18657$4fafbaef@reader3.news.tin.it>

superpollo ha scritto:
> kaklis at gmail.com ha scritto:
>> Hi to all, let's say we have the following Xml
>> 
>>   
>>     17.1
>>     6.4
>>   
>>   
>>     15.5
>>     7.8
>>   
>> 
>>
>> How can i get the players name, age and height?
>> DOM or SAX and how
>>
>> Thanks
>> Antonis
> 
> another minimal xml.etree.ElementTree solution:
> 
>  >>> print document
> 
>   
>     17.1
>     6.4
>   
>   
>     15.5
>     7.8
>   
> 
>  >>> import xml.etree.ElementTree as ET
>  >>> team = ET.XML(document)
>  >>> for player in team:
> ...     print player.attrib["name"]
> ...     print player.attrib["age"]
> ...     print player.attrib["height"]
> ...     print
> ...
> Mick Fowler
> 27
> 1.96m
> 
> Ivan Ivanovic
> 29
> 2.04m
> 
>  >>>
> 
> bye

or, an alternative xml.dom.minidom solution:

 >>> import xml.dom.minidom as MD
 >>> team = MD.parseString(document)
 >>> players = team.getElementsByTagName("player")
 >>> for player in players:
...     print player.getAttribute("name")
...     print player.getAttribute("age")
...     print player.getAttribute("height")
...     print
...
Mick Fowler
27
1.96m

Ivan Ivanovic
29
2.04m

 >>>

bye



From travis+ml-python at subspacefield.org  Sat May 15 12:42:16 2010
From: travis+ml-python at subspacefield.org (travis+ml-python at subspacefield.org)
Date: Sat, 15 May 2010 09:42:16 -0700
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 
	
Message-ID: <20100515164216.GA9146@subspacefield.org>

On Mon, May 10, 2010 at 08:45:51PM +0100, Nobody wrote:
> On Tue, 11 May 2010 00:24:22 +1200, Samuel Williams wrote:
> > Is Python a functional programming language?
> Not in any meaningful sense of the term.

LOL

> > I heard that lambdas were limited to a single expression,
> 
> Yes. In a functional language that wouldn't be a problem, as there's no
> limit to the complexity of an expression. Python's expressions are far
> more limited, which restricts what can be done with a lambda.

One very annoying thing in Python is the distinction between
statements and expressions.

Ever since learning LISP (well, Scheme) in S&ICP I find myself
frequently annoyed by this pointless distinction, started by
C (or earlier), and propogated without much thought.

Often I'll want to write a lamda that, say, prints something, or
modifies a global variable, and find that, well, it's either
impossible or beyond my interest in figuring it out.

It appears there is finally a ternary operator (for making if/else
into "expressions"):
http://en.wikipedia.org/wiki/Ternary_operation#Python
Maybe it will grow on me - it makes sense in English, but on
first glance I thought the programmer suffered from dyslexia.

To be fair, it appears that Python's whitespace-sensitive syntax sort
of precludes the "make a complex function on one line" that is typical
of languages which don't have statement/expression distinctions, but
I'm not convinced it couldn't be solved, perhaps by allowing anonymous
functions to span multiple lines, just like named functions.

> > Finally, even if Python supports functional features, is this a model that
> > is used often in client/application code?
> 
> Not really. List comprehensions are probably the most common example of
> functional idioms, but again they're limited by Python's rather limited
> concept of an expression.

Map/reduce, lambda, apply, that kind of stuff... kinda similar to
functional languages.

But "statements lack any side effects"?  No way.

In fact, a common distinction you'll see observed, but not always, is
that "statements may have side effects, expressions do not".

For some definitions of "functional language", there are no
side-effects, so there is no need for a statement which doesn't
evaluate to a value, so there is no need for a statement/expression
distinction, so everything is an expression.

You may have seen Paul Graham's other article about Python and LISP:
http://www.paulgraham.com/icad.html

Upon re-skimming it, I find myself wondering if I got the
expression/statement annoyance from his pages, or from my own
experience.  I can't remember :-) Probably it was an annoyance that I
hadn't put my finger on until he spelled it out for me, like a
splinter in my mind :-)

He obliquely references my other pet peeve, the global/class/local
distinction, completely ignoring arbitrarily-nested lexical scoping.
From what I've read in this thread, there's a recent "nonlocal"
declaration that sounds like it might accomplish something useful in
this regard.

(I still haven't figured out how he managed to use lexical closures in
 his web server to allow one web page to use another to allow the user
 to select and return a value, like a color from a color wheel, unless
 he implemented his own web server in LISP, since HTTP is stateless).

I really like Scheme's clean syntax (never learned Common LISP, sorry,
too much to remember) but frankly, I've never looked at a problem and
said, "you know, Scheme would be perfect for this".  Maybe if I was
writing a program that did optimizing transformations on abstract
syntax trees, or something.  And since Scheme has never come in handy,
I never bothered with Common LISP.  I feel similarly about ML, OCAML
and Haskell... maybe one day when I'm bored, not today, not this
project.

So in the end, I find myself using python more than anything else,
fully acknowledging its warts.  I used to admire its simplicity, but
now with decorators, iterators, generators, metaclasses, and the
proliferation of special method names, I have to wonder if that still
holds true...  certainly I understand 90+% of python programs, but
do I understand that proportion of the constructs?

PS: Why do people call LISP object-oriented?  Are they smoking crack?
    No classes, no methods, no member variables... WTF?
-- 
A Weapon of Mass Construction
My emails do not have attachments; it's a digital signature that your mail
program doesn't understand. | http://www.subspacefield.org/~travis/ 
If you are a spammer, please email john at subspacefield.org to get blacklisted.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: 

From robert.kern at gmail.com  Sat May 15 13:10:03 2010
From: robert.kern at gmail.com (Robert Kern)
Date: Sat, 15 May 2010 12:10:03 -0500
Subject: Picking a license
In-Reply-To: <4bee08f9$0$8761$c3e8da3@news.astraweb.com>
References: 
	<4bee08f9$0$8761$c3e8da3@news.astraweb.com>
Message-ID: 

On 2010-05-14 21:37 , Steven D'Aprano wrote:
> On Fri, 14 May 2010 06:42:31 -0700, Ed Keith wrote:
>
>> I am not a lawyer, but as I understand the LGPL, If I give someone
>> something that used any LGPLed code I must give them the ability to
>> relink it with any future releases of the LGPLed code. I think that
>> means that I need to give them a linker and teach them how to use it,
>> and I do not want to go there.
>
> Surely you're joking?
>
> Does this mean that if they lose their hands in an accident, you have to
> come sit at their computer and do their typing?
>
> The LGPL and GPL don't grant people "the ability" to do anything, since
> that's not within our power to grant. Some people don't want to, or
> can't, program, or don't have time. It's not like the LGPL is the bite of
> a radioactive spider that can grant superpowers. It is a licence which
> grants *permissions*.

No, the LGPL requires you to do something extra to enable your users to be able 
to relink your program. You need to provide the ability to do this, up to some 
unspecified and untested limit of reasonableness (your example is obviously 
beyond the limit of reasonableness). You can't just give them, say, a statically 
linked program and nothing else. You can't require for-fee, proprietary linkers. 
This is usually not hard to do (just give them unlinked .o or .obj files and a 
Makefile or project file), but it is *not* just a matter of granting permissions.

But you're right, you don't have to teach them how to do it.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From shepard.dl at gmail.com  Sat May 15 13:18:04 2010
From: shepard.dl at gmail.com (Dave)
Date: Sat, 15 May 2010 10:18:04 -0700 (PDT)
Subject: Local variables persist across function calls
Message-ID: <89ea77da-2ae0-41e6-b26f-1eb34bc063be@q36g2000prg.googlegroups.com>

I've been writing Python for a few years now, and tonight I ran into
something that I didn't understand. I'm hoping someone can explain
this to me. I'm writing a recursive function for generating
dictionaries with keys that consist of all permutations of a certain
set. Here's the function:


def make_perm(levels, result = {}, key = ''):
	local = key
	if levels == 1:
		for i in ['a', 'b', 'c', 'd']:
			result [local + i] = ''
	else:
		for i in ['a', 'b', 'c', 'd']:
			make_perm(levels - 1, result, local + i)
	return result


The first time I ran it, make_perm(2) does what I expected, returning
a dictionary of the form {'aa': '', 'ab':'', 'ac':'', ... }. But, if I
run make_perm(3) after that, I get a dictionary that combines the
contents of make_perm(2) with the values of make_perm(3), a dictionary
like {'aaa':'', 'aab':'', ...}. Running make_perm(2) again will return
the same result as make_perm(3) just did. It's like the local variable
is preserved across different calls to the same function. I don't
understand why this happens: "result" is not a global variable, and
accessing it outside the function generates a NameError, as it should.
After running make_perm once, printing the value of result inside the
function produces the last result returned on the first iteration.

If, however, I explicitly pass an empty dictionary into make_perm as
the second argument, the value of "result" is returned correctly. So I
have a solution to my problem, but I still don't understand why it
works. I've tried this on both Python 2.6 and Python 3.2, both in IDLE
and from the command line, and it behaves the same way. So it seems
like this is an intentional language feature, but I'm not sure exactly
why it works this way, or what's going on. Anyway, I'd appreciate it
if someone could explain this to me.


From darragh.ssa at gmail.com  Sat May 15 13:28:37 2010
From: darragh.ssa at gmail.com (Kruptein)
Date: Sat, 15 May 2010 10:28:37 -0700 (PDT)
Subject: d-cm Controll Manager
References: 
Message-ID: 

http://launchpad.net/d-cm


From edquiver at gmail.com  Sat May 15 13:29:41 2010
From: edquiver at gmail.com (Yutao Deng)
Date: Sun, 16 May 2010 01:29:41 +0800
Subject: pickle.load() all dict
Message-ID: 

Hi all:
I'm trying to learn to use Python  wrote a applet to record every day doing.
and i use the pickle
pickle.dump something to file no problem i think.
but pickle.load whith a problem. can not load all dict do my way that what i
pickle.dump().

My code:
####
import cPickle as pickle
pickle_file = open("data2","rb")
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
####
console show :
{'2010-5-23': ['1242', 'first']}
{'2010-5-24': ['1232', 'third']}
{'2010-5-25': ['211', 'second']}
{'2010-3-22': ['3211', 'fourrrr']}
{'2050-3-2': ['3990', '322']}

This is i want but that's silly. if the dict too much, then i have not
ideas.

the other way from
http://mail.python.org/pipermail/tutor/2005-July/039859.html

####
import cPickle as pickle
pickle_file = open("data2","rb")

number_of_pickles = pickle.load(pickle_file)
for n in range(number_of_pickles):
    p = pickle.load(pickle_file)
    print p
####
this way didnt work for me.

console show:
Traceback (most recent call last):
    number_of_pickles = pickle.load(pickle_file)
cPickle.UnpicklingError: invalid load key, '
'.
how do i define the range of pickle.load a file. i mean that how can i know
how many dict in the data2.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From albert at spenarnc.xs4all.nl  Sat May 15 13:49:51 2010
From: albert at spenarnc.xs4all.nl (Albert van der Horst)
Date: 15 May 2010 17:49:51 GMT
Subject: Picking a license
References: 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
Message-ID: 

In article <7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e at d27g2000yqc.googlegroups.com>,
Patrick Maupin   wrote:

>
>That is correct.  All "privileges" as you put it are merely things
>that a user can do with the code without fear of a lawsuit by the
>author, and when an author uses a permissive license, he indicates
>that the things that he could possibly find egregious enough to sue
>over are very few.  For example, if you give an Ubuntu CD to your
>friend without giving source code or a written offer of source code,
>you have violated the license on quite a few of the programs on the
>CD, but not, for example, on Python or Apache, because these licenses
>do not attempt to forbid you from doing this.

Bit this is stupid! The GPL is to accomplish a political goal,
an operating system with tools available to all, that can be
modified by anybody capable of doing so.

Enforcements not amenable to that goal will not happen.

It might surprise even RMS himself but ...
The political goal has been large and by accomplished at the expense
of great legal effort and great efforts of Linus Torvalds c.s. Without
the GPL Linux would not exist -- except in the form of an academic
exercise -- and neither would gcc, so neither would Python.
By proxy I estimate that none of the software with a permissive
license you mention would not be available.

You seem to imply that RMS is a nasty guy.
Yes, RMS is a nasty guy. All warriors are! Get in his
way and you're blasted. But some warriors fight for a right
cause ... This really has nothing to do with anything.
The meek will inherit the world, yes, but only after
the second coming.

>
>Regards,
>Pat

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst



From aahz at pythoncraft.com  Sat May 15 13:52:38 2010
From: aahz at pythoncraft.com (Aahz)
Date: 15 May 2010 10:52:38 -0700
Subject: Is Python a functional programming language?
References: 
	
	
Message-ID: 

In article ,
  wrote:
>
>One very annoying thing in Python is the distinction between
>statements and expressions.

One extremely valuable thing in Python is the distinction between
statements and expressions.

In fact, given the semantic similarity between Python and Lisp, I would
argue that Python having the distinction is partly responsible for its
popularity.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From alfps at start.no  Sat May 15 13:56:33 2010
From: alfps at start.no (Alf P. Steinbach)
Date: Sat, 15 May 2010 19:56:33 +0200
Subject: Local variables persist across function calls
In-Reply-To: <89ea77da-2ae0-41e6-b26f-1eb34bc063be@q36g2000prg.googlegroups.com>
References: <89ea77da-2ae0-41e6-b26f-1eb34bc063be@q36g2000prg.googlegroups.com>
Message-ID: 

On 15.05.2010 19:18, * Dave:
> I've been writing Python for a few years now, and tonight I ran into
> something that I didn't understand. I'm hoping someone can explain
> this to me. I'm writing a recursive function for generating
> dictionaries with keys that consist of all permutations of a certain
> set. Here's the function:
>
> 
> def make_perm(levels, result = {}, key = ''):
> 	local = key
> 	if levels == 1:
> 		for i in ['a', 'b', 'c', 'd']:
> 			result [local + i] = ''
> 	else:
> 		for i in ['a', 'b', 'c', 'd']:
> 			make_perm(levels - 1, result, local + i)
> 	return result
> 

I bet this is a FAQ, but I don't know where the FAQ is (probably at python.org?).

The defaults for formal parameters are evaluated /once/, namely at function 
definition time, when the execution first passes through the definition.

And what you're doing is to update that original default 'result' dictionary.

To achieve the effect that you apparently want you can do


   def make_perm( levels, result = None, key = '' )
       if result is None: result = {}  # Evaluated for each call.
       # Blah blah, the rest


There are also other ways.


Cheers & hth.,

- Alf

-- 
blog at 


From clp2 at rebertia.com  Sat May 15 14:01:03 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Sat, 15 May 2010 11:01:03 -0700
Subject: Local variables persist across function calls
In-Reply-To: <89ea77da-2ae0-41e6-b26f-1eb34bc063be@q36g2000prg.googlegroups.com>
References: <89ea77da-2ae0-41e6-b26f-1eb34bc063be@q36g2000prg.googlegroups.com>
Message-ID: 

On Sat, May 15, 2010 at 10:18 AM, Dave  wrote:
> I've been writing Python for a few years now, and tonight I ran into
> something that I didn't understand. I'm hoping someone can explain
> this to me. I'm writing a recursive function for generating
> dictionaries with keys that consist of all permutations of a certain
> set. Here's the function:
>
> 
> def make_perm(levels, result = {}, key = ''):
> ? ? ? ?local = key
> ? ? ? ?if levels == 1:
> ? ? ? ? ? ? ? ?for i in ['a', 'b', 'c', 'd']:
> ? ? ? ? ? ? ? ? ? ? ? ?result [local + i] = ''
> ? ? ? ?else:
> ? ? ? ? ? ? ? ?for i in ['a', 'b', 'c', 'd']:
> ? ? ? ? ? ? ? ? ? ? ? ?make_perm(levels - 1, result, local + i)
> ? ? ? ?return result
> 
>
> The first time I ran it, make_perm(2) does what I expected, returning
> a dictionary of the form {'aa': '', 'ab':'', 'ac':'', ... }. But, if I
> run make_perm(3) after that, I get a dictionary that combines the
> contents of make_perm(2) with the values of make_perm(3), a dictionary
> like {'aaa':'', 'aab':'', ...}. Running make_perm(2) again will return
> the same result as make_perm(3) just did. It's like the local variable
> is preserved across different calls to the same function. I don't
> understand why this happens: "result" is not a global variable, and
> accessing it outside the function generates a NameError, as it should.
> After running make_perm once, printing the value of result inside the
> function produces the last result returned on the first iteration.
>
> If, however, I explicitly pass an empty dictionary into make_perm as
> the second argument, the value of "result" is returned correctly. So I
> have a solution to my problem, but I still don't understand why it
> works. I've tried this on both Python 2.6 and Python 3.2, both in IDLE
> and from the command line, and it behaves the same way. So it seems
> like this is an intentional language feature, but I'm not sure exactly
> why it works this way, or what's going on. Anyway, I'd appreciate it
> if someone could explain this to me.

Default argument values are only evaluated *once*, at
function-definition time, *not* every time the function is called. So
whenever you call make_perm() without specifying the `result`
argument, `result` will get *the same dictionary* as its value every
time, and modifications to that dictionary will thus persist across
calls.

When a default argument value is of a mutable type such as a
dictionary, the following idiom is used to get around the
aforementioned behavior:

def make_perm(levels, result = None, key = ''):
    if result is None:
        result = {}
    #rest same as before...

This ensures `result` gets a fresh dictionary every time.

See also the "Important warning" on
http://docs.python.org/tutorial/controlflow.html#default-argument-values

Cheers,
Chris
--
I'm not a fan of this behavior either.
http://blog.rebertia.com


From pmaupin at gmail.com  Sat May 15 14:09:29 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 11:09:29 -0700 (PDT)
Subject: Picking a license
References: 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com> 
	 
	<4bece8de$0$8761$c3e8da3@news.astraweb.com>
	
Message-ID: <12d81b67-6ab8-454f-851d-6a32b3bfa529@f14g2000vbn.googlegroups.com>

On May 14, 8:04?am, Ethan Furman  wrote:
> Steven D'Aprano wrote:

>> You've never had to recode something because it was nominally available
>> under a proprietary licence that you (or your client) was unwilling to
>> use? Lucky you!

> Steven, did you actually read what he wrote? ?If you did, why would you
> say something so stupid?

Well, in Steven's defense, my literal words "... labor that could have
been spent elsewhere if someone else had done something differently.
The only time that comes into play in my programming life is when I
have to recode something that is nominally available under the GPL..."
could easily be taken to mean that I have never had to recode
something that was under a proprietary license.

In truth most of what any of us write is probably very similar to
stuff that others have written, so taken in a very literal sense, yes,
obviously, there are several times that I have had to recode
proprietary software.  But I was responding to Brendan's "broken
window" analogy, and, rightly or wrongly, I *assumed* he was only
referring to software that was free *at one time* but then was somehow
taken out of the commons.  To my knowledge, I've never recoded such
software, and to the extent that anybody might be suggesting that
*all* software belongs in an easily-accessible commons and that nobody
should ever have to recode anything -- well, I could probably be
seduced by the Utopian vision, but I strongly reject that the sort of
rights-pooling mandated by the GPL is the single way to get there.

If everybody believes in the Utopian vision, the GPL is rendered
unnecessary, and to the extent that some people *really* don't believe
in the Utopian vision, the wording of the GPL makes a gentle
transition from proprietary to free difficult for programmers with
feet in both camps.  However, the GPL *does* provide a core focal
point for the actual Utopian vision itself, and this does serve a
useful purpose.  Personally, I think we are gradually lurching towards
the Utopian vision, and probably at a faster pace than if we only had
the GPL or if we only had permissive licenses.  I think even RMS
believes this; as a matter of practicality he will suggest the LGPL or
even permissive licensing under some circumstances.

Regards,
Pat


From awilliam at whitemice.org  Sat May 15 14:37:22 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sat, 15 May 2010 14:37:22 -0400
Subject: Reading XML namespaces
Message-ID: <1273948642.2322.10.camel@linux-yu4c.site>

Say I have an XML document that begins with:



...

How can one access the namespaces define in this node?  I've done a fair
amount of XML in Python, but haven't been able to uncover the call to
enumerate the namespaces.

Primarily I am using etree from lxml.
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba



From pmaupin at gmail.com  Sat May 15 14:46:57 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 11:46:57 -0700 (PDT)
Subject: Picking a license
References: 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	
Message-ID: 

On May 15, 12:49?pm, Albert van der Horst 
wrote:
> In article <7bdce8a7-bf7d-4f1f-bc9d-1eca26974... at d27g2000yqc.googlegroups.com>,
> Patrick Maupin ? wrote:
> 
>
> >That is correct. ?All "privileges" as you put it are merely things
> >that a user can do with the code without fear of a lawsuit by the
> >author, and when an author uses a permissive license, he indicates
> >that the things that he could possibly find egregious enough to sue
> >over are very few. ?For example, if you give an Ubuntu CD to your
> >friend without giving source code or a written offer of source code,
> >you have violated the license on quite a few of the programs on the
> >CD, but not, for example, on Python or Apache, because these licenses
> >do not attempt to forbid you from doing this.
>
> Bit this is stupid! The GPL is to accomplish a political goal,
> an operating system with tools available to all, that can be
> modified by anybody capable of doing so.

Sure.

> Enforcements not amenable to that goal will not happen.

Absolutely agreed.  I have no real problem with that.  I *do* have a
problem with some of the faithful acting like I'm completely wrong and
trying to actively mislead about how the license works, but then I
guess that's par for the course for politics.

> It might surprise even RMS himself but ...
> The political goal has been large and by accomplished at the expense
> of great legal effort and great efforts of Linus Torvalds.

Agreed.

> c.s. Without
> the GPL Linux would not exist -- except in the form of an academic
> exercise

Not sure that's true.  Linus would have picked *some* license.
Possibly something like the BSD.  He started development using Minix,
which certainly wasn't licensed freely, and which was first released 2
years before the GPL, so the GPL was not instrumental in providing his
first development environment.  He might have had to choose a
different compiler if GCC weren't available, but there was a compiler
with Unix.  I can believe that the GPL helped Linux gain some momentum
it wouldn't have had otherwise, but I reject your absolute assertion.

> -- and neither would gcc,

Well, not gcc itself, but there were compilers around...

> so neither would Python.

That I *completely* disagree with.  Python was written for the amoeba
O/S, which was in existence and had compilers a good 3 or 4 years
before the first release of gcc.

> By proxy I estimate that none of the software with a permissive
> license you mention would not be available.

I disagree.  If Linux weren't around, MS would not be the sole
winner.  Free development would have coalesced around one of the BSDs
(which in absolute numbers are still pretty big projects right now, in
any case, just lacking the mindshare of Linux).  As apache and other
projects have shown, the propensity of the few to try to lock things
up can easily be overcome with sheer numbers and willpower -- no
reciprocal license required.

> You seem to imply that RMS is a nasty guy.

I think we both agree that people who make history are often
unreasonable.  I really don't have a problem with that, but I do have
a problem with apologists claiming it isn't so in his case.

> Yes, RMS is a nasty guy. All warriors are! Get in his
> way and you're blasted.

So maybe you're not one of the ones I have a problem with.

> But some warriors fight for a right
> cause ... This really has nothing to do with anything.
> The meek will inherit the world, yes, but only after
> the second coming.

If you read all the posts carefully, you will see that people arguing
that sometimes permissive licenses are the right ones also allow a
place for the GPL.  It is only some of the GPL adherents who accuse
some of the "non-believers" of acting duplicitously, with malice, of
being against "freedom".  I reject that characterization of myself,
and when people accuse me of this, I mentally place them in the
category of "religious nutter".  Once I have placed someone in that
category, it is sometimes hard for me to respond civilly to them,
especially when they write something stupid.  I have not yet placed
you in that category, but I do categorically reject your
interpretation of some of the relevant historical events.

Regards,
Pat


From metolone+gmane at gmail.com  Sat May 15 15:31:26 2010
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Sat, 15 May 2010 12:31:26 -0700
Subject: Puzzled by code pages
References: <4bee7823$1@dnews.tpgi.com.au>
	<1273932760.3929.18.camel@linux-yu4c.site>
Message-ID: 


"Adam Tauno Williams"  wrote in message 
news:1273932760.3929.18.camel at linux-yu4c.site...
> On Sat, 2010-05-15 at 20:30 +1000, Lie Ryan wrote:
>> On 05/15/10 10:27, Adam Tauno Williams wrote:
 [snip]

> Yep.  But in the interpreter both unicode() and repr() produce the same
> output.  Nothing displays the accented character.
>
> h = codecs.open('file.txt', 'rb', encoding='iso8859-2')
> data = h.read()
> h.close()
> str(data)

Here you are correctly reading an iso8859-2-encoded file and converting it 
to Unicode.

Try "print data".  "str(data)" converts from Unicode strings to byte 
strings, but only uses the default encoding, which is 'ascii'.  print will 
use the stdout encoding of your terminal, if known.   Try these commands on 
your system (mine is Windows XP):

>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> sys.stdout.encoding
'cp437'

You should only attempt to "print" Unicode strings or byte strings encoded 
in the stdout encoding.  Printing byte strings in any other encoding will 
often print garbage.

[snip]
> I think I'm getting close.  Parsing the file seems to work, and while
> writing it out does not error, rereading my own output fails. :(
> Possibly I'm 'accidentally' writing the output as UTF-8 and not
> ISO8859-2.  I need the internal data to be UTF-8 but read as ISO8859-2
> and rewritten back to ISO8859-2 [at least that is what I believe from
> the OpenStep files I'm seeing].

"internal data" is Unicode, not UTF-8.  Unicode is the absence of an 
encoding (Python uses UTF-16 or UTF-32 internally, but that is an 
implementation detail).  UTF-8 is a byte-encoding.

If you actually need the internal data as UTF-8 (maybe you are working with 
a library that works with UTF-8 strings, then:

>>> f = codecs.open("in.txt", 'rb', encoding="iso8859-2")
>>> s = f.read()  # s is a Unicode string.
>>> s = s.encode('utf-8') # now s is a UTF-8 byte string
>>> f.close()

(process data as UTF-8 here).

>>> s = s.decode('utf-8') # s is Unicode again.
>>> f2 = codecs.open("out.txt", 'wb', encoding="iso8859-2")
>>> f2.write(s)
>>> f2.close()

Note you *decode* byte strings to Unicode and *encode* Unicode into byte 
strings.

-Mark




From paul at boddie.org.uk  Sat May 15 15:59:06 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Sat, 15 May 2010 12:59:06 -0700 (PDT)
Subject: Picking a license
References: 
	
Message-ID: 

On 15 Mai, 04:20, Lawrence D'Oliveiro  wrote:
> In message , Paul Boddie wrote:
> > Although people can argue that usage of the GPL prevents people from
> > potentially contributing because they would not be able to sell
> > proprietary versions of the software ...
>
> It doesn?t prevent them from selling proprietary versions of their own
> contributions, any more than any other licence does.

I already mentioned this several days ago, upon which it was regarded
as not addressing some complaint or other. You own your own work, but
if you release that work to someone and it makes use of a GPL-licensed
work, then the user must be able to deal with the work according to
the terms of the GPL.

> The fact that their contribution may not be much use without the rest of
> that GPL?d code is entirely another matter. It was their choice to build on
> the work of others; they could have reinvented it from scratch themselves.

Yes. I mentioned this before: WebKit (or probably more specifically
WebCore) is an example of both originally building on GPL-licensed
code, and also building on permissively licensed code. The code
specifically belonging to WebKit and its predecessor was never GPL-
licensed itself.

My point about a platform vendor choosing to undertake the multiple
man-year task of rewriting an existing, mature GPL-licensed library
purely so that people are then able to sell proprietary software is
grounded in the observation that if people were content to make their
source code available for their products on such a platform, the GPL
would be a satisfactory basis for such activities: they own their own
code, can license it permissively (but compatibly with the GPL), and
the sources remain available; they don't need a "weaker" copyleft
licence or a permissive licence to do any of this.

Now, since it is unlikely that a business is going to spend money on a
project that doesn't change the situation in any practical sense -
that people are content with having their source code available to
their users, but now (after several man-years of effort) can link to a
permissively licensed (or weak-copyleft licensed) library - the actual
motivation emerges for choosing the LGPL or a permissive licence as
the basis for the platform's licensing: to permit the only thing that
the GPL does not, which is to let people release their software and
not commit to offering the source code; to permit, in effect, the
delivery of proprietary software.

Any claim that a licensing change is needed merely to let people
develop open source applications on the platform is dishonest,
especially as the "about" page for PySide spells out the licensing
objective. Take away the proprietary software requirement and you
might as well use the GPL.

Paul


From john at castleamber.com  Sat May 15 16:22:43 2010
From: john at castleamber.com (John Bokma)
Date: Sat, 15 May 2010 15:22:43 -0500
Subject: Picking a license
References: 
	
	
Message-ID: <87bpcgx6cs.fsf@castleamber.com>

Paul Boddie  writes:

> especially as the "about" page for PySide spells out the licensing
> objective. Take away the proprietary software requirement and you
> might as well use the GPL.

Thank you for mentioning PySide, I wasn't aware of this project.

-- 
John Bokma                                                               j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development


From stefan_ml at behnel.de  Sat May 15 16:29:49 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 15 May 2010 22:29:49 +0200
Subject: Reading XML namespaces
In-Reply-To: <1273948642.2322.10.camel@linux-yu4c.site>
References: <1273948642.2322.10.camel@linux-yu4c.site>
Message-ID: 

Adam Tauno Williams, 15.05.2010 20:37:
> Say I have an XML document that begins with:
>
> 
> 
> ...
>
> How can one access the namespaces define in this node?  I've done a fair
> amount of XML in Python, but haven't been able to uncover the call to
> enumerate the namespaces.
>
> Primarily I am using etree from lxml.

What do you need the namespaces for?

Stefan



From ksa.908 at gmail.com  Sat May 15 16:37:38 2010
From: ksa.908 at gmail.com (Mr.Ss)
Date: Sat, 15 May 2010 13:37:38 -0700 (PDT)
Subject: pass xxx site  ;0
Message-ID: <29d0a789-0e82-483e-b633-30242da6293e@u7g2000vbq.googlegroups.com>

pass xxx site

http://www.2shared.com/uploadComplete.jsp?sId=ISfomojyvBaVf129


From ksa.908 at gmail.com  Sat May 15 16:38:46 2010
From: ksa.908 at gmail.com (Mr.Ss)
Date: Sat, 15 May 2010 13:38:46 -0700 (PDT)
Subject: pass xxx site 2  ;0
Message-ID: 

pass xxx site

http://www.2shared.com/file/MqzpLfxz/pass_xxx_site.html


From awilliam at whitemice.org  Sat May 15 16:40:59 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sat, 15 May 2010 16:40:59 -0400
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>
	
Message-ID: <1273956059.4023.0.camel@linux-yu4c.site>

On Sat, 2010-05-15 at 22:29 +0200, Stefan Behnel wrote:
> Adam Tauno Williams, 15.05.2010 20:37:
> > Say I have an XML document that begins with:
> > 
> > 
> > How can one access the namespaces define in this node?  I've done a fair
> > amount of XML in Python, but haven't been able to uncover the call to
> > enumerate the namespaces.
> > Primarily I am using etree from lxml.
> What do you need the namespaces for?

One needs to know the defined namespace in order to perform xpath
operations.



From stefan_ml at behnel.de  Sat May 15 16:58:06 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 15 May 2010 22:58:06 +0200
Subject: Reading XML namespaces
In-Reply-To: <1273956059.4023.0.camel@linux-yu4c.site>
References: <1273948642.2322.10.camel@linux-yu4c.site>	
	<1273956059.4023.0.camel@linux-yu4c.site>
Message-ID: 

Adam Tauno Williams, 15.05.2010 22:40:
> On Sat, 2010-05-15 at 22:29 +0200, Stefan Behnel wrote:
>> Adam Tauno Williams, 15.05.2010 20:37:
>>> Say I have an XML document that begins with:
>>> 
>>> 
>>> How can one access the namespaces define in this node?  I've done a fair
>>> amount of XML in Python, but haven't been able to uncover the call to
>>> enumerate the namespaces.
>>> Primarily I am using etree from lxml.
>> What do you need the namespaces for?
>
> One needs to know the defined namespace in order to perform xpath
> operations.

Well, yes, but unless you already know the namespace (URI), you can't know 
what the tag you find signifies in the first place.

Unless, obviously, you are confusing namespaces with namespace prefixes. 
But you don't need to know the prefixes for XPath.

Does this help?

http://codespeak.net/lxml/xpathxslt.html#namespaces-and-prefixes

Stefan



From pmaupin at gmail.com  Sat May 15 16:59:30 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 13:59:30 -0700 (PDT)
Subject: Picking a license
References: 
	
	
Message-ID: <1dbd201e-2111-4625-9084-3213d64f609b@c11g2000vbe.googlegroups.com>

On May 15, 2:59?pm, Paul Boddie  wrote:

[Rest of the post, that contains points previously debated and well-
refuted, snipped]

> Any claim that a licensing change is needed merely to let people
> develop open source applications on the platform is dishonest,

See, there you go again, impugning the motives and character of
others.  Is it really that surprising that sometimes others get
annoyed by this and start to assume things about your personality that
you disagree with?

> especially as the "about" page for PySide spells out the licensing
> objective.

Yes, it does: "PySide is licensed under the LGPL version 2.1 license,
allowing both Free/Open source software and proprietary software
development."

> Take away the proprietary software requirement and you
> might as well use the GPL.

You obviously agree that PySide was coded as a direct replacement for
PyQt, for licensing reasons, so certainly there's a perception that
*something* is wrong with PyQt's license.  Let's see what the PyQt
license page has to say about it:

PyQt is available under the following licenses.

    * GNU General Public License v2
    * GNU General Public License v3
    * PyQt Commercial License

Hmm, the only thing that PySide seems to allow that is missing from
this list seems to be the "O" in "FOSS".  But of course, you already
knew that, because I already explained it, and as you've told me that
you read and think about everything very carefully, obviously your
objective in repeating this nonsense is to mislead and confuse.

Regards,
Pat


From awilliam at whitemice.org  Sat May 15 17:04:06 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sat, 15 May 2010 17:04:06 -0400
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>
	
	<1273956059.4023.0.camel@linux-yu4c.site>
	
Message-ID: <1273957446.4023.6.camel@linux-yu4c.site>

On Sat, 2010-05-15 at 22:58 +0200, Stefan Behnel wrote:
> Adam Tauno Williams, 15.05.2010 22:40:
> > On Sat, 2010-05-15 at 22:29 +0200, Stefan Behnel wrote:
> >> Adam Tauno Williams, 15.05.2010 20:37:
> >>> Say I have an XML document that begins with:
> >>> 
> >>> 
> >>> How can one access the namespaces define in this node?  I've done a fair
> >>> amount of XML in Python, but haven't been able to uncover the call to
> >>> enumerate the namespaces.
> >>> Primarily I am using etree from lxml.
> >> What do you need the namespaces for?
> > One needs to know the defined namespace in order to perform xpath
> > operations.
> Well, yes, but unless you already know the namespace (URI), you can't know 
> what the tag you find signifies in the first place.
> Unless, obviously, you are confusing namespaces with namespace prefixes. 
> But you don't need to know the prefixes for XPath.
> Does this help?
> http://codespeak.net/lxml/xpathxslt.html#namespaces-and-prefixes

I know that.  I'm getting an XML document and an xpath and need to
execute it.  But i have to tell xpath via namespaces= the prefixes &
namespaces; so I need to get that data out of the document.   

"If your XPath expression uses namespace prefixes, you must define them
in a prefix mapping"
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba



From sjmachin at lexicon.net  Sat May 15 17:07:20 2010
From: sjmachin at lexicon.net (John Machin)
Date: Sat, 15 May 2010 21:07:20 +0000 (UTC)
Subject: Puzzled by code pages
References: <1273883238.3929.8.camel@linux-yu4c.site>
	<1273883923.3929.10.camel@linux-yu4c.site>
Message-ID: 

Adam Tauno Williams  whitemice.org> writes:

> On Fri, 2010-05-14 at 20:27 -0400, Adam Tauno Williams wrote:
> > I'm trying to process OpenStep plist files in Python.  I have a parser
> > which works, but only for strict ASCII.  However plist files may contain
> > accented characters - equivalent to ISO-8859-2 (I believe).  For example
> > I read in the line:

> > '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
> > NSFileName;\n'
> > What is the correct way to re-encode this data into UTF-8 so I can use
> > unicode strings, and then write the output back to ISO8859-?

> Buried in the parser is a str(...) call.  Replacing that with
> unicode(...) and now the OpenSTEP plist parser is working with Italian
> plists.

Some observations:

Italian text is much more likely to be encoded in ISO-8859-1 than ISO-8859-2.
The latter covers eastern European languages (e.g. Polish, Czech, Hungarian)
that use the Latin alphabet with many "decorations" not found in western 
alphabets.

Let's look at the 'localit\xc3\xa0' example. Using ISO-8859-2, that decodes to
u'localit\u0102\xa0'. The second-last character is LATIN CAPITAL LETTER A WITH
BREVE (according to unicodedata.name()). The last character is NO-BREAK SPACE.
Doesn't look like an Italian word to me.

However, using UTF-8, that decodes to u'localit\xe0'. The last character is
LATIN SMALL LETTER A WITH GRAVE. Looks like a plausible Italian word to me. Also
to Wikipedia: "A localit? (literally "locality"; plural localit?) is the name
given in Italian administrative law to a type of territorial subdivision of a
comune ..."

Conclusions:

It's worth closely scrutinising "accented characters - equivalent to ISO-8859-2
(I believe)". Which variety of "OpenStep plist files" are you looking at:
NeXTSTEP, GNUstep, or MAC OS X? If the latter, it's evidently an XML document,
and you should be letting the XML parser decode it for you and in any case as an
XML document it's most likely UTF-8, not ISO-8859-2.

It's worth examining your definition of "working".




From diazona at ellipsix.net  Sat May 15 17:13:10 2010
From: diazona at ellipsix.net (David Zaslavsky)
Date: Sat, 15 May 2010 17:13:10 -0400
Subject: Human word reader
In-Reply-To: 
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
	
Message-ID: <201005151713.11373.diazona@ellipsix.net>

Here's my take on that:

 loc = re.search('for\s+(\w+)', string).group(1)

Not much different, really, but it does allow for multiple spaces (\s+) as 
well as requiring at least one character in the word (\w+), and I use a 
matching group to extract the location directly instead of splitting the 
string "by hand".

:) David

On Saturday 15 May 2010 8:38:01 am Xavier Ho wrote:
> On Sat, May 15, 2010 at 9:32 PM, timo verbeek 
wrote:
> > On May 15, 1:02 pm, timo verbeek  wrote:
> > Place starts always with for
> 
> Okay, much better.
> 
> Given that constraint, it looks like regular expression can do the job. I'm
> not very experienced with regex, though.
> 
> \w* matches a whole word composed of letters and numbers by default.
> 
> >>> result = re.search('for \w*', 'Give me the weather for London please.')
> >>> result.group()
> 
> 'for London'
> 
> >>> result.group().split()[1]
> 
> 'London'
> 
> Cheers,
> Xav
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part.
URL: 

From stefan_ml at behnel.de  Sat May 15 17:25:33 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 15 May 2010 23:25:33 +0200
Subject: Reading XML namespaces
In-Reply-To: <1273957446.4023.6.camel@linux-yu4c.site>
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>	
	<1273957446.4023.6.camel@linux-yu4c.site>
Message-ID: 

Adam Tauno Williams, 15.05.2010 23:04:
> On Sat, 2010-05-15 at 22:58 +0200, Stefan Behnel wrote:
>> Adam Tauno Williams, 15.05.2010 22:40:
>>> On Sat, 2010-05-15 at 22:29 +0200, Stefan Behnel wrote:
>>>> Adam Tauno Williams, 15.05.2010 20:37:
>>>>> Say I have an XML document that begins with:
>>>>> 
>>>>> 
>>>>> How can one access the namespaces define in this node?  I've done a fair
>>>>> amount of XML in Python, but haven't been able to uncover the call to
>>>>> enumerate the namespaces.
>>>>> Primarily I am using etree from lxml.
>>>> What do you need the namespaces for?
>>> One needs to know the defined namespace in order to perform xpath
>>> operations.
>> Well, yes, but unless you already know the namespace (URI), you can't know
>> what the tag you find signifies in the first place.
>> Unless, obviously, you are confusing namespaces with namespace prefixes.
>> But you don't need to know the prefixes for XPath.
>> Does this help?
>> http://codespeak.net/lxml/xpathxslt.html#namespaces-and-prefixes
>
> I know that.  I'm getting an XML document and an xpath and need to
> execute it.  But i have to tell xpath via namespaces= the prefixes&
> namespaces; so I need to get that data out of the document.

Ah, you didn't provide that information in your initial post. So you 
control neither the document nor the XPath expression, right? Can't you get 
the namespace-prefix mapping from your user? After all, he/she is the only 
one who knows the meaning of the XPath expression. I'd just reject any 
expression with an undefined prefix.

BTW, I'm still not sure I understand your problem. Could you provide some 
more details?

Stefan



From martin at v.loewis.de  Sat May 15 17:37:10 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sat, 15 May 2010 23:37:10 +0200
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>
	
Message-ID: <4BEF1406.7010205@v.loewis.de>

> BTW, I'm still not sure I understand your problem. Could you provide
> some more details?
>

Wouldn't it be easier if you told the OP how to access the prefix
mappings in lxml etree, or, if this was actually not possible, admitted
that it is actually not possible?

FWIW, in the DOM, you look at all attributes of an element node, and
search for those whose namespace is "http://www.w3.org/2000/xmlns/"

In SAX, you watch the startPrefixMapping events.

Regards,
Martin


From martin at v.loewis.de  Sat May 15 17:42:43 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sat, 15 May 2010 23:42:43 +0200
Subject: Puzzled by code pages
In-Reply-To: 
References: <1273883238.3929.8.camel@linux-yu4c.site>	<1273883923.3929.10.camel@linux-yu4c.site>
	
Message-ID: <4BEF1553.8020706@v.loewis.de>


> Conclusions:
> 
> It's worth closely scrutinising "accented characters - equivalent to ISO-8859-2
> (I believe)". Which variety of "OpenStep plist files" are you looking at:
> NeXTSTEP, GNUstep, or MAC OS X? If the latter, it's evidently an XML document,
> and you should be letting the XML parser decode it for you and in any case as an
> XML document it's most likely UTF-8, not ISO-8859-2.
> 
> It's worth examining your definition of "working".

I came to the same conclusions after reading the OP's article.

Regards,
Martin


From awilliam at whitemice.org  Sat May 15 17:43:53 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sat, 15 May 2010 17:43:53 -0400
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>
		<1273956059.4023.0.camel@linux-yu4c.site>
	
	<1273957446.4023.6.camel@linux-yu4c.site>
	
Message-ID: <1273959833.4023.13.camel@linux-yu4c.site>

On Sat, 2010-05-15 at 23:25 +0200, Stefan Behnel wrote:
> Ah, you didn't provide that information in your initial post. So you 
> control neither the document nor the XPath expression, right? 

Correct.

> Can't you get the namespace-prefix mapping from your user? 

Nope. Or they are not going to be expecting to have to [since this works
just fine in Java, which for this feature we are pretty much porting
from].

> After all, he/she is the only one who knows the meaning of the XPath expression. 

???  The namespaces are embedded in the document.  Personally I find it
odd I have to tell xpath about the namespace of the document it is a
$*&@(*& method of.

> I'd just reject any expression with an undefined prefix.

Which I'm okay with;  whether the prefix is undefined can be determined
from the document!

> BTW, I'm still not sure I understand your problem. Could you provide some 
> more details?

This is an action in a workflow action (business process modeling).  It
has an input message of an XML document and a parameter of an xpath;  it
invokes a subordinate action [think: foreach] for each node resulting
from the expression.

-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba



From paul at boddie.org.uk  Sat May 15 18:03:53 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Sat, 15 May 2010 15:03:53 -0700 (PDT)
Subject: Picking a license
References: 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com> 
	 
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com> 
	<47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com> 
	
Message-ID: <9c23d9ef-6ddc-4b04-a92a-9aa887411eb4@i31g2000vbt.googlegroups.com>

On 15 Mai, 03:46, Patrick Maupin  wrote:
> On May 14, 6:52?pm, Paul Boddie  wrote:
> > And suggesting that people have behavioural disorders ("Or because
> > have OCD?") might be a source of amusement to you, or may be a neat
> > debating trick in certain circles you admire, but rest assured that I
> > am neither amused nor impressed, nor are others likely to be.
>
> That was in an honest response to a question you asked "Really, if at
> this point you think I'm playing games with you." where I explained
> that I don't know what to think, because often, when you claimed to be
> addressing my point, you would bring up other red herrings and spend
> more time on those, and often assign positions to me that I never
> took.

You can spare us the excuses. As I said, I was attempting to be
thorough and to explore all possible means of distribution, not least
because this was not your original point - you were originally upset
about Mr Finney's remark, which you still don't accept, but there's
probably no convincing you now - and were then upset at the FSF
definition of a work "based on" or derived from another, leading you
to talk about various strategies for defending potential GPL
violations in the course of copyright infringement litigation. At this
point, it isn't unreasonable to think that you will think of some
other objection to the GPL which you will then have everyone explore.

I have pointed out at least once the section of the GPLv3 which could
reasonably permit someone to receive a binary distribution and there
not be an immediate licence violation, plus an FAQ entry which more or
less addresses the very situation you describe, and I even provided a
link to a discussion of these very issues on the debian-legal mailing
list. You can repeat as often as you like that you don't believe it,
but I have explained my understanding of precisely the "giving CD to a
friend" situation. To summarise: your friend gets the sources from the
same place as the binaries, which is from you. (The SFLC document
seems to treat section 6(d) of GPLv3 as being about Internet
distribution, but given that the term "network server" is only
mentioned after two sentences, and only then in the conditional form,
I regard the FAQ entry I referred to as offering relevant guidance,
and even others [*] have considered the text to be subject to similar
interpretation.)

[*] http://www.gerv.net/hacking/gplv3/draft3/

For the GPLv2 the requirement of a written offer appears to be more
dominant, and I believe the physical media actually shipped by Ubuntu
is accompanied by such an offer. If Ubuntu encourages others to share
media (produced in whichever fashion) or software without any written
offer then it is, as I remarked before, a matter that should be
discussed with them. Yes, it is unfortunate that the obligations are
not communicated, and that is one reason why there is a successor to
that licence, but it merely indicates that the balance of obligation
and tolerance in the licence, maintained without enabling the
widespread and malicious circumvention of the licence, is difficult to
achieve. It doesn't invalidate the intent of the licence, and if
anything it validates the adoption of GPLv3 in preference to GPLv2.

[...]

> (BTW, IMO this was one of your better posts in terms of tone and being
> on-point, etc., and I appreciate that.)

As I said before, spare me the condescension. Making a remark that
someone has a behavioural disorder - a matter, whether true or not,
that should have no influence on the course of any discussion -
especially when that person has attempted to provide explanations for
every quibble spontaneously raised over the course of several days,
not only indicates a certain level of hypocrisy, but it indicates that
as far as you are concerned any remark about a person's mental health
or well-being is fair game if it serves to belittle that person's
standing and ridicule what that person has written.

Paul


From tjreedy at udel.edu  Sat May 15 18:08:21 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Sat, 15 May 2010 18:08:21 -0400
Subject: Is Python a functional programming language?
In-Reply-To: <20100515164216.GA9146@subspacefield.org>
References: 	
	<20100515164216.GA9146@subspacefield.org>
Message-ID: 

On 5/15/2010 12:42 PM, travis+ml-python at subspacefield.org wrote:

> One very annoying thing in Python is the distinction between
> statements and expressions.

GvR regards it as a feature, claiming that research in the 1980s showed 
that the syntactic heterogeneity aided comprehension. I believe this is 
true for me.

> Ever since learning LISP (well, Scheme) in S&ICP I find myself
> frequently annoyed by this pointless distinction,

You have missed the very important distinction generally reflected in 
the statement/expression divide. Some code is meant to be evaluated 
immediately and some is meant to be quoted for later evaluation. In 
general (yes, there are some exceptions), Python statements are either 
restricted gotos or statements that implicitly quote part of the code in 
the statement. And in general, with a few exceptions, including lambda, 
expressions are completely and immediately evaluated. Changing print and 
exec from statements to functions made Py3 more consistent in this 
respect this distinction.

In List, one either quotes explicitly or must remember that certain 
'functions' are not really functions but are 'special functions' or 
'macros' that implicitly quote the code, just like Python statements do.

Simple statement example:

name = expression

The name is implicitely quoted. Behind the scenes, this is a function 
call. At module level, one can write the call explictly, with explicit 
quotes:

globals().__setitem__('name', expression)

If the statement form annoys you, use the expression equivalent. (Within 
functions, however, you do not have this choice in CPython because, for 
efficiency, function local namespaces are not Python objects and hence 
there is no Python function to directly manipulate them.)

In Lisp, the expression would be something like

(set 'name expression)

Compound statement example:

def f(a, b=3);
	'doc for a'
	

The def keyword, default arg expression(s), and doc string are evaluated 
immediately. The function name, parameter names, and body code must be 
quoted somehow. In Python, this is done implicitly as signalled by def 
being a statement keyword rather than a function name. Behind the 
scenes, the def statement is implemented mainly by two function calls: 
compile the (quoted) code and create a function object. I believe that 
one could define functions with explicit calls rather than a statement, 
but it would be much more work and require explicit quotes. Turning a 
class statement into an exec() and type() call is easier, but still 
extra work.

Terry Jan Reedy



From cjw at ncf.ca  Sat May 15 18:34:47 2010
From: cjw at ncf.ca (cjw)
Date: Sat, 15 May 2010 18:34:47 -0400
Subject: Access to comp.lang.python
Message-ID: 

This isn't about Python but I'm seeking suggestions as to the best way 
to access the newsgroup.

It seems that messages are coming from a number of sources, such as 
gmane and google groups.

The problem is that many messages seem to get unlinked from their threads.

I use Thunderbird 3.0.5 and wonder whether the problem lies with the 
merge process, the server or my reader.

Would it be better to go to gmane, google groups or some such provider.

In the past, use of Ctrl K had neatly disposed of thread that are of no 
interest.

I would welcome advice.

Colin W.


From pietro.campe at gmail.com  Sat May 15 18:56:41 2010
From: pietro.campe at gmail.com (Pietro Campesato)
Date: Sat, 15 May 2010 15:56:41 -0700 (PDT)
Subject: parsing XML
References: 
Message-ID: 

On May 14, 7:57?am, "kak... at gmail.com"  wrote:
> Hi to all, let's say we have the following Xml
> 
> ? 
> ? ? 17.1
> ? ? 6.4
> ? 
> ? 
> ? ? 15.5
> ? ? 7.8
> ? 
> 
>
> How can i get the players name, age and height?
> DOM or SAX and how
>
> Thanks
> Antonis

I've found some code which converts an XML string to a dictionary
here:
http://nonplatonic.com/ben.php?title=python_xml_to_dict_bow_to_my_recursive_g&more=1&c=1&tb=1&pb=1

Once your data is in a dictionary extracting info will be much easier.


From davea at ieee.org  Sat May 15 20:09:40 2010
From: davea at ieee.org (Dave Angel)
Date: Sat, 15 May 2010 20:09:40 -0400
Subject: write a 20GB file
In-Reply-To: 
References: 	<4BED2E45.6060301@ieee.org>					
	
Message-ID: <4BEF37C4.4090709@ieee.org>

Nathan Rice wrote:
> This is precisely the situation mmap was made for :)  It has almost the same
> methods as a file so it should be an easy replacement.
>
> 

Only on a 64bit system, and I'm not sure it's even possible there in 
every case.  On a 32bit system, it would be impossible to mmap a 20gb 
file.  You only have 4gb of address space to play with, total.

DaveA



From pmaupin at gmail.com  Sat May 15 20:30:51 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 17:30:51 -0700 (PDT)
Subject: write a 20GB file
References: 
	<4BED2E45.6060301@ieee.org>
	 
	
	 
	
	 
	 
	
Message-ID: <98a5a026-6e5a-41e1-b096-17866b3e0f4e@m21g2000vbr.googlegroups.com>

On May 15, 7:09?pm, Dave Angel  wrote:
> Nathan Rice wrote:
> > This is precisely the situation mmap was made for :) ?It has almost the same
> > methods as a file so it should be an easy replacement.
>
> > 
>
> Only on a 64bit system, and I'm not sure it's even possible there in
> every case. ?On a 32bit system, it would be impossible to mmap a 20gb
> file. ?You only have 4gb of address space to play with, total.
>
> DaveA



From pmaupin at gmail.com  Sat May 15 20:32:38 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 17:32:38 -0700 (PDT)
Subject: write a 20GB file
References: 
	<4BED2E45.6060301@ieee.org>
	 
	
	 
	
	 
	 
	
Message-ID: <1fb377ce-e1c7-4ec3-bed4-dc5c124af217@d12g2000vbr.googlegroups.com>

On May 15, 7:09?pm, Dave Angel  wrote:
> Nathan Rice wrote:
> > This is precisely the situation mmap was made for :) ?It has almost the same
> > methods as a file so it should be an easy replacement.
>
> > 
>
> Only on a 64bit system, and I'm not sure it's even possible there in
> every case. ?On a 32bit system, it would be impossible to mmap a 20gb
> file. ?You only have 4gb of address space to play with, total.
>
> DaveA

Well, depending on the OS, I think you could have multiple mappings
per file.  So you could maintain your own mapping cache.  That could
get a bit ugly, but depending on what you are doing, it might not be
too bad.

Regards,
Pat


From martin at v.loewis.de  Sat May 15 20:37:33 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sun, 16 May 2010 02:37:33 +0200
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>	
	
Message-ID: <4BEF3E4D.9090404@v.loewis.de>

> ???  The namespaces are embedded in the document.  Personally I find it
> odd I have to tell xpath about the namespace of the document it is a
> $*&@(*& method of.

How so? Why do you say it's a "method", and why do you say "of"?

Usually, xpath expressions are *not* part of the document they operate
on, but part of the code that performs the operation. Consequentially,
the namespace prefixes in the xpath expression do *not* occur in the
document (other than by chance), but are defined by whoever writes the
xpath expression. That is typically somebody different from the one
writing the document - if you would always write them together, you
wouldn't need xpath in the first place, but could produce the selection
result right away.

Regards.
Martin


From martin at v.loewis.de  Sat May 15 20:37:33 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sun, 16 May 2010 02:37:33 +0200
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>	
	
Message-ID: <4BEF3E4D.9090404@v.loewis.de>

> ???  The namespaces are embedded in the document.  Personally I find it
> odd I have to tell xpath about the namespace of the document it is a
> $*&@(*& method of.

How so? Why do you say it's a "method", and why do you say "of"?

Usually, xpath expressions are *not* part of the document they operate
on, but part of the code that performs the operation. Consequentially,
the namespace prefixes in the xpath expression do *not* occur in the
document (other than by chance), but are defined by whoever writes the
xpath expression. That is typically somebody different from the one
writing the document - if you would always write them together, you
wouldn't need xpath in the first place, but could produce the selection
result right away.

Regards.
Martin


From ldo at geek-central.gen.new_zealand  Sat May 15 23:05:20 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sun, 16 May 2010 15:05:20 +1200
Subject: Picking a license
References: 
	
	
Message-ID: 

In message
, Patrick 
Maupin wrote:

> On May 14, 9:21 pm, Lawrence D'Oliveiro  central.gen.new_zealand> wrote:
>
>> In message , Ed
>> Keith wrote:
>>
>>> I just refuse to use [the GPL] in any code for a client, because I
>>> do not want to require someone who does not know source code from Morse
>>> code code to figure out what they need to do to avoid violating the
>>> license.
>>
>> Why don?t you just put the source code on the same disc you send them,
>> and tell them to pass copies of the entire disc to anyone they want?
> 
> What you would really have to tell them is "don't pass along the
> program *unless* you copy the whole disk."  That's no longer a
> courtesy -- that's a mandate.  By not using the GPL, Ed avoids having
> to mandate to his customer how to treat the software he has delivered
> to them.

But that?s what ?copyright? means, it means ?right to copy?. It?s his right 
to impose terms on how copies of stuff he created are treated.


From ldo at geek-central.gen.new_zealand  Sat May 15 23:06:54 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sun, 16 May 2010 15:06:54 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> On Fri, 5/14/10, Lawrence D'Oliveiro
>  wrote:
> 
>> In message ,
>> Ed Keith wrote:
>> 
>>> Yes, under the GPL every one has one set of freedoms,
>>> under the MIT or Boost license every one has more freedoms. Under other
>>> licenses they have fewer freedoms.
>> 
>> But what about the ?freedom? to take away other
>> people?s freedom? Is that really ?freedom??
> 
> Yes.

But that?s a ?freedom? that non-GPL licences do not give you, that the GPL 
does. So which licence gives you more ?freedoms?, again?


From ldo at geek-central.gen.new_zealand  Sat May 15 23:08:38 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sun, 16 May 2010 15:08:38 +1200
Subject: Picking a license
References: 
	<93d67bd9-6721-4759-a3de-412b95b29a93@c11g2000vbe.googlegroups.com>
Message-ID: 

In message
<93d67bd9-6721-4759-a3de-412b95b29a93 at c11g2000vbe.googlegroups.com>, Paul 
Boddie wrote:

> Although Bill Gates once apparently claimed that no-one needs the
> source code for their word processor or office suite ...

Thereby committing the sealed-bonnet fallacy.


From ldo at geek-central.gen.new_zealand  Sat May 15 23:09:32 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sun, 16 May 2010 15:09:32 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> But if my client give someone else a copy of the binary I gave them, they
> are now in violation.

Why would they be in violation? It seems to me a violation would only occur 
if someone asked them for the source, and they refused.


From awilliam at whitemice.org  Sun May 16 00:00:59 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sun, 16 May 2010 00:00:59 -0400
Subject: Reading XML namespaces
In-Reply-To: <4BEF1406.7010205@v.loewis.de>
References: <1273948642.2322.10.camel@linux-yu4c.site>
		<1273956059.4023.0.camel@linux-yu4c.site>
		<1273957446.4023.6.camel@linux-yu4c.site>
	
	<4BEF1406.7010205@v.loewis.de>
Message-ID: <1273982459.28715.2.camel@linux-yu4c.site>

On Sat, 2010-05-15 at 23:37 +0200, Martin v. Loewis wrote:
> > BTW, I'm still not sure I understand your problem. Could you provide
> > some more details?
> Wouldn't it be easier if you told the OP how to access the prefix

:)

> mappings in lxml etree, or, if this was actually not possible, admitted
> that it is actually not possible?

I suspect that it is not;  but that seems rather surprising. 

> FWIW, in the DOM, you look at all attributes of an element node, and
> search for those whose namespace is "http://www.w3.org/2000/xmlns/"
> In SAX, you watch the startPrefixMapping events.

Given that XML documents can be very large I'd rather avoid a parsing of
the document [beyond what lxml/etree] has already done] just to retrieve
the namespaces and their prefixes.



From awilliam at whitemice.org  Sun May 16 00:11:57 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sun, 16 May 2010 00:11:57 -0400
Subject: Reading XML namespaces
In-Reply-To: <4BEF3E4D.9090404@v.loewis.de>
References: <1273948642.2322.10.camel@linux-yu4c.site>
		<1273956059.4023.0.camel@linux-yu4c.site>
		<1273957446.4023.6.camel@linux-yu4c.site>
	
	
	<4BEF3E4D.9090404@v.loewis.de>
Message-ID: <1273983117.28715.11.camel@linux-yu4c.site>

On Sun, 2010-05-16 at 02:37 +0200, Martin v. Loewis wrote:
> > ???  The namespaces are embedded in the document.  Personally I find it
> > odd I have to tell xpath about the namespace of the document it is a
> > $*&@(*& method of.
> How so? Why do you say it's a "method", and why do you say "of"?
> Usually, xpath expressions are *not* part of the document they operate
> on, but part of the code that performs the operation.

from lxml import etree

doc = etree.parse(data)
doc.xpath(....)

>  Consequentially,
> the namespace prefixes in the xpath expression do *not* occur in the
> document (other than by chance), but are defined by whoever writes the
> xpath expression. That is typically somebody different from the one
> writing the document 

Maybe true technically, but false in practice.  If I receive XML data
from source XYZ or service XYZ the use of namespaces and their prefixes
is extremely consistent [in practice] and very customary (for example:
I've never seen the DSML namespace abbreviated as anything other than
"dsml" and I rarely see WebDAV propfind XML use a namespace prefix other
than "D").  The odds that a customer or vendors ERP will generate
different namespaces and abbreviations between requests is ludicrously
remote [I don't recall ever seeing it happen].

And if the xpath fails to produce normal [or any] output the workflow
with either do nothing or abend which will draw the attention of an
administrator.

> - if you would always write them together, you
> wouldn't need xpath in the first place, but could produce the selection
> result right away.




From robert.kern at gmail.com  Sun May 16 00:31:19 2010
From: robert.kern at gmail.com (Robert Kern)
Date: Sat, 15 May 2010 23:31:19 -0500
Subject: Picking a license
In-Reply-To: 
References: 		
	
Message-ID: 

On 2010-05-15 22:05 , Lawrence D'Oliveiro wrote:
> In message
> , Patrick
> Maupin wrote:
>
>> On May 14, 9:21 pm, Lawrence D'Oliveiro> central.gen.new_zealand>  wrote:
>>
>>> In message, Ed
>>> Keith wrote:
>>>
>>>> I just refuse to use [the GPL] in any code for a client, because I
>>>> do not want to require someone who does not know source code from Morse
>>>> code code to figure out what they need to do to avoid violating the
>>>> license.
>>>
>>> Why don?t you just put the source code on the same disc you send them,
>>> and tell them to pass copies of the entire disc to anyone they want?
>>
>> What you would really have to tell them is "don't pass along the
>> program *unless* you copy the whole disk."  That's no longer a
>> courtesy -- that's a mandate.  By not using the GPL, Ed avoids having
>> to mandate to his customer how to treat the software he has delivered
>> to them.
>
> But that?s what ?copyright? means, it means ?right to copy?. It?s his right
> to impose terms on how copies of stuff he created are treated.

It's also his right to choose which terms to impose, depending on the client and 
project. If he doesn't think the GPL serves his goals, then he shouldn't use it. 
It shouldn't matter to him how well it serves your goals or how unburdensome you 
personally find the GPL's requirements.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From no.email at nospam.invalid  Sun May 16 00:36:32 2010
From: no.email at nospam.invalid (Paul Rubin)
Date: Sat, 15 May 2010 21:36:32 -0700
Subject: Is Python a functional programming language?
References: 
	
	
Message-ID: <7xocggv4xb.fsf@ruckus.brouhaha.com>

travis+ml-python at subspacefield.org writes:
> To be fair, it appears that Python's whitespace-sensitive syntax sort
> of precludes the "make a complex function on one line" that is typical
> of languages which don't have statement/expression distinctions, but
> I'm not convinced it couldn't be solved, perhaps by allowing anonymous
> functions to span multiple lines, just like named functions.

Haskell has whitespace-based syntax like Python (you can alternatively
use curly braces).  Their term for it is "layout".  You can
alternatively use curly braces and semi-colons.  I'd have to say that
Haskell's indentation rules are a bit harder to understand than Python's
at first.


From tjreedy at udel.edu  Sun May 16 01:00:07 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Sun, 16 May 2010 01:00:07 -0400
Subject: Access to comp.lang.python
In-Reply-To: 
References: 
Message-ID: 

On 5/15/2010 6:34 PM, cjw wrote:
> This isn't about Python but I'm seeking suggestions as to the best way
> to access the newsgroup.
>
> It seems that messages are coming from a number of sources, such as
> gmane and google groups.
>
> The problem is that many messages seem to get unlinked from their threads.

Some people have said that that is due to newreaders not tagging 
responses properly.

> I use Thunderbird 3.0.5 and wonder whether the problem lies with the
> merge process, the server or my reader.
>
> Would it be better to go to gmane, google groups or some such provider.

I believe some spam (like from Google accounts) is filtered out between 
c.l.p and python-list. Gmane mirrors python-list, not c.l.p., so it gets 
the benefit of the filtering. You can see from the headers that that is 
where I post from.

tjr





From aahz at pythoncraft.com  Sun May 16 01:12:11 2010
From: aahz at pythoncraft.com (Aahz)
Date: 15 May 2010 22:12:11 -0700
Subject: Access to comp.lang.python
References: 
	
Message-ID: 

In article ,
Terry Reedy   wrote:
>On 5/15/2010 6:34 PM, cjw wrote:
>>
>> The problem is that many messages seem to get unlinked from their threads.
>
>Some people have said that that is due to newreaders not tagging 
>responses properly.

It's also at least partly due to problems with mail<->news gateways and
the differing fields used to maintain threading.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From prologic at shortcircuit.net.au  Sun May 16 01:31:59 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sun, 16 May 2010 15:31:59 +1000
Subject: Access to comp.lang.python
In-Reply-To: 
References: 
	 
	
Message-ID: 

On Sun, May 16, 2010 at 3:12 PM, Aahz  wrote:
> It's also at least partly due to problems with mail<->news gateways and
> the differing fields used to maintain threading.

Some blame goes on MUAs too :)


From kwatch at gmail.com  Sun May 16 02:41:48 2010
From: kwatch at gmail.com (kwatch)
Date: Sat, 15 May 2010 23:41:48 -0700 (PDT)
Subject: [ANN] Benchmarker 1.0.0 - a samll utility for benchmarking
Message-ID: <4feb1d2e-aa4b-49b6-acd5-06f23762e1a1@11g2000prv.googlegroups.com>

Hi,

I released Benchmarker 1.0.0.
http://pypi.python.org/pypi/Benchmarker/

Benchmarker is a small library for benchmarking.


Example
-------

ex.py::

    def fib(n):
        return n <= 2 and 1 or fib(n-1) + fib(n-2)
    from benchmarker import Benchmarker
    bm = Benchmarker()  # or Benchmarker(width=30, out=sys.stderr,
header=True)
    ## Python 2.5 or later
    with bm('fib(n) (n==34)'):  fib(34)
    with bm('fib(n) (n==35)'):  fib(35)
    ## Python 2.4
    bm('fib(n) (n==34)').run(lambda: fib(34))
    bm('fib(n) (n==35)').run(lambda: fib(35))

Output::

    $ python ex.py
                                       utime      stime
total       real
    fib(n) (n==34)                    4.3700     0.0200     4.3900
4.9449
    fib(n) (n==35)                    7.1500     0.0500     7.2000
8.0643


Download
--------

http://pypi.python.org/pypi/Benchmarker/

Installation::

    ## if you have installed easy_install:
    $ sudo easy_install Benchmarker
    ## or download Benchmarker-1.0.0.tar.gz and install it
    $ wget http://pypi.python.org/packages/source/B/Benchmarker/Benchmarker-1.0.0.tar.gz
    $ tar xzf Benchmarker-1.0.0.tar.gz
    $ cd Benchmarker-1.0.0/
    $ sudo python setup.py install


License
-------

Public Domain


Copyright
---------

copyright(c) 2010 kuwata-lab.com all rights reserved


From stefan_ml at behnel.de  Sun May 16 02:55:48 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sun, 16 May 2010 08:55:48 +0200
Subject: Reading XML namespaces
In-Reply-To: <4BEF1406.7010205@v.loewis.de>
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>	
	<4BEF1406.7010205@v.loewis.de>
Message-ID: 

Martin v. Loewis, 15.05.2010 23:37:
>> BTW, I'm still not sure I understand your problem. Could you provide
>> some more details?
>
> Wouldn't it be easier if you told the OP how to access the prefix
> mappings in lxml etree, or, if this was actually not possible, admitted
> that it is actually not possible?

Well, there's an "nsmap" property on each Element that provides the mapping 
of prefixes to namespace URIs that form the scope of the Element. However, 
while this is what the OP asked for, it is not what the OP wants, simply 
because it doesn't solve the problem. Prefixes can get defined and 
redefined arbitrarily often, so there is no such thing as a 
prefix-namespace mapping "of the document". Example:

     
         
             
>>>>> 
>>>>> How can one access the namespaces define in this node?  I've done a fair
>>>>> amount of XML in Python, but haven't been able to uncover the call to
>>>>> enumerate the namespaces.
>>>>> Primarily I am using etree from lxml.
>>>> What do you need the namespaces for?
>>> One needs to know the defined namespace in order to perform xpath
>>> operations.
>> Well, yes, but unless you already know the namespace (URI), you can't know
>> what the tag you find signifies in the first place.
>> Unless, obviously, you are confusing namespaces with namespace prefixes.
>> But you don't need to know the prefixes for XPath.
>> Does this help?
>> http://codespeak.net/lxml/xpathxslt.html#namespaces-and-prefixes
>
> I know that.

I just remembered that there's also this:

http://codespeak.net/lxml/FAQ.html#how-can-i-find-out-which-namespace-prefixes-are-used-in-a-document

Stefan



From martin at v.loewis.de  Sun May 16 03:07:53 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sun, 16 May 2010 09:07:53 +0200
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>		<4BEF1406.7010205@v.loewis.de>
	
Message-ID: <4BEF99C9.5070709@v.loewis.de>

> Well, there's an "nsmap" property on each Element that provides the
> mapping of prefixes to namespace URIs that form the scope of the
> Element. However, while this is what the OP asked for, it is not what
> the OP wants, simply because it doesn't solve the problem.

Well, it solves the problem at hand: he gets some prefix mapping.

He probably could have used a hard-coded prefix mapping for the 20 or so
namespaces in his application instead (with a different set of flaws in
that approach).

> That's why I asked for more details in order to understand what the
> actual problem is that the OP is trying to solve, because the approach
> that the OP is apparently trying to follow is clearly misguided.

I completely agree. However, I recommend that we let him find out on his
 own. I suspect he has some idiomatic usage of XML, perhaps with all
namespace prefixes defined in the root element. He'll find out that his
approach is flawed in the general case when he encounters such a case.
It's probably pointless trying to convince him in the abstract.

Regards,
Martin


From stefan_ml at behnel.de  Sun May 16 03:21:37 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sun, 16 May 2010 09:21:37 +0200
Subject: Reading XML namespaces
In-Reply-To: <4BEF99C9.5070709@v.loewis.de>
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>		<4BEF1406.7010205@v.loewis.de>	
	<4BEF99C9.5070709@v.loewis.de>
Message-ID: 

Martin v. Loewis, 16.05.2010 09:07:
>> the approach that the OP is apparently trying to follow is
>> clearly misguided.
>
> I completely agree. However, I recommend that we let him find out on his
>   own. I suspect he has some idiomatic usage of XML, perhaps with all
> namespace prefixes defined in the root element. He'll find out that his
> approach is flawed in the general case when he encounters such a case.
> It's probably pointless trying to convince him in the abstract.

Probably, yes. It's just that I prefer it if broken code doesn't get 
written in the first place, rather than having to fix it later on, which in 
this case even seems to imply breaking a user visible feature. But you're 
right, let's leave the decision to the OP.

Stefan



From ninmonkeys at gmail.com  Sun May 16 03:40:07 2010
From: ninmonkeys at gmail.com (Jake b)
Date: Sun, 16 May 2010 02:40:07 -0500
Subject: parsing XML
In-Reply-To: 
References: 
	<4beec709$0$18653$4fafbaef@reader3.news.tin.it>
	
Message-ID: 

Check out Amara: http://www.xml3k.org/Amara/QuickRef

It looks promising. For a pythonic solution over sax / dom.

>>> Iter(doc.team.player)
# or
>>> doc.team.player[0].name

[ new to the list, so I'm not sure why my previous response failed. Is
it on me? Because using iPod, vs thunderbird?

However, looking at superpollo, the reply-to didn't include
python-list. Or even a valid address ?

Message below. Ty.

On Saturday, May 15, 2010, Mail Delivery Subsystem
 wrote:
> Delivery to the following recipient failed permanently:
>
>  ? ? utente at esempio.net
>
> Technical details of permanent failure:
> Google tried to deliver your message, but it was rejected by the recipient domain. We recommend contacting the other email provider for further information about the cause of this error. The error that the other server returned was: 554 554 : Relay access denied (state 14).
>
> ----- Original message -----
>
> MIME-Version: 1.0
> Received: by 10.91.208.24 with SMTP id k24mr18590agq.155.1273969257113; Sat,
>  ? ? ? ?15 May 2010 17:20:57 -0700 (PDT)
> Received: by 10.90.80.20 with HTTP; Sat, 15 May 2010 17:20:57 -0700 (PDT)
> In-Reply-To: <4beec709$0$18653$4fafbaef at reader3.news.tin.it>
> References: 
>  ? ? ? ? <4beec709$0$18653$4fafbaef at reader3.news.tin.it>
> Date: Sat, 15 May 2010 19:20:57 -0500
> Message-ID: 
> Subject: Re: parsing XML
> From: Jake b 
> To: superpollo 
> Content-Type: text/plain; charset=ISO-8859-1
>
> Check out Amara: http://www.xml3k.org/Amara/QuickRef
> For a pythonic solution over sax / dom.
>>> Iter(doc.team.player)
> or
>>> doc.team.player[0].name
>
> --
> Jake
>

--
Jake

-- 
Jake


From prologic at shortcircuit.net.au  Sun May 16 03:43:53 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sun, 16 May 2010 17:43:53 +1000
Subject: joining files
In-Reply-To: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
References: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
Message-ID: 

On Sun, May 16, 2010 at 5:02 PM, mannu jha  wrote:
> Hi,
>
> I have few files like this:
> file1:
> 22 110.1
> 33 331.5 22.7
> 5 271.9 17.2 33.4
> 4 55.1
>
> file1 has total 4 column but some of them are missing in few row.
>
> file2:
> 5 H
> 22 0
>
> file3:
> 4 T
> 5 B
> 22 C
> 121 S
>
> in all these files first column is the main source of matching their
> entries. So What I want in the output is only those entries which is coming
> in all three files.
> output required:
> 5 271.9 17.2 33.4 5 H 5 T
> 22 110.1 22 0 22 C

This had better not be yet another assignment
you're asking us to help you with ? *sigh*

Break your problem down!

Since you haven't really asked a specific question
I can't give you a specific answer.

--James


From kwatch at gmail.com  Sun May 16 03:46:55 2010
From: kwatch at gmail.com (kwatch)
Date: Sun, 16 May 2010 00:46:55 -0700 (PDT)
Subject: [ANN] Oktest 0.3.0 released - a new style testing library
Message-ID: <7e11c574-9a34-4f2f-aeb7-469b03ac5622@u3g2000prl.googlegroups.com>

Hi,
I released Oktest 0.3.0.

http://packages.python.org/Oktest/
http://pypi.python.org/pypi/Oktest/


Overview
--------

Oktest is a new-style testing library for Python.
::

    from oktest import ok
    ok (x) > 0                 # same as assert_(x > 0)
    ok (s) == 'foo'            # same as assertEqual(s, 'foo')
    ok (s) != 'foo'            # same as assertNotEqual(s, 'foo')
    ok (f).raises(ValueError)  # same as assertRaises(ValueError, f)
    ok (u'foo').is_a(unicode)  # same as assert_(isinstance(u'foo',
unicode))
    not_ok (u'foo').is_a(int)  # same as assert_(not
isinstance(u'foo', int))
    ok ('A.txt').is_file()     # same as
assert_(os.path.isfile('A.txt'))
    not_ok ('A.txt').is_dir()  # same as assert_(not
os.path.isdir('A.txt'))

You can use ok() instead of 'assertXxx()' in unittest.

Oktest requires Python 2.3 or later. Oktest is ready for Python 3.

NOTICE!! Oktest is a young project and specification may change in the
future.

See http://packages.python.org/Oktest/ for details.


Changes
-------

* enhanced 'ok (s1) == s2' to display unified diff (diff -u)
* changed to call 'before()/after()' instead of 'before_each()/
after_each()'
  (currently 'before_each()/after_each()' is also enabled but they
will be
   disabled in the future)
* improved compatibility with unittest module
* (internal) 'ValueObject' class is renamed to 'AssertionObject'
* (internal) 'Reporter#before_each()' and '#after_each()' are renamed
into
  '#before()' and '#after()'


Have fun!

--
regards,
makoto kuwata


From stefan_ml at behnel.de  Sun May 16 03:52:22 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sun, 16 May 2010 09:52:22 +0200
Subject: parsing XML
In-Reply-To: 
References: 	<4beec709$0$18653$4fafbaef@reader3.news.tin.it>	
	
Message-ID: 

Jake b, 16.05.2010 09:40:
> Check out Amara: http://www.xml3k.org/Amara/QuickRef
>
> It looks promising. For a pythonic solution over sax / dom.
>
> >>> Iter(doc.team.player)
> # or
> >>> doc.team.player[0].name

Ah, right, and there's also lxml.objectify:

     from lxml.objectify import parse

     root = parse('teamfile.xml').getroot()

     for player in root.player:
         print(player.attrib)

Prints an attribute dict for each player.

Stefan



From clp2 at rebertia.com  Sun May 16 04:18:25 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Sun, 16 May 2010 01:18:25 -0700
Subject: joining files
In-Reply-To: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
References: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
Message-ID: 

On Sun, May 16, 2010 at 12:02 AM, mannu jha  wrote:
> Hi,
>
> I have few files like this:
> file1:
> 22 110.1
> 33 331.5 22.7
> 5 271.9 17.2 33.4
> 4 55.1
>
> file1 has total 4 column but some of them are missing in few row.
>
> file2:
> 5 H
> 22 0
>
> file3:
> 4 T
> 5 B
> 22 C
> 121 S
>
> in all these files first column is the main source of matching their
> entries. So What I want in the output is only those entries which is coming
> in all three files.
> output required:
> 5 271.9 17.2 33.4 5 H 5 T
> 22 110.1 22 0 22 C

Outline of approach:
1. For each file, create a dict mapping the first number on each line
to that line.
2. Take the set intersection of the key sets of the dictionaries.
3. For each key in the intersection, get the values associated with it
from all the dicts and combine them, then output the combination.

HTH, but you're not gonna get any code out of me.
Some trivial parsing and knowledge of Python's datatypes is involved;
you should already know that or be able to readily figure it out from
the docs.

Cheers,
Chris
--

http://blog.rebertia.com


From davea at ieee.org  Sun May 16 04:25:59 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 16 May 2010 04:25:59 -0400
Subject: joining files
In-Reply-To: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
References: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
Message-ID: <4BEFAC17.6020909@ieee.org>

mannu jha wrote:
> Hi,
>
> I have few files like this:
> file1:
> 22 110.1  
> 33 331.5 22.7 
> 5 271.9 17.2 33.4
> 4 55.1 
>
> file1 has total 4 column but some of them are missing in few row.
>
> file2:
> 5 H
> 22 0
>
> file3:
> 4 T
> 5 B
> 22 C
> 121 S
>
> in all these files first column is the main source of matching their entries. So What I want in the output is only those entries which is coming in all three files.
> output required:
> 5 271.9 17.2 33.4 5 H  5 T
> 22 110.1         22 0 22 C
>
>
>   
Do you have a spec?  Have you added any code to the last assignment to 
deal with this question, and in what way isn't it working?  Why don't 
you post your code?

Generally, you seem to have lines where the first "word" is a key to the 
line.  The word appears to be distinguished by whitespace.  So finding 
the key from a line would be just   line.split()[0]    Then you build a 
dictionary from each file.  You didn't specify whether a given file 
might have multiple lines with the same key, so I'll just say to watch 
out for that, as a dictionary will cheerfully overwrite entries with new 
ones.

Since your rule on multiple files is apparently to throw out any line 
whose key isn't in all files, you'd need to make a dictionary for each 
file, then analyze all  of them in a later pass.  That pass could 
involve iterating through one of the dictionaries, and for each key 
deciding if it's in all of the others.  One way to do that is to build a 
list and run all() on it.

DaveA





From clp2 at rebertia.com  Sun May 16 04:40:07 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Sun, 16 May 2010 01:40:07 -0700
Subject: Setup global variables settings for the entire applications
In-Reply-To: 
References: 
Message-ID: 

On Fri, May 14, 2010 at 7:32 AM, AON LAZIO  wrote:
> Hi,
> ?? Say I have an application which requires a global settings for the user.
> When the user finishes setting those global variables for the app. Any class
> can use that variables (which are the same for all), something like that.
> What is the suitable mechanism for this solution?

Have a module that either contains the variables directly or contains
a configuration object that has the variables. Then just import the
module wherever you need to access the variables.

For example:

#config.py
power_user_mode = True
user_avatar = "bacon.jpg"

#elsewhere.py
import mypackage.config as config

class Foo(object):
    #...
    def whatever(self):
        self.set_avatar(config.user_avatar)
        if config.power_user_mode:
            self.show_advanced_interface()
    #...
    def something(self):
        new_avatar = self.avatar_chooser()
        config.user_avatar = new_avatar
        self.set_avatar(new_avatar)

Cheers,
Chris
--
Why bacon? Reddit.
http://blog.rebertia.com


From martin at v.loewis.de  Sun May 16 05:05:51 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sun, 16 May 2010 11:05:51 +0200
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>			<4BEF3E4D.9090404@v.loewis.de>
	
Message-ID: <4BEFB56F.9040102@v.loewis.de>

> Maybe true technically, but false in practice.  If I receive XML data
> from source XYZ or service XYZ the use of namespaces and their prefixes
> is extremely consistent [in practice] and very customary (for example:
> I've never seen the DSML namespace abbreviated as anything other than
> "dsml" and I rarely see WebDAV propfind XML use a namespace prefix other
> than "D").  The odds that a customer or vendors ERP will generate
> different namespaces and abbreviations between requests is ludicrously
> remote [I don't recall ever seeing it happen].

In that case, you could also hard-code all prefixes in your application;
no need to traverse the input document.

Regards,
Martin


From tuomas.vesterinen at iki.fi  Sun May 16 05:07:08 2010
From: tuomas.vesterinen at iki.fi (Tuomas Vesterinen)
Date: Sun, 16 May 2010 12:07:08 +0300
Subject: Using site-packages with alt-installed Python version
Message-ID: <4befb5c3$0$2537$9b536df3@news.fv.fi>

I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native 
Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.

Aplication GUI uses:
import pygtk
pygtk.require('2.0')
import gtk
import gobject

I go to:
$ cd /usr/local/lib/python2.4/site-packages

and say:
$ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py
$ sudo ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0

and try:
$ python2.4 gui_utils.py
Traceback (most recent call last):
   File "gui_utils.py", line 57, in ?
     import gtk
   File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line 
30, in ?
     import gobject as _gobject
   File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py", 
line 26, in ?
     from glib import spawn_async, idle_add, timeout_add, 
timeout_add_seconds, \
   File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line 
22, in ?
     from glib._glib import *
ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol: 
_PyObject_CallFunction_SizeT

What I should say more to get access to the GTK?

Tuomas Vesterinen


From paul.hankin at gmail.com  Sun May 16 07:16:41 2010
From: paul.hankin at gmail.com (Paul Hankin)
Date: Sun, 16 May 2010 04:16:41 -0700 (PDT)
Subject: huh??? weird problem
References: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
	
Message-ID: 

On May 15, 3:41?am, Dave Angel  wrote:
> cerr wrote:
> > Hi There,
>
> > I got following code:
> > start=time.time()
> > print 'warnTimeout '+str(WarnTimeout)
> > print 'critTimeout '+str(CritTimeout)
> > print 'start',str(start)
> > while wait:
> > ? ? passed = ?time.time()-start
> > ? ? print 'passed ',str(passed)
> > ? ? if passed >= WarnTimeout:
> > ? ? ? print ' Warning!'
> > ?...
> > ...
> > ...
> > which basically means that the loops should go until the warning time
> > has been reached and then i want it to print 'warning!' and execute
> > some warning code. But weirdly enough i get following screen output:
> > warnTimeout 3
> > critTimeout 5
> > start 1273882010.43
> > passed ?7.60555267334e-05
> > passed ?0.998471975327
> > passed ?1.99847102165
> > passed ?2.9984691143
> > passed ?3.99847006798
> > passed ?4.998472929
> > ...
> > ...
> > any one a clue why after 3 seconds it doesn't go into the the if an
> > print 'Warning!'? That's odd... :o Crazy, what am i not seeing? :(
>
> we're not seeing all the relevant code. ?While I can ignore the missing
> import, I don't see any creation of the variables WarnTimeout and
> CritTimeout. ?Simplest explanation that fits your sample run is that
> they are not of type float.

Yes, and most likely str. A good debugging tip is to use repr rather
than str to print out debugging messages.

--
Paul Hankin


From alister.ware at ntlworld.com  Sun May 16 07:38:12 2010
From: alister.ware at ntlworld.com (Alister)
Date: Sun, 16 May 2010 11:38:12 GMT
Subject: Using site-packages with alt-installed Python version
References: <4befb5c3$0$2537$9b536df3@news.fv.fi>
Message-ID: 

On Sun, 16 May 2010 12:07:08 +0300, Tuomas Vesterinen wrote:

> I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native
> Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.
> 
> Aplication GUI uses:
> import pygtk
> pygtk.require('2.0')
> import gtk
> import gobject
> 
> I go to:
> $ cd /usr/local/lib/python2.4/site-packages
> 
> and say:
> $ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py $ sudo
> ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0
> 
> and try:
> $ python2.4 gui_utils.py
> Traceback (most recent call last):
>    File "gui_utils.py", line 57, in ?
>      import gtk
>    File
> "/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line
> 30, in ?
>      import gobject as _gobject
>    File
> "/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py",
> line 26, in ?
>      from glib import spawn_async, idle_add, timeout_add,
> timeout_add_seconds, \
>    File
> "/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line
> 22, in ?
>      from glib._glib import *
> ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol:
> _PyObject_CallFunction_SizeT
> 
> What I should say more to get access to the GTK?
> 
> Tuomas Vesterinen

I am not a great expert on this But I think you need to use the Redhat 
alternatives system to switch between versions rather than trying to 
change things manually.

as i understand it the Alternatives system sets up and changes various 
symlinks to ensure everything works correctly. 



-- 
"When the going gets tough, the tough get empirical."
		-- Jon Carroll


From mannu_0523 at rediffmail.com  Sun May 16 09:10:19 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 16 May 2010 13:10:19 -0000
Subject: =?utf-8?B?Rnc6IFJlOiBSZTogam9pbmluZyBmaWxlcw==?=
Message-ID: <1274015375.S.6197.18004.f4mail-235-133.rediffmail.com.1274015419.6048@webmail.rediffmail.com>

Note: Forwarded message attached

-- Original Message --

From: "mannu jha"mannu_0523 at rediffmail.com
To: davea at ieee.org
Subject: Re: Re: joining files
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
An embedded message was scrubbed...
From: "mannu jha"
Subject: Re: Re: joining files
Date: no date
Size: 6032
URL: 

From e_d_k at yahoo.com  Sun May 16 09:40:30 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sun, 16 May 2010 06:40:30 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <468368.26117.qm@web58701.mail.re1.yahoo.com>

--- On Sat, 5/15/10, Robert Kern  wrote:

> From: Robert Kern 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Saturday, May 15, 2010, 1:10 PM
> On 2010-05-14 21:37 , Steven D'Aprano
> wrote:
> > On Fri, 14 May 2010 06:42:31 -0700, Ed Keith wrote:
> > 
> >> I am not a lawyer, but as I understand the LGPL,
> If I give someone
> >> something that used any LGPLed code I must give
> them the ability to
> >> relink it with any future releases of the LGPLed
> code. I think that
> >> means that I need to give them a linker and teach
> them how to use it,
> >> and I do not want to go there.
> > 
> > Surely you're joking?
> > 
> > Does this mean that if they lose their hands in an
> accident, you have to
> > come sit at their computer and do their typing?
> > 
> > The LGPL and GPL don't grant people "the ability" to
> do anything, since
> > that's not within our power to grant. Some people
> don't want to, or
> > can't, program, or don't have time. It's not like the
> LGPL is the bite of
> > a radioactive spider that can grant superpowers. It is
> a licence which
> > grants *permissions*.
> 
> No, the LGPL requires you to do something extra to enable
> your users to be able to relink your program. You need to
> provide the ability to do this, up to some unspecified and
> untested limit of reasonableness (your example is obviously
> beyond the limit of reasonableness). You can't just give
> them, say, a statically linked program and nothing else. You
> can't require for-fee, proprietary linkers. This is usually
> not hard to do (just give them unlinked .o or .obj files and
> a Makefile or project file), but it is *not* just a matter
> of granting permissions.
> 
> But you're right, you don't have to teach them how to do
> it.
> 
> -- Robert Kern
> 
> "I have come to believe that the whole world is an enigma,
> a harmless enigma
>  that is made terrible by our own mad attempt to interpret
> it as though it had
>  an underlying truth."
> ? -- Umberto Eco
> 
> -- http://mail.python.org/mailman/listinfo/python-list
> 

But most of my clients run MS-Windows, and I do most of my development in C++, so they would need to use a proprietary linker.

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From davea at ieee.org  Sun May 16 10:04:42 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 16 May 2010 10:04:42 -0400
Subject: joining files
In-Reply-To: <1273998151.S.3807.41729.H.TkRhdmUgQW5nZWwAUmU6IGpvaW5pbmcgZmlsZXM_.f4-234-213.old.1274015374.26493@webmail.rediffmail.com>
References: <1273998151.S.3807.41729.H.TkRhdmUgQW5nZWwAUmU6IGpvaW5pbmcgZmlsZXM_.f4-234-213.old.1274015374.26493@webmail.rediffmail.com>
Message-ID: <4BEFFB7A.2020404@ieee.org>

(You forgot to include the python-list in your response.  So it only 
went to me.  Normally, you just do reply-all to the message)

mannu jha wrote:
> On Sun, 16 May 2010 13:52:31 +0530  wrote
>   
>> mannu jha wrote:
>>     
>
>   
>> Hi,
>>     
>
>   
>
>   
>> I have few files like this:
>> file1:
>> 22 110.1 
>> 33 331.5 22.7 
>> 5 271.9 17.2 33.4
>> 4 55.1 
>>     
>
>   
>> file1 has total 4 column but some of them are missing in few row.
>>     
>
>   
>> file2:
>> 5 H
>> 22 0
>>     
>
>   
>> file3:
>> 4 T
>> 5 B
>> 22 C
>> 121 S
>>     
>
>   
>
>   
>> in all these files first column is the main source of matching their entries. So What I want in the output is only those entries which is coming in all three files.
>>     
>
>   
>> output required:
>>     
>
>   
>> 5 271.9 17.2 33.4 5 H 5 T
>> 22 110.1     22 0 22 C
>>     
>
>   
> I am trying with this :
>
> from collections import defaultdict
>
> def merge(sources):
>     blanks = [blank for items, blank, keyfunc in sources]
>     d = defaultdict(lambda: blanks[:])
>     for index, (items, blank, keyfunc) in enumerate(sources):
>         for item in items:
>             d[keyfunc(item)][index] = item
>     for key in sorted(d):
>         yield d[key]
>
> if __name__ == "__main__":
>     a = open("input1.txt")
>     
>     c = open("input2.txt")
>
>     def key(line):
>         return line[:2]
>     def source(stream, blank="", key=key):
>         return (line.strip() for line in stream), blank, key
>     for m in merge([source(x) for x in [a,c]]):
>         print "|".join(c.ljust(10) for c in m)
>
> but with input1.txt:
> 187    7.79   122.27   54.37   4.26   179.75
> 194    8.00   121.23   54.79   4.12   180.06
> 15    8.45   119.04   55.02   4.08   178.89
> 176    7.78   118.68   54.57   4.20   181.06
> 180    7.50   119.21   53.93      179.80
> 190    7.58   120.44   54.62   4.25   180.02
> 152    8.39   120.63   55.10   4.15   179.10
> 154    7.79   119.62   54.47   4.22   180.46
> 175    8.42   120.50   55.31   4.04   180.33
> and input2.txt:
>  15   H 
>  37   H 
>  95   T
> 124   H 
> 130   H 
> 152   H 
> 154   H 
> 158   H 
> 164   H
> 175   H 
> 176   H 
> 180   H
> 187   H 
> 190   T
> 194   C
> 196   H 
> 207   H 
> 210   H 
> 232   H 
> it is giving output as:
>           |
>           |124   H
>           |130   H
> 154    7.79   119.62   54.47   4.22   180.46|158   H
>           |164   H
> 175    8.42   120.50   55.31   4.04   180.33|176   H
> 180    7.50   119.21   53.93      179.80|187   H
> 190    7.58   120.44   54.62   4.25   180.02|196   H
>           |207   H
>           |210   H
>           |232   H
>           |37   H
>           |95   T
> so it not matching it properly, can anyone please suggest where I am doing mistake.
>
>
>
>   
I'm about to travel all day, so my response will be quite brief.

Not sure what you mean by the blank and key values that source() takes, 
since they're just passed on to its return value.

I don't see any place where you compare the items from the various 
files, so you aren't checking if an item is in multiple files.

DaveA



From e_d_k at yahoo.com  Sun May 16 10:19:14 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sun, 16 May 2010 07:19:14 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <331306.35765.qm@web58706.mail.re1.yahoo.com>

--- On Sat, 5/15/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Saturday, May 15, 2010, 11:06 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > On Fri, 5/14/10, Lawrence D'Oliveiro
> > 
> wrote:
> > 
> >> In message ,
> >> Ed Keith wrote:
> >> 
> >>> Yes, under the GPL every one has one set of
> freedoms,
> >>> under the MIT or Boost license every one has
> more freedoms. Under other
> >>> licenses they have fewer freedoms.
> >> 
> >> But what about the ?freedom? to take away
> other
> >> people?s freedom? Is that really ?freedom??
> > 
> > Yes.
> 
> But that?s a ?freedom? that non-GPL licences do not
> give you, that the GPL 
> does. So which licence gives you more ?freedoms?,
> again?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 


????? You just answered your own question. The The GPL does not give you the freedoms to take away other people freedom, so the the less restrictive license have less restrictions (which is why they are called "less restrictive" by the way) "Less restrictions" is a synonym for "more freedoms". To the extent that something is "restricted" it is not "free". To the extent which something if "free" it is not "restricted". 

There is clearly some kind of communication problem here. Either were are speaking different languages with some faulty transaction program interviewing, or one of is is either stupid or senile (seems a bit early for me, but it is possible); or you are being disingenuous. 

If you type the word 'restrict' into thesaurus.com you will get the following antonyms: enlarge, expand, free, let go, release, Note the second word on the list. Please do not take my word for it, try it yourself. Try other sites, if you think I may have rigged this one.

     -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Sun May 16 10:25:53 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sun, 16 May 2010 07:25:53 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <216371.45903.qm@web58703.mail.re1.yahoo.com>


--- On Sat, 5/15/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Saturday, May 15, 2010, 11:09 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > But if my client give someone else a copy of the
> binary I gave them, they
> > are now in violation.
> 
> Why would they be in violation? It seems to me a violation
> would only occur 
> if someone asked them for the source, and they refused.
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

No, the GPL makes it clear that the responsibly is on the distributor to either supply the source or written notice, Caveat venditor. The violation exists regardless of whether or not the recipient makes a request.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From aahz at pythoncraft.com  Sun May 16 10:48:06 2010
From: aahz at pythoncraft.com (Aahz)
Date: 16 May 2010 07:48:06 -0700
Subject: joining files
References: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
	
Message-ID: 

In article ,
Chris Rebert   wrote:
>
>--
>

That's not funny.  I'm sure I'd have little difficulty finding poor
programmers of whatever demographic groups you belong to.  Or perhaps you
haven't noticed that PEBKACs are everywhere?
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From cjw at ncf.ca  Sun May 16 11:29:44 2010
From: cjw at ncf.ca (cjw)
Date: Sun, 16 May 2010 11:29:44 -0400
Subject: Access to comp.lang.python
In-Reply-To: 
References: 	
	
	
Message-ID: 

On 16-May-10 01:31 AM, James Mills wrote:
> On Sun, May 16, 2010 at 3:12 PM, Aahz  wrote:
>> It's also at least partly due to problems with mail<->news gateways and
>> the differing fields used to maintain threading.
>
> Some blame goes on MUAs too :)

Thanks for the responses.

Is it possible to connect a newsreader to gmane?  Or is web access required?

Is Thunderbird known to have problems?

Colin W


From invalid at invalid.invalid  Sun May 16 11:35:08 2010
From: invalid at invalid.invalid (Grant Edwards)
Date: Sun, 16 May 2010 15:35:08 +0000 (UTC)
Subject: Access to comp.lang.python
References: 
	
	
	
	
Message-ID: 

On 2010-05-16, cjw  wrote:
> On 16-May-10 01:31 AM, James Mills wrote:
>> On Sun, May 16, 2010 at 3:12 PM, Aahz  wrote:
>>> It's also at least partly due to problems with mail<->news gateways and
>>> the differing fields used to maintain threading.
>>
>> Some blame goes on MUAs too :)
>
> Thanks for the responses.
>
> Is it possible to connect a newsreader to gmane?

nntp://news.gmane.org/

-- 
Grant



From stefan_ml at behnel.de  Sun May 16 11:55:26 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sun, 16 May 2010 17:55:26 +0200
Subject: Reading XML namespaces
In-Reply-To: <4BEFB56F.9040102@v.loewis.de>
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>			<4BEF3E4D.9090404@v.loewis.de>	
	<4BEFB56F.9040102@v.loewis.de>
Message-ID: 

Martin v. Loewis, 16.05.2010 11:05:
>> Maybe true technically, but false in practice.  If I receive XML data
>> from source XYZ or service XYZ the use of namespaces and their prefixes
>> is extremely consistent [in practice] and very customary (for example:
>> I've never seen the DSML namespace abbreviated as anything other than
>> "dsml" and I rarely see WebDAV propfind XML use a namespace prefix other
>> than "D").  The odds that a customer or vendors ERP will generate
>> different namespaces and abbreviations between requests is ludicrously
>> remote [I don't recall ever seeing it happen].
>
> In that case, you could also hard-code all prefixes in your application;
> no need to traverse the input document.

+1. Hard-coding the prefixes is the best way to make the interface of your 
code consistent and predictable.

Stefan



From john at castleamber.com  Sun May 16 12:17:36 2010
From: john at castleamber.com (John Bokma)
Date: Sun, 16 May 2010 11:17:36 -0500
Subject: Access to comp.lang.python
References: 
	
	
	
	
Message-ID: <87y6fjhlcv.fsf@castleamber.com>

cjw  writes:

> Is it possible to connect a newsreader to gmane?

http://johnbokma.com/mexit/2005/01/14/gmane-mail-to-news.html

> Is Thunderbird known to have problems?

It worked good for me, but that was 5+ years ago. (Time flies)

-- 
John Bokma                                                               j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development


From jf_byrnes at comcast.net  Sun May 16 12:47:22 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Sun, 16 May 2010 11:47:22 -0500
Subject: Access to comp.lang.python
In-Reply-To: 
References: 				
	
Message-ID: <4BF0219A.3080004@comcast.net>

Grant Edwards wrote:
> On 2010-05-16, cjw  wrote:
>> On 16-May-10 01:31 AM, James Mills wrote:
>>> On Sun, May 16, 2010 at 3:12 PM, Aahz   wrote:
>>>> It's also at least partly due to problems with mail<->news gateways and
>>>> the differing fields used to maintain threading.
>>>
>>> Some blame goes on MUAs too :)
>>
>> Thanks for the responses.
>>
>> Is it possible to connect a newsreader to gmane?
>
> nntp://news.gmane.org/
>

Could someone please explain how to subscribe to this list on gmane.  I 
subscribe to a couple of other groups there but can't find this one.

Regards,  Jim


From tlikonen at iki.fi  Sun May 16 13:05:28 2010
From: tlikonen at iki.fi (Teemu Likonen)
Date: Sun, 16 May 2010 20:05:28 +0300
Subject: Object-oriented (was: Is Python a functional programming language?)
References: 
	
	
Message-ID: <87ljbj6alj.fsf_-_@mithlond.arda>

* 2010-05-15 09:42 (-0700), travis wrote:

> PS: Why do people call LISP object-oriented?  Are they smoking crack?
>     No classes, no methods, no member variables... WTF?

Maybe because Common Lisp has a strong support for object-oriented
programming.


Peter Seibel: Practical Common Lisp

    Generic functions and methods (chapter 16)
    http://www.gigamonkeys.com/book/object-reorientation-generic-functions.html

    Classes (chapter 17)
    http://www.gigamonkeys.com/book/object-reorientation-classes.html

Paul Graham: On Lisp

    Object-Oriented Lisp (chapter 25)
    http://www.bookshelf.jp/texi/onlisp/onlisp_26.html#SEC156

Wikipedia: Common Lisp Object System

    http://en.wikipedia.org/wiki/Common_Lisp_Object_System


From thom1948 at gmail.com  Sun May 16 13:36:16 2010
From: thom1948 at gmail.com (Thomas)
Date: Sun, 16 May 2010 10:36:16 -0700 (PDT)
Subject: Updating values in a dictionary
Message-ID: 

Greetings

I am having a darn awful time trying to update a matrix:

row = dict([(x,0) for x in range(3)])
matrix = dict([(x,row) for x in range(-3,4,1)])

matrix[2][1] += 1
matrix[-1][2] += 1

"""
Got: a 1 in all col 1 and 2
{-3: {0: 0, 1: 1, 2: 1},
 -2: {0: 0, 1: 1, 2: 1},
 -1: {0: 0, 1: 1, 2: 1},
  0: {0: 0, 1: 1, 2: 1},
  1: {0: 0, 1: 1, 2: 1},
  2: {0: 0, 1: 1, 2: 1},
  3: {0: 0, 1: 1, 2: 1}}
Expected: a 1 in row 2 col 1 and row -1 col 2
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
  0: {0: 0, 1: 0, 2: 0},
  1: {0: 0, 1: 0, 2: 0},
  2: {0: 0, 1: 1, 2: 0},
  3: {0: 0, 1: 0, 2: 0}}
"""

I must be doing something wrong. Researched and researched. Nothing
clicks.


From half.italian at gmail.com  Sun May 16 13:41:54 2010
From: half.italian at gmail.com (Sean DiZazzo)
Date: Sun, 16 May 2010 10:41:54 -0700 (PDT)
Subject: recursively remove all the directories and files which begin with
	'.'
References: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>
	
	<67827508-ddda-44e8-8b88-aae4f78e23da@o8g2000yqo.googlegroups.com>
Message-ID: <9609b853-c7b1-4357-aaf0-b173aebc6879@11g2000prv.googlegroups.com>

On May 14, 8:27?am, albert kao  wrote:
> On May 14, 11:01?am, J  wrote:
>
>
>
> > On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>
> > > C:\python>rmdir.py
> > > C:\test\com.comp.hw.prod.proj.war\bin
> > > ['.svn', 'com']
> > > d .svn
> > > dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
> > > Traceback (most recent call last):
> > > ?File "C:\python\rmdir.py", line 14, in 
> > > ? ?rmtree(os.path.join(curdir, d))
> > > ?File "C:\Python31\lib\shutil.py", line 235, in rmtree
> > > ? ?onerror(os.remove, fullname, sys.exc_info())
> > > ?File "C:\Python31\lib\shutil.py", line 233, in rmtree
> > > ? ?os.remove(fullname)
> > > WindowsError: [Error 5] Access is denied: 'C:\\test\
> > > \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
>
> > You don't have permissions to remove the subdir or file entries in the
> > .svn directory...
>
> > Maybe that file is still open, or still has a lock attached to it?
>
> I reboot my windows computer and run this script as administrator.
> Do my script has a bug?

Are the directory or files marked as read only?

See this recipe and the comment from Chad Stryker:

http://code.activestate.com/recipes/193736-clean-up-a-directory-tree/

"Although it is true you can use shutil.rmtree() in many cases, there
are some cases where it does not work. For example, files that are
marked read-only under Windows cannot be deleted by shutil.rmtree().
By importing the win32api and win32con modules from PyWin32 and adding
line like "win32api.SetFileAttributes(path,
win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this
obstacle can be overcome."

It might not be your problem, but if it is, this had me stumped for a
few weeks before I found this comment!

~Sean


From clp2 at rebertia.com  Sun May 16 13:48:24 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Sun, 16 May 2010 10:48:24 -0700
Subject: Updating values in a dictionary
In-Reply-To: 
References: 
Message-ID: 

On Sun, May 16, 2010 at 10:36 AM, Thomas  wrote:
> Greetings
>
> I am having a darn awful time trying to update a matrix:
>
> row = dict([(x,0) for x in range(3)])
> matrix = dict([(x,row) for x in range(-3,4,1)])

All the columns refer to the very same row dict (`row` obviously).
Python doesn't do any copying unless you explicitly request it.

Try:
matrix = dict([(x, dict([(x,0) for x in range(3)]) ) for x in range(-3,4,1)])

This way, the row-creation code gets called for each column and thus
fresh row dicts are created rather than all just referencing the exact
same one row dict.
Nested comprehensions may be hard to understand, so you may wish to
write it using a function instead:

def make_row():
    return dict([(x,0) for x in range(3)])

matrix = dict([(x,make_row()) for x in range(-3,4,1)])

See also http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list

Cheers,
Chris
--
http://blog.rebertia.com


From aonlazio at gmail.com  Sun May 16 13:50:29 2010
From: aonlazio at gmail.com (AON LAZIO)
Date: Sun, 16 May 2010 13:50:29 -0400
Subject: Global variables for python applications
Message-ID: 

Hi,
   How can I set up global variables for the entire python applications?
Like I can call and set this variables in any .py files.
   Think of it as a global variable in a single .py file but this is for the
entire application.
   Thanks

-- 
Aonlazio
'Peace is always the way.' NW
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From utente at esempio.net  Sun May 16 13:51:41 2010
From: utente at esempio.net (superpollo)
Date: Sun, 16 May 2010 19:51:41 +0200
Subject: Updating values in a dictionary
In-Reply-To: 
References: 
Message-ID: <4bf030ae$0$40284$4fafbaef@reader2.news.tin.it>

Thomas ha scritto:
> Greetings
> 
> I am having a darn awful time trying to update a matrix:
> 
> row = dict([(x,0) for x in range(3)])
> matrix = dict([(x,row) for x in range(-3,4,1)])
> 
> matrix[2][1] += 1
> matrix[-1][2] += 1
> 
> """
> Got: a 1 in all col 1 and 2
> {-3: {0: 0, 1: 1, 2: 1},
>  -2: {0: 0, 1: 1, 2: 1},
>  -1: {0: 0, 1: 1, 2: 1},
>   0: {0: 0, 1: 1, 2: 1},
>   1: {0: 0, 1: 1, 2: 1},
>   2: {0: 0, 1: 1, 2: 1},
>   3: {0: 0, 1: 1, 2: 1}}
> Expected: a 1 in row 2 col 1 and row -1 col 2
> {-3: {0: 0, 1: 0, 2: 0},
>  -2: {0: 0, 1: 0, 2: 0},
>  -1: {0: 0, 1: 0, 2: 1},
>   0: {0: 0, 1: 0, 2: 0},
>   1: {0: 0, 1: 0, 2: 0},
>   2: {0: 0, 1: 1, 2: 0},
>   3: {0: 0, 1: 0, 2: 0}}
> """
> 
> I must be doing something wrong. Researched and researched. Nothing
> clicks.

clone the row:

 >>> row = dict([(x,0) for x in range(3)])
 >>> import copy
 >>> matrix = dict([(x,copy.copy(row)) for x in range(-3,4,1)])
 >>> matrix[2][1] += 1
 >>> matrix[-1][2] += 1
 >>> import pprint
 >>> pp = pprint.PrettyPrinter()
 >>> pp.pprint(matrix)
{-3: {0: 0, 1: 0, 2: 0},
  -2: {0: 0, 1: 0, 2: 0},
  -1: {0: 0, 1: 0, 2: 1},
  0: {0: 0, 1: 0, 2: 0},
  1: {0: 0, 1: 0, 2: 0},
  2: {0: 0, 1: 1, 2: 0},
  3: {0: 0, 1: 0, 2: 0}}
 >>>

bye



From __peter__ at web.de  Sun May 16 13:58:13 2010
From: __peter__ at web.de (Peter Otten)
Date: Sun, 16 May 2010 19:58:13 +0200
Subject: Updating values in a dictionary
References: 
	
Message-ID: 

Chris Rebert wrote:

> Nested comprehensions may be hard to understand, so you may wish to
> write it using a function instead:
> 
> def make_row():
> return dict([(x,0) for x in range(3)])
> 
> matrix = dict([(x,make_row()) for x in range(-3,4,1)])

Another way to skin the cat:

>>> row = dict.fromkeys(range(3), 0)
>>> matrix = dict((x, row.copy()) for x in range(-3, 4))
>>> matrix[2][1] += 1
>>> matrix[-1][2] += 1
>>> from pprint import pprint
>>> pprint(matrix)
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
 0: {0: 0, 1: 0, 2: 0},
 1: {0: 0, 1: 0, 2: 0},
 2: {0: 0, 1: 1, 2: 0},
 3: {0: 0, 1: 0, 2: 0}}



From prologic at shortcircuit.net.au  Sun May 16 13:58:18 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 17 May 2010 03:58:18 +1000
Subject: Global variables for python applications
In-Reply-To: 
References: 
Message-ID: 

On Mon, May 17, 2010 at 3:50 AM, AON LAZIO  wrote:
> Hi,
> ?? How can I set up global variables for the entire python applications?
> Like I can call and set this variables in any .py files.
> ?? Think of it as a global variable in a single .py file but this is for the
> entire application.

If you have to use global variables in your application you are
designing it WRONG!

Python has powerful support for object orientated programming. Use it!

I highly recommend the Python tutorial - especially the section on classes.

--James


From irmen-NOSPAM- at xs4all.nl  Sun May 16 13:59:21 2010
From: irmen-NOSPAM- at xs4all.nl (Irmen de Jong)
Date: Sun, 16 May 2010 19:59:21 +0200
Subject: recursively remove all the directories and files which begin
	with  '.'
In-Reply-To: <9609b853-c7b1-4357-aaf0-b173aebc6879@11g2000prv.googlegroups.com>
References: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>
	
	<67827508-ddda-44e8-8b88-aae4f78e23da@o8g2000yqo.googlegroups.com>
	<9609b853-c7b1-4357-aaf0-b173aebc6879@11g2000prv.googlegroups.com>
Message-ID: <4bf03277$0$22938$e4fe514c@news.xs4all.nl>

On 16-5-2010 19:41, Sean DiZazzo wrote:
> On May 14, 8:27 am, albert kao  wrote:
>> On May 14, 11:01 am, J  wrote:
>>
>>
>>
>>> On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>>
>>>> C:\python>rmdir.py
>>>> C:\test\com.comp.hw.prod.proj.war\bin
>>>> ['.svn', 'com']
>>>> d .svn
>>>> dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
>>>> Traceback (most recent call last):
>>>>   File "C:\python\rmdir.py", line 14, in
>>>>     rmtree(os.path.join(curdir, d))
>>>>   File "C:\Python31\lib\shutil.py", line 235, in rmtree
>>>>     onerror(os.remove, fullname, sys.exc_info())
>>>>   File "C:\Python31\lib\shutil.py", line 233, in rmtree
>>>>     os.remove(fullname)
>>>> WindowsError: [Error 5] Access is denied: 'C:\\test\
>>>> \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>>
>>>> --
>>>> http://mail.python.org/mailman/listinfo/python-list
>>
>>> You don't have permissions to remove the subdir or file entries in the
>>> .svn directory...
>>
>>> Maybe that file is still open, or still has a lock attached to it?
>>
>> I reboot my windows computer and run this script as administrator.
>> Do my script has a bug?
>
> Are the directory or files marked as read only?
>
> See this recipe and the comment from Chad Stryker:
>
> http://code.activestate.com/recipes/193736-clean-up-a-directory-tree/
>
> "Although it is true you can use shutil.rmtree() in many cases, there
> are some cases where it does not work. For example, files that are
> marked read-only under Windows cannot be deleted by shutil.rmtree().
> By importing the win32api and win32con modules from PyWin32 and adding
> line like "win32api.SetFileAttributes(path,
> win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this
> obstacle can be overcome."
>
> It might not be your problem, but if it is, this had me stumped for a
> few weeks before I found this comment!
>
> ~Sean

You should be able to do this with os.chmod as well (no extra modules 
required). I'm not sure what the mode should be though. Perhaps 0777 
does the trick.

-irmen



From krister.svanlund at gmail.com  Sun May 16 14:00:46 2010
From: krister.svanlund at gmail.com (Krister Svanlund)
Date: Sun, 16 May 2010 20:00:46 +0200
Subject: Global variables for python applications
In-Reply-To: 
References: 
Message-ID: 

On Sun, May 16, 2010 at 7:50 PM, AON LAZIO  wrote:
> Hi,
> ?? How can I set up global variables for the entire python applications?
> Like I can call and set this variables in any .py files.
> ?? Think of it as a global variable in a single .py file but this is for the
> entire application.
> ?? Thanks
>
> --
> Aonlazio
> 'Peace is always the way.' NW

First: Do NOT use global variables, it is bad practice and will
eventually give you loads of s**t.

But if you want to create global variables in python I do believe it
is possible to specify them in a .py file and then simply import it as
a module in your application. If you change one value in a module the
change will be available in all places you imported that module in.


From clp2 at rebertia.com  Sun May 16 14:01:15 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Sun, 16 May 2010 11:01:15 -0700
Subject: Global variables for python applications
In-Reply-To: 
References: 
Message-ID: 

On Sun, May 16, 2010 at 10:50 AM, AON LAZIO  wrote:
> Hi,
> ?? How can I set up global variables for the entire python applications?
> Like I can call and set this variables in any .py files.
> ?? Think of it as a global variable in a single .py file but this is for the
> entire application.

Thankfully, there is no such thing (can you say spaghetti code?). The
closest approximation, as I said in my previous reply, is to use the
namespace of a designated module for this purpose, and import that
module wherever you need to access/modify these "superglobal"
variables.

Example:
#g.py:
#this module exists to hold superglobal vars
global1 = "foo"
global2 = "bar"


#elsewhere.py:
#this is some other module in the same program
import mypackage.g as g

print "global #1 = ", g.global1
print "global #2 =", g.global2
g.global1 = "baz" # modify a superglobal
g.global3 = "qux" # create a new superglobal


Cheers,
Chris
--
http://blog.rebertia.com


From tuomas.vesterinen at iki.fi  Sun May 16 14:01:17 2010
From: tuomas.vesterinen at iki.fi (Tuomas Vesterinen)
Date: Sun, 16 May 2010 21:01:17 +0300
Subject: joining files
In-Reply-To: 
References: <1273998151.S.3807.41729.H.TkRhdmUgQW5nZWwAUmU6IGpvaW5pbmcgZmlsZXM_.f4-234-213.old.1274015374.26493@webmail.rediffmail.com>
	
Message-ID: <4bf03335$0$11843$9b536df3@news.fv.fi>

On 05/16/2010 05:04 PM, Dave Angel wrote:
> (You forgot to include the python-list in your response.  So it only
> went to me. Normally, you just do reply-all to the message)
>
> mannu jha wrote:
>> On Sun, 16 May 2010 13:52:31 +0530 wrote
>>> mannu jha wrote:
>>
>>> Hi,
>>
>>
>>> I have few files like this:
>>> file1:
>>> 22 110.1 33 331.5 22.7 5 271.9 17.2 33.4
>>> 4 55.1
>>
>>> file1 has total 4 column but some of them are missing in few row.
>>
>>> file2:
>>> 5 H
>>> 22 0
>>
>>> file3:
>>> 4 T
>>> 5 B
>>> 22 C
>>> 121 S
>>
>>
>>> in all these files first column is the main source of matching their
>>> entries. So What I want in the output is only those entries which is
>>> coming in all three files.
>>
>>> output required:
>>
>>> 5 271.9 17.2 33.4 5 H 5 T
>>> 22 110.1 22 0 22 C
>>
>> I am trying with this :
>>
>> from collections import defaultdict
>>
>> def merge(sources):
>> blanks = [blank for items, blank, keyfunc in sources]
>> d = defaultdict(lambda: blanks[:])
>> for index, (items, blank, keyfunc) in enumerate(sources):
>> for item in items:
>> d[keyfunc(item)][index] = item
>> for key in sorted(d):
>> yield d[key]
>>
>> if __name__ == "__main__":
>> a = open("input1.txt")
>> c = open("input2.txt")
>>
>> def key(line):
>> return line[:2]
>> def source(stream, blank="", key=key):
>> return (line.strip() for line in stream), blank, key
>> for m in merge([source(x) for x in [a,c]]):
>> print "|".join(c.ljust(10) for c in m)
>>
>> but with input1.txt:
>> 187 7.79 122.27 54.37 4.26 179.75
>> 194 8.00 121.23 54.79 4.12 180.06
>> 15 8.45 119.04 55.02 4.08 178.89
>> 176 7.78 118.68 54.57 4.20 181.06
>> 180 7.50 119.21 53.93 179.80
>> 190 7.58 120.44 54.62 4.25 180.02
>> 152 8.39 120.63 55.10 4.15 179.10
>> 154 7.79 119.62 54.47 4.22 180.46
>> 175 8.42 120.50 55.31 4.04 180.33
>> and input2.txt:
>> 15 H 37 H 95 T
>> 124 H 130 H 152 H 154 H 158 H 164 H
>> 175 H 176 H 180 H
>> 187 H 190 T
>> 194 C
>> 196 H 207 H 210 H 232 H it is giving output as:
>> |
>> |124 H
>> |130 H
>> 154 7.79 119.62 54.47 4.22 180.46|158 H
>> |164 H
>> 175 8.42 120.50 55.31 4.04 180.33|176 H
>> 180 7.50 119.21 53.93 179.80|187 H
>> 190 7.58 120.44 54.62 4.25 180.02|196 H
>> |207 H
>> |210 H
>> |232 H
>> |37 H
>> |95 T
>> so it not matching it properly, can anyone please suggest where I am
>> doing mistake.
>>
>>
>>
> I'm about to travel all day, so my response will be quite brief.
>
> Not sure what you mean by the blank and key values that source() takes,
> since they're just passed on to its return value.
>
> I don't see any place where you compare the items from the various
> files, so you aren't checking if an item is in multiple files.
>
> DaveA
>
import os

def merge_sources(sources):
     # sources is a list of tuples (source_name, source_data)
     data = []
     keysets = []
     for nme, sce in sources:
         lines = {}
         for line in sce.split(os.linesep):
             lst = line.split()
             lines[lst[0]] = (nme, lst)
         keysets.append(set(lines.keys()))
         data.append(lines)
     common_keys = keysets[0]
     for keys in keysets[1:]:
         common_keys = common_keys.intersection(keys)
     result = {}
     for key in common_keys:
         result[key] = dict(d[key] for d in data if key in d)
     return result

if __name__ == "__main__":
     # Your test files here are replaced by local strings
     print merge_sources([("file1", file1), ("file2", file2), ("file3", 
file3)])
     print merge_sources([("input1", input1), ("input2", input2)])

Test_results = '''
{'22': {'file3': ['22', 'C'],
         'file2': ['22', '0'],
         'file1': ['22', '110.1', '33', '331.5', '22.7', '5', '271.9',
                   '17.2', '33.4']}}

{'194': {'input2': ['194', 'C'],
          'input1': ['194', '8.00', '121.23', '54.79', '4.12',
                     '180.06']},
  '175': {'input2': ['175', 'H', '176', 'H', '180', 'H'],
          'input1': ['175', '8.42', '120.50', '55.31', '4.04',
                     '180.33']},
   '15': {'input2': ['15', 'H', '37', 'H', '95', 'T'],
          'input1': ['15', '8.45', '119.04', '55.02', '4.08',
                     '178.89']},
  '187': {'input2': ['187', 'H', '190', 'T'],
          'input1': ['187', '7.79', '122.27', '54.37', '4.26',
                     '179.75']}}
'''



From prologic at shortcircuit.net.au  Sun May 16 14:20:26 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 17 May 2010 04:20:26 +1000
Subject: Global variables for python applications
In-Reply-To: 
References:  
	
Message-ID: 

On Mon, May 17, 2010 at 4:00 AM, Krister Svanlund
 wrote:
> On Sun, May 16, 2010 at 7:50 PM, AON LAZIO  wrote:
>> ?? How can I set up global variables for the entire python applications?
>> Like I can call and set this variables in any .py files.
>> ?? Think of it as a global variable in a single .py file but this is for the
>> entire application.
>
> First: Do NOT use global variables, it is bad practice and will
> eventually give you loads of s**t.
>
> But if you want to create global variables in python I do believe it
> is possible to specify them in a .py file and then simply import it as
> a module in your application. If you change one value in a module the
> change will be available in all places you imported that module in.

The only place global variables are considered somewhat "acceptable"
are as constants in a module shared as a static value.

Anything else should be an object that you share. Don't get into the
habit of using global variables!

--james


From omsdiver at gmail.com  Sun May 16 14:28:38 2010
From: omsdiver at gmail.com (OMS)
Date: Sun, 16 May 2010 11:28:38 -0700 (PDT)
Subject: Qt and progressBar - how to update
Message-ID: <808ce044-dfd5-44bf-9c5a-ecf3c657eda5@b21g2000vbh.googlegroups.com>

I am quite new to Python and Qt and need very urgently advice on how
to update Qt progressBar while executing a process. I have went thrugh
number of 'google' stuff and saw different solution, hence none worked
for me. The best idea I have seen is the usage of QThread and emiting
signal from thread to MainWindow. I do not know however why the code I
have written is not working. Most likely a stupid 'beginner related'
error but as far as I am beginner I can't get it. There is a code
below:

#!/opt/local/bin/python2.6

import os
import sys
import time
from PyQt4 import QtCore
from PyQt4 import QtGui

from uiTest import Ui_MainWindow

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),
self.runWorker)

    def runWorker(self):
        self.worker = Worker()
        self.connect(self.worker, QtCore.SIGNAL("progressUpdated"),
self.updateWorkerProgress)
        self.worker.start()

    def updateWorkerProgress(self, min, max, progress):
        self.ui.progressBar.setMinimum = min
        self.ui.progressBar.setMaximum = max
        self.ui.progressBar.setValue = progress
        self.ui.progressBar.repaint()
        #print min, progress, max

class Worker(QtCore.QThread):
    __pyqtSignals__ = ("progressUpdated")
    def __init__(self):
        QtCore.QThread.__init__(self)
        self.min = 0
        self.max = 1000
        self.progress = 0
    def run(self):
        for self.progress in range(self.min, self.max):
            self.emit(QtCore.SIGNAL("progressUpdated"), self.min,
self.max, self.progress)
            time.sleep(0.005)

def main():
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

the uiTest is generated by pyuic4 and for reference can be found
below:

# Form implementation generated from reading ui file 'test.ui'
#
# Created: Sun May 16 19:54:59 2010
#      by: PyQt4 UI code generator 4.7.2
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(640, 480)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(40, 40, 113, 32))
        self.pushButton.setObjectName("pushButton")
        self.progressBar = QtGui.QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QtCore.QRect(50, 80, 431, 23))
        self.progressBar.setProperty("value", 24)
        self.progressBar.setObjectName("progressBar")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
 
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow",
"MainWindow", None, QtGui.QApplication.UnicodeUTF8))
 
self.pushButton.setText(QtGui.QApplication.translate("MainWindow",
"PushButton", None, QtGui.QApplication.UnicodeUTF8))


From tuomas.vesterinen at iki.fi  Sun May 16 14:29:10 2010
From: tuomas.vesterinen at iki.fi (Tuomas Vesterinen)
Date: Sun, 16 May 2010 21:29:10 +0300
Subject: Using site-packages with alt-installed Python version
In-Reply-To: 
References: <4befb5c3$0$2537$9b536df3@news.fv.fi>
	
Message-ID: <4bf039e2$0$2008$9b536df3@news.fv.fi>

On 05/16/2010 02:38 PM, Alister wrote:
> On Sun, 16 May 2010 12:07:08 +0300, Tuomas Vesterinen wrote:
>
>> I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native
>> Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.
>>
>> Aplication GUI uses:
>> import pygtk
>> pygtk.require('2.0')
>> import gtk
>> import gobject
>>
>> I go to:
>> $ cd /usr/local/lib/python2.4/site-packages
>>
>> and say:
>> $ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py $ sudo
>> ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0
>>
>> and try:
>> $ python2.4 gui_utils.py
>> Traceback (most recent call last):
>>     File "gui_utils.py", line 57, in ?
>>       import gtk
>>     File
>> "/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line
>> 30, in ?
>>       import gobject as _gobject
>>     File
>> "/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py",
>> line 26, in ?
>>       from glib import spawn_async, idle_add, timeout_add,
>> timeout_add_seconds, \
>>     File
>> "/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line
>> 22, in ?
>>       from glib._glib import *
>> ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol:
>> _PyObject_CallFunction_SizeT
>>
>> What I should say more to get access to the GTK?
>>
>> Tuomas Vesterinen
>
> I am not a great expert on this But I think you need to use the Redhat
> alternatives system to switch between versions rather than trying to
> change things manually.
>
> as i understand it the Alternatives system sets up and changes various
> symlinks to ensure everything works correctly.
>

Yes, my first trial is not the solution because byte compiled .pyc files 
must be produced by the corresponding Python version.

PEP 3147 http://www.python.org/dev/peps/pep-3147 suggests a common 
solution, but only for Python 3.2 and perhaps 2.7. So I am still looking 
for hints. Have You some helpful links to those "Alternatives system"?

Tuomas Vesterinen


From walterwefft at googlemail.com  Sun May 16 14:33:30 2010
From: walterwefft at googlemail.com (Walter Wefft)
Date: Sun, 16 May 2010 19:33:30 +0100
Subject: recursively remove all the directories and files which begin
	with  '.'
In-Reply-To: <4bf03277$0$22938$e4fe514c@news.xs4all.nl>
References: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>		<67827508-ddda-44e8-8b88-aae4f78e23da@o8g2000yqo.googlegroups.com>	<9609b853-c7b1-4357-aaf0-b173aebc6879@11g2000prv.googlegroups.com>
	<4bf03277$0$22938$e4fe514c@news.xs4all.nl>
Message-ID: 

Irmen de Jong wrote:
> On 16-5-2010 19:41, Sean DiZazzo wrote:
>> On May 14, 8:27 am, albert kao  wrote:
>>> On May 14, 11:01 am, J  wrote:
>>>
>>>
>>>
>>>> On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>>>
>>>>> C:\python>rmdir.py
>>>>> C:\test\com.comp.hw.prod.proj.war\bin
>>>>> ['.svn', 'com']
>>>>> d .svn
>>>>> dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
>>>>> Traceback (most recent call last):
>>>>>   File "C:\python\rmdir.py", line 14, in
>>>>>     rmtree(os.path.join(curdir, d))
>>>>>   File "C:\Python31\lib\shutil.py", line 235, in rmtree
>>>>>     onerror(os.remove, fullname, sys.exc_info())
>>>>>   File "C:\Python31\lib\shutil.py", line 233, in rmtree
>>>>>     os.remove(fullname)
>>>>> WindowsError: [Error 5] Access is denied: 'C:\\test\
>>>>> \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>>>
>>>>> -- 
>>>>> http://mail.python.org/mailman/listinfo/python-list
>>>
>>>> You don't have permissions to remove the subdir or file entries in the
>>>> .svn directory...
>>>
>>>> Maybe that file is still open, or still has a lock attached to it?
>>>
>>> I reboot my windows computer and run this script as administrator.
>>> Do my script has a bug?
>>
>> Are the directory or files marked as read only?
>>
>> See this recipe and the comment from Chad Stryker:
>>
>> http://code.activestate.com/recipes/193736-clean-up-a-directory-tree/
>>
>> "Although it is true you can use shutil.rmtree() in many cases, there
>> are some cases where it does not work. For example, files that are
>> marked read-only under Windows cannot be deleted by shutil.rmtree().
>> By importing the win32api and win32con modules from PyWin32 and adding
>> line like "win32api.SetFileAttributes(path,
>> win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this
>> obstacle can be overcome."
>>
>> It might not be your problem, but if it is, this had me stumped for a
>> few weeks before I found this comment!
>>
>> ~Sean
> 
> You should be able to do this with os.chmod as well (no extra modules 
> required). I'm not sure what the mode should be though. Perhaps 0777 
> does the trick.
> 
> -irmen
> 

def make_readable(fpath):
     '''
     On windows, this will make a read-only file readable.
     '''
     mode = os.stat(fpath)[stat.ST_MODE] | stat.S_IREAD | stat.S_IWRITE
     chmod(fpath, mode)



From thom.1948 at live.com  Sun May 16 14:39:38 2010
From: thom.1948 at live.com (Thomas)
Date: Sun, 16 May 2010 14:39:38 -0400
Subject: Updating values in a dictionary
In-Reply-To: 
References: 
	
Message-ID: <92f55$4bf03bea$6213ba37$27306@ALLTEL.NET>

Chris

Wow, that was a very fast response.
Thank you, it works  (of course)...

Cheers

"Chris Rebert"  wrote in message 
news:mailman.264.1274032106.32709.python-list at python.org...
> On Sun, May 16, 2010 at 10:36 AM, Thomas  wrote:
>> Greetings
>>
>> I am having a darn awful time trying to update a matrix:
>>
>> row = dict([(x,0) for x in range(3)])
>> matrix = dict([(x,row) for x in range(-3,4,1)])
>
> All the columns refer to the very same row dict (`row` obviously).
> Python doesn't do any copying unless you explicitly request it.
>
> Try:
> matrix = dict([(x, dict([(x,0) for x in range(3)]) ) for x in 
> range(-3,4,1)])
>
> This way, the row-creation code gets called for each column and thus
> fresh row dicts are created rather than all just referencing the exact
> same one row dict.
> Nested comprehensions may be hard to understand, so you may wish to
> write it using a function instead:
>
> def make_row():
>    return dict([(x,0) for x in range(3)])
>
> matrix = dict([(x,make_row()) for x in range(-3,4,1)])
>
> See also 
> http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com 



From pacman128 at gmail.com  Sun May 16 14:51:58 2010
From: pacman128 at gmail.com (Paul Carter)
Date: Sun, 16 May 2010 11:51:58 -0700 (PDT)
Subject: imports and exec
Message-ID: <20297a4b-6fc8-4fa0-a203-decdd2586805@l18g2000vbn.googlegroups.com>

We are using python for our build system. Each subproject dir has a
python script that builds it. Parent dirs have python scripts that
recurse into their children and use exec to invoke the python scripts.
Recently we discovered that one of the python scripts works when
invoked directly, but fails when invoked with exec. I've created a
very simple pair of python scripts that demonstrates the problem.
(We're using python 2.6)

Can someone explain or point to a good explanation of why this problem
occurs?

I have two python files: prim.py and sec.py.
prim.py:
-----------------------------------------
#!/usr/bin/env python

##sec2 = open('sec.py')
##exec sec2

def invoke():
  sec = open('sec.py')
  exec sec

invoke()
------------------------------

and sec.py:
----------------------------------
import sys

def sec():
  print('Inside sec(): ' +  str(sys.argv))

print('Outside sec(): ' + str(sys.argv))
sec()
--------------------------------------

When I run prim.py, I get an error:
--------------------------------
Outside sec(): ['./prim.py']
Traceback (most recent call last):
  File "./prim.py", line 10, in 
    invoke()
  File "./prim.py", line 8, in invoke
    exec sec
  File "sec.py", line 7, in 
    sec()
  File "sec.py", line 4, in sec
    print('Inside sec(): ' +  str(sys.argv))
NameError: global name 'sys' is not defined
----------------------------------

I don't understand why the sys import is not visible in the sec()
function. I can fix this by adding a:
  global sys
or
  import sys
inside the sec() function. But I would like to understand why this is
necessary, especially since sys is visible in sec.py outside of the
sec() function. I found this page discussing exec

http://docs.python.org/reference/executionmodel.html

but I'm afraid I couldn't quite follow it. It makes me think that a
free variable is involved, but I don't see how. It did made me try
invoking exec in prim.py outside of the invoke() function (see the
commented out code). Everything worked fine when I did that.

Can someone set me straight? Suggestions on avoiding this problem are
welcome as well!

Thanks in advance.

Paul Carter


From robert.kern at gmail.com  Sun May 16 14:52:17 2010
From: robert.kern at gmail.com (Robert Kern)
Date: Sun, 16 May 2010 13:52:17 -0500
Subject: Qt and progressBar - how to update
In-Reply-To: <808ce044-dfd5-44bf-9c5a-ecf3c657eda5@b21g2000vbh.googlegroups.com>
References: <808ce044-dfd5-44bf-9c5a-ecf3c657eda5@b21g2000vbh.googlegroups.com>
Message-ID: 

On 2010-05-16 13:28 , OMS wrote:
> I am quite new to Python and Qt and need very urgently advice on how
> to update Qt progressBar while executing a process. I have went thrugh
> number of 'google' stuff and saw different solution, hence none worked
> for me. The best idea I have seen is the usage of QThread and emiting
> signal from thread to MainWindow. I do not know however why the code I
> have written is not working. Most likely a stupid 'beginner related'
> error but as far as I am beginner I can't get it. There is a code
> below:
>
> #!/opt/local/bin/python2.6
>
> import os
> import sys
> import time
> from PyQt4 import QtCore
> from PyQt4 import QtGui
>
> from uiTest import Ui_MainWindow
>
> class MainWindow(QtGui.QMainWindow):
>      def __init__(self):
>          QtGui.QMainWindow.__init__(self)
>          self.ui=Ui_MainWindow()
>          self.ui.setupUi(self)
>          self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),
> self.runWorker)
>
>      def runWorker(self):
>          self.worker = Worker()
>          self.connect(self.worker, QtCore.SIGNAL("progressUpdated"),
> self.updateWorkerProgress)
>          self.worker.start()
>
>      def updateWorkerProgress(self, min, max, progress):
>          self.ui.progressBar.setMinimum = min
>          self.ui.progressBar.setMaximum = max
>          self.ui.progressBar.setValue = progress

These should be

self.ui.progressBar.setMinimum(min)
self.ui.progressBar.setMaximum(max)
self.ui.progressBar.setValue(progress)

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From robert.kern at gmail.com  Sun May 16 14:53:06 2010
From: robert.kern at gmail.com (Robert Kern)
Date: Sun, 16 May 2010 13:53:06 -0500
Subject: Access to comp.lang.python
In-Reply-To: <4BF0219A.3080004@comcast.net>
References: 					
	<4BF0219A.3080004@comcast.net>
Message-ID: 

On 2010-05-16 11:47 , Jim Byrnes wrote:
> Grant Edwards wrote:
>> On 2010-05-16, cjw wrote:
>>> On 16-May-10 01:31 AM, James Mills wrote:
>>>> On Sun, May 16, 2010 at 3:12 PM, Aahz wrote:
>>>>> It's also at least partly due to problems with mail<->news gateways
>>>>> and
>>>>> the differing fields used to maintain threading.
>>>>
>>>> Some blame goes on MUAs too :)
>>>
>>> Thanks for the responses.
>>>
>>> Is it possible to connect a newsreader to gmane?
>>
>> nntp://news.gmane.org/
>>
>
> Could someone please explain how to subscribe to this list on gmane. I
> subscribe to a couple of other groups there but can't find this one.

It's name on GMane is gmane.comp.python.general

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From cmpython at gmail.com  Sun May 16 14:57:30 2010
From: cmpython at gmail.com (CM)
Date: Sun, 16 May 2010 11:57:30 -0700 (PDT)
Subject: Human word reader
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
Message-ID: <09bfe5e4-9362-406d-8730-e123bb9ac91c@c7g2000vbc.googlegroups.com>

> > I need help with getting the useful information how do I get the place
> > if I don't now how long the string is?
>
> ? ? ? ? And is it supposed to handle
>
> ? ? ? ? for london give the weather to me
> ? ? ? ? for the london weather give me
>
> ...
>
> ? ? ? ? Do a search on "natural language processing"... You are at the level
> of algorithms, and algorithms are not limited to Python...

Yes, this is a major field of research.  For basic purposes in Python,
maybe just try to trigger off the presence of the word "weather" and
the presence of a particular city's name.  It will not work if the
user tries to trick it ("Don't give me the weather in London"), but,
like a search engine, it will more or less give what people want for
common queries.  Like:

list_of_cities = ['london', 'moscow', 'new york', 'paris']
user_string = 'Give me the weather for London please.'
user_word_list = user_string.split()  #if they put a comma after city,
this will be a problem
for word in user_word_list:
    period_free_word = word.rstrip('.') #strips trailing period for
final word, in case there
    lowered_word = period_free_word.lower()  #makes it case
insensitive
    if lowered_word in list_of_cities:
         print 'The city is: ' + lowered_word
         DoSomething(lowered_word)  #go and get the weather data for
that city I guess

Che






From cmpython at gmail.com  Sun May 16 15:08:13 2010
From: cmpython at gmail.com (CM)
Date: Sun, 16 May 2010 12:08:13 -0700 (PDT)
Subject: Human word reader
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
	<09bfe5e4-9362-406d-8730-e123bb9ac91c@c7g2000vbc.googlegroups.com>
Message-ID: <6305d10e-5c4d-4b2b-8279-a34c670edfff@v18g2000vbc.googlegroups.com>

On May 16, 2:57?pm, CM  wrote:
> > > I need help with getting the useful information how do I get the place
> > > if I don't now how long the string is?
>
> > ? ? ? ? And is it supposed to handle
>
> > ? ? ? ? for london give the weather to me
> > ? ? ? ? for the london weather give me
>
> > ...
>
> > ? ? ? ? Do a search on "natural language processing"... You are at the level
> > of algorithms, and algorithms are not limited to Python...
>
> Yes, this is a major field of research. ?For basic purposes in Python,
> maybe just try to trigger off the presence of the word "weather" and
> the presence of a particular city's name. ?It will not work if the
> user tries to trick it ("Don't give me the weather in London"), but,
> like a search engine, it will more or less give what people want for
> common queries. ?Like:
>
> list_of_cities = ['london', 'moscow', 'new york', 'paris']
> user_string = 'Give me the weather for London please.'
> user_word_list = user_string.split() ?#if they put a comma after city,
> this will be a problem
> for word in user_word_list:
> ? ? period_free_word = word.rstrip('.') #strips trailing period for
> final word, in case there
> ? ? lowered_word = period_free_word.lower() ?#makes it case
> insensitive
> ? ? if lowered_word in list_of_cities:
> ? ? ? ? ?print 'The city is: ' + lowered_word
> ? ? ? ? ?DoSomething(lowered_word) ?#go and get the weather data for
> that city I guess
>
> Che

I forgot to split on two delimiters (a space and a comma).  See here:
http://mail.python.org/pipermail/tutor/2008-August/063570.html

Anyway, you get the idea...


From tjreedy at udel.edu  Sun May 16 15:11:21 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Sun, 16 May 2010 15:11:21 -0400
Subject: Access to comp.lang.python
In-Reply-To: 
References: 				
	
Message-ID: 

On 5/16/2010 11:35 AM, Grant Edwards wrote:
> On 2010-05-16, cjw  wrote:
>> On 16-May-10 01:31 AM, James Mills wrote:
>>> On Sun, May 16, 2010 at 3:12 PM, Aahz   wrote:
>>>> It's also at least partly due to problems with mail<->news gateways and
>>>> the differing fields used to maintain threading.
>>>
>>> Some blame goes on MUAs too :)
>>
>> Thanks for the responses.
>>
>> Is it possible to connect a newsreader to gmane?
>
> nntp://news.gmane.org/

Thunderbird 2 and 3 work fine with it.





From tjreedy at udel.edu  Sun May 16 15:22:20 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Sun, 16 May 2010 15:22:20 -0400
Subject: Updating values in a dictionary
In-Reply-To: 
References: 
Message-ID: 

On 5/16/2010 1:36 PM, Thomas wrote:
> Greetings
>
> I am having a darn awful time trying to update a matrix:
>
> row = dict([(x,0) for x in range(3)])
> matrix = dict([(x,row) for x in range(-3,4,1)])
>
> matrix[2][1] += 1
> matrix[-1][2] += 1

Dicts are fine for sparse matrixes, but when filled in, a list of lists 
is perhaps easier and more efficient. And you can iterate and be 
guaranteed to get the sublists in the expected order.



From xcr4cx at googlemail.com  Sun May 16 15:27:21 2010
From: xcr4cx at googlemail.com (christian schulze)
Date: Sun, 16 May 2010 12:27:21 -0700 (PDT)
Subject: Global variables for python applications
References:  
	 
	
Message-ID: 

On 16 Mai, 20:20, James Mills  wrote:
> On Mon, May 17, 2010 at 4:00 AM, Krister Svanlund
>
>  wrote:
> > On Sun, May 16, 2010 at 7:50 PM, AON LAZIO  wrote:
> >> ?? How can I set up global variables for the entire python applications?
> >> Like I can call and set this variables in any .py files.
> >> ?? Think of it as a global variable in a single .py file but this is for the
> >> entire application.
>
> > First: Do NOT use global variables, it is bad practice and will
> > eventually give you loads of s**t.
>
> > But if you want to create global variables in python I do believe it
> > is possible to specify them in a .py file and then simply import it as
> > a module in your application. If you change one value in a module the
> > change will be available in all places you imported that module in.
>
> The only place global variables are considered somewhat "acceptable"
> are as constants in a module shared as a static value.
>
> Anything else should be an object that you share. Don't get into the
> habit of using global variables!
>
> --james

Exactly! Python's OOP is awesome. Use it. Global vars used as anything
but constants is bad practice. It isn't that much work to implement
that.


From pmaupin at gmail.com  Sun May 16 15:33:09 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sun, 16 May 2010 12:33:09 -0700 (PDT)
Subject: Picking a license
References: 
Message-ID: <078264e1-d518-40ef-acb1-a7234cfc839e@k31g2000vbu.googlegroups.com>

On May 16, 9:19?am, Ed Keith  wrote:
> --- On Sat, 5/15/10, Lawrence D'Oliveiro  wrote:
> > >> But what about the ?freedom? to take away
> > other
> > >> people?s freedom? Is that really ?freedom??
>
> > > Yes.
>
> > But that?s a ?freedom? that non-GPL licences do not
> > give you, that the GPL
> > does. So which licence gives you more ?freedoms?,
> > again?

[ stuff snipped]

> There is clearly some kind of communication problem here. Either were are speaking different languages with some faulty transaction program interviewing, or one of is is either stupid or senile (seems a bit early for me, but it is possible); or you are being disingenuous.

Lawrence is certainly being overly clever.  He is somewhat technically
correct, but is playing a shell game where he moves around who the
potential "freedom" giver is and who the potential "freedom" receiver
is.

The problem is, you have to handle this sort of argument very
carefully, or someone will come along and then point out (again,
somewhat technically correctly) that copyright law restricts the
"freedoms", and the GPL license only gives them out, so where's the
problem?  It's easy to lose sight of where the pea is, particularly
when you were expecting straightforward communication rather than this
sort of sophistry.

When people in this thread previously said that permissive licenses
give you the "freedom" to take away others' "freedoms", but the GPL
does not, the "you" they are referring to is "a person who has
received the software from someone else".

When Lawrence is now saying that the GPL gives you the "freedom" to
take away others' "freedoms" but other licenses do not, the "you" he
is referring to is the "author of the software", who I think we all
agree retains more "freedom" to restrict others' "freedoms" if he uses
the GPL than if he uses a permissive license.

So in this instance, the thing that disappeared under the shell where
you thought it was and reappeared under a different shell was the very
definition of the word "you".  But don't feel bad; some of the
thimbleriggers around here are quite accomplished, and very hard to
catch out.

Regards,
Pat


From omsdiver at gmail.com  Sun May 16 15:38:04 2010
From: omsdiver at gmail.com (OMS)
Date: Sun, 16 May 2010 12:38:04 -0700 (PDT)
Subject: Qt and progressBar - how to update
References: <808ce044-dfd5-44bf-9c5a-ecf3c657eda5@b21g2000vbh.googlegroups.com>
	
Message-ID: <83dbfb8c-31a3-4a90-b623-c017b5ec70f3@p17g2000vbe.googlegroups.com>

On 16 Maj, 20:52, Robert Kern  wrote:
> On 2010-05-16 13:28 , OMS wrote:
>
>
>
> > I am quite new to Python and Qt and need very urgently advice on how
> > to update Qt progressBar while executing a process. I have went thrugh
> > number of 'google' stuff and saw different solution, hence none worked
> > for me. The best idea I have seen is the usage of QThread and emiting
> > signal from thread to MainWindow. I do not know however why the code I
> > have written is not working. Most likely a stupid 'beginner related'
> > error but as far as I am beginner I can't get it. There is a code
> > below:
>
> > #!/opt/local/bin/python2.6
>
> > import os
> > import sys
> > import time
> > from PyQt4 import QtCore
> > from PyQt4 import QtGui
>
> > from uiTest import Ui_MainWindow
>
> > class MainWindow(QtGui.QMainWindow):
> > ? ? ?def __init__(self):
> > ? ? ? ? ?QtGui.QMainWindow.__init__(self)
> > ? ? ? ? ?self.ui=Ui_MainWindow()
> > ? ? ? ? ?self.ui.setupUi(self)
> > ? ? ? ? ?self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),
> > self.runWorker)
>
> > ? ? ?def runWorker(self):
> > ? ? ? ? ?self.worker = Worker()
> > ? ? ? ? ?self.connect(self.worker, QtCore.SIGNAL("progressUpdated"),
> > self.updateWorkerProgress)
> > ? ? ? ? ?self.worker.start()
>
> > ? ? ?def updateWorkerProgress(self, min, max, progress):
> > ? ? ? ? ?self.ui.progressBar.setMinimum = min
> > ? ? ? ? ?self.ui.progressBar.setMaximum = max
> > ? ? ? ? ?self.ui.progressBar.setValue = progress
>
> These should be
>
> self.ui.progressBar.setMinimum(min)
> self.ui.progressBar.setMaximum(max)
> self.ui.progressBar.setValue(progress)
>
> --
> Robert Kern

Thanks. You have saved the day. I knew it must be something only
greenhorn could do.

Once again thanks!


From vincent at vincentdavis.net  Sun May 16 15:55:51 2010
From: vincent at vincentdavis.net (Vincent Davis)
Date: Sun, 16 May 2010 13:55:51 -0600
Subject: Access to comp.lang.python
In-Reply-To: 
References: 
Message-ID: 

I have no problem with threads
Using gmail in a browser.
That said I like how google groups handles email.
I am also ways having to fix the reply on this list to send back to the list
and not to the list and the last author. If someone knows a way to fix that
I would be happy to hear it.

Vincent


On Sat, May 15, 2010 at 4:34 PM, cjw  wrote:

> This isn't about Python but I'm seeking suggestions as to the best way to
> access the newsgroup.
>
> It seems that messages are coming from a number of sources, such as gmane
> and google groups.
>
> The problem is that many messages seem to get unlinked from their threads.
>
> I use Thunderbird 3.0.5 and wonder whether the problem lies with the merge
> process, the server or my reader.
>
> Would it be better to go to gmane, google groups or some such provider.
>
> In the past, use of Ctrl K had neatly disposed of thread that are of no
> interest.
>
> I would welcome advice.
>
> Colin W.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

  *Vincent Davis
720-301-3003 *
vincent at vincentdavis.net
 my blog  |
LinkedIn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From pmaupin at gmail.com  Sun May 16 16:22:08 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sun, 16 May 2010 13:22:08 -0700 (PDT)
Subject: imports and exec
References: <20297a4b-6fc8-4fa0-a203-decdd2586805@l18g2000vbn.googlegroups.com>
Message-ID: 

On May 16, 1:51?pm, Paul Carter  wrote:
> We are using python for our build system. Each subproject dir has a
> python script that builds it. Parent dirs have python scripts that
> recurse into their children and use exec to invoke the python scripts.
> Recently we discovered that one of the python scripts works when
> invoked directly, but fails when invoked with exec. I've created a
> very simple pair of python scripts that demonstrates the problem.
> (We're using python 2.6)
>
> Can someone explain or point to a good explanation of why this problem
> occurs?
>
> I have two python files: prim.py and sec.py.
> prim.py:
> -----------------------------------------
> #!/usr/bin/env python
>
> ##sec2 = open('sec.py')
> ##exec sec2
>
> def invoke():
> ? sec = open('sec.py')
> ? exec sec
>
> invoke()
> ------------------------------
>
> and sec.py:
> ----------------------------------
> import sys
>
> def sec():
> ? print('Inside sec(): ' + ?str(sys.argv))
>
> print('Outside sec(): ' + str(sys.argv))
> sec()
> --------------------------------------
>
> When I run prim.py, I get an error:
> --------------------------------
> Outside sec(): ['./prim.py']
> Traceback (most recent call last):
> ? File "./prim.py", line 10, in 
> ? ? invoke()
> ? File "./prim.py", line 8, in invoke
> ? ? exec sec
> ? File "sec.py", line 7, in 
> ? ? sec()
> ? File "sec.py", line 4, in sec
> ? ? print('Inside sec(): ' + ?str(sys.argv))
> NameError: global name 'sys' is not defined
> ----------------------------------
>
> I don't understand why the sys import is not visible in the sec()
> function. I can fix this by adding a:
> ? global sys
> or
> ? import sys
> inside the sec() function. But I would like to understand why this is
> necessary, especially since sys is visible in sec.py outside of the
> sec() function. I found this page discussing exec
>
> http://docs.python.org/reference/executionmodel.html
>
> but I'm afraid I couldn't quite follow it. It makes me think that a
> free variable is involved, but I don't see how. It did made me try
> invoking exec in prim.py outside of the invoke() function (see the
> commented out code). Everything worked fine when I did that.
>
> Can someone set me straight? Suggestions on avoiding this problem are
> welcome as well!
>
> Thanks in advance.

Yes.  Since you did not pass any dictionaries to your exec of "sec",
sec inherited the globals and locals from the calling function.  So
the import of sys happened in that functions locals (bad practice in
any case) and the globals used by sec() are the globals of your main
module.

Especially if invoked from inside a function, you should always pass a
dict to exec.  Just "exec sec() in {}" will do the trick.  But if you
want to use your caller's dictionaries, you can do "exec sec() in
globals()"  But you should *not* use a functions locals directly if
you are going to modify them (as you are currently doing).

Regards,
Pat


From vicente.soler at gmail.com  Sun May 16 17:42:40 2010
From: vicente.soler at gmail.com (vsoler)
Date: Sun, 16 May 2010 14:42:40 -0700 (PDT)
Subject: global variables in imported modules
Message-ID: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>

Taken from www.python.org, FAQ 2.3 How do I share global variables
across modules?

config.py:

x = 0   # Default value of the 'x' configuration setting


mod.py:

import config
config.x = 1


main.py:

import config       # try removing it
import mod
print config.x

The example, such as shown in the website, works perfectly well.
However, I don't fully understand why I have to import config in
main.py, since it has already been imported by mod.py.

As the website explains, there is only one module namespace for each
module, and mod.py has aleady created the config namespace by
importing it. Why should I import it again in main.py if that
namespace already exists?

If I remove ->   import config       # try removing it     in main.py,
the application does not run

What am I missing?


From pmaupin at gmail.com  Sun May 16 18:05:43 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sun, 16 May 2010 15:05:43 -0700 (PDT)
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
Message-ID: 

On May 16, 4:42?pm, vsoler  wrote:
> Taken fromwww.python.org, FAQ 2.3 How do I share global variables
> across modules?
>
> config.py:
>
> x = 0 ? # Default value of the 'x' configuration setting
>
> mod.py:
>
> import config
> config.x = 1
>
> main.py:
>
> import config ? ? ? # try removing it
> import mod
> print config.x
>
> The example, such as shown in the website, works perfectly well.
> However, I don't fully understand why I have to import config in
> main.py, since it has already been imported by mod.py.
>
> As the website explains, there is only one module namespace for each
> module, and mod.py has aleady created the config namespace by
> importing it. Why should I import it again in main.py if that
> namespace already exists?
>
> If I remove -> ? import config ? ? ? # try removing it ? ? in main.py,
> the application does not run
>
> What am I missing?

What you are missing is that the interpreter has to look *inside* a
namespace in order to actually find the object associated with a
name.  As you found out, there is a namespace per module.  So
main.py's namespace is where the code in main.py will search for
variables.  If 'mod' imports config, then the 'mod' module's namespace
is updated with 'config' -> the config module.  But the act of 'mod'
importing 'config' will not alter the namespace of 'main' at all.  So
if you want to access variable 'x' inside 'config' from main you can
either import config directly into main and access it as config.x, or
you can import config into mod and import mod into main and access it
as mod.config.x.

Regards,
Pat


From rhodri at wildebst.demon.co.uk  Sun May 16 18:23:18 2010
From: rhodri at wildebst.demon.co.uk (Rhodri James)
Date: Sun, 16 May 2010 23:23:18 +0100
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
Message-ID: 

On Sun, 16 May 2010 22:42:40 +0100, vsoler  wrote:

> Taken from www.python.org, FAQ 2.3 How do I share global variables
> across modules?
>
> config.py:
>
> x = 0   # Default value of the 'x' configuration setting
>
>
> mod.py:
>
> import config
> config.x = 1
>
>
> main.py:
>
> import config       # try removing it
> import mod
> print config.x
>
> The example, such as shown in the website, works perfectly well.
> However, I don't fully understand why I have to import config in
> main.py, since it has already been imported by mod.py.

Globals are only global to a module.  As you can see above, they
don't magically appear in the namespace of the module you import
them into (not unless you do something careless like "from config
import *", at which point you deserve all the confusion you're
going to get).  In both mod.py and main.py you get at the global
x through its module: config.x

Now as you say, main.py imports mod.  In exactly the same way as
mod imports config.  *Exactly*.  We get at the contents of mod
(the things in its namespace) in the same way: mod.thing.  When
mod imports config it imports it into its own namespace only;
there is no magic that makes it appear in the namespace of anything
importing mod any more than happens for anything else.

If you want to access config in main.py without importing it
directly because you know that (in this case) mod has already
imported it, you have to access it through the module that did
the importing.  Instead of "config.x", in main it would be
"mod.config.x".

-- 
Rhodri James *-* Wildebeeste Herder to the Masses


From vicente.soler at gmail.com  Sun May 16 18:26:01 2010
From: vicente.soler at gmail.com (vsoler)
Date: Sun, 16 May 2010 15:26:01 -0700 (PDT)
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
	
Message-ID: 

On 17 mayo, 00:05, Patrick Maupin  wrote:
> On May 16, 4:42?pm, vsoler  wrote:
>
>
>
> > Taken fromwww.python.org, FAQ 2.3 How do I share global variables
> > across modules?
>
> > config.py:
>
> > x = 0 ? # Default value of the 'x' configuration setting
>
> > mod.py:
>
> > import config
> > config.x = 1
>
> > main.py:
>
> > import config ? ? ? # try removing it
> > import mod
> > print config.x
>
> > The example, such as shown in the website, works perfectly well.
> > However, I don't fully understand why I have to import config in
> > main.py, since it has already been imported by mod.py.
>
> > As the website explains, there is only one module namespace for each
> > module, and mod.py has aleady created the config namespace by
> > importing it. Why should I import it again in main.py if that
> > namespace already exists?
>
> > If I remove -> ? import config ? ? ? # try removing it ? ? in main.py,
> > the application does not run
>
> > What am I missing?
>
> What you are missing is that the interpreter has to look *inside* a
> namespace in order to actually find the object associated with a
> name. ?As you found out, there is a namespace per module. ?So
> main.py's namespace is where the code in main.py will search for
> variables. ?If 'mod' imports config, then the 'mod' module's namespace
> is updated with 'config' -> the config module. ?But the act of 'mod'
> importing 'config' will not alter the namespace of 'main' at all. ?So
> if you want to access variable 'x' inside 'config' from main you can
> either import config directly into main and access it as config.x, or
> you can import config into mod and import mod into main and access it
> as mod.config.x.
>
> Regards,
> Pat

Thank you Pat, it's very clear.

However, can I be 100% sure that,no matter how I access variable
'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
that either reference of 'x' points to the same id(memory position)?

Thank you


From prologic at shortcircuit.net.au  Sun May 16 18:38:48 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 17 May 2010 08:38:48 +1000
Subject: global variables in imported modules
In-Reply-To: 
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
	 
	
Message-ID: 

On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> However, can I be 100% sure that,no matter how I access variable
> 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> that either reference of 'x' points to the same id(memory position)?

Yes it does unless you re-assign it.

--James


From vicente.soler at gmail.com  Sun May 16 18:45:54 2010
From: vicente.soler at gmail.com (vsoler)
Date: Sun, 16 May 2010 15:45:54 -0700 (PDT)
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
	 
	 
	
Message-ID: <79a4c855-8fbc-4c49-98e6-78a7fe728698@c7g2000vbc.googlegroups.com>

On 17 mayo, 00:38, James Mills  wrote:
> On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> > However, can I be 100% sure that,no matter how I access variable
> > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> > that either reference of 'x' points to the same id(memory position)?
>
> Yes it does unless you re-assign it.
>
> --James

Understood, thank you very much

Vicente Soler


From pmaupin at gmail.com  Sun May 16 18:52:37 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sun, 16 May 2010 15:52:37 -0700 (PDT)
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
	 
	 
	
Message-ID: 

On May 16, 5:38?pm, James Mills  wrote:
> On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> > However, can I be 100% sure that,no matter how I access variable
> > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> > that either reference of 'x' points to the same id(memory position)?
>
> Yes it does unless you re-assign it.
>
> --James


To expand a bit on what James is saying:

If, for example, inside your main module, you got tired of typing
"mod.config.x" everywhere you were using it, and decided that you
could make a local reference to the same variable:

x = mod.config.x

Now, whenever you use just plain x inside the main module, you are
also referencing the exact same object, *until* some other function
decides to do:

mod.config.x = y

At this point in time, the 'x' inside main references the object that
mod.config.x originally referenced, but mod.config.x now references a
different object.

Unlike C, for example, where the assignment operator physically places
an item into a specific memory location (either fixed globally or
within a stack frame), the assignment operator in python simply stores
a key/value pair into a namespace dictionary.  So whenever you
retrieve a value from the dictionary using that key, you will get the
value that was last associated with that key.

So, 'mod.config.x' will first retrieve the object associated with the
key 'mod' from the main module's namespace dictionary, then will
retrieve the object associated with the key 'config' from that
module's namespace dictionary, then will retrieve the object
associated with the key 'x' from that module's namespace dictionary.
Unless you later modify any of those key/value pairs, subsequent
retrieval will always result in the same final value.

Regards,
Pat


From paul.lafollette at gmail.com  Sun May 16 18:58:45 2010
From: paul.lafollette at gmail.com (Paul LaFollette)
Date: Sun, 16 May 2010 18:58:45 -0400
Subject: A couple questions about classes and inheritance
Message-ID: 

Kind people,
Using Python 3.1

I have been poking around trying to get more insight into Python's
innards, and I have a couple of (marginally) related questions.

First, I've looked a fair bit and can't find how one can find the base
classes of a subclass?  isinstance and issubclass sort of do the
opposite of what I want.  Surely somewhere there is something like

MyThingee.something.orOther.baseClasses()

that returns a tuple of the parents?  If there is, can you point me to
the appropriate documentation?

Second,
I can subclass most builtin things like int and float and list and so
on, and then override operators to play Twilight Zone if I am so
inclined.

  But what happens if I try to subclass function?

First attempt:
>>>
>>> class MyFunction(function):
...       pass
...
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'function' is not defined
>>>

OK.. so second attempt:


>>>
>>> def a():
...       pass
...
>>> a

>>> function
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'function' is not defined
>>> function=type(a)
>>> function

>>>
>>> class MyFunction(function):
...       pass
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: type 'function' is not an acceptable base type
>>>

So, it appears that function is perhaps the equivalent of a Java final
class? Or isn't really a class at all but something that "looks like"
a class?

Anyway, again can you point me to somewhere that I can learn more?  In
particular, is there a list somewhere of the builtin types that are
not subclassable?

I'm willing to root through the source code if that is what I need to
do, but even there (especially there) a hint as to where to start
looking would be helpful.

Thank you in advance,
Paul


From ethan at stoneleaf.us  Sun May 16 19:00:19 2010
From: ethan at stoneleaf.us (Ethan Furman)
Date: Sun, 16 May 2010 16:00:19 -0700
Subject: Picking a license
In-Reply-To: <9c23d9ef-6ddc-4b04-a92a-9aa887411eb4@i31g2000vbt.googlegroups.com>
References: 	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com>
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com>
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com>
	
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com>
	<47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com>
	
	<9c23d9ef-6ddc-4b04-a92a-9aa887411eb4@i31g2000vbt.googlegroups.com>
Message-ID: <4BF07903.1040304@stoneleaf.us>

Paul Boddie wrote:
> As I said before, spare me the condescension. 

Spare us your self-righteous bull-crap.

Do you think we haven't seen your false accusations and made-up motives 
against Patrick Maupin?  If I cared more and/or had more time, I'd make 
a summary -- but quite frankly Pat has defended himself quite well, 
while being very reasonable, and has said at least twice (more, I'm 
sure) that the choice of license is up to the author, and that there are 
good reasons for choosing any of the free licenses (including the GPL).

~Ethan~


From lists at cheimes.de  Sun May 16 19:17:19 2010
From: lists at cheimes.de (Christian Heimes)
Date: Mon, 17 May 2010 01:17:19 +0200
Subject: A couple questions about classes and inheritance
In-Reply-To: 
References: 
Message-ID: 

> First, I've looked a fair bit and can't find how one can find the base
> classes of a subclass?  isinstance and issubclass sort of do the
> opposite of what I want.  Surely somewhere there is something like
>
> MyThingee.something.orOther.baseClasses()

You can get the direct parents of a class with the attribute __bases__. 
The class attribute __mro__ returns a tuple of for the method resolution 
order. But instead of poking around yourself I suggest you use the 
inspect module. It provides a high level interface.

>>> class Example:
...     pass
...
>>> Example.__bases__
(,)
>>> Example.__mro__
(, )


>    But what happens if I try to subclass function?
>
> First attempt:
>>>>
>>>> class MyFunction(function):
> ....       pass
> ....
> Traceback (most recent call last):
>    File "", line 1, in
> NameError: name 'function' is not defined

There is no object called function in the list of builtins. You can't 
subclass from function anyway so there is no point in accessing the 
function object. If you want to create some callable class you have to 
provide a method call "__call__". It's called when you call the 
instances of your class like a function.

>>> def a():
...     pass
...
>>> type(a)

>>> function = type(a)
>>> class MyFunc(function):
...     pass
...
Traceback (most recent call last):
   File "", line 1, in 
TypeError: type 'function' is not an acceptable base type

> Anyway, again can you point me to somewhere that I can learn more?  In
> particular, is there a list somewhere of the builtin types that are
> not subclassable?

I don't think it's documented anyway. You have to try yourself. In 
general you don't have to subclass builtin types. Some classes are 
tricky to subclass like e.g. immutable classes (str, bytes) or dict.

Christian



From vicente.soler at gmail.com  Sun May 16 19:21:41 2010
From: vicente.soler at gmail.com (vsoler)
Date: Sun, 16 May 2010 16:21:41 -0700 (PDT)
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
	 
	 
	
	
Message-ID: <4a532680-303c-497f-80dc-0dbbf985a3d9@s41g2000vba.googlegroups.com>

On 17 mayo, 00:52, Patrick Maupin  wrote:
> On May 16, 5:38?pm, James Mills  wrote:
>
> > On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> > > However, can I be 100% sure that,no matter how I access variable
> > > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> > > that either reference of 'x' points to the same id(memory position)?
>
> > Yes it does unless you re-assign it.
>
> > --James
>
> To expand a bit on what James is saying:
>
> If, for example, inside your main module, you got tired of typing
> "mod.config.x" everywhere you were using it, and decided that you
> could make a local reference to the same variable:
>
> x = mod.config.x
>
> Now, whenever you use just plain x inside the main module, you are
> also referencing the exact same object, *until* some other function
> decides to do:
>
> mod.config.x = y
>
> At this point in time, the 'x' inside main references the object that
> mod.config.x originally referenced, but mod.config.x now references a
> different object.
>
> Unlike C, for example, where the assignment operator physically places
> an item into a specific memory location (either fixed globally or
> within a stack frame), the assignment operator in python simply stores
> a key/value pair into a namespace dictionary. ?So whenever you
> retrieve a value from the dictionary using that key, you will get the
> value that was last associated with that key.
>
> So, 'mod.config.x' will first retrieve the object associated with the
> key 'mod' from the main module's namespace dictionary, then will
> retrieve the object associated with the key 'config' from that
> module's namespace dictionary, then will retrieve the object
> associated with the key 'x' from that module's namespace dictionary.
> Unless you later modify any of those key/value pairs, subsequent
> retrieval will always result in the same final value.
>
> Regards,
> Pat

Really interesting, it helps a lot.

Thank you


From steve at REMOVE-THIS-cybersource.com.au  Sun May 16 19:55:33 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 16 May 2010 23:55:33 GMT
Subject: A couple questions about classes and inheritance
References: 
Message-ID: <4bf085f5$0$8846$c3e8da3@news.astraweb.com>

On Sun, 16 May 2010 18:58:45 -0400, Paul LaFollette wrote:

> First, I've looked a fair bit and can't find how one can find the base
> classes of a subclass?

subclass.__base__
subclass.__bases__
subclass.__mro__

(The third one stands for "Method Resolution Order".)


See also the inspect module.



> So, it appears that function is perhaps the equivalent of a Java final
> class? Or isn't really a class at all but something that "looks like" a
> class?

No, it really is a class, at least as far as Python is concerned:

>>> type(lambda: None)

>>> type(type(lambda: None))


but as you've discovered, it's also special. Unfortunately I can't find 
any explanation of *why* (other than the obvious that subclassing doesn't 
work).



> Anyway, again can you point me to somewhere that I can learn more?  In
> particular, is there a list somewhere of the builtin types that are not
> subclassable?


I don't believe so. Apart from intellectual curiosity, is there any 
reason you need to know?


This may be helpful:

http://www.python.org/dev/peps/pep-0253/

You can also google for the error message, although in my few minutes of 
searching I've only found people demonstrating the failure and not 
explaining it.

Here's a rather long discussion about subclassing function:

http://mail.python.org/pipermail/python-list/2008-March/531661.html

but again, no explanation of why type(function) isn't subclassable.




-- 
Steven


From pavlovevidence at gmail.com  Sun May 16 20:38:41 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sun, 16 May 2010 17:38:41 -0700 (PDT)
Subject: A couple questions about classes and inheritance
References:  
	
Message-ID: <52bce3fa-2852-46fe-b724-d8ab47ea3285@t26g2000prt.googlegroups.com>

On May 16, 4:17?pm, Christian Heimes  wrote:
> > First, I've looked a fair bit and can't find how one can find the base
> > classes of a subclass? ?isinstance and issubclass sort of do the
> > opposite of what I want. ?Surely somewhere there is something like
>
> > MyThingee.something.orOther.baseClasses()
>
> You can get the direct parents of a class with the attribute __bases__.
> The class attribute __mro__ returns a tuple of for the method resolution
> order. But instead of poking around yourself I suggest you use the
> inspect module. It provides a high level interface.
>
> >>> class Example:
>
> ... ? ? pass
> ...>>> Example.__bases__
> (,)
> >>> Example.__mro__
>
> (, )
>
> > ? ?But what happens if I try to subclass function?
>
> > First attempt:
>
> >>>> class MyFunction(function):
> > .... ? ? ? pass
> > ....
> > Traceback (most recent call last):
> > ? ?File "", line 1, in
> > NameError: name 'function' is not defined
>
> There is no object called function in the list of builtins. You can't
> subclass from function anyway so there is no point in accessing the
> function object. If you want to create some callable class you have to
> provide a method call "__call__". It's called when you call the
> instances of your class like a function.
>
> >>> def a():
>
> ... ? ? pass
> ...>>> type(a)
> 
> >>> function = type(a)
> >>> class MyFunc(function):
>
> ... ? ? pass
> ...
> Traceback (most recent call last):
> ? ?File "", line 1, in 
> TypeError: type 'function' is not an acceptable base type
>
> > Anyway, again can you point me to somewhere that I can learn more? ?In
> > particular, is there a list somewhere of the builtin types that are
> > not subclassable?
>
> I don't think it's documented anyway. You have to try yourself. In
> general you don't have to subclass builtin types. Some classes are
> tricky to subclass like e.g. immutable classes (str, bytes) or dict.


It's not a list, but you can tell if a given type is subclassable by
testing bit 10 of the __flags__ attribute:

type(lambda:0).__flags__ & 1024  ->  0
int.__flags__ & 1024  ->  1024


The reason some types are not subclassable is simply because there's
more involved to write a type at the C level that's subclassable.  For
a lot of types the work wasn't considered worth it.


If you think you want to subclass function, consider whether you can
do what you want with decorator syntax.


Carl Banks


From tjreedy at udel.edu  Sun May 16 20:58:04 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Sun, 16 May 2010 20:58:04 -0400
Subject: A couple questions about classes and inheritance
In-Reply-To: 
References: 
Message-ID: 

On 5/16/2010 6:58 PM, Paul LaFollette wrote:

> Anyway, again can you point me to somewhere that I can learn more?  In
> particular, is there a list somewhere of the builtin types that are
> not subclassable?

I believe that in 3.1, the builtin classes with builtin names can be 
subclassed and and those without cannot. (If you find any exceptionss, 
please post ;-). The ones with names are exactly the ones you are 
expected to directly interact with in normal code.

Terry Jan Reedy



From nagle at animats.com  Sun May 16 21:57:15 2010
From: nagle at animats.com (John Nagle)
Date: Sun, 16 May 2010 18:57:15 -0700
Subject: Global variables for python applications
In-Reply-To: 
References: 
	
	
Message-ID: <4bf09ce6$0$1661$742ec2ed@news.sonic.net>

James Mills wrote:
> The only place global variables are considered somewhat "acceptable"
> are as constants in a module shared as a static value.

    Python really ought to have named constants.

    For one thing, it's fine to share constants across threads, while
sharing globals is generally undesirable.  Also, more compile-time
arithmetic becomes possible.

    Python does have a few built-in named unassignable constants:
"True", "None", "__debug__", etc.  "Ellipsis" is supposed to be a
constant, too, but in fact you can assign to it, at least through Python 3.1.

    I think there's some religious objection to constants in Python, but
it predated threading.

					John Nagle


From mehgcap at gmail.com  Sun May 16 22:41:37 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Sun, 16 May 2010 22:41:37 -0400
Subject: tone generation for motherboard and sound card speakers?
Message-ID: 

Hi all,
I am wondering if there is a way to generate a tone for the
motherboard speaker, like the call to Beep() in C++?

Also, is there a module to generate tones in Python using the sound
card? A module that can beep at a given frequency for a given time
using the usual sine wave is okay, but the fancier the better
(different waves, sweeping, and so on).

My final question will likely hinge upon the answer to the second
question, but is there a way to play a tone in a given position in the
stereo field? For example, I have a Battleship tactical board (my name
for where the little red and white pins go) which I am trying to
sonify using different tones for each status (not fired on, ship
sighted, ship hit, ship sunk). I want each row to play, from top to
bottom, but each square in each row should start at the left and
continue to the last square playing in the right speaker, giving the
user a better idea of where each square is. Oh, this is for blind
users, in case you were wondering why anyone would want to sonify a
battleship board.
Thanks for any information, and note that I am using Python2.6; unless
there is an easy way to use a module meant for 2.5 or before inside a
2.6 project, I would need a 2.6 module.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


From marky1991 at gmail.com  Sun May 16 22:52:41 2010
From: marky1991 at gmail.com (Mark Young)
Date: Sun, 16 May 2010 22:52:41 -0400
Subject: A couple questions about classes and inheritance
In-Reply-To: 
References: 
	
Message-ID: 

You can't subclass Ellipsis.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From prologic at shortcircuit.net.au  Sun May 16 23:34:57 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 17 May 2010 13:34:57 +1000
Subject: Global variables for python applications
In-Reply-To: <4bf09ce6$0$1661$742ec2ed@news.sonic.net>
References:  
	 
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
Message-ID: 

On Mon, May 17, 2010 at 11:57 AM, John Nagle  wrote:
> ? For one thing, it's fine to share constants across threads, while
> sharing globals is generally undesirable. ?Also, more compile-time
> arithmetic becomes possible.
>
> ? Python does have a few built-in named unassignable constants:
> "True", "None", "__debug__", etc. ?"Ellipsis" is supposed to be a
> constant, too, but in fact you can assign to it, at least through Python
> 3.1.
>
> ? I think there's some religious objection to constants in Python, but
> it predated threading.

To be honest, classes work just fine for defining constants.
(Though in my own code I use ALL UPPER CASE variables as it the style).

--James


From steven at REMOVE.THIS.cybersource.com.au  Mon May 17 00:24:08 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 17 May 2010 04:24:08 GMT
Subject: Global variables for python applications
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
	
Message-ID: 

On Mon, 17 May 2010 13:34:57 +1000, James Mills wrote:

> On Mon, May 17, 2010 at 11:57 AM, John Nagle  wrote:
>> ? For one thing, it's fine to share constants across threads, while
>> sharing globals is generally undesirable. ?Also, more compile-time
>> arithmetic becomes possible.
>>
>> ? Python does have a few built-in named unassignable constants:
>> "True", "None", "__debug__", etc. ?"Ellipsis" is supposed to be a
>> constant, too, but in fact you can assign to it, at least through
>> Python 3.1.
>>
>> ? I think there's some religious objection to constants in Python, but
>> it predated threading.
> 
> To be honest, classes work just fine for defining constants. (Though in
> my own code I use ALL UPPER CASE variables as it the style).


In what way are they constant? Can you not modify them and rebind them?


-- 
Steven


From aahz at pythoncraft.com  Mon May 17 00:28:54 2010
From: aahz at pythoncraft.com (Aahz)
Date: 16 May 2010 21:28:54 -0700
Subject: Picking a license
References: 
	
	 <87r5ldbw3k.fsf@benfinney.id.au>
Message-ID: 

In article <87r5ldbw3k.fsf at benfinney.id.au>,
Ben Finney   wrote:
>aahz at pythoncraft.com (Aahz) writes:
>>
>> You can't really sell Open Source software in any practical way;
>> someone will always undercut you once it's out in the wild. You can
>> only sell support for the software, which is entirely different.
>
>Not at all. I've been selling all the software I write for clients for
>the past ten years, and it's all free software. It's been very practical
>for me and those I've worked with.
>
>You can't sell free software like selling loaves of bread, but that's a
>much more limited case and a far cry from your claim. Selling free
>software is quite practical and a good way to fund development of
>software that otherwise wouldn't be written as free software.

>From my POV, if you're not selling COTS, you're really selling support
and consulting services, because that's what keeps your competitors from
just picking up your software and reselling it for cheaper.  BTDT.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From steven at REMOVE.THIS.cybersource.com.au  Mon May 17 00:29:20 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 17 May 2010 04:29:20 GMT
Subject: Global variables for python applications
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
Message-ID: 

On Sun, 16 May 2010 18:57:15 -0700, John Nagle wrote:

> James Mills wrote:
>> The only place global variables are considered somewhat "acceptable"
>> are as constants in a module shared as a static value.
> 
>     Python really ought to have named constants.

+1

Unfortunately, it will most likely require new syntax, and semantics. 
While the concept of a constant is pretty straightforward for immutable 
types like ints and strings, what about mutable types?

And then there's the moratorium, so even if we had agreement on semantics 
and syntax, and a patch, it couldn't be deployed for a few years.



-- 
Steven


From ninmonkeys at gmail.com  Mon May 17 00:31:10 2010
From: ninmonkeys at gmail.com (Jake b)
Date: Sun, 16 May 2010 23:31:10 -0500
Subject: tone generation for motherboard and sound card speakers?
In-Reply-To: 
References: 
Message-ID: 

For sound ( not internal beep ) you can check out:

   - pygame: http://www.pygame.org/project-PygSoundTestTest-1453-.html
   - python.org/sound : http://wiki.python.org/moin/PythonInMusic
   - pk http://trac2.assembla.com/pkaudio/
   - pureData http://puredata.info/Members/thomas/py



-- 
Jake
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From prologic at shortcircuit.net.au  Mon May 17 00:31:23 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 17 May 2010 14:31:23 +1000
Subject: Global variables for python applications
In-Reply-To: 
References:  
	 
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net> 
	
	
Message-ID: 

On Mon, May 17, 2010 at 2:24 PM, Steven D'Aprano
 wrote:
> In what way are they constant? Can you not modify them and rebind them?

It's just style/convention :)
Much like _ to denote private variables and methods!

--james


From pavlovevidence at gmail.com  Mon May 17 00:53:21 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sun, 16 May 2010 21:53:21 -0700 (PDT)
Subject: an element from a set
References: <28560792.post@talk.nabble.com>
	 
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com> 
	
Message-ID: <248cbfa6-5992-4bc3-bef6-a240a901a07b@42g2000prb.googlegroups.com>

On May 14, 11:52?pm, Chris Rebert  wrote:
> On Fri, May 14, 2010 at 11:23 PM, Carl Banks  wrote:
> > On May 14, 9:39?am, Terry Reedy  wrote:
> >> On 5/14/2010 11:24 AM, gerardob wrote:
> >> > Hello, let S be a python set which is not empty
> >> > (http://docs.python.org/library/sets.html)
>
> >> > i would like to obtain one element (anyone, it doesn't matter which one) and
> >> > assign it to a variable.
>
> >> > How can i do this?
>
> >> Depends on whether or not you want the element removed from the set
>
> >> #3.1
> >> ?>>> s=set(range(10))
> >> ?>>> s
> >> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
> >> ?>>> x=next(iter(s))
> >> ?>>> x
> >> 0
> >> ?>>> s
> >> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
> >> ?>>> x = s.pop()
> >> ?>>> x
> >> 0
> >> ?>>> s
> >> {1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed
>
> >> The choice of 0 is an implementation artifact. It could have been any
> >> member.
>
> > Which brings up an interesting question: how do you get a random
> > element from a set?
>
> > random.choice(list(s))
>
> > is the most straightforward way and will work a lot of the time, but
> > how would you avoid creating the list? ?I can't think of a way off
> > hand.
>
> def random_set_elem(s):
> ? ? iterator = iter(s)
> ? ? n = random.randint(0, len(s)-1)
> ? ? for i in xrange(n):
> ? ? ? ? next(iterator)
> ? ? return next(iterator)
>
> Avoids creating the list, but it's still O(M). If you're gonna pick
> multiple times from the same set, you're better off just converting it
> to a list.

I've never had to do it (at least not in any situations where I had
any reluctance to call list on it), but it seems like a fairly bad
limitation.  Random element from a set is such a natural idea.

Even if we were to modify the set type at the C level to support it, I
can't think of an easy way to get a random element without selection
bias.  For instance, if you start from a random hash code, some
elements are more likely to be selected than others, depending on
distance between entries in the hash table.  You'd probably have to
choose an number in range(len(s)) and count off that many, but then
might as well have just converted it to a list or used an iterator.  A
little disappointing, actually.

Probably the "right" way is to use a binary-tree-based set.


Carl Banks


From steven at REMOVE.THIS.cybersource.com.au  Mon May 17 02:21:17 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 17 May 2010 06:21:17 GMT
Subject: an element from a set
References: <28560792.post@talk.nabble.com>
	
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
	
	<248cbfa6-5992-4bc3-bef6-a240a901a07b@42g2000prb.googlegroups.com>
Message-ID: 

On Sun, 16 May 2010 21:53:21 -0700, Carl Banks wrote:

> I've never had to do it (at least not in any situations where I had any
> reluctance to call list on it), but it seems like a fairly bad
> limitation.  Random element from a set is such a natural idea.

There was a long discussion on the Python-Dev mailing list about that. As 
I recall, there was no consensus about this, and the moratorium hit, so 
as far as I can tell it went absolutely nowhere.

The thread started here:

http://mail.python.org/pipermail/python-dev/2009-October/093227.html

and there was a patch here:

http://mail.python.org/pipermail/python-dev/2009-October/093228.html




-- 
Steven


From davea at ieee.org  Mon May 17 03:16:25 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 17 May 2010 03:16:25 -0400
Subject: joining files
In-Reply-To: <1273998151.S.3807.41729.H.TkRhdmUgQW5nZWwAUmU6IGpvaW5pbmcgZmlsZXM_.f4-234-213.old.1274015374.26493@webmail.rediffmail.com>
References: <1273998151.S.3807.41729.H.TkRhdmUgQW5nZWwAUmU6IGpvaW5pbmcgZmlsZXM_.f4-234-213.old.1274015374.26493@webmail.rediffmail.com>
Message-ID: <4BF0ED49.4060008@ieee.org>

mannu jha wrote:
> On Sun, 16 May 2010 13:52:31 +0530  wrote
>   
>> mannu jha wrote:
>>     
>
>   
>> Hi,
>>     
>
>   
>
>   
>> I have few files like this:
>> file1:
>> 22 110.1 
>> 33 331.5 22.7 
>> 5 271.9 17.2 33.4
>> 4 55.1 
>>     
>
>   
>> file1 has total 4 column but some of them are missing in few row.
>>     
>
>   
>> file2:
>> 5 H
>> 22 0
>>     
>
>   
>> file3:
>> 4 T
>> 5 B
>> 22 C
>> 121 S
>>     
>
>   
>
>   
>> in all these files first column is the main source of matching their entries. So What I want in the output is only those entries which is coming in all three files.
>>     
>
>   
>> output required:
>>     
>
>   
>> 5 271.9 17.2 33.4 5 H 5 T
>> 22 110.1     22 0 22 C
>>     
>
>   
> I am trying with this :
>
> from collections import defaultdict
>
> def merge(sources):
>     blanks = [blank for items, blank, keyfunc in sources]
>     d = defaultdict(lambda: blanks[:])
>     for index, (items, blank, keyfunc) in enumerate(sources):
>         for item in items:
>             d[keyfunc(item)][index] = item
>     for key in sorted(d):
>         yield d[key]
>
> if __name__ == "__main__":
>     a = open("input1.txt")
>     
>     c = open("input2.txt")
>
>     def key(line):
>         return line[:2]
>     def source(stream, blank="", key=key):
>         return (line.strip() for line in stream), blank, key
>     for m in merge([source(x) for x in [a,c]]):
>         print "|".join(c.ljust(10) for c in m)
>
> but with input1.txt:
> 187    7.79   122.27   54.37   4.26   179.75
> 194    8.00   121.23   54.79   4.12   180.06
> 15    8.45   119.04   55.02   4.08   178.89
> 176    7.78   118.68   54.57   4.20   181.06
> 180    7.50   119.21   53.93      179.80
> 190    7.58   120.44   54.62   4.25   180.02
> 152    8.39   120.63   55.10   4.15   179.10
> 154    7.79   119.62   54.47   4.22   180.46
> 175    8.42   120.50   55.31   4.04   180.33
> and input2.txt:
>  15   H 
>  37   H 
>  95   T
> 124   H 
> 130   H 
> 152   H 
> 154   H 
> 158   H 
> 164   H
> 175   H 
> 176   H 
> 180   H
> 187   H 
> 190   T
> 194   C
> 196   H 
> 207   H 
> 210   H 
> 232   H 
> it is giving output as:
>           |
>           |124   H
>           |130   H
> 154    7.79   119.62   54.47   4.22   180.46|158   H
>           |164   H
> 175    8.42   120.50   55.31   4.04   180.33|176   H
> 180    7.50   119.21   53.93      179.80|187   H
> 190    7.58   120.44   54.62   4.25   180.02|196   H
>           |207   H
>           |210   H
>           |232   H
>           |37   H
>           |95   T
> so it not matching it properly, can anyone please suggest where I am doing mistake.
>
>
>   
Several mistakes here, some in making it unnecessarily complex, but I'll 
concentrate on the ones that just don't work.

Your key() function returns the first two characters of the line.  So 
you're keying not on the whole number, but only on the first two digits 
of it.  To find out what's going on, you need to decompose the complex 
line from:
  

            d[keyfunc(item)][index] = item

to some things you can actually examine:
                       key = keyfunc(item)
                       d[key][index] = item


You don't make any check to see if a particular item is in all the 
files.  For your particular data structure, this would mean that a 
particular value in the dictionary (which is a list of two items) has 
all non-blank strings in it.  To do this, you might want to do an all() 
function on the list.


DaveA




From switch2mathan at gmail.com  Mon May 17 03:22:22 2010
From: switch2mathan at gmail.com (gmail)
Date: Sun, 16 May 2010 19:22:22 -1200
Subject: Convert PyUnicodeObject to PyBytesObject in python3.x?
Message-ID: <128a5245954.-448886445627513620.-3443650374649801849@gmail.com>

Hi All,

A variable whose data type is PyUnicodeObject needs to passed to a function as an argument whose data type should be PyBytesObject type 

example :

PyUnicodeObject *p = ...whatever...; 
function (PyByteObject* a); 

function((PyBytesObject *)p);

compiled and got a Bus Error.

Thanks for spending ur valuable time.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From Gabyswisswatch1900 at gmail.com  Mon May 17 03:24:06 2010
From: Gabyswisswatch1900 at gmail.com (Gaby)
Date: Mon, 17 May 2010 15:24:06 +0800
Subject: tone generation for motherboard and sound card speakers?
References: 
Message-ID: 

It is amazing, the Ballon Bleu de Cartier Replica Watches at 
http://www.swizwatch.com/ are perfect, cheap and high quality.

Ballon Bleu de Cartier Watches Collection: 
http://www.swizwatch.com/ballon-bleu-de-cartier-replica-watches.html

Replica Cartier Ballon Bleu de Cartier Two-Tone Ladies Watch W69007Z3
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Two-Tone-Ladies-Watch-W69007Z3-.html

Replica Cartier Ballon Bleu de Cartier 18K Yellow Gold Leather Strap Mens 
Watch W6900551
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-18K-Yellow-Gold-Leather-Strap-Mens-Watch-W6900551.html

Replica Cartier Ballon Bleu de Cartier Two-Tone Mens Watch W69009Z3
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Two-Tone-Mens-Watch-W69009Z3.html

Replica Cartier Ballon Bleu de Cartier 18K Rose Gold Mens Watch W69006Z2
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-18K-Rose-Gold-Mens-Watch-W69006Z2.html

Replica Cartier Ballon Bleu de Cartier Mens Gold Watch W69013Z2

http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Mens-Gold-Watch-W69013Z2.html


Buy more Cartier replica watches at low price by click:
http://www.swizwatch.com/cartier-replica-watches.html

"Alex Hall"  
??????:mailman.280.1274064100.32709.python-list at python.org...
> Hi all,
> I am wondering if there is a way to generate a tone for the
> motherboard speaker, like the call to Beep() in C++?
>
> Also, is there a module to generate tones in Python using the sound
> card? A module that can beep at a given frequency for a given time
> using the usual sine wave is okay, but the fancier the better
> (different waves, sweeping, and so on).
>
> My final question will likely hinge upon the answer to the second
> question, but is there a way to play a tone in a given position in the
> stereo field? For example, I have a Battleship tactical board (my name
> for where the little red and white pins go) which I am trying to
> sonify using different tones for each status (not fired on, ship
> sighted, ship hit, ship sunk). I want each row to play, from top to
> bottom, but each square in each row should start at the left and
> continue to the last square playing in the right speaker, giving the
> user a better idea of where each square is. Oh, this is for blind
> users, in case you were wondering why anyone would want to sonify a
> battleship board.
> Thanks for any information, and note that I am using Python2.6; unless
> there is an easy way to use a module meant for 2.5 or before inside a
> 2.6 project, I would need a 2.6 module.
>
> -- 
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap 




From greg.ewing at canterbury.ac.nz  Mon May 17 03:26:15 2010
From: greg.ewing at canterbury.ac.nz (Gregory Ewing)
Date: Mon, 17 May 2010 19:26:15 +1200
Subject: Human word reader
In-Reply-To: 
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
Message-ID: <85c8q9FqboU1@mid.individual.net>

Dennis Lee Bieber wrote:

> 	And is it supposed to handle
> 
> 	for london give the weather to me
> 	for the london weather give me

Or

         Where can I buy some new weather boarding for my
         house in London?

:-)

-- 
Greg

> 
> ...
> 
> 	Do a search on "natural language processing"... You are at the level
> of algorithms, and algorithms are not limited to Python...


From greg.ewing at canterbury.ac.nz  Mon May 17 03:39:40 2010
From: greg.ewing at canterbury.ac.nz (Gregory Ewing)
Date: Mon, 17 May 2010 19:39:40 +1200
Subject: Updating values in a dictionary
In-Reply-To: 
References: 
	
Message-ID: <85c9jhFv7fU1@mid.individual.net>

> On 5/16/2010 1:36 PM, Thomas wrote:
>> row = dict([(x,0) for x in range(3)])
>> matrix = dict([(x,row) for x in range(-3,4,1)])
>>
>> matrix[2][1] += 1
>> matrix[-1][2] += 1

Another possibility is to use a single dict with
tuples for the indexes.

   matrix = dict([((x, y), 0) for x in range(-3, 4) for y in range(3)])

   matrix[2, 1] += 1
   matrix[-1, 2] += 1

-- 
Greg


From greg.ewing at canterbury.ac.nz  Mon May 17 03:56:15 2010
From: greg.ewing at canterbury.ac.nz (Gregory Ewing)
Date: Mon, 17 May 2010 19:56:15 +1200
Subject: Global variables for python applications
In-Reply-To: <4bf09ce6$0$1661$742ec2ed@news.sonic.net>
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
Message-ID: <85caikF5auU1@mid.individual.net>

John Nagle wrote:
> Also, more compile-time arithmetic becomes possible.

But only if their values can be computed at compile time. This
leads to a huge can of worms if you want to be able to import
named constants from other modules. A large part of what
currently happens only at run time would have to become
possible at compile time as well. Either that or so many
restrictions would have to be placed on the way that the
values of named constants are specified that they would not
be very useful in practice.

>    I think there's some religious objection to constants in Python,

Not religious, but pragmatic. What appears to be a simple and
obvious idea on the surface turns out not to be nearly so simple
or obvious in a language as dynamic as Python.

-- 
Greg


From mannu_0523 at rediffmail.com  Mon May 17 04:25:37 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 17 May 2010 08:25:37 -0000
Subject: =?utf-8?B?UmU6IFJlOiBqb2luaW5nIGZpbGVz?=
In-Reply-To: <4bf03335$0$11843$9b536df3@news.fv.fi>
Message-ID: <1274034070.S.7524.33809.H.TlR1b21hcyBWZXN0ZXJpbmVuAFJlOiBqb2luaW5nIGZpbGVz.f4-234-216.old.1274084737.24357@webmail.rediffmail.com>


On Sun, 16 May 2010 23:51:10 +0530  wrote
>On 05/16/2010 05:04 PM, Dave Angel wrote:
> (You forgot to include the python-list in your response. So it only
> went to me. Normally, you just do reply-all to the message)
> mannu jha wrote:
>> On Sun, 16 May 2010 13:52:31 +0530 wrote
>>> mannu jha wrote:
>>> Hi,
>>> I have few files like this:
>>> file1:
>>> 22 110.1 33 331.5 22.7 5 271.9 17.2 33.4
>>> 4 55.1
>>> file1 has total 4 column but some of them are missing in few row.
>>> file2:
>>> 5 H
>>> 22 0
>>> file3:
>>> 4 T
>>> 5 B
>>> 22 C
>>> 121 S
>>> in all these files first column is the main source of matching their entries. So What I want in the output is only those entries which is coming in all three files. output required:
>>> 5 271.9 17.2 33.4 5 H 5 T
>>> 22 110.1 22 0 22 C
>> I am trying with this :
>> from collections import defaultdict
>> def merge(sources):
>> blanks = [blank for items, blank, keyfunc in sources]
>> d = defaultdict(lambda: blanks[:])
>> for index, (items, blank, keyfunc) in enumerate(sources):
>> for item in items:
>> d[keyfunc(item)][index] = item
>> for key in sorted(d):
>> yield d[key]
>> if __name__ == "__main__":
>> a = open("input1.txt")
>> c = open("input2.txt")
>> def key(line):
>> return line[:2]
>> def source(stream, blank="", key=key):
>> return (line.strip() for line in stream), blank, key
>> for m in merge([source(x) for x in [a,c]]):
>> print "|".join(c.ljust(10) for c in m)
>> but with input1.txt:
>> 187 7.79 122.27 54.37 4.26 179.75
>> 194 8.00 121.23 54.79 4.12 180.06
>> 15 8.45 119.04 55.02 4.08 178.89
>> 176 7.78 118.68 54.57 4.20 181.06
>> 180 7.50 119.21 53.93 179.80
>> 190 7.58 120.44 54.62 4.25 180.02
>> 152 8.39 120.63 55.10 4.15 179.10
>> 154 7.79 119.62 54.47 4.22 180.46
>> 175 8.42 120.50 55.31 4.04 180.33
>> and input2.txt:
>> 15 H 37 H 95 T
>> 124 H 130 H 152 H 154 H 158 H 164 H
>> 175 H 176 H 180 H
>> 187 H 190 T
>> 194 C
>> 196 H 207 H 210 H 232 H it is giving output as:
>> |
>> |124 H
>> |130 H
>> 154 7.79 119.62 54.47 4.22 180.46|158 H
>> |164 H
>> 175 8.42 120.50 55.31 4.04 180.33|176 H
>> 180 7.50 119.21 53.93 179.80|187 H
>> 190 7.58 120.44 54.62 4.25 180.02|196 H
>> |207 H
>> |210 H
>> |232 H
>> |37 H
>> |95 T
>> so it not matching it properly, can anyone please suggest where I am doing mistake.

import os

def merge_sources(sources):
   # sources is a list of tuples (source_name, source_data)
   data = []
   keysets = []
   for nme, sce in sources:
     lines = {}
     for line in sce.split(os.linesep):
       lst = line.split()
       lines[lst[0]] = (nme, lst)
     keysets.append(set(lines.keys()))
     data.append(lines)
   common_keys = keysets[0]
   for keys in keysets[1:]:
     common_keys = common_keys.intersection(keys)
   result = {}
   for key in common_keys:
     result[key] = dict(d[key] for d in data if key in d)
   return result
if __name__ == "__main__":
   # Your test files here are replaced by local strings
   print merge_sources([("file1", file1), ("file2", file2), ("file3", 
file3)])
   print merge_sources([("input1", input1), ("input2", input2)])
Test_results = '''
{'22': {'file3': ['22', 'C'],
     'file2': ['22', '0'],
     'file1': ['22', '110.1', '33', '331.5', '22.7', '5', '271.9',
          '17.2', '33.4']}}
{'194': {'input2': ['194', 'C'],
     'input1': ['194', '8.00', '121.23', '54.79', '4.12',
           '180.06']},
 '175': {'input2': ['175', 'H', '176', 'H', '180', 'H'],
     'input1': ['175', '8.42', '120.50', '55.31', '4.04',
           '180.33']},
  '15': {'input2': ['15', 'H', '37', 'H', '95', 'T'],
     'input1': ['15', '8.45', '119.04', '55.02', '4.08',
           '178.89']},
 '187': {'input2': ['187', 'H', '190', 'T'],
     'input1': ['187', '7.79', '122.27', '54.37', '4.26',
           '179.75']}}

Dear Sir,

I tried above program but with that it is showing error:
nmruser at caf:~> python join1.py
Traceback (most recent call last):
  File "join1.py", line 24, in 
    print merge_sources([("file1", file1), ("file2", file2), ("file3",
NameError: name 'file1' is not defined                                
nmruser at caf:~> 



-- 

http://mail.python.org/mailman/listinfo/python-list

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From greg.ewing at canterbury.ac.nz  Mon May 17 04:26:05 2010
From: greg.ewing at canterbury.ac.nz (Gregory Ewing)
Date: Mon, 17 May 2010 20:26:05 +1200
Subject: tone generation for motherboard and sound card speakers?
In-Reply-To: 
References: 
Message-ID: <4BF0FD9D.80004@canterbury.ac.nz>

Alex Hall wrote:

> Also, is there a module to generate tones in Python using the sound
> card? A module that can beep at a given frequency for a given time
> using the usual sine wave is okay, but the fancier the better
> (different waves, sweeping, and so on).
> 
> My final question will likely hinge upon the answer to the second
> question, but is there a way to play a tone in a given position in the
> stereo field?

The mixer module of pygame will do all of this, I think:

    http://www.pygame.org/

You may find the rest of pygame useful for implementing your
battleship game as well, if you haven't already chosen a library
for that.

-- 
Greg


From ershantibhushan at gmail.com  Mon May 17 04:34:51 2010
From: ershantibhushan at gmail.com (shanti bhushan)
Date: Mon, 17 May 2010 01:34:51 -0700 (PDT)
Subject: reading XML file using python
Message-ID: 

Hi ,
i am new to python.i want to read the XML file using python it ,by
using DOm or SAX any of them.
I want to read the http://www.google.com(any hyper text) from XML and
print that.
please give me the sample program for this.
regards
Shanti Bhushan
Bangalore,India


From stefan_ml at behnel.de  Mon May 17 05:01:24 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 17 May 2010 11:01:24 +0200
Subject: reading XML file using python
In-Reply-To: 
References: 
Message-ID: 

shanti bhushan, 17.05.2010 10:34:
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com (any hyper text) from XML and
> print that.

Note that web sites usually are HTML, not XML. Are you sure you want to 
read XML as well? Also, DOM/SAX are certainly not the easiest way to 
extract information from XML, use the xml.etree.ElementTree package instead.

To parse HTML from web pages, you can use several different tools in 
Python, see

http://www.google.com/search?q=python+web+scraping

Stefan



From mannu_0523 at rediffmail.com  Mon May 17 05:01:38 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 17 May 2010 09:01:38 -0000
Subject: =?utf-8?B?Rnc6IFJlOiBSZTogUmU6IGpvaW5pbmcgZmlsZXM=?=
Message-ID: <1274086839.S.12359.51906.f4mail-235-142.rediffmail.com.1274086897.56220@webmail.rediffmail.com>

Note: Forwarded message attached

-- Original Message --

From: "mannu jha"mannu_0523 at rediffmail.com
To: mannu_0523 at rediffmail.com
Subject: Re: Re: Re: joining files
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
An embedded message was scrubbed...
From: "mannu jha"
Subject: Re: Re: Re: joining files
Date: no date
Size: 12135
URL: 

From kelnreiter at gmail.com  Mon May 17 05:05:12 2010
From: kelnreiter at gmail.com (Franz Kelnreiter)
Date: Mon, 17 May 2010 11:05:12 +0200
Subject: reading XML file using python
In-Reply-To: 
References: 
Message-ID: 

2010/5/17 shanti bhushan :
> Hi ,
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com(any hyper text) from XML and
> print that.
> please give me the sample program for this.
Hi Shanti,
The question how to read an XML file has already been answerd more
than 50 times within this group. So I fear nobody wont any longer be
willing to repeat this matter every 15 days...
Greetings,
Franz


From simon at brunningonline.net  Mon May 17 05:12:39 2010
From: simon at brunningonline.net (Simon Brunning)
Date: Mon, 17 May 2010 10:12:39 +0100
Subject: reading XML file using python
In-Reply-To: 
References: 
Message-ID: 

On 17 May 2010 09:34:51 UTC+1, shanti bhushan  wrote:
> Hi ,
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com(any hyper text) from XML and
> print that.
> please give me the sample program for this.

Your question isn't very clear. Do you want to read the data from a
URL (such as http://www.google.com) and parse it? If so, you probably
don't want an XML parser as such - try Beautiful Soup.

Or do you have a piece of XML with some URLs in it that you want to
extract? ElementTree in the standard library is one good choice here
if you're not wedded to one of DOM or SAX.

What have you tried so far? No one is going to write code for you, but
we'd be happy to help you fix problems with your own code.
 might be worth a
read.

-- 
Cheers,
Simon B.


From steven at REMOVE.THIS.cybersource.com.au  Mon May 17 05:13:35 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 17 May 2010 09:13:35 GMT
Subject: Global variables for python applications
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
	<85caikF5auU1@mid.individual.net>
Message-ID: 

On Mon, 17 May 2010 19:56:15 +1200, Gregory Ewing wrote:

> John Nagle wrote:
>> Also, more compile-time arithmetic becomes possible.
> 
> But only if their values can be computed at compile time.

John said "more", not "everything imaginable can be calculated at compile 
time" :)

Python already does constant folding at compile time:


>>> code = compile('"abc"*2*3', '', 'single')
>>> dis.dis(code)
  1           0 LOAD_CONST               5 ('abcabcabcabcabcabc')
              3 PRINT_EXPR
              4 LOAD_CONST               3 (None)
              7 RETURN_VALUE



> This leads to
> a huge can of worms if you want to be able to import named constants
> from other modules.


Why? Once the module is loaded, the named constant is bound to an object. 
Provided that it can't be rebound or mutated, where's the can of worms?


> A large part of what currently happens only at run
> time would have to become possible at compile time as well. Either that
> or so many restrictions would have to be placed on the way that the
> values of named constants are specified that they would not be very
> useful in practice.

I disagree. Enforcing immutability would be tricky, but enforcing once-
only name binding is relatively simple. There's even a recipe for it in 
the Python Cookbook.




-- 
Steven


From switch2mathan at gmail.com  Mon May 17 05:24:07 2010
From: switch2mathan at gmail.com (gmail)
Date: Sun, 16 May 2010 21:24:07 -1200
Subject: Issue with PyUnicodeObject type variables
Message-ID: <128a593d08d.2531741629325199127.7040266275157033338@gmail.com>

A variable whose data type is PyUnicodeObject checked whether it is a UnicodeObject type.
Got output as false

example :

PyUnicodeObject *p; 

if (PyUnicode_Check(path)) {
        printf("\nTrue.\n");
        
}
else {
        printf("\nfalse.\n");
}

output: false


Confused what went wrong.

regards
mathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From utente at esempio.net  Mon May 17 05:24:34 2010
From: utente at esempio.net (superpollo)
Date: Mon, 17 May 2010 11:24:34 +0200
Subject: reading XML file using python
In-Reply-To: 
References: 
	
Message-ID: <4bf10b53$0$31374$4fafbaef@reader1.news.tin.it>

Simon Brunning ha scritto:
> On 17 May 2010 09:34:51 UTC+1, shanti bhushan  wrote:
>> Hi ,
>> i am new to python.i want to read the XML file using python it ,by
>> using DOm or SAX any of them.
>> I want to read the http://www.google.com(any hyper text) from XML and
>> print that.
>> please give me the sample program for this.
> 
> Your question isn't very clear. Do you want to read the data from a
> URL (such as http://www.google.com) and parse it? If so, you probably
> don't want an XML parser as such - try Beautiful Soup.

btw, is there any chance that bs will be part of the stdlib anytime soon?

bye


From stefan_ml at behnel.de  Mon May 17 05:33:40 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 17 May 2010 11:33:40 +0200
Subject: Issue with PyUnicodeObject type variables
In-Reply-To: <128a593d08d.2531741629325199127.7040266275157033338@gmail.com>
References: <128a593d08d.2531741629325199127.7040266275157033338@gmail.com>
Message-ID: 

gmail, 17.05.2010 11:24:
> A variable whose data type is PyUnicodeObject checked whether it is a UnicodeObject type.
> Got output as false
>
> example :
>
> PyUnicodeObject *p;
> if (PyUnicode_Check(path)) {
>          printf("\nTrue.\n");
>
> }
> else {
>          printf("\nfalse.\n");
> }
>
> output: false

Doesn't surprise me at all. Could you make sure this is the code you are 
using? Especially the names 'p' and 'path'? And that you are initialising 
neither of the two in your code?

Stefan



From stefan_ml at behnel.de  Mon May 17 05:35:21 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 17 May 2010 11:35:21 +0200
Subject: reading XML file using python
In-Reply-To: <4bf10b53$0$31374$4fafbaef@reader1.news.tin.it>
References: 	
	<4bf10b53$0$31374$4fafbaef@reader1.news.tin.it>
Message-ID: 

superpollo, 17.05.2010 11:24:
> Simon Brunning ha scritto:
>> On 17 May 2010 09:34:51 UTC+1, shanti bhushan wrote:
>>> i am new to python.i want to read the XML file using python it ,by
>>> using DOm or SAX any of them.
>>> I want to read the http://www.google.com(any hyper text) from XML and
>>> print that.
>>> please give me the sample program for this.
>>
>> Your question isn't very clear. Do you want to read the data from a
>> URL (such as http://www.google.com) and parse it? If so, you probably
>> don't want an XML parser as such - try Beautiful Soup.
>
> btw, is there any chance that bs will be part of the stdlib anytime soon?

If someone takes over maintainership and offers support for the stdlib, 
this might be worth discussing. Otherwise, no.

Stefan



From simon at brunningonline.net  Mon May 17 05:49:38 2010
From: simon at brunningonline.net (Simon Brunning)
Date: Mon, 17 May 2010 10:49:38 +0100
Subject: reading XML file using python
In-Reply-To: 
References: 
	
	
Message-ID: 

On 17 May 2010 10:43:06 UTC+1, Shanti Bhushan  wrote:
> Hi simon,
> you are right in 2nd paragaraph.
> i have a piece of XML with some URLs in it that?i want to
> extract.
> I have no clue from where to get help on this.
> Please atleast guide me for document or link where i can get such help
> i can use elementary tree also but i dont know how to proceed with that.

You've not given us any idea as to the structure of your XML, so this
won't work. ;-)

import xml.etree.ElementTree as ET

for node in ET.parse('our.xml'):
    print node.text

An introduction to ElementTree at .

-- 
Cheers,
Simon B.


From jmheralds at gmail.com  Mon May 17 06:05:58 2010
From: jmheralds at gmail.com (James Heralds)
Date: Mon, 17 May 2010 03:05:58 -0700 (PDT)
Subject: Call for papers: SETP-10, USA, July 2010
Message-ID: <64a2e2d5-5416-4831-870f-1fd07ec524b7@r9g2000vbk.googlegroups.com>

It would be highly appreciated if you could share this announcement
with your colleagues, students and individuals whose research is in
software engineering, software testing, software quality assurance,
software design and related areas.

Call for papers: SETP-10, USA, July 2010

The 2010 International Conference on Software Engineering Theory and
Practice (SETP-10) (website: http://www.PromoteResearch.org ) will be
held during 12-14 of July 2010 in Orlando, FL, USA.  SETP is an
important event in the areas of Software development, maintenance, and
other areas of software engineering and related topics.

The conference will be held at the same time and location where
several other major international conferences will be taking place.
The conference will be held as part of 2010 multi-conference
(MULTICONF-10). MULTICONF-10 will be held during July 12-14, 2010 in
Orlando, Florida, USA. The primary goal of MULTICONF is to promote
research and developmental activities in computer science, information
technology, control engineering, and related fields. Another goal is
to promote the dissemination of research to a multidisciplinary
audience and to facilitate communication among researchers,
developers, practitioners in different fields. The following
conferences are planned to be organized as part of MULTICONF-10.

?	International Conference on Artificial Intelligence and Pattern
Recognition (AIPR-10)
?	 International Conference on Automation, Robotics and Control
Systems (ARCS-10)
?	International Conference on Bioinformatics, Computational Biology,
Genomics and Chemoinformatics (BCBGC-10)
?	International Conference on Computer Communications and Networks
(CCN-10)
?	International Conference on Enterprise Information Systems and Web
Technologies (EISWT-10)
?	International Conference on High Performance Computing Systems
(HPCS-10)
?	International Conference on Information Security and Privacy
(ISP-10)
?	International Conference on Image and Video Processing and Computer
Vision (IVPCV-10)
?	International Conference on Software Engineering Theory and Practice
(SETP-10)
?	International Conference on Theoretical and Mathematical Foundations
of Computer Science (TMFCS-10)

MULTICONF-10 will be held at Imperial Swan Hotel and Suites.  It is a
full-service resort that puts you in the middle of the fun! Located
1/2 block south of the famed International Drive, the hotel is just
minutes from great entertainment like Walt Disney World? Resort,
Universal Studios and Sea World Orlando. Guests can enjoy free
scheduled transportation to these theme parks, as well as spacious
accommodations, outdoor pools and on-site dining ? all situated on 10
tropically landscaped acres. Here, guests can experience a full-
service resort with discount hotel pricing in Orlando.


We invite draft paper submissions. Please see the website
http://www.PromoteResearch.org  for more details.

Sincerely
James Heralds


From switch2mathan at gmail.com  Mon May 17 06:12:45 2010
From: switch2mathan at gmail.com (mathan kumar)
Date: Mon, 17 May 2010 15:42:45 +0530
Subject: Conversion method for PyUnicodeObject type to PyBytesObject type
Message-ID: 

A variable whose data type is PyUnicodeObject needs to be passed to a
function as an argument whose data type should be PyBytesObject type

example :
function (PyByteObject* a){
.....operations....
}
PyUnicodeObject *p = somevalue;
function((PyBytesObject *)p);

ouptut: Got a Bus Error.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From switch2mathan at gmail.com  Mon May 17 06:16:34 2010
From: switch2mathan at gmail.com (mathan kumar)
Date: Mon, 17 May 2010 15:46:34 +0530
Subject: Issue with PyUnicodeObject type variables
Message-ID: 

---------- Forwarded message ----------
From: Stefan Behnel 
To: python-list at python.org
Date: Mon, 17 May 2010 11:33:40 +0200
Subject: Re: Issue with PyUnicodeObject type variables
gmail, 17.05.2010 11:24:

> A variable whose data type is PyUnicodeObject checked whether it is a
> UnicodeObject type.
> Got output as false
>
> example :
>
> PyUnicodeObject *p;
> if (PyUnicode_Check(path)) {
>         printf("\nTrue.\n");
>
> }
> else {
>         printf("\nfalse.\n");
> }
>
> output: false
>

Doesn't surprise me at all. Could you make sure this is the code you are
using? Especially the names 'p' and 'path'? And that you are initialising
neither of the two in your code?

Stefan


Tat was a typo mistake instead of *p pls consider *path as follows.

PyUnicodeObject *path;
if (PyUnicode_Check(path)) {
        printf("\nTrue.\n");

}
else {
        printf("\nfalse.\n");
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From eric.brunel.pragmadev at gmail.com  Mon May 17 06:18:37 2010
From: eric.brunel.pragmadev at gmail.com (eb303)
Date: Mon, 17 May 2010 03:18:37 -0700 (PDT)
Subject: platform-independent image copy/paste with Tkinter?
References: 
Message-ID: <74406aa5-e570-40d5-97c8-e638c37810e2@j27g2000vbp.googlegroups.com>

On May 15, 4:56?pm, technocake  wrote:
> Hi.
>
> Is there a good way to copy from or paste to the clipboard on all
> systems running python using Tkinter?
> started a small road too it here:
>
> #!/usr/bin/python
> __author__="technocake"
> __date__ ="$15.mai.2010 15:53:39$"
>
> from Tkinter import *
>
> if __name__ == "__main__":
>
> ? ? def displayClipboard(event):
> ? ? ? ? try:
> ? ? ? ? ? ? data = event.widget.clipboard_get(type="STRING")
> ? ? ? ? except :
> ? ? ? ? ? ? #Need a method for displaying a image here..
> ? ? ? ? ? ? data = "Image" #
> ? ? ? ? finally: #Updates the textlabel
> ? ? ? ? ? ? lbl.config(text=data)
>
> ? ? root = Tk()
> ? ? lbl= Label(root, width=20)
> ? ? lbl.bind("", displayClipboard) #binding to leftclick
> ? ? lbl.pack()
>
> ? ? root.mainloop()

The copy part is done via the methods clipboard_clear and
clipboard_append, available on all Tkinter widgets. By the way, the
default value for the 'type' option is 'STRING', so you actually don't
need it here, and neither do you in clipboard_append.

To be able to copy/paste images is much more platform dependent. There
are actually types for clipboard contents that handle images, but they
will vary from platform to platform and sometimes from application to
application. You can even have several types for the same contents. To
get these, you can use:
widget.selection_get(selection='CLIPBOARD', type='TARGETS')
You can try to copy an image on various platforms with various
applications, then print the value for this expression to figure out
what you can do with it.

HTH
 - Eric -


From kaklis at gmail.com  Mon May 17 06:23:03 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Mon, 17 May 2010 03:23:03 -0700 (PDT)
Subject: parsing XML
References: 
	<4beec709$0$18653$4fafbaef@reader3.news.tin.it>
	 
	 
	
Message-ID: <8ff02667-182e-4fad-a621-9eaa4437ad25@p17g2000vbe.googlegroups.com>

On May 16, 10:52?am, Stefan Behnel  wrote:
> Jake b, 16.05.2010 09:40:
>
> > Check out Amara:http://www.xml3k.org/Amara/QuickRef
>
> > It looks promising. For a pythonic solution over sax / dom.
>
> > >>> Iter(doc.team.player)
> > # or
> > >>> doc.team.player[0].name
>
> Ah, right, and there's also lxml.objectify:
>
> ? ? ?from lxml.objectify import parse
>
> ? ? ?root = parse('teamfile.xml').getroot()
>
> ? ? ?for player in root.player:
> ? ? ? ? ?print(player.attrib)
>
> Prints an attribute dict for each player.
>
> Stefan

Thank you all so much!!!
And it's not for a homework.
Just trying to find out the style DOM, SAX, ElementTree etc. that fits
better to my kind of thinking.
Antonis


From stefan_ml at behnel.de  Mon May 17 06:27:05 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 17 May 2010 12:27:05 +0200
Subject: Issue with PyUnicodeObject type variables
In-Reply-To: 
References: 
Message-ID: 

mathan kumar, 17.05.2010 12:16:
> From: Stefan Behnel
>> Doesn't surprise me at all. Could you make sure this is the code you are
>> using? Especially the names 'p' and 'path'? And that you are initialising
>> neither of the two in your code?
>
> Tat was a typo mistake instead of *p pls consider *path as follows.
>
> PyUnicodeObject *path;
> if (PyUnicode_Check(path)) {

Again, you are not initialising the pointer, so it contains an arbitrary 
value when you run the program. You are lucky that it gives you a result at 
all, instead of just plain crashing.

You do not seem to have much experience with C. Is there any reason why you 
want to use it? Or is this just for curiosity?

Stefan



From bryanjugglercryptographer at yahoo.com  Mon May 17 06:42:43 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Mon, 17 May 2010 03:42:43 -0700 (PDT)
Subject: an element from a set
References: <28560792.post@talk.nabble.com>
	 
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com> 
	
	<248cbfa6-5992-4bc3-bef6-a240a901a07b@42g2000prb.googlegroups.com>
Message-ID: <84fd3929-ab9c-4e7d-9d3f-533f4313d7eb@q36g2000prg.googlegroups.com>

Carl Banks wrote:
[...]
>?Random element from a set is such a natural idea.
>
> Even if we were to modify the set type at the C level to support it, I
> can't think of an easy way to get a random element without selection
> bias. ?For instance, if you start from a random hash code, some
> elements are more likely to be selected than others, depending on
> distance between entries in the hash table. ?You'd probably have to
> choose an number in range(len(s)) and count off that many, but then
> might as well have just converted it to a list or used an iterator. ?A
> little disappointing, actually.
>
> Probably the "right" way is to use a binary-tree-based set.

There's a reasonably straightforward solution supporting O(1) time
random choice that also preserves the O(1) average-case time of set's
add(), remove(), and 'in'. The trick is to keep each element in both a
list and a hash table. Implementing Python's entire set interface is a
bit of project, so the code below just supports enough for a demo.

-Bryan Olson

# --------

from random import choice

class SetWithRandom:

    def __init__(self, *args):
        self.lst = list(*args)
        self.dct = dict((elem, i) for (i, elem) in
                enumerate(self.lst))

    def audit(self):
        # Test consistency of dict and list.
        assert len(self.lst) == len(self.dct)
        for elem in self.dct:
            assert self.lst[self.dct[elem]] == elem

    def random(self):
        return choice(self.lst)

    def add(self, elem):
        if elem not in self.dct:
            self.dct[elem] = len(self.lst)
            self.lst.append(elem)

    def remove(self, elem):
        index = self.dct[elem]
        # Move the last item into vacated index.
        mover = self.lst[-1]
        self.lst[index] = mover
        self.dct[mover] = index
        del self.dct[elem]
        self.lst.pop()

    def __len__(self):
        return len(self.lst)

    def __contains__(self, elem):
        return elem in self.dct

    def __iter__(self):
        return self.dct.__iter__()


# ---------
# Test against Python's built-in set.
for i in range(0, 100, 20):
    trange = list(range(1000, 1000 + i))
    pyset = set(trange)
    testset = SetWithRandom(pyset)
    testset.audit()
    assert pyset == set(testset)
    rands = set(testset.random() for _ in trange)
    assert len(rands) >= i / 4
    while pyset:
        randx = testset.random()
        pyset.remove(randx)
        testset.remove(randx)
        testset.audit()
        for _ in range(choice([0, 0, 1, 2])):
            randx = choice(trange)
            pyset.add(randx)
            testset.add(randx)
        assert pyset == set(testset)
    assert not testset



From kaklis at gmail.com  Mon May 17 08:11:25 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Mon, 17 May 2010 05:11:25 -0700 (PDT)
Subject: cmd with three arguments
Message-ID: 

Hi pythonistas,
While playing with the Python Standard Library, i came across "cmd".
So I'm trying to make a console application. Everything works fine, i
created many function with do_....(self, line) prefix, but when i
tried to create a function with more arguments
 i can't make it work.  e.g
def do_connect(self, ip, command):

>>> connect 127.0.0.1 delete
 Are there any work arounds

Thanks in advance

Antonis


From python.list at tim.thechases.com  Mon May 17 09:12:39 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Mon, 17 May 2010 08:12:39 -0500
Subject: cmd with three arguments
In-Reply-To: 
References: 
Message-ID: <4BF140C7.3030502@tim.thechases.com>

On 05/17/2010 07:11 AM, kaklis at gmail.com wrote:
> While playing with the Python Standard Library, i came across "cmd".
> So I'm trying to make a console application. Everything works fine, i
> created many function with do_....(self, line) prefix, but when i
> tried to create a function with more arguments
>   i can't make it work.  e.g
> def do_connect(self, ip, command):
>
>>>> connect 127.0.0.1 delete
>   Are there any work arounds

You simply receive all the text after the command:

   class C(Cmd):
     def do_thing(self, arguments):
       print repr(arguments)

If you want to split it, you can do it boringly:

     def do_thing(self, arguments):
       args = arguments.split()

or you can let Python's standard library do some heavy-lifting 
for you:

   import shlex
   #...
     def do_thing(self, arguments):
       args = shlex.split(arguments)

-tkc





From oxfordenergyservices at googlemail.com  Mon May 17 09:20:42 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Mon, 17 May 2010 06:20:42 -0700 (PDT)
Subject: python application question
Message-ID: <8df6cb20-f822-4286-a075-2633c6025e84@z17g2000vbd.googlegroups.com>

I am trying to write an application that takes two files from over the
internet and plots one against the other

i am getting the data ok.

if i want to plot it i have to use something like matplotlib?  but
this doesn't come with the standard installation.  so if i want
someone else to use this application, do they have to install
matplotlib themselves or is there a better way?

ps someone helped me with enumerate(), which works on the linux but
not on the windows?

thanks


From kaklis at gmail.com  Mon May 17 09:25:30 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Mon, 17 May 2010 06:25:30 -0700 (PDT)
Subject: cmd with three arguments
References: 
	
Message-ID: <2897c931-8809-4a3f-9dc8-d05e74a376d7@z17g2000vbd.googlegroups.com>

On May 17, 4:12?pm, Tim Chase  wrote:
> On 05/17/2010 07:11 AM, kak... at gmail.com wrote:
>
> > While playing with the Python Standard Library, i came across "cmd".
> > So I'm trying to make a console application. Everything works fine, i
> > created many function with do_....(self, line) prefix, but when i
> > tried to create a function with more arguments
> > ? i can't make it work. ?e.g
> > def do_connect(self, ip, command):
>
> >>>> connect 127.0.0.1 delete
> > ? Are there any work arounds
>
> You simply receive all the text after the command:
>
> ? ?class C(Cmd):
> ? ? ?def do_thing(self, arguments):
> ? ? ? ?print repr(arguments)
>
> If you want to split it, you can do it boringly:
>
> ? ? ?def do_thing(self, arguments):
> ? ? ? ?args = arguments.split()
>
> or you can let Python's standard library do some heavy-lifting
> for you:
>
> ? ?import shlex
> ? ?#...
> ? ? ?def do_thing(self, arguments):
> ? ? ? ?args = shlex.split(arguments)
>
> -tkc

Thanks, great answer!!!


From __peter__ at web.de  Mon May 17 09:34:10 2010
From: __peter__ at web.de (Peter Otten)
Date: Mon, 17 May 2010 15:34:10 +0200
Subject: cmd with three arguments
References: 
Message-ID: 

kaklis at gmail.com wrote:

> Hi pythonistas,
> While playing with the Python Standard Library, i came across "cmd".
> So I'm trying to make a console application. Everything works fine, i
> created many function with do_....(self, line) prefix, but when i
> tried to create a function with more arguments
>  i can't make it work.  e.g
> def do_connect(self, ip, command):
> 
>>>> connect 127.0.0.1 delete
>  Are there any work arounds
> 
> Thanks in advance
> 
> Antonis

You have to split the user input into arguments yourself. You can do this in 
the body of the do_xxx() methods, use a decorator, or subclass cmd.Cmd.

Here's a solution using a decorator:

import cmd
import inspect
import shlex

def split(f):
    def g(self, line):
        argvalues = shlex.split(line)
        argnames = inspect.getargspec(f).args
        argcount = len(argnames) - 1
        if len(argvalues) != argcount:
            print "Need exactly %d args" % argcount
            return
        return f(self, *argvalues)
    return g

class Cmd(cmd.Cmd):
    @split
    def do_connect(self, ip, command):
        print "ip=%r, command=%r" % (ip, command)


if __name__ == "__main__":
    c = Cmd()
    c.cmdloop()

And here's a subclass that avoids the need for explicit @split decorations:

import cmd
import inspect
import shlex

def split(f):
    def g(line):
        argvalues = shlex.split(line)
        argnames = inspect.getargspec(f).args
        argcount = len(argnames) -1
        if len(argvalues) != argcount:
            print "Need exactly %d args" % argcount
            return
        return f(*argvalues)
    return g

class CmdBase(cmd.Cmd, object):
    def __getattribute__(self, name):
        attr = object.__getattribute__(self, name)
        if name.startswith("do_"):
            attr = split(attr)
        return attr

class Cmd(CmdBase):
    def do_connect(self, ip, command):
        print "ip=%r, command=%r" % (ip, command)


if __name__ == "__main__":
    c = Cmd()
    c.cmdloop()

Now you've got an idea of the general direction you can certainly come up 
with something less hackish ;)

Peter


From mouadino at gmail.com  Mon May 17 09:35:11 2010
From: mouadino at gmail.com (mouadino)
Date: Mon, 17 May 2010 06:35:11 -0700 (PDT)
Subject: abc don't play well with private method
References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com>
	<4be18d3d$0$19014$426a34cc@news.free.fr>
Message-ID: 

Hello
and thanx for your answer it's was very helpful

but just to clear some thinks :

> There's no such thing as a "private" attribute in Python. The
> name-mangling mechanism invoked by "__name" is really meant to avoid
> accidental redefinition of the attribute in a derived class.

> In this case, your attribute is expected to be redefined, so you
> definitly don't want any name mangling here.

yes , but what i have supposed is that the name mangling will not be
applied when you use abc especially when you decorate the function
with abc.abstractmethod , because it's will(should) be redefined (so
something is wrong with the abc module) .

> Also and FWIW, the naming convention for "implementation attributes" is
> a single leading underscore

sorry but i don't agree on this. the two underscore (__) are used in
classes level for defining private method in the python way, and the
one underscore (_) is used in the module level :

"""Prepending a single underscore (_) has some support for protecting
module variables and functions (not included with import * from).
Prepending a double underscore (__) to an instance variable or method
effectively serves to make the variable or method private to its class
(using name mangling). """
src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

> > ? ? def close(self):
>
> > ? ? ? ? self.close()
>
> > ? ? def quit(self):
>
> > ? ? ? ? self.quit()
>
> Don't you see kind of a problem here ? Something like, say, an infinite
> recursion ?

yep , thanx




From mouadino at gmail.com  Mon May 17 09:35:42 2010
From: mouadino at gmail.com (mouadino)
Date: Mon, 17 May 2010 06:35:42 -0700 (PDT)
Subject: abc don't play well with private method
References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com>
	<4be18d3d$0$19014$426a34cc@news.free.fr>
Message-ID: <65ef6ef8-efe5-4d00-9700-e23c9cffae3f@o1g2000vbe.googlegroups.com>

Hello
and thanx for your answer it's was very helpful

but just to clear some thinks :

> There's no such thing as a "private" attribute in Python. The
> name-mangling mechanism invoked by "__name" is really meant to avoid
> accidental redefinition of the attribute in a derived class.

> In this case, your attribute is expected to be redefined, so you
> definitly don't want any name mangling here.

yes , but what i have supposed is that the name mangling will not be
applied when you use abc especially when you decorate the function
with abc.abstractmethod , because it's will(should) be redefined (so
something is wrong with the abc module) .

> Also and FWIW, the naming convention for "implementation attributes" is
> a single leading underscore

sorry but i don't agree on this. the two underscore (__) are used in
classes level for defining private method in the python way, and the
one underscore (_) is used in the module level :

"""Prepending a single underscore (_) has some support for protecting
module variables and functions (not included with import * from).
Prepending a double underscore (__) to an instance variable or method
effectively serves to make the variable or method private to its class
(using name mangling). """
src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

> > ? ? def close(self):
>
> > ? ? ? ? self.close()
>
> > ? ? def quit(self):
>
> > ? ? ? ? self.quit()
>
> Don't you see kind of a problem here ? Something like, say, an infinite
> recursion ?

yep , thanx




From kaklis at gmail.com  Mon May 17 09:36:44 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Mon, 17 May 2010 06:36:44 -0700 (PDT)
Subject: cmd with three arguments
References: 
	
Message-ID: 

On May 17, 4:34?pm, Peter Otten <__pete... at web.de> wrote:
> kak... at gmail.com wrote:
> > Hi pythonistas,
> > While playing with the Python Standard Library, i came across "cmd".
> > So I'm trying to make a console application. Everything works fine, i
> > created many function with do_....(self, line) prefix, but when i
> > tried to create a function with more arguments
> > ?i can't make it work. ?e.g
> > def do_connect(self, ip, command):
>
> >>>> connect 127.0.0.1 delete
> > ?Are there any work arounds
>
> > Thanks in advance
>
> > Antonis
>
> You have to split the user input into arguments yourself. You can do this in
> the body of the do_xxx() methods, use a decorator, or subclass cmd.Cmd.
>
> Here's a solution using a decorator:
>
> import cmd
> import inspect
> import shlex
>
> def split(f):
> ? ? def g(self, line):
> ? ? ? ? argvalues = shlex.split(line)
> ? ? ? ? argnames = inspect.getargspec(f).args
> ? ? ? ? argcount = len(argnames) - 1
> ? ? ? ? if len(argvalues) != argcount:
> ? ? ? ? ? ? print "Need exactly %d args" % argcount
> ? ? ? ? ? ? return
> ? ? ? ? return f(self, *argvalues)
> ? ? return g
>
> class Cmd(cmd.Cmd):
> ? ? @split
> ? ? def do_connect(self, ip, command):
> ? ? ? ? print "ip=%r, command=%r" % (ip, command)
>
> if __name__ == "__main__":
> ? ? c = Cmd()
> ? ? c.cmdloop()
>
> And here's a subclass that avoids the need for explicit @split decorations:
>
> import cmd
> import inspect
> import shlex
>
> def split(f):
> ? ? def g(line):
> ? ? ? ? argvalues = shlex.split(line)
> ? ? ? ? argnames = inspect.getargspec(f).args
> ? ? ? ? argcount = len(argnames) -1
> ? ? ? ? if len(argvalues) != argcount:
> ? ? ? ? ? ? print "Need exactly %d args" % argcount
> ? ? ? ? ? ? return
> ? ? ? ? return f(*argvalues)
> ? ? return g
>
> class CmdBase(cmd.Cmd, object):
> ? ? def __getattribute__(self, name):
> ? ? ? ? attr = object.__getattribute__(self, name)
> ? ? ? ? if name.startswith("do_"):
> ? ? ? ? ? ? attr = split(attr)
> ? ? ? ? return attr
>
> class Cmd(CmdBase):
> ? ? def do_connect(self, ip, command):
> ? ? ? ? print "ip=%r, command=%r" % (ip, command)
>
> if __name__ == "__main__":
> ? ? c = Cmd()
> ? ? c.cmdloop()
>
> Now you've got an idea of the general direction you can certainly come up
> with something less hackish ;)
>
> Peter

Thanks great advice!
Antonis


From mouadino at gmail.com  Mon May 17 09:36:44 2010
From: mouadino at gmail.com (mouadino)
Date: Mon, 17 May 2010 06:36:44 -0700 (PDT)
Subject: abc don't play well with private method
References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com>
	<4be18d3d$0$19014$426a34cc@news.free.fr>
Message-ID: <148e3e6a-b4a9-4041-8951-9f965927a3c0@b21g2000vbh.googlegroups.com>

Hello
and thanx for your answer it's was very helpful

but just to clear some thinks :

> There's no such thing as a "private" attribute in Python. The
> name-mangling mechanism invoked by "__name" is really meant to avoid
> accidental redefinition of the attribute in a derived class.

> In this case, your attribute is expected to be redefined, so you
> definitly don't want any name mangling here.

yes , but what i have supposed is that the name mangling will not be
applied when you use abc especially when you decorate the function
with abc.abstractmethod , because it's will(should) be redefined (so
something is wrong with the abc module) .

> Also and FWIW, the naming convention for "implementation attributes" is
> a single leading underscore

sorry but i don't agree on this. the two underscore (__) are used in
classes level for defining private method in the python way, and the
one underscore (_) is used in the module level :

"""Prepending a single underscore (_) has some support for protecting
module variables and functions (not included with import * from).
Prepending a double underscore (__) to an instance variable or method
effectively serves to make the variable or method private to its class
(using name mangling). """
src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

> > ? ? def close(self):
>
> > ? ? ? ? self.close()
>
> > ? ? def quit(self):
>
> > ? ? ? ? self.quit()
>
> Don't you see kind of a problem here ? Something like, say, an infinite
> recursion ?

yep , thanx




From jayeola at gmail.com  Mon May 17 09:37:55 2010
From: jayeola at gmail.com (John Maclean)
Date: Mon, 17 May 2010 14:37:55 +0100
Subject: pythonic ssh
Message-ID: <4BF146B3.2070207@gmail.com>

hi,

pyssh, pexpect, paramiko or creating your your own sockets. what do you 
use to pythonically ssh to boxes?


-- 
John Maclean
MSc. (DIC) BSc. (Hons)
Linux Systems and Applications
07739 171 531


From awilliam at whitemice.org  Mon May 17 09:45:44 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Mon, 17 May 2010 09:45:44 -0400
Subject: python application question
In-Reply-To: <8df6cb20-f822-4286-a075-2633c6025e84@z17g2000vbd.googlegroups.com>
References: <8df6cb20-f822-4286-a075-2633c6025e84@z17g2000vbd.googlegroups.com>
Message-ID: <1274103944.9420.2.camel@linux-yu4c.site>

On Mon, 2010-05-17 at 06:20 -0700, a wrote:
> if i want to plot it i have to use something like matplotlib?  but
> this doesn't come with the standard installation.  so if i want
> someone else to use this application, do they have to install
> matplotlib themselves or is there a better way?

Use PyPI to distribute your application and declare matplotlib as a
requirement in your setup.py.  Then when they easy_install it should
take care of it.



From pacman128 at gmail.com  Mon May 17 09:52:26 2010
From: pacman128 at gmail.com (Paul Carter)
Date: Mon, 17 May 2010 06:52:26 -0700 (PDT)
Subject: imports and exec
References: <20297a4b-6fc8-4fa0-a203-decdd2586805@l18g2000vbn.googlegroups.com>
	
Message-ID: 

On May 16, 4:22?pm, Patrick Maupin  wrote:
> On May 16, 1:51?pm, Paul Carter  wrote:
>
>
>
> > We are using python for our build system. Each subproject dir has a
> > python script that builds it. Parent dirs have python scripts that
> > recurse into their children and use exec to invoke the python scripts.
> > Recently we discovered that one of the python scripts works when
> > invoked directly, but fails when invoked with exec. I've created a
> > very simple pair of python scripts that demonstrates the problem.
> > (We're using python 2.6)
>
> > Can someone explain or point to a good explanation of why this problem
> > occurs?
>
> > I have two python files: prim.py and sec.py.
> > prim.py:
> > -----------------------------------------
> > #!/usr/bin/env python
>
> > ##sec2 = open('sec.py')
> > ##exec sec2
>
> > def invoke():
> > ? sec = open('sec.py')
> > ? exec sec
>
> > invoke()
> > ------------------------------
>
> > and sec.py:
> > ----------------------------------
> > import sys
>
> > def sec():
> > ? print('Inside sec(): ' + ?str(sys.argv))
>
> > print('Outside sec(): ' + str(sys.argv))
> > sec()
> > --------------------------------------
>
> > When I run prim.py, I get an error:
> > --------------------------------
> > Outside sec(): ['./prim.py']
> > Traceback (most recent call last):
> > ? File "./prim.py", line 10, in 
> > ? ? invoke()
> > ? File "./prim.py", line 8, in invoke
> > ? ? exec sec
> > ? File "sec.py", line 7, in 
> > ? ? sec()
> > ? File "sec.py", line 4, in sec
> > ? ? print('Inside sec(): ' + ?str(sys.argv))
> > NameError: global name 'sys' is not defined
> > ----------------------------------
>
> > I don't understand why the sys import is not visible in the sec()
> > function. I can fix this by adding a:
> > ? global sys
> > or
> > ? import sys
> > inside the sec() function. But I would like to understand why this is
> > necessary, especially since sys is visible in sec.py outside of the
> > sec() function. I found this page discussing exec
>
> >http://docs.python.org/reference/executionmodel.html
>
> > but I'm afraid I couldn't quite follow it. It makes me think that a
> > free variable is involved, but I don't see how. It did made me try
> > invoking exec in prim.py outside of the invoke() function (see the
> > commented out code). Everything worked fine when I did that.
>
> > Can someone set me straight? Suggestions on avoiding this problem are
> > welcome as well!
>
> > Thanks in advance.
>
> Yes. ?Since you did not pass any dictionaries to your exec of "sec",
> sec inherited the globals and locals from the calling function. ?So
> the import of sys happened in that functions locals (bad practice in
> any case) and the globals used by sec() are the globals of your main
> module.
>
> Especially if invoked from inside a function, you should always pass a
> dict to exec. ?Just "exec sec() in {}" will do the trick. ?But if you
> want to use your caller's dictionaries, you can do "exec sec() in
> globals()" ?But you should *not* use a functions locals directly if
> you are going to modify them (as you are currently doing).
>
> Regards,
> Pat

Thanks, that helped a lot! I was misunderstanding what exec does by
default.

--
Paul


From pmaupin at gmail.com  Mon May 17 09:58:13 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Mon, 17 May 2010 06:58:13 -0700 (PDT)
Subject: python application question
References: <8df6cb20-f822-4286-a075-2633c6025e84@z17g2000vbd.googlegroups.com>
Message-ID: <8ee69746-422b-4c25-b8b4-247218c196c5@o12g2000vba.googlegroups.com>

On May 17, 8:20?am, a  wrote:

> ps someone helped me with enumerate(), which works on the linux but
> not on the windows?

enumerate() works fine on windows.  Perhaps your windows box has a
really old Python?

Regards,
Pat


From schettino72 at gmail.com  Mon May 17 10:11:31 2010
From: schettino72 at gmail.com (Eduardo Schettino)
Date: Mon, 17 May 2010 22:11:31 +0800
Subject: [ANN] doit - automation tool 0.8 released
Message-ID: 

pypi: http://pypi.python.org/pypi/doit
homepage: http://python-doit.sourceforge.net/


`doit` comes from the idea of bringing the power of build-tools to
execute any kind of task. It will keep track of dependencies between
"tasks" and execute them only when necessary. It was designed to be
easy to use and "get out of your way".

Features:

 * Easy to use, "no-API"
 * Use python to dynamically create tasks on-the-fly
 * Flexible, adapts to many workflows for creation of tasks/rules/recipes
 * Support for multi-process parallel execution
 * Built-in integration of inotify (automatically re-execution)

`doit` can be used as:

 * a build tool (generic and flexible)
 * home of your management scripts (it helps you organize and combine
shell scripts and python scripts)
 * a functional tests runner (combine together different tools)


From mannu_0523 at rediffmail.com  Mon May 17 10:24:28 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 17 May 2010 14:24:28 -0000
Subject: =?utf-8?B?Rnc6IFJlOiBSZTogam9pbmluZyBmaWxlcw==?=
Message-ID: <1274106232.S.7666.37655.f4mail-234-211.rediffmail.com.1274106266.38667@webmail.rediffmail.com>

Note: Forwarded message attached

-- Original Message --

From: "mannu jha"mannu_0523 at rediffmail.com
To: tuomas.vesterinen at iki.fi
Subject: Re: Re: joining files
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
An embedded message was scrubbed...
From: "mannu jha"
Subject: Re: Re: joining files
Date: no date
Size: 7506
URL: 

From cjw at ncf.ca  Mon May 17 10:57:40 2010
From: cjw at ncf.ca (cjw)
Date: Mon, 17 May 2010 10:57:40 -0400
Subject: Access to comp.lang.python
In-Reply-To: 
References: 					
	
Message-ID: 

On 16-May-10 12:47 PM, Jim Byrnes wrote:
> Grant Edwards wrote:
>> On 2010-05-16, cjw wrote:
>>> On 16-May-10 01:31 AM, James Mills wrote:
>>>> On Sun, May 16, 2010 at 3:12 PM, Aahz wrote:
>>>>> It's also at least partly due to problems with mail<->news gateways
>>>>> and
>>>>> the differing fields used to maintain threading.
>>>>
>>>> Some blame goes on MUAs too :)
>>>
>>> Thanks for the responses.
>>>
>>> Is it possible to connect a newsreader to gmane?
>>
>> nntp://news.gmane.org/
>>
>
> Could someone please explain how to subscribe to this list on gmane. I
> subscribe to a couple of other groups there but can't find this one.
>
> Regards, Jim

With Thunderbird, you need to set up a new account:

Tools => AccountSettings => Account Actions => Add another account.

=> News Group Account => Next

 From there, it's a matter of filling in the blanks.

The news server is "news.gmane.org".

I'm just trying it.

Colin W,


From mcrute at gmail.com  Mon May 17 10:59:43 2010
From: mcrute at gmail.com (Michael Crute)
Date: Mon, 17 May 2010 10:59:43 -0400
Subject: pythonic ssh
In-Reply-To: <4BF146B3.2070207@gmail.com>
References: <4BF146B3.2070207@gmail.com>
Message-ID: 

On Mon, May 17, 2010 at 9:37 AM, John Maclean  wrote:
> pyssh, pexpect, paramiko or creating your your own sockets. what do you use
> to pythonically ssh to boxes?

I think the answer to this depends on your goals. Paramiko is the best
way to go if you want a pythonic API to ssh but you also will
introduce a dependency on paramiko and a transitive dependency on
pycrypto (which requires openssl). I personally prefer to just use
subprocess with the ssh binary for most of my scripts because it
doesn't introduce any extra dependencies and is relatively easy to
implement. pyssh tries to wrap up the common ssh patterns using
os.popen but it hasn't been maintained in several years so your best
bet is probably to stick with using subprocess if you don't go with
paramiko.

-- 
Michael E. Crute
http://mike.crute.org

It is a mistake to think you can solve any major problem just with
potatoes. --Douglas Adams


From jonvspython at gmail.com  Mon May 17 11:05:12 2010
From: jonvspython at gmail.com (jon vs. python)
Date: Mon, 17 May 2010 17:05:12 +0200
Subject: Pyserial and pysqlite data types, need advice
Message-ID: 

Hi,
I'm trying to store frames received via serial port (using Pyserial) into a
sqlite database (using Pysqlite) in order to perform off-line processing.
Thus I could use both SQL's power and Python's magic to make everything
easier. I'd like my code to be generic and work both for binary and ascii
protocols, too.

Which kind of data should I use to store the frames?
Should I store every byte as a char in VARCHAR? (This seems to fail when
trying to store non printable characters).
Should I encapsulate frames in buffer objects and store them in BLOBs? (This
seems to work but hides content and thus doesn't allow to use database
operations directly on the data)
I've also tried, unsuccessfully, to use bytearrays with pysqlite...

Any suggestion?

Thanks, Jon.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From keobox at gmail.com  Mon May 17 11:09:59 2010
From: keobox at gmail.com (keobox)
Date: Mon, 17 May 2010 08:09:59 -0700 (PDT)
Subject: [jython] Problem with an huge dictionary
Message-ID: 

Hi,
I apologize if this is not the right group for posting question
related to jython.
Please give me the right directions if this is the case.

The question is:
Is there a limit on the number of entries a dictionary can have i
jython?

I wrote a little app where my data is stored in a huge dictionary
(11746 entries) generated with a python script.
When I try to import the dictionary, jython complains with the
following message:

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\ceplacan\My Documents\Documents\Source\source
\Python\j
moco-test>jython
Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.5.0_13
Type "help", "copyright", "credits" or "license" for more information.
>>> import jmoco_event_data
Traceback (most recent call last):
  File "", line 1, in 
java.lang.ClassFormatError: Invalid this class index 3241 in constant
pool in cl
ass file _1076
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
        at org.python.core.BytecodeLoader
$Loader.loadClassFromBytes(BytecodeLoad
er.java:119)
        at
org.python.core.BytecodeLoader.makeClass(BytecodeLoader.java:37)
        at org.python.core.BytecodeLoader.makeCode(BytecodeLoader.java:
67)
        at org.python.core.imp.createFromSource(imp.java:288)
        at org.python.core.imp.loadFromSource(imp.java:514)
        at org.python.core.imp.find_module(imp.java:411)
        at org.python.core.imp.import_next(imp.java:635)
        at org.python.core.imp.import_name(imp.java:746)
        at org.python.core.imp.importName(imp.java:806)
        at org.python.core.ImportFunction.__call__(__builtin__.java:
1232)
        at org.python.core.PyObject.__call__(PyObject.java:367)
        at org.python.core.__builtin__.__import__(__builtin__.java:
1202)
        at org.python.core.__builtin__.__import__(__builtin__.java:
1185)
        at org.python.core.imp.importOne(imp.java:817)
        at org.python.pycode._pyx1.f$0(:1)
        at org.python.pycode._pyx1.call_function()
        at org.python.core.PyTableCode.call(PyTableCode.java:165)
        at org.python.core.PyCode.call(PyCode.java:18)
        at org.python.core.Py.runCode(Py.java:1204)
        at org.python.core.Py.exec(Py.java:1248)
        at
org.python.util.PythonInterpreter.exec(PythonInterpreter.java:181)
        at
org.python.util.InteractiveInterpreter.runcode(InteractiveInterpreter
.java:89)
        at
org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
er.java:70)
        at
org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
er.java:46)
        at
org.python.util.InteractiveConsole.push(InteractiveConsole.java:110)
        at
org.python.util.InteractiveConsole.interact(InteractiveConsole.java:9
0)
        at org.python.util.jython.run(jython.java:316)
        at org.python.util.jython.main(jython.java:129)

java.lang.ClassFormatError: java.lang.ClassFormatError: Invalid this
class index
 3241 in constant pool in class file _1076

What can I do to avoid this?

Regards,
Cesare


From pierre.ruyssen at gmail.com  Mon May 17 11:38:05 2010
From: pierre.ruyssen at gmail.com (Pierre)
Date: Mon, 17 May 2010 08:38:05 -0700 (PDT)
Subject: [BarCamp] WebWorkersCamp BarCamp: NodeJS, NoSQL, Message Queues, 
	Asynchronous programming, Web Sockets, Distributed Applications, 
	Decentralized Social Networks, buzzword generators...
Message-ID: <3797a708-ffd0-4330-acbd-7281699b2af4@o1g2000vbe.googlegroups.com>

Hello,

AF83 will be holding a barcamp event on Saturday afternoon, July 3rd
in Paris (in La Cantine, a famous Parisian tech place). We wanted to
let you know about this event and tell you that you would be most
welcome if you could join us on that day.

In the ever-growing context of real-time web and multiplying
webservices, websites as they are now designed are hardly scalable, or
at high costs. So we thought appropriate to hold an event to discuss
the technologies which will allow us to code differently in order to
solve these issues.

Our guests will be invited to share their experience in asynchronous
programming (server-side javascript with NodeJS, Python?s Tornado,
Ruby?s Event Machine, etc.) as well as Websockets, NoSQL databases,
queues, XMPP and others.

We?d be thrilled to have you amongst us and hear your story on this
matter! We thought this could be the opportunity for you to tell us
about your work and learn from other developers. Would you be
interested in coming and, if you wish, leading a workshop?
Then register on http://barcamp.org/WebWorkersCamp .

We?re looking forward to hearing from you soon,

Thank you,
The AF83 team.


From python at rcn.com  Mon May 17 11:43:23 2010
From: python at rcn.com (Raymond Hettinger)
Date: Mon, 17 May 2010 08:43:23 -0700 (PDT)
Subject: an element from a set
References: 
Message-ID: <3a3dd59c-4280-46b1-98af-7e9fe8a4bd2f@q33g2000vbt.googlegroups.com>

On May 14, 3:24?pm, gerardob  wrote:
> Hello, let S be a python set which is not empty
> (http://docs.python.org/library/sets.html)
>
> i would like to obtain one element (anyone, it doesn't matter which one) and
> assign it to a variable.
>
> How can i do this?

x = next(iter(s))

or you can supply a default value in case the set is empty:

x = next(iter(s), default_value)


Raymond


From alley at dragoncreativeworks.net  Mon May 17 11:51:36 2010
From: alley at dragoncreativeworks.net (Allan Davis)
Date: Mon, 17 May 2010 10:51:36 -0500
Subject: [jython] Problem with an huge dictionary
In-Reply-To: 
References: 
Message-ID: 

KeoBox,

Can i look at the jython file you are executing? the ClassFormatException is
not with the size of the dictionary.  Jython is failing on an import.

thanks,
--------------------------------------------------------------
Allan Davis
Member of NetBeans Dream Team
http://wiki.netbeans.org/NetBeansDreamTeam
Lead Developer, nbPython
http://wiki.netbeans.org/Python
http://codesnakes.blogspot.com (my blog)
Co-Chair, CajunJUG
http://www.cajunjug.org


On Mon, May 17, 2010 at 10:09 AM, keobox  wrote:

> Hi,
> I apologize if this is not the right group for posting question
> related to jython.
> Please give me the right directions if this is the case.
>
> The question is:
> Is there a limit on the number of entries a dictionary can have i
> jython?
>
> I wrote a little app where my data is stored in a huge dictionary
> (11746 entries) generated with a python script.
> When I try to import the dictionary, jython complains with the
> following message:
>
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
>
> C:\Documents and Settings\ceplacan\My Documents\Documents\Source\source
> \Python\j
> moco-test>jython
> Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
> [Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.5.0_13
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import jmoco_event_data
> Traceback (most recent call last):
>  File "", line 1, in 
> java.lang.ClassFormatError: Invalid this class index 3241 in constant
> pool in cl
> ass file _1076
>        at java.lang.ClassLoader.defineClass1(Native Method)
>        at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
>        at org.python.core.BytecodeLoader
> $Loader.loadClassFromBytes(BytecodeLoad
> er.java:119)
>        at
> org.python.core.BytecodeLoader.makeClass(BytecodeLoader.java:37)
>        at org.python.core.BytecodeLoader.makeCode(BytecodeLoader.java:
> 67)
>        at org.python.core.imp.createFromSource(imp.java:288)
>        at org.python.core.imp.loadFromSource(imp.java:514)
>        at org.python.core.imp.find_module(imp.java:411)
>        at org.python.core.imp.import_next(imp.java:635)
>        at org.python.core.imp.import_name(imp.java:746)
>        at org.python.core.imp.importName(imp.java:806)
>        at org.python.core.ImportFunction.__call__(__builtin__.java:
> 1232)
>        at org.python.core.PyObject.__call__(PyObject.java:367)
>        at org.python.core.__builtin__.__import__(__builtin__.java:
> 1202)
>        at org.python.core.__builtin__.__import__(__builtin__.java:
> 1185)
>        at org.python.core.imp.importOne(imp.java:817)
>        at org.python.pycode._pyx1.f$0(:1)
>        at org.python.pycode._pyx1.call_function()
>        at org.python.core.PyTableCode.call(PyTableCode.java:165)
>        at org.python.core.PyCode.call(PyCode.java:18)
>        at org.python.core.Py.runCode(Py.java:1204)
>        at org.python.core.Py.exec(Py.java:1248)
>        at
> org.python.util.PythonInterpreter.exec(PythonInterpreter.java:181)
>        at
> org.python.util.InteractiveInterpreter.runcode(InteractiveInterpreter
> .java:89)
>        at
> org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
> er.java:70)
>        at
> org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
> er.java:46)
>        at
> org.python.util.InteractiveConsole.push(InteractiveConsole.java:110)
>        at
> org.python.util.InteractiveConsole.interact(InteractiveConsole.java:9
> 0)
>        at org.python.util.jython.run(jython.java:316)
>        at org.python.util.jython.main(jython.java:129)
>
> java.lang.ClassFormatError: java.lang.ClassFormatError: Invalid this
> class index
>  3241 in constant pool in class file _1076
>
> What can I do to avoid this?
>
> Regards,
> Cesare
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From cde3 at live.com  Mon May 17 11:54:37 2010
From: cde3 at live.com (Sandy Ydnas)
Date: Mon, 17 May 2010 20:54:37 +0500
Subject: python and GNU plot
Message-ID: 


 

pls pls help how to use Gnuplot 

 

Gnuplot runs from Python under Vista

 

downloaded  Gnuplot, but what they suggest only Run wgnuplot.exe

 

Thank you very much in advance!!!!!!!!!!!

 

Sandy
 		 	   		  
_________________________________________________________________
Hotmail: Trusted email with Microsoft?s powerful SPAM protection.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From sam.bancal at gmail.com  Mon May 17 11:54:38 2010
From: sam.bancal at gmail.com (Samuel Bancal)
Date: Mon, 17 May 2010 17:54:38 +0200
Subject: subprocess and gvfs-mount
Message-ID: 

Hi,

I'm coding a script that does some automates for my users ... including
mounting a smb share.

Because we are using Gnome, I choosed to use gvfs-mount, which is quite
similar to "Places > Connect to Server > ..."

Now my script does :
        print "*** Mounting the FILER ..."
        cmd = "/usr/bin/gvfs-mount smb://%s\;%s at myfiler.domain.ch/data/%s" %
(my_domain, my_user_name, my_user_name)
        try:
            retCode = subprocess.call(cmd, shell=True)
        except KeyboardInterrupt, e:
            sys.stderr.write("Interrupted by ctrl-c. Exiting\n")
            sys.exit(1)
        if retCode != 0:
            sys.stderr.write("Error while mounting : %s\n" % retCode)

I have two major problems with this code :
- In case of "ctr-c" while the password is asked to the user, I get a
Terminal in which the output from keyboard is inhibited... (like while
typing password)
- When the user runs this script by "double-click > Run" (not "Run in
terminal") ... there is no interaction with the user.

I also did some try with subprocess.Popen ... with no success yet...

Thanks for any comment or suggestion!

Regards,
Samuel Bancal

ps : Or anyone knows how to get that gvfs-mount in GUI mode... Could see
nautilus-connect-server ... but couldn't find any options.

-- 
Samuel Bancal - CH
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nima.irt at gmail.com  Mon May 17 12:12:32 2010
From: nima.irt at gmail.com (Nima)
Date: Mon, 17 May 2010 09:12:32 -0700 (PDT)
Subject: Installing Lightweight Python
Message-ID: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>

I'd like to install python on an embedded system. It's a powerful x86-
based computer with the only limitation of having a small-size flash
ROM as its secondary storage. So there is no hard drive and the system
is booted from the flash memory.
The operating system, BusyBox (a flavor of Linux), and other
applications occupy most of the flash memory. As the subject implies,
Python isn't already installed on the box. I tried to compile/install
python on a Linux box which roughly took 60MB of the memory. The
maximum amount of Flash memory I'm permitted to use is about 10-20 MB.
Is there a light-weight implementation of python which I could use? Is
there a way to remove unnecessary modules?
BTW,
+ I'm supposed to write a web management interface for this system
(using python).
+ I know how to use Google!
+ I'm a newbie, so please be gentle :)


From tjreedy at udel.edu  Mon May 17 12:24:04 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Mon, 17 May 2010 12:24:04 -0400
Subject: an element from a set
In-Reply-To: <248cbfa6-5992-4bc3-bef6-a240a901a07b@42g2000prb.googlegroups.com>
References: <28560792.post@talk.nabble.com>	
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
	
	<248cbfa6-5992-4bc3-bef6-a240a901a07b@42g2000prb.googlegroups.com>
Message-ID: 

On 5/17/2010 12:53 AM, Carl Banks wrote:

> Even if we were to modify the set type at the C level to support it, I
> can't think of an easy way to get a random element without selection
> bias.

At the C level, a (hashed) set is a list with empty slots. So the C 
function would have to pick random ints in the appropriate range until 
it got an index for a non-empty slot. A sequence of selections from 
equal sets would not, in general, be reproducible, since the internal 
array need not be the same.



From yourpadre at gmail.com  Mon May 17 12:27:53 2010
From: yourpadre at gmail.com (Miguel Beltran R.)
Date: Mon, 17 May 2010 11:27:53 -0500
Subject: OT Pagina sobre programacion en paralelo
Message-ID: 

Hola Lista,

Disculpen el off-topic, pero creo que aqui fue donde una vez postearon un
enlace sobre programaci?n en paralelo y explica porque no es el doble de
rapido que con 1 micro.

Tambien hablaba de que si el algoritmo es log(n) o log(n2) o algo asi

ya lo busque en el historial pero no lo encuentro, alguien tiene el enlace?
o no lo vi aqui?

-- 
________________________________________
Lo bueno de vivir un dia mas
es saber que nos queda un dia menos de vida
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From tjreedy at udel.edu  Mon May 17 12:56:12 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Mon, 17 May 2010 12:56:12 -0400
Subject: A couple questions about classes and inheritance
In-Reply-To: 
References: 	
	
Message-ID: 

On 5/16/2010 10:52 PM, Mark Young wrote:
> You can't subclass Ellipsis.

You clipped what I believe you were responding to that I posted:
"I believe that in 3.1, the builtin classes with builtin names can be 
subclassed and and those without cannot. (If you find any exceptionss, 
please post ;-). The ones with names are exactly the ones you are 
expected to directly interact with in normal code."

Ellipsis is not an exception to what I said but rather an example that 
supports my point. It is not a class, but an instance of an 
intentionally *unnamed* class which one cannot subclass. It is unnamed 
in the sense of not being bound to a name in a namespace (builtins), 
even though, like all classes, it has a 'definition' or name-attribute name.

 >>> Ellipsis
Ellipsis
 >>> type(Ellipsis)

 >>> class C(type(Ellipsis)): pass

Traceback (most recent call last):
   File "", line 1, in 
     class C(type(Ellipsis)): pass
TypeError: type 'ellipsis' is not an acceptable base type

The class of None is also unnamed, while the class of True and False, 
bool, is named so we can call it. It does turn out that bool *is* an 
exception to the general rule.

 >>> class C(bool): pass

Traceback (most recent call last):
   File "", line 1, in 
     class C(bool): pass
TypeError: type 'bool' is not an acceptable base type

If there were a practical reason to subclass it, a subclass of int 
instead should do just as well.

Terry Jan Reedy



From debatem1 at gmail.com  Mon May 17 13:00:30 2010
From: debatem1 at gmail.com (geremy condra)
Date: Mon, 17 May 2010 10:00:30 -0700
Subject: Installing Lightweight Python
In-Reply-To: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
Message-ID: 

On Mon, May 17, 2010 at 9:12 AM, Nima  wrote:
> I'd like to install python on an embedded system. It's a powerful x86-
> based computer with the only limitation of having a small-size flash
> ROM as its secondary storage. So there is no hard drive and the system
> is booted from the flash memory.
> The operating system, BusyBox (a flavor of Linux), and other
> applications occupy most of the flash memory. As the subject implies,
> Python isn't already installed on the box. I tried to compile/install
> python on a Linux box which roughly took 60MB of the memory. The
> maximum amount of Flash memory I'm permitted to use is about 10-20 MB.
> Is there a light-weight implementation of python which I could use? Is
> there a way to remove unnecessary modules?
> BTW,
> + I'm supposed to write a web management interface for this system
> (using python).
> + I know how to use Google!
> + I'm a newbie, so please be gentle :)
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I'm not an expert, but there are probably a large-ish number of modules
you could remove without much sacrifice on your part. Looking at the
module list and just picking the platform-dependent ones:

* _winreg
* aepack
* aetools
* aetypes
* AL
* al
* applesingle
* autoGIL
* buildtools
* Carbon
* cd
* cfmfile
* chunk
* colorpicker
* etc
* etc
* etc

You could also probably remove things like 2to3, tabnanny, etc,
and I doubt tkinter is doing you much good.

I also recall someone at pycon talking about importing modules
from a .zip archive. I'm not sure how easy/hard that is, but you
may want to look at PEP 302.

Geremy Condra


From tjreedy at udel.edu  Mon May 17 13:00:57 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Mon, 17 May 2010 13:00:57 -0400
Subject: OT Pagina sobre programacion en paralelo
In-Reply-To: 
References: 
Message-ID: 

On 5/17/2010 12:27 PM, Miguel Beltran R. wrote:

> Disculpen el off-topic, pero creo que aqui fue donde una vez postearon
> un enlace sobre programaci?n en paralelo y explica porque no es el doble
> de rapido que con 1 micro.

No me recuerdo algo como esto. Lo dudo mucho.





From python at bdurham.com  Mon May 17 13:54:27 2010
From: python at bdurham.com (python at bdurham.com)
Date: Mon, 17 May 2010 13:54:27 -0400
Subject: Converting datetime.ctime() values to Unicode
Message-ID: <1274118867.15576.1375504195@webmail.messagingengine.com>

I would like to convert datetime.ctime() values to Unicode.

Using Python 2.6.4 running under Windows I can set my locale to
Spanish like below:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'esp' )

Then I can pass %a, %A, %b, and %B to ctime() to get day and
month names and abbreviations.

>>> import datetime
>>> dateValue = datetime.date( 2010, 5, 15 )
>>> dayName = dateValue.strftime( '%A' )
>>> dayName
's\xe1bado'

How do I convert the 's\xe1bado' value to Unicode? Specifically what
encoding do I use?

I'm thinking I might do something like the following, but I'm not sure
this is the right approach.

>>> codePage = locale.getdefaultlocale()[ 1 ]
>>> dayNameUnicode = unicode( dayName, codePage )
>>> dayNameUnicode
u's\xe1bado'

Feedback appreciated.

Regards,
Malcolm



From eike.welk at gmx.net  Mon May 17 14:09:37 2010
From: eike.welk at gmx.net (Eike Welk)
Date: Mon, 17 May 2010 20:09:37 +0200
Subject: Engineering numerical format PEP discussion
References: 
Message-ID: 

Keith wrote:

> I am considering writing a PEP for the inclusion of an engineering
> format specifier, and would appreciate input from others.

I think it's a good idea. I regularly type numbers into my pocket calculator 
just to do this conversion. 


Eike.


From python at bdurham.com  Mon May 17 14:14:27 2010
From: python at bdurham.com (python at bdurham.com)
Date: Mon, 17 May 2010 14:14:27 -0400
Subject: Converting datetime.ctime() values to Unicode
In-Reply-To: <1274118867.15576.1375504195@webmail.messagingengine.com>
References: <1274118867.15576.1375504195@webmail.messagingengine.com>
Message-ID: <1274120067.18728.1375508915@webmail.messagingengine.com>

In researching a solution, I believe locale.getpreferredencoding() might
be a better choice (than locale.getdefaultlocale()[ 1 ]) for determining
a system's default encoding?

In other words change:

>>> codePage = locale.getdefaultlocale()[ 1 ]

To this:

>>> codePage = locale.getpreferredencoding() 

... in my original post's code (original post follows my signature).

Malcolm

----- Original message -----
From: python at bdurham.com
To: python-list at python.org
Date: Mon, 17 May 2010 13:54:27 -0400
Subject: Converting datetime.ctime() values to Unicode

I would like to convert datetime.ctime() values to Unicode.

Using Python 2.6.4 running under Windows I can set my locale to
Spanish like below:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'esp' )

Then I can pass %a, %A, %b, and %B to ctime() to get day and
month names and abbreviations.

>>> import datetime
>>> dateValue = datetime.date( 2010, 5, 15 )
>>> dayName = dateValue.strftime( '%A' )
>>> dayName
's\xe1bado'

How do I convert the 's\xe1bado' value to Unicode? Specifically what
encoding do I use?

I'm thinking I might do something like the following, but I'm not sure
this is the right approach.

>>> codePage = locale.getdefaultlocale()[ 1 ]
>>> dayNameUnicode = unicode( dayName, codePage )
>>> dayNameUnicode
u's\xe1bado'

Feedback appreciated.

Regards,
Malcolm

-- 
http://mail.python.org/mailman/listinfo/python-list



From malaclypse2 at gmail.com  Mon May 17 14:32:59 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Mon, 17 May 2010 14:32:59 -0400
Subject: Converting datetime.ctime() values to Unicode
In-Reply-To: <1274120067.18728.1375508915@webmail.messagingengine.com>
References: <1274118867.15576.1375504195@webmail.messagingengine.com>
	<1274120067.18728.1375508915@webmail.messagingengine.com>
Message-ID: 

On Mon, May 17, 2010 at 2:14 PM,   wrote:
> In researching a solution, I believe locale.getpreferredencoding() might
> be a better choice (than locale.getdefaultlocale()[ 1 ]) for determining
> a system's default encoding?

I haven't used the locale module a lot, but it seems to me that if
you're setting the locale with locale.setlocale(), you should get the
encoding from locale.getlocale()[1].

You're not really interested in the system's default encoding at this
point, you're interested in the encoding of the locale you've
explicitly set.

-- 
Jerry


From dodo_do_not_wake_up at yahoo.Fr  Mon May 17 14:34:21 2010
From: dodo_do_not_wake_up at yahoo.Fr (Dodo)
Date: Mon, 17 May 2010 20:34:21 +0200
Subject: Python3 buffer extra byte??
Message-ID: <4bf18c2d$0$27615$ba4acef3@reader.news.orange.fr>

Let's consider this code:

#!/usr/bin/python3
import cgi, sys
print("Content-type:image/jpeg\n\n")
f = open("img.jpg","rb")
sys.stdout.flush()
sys.stdout.buffer.write( f.read() )
f.close()

I receive the file with one padding byte at the start of the file (0x0a)
http://www.1pix.org/multi/images/wg7zg58gsgbhc9cppo5i.jpg

Any idea why?

Dorian
(yes, this is the continuation of "CGI python 3 write RAW BINARY")


From solipsis at pitrou.net  Mon May 17 14:46:12 2010
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Mon, 17 May 2010 20:46:12 +0200
Subject: Python3 buffer extra byte??
References: <4bf18c2d$0$27615$ba4acef3@reader.news.orange.fr>
Message-ID: <20100517204612.262b301f@pitrou.net>

On Mon, 17 May 2010 20:34:21 +0200
Dodo  wrote:

> Let's consider this code:
> 
> #!/usr/bin/python3
> import cgi, sys
> print("Content-type:image/jpeg\n\n")

print() adds an additional \n, so there's one too many.
Also, HTTP headers should be separated with \r\n, not \n.

(besides, under Windows \n will be converted to \r\n by the text I/O
layer, therefore, it would be better to use the binary I/O layer, a.k.a
sys.stdout.buffer, if you want your script to be portable)

Therefore, I would advocate rewriting it as:

sys.stdout.buffer.write(b"Content-type:image/jpeg\r\n\r\n")





From nima.irt at gmail.com  Mon May 17 15:08:02 2010
From: nima.irt at gmail.com (Nima Mohammadi)
Date: Mon, 17 May 2010 12:08:02 -0700 (PDT)
Subject: Installing Lightweight Python
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	
Message-ID: 

Thanks Geremy :)

The majority of installed files (56MB of data) reside in /lib/
python2.6/. So far, I took these steps to make it as compact as
possible:
1. I deleted /lib/python2.6/test directory. This reduced the size by
20MB.
2. I deleted .py files (cause the corresponding pyc ones are there).
This reduced the size by 9MB.
3. I deleted the /lib/libpython2.6.a which was 6MB.
* By far the python runs flawlessly.

4. I zip up the /lib/python2.6/ as python26.zip and place it in the /
lib/ directory.
Then I delete the /lib/python2.6/ directory. By running python, I get
this output, though /lib/python26.zip is in the sys.path variable.

nima at nima-desktop:~/py$ ./bin/python
Could not find platform independent libraries 
Could not find platform dependent libraries 
Consider setting $PYTHONHOME to [:]
'import site' failed; use -v for traceback
Python 2.6.5 (r265:79063, May 17 2010, 18:36:54)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/',
'/home/nima/py/lib/python2.6/plat-linux2', '/home/nima/py/lib/
python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old', '/home/nima/
py/lib/lib-dynload']



On May 17, 9:00?pm, geremy condra  wrote:
> I'm not an expert, but there are probably a large-ish number of modules
> you could remove without much sacrifice on your part. Looking at the
> module list and just picking the platform-dependent ones:
>
> * _winreg
> * aepack
> * aetools
> * aetypes
> * AL
> * al
> * applesingle
> * autoGIL
> * buildtools
> * Carbon
> * cd
> * cfmfile
> * chunk
> * colorpicker
> * etc
> * etc
> * etc
>
> You could also probably remove things like 2to3, tabnanny, etc,
> and I doubt tkinter is doing you much good.
>
> I also recall someone at pycon talking about importing modules
> from a .zip archive. I'm not sure how easy/hard that is, but you
> may want to look at PEP 302.
>
> Geremy Condra

Yours sincerely,
Nima Mohammadi


From mannu_0523 at rediffmail.com  Mon May 17 15:35:51 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 17 May 2010 19:35:51 -0000
Subject: =?utf-8?B?UmU6IFJlOiBqb2luaW5nIGZpbGVz?=
In-Reply-To: <4BF18BCD.6050407@iki.fi>
Message-ID: <1274120838.S.6249.7432.H.TlR1b21hcyBWZXN0ZXJpbmVuAFJlOiBqb2luaW5nIGZpbGVz.f4-234-233.1274124951.59048@webmail.rediffmail.com>



On Mon, 17 May 2010 23:57:18 +0530  wrote
>Try:
file = open("input11.txt")
file1 = file.read() # file1 is a string
file.close()
or
file1 = open("input11.txt") # file1 is an open file object
and replace lines:
     for line in sce.split(os.linesep):
       lst = line.split()
       lines[lst[0]] = (nme, lst)
with lines:
     for line in sce:
       lst = line.split()
       lines[lst[0]] = (nme, lst)
     sce.close()


Thankyou very much sir it has worked. Thankyou once again.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nima.irt at gmail.com  Mon May 17 16:05:29 2010
From: nima.irt at gmail.com (Nima)
Date: Tue, 18 May 2010 00:35:29 +0430
Subject: Installing Lightweight Python
In-Reply-To: 
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	
Message-ID: 

Well, I tried to run Python with -v option. It seems that python26.zip is
partially loaded but can't be used, because zlib is "unavailable".

nima at nima-desktop:~/py$ ./bin/*python -v*
Could not find platform independent libraries 
Could not find platform dependent libraries 
Consider setting $PYTHONHOME to [:]
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
*# zipimport: found 2509 names in /home/nima/py/lib/python26.zip*
# zipimport: *zlib UNAVAILABLE*
'import site' failed; traceback:
*zipimport.ZipImportError: can't decompress data; zlib not available
# zipimport: zlib UNAVAILABLE*
Python 2.6.5 (r265:79063, May 17 2010, 18:36:54)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/',
'/home/nima/py/lib/python2.6/plat-linux2',
'/home/nima/py/lib/python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old',
'/home/nima/py/lib/lib-dynload']


-- 
*Yours sincerely,
Nima Mohammadi*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nima.irt at gmail.com  Mon May 17 16:11:41 2010
From: nima.irt at gmail.com (Nima Mohammadi)
Date: Mon, 17 May 2010 13:11:41 -0700 (PDT)
Subject: Installing Lightweight Python
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	
	
Message-ID: <5b9dd21e-43c7-4603-90a7-51299e1a599b@f13g2000vbm.googlegroups.com>

Well, I tried to run Python with -v option. It seems that python26.zip
is partially loaded but can't be used, because zlib is "unavailable".

nima at nima-desktop:~/py$ ./bin/python -v
Could not find platform independent libraries 
Could not find platform dependent libraries 
Consider setting $PYTHONHOME to [:]
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# zipimport: found 2509 names in /home/nima/py/lib/python26.zip
# zipimport: zlib UNAVAILABLE
'import site' failed; traceback:
zipimport.ZipImportError: can't decompress data; zlib not available
# zipimport: zlib UNAVAILABLE

Python 2.6.5 (r265:79063, May 17 2010, 18:36:54)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/',
'/home/nima/py/lib/python2.6/plat-linux2', '/home/nima/py/lib/
python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old', '/home/nima/
py/lib/lib-dynload']


--
Yours sincerely,
Nima Mohammadi


From mehgcap at gmail.com  Mon May 17 16:19:59 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 17 May 2010 16:19:59 -0400
Subject: classes and __init__ question
Message-ID: 

Hi all,
I am a bit confused about classes. What do you pass a class, since all
the actual information is passed to __init__? For example, say you
have a dog class. The dog object has a name, a size, and a color. I
believe you would say this:

class dog():
 def __init__(self, name, size, color):
  self.name=name
  self.size=size
  self.color=color
 #end def
#end class

What, then, gets passed to the class constructor?
class dog(whatGoesHere?):
Sometimes I see things passed to this. For example, if you create a
class for a wxPython frame, you will say:
class myapp(wx.App):
In this case you pass something. However, I have a class that I use in
one of my programs to create "contact" objects, which looks like this:
class contact():
 def __init__(self, name, email, status, service):
  self.name=name
  self.email=email
  self.status=status
  self.service=service
 #end def
#end class

Here, I do not pass anything to the class, only to __init__. What is going on?

On a related note, is it horrible for resource usage to create a large
array, up to 500 or so, where each member is a small object? I am
thinking of, for example, a game board array where each member of the
array is a "square" object. A square might have a status, a color, and
other flags associated with it, so you could then say something like
board[i][j].hasGamePiece=True. Lookups and adjustments like this will
be going on a lot. Am I better off using an array of numbers where
each number means something different?

Thanks in advance for any info.


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


From debatem1 at gmail.com  Mon May 17 16:30:52 2010
From: debatem1 at gmail.com (geremy condra)
Date: Mon, 17 May 2010 13:30:52 -0700
Subject: Installing Lightweight Python
In-Reply-To: 
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	
	
Message-ID: 

On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> Well, I tried to run Python with -v option. It seems that python26.zip is
> partially loaded but can't be used, because zlib is "unavailable".

is the zlib module among the files you've compressed?

Geremy Condra


From pmaupin at gmail.com  Mon May 17 16:38:34 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Mon, 17 May 2010 13:38:34 -0700 (PDT)
Subject: classes and __init__ question
References: 
Message-ID: <9a25af1e-a41d-44cd-a965-e82acd6caa76@40g2000vbr.googlegroups.com>

On May 17, 3:19?pm, Alex Hall  wrote:
> Hi all,
> I am a bit confused about classes. What do you pass a class, since all
> the actual information is passed to __init__? For example, say you
> have a dog class. The dog object has a name, a size, and a color. I
> believe you would say this:
>
> class dog():
> ?def __init__(self, name, size, color):
> ? self.name=name
> ? self.size=size
> ? self.color=color
> ?#end def
> #end class
>
> What, then, gets passed to the class constructor?
> class dog(whatGoesHere?):
> Sometimes I see things passed to this. For example, if you create a
> class for a wxPython frame, you will say:
> class myapp(wx.App):
> In this case you pass something. However, I have a class that I use in
> one of my programs to create "contact" objects, which looks like this:
> class contact():
> ?def __init__(self, name, email, status, service):
> ? self.name=name
> ? self.email=email
> ? self.status=status
> ? self.service=service
> ?#end def
> #end class
>
> Here, I do not pass anything to the class, only to __init__. What is going on?
>
> On a related note, is it horrible for resource usage to create a large
> array, up to 500 or so, where each member is a small object? I am
> thinking of, for example, a game board array where each member of the
> array is a "square" object. A square might have a status, a color, and
> other flags associated with it, so you could then say something like
> board[i][j].hasGamePiece=True. Lookups and adjustments like this will
> be going on a lot. Am I better off using an array of numbers where
> each number means something different?
>
> Thanks in advance for any info.
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg... at gmail.com;http://www.facebook.com/mehgcap

What you are calling "passing to a class" is the superclass (or list
of superclasses) if you are creating a subclass.

Under Python 2.x, you might want to subclass object (if you need/want
a newstyle class), so it is fairly common to see:

class foo(object):
   whatever

Regards,
Pat


From python at bdurham.com  Mon May 17 16:45:47 2010
From: python at bdurham.com (python at bdurham.com)
Date: Mon, 17 May 2010 16:45:47 -0400
Subject: How to determine subprocess.Popen() failed when shell=True
Message-ID: <1274129147.11923.1375533733@webmail.messagingengine.com>

Windows version of Python 2.6.4: Is there any way to determine if
subprocess.Popen() fails when using shell=True?

Popen() successfully fails when shell=False

>>> import subprocess
>>> p = subprocess.Popen( 'Nonsense.application', shell=False )
Traceback (most recent call last):
  File "", line 1, in 
    p = subprocess.Popen( 'Nonsense.application' )
  File "C:\Python26\lib\subprocess.py", line 621, in __init__
    errread, errwrite)
  File "C:\Python26\lib\subprocess.py", line 830, in
_execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

But when shell=True, there appears to be no way to determine if a
Popen() call was successful or not.

>>> p = subprocess.Popen( 'Nonsense.application', shell=True )
>>> p

>>> p.pid
6620
>>> p.returncode
>>>

Regards,
Malcolm



From clp2 at rebertia.com  Mon May 17 16:51:50 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Mon, 17 May 2010 13:51:50 -0700
Subject: classes and __init__ question
In-Reply-To: 
References: 
Message-ID: 

On Mon, May 17, 2010 at 1:19 PM, Alex Hall  wrote:
> Hi all,
> I am a bit confused about classes. What do you pass a class, since all
> the actual information is passed to __init__? For example, say you
> have a dog class. The dog object has a name, a size, and a color. I
> believe you would say this:
>
> class dog():
> ?def __init__(self, name, size, color):
> ?self.name=name
> ?self.size=size
> ?self.color=color
> ?#end def
> #end class
>
> What, then, gets passed to the class constructor?
> class dog(whatGoesHere?):
> Sometimes I see things passed to this. For example, if you create a
> class for a wxPython frame, you will say:
> class myapp(wx.App):
> In this case you pass something. However, I have a class that I use in
> one of my programs to create "contact" objects, which looks like this:
> class contact():
> ?def __init__(self, name, email, status, service):
> ?self.name=name
> ?self.email=email
> ?self.status=status
> ?self.service=service
> ?#end def
> #end class
>
> Here, I do not pass anything to the class, only to __init__. What is going on?

There is no notion of "passing" stuff to classes (at least in the way
you're thinking about it). The parentheses in these cases have nothing
to do with function calls.

`class Foo(Bar, Baz):` declares a new class with classes Bar and Baz
as base classes (Python has multiple inheritance).

`class Foo():` declares a new class with only the class `object` as
its implicit base class. The parentheses can and almost always are
omitted in such cases, so one would normally write `class Foo:`
instead.

There's some metaclass magic involved and the constructor of the
metaclass is called (in the earlier case, with Bar and Baz among the
parameters) behind the scenes to create the class Foo itself, but Foo
itself isn't "called" when Foo is being created; indeed, that wouldn't
even make sense, for how could the class possibly be called when it's
still being defined?

In other words, the parentheses in class declarations have nothing
directly to do with function calls and it's probably best not to
conceptualize it that way; they're used just to specify base classes
(and the metaclass in recent Python versions with some extra syntax).

> On a related note, is it horrible for resource usage to create a large
> array, up to 500 or so, where each member is a small object? I am
> thinking of, for example, a game board array where each member of the
> array is a "square" object. A square might have a status, a color, and
> other flags associated with it, so you could then say something like
> board[i][j].hasGamePiece=True. Lookups and adjustments like this will
> be going on a lot. Am I better off using an array of numbers where
> each number means something different?

Premature optimization is the root of all evil. Only *if* your program
ends up using too much memory *and* memory profiling shows the board
to be a significant contributor to the problem, *then* you would start
looking into such memory optimizations.

Cheers,
Chris
--
http://blog.rebertia.com


From mehgcap at gmail.com  Mon May 17 16:55:20 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 17 May 2010 16:55:20 -0400
Subject: classes and __init__ question
In-Reply-To: <9a25af1e-a41d-44cd-a965-e82acd6caa76@40g2000vbr.googlegroups.com>
References: 
	<9a25af1e-a41d-44cd-a965-e82acd6caa76@40g2000vbr.googlegroups.com>
Message-ID: 

On 5/17/10, Patrick Maupin  wrote:
> On May 17, 3:19 pm, Alex Hall  wrote:
>> Hi all,
>> I am a bit confused about classes. What do you pass a class, since all
>> the actual information is passed to __init__? For example, say you
>> have a dog class. The dog object has a name, a size, and a color. I
>> believe you would say this:
>>
>> class dog():
>>  def __init__(self, name, size, color):
>>   self.name=name
>>   self.size=size
>>   self.color=color
>>  #end def
>> #end class
>>
>> What, then, gets passed to the class constructor?
>> class dog(whatGoesHere?):
>> Sometimes I see things passed to this. For example, if you create a
>> class for a wxPython frame, you will say:
>> class myapp(wx.App):
>> In this case you pass something. However, I have a class that I use in
>> one of my programs to create "contact" objects, which looks like this:
>> class contact():
>>  def __init__(self, name, email, status, service):
>>   self.name=name
>>   self.email=email
>>   self.status=status
>>   self.service=service
>>  #end def
>> #end class
>>
>> Here, I do not pass anything to the class, only to __init__. What is going
>> on?
>>
>> On a related note, is it horrible for resource usage to create a large
>> array, up to 500 or so, where each member is a small object? I am
>> thinking of, for example, a game board array where each member of the
>> array is a "square" object. A square might have a status, a color, and
>> other flags associated with it, so you could then say something like
>> board[i][j].hasGamePiece=True. Lookups and adjustments like this will
>> be going on a lot. Am I better off using an array of numbers where
>> each number means something different?
>>
>> Thanks in advance for any info.
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehg... at gmail.com;http://www.facebook.com/mehgcap
>
> What you are calling "passing to a class" is the superclass (or list
> of superclasses) if you are creating a subclass.
So what is a subclass compared to a class? Are you saying that what is
passed to the class, so what is in the parentheses of the class, is
really the superclass? If so, what is the advantage of doing this; why
not just create a class that is not a sub? I thinking I am missing
something elementary here. :)
>
> Under Python 2.x, you might want to subclass object (if you need/want
> a newstyle class), so it is fairly common to see:
>
> class foo(object):
>    whatever
In Java, a class is an object. Is Python the same thing? Would you say
that my dog class, for example, creates a new dog object when an
instance is instantiated?
Thanks.
>
> Regards,
> Pat
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


From clp2 at rebertia.com  Mon May 17 16:59:56 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Mon, 17 May 2010 13:59:56 -0700
Subject: How to determine subprocess.Popen() failed when shell=True
In-Reply-To: <1274129147.11923.1375533733@webmail.messagingengine.com>
References: <1274129147.11923.1375533733@webmail.messagingengine.com>
Message-ID: 

On Mon, May 17, 2010 at 1:45 PM,   wrote:
> Windows version of Python 2.6.4: Is there any way to determine if
> subprocess.Popen() fails when using shell=True?
>
> Popen() successfully fails when shell=False
>
>>>> import subprocess
>>>> p = subprocess.Popen( 'Nonsense.application', shell=False )
> Traceback (most recent call last):
> ?File "", line 1, in 
> ? ?p = subprocess.Popen( 'Nonsense.application' )
> ?File "C:\Python26\lib\subprocess.py", line 621, in __init__
> ? ?errread, errwrite)
> ?File "C:\Python26\lib\subprocess.py", line 830, in
> _execute_child
> ? ?startupinfo)
> WindowsError: [Error 2] The system cannot find the file specified
>
> But when shell=True, there appears to be no way to determine if a
> Popen() call was successful or not.
>
>>>> p = subprocess.Popen( 'Nonsense.application', shell=True )
>>>> p
> 
>>>> p.pid
> 6620
>>>> p.returncode
>>>>

I don't have a Windows box to test on, but have you tried p.wait()?
Worked for me on *nix:
$ python
Python 2.6.5 (r265:79063, May 11 2010, 13:15:13)
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen
>>> a = Popen("nonsense", shell=True)
>>> /bin/sh: nonsense: command not found

>>> a.returncode
>>> a.wait()
127
>>> a.returncode
127

Cheers,
Chris
--
http://blog.rebertia.com


From nima.irt at gmail.com  Mon May 17 17:04:18 2010
From: nima.irt at gmail.com (Nima Mohammadi)
Date: Mon, 17 May 2010 14:04:18 -0700 (PDT)
Subject: Installing Lightweight Python
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	 
	 
	
Message-ID: <34179bf9-88b2-4b8e-b21a-1b09d5bacfa3@o39g2000vbd.googlegroups.com>

On May 18, 12:30?am, geremy condra  wrote:
> On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> > Well, I tried to run Python with -v option. It seems that python26.zip is
> > partially loaded but can't be used, because zlib is "unavailable".
>
> is the zlib module among the files you've compressed?
>
> Geremy Condra

zlib.so is a shared library which is in the /lib/python2.6/lib-
dynload/ directory.
In PEP 273 is noted that:

> Any files may be present in the zip archive, but only files
> *.py and *.py[co] are available for import.  Zip import of
> dynamic modules (*.pyd, *.so) is disallowed.

http://www.python.org/dev/peps/pep-0273/

--
Yours sincerely,
Nima Mohammadi


From pmaupin at gmail.com  Mon May 17 17:09:34 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Mon, 17 May 2010 14:09:34 -0700 (PDT)
Subject: classes and __init__ question
References:  
	<9a25af1e-a41d-44cd-a965-e82acd6caa76@40g2000vbr.googlegroups.com> 
	
Message-ID: 

On May 17, 3:55?pm, Alex Hall  wrote:

> So what is a subclass compared to a class? Are you saying that what is
> passed to the class, so what is in the parentheses of the class, is
> really the superclass? If so, what is the advantage of doing this; why
> not just create a class that is not a sub? I thinking I am missing
> something elementary here. :)

A subclass can inherit methods and attributes from a base class.  This
is not necessary, but is sometimes useful.

> In Java, a class is an object. Is Python the same thing?

Yes, a class is an object.  A class's class is its "metaclass".

An instance of a class is also an object.

> Would you say
> that my dog class, for example, creates a new dog object when an
> instance is instantiated?

Yes. But the actual act of coding something like:

class foo(object):
    pass

Creates a class object, which is a subclass of the 'object' object,
and is an instance of the 'type' object.  Since Python is so dynamic,
you can easily determine this at the command prompt:

>>> class foo(object):
...     pass
...
>>> x = foo()
>>>
>>> type(x)

>>> type(foo)

>>>


Regards,
Pat


From nima.irt at gmail.com  Mon May 17 17:09:43 2010
From: nima.irt at gmail.com (Nima Mohammadi)
Date: Mon, 17 May 2010 14:09:43 -0700 (PDT)
Subject: Installing Lightweight Python
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	 
	 
	
	<34179bf9-88b2-4b8e-b21a-1b09d5bacfa3@o39g2000vbd.googlegroups.com>
Message-ID: <2f3354d5-85e5-41ce-8eac-e23154867113@d12g2000vbr.googlegroups.com>

On May 18, 1:04?am, Nima Mohammadi  wrote:
> On May 18, 12:30?am, geremy condra  wrote:
>
> > On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> > > Well, I tried to run Python with -v option. It seems that python26.zip is
> > > partially loaded but can't be used, because zlib is "unavailable".
>
> > is the zlib module among the files you've compressed?
>
> > Geremy Condra
>
> zlib.so is a shared library which is in the /lib/python2.6/lib-
> dynload/ directory.
> In PEP 273 is noted that:
>
> > Any files may be present in the zip archive, but only files
> > *.py and *.py[co] are available for import. ?Zip import of
> > dynamic modules (*.pyd, *.so) is disallowed.
>
> http://www.python.org/dev/peps/pep-0273/
>
> --
> Yours sincerely,
> Nima Mohammadi

The problem is solved! I just needed to make a directory named
"python2.6" in the /lib/ directory and copy the lib-dynload/ directory
in it.
Thanks for your precious help, Geremy :)

Does anyone have the list of essentials modules to run python?


From apt.shansen at gmail.com  Mon May 17 17:18:13 2010
From: apt.shansen at gmail.com (Stephen Hansen)
Date: Mon, 17 May 2010 14:18:13 -0700
Subject: Installing Lightweight Python
In-Reply-To: <34179bf9-88b2-4b8e-b21a-1b09d5bacfa3@o39g2000vbd.googlegroups.com>
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	 
	 
	
	<34179bf9-88b2-4b8e-b21a-1b09d5bacfa3@o39g2000vbd.googlegroups.com>
Message-ID: 

On Mon, May 17, 2010 at 2:04 PM, Nima Mohammadi  wrote:

> On May 18, 12:30 am, geremy condra  wrote:
> > On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> > > Well, I tried to run Python with -v option. It seems that python26.zip
> is
> > > partially loaded but can't be used, because zlib is "unavailable".
> >
> > is the zlib module among the files you've compressed?
> >
> > Geremy Condra
>
> zlib.so is a shared library which is in the /lib/python2.6/lib-
> dynload/ directory.
>


Yes, but you're not running python from say, /bin; if you were, it might go
out and look in /lib and such to find files. You're running it from a local
directory, ./bin/python. Thus, its finding its "center" (where the
executable is installed), and from there building a search path.

Its center -- PYTHONHOME -- is /home/nima/py; from there, it adds
/home/nima/py/lib-dynload among other search paths.

So: zlib.so needs to be in /home/nima/py/lib-dynload. If its not, then it
won't be able to decompress python26.zip into memory.

In PEP 273 is noted that:
>
> > Any files may be present in the zip archive, but only files
> > *.py and *.py[co] are available for import.  Zip import of
> > dynamic modules (*.pyd, *.so) is disallowed.
>
> http://www.python.org/dev/peps/pep-0273/


He knows, he was wondering if you accidentally zipped up zlib.so in the zip,
basically. I think :)

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rolf.oltmans at gmail.com  Mon May 17 17:19:05 2010
From: rolf.oltmans at gmail.com (Oltmans)
Date: Mon, 17 May 2010 14:19:05 -0700 (PDT)
Subject: Some help needed with small multi-threaded program!
Message-ID: 

I've a small multi-threaded program that is written by keeping
Producer-Consumer pattern in mind. In the Producer part of the program
we create new users by doing a POST to a certain web URL whereas in
the Consumer part of the program we try to login newly created users.
Problem is that program sort of runs fine, however, it never
terminates itself and, more importantly, it doesn't print last-three
lines of the program(which is important for my purposes). I've looked
at the docs, but I couldn't figure out a solution so if someone can
spot the problem and suggest a solution that will be highly
appreciated. Many thanks in advance.

-----
#!/usr/bin/env python

import Queue
import re
import random
import time
import threading
import urllib2
import simplejson
from urllib2 import HTTPError
import urllib

base_url = "http://example.com/"
queue = Queue.Queue()
total_users = 0
#keeps the record of time it takes to create a user
create_user_times = {}
#keeps the record of time it takes to authenticate a user
login_user_times = {}
lock = threading.Lock()
errors = []

class User():
    def
__init__(self,firstName,lastName,email,password,userName,active):
        self.firstName = firstName
        self.lastName = lastName
        self.password = password
        self.email = email
        self.userName = userName
#producer
class CreateUsers(threading.Thread):
    def __init__(self,queue,limit):
        threading.Thread.__init__(self)
        self.queue = queue
        self.limit = limit

    def create_user(self):

        url = base_url + "users/"
        email = "stokeywonder+"+str(random.randrange(0,100000))
+"@example.com"
        obj = {'firstName' : 'Coyotee',
        'lastName' : 'Stevey', 'email' : email,
        'password':'7887',
        'userName':email
        }
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE
5.5; Windows NT)')
        req.add_header("Content-Type","application/json")
        req.add_data(simplejson.dumps(obj))

        try:

            t = time.time()
            f = urllib2.urlopen(req)
            page = f.read()
            if str(f.code) != '200':
                pass
            else:
                create_user_times[obj['userName']] = str("%.
2f"%float(time.time() - t))
                user = User(**obj)
                self.queue.put(user)

        except:
            errors.append(obj['userName'])

    def run(self):
        global total_users
        global lock

        while total_users < self.limit:
            lock.acquire()
            try:
                total_users += 1
            finally:
                lock.release()

            self.create_user()
            if total_users == self.limit:
                try:
                    self.queue.task_done()
                except ValueError:
                    pass

#Consumer
class TestService(threading.Thread):
    def __init__(self,queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def login(self,user):

        user_name = user.userName
        pwd = user.password
        url = base_url+'u?uName='+user_name+'&pwd='+pwd
        user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        req = urllib2.Request(url)
        req.add_header('User-Agent', user_agent)
        try:
            t = time.time()

            f = urllib2.urlopen(req)

            if str(f.code) != '200':
                pass
            else:
                login_user_times[user_name] = str("%.
2f"%float(time.time() - t))
        except:
            errors.append(user_name)

    def run (self):
        while True:
            user = self.queue.get()
            if user:
                self.login(user)


if __name__ == "__main__":
    #limit = number of users
    limit = 5
    th = []
    for i in range(2):
        t = CreateUsers(queue,limit)
        t1 = TestService(queue)
        t.start()
        t1.start()
        th.append(t1)
        th.append(t)

    for t in th:
        t.join()
    print create_user_times
    print '---------------'
    print login_user_times





From nahooda at hotmail.de  Mon May 17 17:29:49 2010
From: nahooda at hotmail.de (D. Schramm)
Date: Mon, 17 May 2010 23:29:49 +0200
Subject: wxPython: How to get letter colour from TextCtrl
Message-ID: <85dqqkFl53U1@mid.individual.net>

Hello,

I've got a problem getting the colour of a single letter within the 
TextCtrl widget:

letterstyle = wx.TextAttr()
self.p1.GetStyle(self.p1.XYToPosition(0,0),letterstyle)
color = letterstyle.GetTextColour()
print color

This should display the colour value of the very first letter in the 
very first line of the TextCtrl. But no matter what I try, it always 
returns the value (-1, -1, -1, 255).

Any help?

Thanks in advance,

Dennis Schramm


From ethan at stoneleaf.us  Mon May 17 18:01:35 2010
From: ethan at stoneleaf.us (Ethan Furman)
Date: Mon, 17 May 2010 15:01:35 -0700
Subject: classes and __init__ question
In-Reply-To: 
References: 
Message-ID: <4BF1BCBF.4010506@stoneleaf.us>

Alex Hall wrote:
> Hi all,
> I am a bit confused about classes. What do you pass a class, since all
> the actual information is passed to __init__? For example, say you
> have a dog class. The dog object has a name, a size, and a color. I
> believe you would say this:
> 
> class dog():
>  def __init__(self, name, size, color):
>   self.name=name
>   self.size=size
>   self.color=color

Here you have defined a dog class (you have not called it, yet).


> What, then, gets passed to the class constructor?
> class dog(whatGoesHere?):

whatGoesHere = any parent classes (the constructor is *not* being called 
yet)

parent classes can be used when you want what they have, but need to 
either add more, or change some, of the methods/attributes that the 
parent has.

> Sometimes I see things passed to this. For example, if you create a
> class for a wxPython frame, you will say:
> class myapp(wx.App):

wx.App is not being passed, per se, rather Python is being told that 
myapp is based on wx.App, and will have all the methods/attributes that 
wx.App has, plus whatever else follows.

So far, all that has been done is to _define_ classes.

> class contact():
>  def __init__(self, name, email, status, service):
>   self.name=name
>   self.email=email
>   self.status=status
>   self.service=service
> 
> Here, I do not pass anything to the class, only to __init__. What is going on?

You have defined a class -- nothing more, nothing less.

When you actually call the class is when any necessary items are passed 
to the constructor (__init__):

a_dog = dog('Ralph', 'big', RED)

this_app = myapp()

fred = contact('Fred Flinstone','f1 at flinstone.gv','active','exemplary')

Hope this helps.

~Ethan~


From stef.mientki at gmail.com  Mon May 17 18:05:31 2010
From: stef.mientki at gmail.com (Stef Mientki)
Date: Tue, 18 May 2010 00:05:31 +0200
Subject: wxPython: How to get letter colour from TextCtrl
In-Reply-To: <85dqqkFl53U1@mid.individual.net>
References: <85dqqkFl53U1@mid.individual.net>
Message-ID: <4BF1BDAB.7040503@gmail.com>

On 17-05-2010 23:29, D. Schramm wrote:
> Hello,
>
> I've got a problem getting the colour of a single letter within the
> TextCtrl widget:
>
> letterstyle = wx.TextAttr()
> self.p1.GetStyle(self.p1.XYToPosition(0,0),letterstyle)
> color = letterstyle.GetTextColour()
> print color
>
> This should display the colour value of the very first letter in the
> very first line of the TextCtrl. But no matter what I try, it always
> returns the value (-1, -1, -1, 255).
>
> Any help?
>
AFAIK, TextAttributes are just onw way, you can set them, but never read
them back.

cheers,
Stef
>
> Thanks in advance,
>
> Dennis Schramm



From ben+python at benfinney.id.au  Mon May 17 18:05:50 2010
From: ben+python at benfinney.id.au (Ben Finney)
Date: Tue, 18 May 2010 08:05:50 +1000
Subject: Picking a license
References: 
	
	 <87r5ldbw3k.fsf@benfinney.id.au>
	
Message-ID: <87fx1qji9t.fsf@benfinney.id.au>

aahz at pythoncraft.com (Aahz) writes:

> Ben Finney   wrote:
> >[It is impractical to] sell free software like selling loaves of
> >bread, but that's a much more limited case and a far cry from your
> >claim [that it's impractical to sell free software]. Selling free
> >software is quite practical and a good way to fund development of
> >software that otherwise wouldn't be written as free software.
>
> From my POV, if you're not selling COTS, you're really selling support
> and consulting services, because that's what keeps your competitors
> from just picking up your software and reselling it for cheaper. BTDT.

This thread has revealed some staggering gulfs in concepts as held by
different people. For example, I don't think it's at all germane to the
definition of ?sell FOO? that ?your competitors can pick up the FOO and
resell it cheaper?. Whether they can or not, that doesn't change that
fact that one is selling FOO.

Moreover, I don't try to prevent my competitors from reselling the
software (so long as they don't misrepresent who holds copyright or
further restrict the terms). That's part and parcel of the freedoms in
the software. Indeed, I find that helps the customers trust me more and
tend to come back when they want something else new; and my customers
are free to show others the solutions I've already implemented.

Thus is an ongoing business relationship crafted, including return
customers and referrals for new work. It really is practical to sell
free software.

-- 
 \          ?It's dangerous to be right when the government is wrong.? |
  `\                                   ?Francois Marie Arouet Voltaire |
_o__)                                                                  |
Ben Finney


From jbravado at gmail.com  Mon May 17 18:10:25 2010
From: jbravado at gmail.com (JB)
Date: Mon, 17 May 2010 15:10:25 -0700 (PDT)
Subject: Encoding troubles
Message-ID: <7bb834e4-940f-43eb-8ebb-8c29599dda87@h37g2000pra.googlegroups.com>

I'm working on the webapp of our company intranet and I had a question
about proper handling of user input that's causing encoding issues.

Some of the uesrs take notes in Microsoft Office and copy/paste these
into textarea's of the webapp. Some of the characters from Word such
as hypens (?) and apostrophes (?) are in an odd encoding. When passed
to the database using sqlalchemy they appear as ??? and other
characters.

What's the proper handling (conversion?) of user input before it gets
to my database. Do I need to start making a list of the offending
characters and .replace them? Or is there a means to decode/encode the
user input to something more generic? Thanks for your time.


From pengyu.ut at gmail.com  Mon May 17 18:26:51 2010
From: pengyu.ut at gmail.com (Peng Yu)
Date: Mon, 17 May 2010 17:26:51 -0500
Subject: Can't find _sqlite3.so in lib-dynload
Message-ID: 

I compiled python2.6.4 from source. But I can't find _sqlite3.so in
the install directory. I thought that _sqlite3.so should be generated
to the install directory.

Would you please let me know how to fix it?

-- 
Regards,
Peng


From debatem1 at gmail.com  Mon May 17 18:48:01 2010
From: debatem1 at gmail.com (geremy condra)
Date: Mon, 17 May 2010 15:48:01 -0700
Subject: Picking a license
In-Reply-To: <87fx1qji9t.fsf@benfinney.id.au>
References: 
	
	 <87r5ldbw3k.fsf@benfinney.id.au>
	 <87fx1qji9t.fsf@benfinney.id.au>
Message-ID: 

This whole conversation is ridiculous, and better suited to slashdot than
python-list. Is it really necessary for it to continue?

Geremy Condra


From rhodri at wildebst.demon.co.uk  Mon May 17 18:54:38 2010
From: rhodri at wildebst.demon.co.uk (Rhodri James)
Date: Mon, 17 May 2010 23:54:38 +0100
Subject: Global variables for python applications
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
	
Message-ID: 

On Mon, 17 May 2010 05:29:20 +0100, Steven D'Aprano  
 wrote:

> On Sun, 16 May 2010 18:57:15 -0700, John Nagle wrote:
>
>> James Mills wrote:
>>> The only place global variables are considered somewhat "acceptable"
>>> are as constants in a module shared as a static value.
>>
>>     Python really ought to have named constants.
>
> +1
>
> Unfortunately, it will most likely require new syntax, and semantics.
> While the concept of a constant is pretty straightforward for immutable
> types like ints and strings, what about mutable types?
>
> And then there's the moratorium, so even if we had agreement on semantics
> and syntax, and a patch, it couldn't be deployed for a few years.

Careful, you're reconflating two concepts that John separated: mutability  
of an object and binding of a name.  I'm on the side of 'named constant'  
meaning 'this name (in this scope) is bound to this object and cannot be  
rebound.'  That would cover most of the cases people care about, and the  
gotchas are essentially the same as with default arguments.

But yes, it would require new syntax.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses


From nyamatongwe+thunder at gmail.com  Mon May 17 19:05:10 2010
From: nyamatongwe+thunder at gmail.com (Neil Hodgson)
Date: Mon, 17 May 2010 23:05:10 GMT
Subject: Encoding troubles
In-Reply-To: <7bb834e4-940f-43eb-8ebb-8c29599dda87@h37g2000pra.googlegroups.com>
References: <7bb834e4-940f-43eb-8ebb-8c29599dda87@h37g2000pra.googlegroups.com>
Message-ID: 

JB:

> as hypens (?) and apostrophes (?) are in an odd encoding. When passed
> to the database using sqlalchemy they appear as ??? and other
> characters.

   The encoding is UTF-8. Normally the best way to handle encodings is
to convert to Unicode strings (unicode(s, "UTF-8")) as soon as possible
and perform most processing in Unicode.

   Neil


From bryanjugglercryptographer at yahoo.com  Mon May 17 19:29:22 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Mon, 17 May 2010 16:29:22 -0700 (PDT)
Subject: Some help needed with small multi-threaded program!
References: 
Message-ID: <94c05c9b-2f5f-42b2-a320-e0f7db7fab23@a2g2000prd.googlegroups.com>

Oltmans wrote:
> I've a small multi-threaded program that is written by keeping
> Producer-Consumer pattern in mind.
[...]
> Problem is that program sort of runs fine, however, it never
> terminates itself and, more importantly, it doesn't print last-three
> lines of the program(which is important for my purposes). I've looked
> at the docs, but I couldn't figure out a solution so if someone can
> spot the problem and suggest a solution that will be highly
> appreciated. Many thanks in advance.

Well, "the problem" may be a bit presumptuous, but here's *a* problem:

> class TestService(threading.Thread):
[...]
> ? ? def run (self):
> ? ? ? ? while True:
> ? ? ? ? ? ? user = self.queue.get()
> ? ? ? ? ? ? if user:
> ? ? ? ? ? ? ? ? self.login(user)

That thread will not exit, and your main thread tries to join it.

In other news. There's no reason to call queue.task_done() if you
never call queue.join(). Your exception handling is kind of whacked;
that errors[] list doesn't collect enough info and if your program
hangs it's no use.

Your Producer-Consumer pattern is a misfit. Registering a user then
trying to log her in is a nice sequential unit of work that one thread
could handle. The reason for threading in this problem is so that when
one user's work is waiting for the network, you can make progress on
other users.

Hope that helps.

-Bryan Olson


From g.rodola at gmail.com  Mon May 17 19:33:52 2010
From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=)
Date: Tue, 18 May 2010 01:33:52 +0200
Subject: Global variables for python applications
In-Reply-To: 
References: 
	
Message-ID: 

2010/5/16 Chris Rebert :
> On Sun, May 16, 2010 at 10:50 AM, AON LAZIO  wrote:
>> Hi,
>>    How can I set up global variables for the entire python applications?
>> Like I can call and set this variables in any .py files.
>>    Think of it as a global variable in a single .py file but this is for the
>> entire application.
>
> Thankfully, there is no such thing (can you say spaghetti code?). The
> closest approximation, as I said in my previous reply, is to use the
> namespace of a designated module for this purpose, and import that
> module wherever you need to access/modify these "superglobal"
> variables.
>
> Example:
> #g.py:
> #this module exists to hold superglobal vars
> global1 = "foo"
> global2 = "bar"
>
>
> #elsewhere.py:
> #this is some other module in the same program
> import mypackage.g as g
>
> print "global #1 = ", g.global1
> print "global #2 =", g.global2
> g.global1 = "baz" # modify a superglobal
> g.global3 = "qux" # create a new superglobal
>
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
> --
> http://mail.python.org/mailman/listinfo/python-list

I agree global variables are evil, but a config.py module within a
serie of global constants which are supposed to be shared amongst all
other modules is a little less evil, and also a different beast IMO.
Even if you use a class to store such data, a "global" reference to
its instance accessible from everywhere must still exist, so the
problem basically still stands.
I would be interested to know a good practice to solve such a problem.


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil


From aahz at pythoncraft.com  Mon May 17 19:38:56 2010
From: aahz at pythoncraft.com (Aahz)
Date: 17 May 2010 16:38:56 -0700
Subject: Can't find _sqlite3.so in lib-dynload
References: 
Message-ID: 

In article ,
Peng Yu   wrote:
>
>I compiled python2.6.4 from source. But I can't find _sqlite3.so in
>the install directory. I thought that _sqlite3.so should be generated
>to the install directory.
>
>Would you please let me know how to fix it?

Only if you provide some relevant details.  Such as, what OS?

http://www.mikeash.com/getting_answers.html
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From pengyu.ut at gmail.com  Mon May 17 20:08:35 2010
From: pengyu.ut at gmail.com (Peng Yu)
Date: Mon, 17 May 2010 17:08:35 -0700 (PDT)
Subject: Can't find _sqlite3.so in lib-dynload
References:  
	
Message-ID: <2f84cf3b-dda7-42f9-bf8e-ac35f99e9318@u7g2000vbq.googlegroups.com>

On May 17, 6:38?pm, a... at pythoncraft.com (Aahz) wrote:
> In article ,
> Peng Yu ? wrote:
>
>
>
> >I compiled python2.6.4 from source. But I can't find _sqlite3.so in
> >the install directory. I thought that _sqlite3.so should be generated
> >to the install directory.
>
> >Would you please let me know how to fix it?
>
> Only if you provide some relevant details. ?Such as, what OS?
>
> http://www.mikeash.com/getting_answers.html

ubuntu.


From alessandro at molarulez.com  Mon May 17 20:13:52 2010
From: alessandro at molarulez.com (Alessandro Molari)
Date: Tue, 18 May 2010 02:13:52 +0200
Subject: reading XML file using python
In-Reply-To: 
References: 
Message-ID: <201005180213.52470.alessandro@molarulez.com>

I can suggest you the lxml library at http://codespeak.net/lxml/

I've already used it and I think it works very well, it's more pythonic 
than the built-in xml library

For a simple use of xml functionalities you can read 
http://codespeak.net/lxml/tutorial.html

--------
Alessandro Molari
--------
On Monday 17 May 2010 10:34:51 shanti bhushan wrote:
> Hi ,
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com(any hyper text) from XML 
and
> print that.
> please give me the sample program for this.
> regards
> Shanti Bhushan
> Bangalore,India


From steve at REMOVE-THIS-cybersource.com.au  Mon May 17 20:22:52 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 18 May 2010 00:22:52 GMT
Subject: Global variables for python applications
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
	
	
Message-ID: <4bf1dddc$0$27851$c3e8da3@news.astraweb.com>

On Mon, 17 May 2010 23:54:38 +0100, Rhodri James wrote:

> On Mon, 17 May 2010 05:29:20 +0100, Steven D'Aprano
>  wrote:
> 
>> On Sun, 16 May 2010 18:57:15 -0700, John Nagle wrote:
>>
>>> James Mills wrote:
>>>> The only place global variables are considered somewhat "acceptable"
>>>> are as constants in a module shared as a static value.
>>>
>>>     Python really ought to have named constants.
>>
>> +1
>>
>> Unfortunately, it will most likely require new syntax, and semantics.
>> While the concept of a constant is pretty straightforward for immutable
>> types like ints and strings, what about mutable types?
>>
>> And then there's the moratorium, so even if we had agreement on
>> semantics and syntax, and a patch, it couldn't be deployed for a few
>> years.
> 
> Careful, you're reconflating two concepts that John separated:
> mutability of an object and binding of a name.

In my own head the two issues of mutability and rebinding were completely 
separate, but I see now that didn't come through as clearly as I hoped in 
my post. My apologies for any confusion.


> I'm on the side of
> 'named constant' meaning 'this name (in this scope) is bound to this
> object and cannot be rebound.'  That would cover most of the cases
> people care about, and the gotchas are essentially the same as with
> default arguments.

I think it is an abuse of the term constant to allow you to talk about a 
mutable object being "constant", since it can vary. Generally, you don't 
care about identity, only equality. Making up a syntax on the spot:

constant pi = [3.1415]
assert pi = 3.1415
pi[0] = 3
assert pi = 3.1415

makes a mockery of the concept of a constant.

Having said that, recognising mutable objects is a hard problem, so 
simply for reasons of practicality we might have to just live with the 
limitation that "constants" can be mutated if the object supports it.



> But yes, it would require new syntax.


Ideally, but there may be alternatives. I've already mentioned the 
Cookbook recipe, or perhaps something like:

import constants
constants.register('pi')
pi = 3.1415


-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Mon May 17 20:36:13 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 18 May 2010 00:36:13 GMT
Subject: abc don't play well with private method
References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com>
	<4be18d3d$0$19014$426a34cc@news.free.fr>
	
Message-ID: <4bf1e0fd$0$27851$c3e8da3@news.astraweb.com>

On Mon, 17 May 2010 06:35:11 -0700, mouadino wrote:

>> There's no such thing as a "private" attribute in Python. The
>> name-mangling mechanism invoked by "__name" is really meant to avoid
>> accidental redefinition of the attribute in a derived class.
> 
>> In this case, your attribute is expected to be redefined, so you
>> definitly don't want any name mangling here.
> 
> yes , but what i have supposed is that the name mangling will not be
> applied when you use abc especially when you decorate the function with
> abc.abstractmethod , because it's will(should) be redefined (so
> something is wrong with the abc module) .

No, your expectations are wrong. Name mangling works the same no matter 
what class, whether you are using ABCs or not.


>> Also and FWIW, the naming convention for "implementation attributes" is
>> a single leading underscore
> 
> sorry but i don't agree on this. the two underscore (__) are used in
> classes level for defining private method in the python way, and the one
> underscore (_) is used in the module level :

Whether you agree or not, single underscores are commonly used as the 
convention for private methods and attributes. See PEP 8, which is 
written by Python's creator, Guido van Rossum:

http://www.python.org/dev/peps/pep-0008/




> """Prepending a single underscore (_) has some support for protecting
> module variables and functions (not included with import * from).
> Prepending a double underscore (__) to an instance variable or method
> effectively serves to make the variable or method private to its class
> (using name mangling). """
> src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html


If that's what it says, it's wrong, because there's nothing "effective" 
about double-underscore privacy. It's a very weak, easily bypassed 
(deliberately and accidentally) form of privacy, and it complicates 
debugging.

Generally, most people here recommend you ignore leading double-
underscores and just flag your methods as "private by convention" with a 
single leading underscore.



-- 
Steven


From parag.kanade at gmail.com  Mon May 17 22:02:18 2010
From: parag.kanade at gmail.com (paragk)
Date: Mon, 17 May 2010 19:02:18 -0700 (PDT)
Subject: pickle unable to load collection
Message-ID: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com>

Hi,

I am unable to figure out the cause of python pickle unable to find
the collection module.

I am getting

    __import__(module)
ImportError: No module named collections

when I try to load a pickled object.

Details:

Python version:

Python 2.6 (r26:66721, Oct  2 2008, 11:35:03) [MSC v.1500 32 bit
(Intel)] on win32


[CODE]

import sys
import glob
import collections
import pickle

...

SomeListDict = collections.defaultdict(list)

... # Populate SomeListDict

DictFile = open (options.saveDict, 'w')
pickle.dump(SomeListDict , DictFile, -1)
DictFile.close()

...

# Try loading the dictionary

LoadDictFile = open(options.loadDict, 'rb')
SomeListDict = pickle.load(LoadDictFile)
LoadDictFile.close()

...
 [CODE END]

The pickle.dump(CallGraphDict, DictFile, -1) works fine. The
dictionary is saved.

The interesting thing is, the dump function is able to find the
collections module.
        try:
            __import__(module)
            mod = sys.modules[module]
            klass = getattr(mod, name)

The above try block succeeds.

module
str: collections

mod
module: 

klass
type: 


The SomeListDict = pickle.load(LoadDictFile) fails with

    __import__(module)
ImportError: No module named collections


The sequence of calls is:

    def load_global(self):
        module = self.readline()[:-1]
        name = self.readline()[:-1]
        klass = self.find_class(module, name)
        self.append(klass)
    dispatch[GLOBAL] = load_global

Variables:

module
str: collections

name
str: defaultdict


The code where the exception occurs is:

    def find_class(self, module, name):
        # Subclasses may override this
        __import__(module)
        mod = sys.modules[module]
        klass = getattr(mod, name)
        return klass


>From the above analysis, clearly the collection module exists, since
the dump works.

What am I missing?


From steven at REMOVE.THIS.cybersource.com.au  Mon May 17 22:07:56 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 18 May 2010 02:07:56 GMT
Subject: pickle unable to load collection
References: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com>
Message-ID: 

On Mon, 17 May 2010 19:02:18 -0700, paragk wrote:

> Hi,
> 
> I am unable to figure out the cause of python pickle unable to find the
> collection module.
> 
> I am getting
> 
>     __import__(module)
> ImportError: No module named collections

What is the actual value of module? Here's an obvious failure mode:

>>> __import__("collections ")
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named collections


> module
> str: collections

Try printing repr(str) to see what's actually there.


It may also help if you post a copy-and-paste of the complete traceback.



-- 
Steven


From bryanjugglercryptographer at yahoo.com  Mon May 17 22:38:51 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Mon, 17 May 2010 19:38:51 -0700 (PDT)
Subject: Encoding troubles
References: <7bb834e4-940f-43eb-8ebb-8c29599dda87@h37g2000pra.googlegroups.com>
	
Message-ID: <2a2b3dcb-d323-4733-9efe-77f6466dd788@k25g2000prh.googlegroups.com>

Neil Hodgson wrote:
> JB:
>
> > as hypens (?) and apostrophes (?) are in an odd encoding. When passed
> > to the database using sqlalchemy they appear as ??? and other
> > characters.
>
> ? ?The encoding is UTF-8. Normally the best way to handle encodings is
> to convert to Unicode strings (unicode(s, "UTF-8")) as soon as possible
> and perform most processing in Unicode.

Good advice to work in Unicode (and in Python 3.X str is unicode), but
I'd guess the encoding he's getting is "Windows-1252". The default
character set of HTTP is ISO-8859-1, but Microsoft likes to use
Windows-1252 in it's place.

What to do about it? First, try specifying utf-8 in the form
containing the textarea, as in

  
Note that specifying ISO-8859-1 will not work, in that Microsoft will still use Windows-1252. I've heard they've gotten better at supporting utf-8, but I haven't tested. When a request comes in, check for a Content-Type header that names the character set, which should be: Content-Type: application/x-www-form-urlencoded; charset=utf-8 Then you con decode to a unicode object as Neil Hodgson explained. In case you still have to deal with Windows-1252, Python knows how to translate Windows-1252 to the best-fit in Unicode. In current Python 2.x: ustring = unicode(raw_string, 'Windows-1252') In Python 3.X, what comes from a socket is bytes, and str means unicode: ustring = str(raw_bytes, 'Windows-1252') Of course this all assumes that JB's database likes Unicode. If it chokes, then alternatives include encoding back to utf-8 and storing as binary, or translating characters to some best-fit in the set the database supports. -- --Bryan Olson From shuvro05 at gmail.com Mon May 17 23:52:01 2010 From: shuvro05 at gmail.com (shuvro) Date: Mon, 17 May 2010 20:52:01 -0700 (PDT) Subject: getting attributes and methods of class without creating object Message-ID: <50a7abf5-bbe7-4c2d-af53-209be5822a6a@q13g2000vbm.googlegroups.com> Suppose I have a class like this - class myClass(object): def __init__(self): self.a = 10 self.b = 20 def my_method(self,var = 20): self.local_var = var I want to know about its method(__init__ and my_method) and variables(a,b, local_var) without creating the object of it. I tried getmembers function of inspect module. But it can do this with an object of myClass as argument. Like import inspect var = myClass() inspect.getmembers(var) I have to know about this without creating the object of myClass. Can anyone help me please? From r1chardj0n3s at gmail.com Tue May 18 00:12:53 2010 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Tue, 18 May 2010 14:12:53 +1000 Subject: PyCon Australia 2010 program announced Message-ID: Hi all, The program for PyCon Australia 2010, to be held at the Sydney Masonic Center over the weekend of June 26 and 27, has been posted. View the full list of presentations and the schedule at: http://pycon-au.org/2010/conference/ Register here: http://pycon-au.org/reg Richard Jones PyCon Australia 2010 Program Chair From pmaupin at gmail.com Tue May 18 00:50:15 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Mon, 17 May 2010 21:50:15 -0700 (PDT) Subject: getting attributes and methods of class without creating object References: <50a7abf5-bbe7-4c2d-af53-209be5822a6a@q13g2000vbm.googlegroups.com> Message-ID: <25494d5d-19cd-43f2-8483-07bcdfa71a27@e28g2000vbd.googlegroups.com> On May 17, 10:52?pm, shuvro wrote: > Suppose I have a class like this - > > class myClass(object): > > ? ? def __init__(self): > ? ? ? ? self.a = 10 > ? ? ? ? self.b = 20 > > ? ? def my_method(self,var = 20): > ? ? ? ? self.local_var = var > > I want to know about its method(__init__ and my_method) and > variables(a,b, local_var) without creating the object of it. I tried > getmembers function of inspect module. But it can do this with an > object of myClass as argument. Like > > import inspect > var = myClass() > inspect.getmembers(var) > > I have to know about this without creating the object of myClass. > Can anyone help me please? Well, you can do the same thing with myClass itself: inspect.getmembers(myClass) But that won't show you a,b, or local_var, because those don't belong to the class. They only belong to class instances, and maybe even not all class instances. (For example, if my_method is not called, then the instance won't have local_var defined.) Python is a very dynamic language, and class instances (and even the classes themselves!) can be modified at any time during execution. You don't even have to be executing inside a class's function to add stuff to it: class foo: pass bar = foo() bar.a = 3 So to "know" about the attributes of an instance of a class without actually creating that instance is very difficult. You didn't specify why you want to do this, but often the reason is to try to catch potential errors without actually running code. This is typically called "linting", and there are a few Python packages designed to do this, such as pylint and pychecker. Probably others, but I don't know anything about them, because I find that in most cases, the best way to test or to reason about Python code is to actually run it. Regards, Pat From ershantibhushan at gmail.com Tue May 18 01:18:44 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Mon, 17 May 2010 22:18:44 -0700 (PDT) Subject: url fetching from xml depending upon selection Message-ID: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> I have a sample.XML file the code is like this My Podcasts Sun, 07 Mar 2010 15:53:26 GMT Sun, 07 Mar 2010 15:53:26 GMT This my python code from xml.etree import ElementTree with open('our.xml', 'rt') as f: tree = ElementTree.parse(f) for node, value in tree.findall('.//TestCase/Input'): url=node.attrib.get('url') print url i want to print the url depending on name="sprint_001". If i change my option to sprint_002 it should print url for sprint_002 From vincent at vincentdavis.net Tue May 18 01:21:32 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 17 May 2010 23:21:32 -0600 Subject: Is this an ok thing to do in a class Message-ID: Just wondering if there is a problem with mixing a dictionary into a class like this. Everything seems to work as I would expect. class foo(object): def __init__(self, x): self.letter = dict(a=1,b=2,c=3) self.A=self.letter['a'] self.x=self.letter[x] >>> afoo = foo('b') >>> afoo.x 2 >>> afoo.A 1 >>> afoo.letter['a'] 1 >>> afoo.letter.items() [('a', 1), ('c', 3), ('b', 2)] *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From ershantibhushan at gmail.com Tue May 18 01:23:43 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Mon, 17 May 2010 22:23:43 -0700 (PDT) Subject: url fetching from xml depending upon selection References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: <878c9bd6-eda2-4b97-b78a-c49b32ee7328@h37g2000pra.googlegroups.com> On May 18, 10:18?am, shanti bhushan wrote: > I have a sample.XML file > the code is like this > > > > > ? ? ? ? My Podcasts > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > > > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > > > > This my python code > from xml.etree import ElementTree > > with open('our.xml', 'rt') as f: > ? ? tree = ElementTree.parse(f) > > for node, value in tree.findall('.//TestCase/Input'): > > ? ? ? ? url=node.attrib.get('url') > ? ? ? ? print url > > i want to print the url depending on name="sprint_001". > If i change my option to sprint_002 it should print url for sprint_002 this code print all URL but there is no option to select URLs depending upon my choice from xml.etree import ElementTree with open('our.xml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.findall('.//TestCase/Input'): url=node.attrib.get('url') print url From ershantibhushan at gmail.com Tue May 18 01:45:13 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Mon, 17 May 2010 22:45:13 -0700 (PDT) Subject: url fetching from xml depending upon selection References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: <371a76e4-3fce-4578-9dfc-a20294607550@t14g2000prm.googlegroups.com> On May 18, 10:18?am, shanti bhushan wrote: > I have a sample.XML file > the code is like this > > > > > ? ? ? ? My Podcasts > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > > > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > > > > This my python code > from xml.etree import ElementTree > > with open('our.xml', 'rt') as f: > ? ? tree = ElementTree.parse(f) > > for node, value in tree.findall('.//TestCase/Input'): > > ? ? ? ? url=node.attrib.get('url') > ? ? ? ? print url > > i want to print the url depending on name="sprint_001". > If i change my option to sprint_002 it should print url for sprint_002 i am trying to do with this code please correct my code from xml.etree import ElementTree with open('our.xml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.findall('.//TestCase/Input'): if name=='Sprint_001': print node.attrib.get('url') i want to print only url that comes under name=Sprint_001 From shuvro05 at gmail.com Tue May 18 02:11:29 2010 From: shuvro05 at gmail.com (shuvro) Date: Mon, 17 May 2010 23:11:29 -0700 (PDT) Subject: getting attributes and methods of class without creating object References: <50a7abf5-bbe7-4c2d-af53-209be5822a6a@q13g2000vbm.googlegroups.com> <25494d5d-19cd-43f2-8483-07bcdfa71a27@e28g2000vbd.googlegroups.com> Message-ID: <84f6e33a-05da-4f3e-9d9f-532d7ce72d10@q13g2000vbm.googlegroups.com> On May 18, 11:50?am, Patrick Maupin wrote: > On May 17, 10:52?pm, shuvro wrote: > > > > > Suppose I have a class like this - > > > class myClass(object): > > > ? ? def __init__(self): > > ? ? ? ? self.a = 10 > > ? ? ? ? self.b = 20 > > > ? ? def my_method(self,var = 20): > > ? ? ? ? self.local_var = var > > > I want to know about its method(__init__ and my_method) and > > variables(a,b, local_var) without creating the object of it. I tried > > getmembers function of inspect module. But it can do this with an > > object of myClass as argument. Like > > > import inspect > > var = myClass() > > inspect.getmembers(var) > > > I have to know about this without creating the object of myClass. > > Can anyone help me please? > > Well, you can do the same thing with myClass itself: > > inspect.getmembers(myClass) > > But that won't show you a,b, or local_var, because those don't belong > to the class. ?They only belong to class instances, and maybe even not > all class instances. ?(For example, if my_method is not called, then > the instance won't have local_var defined.) > > Python is a very dynamic language, and class instances (and even the > classes themselves!) can be modified at any time during execution. > You don't even have to be executing inside a class's function to add > stuff to it: > > class foo: > ? ? pass > > bar = foo() > bar.a = 3 > > So to "know" about the attributes of an instance of a class without > actually creating that instance is very difficult. ?You didn't specify > why you want to do this, but often the reason is to try to catch > potential errors without actually running code. ?This is typically > called "linting", and there are a few Python packages designed to do > this, such as pylint and pychecker. ?Probably others, but I don't know > anything about them, because I find that in most cases, the best way > to test or to reason about Python code is to actually run it. > > Regards, > Pat Thanks Pat for your informative reply. Actually what I am trying to do is to write an external exporter for the data types an open source software(Blender). So, I have to collect the properties of the classes. Here, I have no chance to edit the class and add inspect codes there, neither I can create objects of the existing classes (that will do some additional things which I not want). Is it not possible with the existing python facilities (without adding external libraries) ? Shuvro From stefan_ml at behnel.de Tue May 18 03:04:14 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 May 2010 09:04:14 +0200 Subject: url fetching from xml depending upon selection In-Reply-To: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: shanti bhushan, 18.05.2010 07:18: > I have a sample.XML file > the code is like this > > > > > My Podcasts > Sun, 07 Mar 2010 15:53:26 > > GMT > Sun, 07 Mar 2010 15:53:26 > > GMT > > > > > > > > > > > > > > > > > > > > > > This my python code > from xml.etree import ElementTree > > with open('our.xml', 'rt') as f: > tree = ElementTree.parse(f) > > for node, value in tree.findall('.//TestCase/Input'): > > url=node.attrib.get('url') > print url > > i want to print the url depending on name="sprint_001". for test_case in tree.findall('.//TestCase'): if test_case.get('name') == 'sprint_002': for input_el in test_case: print input_el.get('url') Stefan From __peter__ at web.de Tue May 18 03:10:24 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 May 2010 09:10:24 +0200 Subject: pickle unable to load collection References: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com> Message-ID: paragk wrote: > Hi, > > I am unable to figure out the cause of python pickle unable to find > the collection module. > > I am getting > > __import__(module) > ImportError: No module named collections > > when I try to load a pickled object. > > Details: > > Python version: > > Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit > (Intel)] on win32 > > > [CODE] > > import sys > import glob > import collections > import pickle > > ... > > SomeListDict = collections.defaultdict(list) > > ... # Populate SomeListDict > > DictFile = open (options.saveDict, 'w') > pickle.dump(SomeListDict , DictFile, -1) > DictFile.close() [...] > From the above analysis, clearly the collection module exists, since > the dump works. > > What am I missing? You have to open the file in binary mode "wb". >>> import collections >>> import pickle >>> data = pickle.dumps(collections.defaultdict()) >>> pickle.loads(data) defaultdict(None, {}) Now simulate the effect of writing in text mode and reading in binary mode: >>> garbled_data = data.replace("\n", "\r\n") >>> pickle.loads(garbled_data) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/pickle.py", line 1374, in loads return Unpickler(file).load() File "/usr/lib/python2.6/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.6/pickle.py", line 1090, in load_global klass = self.find_class(module, name) File "/usr/lib/python2.6/pickle.py", line 1124, in find_class __import__(module) ImportError: No module named collections >>> try: pickle.loads(garbled_data) ... except ImportError as e: ... e ... ImportError('No module named collections\r',) So as Steven suspected there was a whitespace char in the module name: pickle.load() was looking for the "collections\r" module. Peter From jonvspython at gmail.com Tue May 18 03:31:51 2010 From: jonvspython at gmail.com (jon vs. python) Date: Tue, 18 May 2010 09:31:51 +0200 Subject: Pyserial and pysqlite data types, need advice In-Reply-To: References: Message-ID: The best thing I've found is this: http://eli.thegreenplace.net/2009/05/29/storing-blobs-in-a-sqlite-db-with-pythonpysqlite/ On Mon, May 17, 2010 at 5:05 PM, jon vs. python wrote: > Hi, > I'm trying to store frames received via serial port (using Pyserial) into a > sqlite database (using Pysqlite) in order to perform off-line processing. > Thus I could use both SQL's power and Python's magic to make everything > easier. I'd like my code to be generic and work both for binary and ascii > protocols, too. > > Which kind of data should I use to store the frames? > Should I store every byte as a char in VARCHAR? (This seems to fail when > trying to store non printable characters). > Should I encapsulate frames in buffer objects and store them in BLOBs? > (This seems to work but hides content and thus doesn't allow to use database > operations directly on the data) > I've also tried, unsuccessfully, to use bytearrays with pysqlite... > > Any suggestion? > > Thanks, Jon. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ershantibhushan at gmail.com Tue May 18 04:06:08 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Tue, 18 May 2010 01:06:08 -0700 (PDT) Subject: url fetching from xml depending upon selection References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: On May 18, 10:18?am, shanti bhushan wrote: > I have a sample.XML file > the code is like this > > > > > ? ? ? ? My Podcasts > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > > > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > > > > This my python code > from xml.etree import ElementTree > > with open('our.xml', 'rt') as f: > ? ? tree = ElementTree.parse(f) > > for node, value in tree.findall('.//TestCase/Input'): > > ? ? ? ? url=node.attrib.get('url') > ? ? ? ? print url > > i want to print the url depending on name="sprint_001". > If i change my option to sprint_002 it should print url for sprint_002 i have tried some new things here from xml.etree import ElementTree with open('our.xml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.findall('.//TestCase/'): print node.attrib.keys() print node.attrib.items() print node.attrib.get(1) url=node.attrib.get('url') print url but i am not getting idea ... how to achive my motive From ershantibhushan at gmail.com Tue May 18 04:08:48 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Tue, 18 May 2010 01:08:48 -0700 (PDT) Subject: url fetching from xml depending upon selection References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: <9bf77ce4-474a-45ff-9955-23faadf8bac2@s4g2000prh.googlegroups.com> On May 18, 12:04?pm, Stefan Behnel wrote: > shanti bhushan, 18.05.2010 07:18: > > > > > > > I have a sample.XML file > > the code is like this > > > > > > > > > ? ?My Podcasts > > ? ?Sun, 07 Mar 2010 15:53:26 > > > GMT > > ? ?Sun, 07 Mar 2010 15:53:26 > > > GMT > > > > > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > > > > > > This my python code > > from xml.etree import ElementTree > > > with open('our.xml', 'rt') as f: > > ? ? ?tree = ElementTree.parse(f) > > > for node, value in tree.findall('.//TestCase/Input'): > > > ? ? ? ? ?url=node.attrib.get('url') > > ? ? ? ? ?print url > > > i want to print the url depending on name="sprint_001". > > ? ? ?for test_case in tree.findall('.//TestCase'): > ? ? ? ? ?if test_case.get('name') == 'sprint_002': > ? ? ? ? ? ? for input_el in test_case: > ? ? ? ? ? ? ? ? print input_el.get('url') > > Stefan- Hide quoted text - > > - Show quoted text - Hi Stevan i tried your logic i am not getting any out put for this From stefan_ml at behnel.de Tue May 18 04:12:57 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 May 2010 10:12:57 +0200 Subject: url fetching from xml depending upon selection In-Reply-To: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: shanti bhushan, 18.05.2010 07:18: > I have a sample.XML file > the code is like this > > > > > My Podcasts > Sun, 07 Mar 2010 15:53:26 > > GMT > Sun, 07 Mar 2010 15:53:26 > > GMT > > > > > > > > > > > > > > > > > > > > > > This my python code > from xml.etree import ElementTree > > with open('our.xml', 'rt') as f: > tree = ElementTree.parse(f) > > for node, value in tree.findall('.//TestCase/Input'): > > url=node.attrib.get('url') > print url > > > > i want to print the url depending on name="sprint_001". > If i change my option to sprint_002 it should print url for sprint_002 Actually, try this: test_cases = dict( (test_case.get('name'), [ el.get('url') for el in test_case ]) for test_case in tree.findall('.//TestCase') ) print test_cases['Sprint_001'] # -> prints list of URLs That gives you a dict of test case names that are mapped to the list of their URLs. Stefan From ershantibhushan at gmail.com Tue May 18 04:19:20 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Tue, 18 May 2010 01:19:20 -0700 (PDT) Subject: url fetching from xml depending upon selection References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: <57174614-2db9-4171-bd4e-6d2720f1552c@h20g2000prn.googlegroups.com> On May 18, 12:04?pm, Stefan Behnel wrote: > shanti bhushan, 18.05.2010 07:18: > > > > > > > I have a sample.XML file > > the code is like this > > > > > > > > > ? ?My Podcasts > > ? ?Sun, 07 Mar 2010 15:53:26 > > > GMT > > ? ?Sun, 07 Mar 2010 15:53:26 > > > GMT > > > > > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > > > > > > This my python code > > from xml.etree import ElementTree > > > with open('our.xml', 'rt') as f: > > ? ? ?tree = ElementTree.parse(f) > > > for node, value in tree.findall('.//TestCase/Input'): > > > ? ? ? ? ?url=node.attrib.get('url') > > ? ? ? ? ?print url > > > i want to print the url depending on name="sprint_001". > > ? ? ?for test_case in tree.findall('.//TestCase'): > ? ? ? ? ?if test_case.get('name') == 'sprint_002': > ? ? ? ? ? ? for input_el in test_case: > ? ? ? ? ? ? ? ? print input_el.get('url') > > Stefan- Hide quoted text - > > - Show quoted text - Great Help Stefan - my regards to you thankyou once again it waorks fine ... From parag.kanade at gmail.com Tue May 18 04:26:24 2010 From: parag.kanade at gmail.com (paragk) Date: Tue, 18 May 2010 01:26:24 -0700 (PDT) Subject: pickle unable to load collection References: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com> Message-ID: On May 18, 12:10?am, Peter Otten <__pete... at web.de> wrote: > paragk wrote: > > Hi, > > > I am unable to figure out the cause of python pickle unable to find > > the collection module. > > > I am getting > > > ? ? __import__(module) > > ImportError: No module named collections > > > when I try to load a pickled object. > > > Details: > > > Python version: > > > Python 2.6 (r26:66721, Oct ?2 2008, 11:35:03) [MSC v.1500 32 bit > > (Intel)] on win32 > > > [CODE] > > > import sys > > import glob > > import collections > > import pickle > > > ... > > > SomeListDict = collections.defaultdict(list) > > > ... # Populate SomeListDict > > > DictFile = open (options.saveDict, 'w') > > pickle.dump(SomeListDict , DictFile, -1) > > DictFile.close() > > [...] > > > From the above analysis, clearly the collection module exists, since > > the dump works. > > > What am I missing? > > You have to open the file in binary mode "wb". > > >>> import collections > >>> import pickle > >>> data = pickle.dumps(collections.defaultdict()) > >>> pickle.loads(data) > > defaultdict(None, {}) > > Now simulate the effect of writing in text mode and reading in binary mode: > > >>> garbled_data = data.replace("\n", "\r\n") > >>> pickle.loads(garbled_data) > > Traceback (most recent call last): > ? File "", line 1, in > ? File "/usr/lib/python2.6/pickle.py", line 1374, in loads > ? ? return Unpickler(file).load() > ? File "/usr/lib/python2.6/pickle.py", line 858, in load > ? ? dispatch[key](self) > ? File "/usr/lib/python2.6/pickle.py", line 1090, in load_global > ? ? klass = self.find_class(module, name) > ? File "/usr/lib/python2.6/pickle.py", line 1124, in find_class > ? ? __import__(module) > ImportError: No module named collections > > >>> try: pickle.loads(garbled_data) > > ... except ImportError as e: > ... ? ? e > ... > ImportError('No module named collections\r',) > > So as Steven suspected there was a whitespace char in the module name: > pickle.load() was looking for the "collections\r" module. > > Peter Thank you for the suggestions. Opening the file in 'wb' mode worked. Thanks, Parag From stefan_ml at behnel.de Tue May 18 04:26:47 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 May 2010 10:26:47 +0200 Subject: url fetching from xml depending upon selection In-Reply-To: <9bf77ce4-474a-45ff-9955-23faadf8bac2@s4g2000prh.googlegroups.com> References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> <9bf77ce4-474a-45ff-9955-23faadf8bac2@s4g2000prh.googlegroups.com> Message-ID: shanti bhushan, 18.05.2010 10:08: > On May 18, 12:04 pm, Stefan Behnel wrote: >> shanti bhushan, 18.05.2010 07:18: >>> [...] >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >> >>> This my python code >>> from xml.etree import ElementTree >> >>> with open('our.xml', 'rt') as f: >>> tree = ElementTree.parse(f) >> >>> for node, value in tree.findall('.//TestCase/Input'): >> >>> url=node.attrib.get('url') >>> print url >> >>> i want to print the url depending on name="sprint_001". >> >> for test_case in tree.findall('.//TestCase'): >> if test_case.get('name') == 'sprint_002': >> for input_el in test_case: >> print input_el.get('url') >> > i tried your logic i am not getting any out put for this Obviously, because the correct name value is 'Sprint_002', not 'sprint_002'. Please ask back if you need help in understanding the code I posted. Stefan From duncan.booth at invalid.invalid Tue May 18 04:39:43 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 May 2010 08:39:43 GMT Subject: Global variables for python applications References: <4bf09ce6$0$1661$742ec2ed@news.sonic.net> <4bf1dddc$0$27851$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I think it is an abuse of the term constant to allow you to talk about a > mutable object being "constant", since it can vary. Generally, you don't > care about identity, only equality. Making up a syntax on the spot: > > constant pi = [3.1415] > assert pi = 3.1415 > pi[0] = 3 > assert pi = 3.1415 > > makes a mockery of the concept of a constant. A better keyword might be something like 'alias' to imply that the name and value are interchangeable. -- Duncan Booth http://kupuguy.blogspot.com From simon at brunningonline.net Tue May 18 04:54:37 2010 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 18 May 2010 09:54:37 +0100 Subject: Is this an ok thing to do in a class In-Reply-To: References: Message-ID: On 18 May 2010 06:21:32 UTC+1, Vincent Davis wrote: > > Just wondering if there is a problem with mixing a dictionary into a class like this. Everything seems to work as I would expect. No problem at all AFAIC. -- Cheers, Simon B. From pacopyc at gmail.com Tue May 18 05:45:03 2010 From: pacopyc at gmail.com (pacopyc) Date: Tue, 18 May 2010 02:45:03 -0700 (PDT) Subject: max time wait for a function Message-ID: <4418c1f3-564f-48c1-85e3-48d5678a4f38@y21g2000vba.googlegroups.com> Hi, I've a question for you. I'd like to call a function and waiting its return value for a time max (30 sec). The function could not respond and then I must avoid to wait for infinite time. OS is Windows XP. Can you help me? Thank From marduk at letterboxes.org Tue May 18 06:24:23 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 18 May 2010 06:24:23 -0400 Subject: max time wait for a function In-Reply-To: <4418c1f3-564f-48c1-85e3-48d5678a4f38@y21g2000vba.googlegroups.com> References: <4418c1f3-564f-48c1-85e3-48d5678a4f38@y21g2000vba.googlegroups.com> Message-ID: <1274178263.232897.38.camel@paska> On Tue, 2010-05-18 at 02:45 -0700, pacopyc wrote: > Hi, I've a question for you. I'd like to call a function and waiting > its return value for a time max (30 sec). > The function could not respond and then I must avoid to wait for > infinite time. OS is Windows XP. > Can you help me? > > Thank This is how I do it with a function decorator. I probably borrowed this from someone and not attributed it. Anyway, it works on Linux, not sure about Windows: def function_timeout(seconds): """Function decorator to raise a timeout on a function call""" import signal class FunctionTimeOut(Exception): pass def decorate(f): def timeout(signum, frame): raise FunctionTimeOut() def funct(*args, **kwargs): old = signal.signal(signal.SIGALRM, timeout) signal.alarm(seconds) try: result = f(*args, **kwargs) finally: signal.signal(signal.SIGALRM, old) signal.alarm(0) return result return funct return decorate From kushal.kumaran+python at gmail.com Tue May 18 07:10:23 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 18 May 2010 16:40:23 +0530 Subject: Can't find _sqlite3.so in lib-dynload In-Reply-To: <2f84cf3b-dda7-42f9-bf8e-ac35f99e9318@u7g2000vbq.googlegroups.com> References: <2f84cf3b-dda7-42f9-bf8e-ac35f99e9318@u7g2000vbq.googlegroups.com> Message-ID: On Tue, May 18, 2010 at 5:38 AM, Peng Yu wrote: > On May 17, 6:38?pm, a... at pythoncraft.com (Aahz) wrote: >> In article , >> Peng Yu ? wrote: >> >> >> >> >I compiled python2.6.4 from source. But I can't find _sqlite3.so in >> >the install directory. I thought that _sqlite3.so should be generated >> >to the install directory. >> >> >Would you please let me know how to fix it? >> >> Only if you provide some relevant details. ?Such as, what OS? >> >> http://www.mikeash.com/getting_answers.html > > ubuntu. Did the build process give a message at the end listing out the modules it couldn't build? Was _sqlite3 in that list? Do you have the sqlite3 dev package installed? With ubuntu, that's the libsqlite3-dev package. -- regards, kushal From awilliam at whitemice.org Tue May 18 08:12:59 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 18 May 2010 08:12:59 -0400 Subject: subprocess and gvfs-mount In-Reply-To: References: Message-ID: <1274184779.4085.2.camel@linux-yu4c.site> On Mon, 2010-05-17 at 17:54 +0200, Samuel Bancal wrote: > Hi, > I'm coding a script that does some automates for my users ... > including mounting a smb share. > Because we are using Gnome, I choosed to use gvfs-mount, which is > quite similar to "Places > Connect to Server > ..."= > Now my script does : > print "*** Mounting the FILER ..." > cmd = "/usr/bin/gvfs-mount smb://%s\;% > s at myfiler.domain.ch/data/%s" % (my_domain, my_user_name, my_user_name) > try: > retCode = subprocess.call(cmd, shell=True) > except KeyboardInterrupt, e: > sys.stderr.write("Interrupted by ctrl-c. Exiting\n") > sys.exit(1) > if retCode != 0: > sys.stderr.write("Error while mounting : %s\n" % retCode > I have two major problems with this code : > - In case of "ctr-c" while the password is asked to the user, I get a > Terminal in which the output from keyboard is inhibited... (like while > typing password) > - When the user runs this script by "double-click > Run" (not "Run in > terminal") ... there is no interaction with the user. Which is normal [there is a run-in-terminal check box somewhere?]. If your users are running it in GNOME then you should implement a GUI (PyGTK) for the user interaction [prompting for the password]. Or better use the GNOME keyring. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From bryanjugglercryptographer at yahoo.com Tue May 18 09:22:23 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 18 May 2010 06:22:23 -0700 (PDT) Subject: max time wait for a function References: <4418c1f3-564f-48c1-85e3-48d5678a4f38@y21g2000vba.googlegroups.com> Message-ID: <5d0c68d3-21b0-49aa-ab78-dad0bccbfe45@v29g2000prb.googlegroups.com> pacopyc wrote: > I'd like to call a function and waiting > its return value for a time max (30 sec). > The function could not respond and then I must avoid to wait for > infinite time. OS is Windows XP. You can do that using the multiprocessing module, which is in the standard library of Python 2.6 or better. It has certain limitations, but works on XP. The functions have to be defined at module scope, and the arguments and return value must be pickleable. The way multiprocessing works on Windows, it launches a new process which runs the Python interpreter on the module again, and pickles the arguments to pipe them to the new process. Below is a simple working demo/test. The demo uses a timeout of 1 second, rather than the specified 30, to avoid excessive boringness. In practice, timeout_function() would be recklessly inefficient for controlling quick operations; it creates a new pool of processes for each function call that it might need to time-out. That's fixable, but the question here is about a 30-second-plus processing problem, and in that kind of case the overhead of creating one or a few new processes is lost in the noise. -Bryan Olson #-------------------- from multiprocessing import Pool, TimeoutError def timeout_function(timeout, f, args=(), kwargs={}): """ Return f(*args, **kwargs), or if that takes to long raise multiprocessing.TimeoutError. """ pool = Pool(1) return pool.apply_async(f, args, kwargs).get(timeout) #-------------- # simple demo-test: from random import random as rand from time import sleep def sillyfunc(sleeptime): # Time-absorbing function for testing sleep(sleeptime) return 'Done.' if __name__ == '__main__': timeout = 1.0 print "Timeout is %f seconds" % timeout trials = 100 ntimeouts = 0 for _ in range(trials): # time-out probability a bit over 0.5 sleeptime = rand() * timeout * 2 try: result = timeout_function( timeout, sillyfunc, (sleeptime,)) assert result == 'Done.' print 'Ran without timing out' except TimeoutError: ntimeouts += 1 print 'Timed out' if sleeptime < timeout: print '...Sucks! Slept %f' % sleeptime print 'Timed out %d out of %d' % (ntimeouts, trials) From backgoodoo at gmail.com Tue May 18 09:48:55 2010 From: backgoodoo at gmail.com (Back9) Date: Tue, 18 May 2010 06:48:55 -0700 (PDT) Subject: Regular expression Message-ID: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> Hi, I have a string like this: 0x340x5A0x9B0xBA I want to extract 0x from the string but the first one. How I can use re for this case? The string size will vary. TIA From terenzio.berni at gmail.com Tue May 18 10:09:48 2010 From: terenzio.berni at gmail.com (ilvecchio) Date: Tue, 18 May 2010 07:09:48 -0700 (PDT) Subject: Regular expression References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> Message-ID: <70937fa2-8e91-4343-91e5-2abfc7b755b6@y21g2000vba.googlegroups.com> On May 18, 3:48?pm, Back9 wrote: > ?Hi, > > I have a string like this: > 0x340x5A0x9B0xBA > I want to extract 0x from the string but the first one. > > How I can use re for this case? > > The string size will vary. > > TIA Maybe the easy way is something like this: m = re.match('(0x)(.*)','0x340x5A0x9B0xBA') m.groups()[1] Terenzio From backgoodoo at gmail.com Tue May 18 10:32:54 2010 From: backgoodoo at gmail.com (Back9) Date: Tue, 18 May 2010 07:32:54 -0700 (PDT) Subject: Regular expression References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> <70937fa2-8e91-4343-91e5-2abfc7b755b6@y21g2000vba.googlegroups.com> Message-ID: <7d9d0c8a-26b7-4cc2-8a20-11dc852e2800@j27g2000vbp.googlegroups.com> On May 18, 10:09?am, ilvecchio wrote: > On May 18, 3:48?pm, Back9 wrote: > > > ?Hi, > > > I have a string like this: > > 0x340x5A0x9B0xBA > > I want to extract 0x from the string but the first one. > > > How I can use re for this case? > > > The string size will vary. > > > TIA > > Maybe the easy way is something like this: > > m = re.match('(0x)(.*)','0x340x5A0x9B0xBA') > m.groups()[1] > > Terenzio I mean the result should be like this: 0x345A9BBA From lourosas at gmail.com Tue May 18 10:35:57 2010 From: lourosas at gmail.com (Lou) Date: Tue, 18 May 2010 07:35:57 -0700 (PDT) Subject: Multi-Threading in Python Message-ID: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> Can anyone tell me how easy it is to do multi-threading in Python? This has probably been brought up already, so if it has, thanks anyway From joncle at googlemail.com Tue May 18 10:37:22 2010 From: joncle at googlemail.com (Jon Clements) Date: Tue, 18 May 2010 07:37:22 -0700 (PDT) Subject: Regular expression References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> <70937fa2-8e91-4343-91e5-2abfc7b755b6@y21g2000vba.googlegroups.com> <7d9d0c8a-26b7-4cc2-8a20-11dc852e2800@j27g2000vbp.googlegroups.com> Message-ID: <5f25fa23-0968-4426-bcd4-7075c94f4b64@e21g2000vbl.googlegroups.com> On 18 May, 15:32, Back9 wrote: > On May 18, 10:09?am, ilvecchio wrote: > > > > > On May 18, 3:48?pm, Back9 wrote: > > > > ?Hi, > > > > I have a string like this: > > > 0x340x5A0x9B0xBA > > > I want to extract 0x from the string but the first one. > > > > How I can use re for this case? > > > > The string size will vary. > > > > TIA > > > Maybe the easy way is something like this: > > > m = re.match('(0x)(.*)','0x340x5A0x9B0xBA') > > m.groups()[1] > > > Terenzio > > I mean the result should be like this: > 0x345A9BBA Something like: re.sub(r'\B(0x)', '', s) hth, Jon. From jcd at sdf.lonestar.org Tue May 18 10:40:56 2010 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 18 May 2010 10:40:56 -0400 Subject: Regular expression In-Reply-To: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> Message-ID: <1274193656.13989.10.camel@jcdyer-laptop> Don't use regular expressions for that. s = '0x340x5A0x9B0xBA' return '0x' + ''.join(s.split('0x')) On Tue, 2010-05-18 at 06:48 -0700, Back9 wrote: > Hi, > > I have a string like this: > 0x340x5A0x9B0xBA > I want to extract 0x from the string but the first one. > > How I can use re for this case? > > The string size will vary. > > TIA > From awilliam at whitemice.org Tue May 18 10:45:11 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 18 May 2010 10:45:11 -0400 Subject: Multi-Threading in Python In-Reply-To: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> Message-ID: <1274193911.4085.13.camel@linux-yu4c.site> On Tue, 2010-05-18 at 07:35 -0700, Lou wrote: > Can anyone tell me how easy it is to do multi-threading in Python? Very easy. Or as easy as in any other platform - and as easy to screw up. Personally I prefer to use multiprocessing [which is a module that 'simulates' threads using separate processes]. IMO, it is hard to screw up as you don't get any shared-state for free. > This has probably been brought up already, so if it has, thanks anyway -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From bruno.42.desthuilliers at websiteburo.invalid Tue May 18 10:50:51 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 18 May 2010 16:50:51 +0200 Subject: Is this an ok thing to do in a class In-Reply-To: References: Message-ID: <4bf2a930$0$14553$426a74cc@news.free.fr> Simon Brunning a ?crit : > On 18 May 2010 06:21:32 UTC+1, Vincent Davis wrote: >> Just wondering if there is a problem with mixing a dictionary into a class like this. Everything seems to work as I would expect. > > No problem at all AFAIC. OP didn't show up on c.l.py, so too bad you snipped the relevant code snippet... From bruno.42.desthuilliers at websiteburo.invalid Tue May 18 11:17:35 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 18 May 2010 17:17:35 +0200 Subject: abc don't play well with private method In-Reply-To: References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com> <4be18d3d$0$19014$426a34cc@news.free.fr> Message-ID: <4bf2af74$0$24527$426a74cc@news.free.fr> mouadino a ?crit : > Hello > and thanx for your answer it's was very helpful > > but just to clear some thinks : > >> There's no such thing as a "private" attribute in Python. The >> name-mangling mechanism invoked by "__name" is really meant to avoid >> accidental redefinition of the attribute in a derived class. > >> In this case, your attribute is expected to be redefined, so you >> definitly don't want any name mangling here. > > yes , but what i have supposed is that the name mangling will not be > applied when you use abc especially when you decorate the function > with abc.abstractmethod , because it's will(should) be redefined (so > something is wrong with the abc module) . I agree this might be a bit inconsistant - or at least that your expectations were rather understandable. But well, that's how it is and you'll have to deal with it for at least a few years. Now I bet the name_mangling mechanism is applied in such a way that implementing your expectations would be rather impractical or add way to much overhead. Specially when almost no one ever seem to find a use for this "feature". As far as I'm concerned, I think I didn't used it more half a dozen times, for some very deep implementation detail of some miniframework, and mostly because I'm a bit on the paranoid side. > >> Also and FWIW, the naming convention for "implementation attributes" is >> a single leading underscore > > sorry but i don't agree on this. So you disagree with the established convention followed by (wild guess) about 99.99% of the regulars here and applied in most of the existing python code base. > the two underscore (__) are used in > classes level for defining private method in the python way, The __names are used to invoke name mangling on the attribute (whatever type it is). It doesn't make it "private" - just a bit less subject to accidental override. And - I have ton insist on this - it applies to every attribute. FWIW, Python's "methods" are really not what you may think they are !-) > and the > one underscore (_) is used in the module level : ... to avoid export such named symbols in the case of a wildcard import AND if the module didn't defined an __ALL__ attribute. The _names are used to denote implementation attribute - IOW, don't touch unless you're ready to pay the price. > """Prepending a single underscore (_) has some support for protecting > module variables and functions (not included with import * from). > Prepending a double underscore (__) to an instance variable or method > effectively serves to make the variable or method private to its class > (using name mangling). """ > src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html This is at best badly formulated and really needs a rewrite. From cde3 at live.com Tue May 18 11:29:41 2010 From: cde3 at live.com (Sandy Ydnas) Date: Tue, 18 May 2010 20:29:41 +0500 Subject: Multi-Threading in Python In-Reply-To: <1274193911.4085.13.camel@linux-yu4c.site> References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com>, <1274193911.4085.13.camel@linux-yu4c.site> Message-ID: great can help to find some examples of multiprocessing Sandy > Subject: Re: Multi-Threading in Python > From: awilliam at whitemice.org > To: python-list at python.org > Date: Tue, 18 May 2010 10:45:11 -0400 > > On Tue, 2010-05-18 at 07:35 -0700, Lou wrote: > > Can anyone tell me how easy it is to do multi-threading in Python? > > Very easy. Or as easy as in any other platform - and as easy to screw > up. Personally I prefer to use multiprocessing [which is a module that > 'simulates' threads using separate processes]. IMO, it is hard to screw > up as you don't get any shared-state for free. > > > This has probably been brought up already, so if it has, thanks anyway > > -- > Adam Tauno Williams LPIC-1, Novell CLA > > OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba > > -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Hotmail: Free, trusted and rich email service. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From switch2mathan at gmail.com Tue May 18 11:41:29 2010 From: switch2mathan at gmail.com (MathanK) Date: Tue, 18 May 2010 03:41:29 -1200 Subject: Getting System error with PyModule_AddIntConstant funtion Message-ID: <128ac13aa89.1830538159355529885.-4186638668702438058@gmail.com> Following is a Python C api which runs properly without PyModule_AddIntConstant function. But when PyModule_AddIntConstant() function is used, getting the following error when i call c. path("test call"); " SystemError: NULL result without error in PyObject_Call " Python C api- c.c int test(int a){ return (2*a+a); } PyObject* dict = NULL; static PyObject* path(PyObject* self, PyObject* args) { char *cpath; PyUnicodeObject *path; PyUnicodeObject *test; if (!PyArg_ParseTuple(args, "s", &path)) return NULL; cpath = (char *)path; test = (PyUnicodeObject*)(cpath); PyObject *testDict = PyDict_New(); int testVal = PyDict_SetItem(testDict, (PyObject *)PyUnicode_FromString(cpath), (PyObject *)PyUnicode_FromString(cpath)); return Py_BuildValue("s", test); } static PyObject* c(PyObject* self, PyObject* args) { int a; int result; if(!PyArg_ParseTuple(args, "i", &a)) return NULL; result = test(a); return Py_BuildValue("i", result); } static PyMethodDef cmethods[] = { {"c", c, METH_VARARGS, "watch"}, {"path", path, METH_VARARGS, "test"}, {NULL, NULL, 0, NULL}, }; static struct PyModuleDef c_Module = { PyModuleDef_HEAD_INIT, "c", ( "Interface." ), -1, cmethods }; PyMODINIT_FUNC PyInit_c(void) { PyObject* obj = PyModule_Create(&c_Module); long lon1 = 0; PyModule_AddIntConstant(obj, "test", lon1); } int main(int argc, wchar_t *argv[]) { PyImport_AppendInittab("c", PyInit_c); Py_SetProgramName(argv[0]); Py_Initialize(); PyImport_ImportModule("c"); return 0; } -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Tue May 18 11:50:46 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 18 May 2010 11:50:46 -0400 Subject: Getting System error with PyModule_AddIntConstant funtion In-Reply-To: <128ac13aa89.1830538159355529885.-4186638668702438058@gmail.com> References: <128ac13aa89.1830538159355529885.-4186638668702438058@gmail.com> Message-ID: <84A0B79D-BE5B-482A-A100-4E0B6EEF457F@semanchuk.com> On May 18, 2010, at 11:41 AM, MathanK wrote: > Following is a Python C api which runs properly without > PyModule_AddIntConstant function. > > > But when PyModule_AddIntConstant() function is used, getting the > following error when i call > c. path("test call"); > " SystemError: NULL result without error in PyObject_Call " Hi Mathan, You're not checking the return code from PyModule_Create(). Is it returning NULL? Also, there's a list specific to Python's C API. You might get a better response to your question there: http://mail.python.org/mailman/listinfo/capi-sig bye Philip > > > Python C api- c.c > > > int test(int a){ > return (2*a+a); > } > > > PyObject* dict = NULL; > > > static PyObject* path(PyObject* self, PyObject* args) { > char *cpath; > PyUnicodeObject *path; > PyUnicodeObject *test; > > > if (!PyArg_ParseTuple(args, "s", &path)) > return NULL; > cpath = (char *)path; > test = (PyUnicodeObject*)(cpath); > PyObject *testDict = PyDict_New(); > int testVal = PyDict_SetItem(testDict, (PyObject > *)PyUnicode_FromString(cpath), (PyObject > *)PyUnicode_FromString(cpath)); > > return Py_BuildValue("s", test); > } > static PyObject* c(PyObject* self, PyObject* args) { > > int a; > int result; > if(!PyArg_ParseTuple(args, "i", &a)) > return NULL; > result = test(a); > return Py_BuildValue("i", result); > > } > > > static PyMethodDef cmethods[] = { > {"c", c, METH_VARARGS, "watch"}, > {"path", path, METH_VARARGS, "test"}, > {NULL, NULL, 0, NULL}, > }; > > > static struct PyModuleDef c_Module = { > PyModuleDef_HEAD_INIT, > "c", > ( > "Interface." > ), > -1, > cmethods > }; > > > PyMODINIT_FUNC PyInit_c(void) { > > PyObject* obj = PyModule_Create(&c_Module); > long lon1 = 0; > PyModule_AddIntConstant(obj, "test", lon1); > > } > > > int main(int argc, wchar_t *argv[]) > { > PyImport_AppendInittab("c", PyInit_c); > Py_SetProgramName(argv[0]); > Py_Initialize(); > PyImport_ImportModule("c"); > return 0; > } > -- > http://mail.python.org/mailman/listinfo/python-list From robert.kern at gmail.com Tue May 18 12:03:53 2010 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 18 May 2010 11:03:53 -0500 Subject: Picking a license In-Reply-To: <216371.45903.qm@web58703.mail.re1.yahoo.com> References: <216371.45903.qm@web58703.mail.re1.yahoo.com> Message-ID: On 2010-05-16 09:25 , Ed Keith wrote: > > --- On Sat, 5/15/10, Lawrence D'Oliveiro wrote: > >> From: Lawrence D'Oliveiro >> Subject: Re: Picking a license >> To: python-list at python.org >> Date: Saturday, May 15, 2010, 11:09 PM >> In message, >> Ed Keith >> wrote: >> >>> But if my client give someone else a copy of the >> binary I gave them, they >>> are now in violation. >> >> Why would they be in violation? It seems to me a violation >> would only occur >> if someone asked them for the source, and they refused. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > No, the GPL makes it clear that the responsibly is on the distributor to either supply the source or written notice, Caveat venditor. The violation exists regardless of whether or not the recipient makes a request. No, one of the options for you is that you make the source available upon request. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From tjreedy at udel.edu Tue May 18 12:03:55 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 12:03:55 -0400 Subject: getting attributes and methods of class without creating object In-Reply-To: <84f6e33a-05da-4f3e-9d9f-532d7ce72d10@q13g2000vbm.googlegroups.com> References: <50a7abf5-bbe7-4c2d-af53-209be5822a6a@q13g2000vbm.googlegroups.com> <25494d5d-19cd-43f2-8483-07bcdfa71a27@e28g2000vbd.googlegroups.com> <84f6e33a-05da-4f3e-9d9f-532d7ce72d10@q13g2000vbm.googlegroups.com> Message-ID: On 5/18/2010 2:11 AM, shuvro wrote: >> to know the attributes of an instance of a class without >> actually creating that instance is very difficult. > Is it not possible with the existing python facilities (without adding > external libraries) ? To know what a function would do if you were to call it, without actually calling it, look at the function code with the dis (assembler) module. #3.1 >>> import dis >>> class C: def __init__(self, a): self.a = a >>> dis.dis(C.__init__) 2 0 LOAD_FAST 1 (a) 3 LOAD_FAST 0 (self) 6 STORE_ATTR 0 (a) 9 LOAD_CONST 0 (None) 12 RETURN_VALUE If you read the doc, or know assembler, you would see that the instance gets attribute a. Use dir(C) to find all the methods to disassemble. Terry Jan Reedy From bluesmanu at gmail.com Tue May 18 12:05:50 2010 From: bluesmanu at gmail.com (bluesmanu) Date: Tue, 18 May 2010 09:05:50 -0700 (PDT) Subject: Discover PyH Message-ID: Hi all, I would like to present my first python library : PyH. PyH is a concise and powerful module that lets you build your HTML pages like a GUI. Tags are objects that can be created, included and modified at any time during your script. Discover it at http://pyh.googlecode.com . You can file bug reports and feature requests at https://launchpad.net/pyh . Cheers, Emmanuel Turlay From debatem1 at gmail.com Tue May 18 12:07:31 2010 From: debatem1 at gmail.com (geremy condra) Date: Tue, 18 May 2010 09:07:31 -0700 Subject: Multi-Threading in Python In-Reply-To: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> Message-ID: On Tue, May 18, 2010 at 7:35 AM, Lou wrote: > Can anyone tell me how easy it is to do multi-threading in Python? > This has probably been brought up already, so if it has, thanks anyway > -- > http://mail.python.org/mailman/listinfo/python-list It's very easy, but it's probably best to use multiple processes to take advantage of multiple cores. Take a look at the threading and multiprocessing modules. Geremy Condra From tjreedy at udel.edu Tue May 18 12:11:57 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 12:11:57 -0400 Subject: Is there conversion method to convert pyunicodeobject to pybyteobject? In-Reply-To: <1289c71c8d7.-2177546074900212455.7511215933185914503@gmail.com> References: <1289c71c8d7.-2177546074900212455.7511215933185914503@gmail.com> Message-ID: On 5/15/2010 10:50 AM, MathanK wrote: This is the third time, at least, that you posted this, though the first time you asked a question. You have given no indication that you bothered to look in the manual before or between postings. > A variable whose data type is PyUnicodeObject is to be assigned to > varioable of PyBytesObject type > > example : > > PyUnicodeObject *p = ...whatever...; > function( (PyByteObject*p)); C casting is usually not conversion. It says "pretend that the data is another type, even though it is not." Only use it when you actually know what you are doing. > compiled and got a Bus Error. In Python, b = p.encode('utf-8') or whatever encoding you want. Look in the C-API manual for the CPython function that actually does this. From tjreedy at udel.edu Tue May 18 12:22:58 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 12:22:58 -0400 Subject: max time wait for a function In-Reply-To: <1274178263.232897.38.camel@paska> References: <4418c1f3-564f-48c1-85e3-48d5678a4f38@y21g2000vba.googlegroups.com> <1274178263.232897.38.camel@paska> Message-ID: On 5/18/2010 6:24 AM, Albert Hopkins wrote: > On Tue, 2010-05-18 at 02:45 -0700, pacopyc wrote: >> Hi, I've a question for you. I'd like to call a function and waiting >> its return value for a time max (30 sec). >> The function could not respond and then I must avoid to wait for >> infinite time. OS is Windows XP. >> Can you help me? >> >> Thank > > This is how I do it with a function decorator. I probably borrowed this > from someone and not attributed it. Anyway, it works on Linux, not sure > about Windows: > > def function_timeout(seconds): > """Function decorator to raise a timeout on a function call""" > import signal > class FunctionTimeOut(Exception): > pass > > def decorate(f): > def timeout(signum, frame): > raise FunctionTimeOut() > > def funct(*args, **kwargs): > old = signal.signal(signal.SIGALRM, timeout) > signal.alarm(seconds) from help(signal): alarm() -- cause SIGALRM after a specified time [Unix only] I do not know of any replacement in the stdlib, but one could check the code for multiprocessing to see how it does a timeout. Or check the pywin32 library http://pypi.python.org/pypi/pywin32/210 > try: > result = f(*args, **kwargs) > finally: > signal.signal(signal.SIGALRM, old) > signal.alarm(0) > return result > > return funct > > return decorate > > From tjreedy at udel.edu Tue May 18 12:25:38 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 12:25:38 -0400 Subject: Multi-Threading in Python In-Reply-To: References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com>, <1274193911.4085.13.camel@linux-yu4c.site> Message-ID: On 5/18/2010 11:29 AM, Sandy Ydnas wrote: > can help to find some examples of multiprocessing Multiprocessing is designed to be api-compatible with threading. Search the archives of this list/newsgroup for several examples. From awilliam at whitemice.org Tue May 18 12:45:37 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 18 May 2010 12:45:37 -0400 Subject: Multi-Threading in Python In-Reply-To: References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> ,<1274193911.4085.13.camel@linux-yu4c.site> Message-ID: <1274201137.7652.3.camel@linux-yu4c.site> On Tue, 2010-05-18 at 20:29 +0500, Sandy Ydnas wrote: > great > can help to find some examples of multiprocessing There is the reasonably good documentation at: I did a Multiprocessing presentation recently: And I use multiprocessing in my project; but less than previously as I now use AMQ for the IPC and multiprocessing only for the process management. But an entire project is quite a bit to pick through. > > Subject: Re: Multi-Threading in Python > > From: awilliam at whitemice.org > > To: python-list at python.org > > Date: Tue, 18 May 2010 10:45:11 -0400 > > > > On Tue, 2010-05-18 at 07:35 -0700, Lou wrote: > > > Can anyone tell me how easy it is to do multi-threading in Python? > > > > Very easy. Or as easy as in any other platform - and as easy to > screw > > up. Personally I prefer to use multiprocessing [which is a module > that > > 'simulates' threads using separate processes]. IMO, it is hard to > screw > > up as you don't get any shared-state for free. > > > > > This has probably been brought up already, so if it has, thanks > anyway > > > > -- > > Adam Tauno Williams LPIC-1, Novell CLA > > > > OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > ______________________________________________________________________ > Hotmail: Free, trusted and rich email service. Get it now. From e_d_k at yahoo.com Tue May 18 12:45:41 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 18 May 2010 09:45:41 -0700 (PDT) Subject: Picking a license In-Reply-To: Message-ID: <993000.4063.qm@web58707.mail.re1.yahoo.com> --- On Tue, 5/18/10, Robert Kern wrote: > From: Robert Kern > Subject: Re: Picking a license > To: python-list at python.org > Date: Tuesday, May 18, 2010, 12:03 PM > On 2010-05-16 09:25 , Ed Keith > wrote: > > > > --- On Sat, 5/15/10, Lawrence D'Oliveiro? > wrote: > > > >> From: Lawrence D'Oliveiro > >> Subject: Re: Picking a license > >> To: python-list at python.org > >> Date: Saturday, May 15, 2010, 11:09 PM > >> In message, > >> Ed Keith > >> wrote: > >> > >>> But if my client give someone else a copy of > the > >> binary I gave them, they > >>> are now in violation. > >> > >> Why would they be in violation? It seems to me a > violation > >> would only occur > >> if someone asked them for the source, and they > refused. > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > > > > No, the GPL makes it clear that the responsibly is on > the distributor to either supply the source or written > notice, Caveat venditor. The violation exists regardless of > whether or not the recipient makes a request. > > No, one of the options for you is that you make the source > available upon request. > But I am required to give written notice to that effect. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From cde3 at live.com Tue May 18 13:06:01 2010 From: cde3 at live.com (Sandy Ydnas) Date: Tue, 18 May 2010 22:06:01 +0500 Subject: Multi-Threading in Python In-Reply-To: <1274201137.7652.3.camel@linux-yu4c.site> References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com>, , <1274193911.4085.13.camel@linux-yu4c.site>, , <1274201137.7652.3.camel@linux-yu4c.site> Message-ID: good thanks a lot Sandy > Subject: RE: Multi-Threading in Python > From: awilliam at whitemice.org > To: python-list at python.org > Date: Tue, 18 May 2010 12:45:37 -0400 > > On Tue, 2010-05-18 at 20:29 +0500, Sandy Ydnas wrote: > > great > > can help to find some examples of multiprocessing > > There is the reasonably good documentation at: > > > I did a Multiprocessing presentation recently: > > > And I use multiprocessing in my project; but less than previously as I > now use AMQ for the IPC and multiprocessing only for the process > management. > > But an entire project is quite a bit to pick through. > > > > Subject: Re: Multi-Threading in Python > > > From: awilliam at whitemice.org > > > To: python-list at python.org > > > Date: Tue, 18 May 2010 10:45:11 -0400 > > > > > > On Tue, 2010-05-18 at 07:35 -0700, Lou wrote: > > > > Can anyone tell me how easy it is to do multi-threading in Python? > > > > > > Very easy. Or as easy as in any other platform - and as easy to > > screw > > > up. Personally I prefer to use multiprocessing [which is a module > > that > > > 'simulates' threads using separate processes]. IMO, it is hard to > > screw > > > up as you don't get any shared-state for free. > > > > > > > This has probably been brought up already, so if it has, thanks > > anyway > > > > > > -- > > > Adam Tauno Williams LPIC-1, Novell CLA > > > > > > OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > ______________________________________________________________________ > > Hotmail: Free, trusted and rich email service. Get it now. > > > -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Hotmail: Trusted email with powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue May 18 13:07:00 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 13:07:00 -0400 Subject: pickle unable to load collection In-Reply-To: References: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com> Message-ID: On 5/18/2010 3:10 AM, Peter Otten wrote: > Now simulate the effect of writing in text mode and reading in binary mode: > >>>> >>> garbled_data = data.replace("\n", "\r\n") >>>> >>> pickle.loads(garbled_data) > Traceback (most recent call last): ... > ImportError: No module named collections > >>>> >>> try: pickle.loads(garbled_data) > ... except ImportError as e: > ... e > ... > ImportError('No module named collections\r',) Nice catch, Peter. I filed a request that the message quote the name it cannot import, so that the OP would have seen the more informative ImportError: No module named 'collections\r' http://bugs.python.org/issue8754 Terry Jan Reedy From tjreedy at udel.edu Tue May 18 13:11:42 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 13:11:42 -0400 Subject: Regular expression In-Reply-To: <1274193656.13989.10.camel@jcdyer-laptop> References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> <1274193656.13989.10.camel@jcdyer-laptop> Message-ID: On 5/18/2010 10:40 AM, J. Cliff Dyer wrote: > Don't use regular expressions for that. > > s = '0x340x5A0x9B0xBA' > return '0x' + ''.join(s.split('0x')) or >>> '0x'+s[2:].replace('0x','') '0x345A9BBA' Take your pick, you should learn and understand both. > On Tue, 2010-05-18 at 06:48 -0700, Back9 wrote: >> Hi, >> >> I have a string like this: >> 0x340x5A0x9B0xBA >> I want to extract 0x from the string but the first one. >> >> How I can use re for this case? >> >> The string size will vary. >> >> TIA >> > > From pmaupin at gmail.com Tue May 18 13:22:30 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Tue, 18 May 2010 10:22:30 -0700 (PDT) Subject: Picking a license References: <216371.45903.qm@web58703.mail.re1.yahoo.com> Message-ID: On May 18, 11:03?am, Robert Kern wrote: > On 2010-05-16 09:25 , Ed Keith wrote: > > No, the GPL makes it clear that the responsibly is on the distributor to either supply the source or written notice, Caveat venditor. The violation exists regardless of whether or not the recipient makes a request. > > No, one of the options for you is that you make the source available upon request. Do you have a citation for that? My reading, of both GPL v2 section 3 and GPL v3 section 6, is that someone distributing GPL licensed object must do one of the following: - supply the source with the object - supply a written offer for source with the object - supply a copy of someone else's written offer for source with the object (only allowed sometimes) - Perhaps verbally communicate an offer (GPL v2 only, very liberal reading of 3c, but even then the communication must "accompany" the object distribution). - supply object by "offering access from a designated place" as long as you "offer equivalent access to the Corresponding Source in the same way through the same place" or "you maintain clear directions next to the object code saying where to find the Corresponding Source". That last one effectively has "written offer" defined in a slightly different way ("maintain clear directions"), and also might allow you to just have a pile of source DVDs adjacent to a pile of object CDs with no explicit written offer, but I honestly can't see how even that can be stretched to cover just handing somebody an object CD without even mentioning that source is available, and then only later giving them source if they explicitly ask for it. Sure, if you give somebody source after they ask for it, you have probably "cured" any violation, but I think the very act of handing someone an object CD without source or a written offer of source would put you in violation of the license at the time you give them the object CD. It may be that saying "oh, by the way, source code's available if you want it" would suffice in some cases under GPL v2, but it doesn't look like that would work at all for GPL v3. Regards, Pat From switch2mathan at gmail.com Tue May 18 13:31:06 2010 From: switch2mathan at gmail.com (MathanK) Date: Tue, 18 May 2010 05:31:06 -1200 Subject: Getting System error with PyModule_AddIntConstant funtion Message-ID: <128ac78068e.753885165126954409.7078058063089783964@gmail.com> I checked for Null also. But No change in the result. Still getting the system error. But when i m calling only c.c(5) function and not calling c.path("hi python c api") function, i m getting proper output without any system error. Any clue? Subject: Re: Getting System error with PyModule_AddIntConstant funtion From: Philip Semanchuk <philip at semanchuk.com> Date: Tue, 18 May 2010 11:50:46 -0400 To: "python-list (General)" <python-list at python.org> ------------------------- Contents ------------------------- On May 18, 2010, at 11:41 AM, MathanK wrote: > Following is a Python C api which runs properly without > PyModule_AddIntConstant function. > > > But when PyModule_AddIntConstant() function is used, getting the > following error when i call > c. path("test call"); > " SystemError: NULL result without error in PyObject_Call " Hi Mathan, You're not checking the return code from PyModule_Create(). Is it returning NULL? Also, there's a list specific to Python's C API. You might get a better response to your question there: http://mail.python.org/mailman/listinfo/capi-sig bye Philip > > > Python C api- c.c > > > int test(int a){ > return (2*a+a); > } > > > PyObject* dict = NULL; > > > static PyObject* path(PyObject* self, PyObject* args) { > char *cpath; > PyUnicodeObject *path; > PyUnicodeObject *test; > > > if (!PyArg_ParseTuple(args, "s", &amp;path)) > return NULL; > cpath = (char *)path; > test = (PyUnicodeObject*)(cpath); > PyObject *testDict = PyDict_New(); > int testVal = PyDict_SetItem(testDict, (PyObject > *)PyUnicode_FromString(cpath), (PyObject > *)PyUnicode_FromString(cpath)); > > return Py_BuildValue("s", test); > } > static PyObject* c(PyObject* self, PyObject* args) { > > int a; > int result; > if(!PyArg_ParseTuple(args, "i", &amp;a)) > return NULL; > result = test(a); > return Py_BuildValue("i", result); > > } > > > static PyMethodDef cmethods[] = { > {"c", c, METH_VARARGS, "watch"}, > {"path", path, METH_VARARGS, "test"}, > {NULL, NULL, 0, NULL}, > }; > > > static struct PyModuleDef c_Module = { > PyModuleDef_HEAD_INIT, > "c", > ( > "Interface." > ), > -1, > cmethods > }; > > > PyMODINIT_FUNC PyInit_c(void) { > > PyObject* obj = PyModule_Create(&amp;c_Module); > long lon1 = 0; > PyModule_AddIntConstant(obj, "test", lon1); > > } > > > int main(int argc, wchar_t *argv[]) > { > PyImport_AppendInittab("c", PyInit_c); > Py_SetProgramName(argv[0]); > Py_Initialize(); > PyImport_ImportModule("c"); > return 0; > } -------------- next part -------------- An HTML attachment was scrubbed... URL: From utente at esempio.net Tue May 18 13:31:42 2010 From: utente at esempio.net (superpollo) Date: Tue, 18 May 2010 19:31:42 +0200 Subject: recall function definition from shell Message-ID: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> >>> def myfun(): ... return "WOW" ... >>> myfun() 'WOW' >>> now, i would like to "list" the funcion definition, something like this: >>> myfun.somethinglikethis() def myfun(): return "WOW" >>> is there something like this around? bye From fasteliteprogrammer at gmail.com Tue May 18 14:18:49 2010 From: fasteliteprogrammer at gmail.com (packet) Date: Tue, 18 May 2010 13:18:49 -0500 Subject: upgrade python Message-ID: <4BF2DA09.7090208@gmail.com> Would it be safe to upgrade from python 2.6.4 to 2.6.5 without hurting the 2.6.4? From pmaupin at gmail.com Tue May 18 14:32:40 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Tue, 18 May 2010 11:32:40 -0700 (PDT) Subject: recall function definition from shell References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> Message-ID: <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> On May 18, 12:31?pm, superpollo wrote: > ?>>> def myfun(): > ... ? ? return "WOW" > ... > ?>>> myfun() > 'WOW' > ?>>> > > now, i would like to "list" the funcion definition, something like this: > > ?>>> myfun.somethinglikethis() > def myfun(): > ? ? ?return "WOW" > ?>>> > > is there something like this around? > > bye Sure, just give it a docstring and then you can call help on it: >>> def myfun(): ... ''' myfun returns "WOW" when called. ... This is just a Python __doc__ string ... ''' ... return "WOW" ... >>> help(myfun) Regards, Pat From utente at esempio.net Tue May 18 14:41:50 2010 From: utente at esempio.net (superpollo) Date: Tue, 18 May 2010 20:41:50 +0200 Subject: recall function definition from shell In-Reply-To: <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> Message-ID: <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> Patrick Maupin ha scritto: > On May 18, 12:31 pm, superpollo wrote: >> >>> def myfun(): >> ... return "WOW" >> ... >> >>> myfun() >> 'WOW' >> >>> >> >> now, i would like to "list" the funcion definition, something like this: >> >> >>> myfun.somethinglikethis() >> def myfun(): >> return "WOW" >> >>> >> >> is there something like this around? >> >> bye > > Sure, just give it a docstring and then you can call help on it: > >>>> def myfun(): > ... ''' myfun returns "WOW" when called. > ... This is just a Python __doc__ string > ... ''' > ... return "WOW" > ... >>>> help(myfun) > > Regards, > Pat mmm... thanks but not quite what i meant :-( bye From pmaupin at gmail.com Tue May 18 14:50:32 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Tue, 18 May 2010 11:50:32 -0700 (PDT) Subject: recall function definition from shell References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> Message-ID: <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> On May 18, 1:41?pm, superpollo wrote: > Patrick Maupin ha scritto: > > > > > On May 18, 12:31 pm, superpollo wrote: > >> ?>>> def myfun(): > >> ... ? ? return "WOW" > >> ... > >> ?>>> myfun() > >> 'WOW' > > >> now, i would like to "list" the funcion definition, something like this: > > >> ?>>> myfun.somethinglikethis() > >> def myfun(): > >> ? ? ?return "WOW" > > >> is there something like this around? > > >> bye > > > Sure, just give it a docstring and then you can call help on it: > > >>>> def myfun(): > > ... ? ? ''' myfun returns "WOW" when called. > > ... ? ? ? ? This is just a Python __doc__ string > > ... ? ? ''' > > ... ? ? return "WOW" > > ... > >>>> help(myfun) > > > Regards, > > Pat > > mmm... thanks but not quite what i meant :-( > > bye Well, I don't think Python remembers exactly how you typed it in, but you can always ask Python for what it remembers about the function: >>> def myfun(): ... return "WOW" ... >>> import dis >>> dis.dis(myfun) 2 0 LOAD_CONST 1 ('WOW') 3 RETURN_VALUE The inspect module is useful, as well. But AFAIK Python doesn't "remember" the source code for stuff you typed in. (For functions in imported modules, there is sufficient information remembered for tracebacks to allow you to print out the lines of a function.) Regards, Pat From utente at esempio.net Tue May 18 14:55:17 2010 From: utente at esempio.net (superpollo) Date: Tue, 18 May 2010 20:55:17 +0200 Subject: recall function definition from shell In-Reply-To: <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> Message-ID: <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Patrick Maupin ha scritto: > On May 18, 1:41 pm, superpollo wrote: >> Patrick Maupin ha scritto: >> >> >> >>> On May 18, 12:31 pm, superpollo wrote: >>>> >>> def myfun(): >>>> ... return "WOW" >>>> ... >>>> >>> myfun() >>>> 'WOW' >>>> now, i would like to "list" the funcion definition, something like this: >>>> >>> myfun.somethinglikethis() >>>> def myfun(): >>>> return "WOW" >>>> is there something like this around? >>>> bye >>> Sure, just give it a docstring and then you can call help on it: >>>>>> def myfun(): >>> ... ''' myfun returns "WOW" when called. >>> ... This is just a Python __doc__ string >>> ... ''' >>> ... return "WOW" >>> ... >>>>>> help(myfun) >>> Regards, >>> Pat >> mmm... thanks but not quite what i meant :-( >> >> bye > > Well, I don't think Python remembers exactly how you typed it in yes python does not, but maybe the *shell* does, or so i thought. i just wanted to dump the code for the function in a file, after i tested in the shell... From __peter__ at web.de Tue May 18 15:08:33 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 May 2010 21:08:33 +0200 Subject: recall function definition from shell References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Message-ID: superpollo wrote: > Patrick Maupin ha scritto: >> On May 18, 1:41 pm, superpollo wrote: >>> Patrick Maupin ha scritto: >>> >>> >>> >>>> On May 18, 12:31 pm, superpollo wrote: >>>>> >>> def myfun(): >>>>> ... return "WOW" >>>>> ... >>>>> >>> myfun() >>>>> 'WOW' >>>>> now, i would like to "list" the funcion definition, something like >>>>> this: >>>>> >>> myfun.somethinglikethis() >>>>> def myfun(): >>>>> return "WOW" >>>>> is there something like this around? >>>>> bye >>>> Sure, just give it a docstring and then you can call help on it: >>>>>>> def myfun(): >>>> ... ''' myfun returns "WOW" when called. >>>> ... This is just a Python __doc__ string >>>> ... ''' >>>> ... return "WOW" >>>> ... >>>>>>> help(myfun) >>>> Regards, >>>> Pat >>> mmm... thanks but not quite what i meant :-( >>> >>> bye >> >> Well, I don't think Python remembers exactly how you typed it in > > yes python does not, but maybe the *shell* does, or so i thought. i just > wanted to dump the code for the function in a file, after i tested in > the shell... You could try ipython: $ ipython Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: def f(): ...: return 42 ...: In [2]: f() Out[2]: 42 In [3]: %save tmp.py 1 The following commands were written to file `tmp.py`: def f(): return 42 In [4]: Do you really want to exit ([y]/n)? $ cat tmp.py def f(): return 42 $ Peter From __peter__ at web.de Tue May 18 15:12:05 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 May 2010 21:12:05 +0200 Subject: pickle unable to load collection References: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com> Message-ID: Terry Reedy wrote: > Nice catch, Peter. I filed a request that the message quote the name it > cannot import, so that the OP would have seen the more informative > > ImportError: No module named 'collections\r' > > http://bugs.python.org/issue8754 Good idea; thank you for taking the initiative. Peter From utente at esempio.net Tue May 18 15:13:50 2010 From: utente at esempio.net (superpollo) Date: Tue, 18 May 2010 21:13:50 +0200 Subject: recall function definition from shell In-Reply-To: References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Message-ID: <4bf2e6ef$0$18992$4fafbaef@reader5.news.tin.it> Peter Otten ha scritto: > superpollo wrote: > >> Patrick Maupin ha scritto: >>> On May 18, 1:41 pm, superpollo wrote: >>>> Patrick Maupin ha scritto: >>>> >>>> >>>> >>>>> On May 18, 12:31 pm, superpollo wrote: >>>>>> >>> def myfun(): >>>>>> ... return "WOW" >>>>>> ... >>>>>> >>> myfun() >>>>>> 'WOW' >>>>>> now, i would like to "list" the funcion definition, something like >>>>>> this: >>>>>> >>> myfun.somethinglikethis() >>>>>> def myfun(): >>>>>> return "WOW" >>>>>> is there something like this around? >>>>>> bye >>>>> Sure, just give it a docstring and then you can call help on it: >>>>>>>> def myfun(): >>>>> ... ''' myfun returns "WOW" when called. >>>>> ... This is just a Python __doc__ string >>>>> ... ''' >>>>> ... return "WOW" >>>>> ... >>>>>>>> help(myfun) >>>>> Regards, >>>>> Pat >>>> mmm... thanks but not quite what i meant :-( >>>> >>>> bye >>> Well, I don't think Python remembers exactly how you typed it in >> yes python does not, but maybe the *shell* does, or so i thought. i just >> wanted to dump the code for the function in a file, after i tested in >> the shell... > > You could try ipython: > > $ ipython > Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) > Type "copyright", "credits" or "license" for more information. > > IPython 0.10 -- An enhanced Interactive Python. > ? -> Introduction and overview of IPython's features. > %quickref -> Quick reference. > help -> Python's own help system. > object? -> Details about 'object'. ?object also works, ?? prints more. > > In [1]: def f(): > ...: return 42 > ...: > > In [2]: f() > Out[2]: 42 > > In [3]: %save tmp.py 1 > The following commands were written to file `tmp.py`: > def f(): > return 42 > > > In [4]: > Do you really want to exit ([y]/n)? > $ cat tmp.py > def f(): > return 42 > $ > > Peter hey great! thanks a lot! best regards From lists at necoro.eu Tue May 18 15:21:18 2010 From: lists at necoro.eu (=?UTF-8?B?UmVuw6kgJ05lY29ybycgTmV1bWFubg==?=) Date: Tue, 18 May 2010 21:21:18 +0200 Subject: recall function definition from shell In-Reply-To: <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Message-ID: <4BF2E8AE.2020208@necoro.eu> Am 18.05.2010 20:55, schrieb superpollo: > > yes python does not, but maybe the *shell* does, or so i thought. i just > wanted to dump the code for the function in a file, after i tested in > the shell... You might want to have a look at the IPython shell [1]. I personally do not use it myself, but I thought to remember that it had some feature like this (perhaps not dump _one function_, but all the input, which you then only need to cleanup). A quick glance revealed f.ex. the history and edit functionality [2] -- a bit more digging might really show up the thing you are looking for. - Ren? [1] http://ipython.scipy.org/ [2] http://ipython.scipy.org/doc/manual/html/interactive/tutorial.html#source-code-handling-tips -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From ethan at stoneleaf.us Tue May 18 15:26:47 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 12:26:47 -0700 Subject: recall function definition from shell In-Reply-To: <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Message-ID: <4BF2E9F7.6040806@stoneleaf.us> superpollo wrote: > Patrick Maupin ha scritto: >> On May 18, 1:41 pm, superpollo wrote: >>> Patrick Maupin ha scritto: >>> >>> >>> >>>> On May 18, 12:31 pm, superpollo wrote: >>>>> >>> def myfun(): >>>>> ... return "WOW" >>>>> ... >>>>> >>> myfun() >>>>> 'WOW' >>>>> now, i would like to "list" the funcion definition, something like >>>>> this: >>>>> >>> myfun.somethinglikethis() >>>>> def myfun(): >>>>> return "WOW" >>>>> is there something like this around? >>>>> bye >>>> Sure, just give it a docstring and then you can call help on it: >>>>>>> def myfun(): >>>> ... ''' myfun returns "WOW" when called. >>>> ... This is just a Python __doc__ string >>>> ... ''' >>>> ... return "WOW" >>>> ... >>>>>>> help(myfun) >>>> Regards, >>>> Pat >>> mmm... thanks but not quite what i meant :-( >>> >>> bye >> >> Well, I don't think Python remembers exactly how you typed it in > > yes python does not, but maybe the *shell* does, or so i thought. i just > wanted to dump the code for the function in a file, after i tested in > the shell... Take a look at ipython -- it has many enhancements: ipython.scipy.org ~Ethan~ From ethan at stoneleaf.us Tue May 18 15:28:25 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 12:28:25 -0700 Subject: Picking a license In-Reply-To: <87fx1qji9t.fsf@benfinney.id.au> References: <87r5ldbw3k.fsf@benfinney.id.au> <87fx1qji9t.fsf@benfinney.id.au> Message-ID: <4BF2EA59.6090209@stoneleaf.us> Ben Finney wrote: > aahz at pythoncraft.com (Aahz) writes: > >> Ben Finney wrote: >>> [It is impractical to] sell free software like selling loaves of >>> bread, but that's a much more limited case and a far cry from your >>> claim [that it's impractical to sell free software]. Selling free >>> software is quite practical and a good way to fund development of >>> software that otherwise wouldn't be written as free software. >> From my POV, if you're not selling COTS, you're really selling support >> and consulting services, because that's what keeps your competitors >> from just picking up your software and reselling it for cheaper. BTDT. > > This thread has revealed some staggering gulfs in concepts as held by > different people. For example, I don't think it's at all germane to the > definition of ?sell FOO? that ?your competitors can pick up the FOO and > resell it cheaper?. Whether they can or not, that doesn't change that > fact that one is selling FOO. > > Moreover, I don't try to prevent my competitors from reselling the > software (so long as they don't misrepresent who holds copyright or > further restrict the terms). That's part and parcel of the freedoms in > the software. Indeed, I find that helps the customers trust me more and > tend to come back when they want something else new; and my customers > are free to show others the solutions I've already implemented. > > Thus is an ongoing business relationship crafted, including return > customers and referrals for new work. It really is practical to sell > free software. > This doesn't make sense to me, but I'm willing to learn -- how do you do this in practice? Are you really selling the software, or rather selling things like setup, support, new code (or time to code), etc? ~Ethan~ From grenander at gmail.com Tue May 18 16:15:13 2010 From: grenander at gmail.com (Art) Date: Tue, 18 May 2010 13:15:13 -0700 (PDT) Subject: setting variables in pdb Message-ID: <8596b692-2e9f-452d-99b0-ba55ec592936@h37g2000pra.googlegroups.com> If I am in Pdb, I would like to set a temporary variable, for example: (Pdb) r = 1 The 'r' gets interpreted as 'return' by Pdb. Is there a Pdb instruction that guarantees the intended effect, like: (Pdb) let r = 1 I can usually avoid using such variable names, but if I am changing the value of a local variable, it is convenient to be able to make sure that trying to change that variable doesn't unintentionally call a Pdb routine. Thanks, Art. From vincent at vincentdavis.net Tue May 18 16:17:57 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 14:17:57 -0600 Subject: Is this an ok thing to do in a class In-Reply-To: <4bf2a930$0$14553$426a74cc@news.free.fr> References: <4bf2a930$0$14553$426a74cc@news.free.fr> Message-ID: Thanks for the feed back Vincent On Tue, May 18, 2010 at 8:50 AM, Bruno Desthuilliers wrote: > Simon Brunning a ?crit : > >> On 18 May 2010 06:21:32 UTC+1, Vincent Davis >> wrote: >> >>> Just wondering if there is a problem with mixing a dictionary into a >>> class like this. Everything seems to work as I would expect. >>> >> >> No problem at all AFAIC. >> > > OP didn't show up on c.l.py, so too bad you snipped the relevant code > snippet... > > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjposner at optimum.net Tue May 18 16:32:15 2010 From: jjposner at optimum.net (John Posner) Date: Tue, 18 May 2010 16:32:15 -0400 Subject: setting variables in pdb In-Reply-To: <8596b692-2e9f-452d-99b0-ba55ec592936@h37g2000pra.googlegroups.com> References: <8596b692-2e9f-452d-99b0-ba55ec592936@h37g2000pra.googlegroups.com> Message-ID: <4BF2F94F.9050604@optimum.net> On 5/18/2010 4:15 PM, Art wrote: > If I am in Pdb, I would like to set a temporary variable, for example: > > (Pdb) r = 1 > > The 'r' gets interpreted as 'return' by Pdb. > > Is there a Pdb instruction that guarantees the intended effect, like: > > (Pdb) let r = 1 > > I can usually avoid using such variable names, but if I am changing > the value of a local variable, it is convenient to be able to make > sure that trying to change that variable doesn't unintentionally call > a Pdb routine. Try setting *two* values at the interactive prompt: foo, r = 0, 3456 Variable "r" now has the value 3456. HTH, John From duncan.booth at invalid.invalid Tue May 18 16:33:27 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 May 2010 20:33:27 GMT Subject: setting variables in pdb References: <8596b692-2e9f-452d-99b0-ba55ec592936@h37g2000pra.googlegroups.com> Message-ID: Art wrote: > If I am in Pdb, I would like to set a temporary variable, for example: > > (Pdb) r = 1 > > The 'r' gets interpreted as 'return' by Pdb. > > Is there a Pdb instruction that guarantees the intended effect, like: > > (Pdb) let r = 1 (Pdb) exec "r=1" From vincent at vincentdavis.net Tue May 18 16:39:13 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 14:39:13 -0600 Subject: how to cause a request for a missing class attribute cause its calculation Message-ID: Lets say I have class foo(object): def __init__(self, x, y): self.x=x self.y=y def xplusy(self): self.xy = x+y inst = foo(1,2) inst.xy # no value, but I what this to cause the calculation of inst.xy I don't what to have self.xy calculated before it is called. Thanks *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Tue May 18 16:41:59 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 13:41:59 -0700 Subject: Is this an ok thing to do in a class In-Reply-To: References: Message-ID: <4BF2FB97.6040205@stoneleaf.us> Vincent Davis wrote: > Just wondering if there is a problem with mixing a dictionary into a > class like this. Everything seems to work as I would expect. > > class foo(object): > def __init__(self, x): > self.letter = dict(a=1,b=2,c=3) > self.A=self.letter['a'] > self.x=self.letter[x] > > >>> afoo = foo('b') > >>> afoo.x > 2 > >>> afoo.A > 1 > >>> afoo.letter['a'] > 1 > >>> afoo.letter.items() > [('a', 1), ('c', 3), ('b', 2)] Do you expect afoo.letter[x] to always be afoo.x? Because they aren't: >>> afoo.A = 9 >>> afoo.letter['a'] 1 ~Ethan~ From vincent at vincentdavis.net Tue May 18 16:49:30 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 14:49:30 -0600 Subject: Is this an ok thing to do in a class In-Reply-To: <4BF2FB97.6040205@stoneleaf.us> References: <4BF2FB97.6040205@stoneleaf.us> Message-ID: On Tue, May 18, 2010 at 2:41 PM, Ethan Furman wrote: > > Do you expect afoo.letter[x] to always be afoo.x? Because they aren't: > > >>> afoo.A = 9 > >>> afoo.letter['a'] > 1 > What you are pointing out is that the assignment is not reversed . But that does make me thing of something I had not. >>> afoo.letter['a'] = 345 >>> afoo.A 1 Thats kinda a bummer, whats a good way to make sure affo.A gets updated? Vincent > > ~Ethan~ > > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue May 18 16:54:30 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 May 2010 13:54:30 -0700 Subject: how to cause a request for a missing class attribute cause its calculation In-Reply-To: References: Message-ID: On Tue, May 18, 2010 at 1:39 PM, Vincent Davis wrote: > > Lets say I have > class foo(object): > ?? ?def __init__(self, x, y): > ?? ? ? ?self.x=x > ?? ? ? ?self.y=y > ?? ?def xplusy(self): > ?? ? ? ?self.xy = x+y > inst = foo(1,2) > inst.xy ? # no value, but I what this to cause the calculation of inst.xy > I don't what to have self.xy calculated before it is called. class Foo(object): def __init__(self, x, y): self.x = x self.y = y @property def xy(self): '''Will calculate x+y every time''' return self.x + self.y Or if Foo is immutable and you wish to cache x+y: class Foo(object): def __init__(self, x, y): self.x = x self.y = y self._xy = None @property def xy(self): if self._xy is None: self._xy = self.x + self.y return self._xy Suggested reading: http://docs.python.org/library/functions.html#property Cheers, Chris -- http://blog.rebertia.com From ethan at stoneleaf.us Tue May 18 17:15:04 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 14:15:04 -0700 Subject: Is this an ok thing to do in a class In-Reply-To: References: <4BF2FB97.6040205@stoneleaf.us> Message-ID: <4BF30358.1010005@stoneleaf.us> Vincent Davis wrote: > On Tue, May 18, 2010 at 2:41 PM, Ethan Furman > wrote: > > Do you expect afoo.letter[x] to always be afoo.x? Because they aren't: > > >>> afoo.A = 9 > >>> afoo.letter['a'] > 1 > > > What you are pointing out is that the assignment is not reversed . But > that does make me thing of something I had not. > > >>> afoo.letter['a'] = 345 > >>> afoo.A > 1 > > Thats kinda a bummer, whats a good way to make sure affo.A gets updated? It's possible, and not too tough, but... why do you need it done that way? Keeping redundant information seems like extra work with no advantage. ~Ethan~ From ethan at stoneleaf.us Tue May 18 17:19:39 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 14:19:39 -0700 Subject: how to cause a request for a missing class attribute cause its calculation In-Reply-To: References: Message-ID: <4BF3046B.7060100@stoneleaf.us> Vincent Davis wrote: > Lets say I have > class foo(object): > def __init__(self, x, y): > self.x=x > self.y=y > def xplusy(self): > self.xy = x+y ^ this needs to be self.x + self.y > > inst = foo(1,2) > inst.xy # no value, but I what this to cause the calculation of inst.xy > > I don't what to have self.xy calculated before it is called. My current favorite method: def __getattr__(self, name): if name != 'xy': raise AttributeError("%s not found" % name) self.xy = self.x + self.y return self.xy ~Ethan~ From vincent at vincentdavis.net Tue May 18 17:36:49 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 15:36:49 -0600 Subject: Is this an ok thing to do in a class In-Reply-To: <4BF30358.1010005@stoneleaf.us> References: <4BF2FB97.6040205@stoneleaf.us> <4BF30358.1010005@stoneleaf.us> Message-ID: On Tue, May 18, 2010 at 3:15 PM, Ethan Furman wrote: > Vincent Davis wrote: > >> >> What you are pointing out is that the assignment is not reversed . But >> that does make me thing of something I had not. >> >> >>> afoo.letter['a'] = 345 >> >>> afoo.A >> 1 >> >> Thats kinda a bummer, whats a good way to make sure afoo.A gets updated? >> > > It's possible, and not too tough, but... why do you need it done that way? > Keeping redundant information seems like extra work with no advantage. > > Not sure I do, basicly I have a long list of values that could be calculated from data. Some may take some time depending on the amount of data. I don't what to calculate them all if not needed but I don't what the user to need to know which are and which are not. But maybe @property is what I need to be looking at, see my other post on the list. Thanks Vincent > ~Ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Tue May 18 17:51:33 2010 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 18 May 2010 17:51:33 -0400 Subject: another question about classes and subclassing Message-ID: Hi again all, More about classes. I am still looking into my battleship game, and I will have several different craft. All craft have common attribs (position, alive, and so on) but each craft may be a surface ship, submarine, or airplane. All three are craft, but a submarine can be submerged or not, which does not apply to a surface ship or a plane, while a plane can be airborne or not, which is not applicable to the other two. Is there any advantage to creating a craft class: class craft(): #has attribs common to any and all craft #end class then doing something like: class submarine(craft): #sub-specific attribs #end class How would I create a submarine, and then get at the craft-level attribs? Come to think of it, how would I pass anything to the craft constructor (position and alive, for example) when creating a new submarine object? Am I even doing this right to make submarine a subclass of craft? Thanks. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From astan.chee at al.com.au Tue May 18 18:05:05 2010 From: astan.chee at al.com.au (Astan Chee) Date: Wed, 19 May 2010 08:05:05 +1000 Subject: sound effects in python Message-ID: <4BF30F11.1050402@al.com.au> Hi, I have a sound file (e.g. .wav; .mp3, etc) in python that I'd like to modify (e.g. change tempo, pitch, add echo, amplify, etc). Any recommendation on how I can achieve this in python independent of platform? Thanks From ethan at stoneleaf.us Tue May 18 18:26:57 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 15:26:57 -0700 Subject: how to cause a request for a missing class attribute cause its calculation In-Reply-To: <4BF3046B.7060100@stoneleaf.us> References: <4BF3046B.7060100@stoneleaf.us> Message-ID: <4BF31431.8030809@stoneleaf.us> Ethan Furman wrote: > Vincent Davis wrote: >> Lets say I have class foo(object): >> def __init__(self, x, y): >> self.x=x >> self.y=y >> def xplusy(self): >> self.xy = x+y > ^ this needs to be self.x + self.y >> >> inst = foo(1,2) >> inst.xy # no value, but I what this to cause the calculation of inst.xy >> >> I don't what to have self.xy calculated before it is called. > > My current favorite method: > > def __getattr__(self, name): > if name != 'xy': > raise AttributeError("%s not found" % name) > self.xy = self.x + self.y > return self.xy > > > ~Ethan~ Chris' reply is more on-point, I think -- I was thinking of attributes that are only calculated once. *sigh* ~Ethan~ From vincent at vincentdavis.net Tue May 18 19:06:25 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 17:06:25 -0600 Subject: sound effects in python In-Reply-To: <4BF30F11.1050402@al.com.au> References: <4BF30F11.1050402@al.com.au> Message-ID: There was a talk at pycon about this. Sounded interecting but I don't know much about it. http://us.pycon.org/2010/conference/schedule/event/136/ Vincent On Tue, May 18, 2010 at 4:05 PM, Astan Chee wrote: > Hi, > I have a sound file (e.g. .wav; .mp3, etc) in python that I'd like to > modify (e.g. change tempo, pitch, add echo, amplify, etc). > Any recommendation on how I can achieve this in python independent of > platform? > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Tue May 18 19:27:08 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 18 May 2010 18:27:08 -0500 Subject: Access to comp.lang.python In-Reply-To: References: Message-ID: <4BF3224C.4060707@tim.thechases.com> On 05/15/2010 05:34 PM, cjw wrote: > It seems that messages are coming from a number of sources, such as > gmane and google groups. > > The problem is that many messages seem to get unlinked from their threads. > > I use Thunderbird 3.0.5 and wonder whether the problem lies with the > merge process, the server or my reader. While others have told you about using gmane or other sources (direct email, etc), I haven't seen anything fly by regarding the "unlinked from their threads" portion of your question. Thunderbird 2.0 -> 3.0 changed the default value for mail.strict_threading from False to True. Pulling up the config editor (essentially the about:config, buried in the options->advanced stuff, I think; or perhaps I have the "about:config" plugin to do that) allows you to toggle this value back to "True". This setting controls whether threads are defined *only* by the mail header (strict=True), or whether TB also tries to guess based on the Subject header (strict=False). Toggle it (and perhaps restart TB?) and see if that helps rectify the threading. There are a lot of folks here on c.l.p that use broken newsreaders that don't correctly set news/threading headers. -tkc From robin.garen at gmail.com Tue May 18 20:27:39 2010 From: robin.garen at gmail.com (technocake) Date: Tue, 18 May 2010 17:27:39 -0700 (PDT) Subject: sound effects in python References: Message-ID: <05a04ed0-3315-48fe-80f4-a2665c7a0b65@o39g2000vbd.googlegroups.com> On 19 Mai, 00:05, Astan Chee wrote: > Hi, > I have a sound file (e.g. .wav; .mp3, etc) in python that I'd like to > modify (e.g. change tempo, pitch, add echo, amplify, etc). > Any recommendation on how I can achieve this in python independent of > platform? > Thanks You could have a look on PyAudio : http://people.csail.mit.edu/hubert/pyaudio/ I have not any experience with it, so I can only point you to it for now. Hope you find it useful technocake From davea at ieee.org Tue May 18 21:31:11 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 18 May 2010 21:31:11 -0400 Subject: another question about classes and subclassing In-Reply-To: References: Message-ID: <4BF33F5F.2030207@ieee.org> Alex Hall wrote: > Hi again all, > More about classes. I am still looking into my battleship game, and I > will have several different craft. All craft have common attribs > (position, alive, and so on) but each craft may be a surface ship, > submarine, or airplane. All three are craft, but a submarine can be > submerged or not, which does not apply to a surface ship or a plane, > while a plane can be airborne or not, which is not applicable to the > other two. Is there any advantage to creating a craft class: > > class craft(): > #has attribs common to any and all craft > #end class > > then doing something like: > > class submarine(craft): > #sub-specific attribs > #end class > > How would I create a submarine, and then get at the craft-level > attribs? Come to think of it, how would I pass anything to the craft > constructor (position and alive, for example) when creating a new > submarine object? Am I even doing this right to make submarine a > subclass of craft? Thanks. > > Inside the __init__() method of Submarine, simply call the __init__() method of Craft, with appropriate parameters. As for getting at the attributes of the Craft parent class, from a Submarine object, you simply reference the attributes as always. If they're not overridden in Submarine, they'll be searched for in Craft. DaveA From mehgcap at gmail.com Tue May 18 21:41:31 2010 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 18 May 2010 21:41:31 -0400 Subject: another question about classes and subclassing In-Reply-To: <4BF33F5F.2030207@ieee.org> References: <4BF33F5F.2030207@ieee.org> Message-ID: Okay, that makes sense. So by calling submarine(craft) I am bringing in all of craft's attribs (subclassing)? Or does calling craft's __init__ method do that instead? Is there an advantage to doing it this way, rather than just making separate classes for everything, except for my own sense of organization; speed, memory usage, less coding? Thanks. On 5/18/10, Dave Angel wrote: > Alex Hall wrote: >> Hi again all, >> More about classes. I am still looking into my battleship game, and I >> will have several different craft. All craft have common attribs >> (position, alive, and so on) but each craft may be a surface ship, >> submarine, or airplane. All three are craft, but a submarine can be >> submerged or not, which does not apply to a surface ship or a plane, >> while a plane can be airborne or not, which is not applicable to the >> other two. Is there any advantage to creating a craft class: >> >> class craft(): >> #has attribs common to any and all craft >> #end class >> >> then doing something like: >> >> class submarine(craft): >> #sub-specific attribs >> #end class >> >> How would I create a submarine, and then get at the craft-level >> attribs? Come to think of it, how would I pass anything to the craft >> constructor (position and alive, for example) when creating a new >> submarine object? Am I even doing this right to make submarine a >> subclass of craft? Thanks. >> >> > Inside the __init__() method of Submarine, simply call the __init__() > method of Craft, with appropriate parameters. > > As for getting at the attributes of the Craft parent class, from a > Submarine object, you simply reference the attributes as always. If > they're not overridden in Submarine, they'll be searched for in Craft. > > > DaveA > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From aahz at pythoncraft.com Tue May 18 21:47:41 2010 From: aahz at pythoncraft.com (Aahz) Date: 18 May 2010 18:47:41 -0700 Subject: upgrade python References: Message-ID: In article , packet wrote: > >Would it be safe to upgrade from python 2.6.4 to 2.6.5 without hurting >the 2.6.4? Define "hurting". Generally speaking, it's always safe to upgrade a point release, but you should replace the previous version. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From davea at ieee.org Tue May 18 22:01:07 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 18 May 2010 22:01:07 -0400 Subject: another question about classes and subclassing In-Reply-To: References: <4BF33F5F.2030207@ieee.org> Message-ID: <4BF34663.2000704@ieee.org> Alex Hall wrote: > Okay, that makes sense. So by calling submarine(craft) I am bringing > in all of craft's attribs (subclassing)? Or does calling craft's > __init__ method do that instead? Is there an advantage to doing it > this way, rather than just making separate classes for everything, > except for my own sense of organization; speed, memory usage, less > coding? Thanks. > > >> You put your response at the wrong end of the message. It should *follow* whatever you're quoting. So in your case, I'm forced to delete everything just to make the order correct. You don't call Submarine(Craft), as it's not a function. That's a class definition. You instantiate a Submarine by something like: sub = Submarine(arg1, arg2, arg3) And those three arguments are then passed to the __init__() method of Submarine. It may choose to call the __init__() method of Craft, in the method. There are lots of advantages of using inheritance. First, any common code only has to be entered once, so you'll only have to fix it once when you find mistakes, or decide to redesign. Second, it's easier to read - very important. It may take less memory, but probably not. And it's not likely to have any speed impact. Craft instances don't have any instance data attributes if nobody assigns them. And that's normally the job of __init__(). So naturally, you need to call it from the Submarine class. Incidentally, convention is to capitalize class names. DaveA From gobnat at optusnet.com.au Tue May 18 22:05:14 2010 From: gobnat at optusnet.com.au (gobnat) Date: Wed, 19 May 2010 12:05:14 +1000 Subject: Pointers on packaging python programs for installation on multiple platforms? Message-ID: <4BF3475A.80304@optusnet.com.au> Hi all I am trying to release my first python program. I would like to be able to create a download which will automatically do stuff like add menu items (eg for KDE, GNOME and Windows). Is there anywhere which explains how to do this? Thanks in advance Brendan From mehgcap at gmail.com Tue May 18 22:12:37 2010 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 18 May 2010 22:12:37 -0400 Subject: another question about classes and subclassing In-Reply-To: <4BF34663.2000704@ieee.org> References: <4BF33F5F.2030207@ieee.org> <4BF34663.2000704@ieee.org> Message-ID: On 5/18/10, Dave Angel wrote: > Alex Hall wrote: >> Okay, that makes sense. So by calling submarine(craft) I am bringing >> in all of craft's attribs (subclassing)? Or does calling craft's >> __init__ method do that instead? Is there an advantage to doing it >> this way, rather than just making separate classes for everything, >> except for my own sense of organization; speed, memory usage, less >> coding? Thanks. >> >> >>> > You put your response at the wrong end of the message. It should > *follow* whatever you're quoting. So in your case, I'm forced to delete > everything just to make the order correct. Sorry, top-posting is a habit on some other lists I am on, and sometimes it follows me to lists where in-line posting is the way to do it. > > You don't call Submarine(Craft), as it's not a function. That's a class > definition. You instantiate a Submarine by something like: > > sub = Submarine(arg1, arg2, arg3) > > And those three arguments are then passed to the __init__() method of > Submarine. It may choose to call the __init__() method of Craft, in the > method. So that is the only way of making submarine inherit craft, by calling craft's __init__ inside submarine's __init__. Okay, I think I get it. > > There are lots of advantages of using inheritance. First, any common > code only has to be entered once, so you'll only have to fix it once > when you find mistakes, or decide to redesign. Very true. > Second, it's easier to > read - very important. It may take less memory, but probably not. And > it's not likely to have any speed impact. > > Craft instances don't have any instance data attributes if nobody > assigns them. And that's normally the job of __init__(). So naturally, > you need to call it from the Submarine class. Right, I think I have it now... At least I hope I do! > > Incidentally, convention is to capitalize class names. Yes, I had planned on doing that in my project, but I got caught up in just making it work and forgot to do so. Thanks for the reminder. > > DaveA > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From tjreedy at udel.edu Tue May 18 22:28:40 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 22:28:40 -0400 Subject: Access to comp.lang.python In-Reply-To: <4BF3224C.4060707@tim.thechases.com> References: <4BF3224C.4060707@tim.thechases.com> Message-ID: On 5/18/2010 7:27 PM, Tim Chase wrote: > On 05/15/2010 05:34 PM, cjw wrote: >> It seems that messages are coming from a number of sources, such as >> gmane and google groups. >> >> The problem is that many messages seem to get unlinked from their >> threads. >> >> I use Thunderbird 3.0.5 and wonder whether the problem lies with the >> merge process, the server or my reader. > > While others have told you about using gmane or other sources (direct > email, etc), I haven't seen anything fly by regarding the "unlinked from > their threads" portion of your question. Thunderbird 2.0 -> 3.0 changed > the default value for mail.strict_threading from False to True. Pulling > up the config editor (essentially the about:config, buried in the > options->advanced stuff, I think; or perhaps I have the "about:config" > plugin to do that) allows you to toggle this value back to "True". This > setting controls whether threads are defined *only* by the mail header > (strict=True), or whether TB also tries to guess based on the Subject > header (strict=False). I solved the problem for me, well enough, by sorting threads by subject instead of 'Date' (actually, time) so that disconnect threads sort together anyway. From tjreedy at udel.edu Tue May 18 22:36:32 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 22:36:32 -0400 Subject: recall function definition from shell In-Reply-To: <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Message-ID: On 5/18/2010 2:55 PM, superpollo wrote: > yes python does not, but maybe the *shell* does, or so i thought. i just > wanted to dump the code for the function in a file, after i tested in > the shell... On Windows, you can tell the shell (command window) how many lines to remember. One can sensibly make this a lot higher on a gigabyte machine than back in the 640K days. No idea about other systems. From tjreedy at udel.edu Tue May 18 22:39:42 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 22:39:42 -0400 Subject: upgrade python In-Reply-To: References: Message-ID: On 5/18/2010 9:47 PM, Aahz wrote: > In article, > packet wrote: >> >> Would it be safe to upgrade from python 2.6.4 to 2.6.5 without hurting >> the 2.6.4? > > Define "hurting". Generally speaking, it's always safe to upgrade a > point release, but you should replace the previous version. The default action on windows is replace. I keep the previous installer around with the current one fora while in case a bugfix release has a problem and I need to revert. From ben+python at benfinney.id.au Tue May 18 22:54:04 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 May 2010 12:54:04 +1000 Subject: Picking a license References: <87r5ldbw3k.fsf@benfinney.id.au> <87fx1qji9t.fsf@benfinney.id.au> Message-ID: <87ocgciotv.fsf@benfinney.id.au> This thread is already off-topic and too long. I'm conflicted about my role in that; I have endeavoured only to address falsehoods that IMO were not otherwise being addressed. So I'll try to keep this brief. Ethan Furman writes: > This doesn't make sense to me, but I'm willing to learn -- how do you > do this in practice? Are you really selling the software Perhaps in private email we can discuss what you mean by ?really selling the software?; it's too off-topic here. By my understanding of that term, yes, I am selling software. > or rather selling things like setup, support, new code (or time to > code), etc? All of the above, depending on the project. -- \ ?If you don't know what your program is supposed to do, you'd | `\ better not start writing it.? ?Edsger W. Dijkstra | _o__) | Ben Finney From see at signature.invalid Tue May 18 23:01:10 2010 From: see at signature.invalid (Nigel Rowe) Date: Wed, 19 May 2010 13:01:10 +1000 Subject: help need to write a python spell checker References: Message-ID: On Fri, 14 May 2010 18:19, harry k wrote in comp.lang.python <>: > Write a spell checking tool that will identify all misspelled word in a text file using a provided dictionary. > > > > Extend the spell-checking tool so that the program will also print out a list of possible correct spellings for the words. > I'm happy to do you homework for you, cost is us$1000 per hour. Email to your professor automatically on receipt. From steve-REMOVE-THIS at cybersource.com.au Tue May 18 23:37:45 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 May 2010 03:37:45 GMT Subject: help need to write a python spell checker References: Message-ID: <4bf35d09$0$8802$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 13:01:10 +1000, Nigel Rowe wrote: > I'm happy to do you homework for you, cost is us$1000 per hour. Email > to your professor automatically on receipt. I'll do it for $700 an hour! -- Steven From awasilenko at gmail.com Tue May 18 23:39:20 2010 From: awasilenko at gmail.com (Adam W.) Date: Tue, 18 May 2010 20:39:20 -0700 (PDT) Subject: Classes and threading Message-ID: I thought I knew how classes worked, but this code sample is making my second guess myself: import threading class nThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self,args): print self.name print self.args pants = nThread(args=('fruit'),name='charlie') pants.start() Traceback (most recent call last): File "C:\Users\Adam\Desktop\PyTiVo\task_master.py", line 13, in pants = nThread(args=('fruit'),name='charlie') TypeError: __init__() got an unexpected keyword argument 'args' Shouldn't __init__ still handle these (as per http://docs.python.org/library/threading.html#thread-objects ), even if its subclassed? I thought this was the whole idea of inheritance and overdriving. And sort of related, why does this crash IDLE GUI but not the command line?: import threading class nThread(threading.Thread): def run(self): print 2+2 pants = nThread() pants.start() From frank.zhu.mingyu at gmail.com Tue May 18 23:42:10 2010 From: frank.zhu.mingyu at gmail.com (frank zhu) Date: Tue, 18 May 2010 23:42:10 -0400 Subject: question on logging module Message-ID: Hi, >From the python 2.6.4 tutorial, refer to http://docs.python.org/release/2.6.4/tutorial/stdlib2.html#logging The above example doesn't work for me. Here is script log ############################################# oem at oem-desktop ~ $ python -V Python 2.6.4 oem at oem-desktop ~ $ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logging.debug('debug information') Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'debug' ################################################ I am current using python2.6.4. Can anyone point out what's problem? Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Wed May 19 00:04:40 2010 From: max at alcyone.com (Erik Max Francis) Date: Tue, 18 May 2010 21:04:40 -0700 Subject: Classes and threading In-Reply-To: References: Message-ID: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> Adam W. wrote: > I thought I knew how classes worked, but this code sample is making my > second guess myself: > > import threading > > class nThread(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > > def run(self,args): > print self.name > print self.args > > pants = nThread(args=('fruit'),name='charlie') > pants.start() > > Traceback (most recent call last): > File "C:\Users\Adam\Desktop\PyTiVo\task_master.py", line 13, in > > pants = nThread(args=('fruit'),name='charlie') > TypeError: __init__() got an unexpected keyword argument 'args' > > Shouldn't __init__ still handle these (as per > http://docs.python.org/library/threading.html#thread-objects ), even > if its subclassed? I thought this was the whole idea of inheritance > and overdriving. You've overridden the __init__ method to _not_ take any arguments, and explicitly call its parent constructor not passing anything. So it shouldn't be a wonder that it won't accept any arguments. If you don't intend to override the constructor in the parent class, simply don't define it. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis I like young girls. Their stories are shorter. -- Thomas McGuane From pmaupin at gmail.com Wed May 19 00:18:46 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Tue, 18 May 2010 21:18:46 -0700 (PDT) Subject: help need to write a python spell checker References: Message-ID: <49bffe0f-00a7-47a2-a857-1c1e35ac8870@p17g2000vbe.googlegroups.com> On May 14, 3:19?am, "harry k" wrote: > Write a spell checking tool that will identify all misspelled word in a text file using a provided dictionary. Well, this has been educational. Both my daughters just finished their final exams last week, so I was confused about seeing the homework assignment. Then I saw the email address. Although it makes perfect sense, I never really thought much about the possibility that the school year would be "upside down" "down under"... Regards, Pat From sjmachin at lexicon.net Wed May 19 00:23:44 2010 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 May 2010 21:23:44 -0700 (PDT) Subject: help need to write a python spell checker References: <4bf35d09$0$8802$c3e8da3@news.astraweb.com> Message-ID: <47839461-9f71-48cf-a7f2-dd9af2ef40d3@k17g2000pro.googlegroups.com> On May 19, 1:37?pm, Steven D'Aprano wrote: > On Wed, 19 May 2010 13:01:10 +1000, Nigel Rowe wrote: > > I'm happy to do you homework for you, cost is us$1000 per hour. ?Email > > to your professor automatically on receipt. > > I'll do it for $700 an hour! he could save the money if he oogledgay orvignay ellspay eckerchay From cs at zip.com.au Wed May 19 00:33:34 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 19 May 2010 14:33:34 +1000 Subject: question on logging module In-Reply-To: References: Message-ID: <20100519043334.GA17039@cskk.homeip.net> On 18May2010 23:42, frank zhu wrote: | Hi, | >From the python 2.6.4 tutorial, refer to | http://docs.python.org/release/2.6.4/tutorial/stdlib2.html#logging | | The above example doesn't work for me. | Here is script log | | ############################################# | | oem at oem-desktop ~ $ python -V | Python 2.6.4 | oem at oem-desktop ~ $ python | Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) | [GCC 4.4.1] on linux2 | Type "help", "copyright", "credits" or "license" for more information. | >>> import logging | >>> logging.debug('debug information') | Traceback (most recent call last): | File "", line 1, in | AttributeError: 'module' object has no attribute 'debug' | | ################################################ | | I am current using python2.6.4. | | Can anyone point out what's problem? I don't suppose you have a file called "logging.py" in your working directory? Python will find it before the system libraries; it is a bad idea to name .py files the same as library module for this reason. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ The First Law of Internet Communications: Be liberal in what you accept, and conservative in what you send. - Jon Postel From contact at xavierho.com Wed May 19 00:45:49 2010 From: contact at xavierho.com (Xavier Ho) Date: Wed, 19 May 2010 14:45:49 +1000 Subject: help need to write a python spell checker In-Reply-To: <49bffe0f-00a7-47a2-a857-1c1e35ac8870@p17g2000vbe.googlegroups.com> References: <49bffe0f-00a7-47a2-a857-1c1e35ac8870@p17g2000vbe.googlegroups.com> Message-ID: Yeah, most unis here commence in March, and the first semester usually finish in June, when the exams are. - Xav on his 'droid On 19/05/2010 2:21 PM, "Patrick Maupin" wrote: On May 14, 3:19 am, "harry k" wrote: > Write a spell checking tool that wil... Well, this has been educational. Both my daughters just finished their final exams last week, so I was confused about seeing the homework assignment. Then I saw the email address. Although it makes perfect sense, I never really thought much about the possibility that the school year would be "upside down" "down under"... Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at vincentdavis.net Wed May 19 01:14:49 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 23:14:49 -0600 Subject: __str__ for each function in a class Message-ID: I am sure this is easy but I am not sure how to do it and google was failing me. Lets say I have a class() with an def x() and def y() and I want print(class.x) and (class.y) to have custom prints (__str__) how do I do this For example class C(object): def __init__(self, new): self.letter = dict(a=1,b=2,c=3, amin=np.amin) self.new = new self._x = None self._Y = None @property def x(self): """I'm the 'x' property.""" self._x = self.new return self._x @property def y(self): """I'm the 'x' property.""" self._y = self.new*-1 return self._y ....... >>> print(class.x) ****x**** >>> print(class.y) --------- ++++y++++ --------- *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From hellofromsahar at gmail.com Wed May 19 02:07:13 2010 From: hellofromsahar at gmail.com (sahar Dar) Date: Tue, 18 May 2010 23:07:13 -0700 (PDT) Subject: Quality Indian Dresses At Reasonable Prices Message-ID: <5ec2a0b4-17e1-4ddd-9ee2-de17c4128c96@o1g2000vbe.googlegroups.com> Dear All, My Ladies Wear Site Is Live Now. We Bring You the Latest Designer Wear From All Over THE World specially India & Pakistan. To Place Your Orders Checkout www.e-atitude.com From switch2mathan at gmail.com Wed May 19 02:57:40 2010 From: switch2mathan at gmail.com (MathanK) Date: Tue, 18 May 2010 18:57:40 -1200 Subject: Is there conversion method to convert pyunicodeobject to pybyteobject? Message-ID: <128af5a76ca.2387060254380996511.-7043682202504556201@gmail.com> Got it worked with the following change. PyUnicodeObject *p = ...whatever...; char* tmp = (char *)p; PyObject* arg = PyBytes_FromString (tmp); function( (PyBytesObject*) arg); >From : MathanK<switch2mathan at gmail.com> To : "python-list" <python-list at python.org> Date : Sat, 15 May 2010 02:50:22 -1200 Subject : Is there conversion method to convert pyunicodeobject to pybyteobject? Hi All, A variable whose data type is PyUnicodeObject is to be assigned to varioable of PyBytesObject type example : void function( (PyBytesObject* byte){........} PyUnicodeObject *p = ...whatever...; function( (PyBytesObject*)p); compiled and got a Bus Error. Cheers, Mathan -------------- next part -------------- An HTML attachment was scrubbed... URL: From tomf.sessile at gmail.com Wed May 19 03:16:56 2010 From: tomf.sessile at gmail.com (TomF) Date: Wed, 19 May 2010 00:16:56 -0700 Subject: Global variables for python applications References: Message-ID: <2010051900165614229-tomfsessile@gmailcom> On 2010-05-16 12:27:21 -0700, christian schulze said: > On 16 Mai, 20:20, James Mills wrote: >> On Mon, May 17, 2010 at 4:00 AM, Krister Svanlund >> >> wrote: >>> On Sun, May 16, 2010 at 7:50 PM, AON LAZIO wrote: >>>> ?? How can I set up global variables for the entire python applications? >>>> Like I can call and set this variables in any .py files. >>>> ?? Think of it as a global variable in a single .py file but thisis for the >>>> entire application. >> >>> First: Do NOT use global variables, it is bad practice and will >>> eventually give you loads of s**t. >> >>> But if you want to create global variables in python I do believe it >>> is possible to specify them in a .py file and then simply import it as >>> a module in your application. If you change one value in a module the >>> change will be available in all places you imported that module in. >> >> The only place global variables are considered somewhat "acceptable" >> are as constants in a module shared as a static value. >> >> Anything else should be an object that you share. Don't get into the >> habit of using global variables! >> >> --james > > Exactly! Python's OOP is awesome. Use it. Global vars used as anything > but constants is bad practice. It isn't that much work to implement > that. Let's say you have a bunch of globals, one of which is a verbose flag. If I understand the difference, using a module gbls.py: # in gbls.py verbose = False # elsewhere: import gbls gbls.verbose = True Using a class: # In the main module: class gbls(object): def __init__(self, verbose=False): self.verbose = verbose my_globals = gbls.gbls(verbose=True) ... some_function(my_globals, ...) If this is what you have in mind, I'm not really seeing how one is good practice and the other is bad. The OOP method is more verbose (no pun intended) and I don't see how I'm any less likely to shoot myself in the foot with it. -Tom From cmpython at gmail.com Wed May 19 03:17:05 2010 From: cmpython at gmail.com (CM) Date: Wed, 19 May 2010 00:17:05 -0700 (PDT) Subject: help need to write a python spell checker References: Message-ID: I love how he just copied and pasted the assignment without any other remarks. From anthra.norell at bluewin.ch Wed May 19 03:26:17 2010 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Wed, 19 May 2010 09:26:17 +0200 Subject: Regular expression In-Reply-To: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> Message-ID: <4BF39299.1090804@bluewin.ch> Back9 wrote: > Hi, > > I have a string like this: > 0x340x5A0x9B0xBA > I want to extract 0x from the string but the first one. > > How I can use re for this case? > > The string size will vary. > > TIA > > Unless the use of a regular expression is a requirement I'd do it like this: '0x%s' % s.split ('x', 1)[1].replace ('x', '') Frederic From awasilenko at gmail.com Wed May 19 03:50:48 2010 From: awasilenko at gmail.com (Adam W.) Date: Wed, 19 May 2010 00:50:48 -0700 (PDT) Subject: Classes and threading References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> Message-ID: On May 19, 12:04?am, Erik Max Francis wrote: > Adam W. wrote: > > I thought I knew how classes worked, but this code sample is making my > > second guess myself: > > > import threading > > > class nThread(threading.Thread): > > ? ? def __init__(self): > > ? ? ? ? threading.Thread.__init__(self) > > > ? ? def run(self,args): > > ? ? ? ? print self.name > > ? ? ? ? print self.args > > > pants = nThread(args=('fruit'),name='charlie') > > pants.start() > > > Traceback (most recent call last): > > ? File "C:\Users\Adam\Desktop\PyTiVo\task_master.py", line 13, in > > > > ? ? pants = nThread(args=('fruit'),name='charlie') > > TypeError: __init__() got an unexpected keyword argument 'args' > > > Shouldn't __init__ still handle these (as per > >http://docs.python.org/library/threading.html#thread-objects), even > > if its subclassed? ?I thought this was the whole idea of inheritance > > and overdriving. > > You've overridden the __init__ method to _not_ take any arguments, and > explicitly call its parent constructor not passing anything. ?So it > shouldn't be a wonder that it won't accept any arguments. > > If you don't intend to override the constructor in the parent class, > simply don't define it. Hummm, so lets say I wanted it pass all the variables to the parent constructor, how would I do that? I wouldn't have to list every variable it could possible receive would I? This is like the opposite behavior I remember. When working with PyQt GUI classes, I swear I just sub classed the few things I wanted to change, and everything else would refer back to the parent... What I really just want to do is pass run() some args, which is what I assumed the default __init__'s args was for, but I give it args without sub classing __init__ and it has no idea what to do with them. I subclass __init__ to take args, and I break everything else? Is this really how this is supposed to work? From mail at timgolden.me.uk Wed May 19 03:55:42 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 19 May 2010 08:55:42 +0100 Subject: Pointers on packaging python programs for installation on multiple platforms? In-Reply-To: <4BF3475A.80304@optusnet.com.au> References: <4BF3475A.80304@optusnet.com.au> Message-ID: <4BF3997E.5080805@timgolden.me.uk> On 19/05/2010 03:05, gobnat wrote: > I am trying to release my first python program. I would like to be > able to create a download which will automatically do stuff like add > menu items (eg for KDE, GNOME and Windows). Is there anywhere which > explains how to do this? Speaking from the Windows perspective (although the same probably applies elsewhere): this is the kind of thing which installer generators handle for you. If you wrap your installer using NSIS [1] or Wix [2] or whatever other installer-generator, that will include options to add menu items. (Caveat: this is informed hearsay; I've never actually used either of those in earnest). If you *want* to do it yourself then, on Windows, you basically want to create folders and shortcuts within the user's Start Menu shell folder. It's not too hard even from scratch; my winshell module might help a little, too. [3] TJG [1] http://nsis.sourceforge.net/Main_Page [2] http://wix.sourceforge.net/ [3]http://timgolden.me.uk/python/winshell.html From greg.ewing at canterbury.ac.nz Wed May 19 04:04:32 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 19 May 2010 20:04:32 +1200 Subject: another question about classes and subclassing In-Reply-To: References: <4BF33F5F.2030207@ieee.org> <4BF34663.2000704@ieee.org> Message-ID: <85hjq5FdqlU1@mid.individual.net> Alex Hall wrote: > Sorry, top-posting is a habit on some other lists I am on, and > sometimes it follows me to lists where in-line posting is the way to > do it. Which list you're on shouldn't matter. You should cultivate the habit of always quoting selectively and minimally, on any list. It may take you a little longer to write your reply that way, but it will make your posts a lot easier for everyone else to read and understand. -- Greg From greg.ewing at canterbury.ac.nz Wed May 19 04:15:30 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 19 May 2010 20:15:30 +1200 Subject: another question about classes and subclassing In-Reply-To: References: <4BF33F5F.2030207@ieee.org> Message-ID: <85hkenFhdkU1@mid.individual.net> Alex Hall wrote: > So by calling submarine(craft) I am bringing > in all of craft's attribs (subclassing)? Or does calling craft's > __init__ method do that instead? By making Submarine a subclass of Craft, you are inheriting any methods, or other class attributes, defined in the classes themselves. Instance attributes are a little different -- they only come into existence when you assign to them, which is usually done for the first time in the __init__ method. Each instance has its own dictionary that holds the values of its instance attributes, and it's just a flat namespace -- there is no real distinction between an instance attribute of a class or a subclass. Any "inheritance" of instance attributes is just a consequence of one __init__ method calling another. -- Greg From duncan.booth at invalid.invalid Wed May 19 04:17:41 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 May 2010 08:17:41 GMT Subject: Classes and threading References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> Message-ID: "Adam W." wrote: >> If you don't intend to override the constructor in the parent class, >> simply don't define it. > > Hummm, so lets say I wanted it pass all the variables to the parent > constructor, how would I do that? I wouldn't have to list every > variable it could possible receive would I? > No, you just have to handle them the way you would for any function that accepts arguments that it doesn't know in advance: class nThread(threading.Thread): def __init__(self, *args, **kw): threading.Thread.__init__(self, *args, **kw) If you want to add your own additional arguments then name them explicitly and don't pass them through: class nThread(threading.Thread): def __init__(self, myarg1, mayarg2, *args, **kw): threading.Thread.__init__(self, *args, **kw) -- Duncan Booth http://kupuguy.blogspot.com From greg.ewing at canterbury.ac.nz Wed May 19 04:22:21 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 19 May 2010 20:22:21 +1200 Subject: another question about classes and subclassing In-Reply-To: References: Message-ID: <85hkrkFjqlU1@mid.individual.net> Dave Angel wrote: > Inside the __init__() method of Submarine, simply call the __init__() > method of Craft, with appropriate parameters. To elaborate on that a little, it looks like this: class Craft: def __init__(self, position): self.position = position class Submarine(Craft): def __init__(self, position, depth): Craft.__init__(self, position) self.depth = depth Note the explicit 'self' passed to the __init__ method of Craft. This is necessary because you are calling the method's underlying function directly, bypassing the magic which normally inserts 'self' automatically. -- Greg From greg.ewing at canterbury.ac.nz Wed May 19 04:30:11 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 19 May 2010 20:30:11 +1200 Subject: Classes and threading In-Reply-To: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> Message-ID: <85hla5FjqlU2@mid.individual.net> Erik Max Francis wrote: > Adam W. wrote: > >> class nThread(threading.Thread): >> def __init__(self): >> threading.Thread.__init__(self) > > If you don't intend to override the constructor in the parent class, > simply don't define it. Or if you do need to override it for some reason, you need to accept the extra args and pass them on: class nThread(threading.Thread): def __init__(self, *args, **kwds): threading.Thread.__init__(self, *args, **kwds) # your other stuff here -- Greg From awasilenko at gmail.com Wed May 19 05:08:24 2010 From: awasilenko at gmail.com (Adam W.) Date: Wed, 19 May 2010 02:08:24 -0700 (PDT) Subject: Classes and threading References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> <85hla5FjqlU2@mid.individual.net> Message-ID: <1459066c-5611-4fe4-8a8b-5cc264e7fa4d@o15g2000vbb.googlegroups.com> On May 19, 4:30?am, Gregory Ewing wrote: > Or if you do need to override it for some reason, you > need to accept the extra args and pass them on: > > ? ?class nThread(threading.Thread): > > ? ? ? ?def __init__(self, *args, **kwds): > ? ? ? ? ? ?threading.Thread.__init__(self, *args, **kwds) > ? ? ? ? ? ?# your other stuff here > Amazing, I've never seen *args used before outside of documentation, I didn't think it was "real" :P One problem down, still looking for why printing inside a thread crashes IDLE. From jimmy.cullen at gmail.com Wed May 19 05:28:15 2010 From: jimmy.cullen at gmail.com (Jimoid) Date: Wed, 19 May 2010 02:28:15 -0700 (PDT) Subject: Reading data from a Microsoft Access 2003 database Message-ID: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> Hi All, I use Ubuntu 64 bit and need to develop a programme (ideally in Python) to work on data that is contained in a Microsoft Access 2003 database. I do not need to modify the database, simply read a few columns of data from some tables. Google hasn't been able to offer me a suitable solution to this problem, and although there are some references to this problem in the archives of this group, they are mainly very old and I wonder if there is anything more recent that members could suggest to me? Python would be my language of choice, however if someone has any other suggestions then I'm open to ideas. TIA, Jimmy From lists at cheimes.de Wed May 19 05:43:49 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 19 May 2010 11:43:49 +0200 Subject: Classes and threading In-Reply-To: <85hla5FjqlU2@mid.individual.net> References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> <85hla5FjqlU2@mid.individual.net> Message-ID: > Or if you do need to override it for some reason, you > need to accept the extra args and pass them on: > > class nThread(threading.Thread): > > def __init__(self, *args, **kwds): > threading.Thread.__init__(self, *args, **kwds) > # your other stuff here Since Thread is a new style class, this should read: class NThread(threading.thread): def __init__(self, *args, **kwargs): super(NThread, self).__init__(*args, **kwargs) Christian From simon at brunningonline.net Wed May 19 06:13:19 2010 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 19 May 2010 11:13:19 +0100 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> Message-ID: On 19 May 2010 10:28:15 UTC+1, Jimoid wrote: > I use Ubuntu 64 bit and need to develop a programme (ideally in > Python) to work on data that is contained in a Microsoft Access 2003 > database. I do not need to modify the database, simply read a few > columns of data from some tables. mxODBC might well be what you are looking for, -- Cheers, Simon B. From jmontoyaz at gmail.com Wed May 19 06:53:44 2010 From: jmontoyaz at gmail.com (Javier Montoya) Date: Wed, 19 May 2010 03:53:44 -0700 (PDT) Subject: remove elements incrementally from a list Message-ID: Dear all, I've a list of float numbers and I would like to delete incrementally a set of elements in a given range of indexes, sth. like: for j in range(beginIndex, endIndex+1): print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j] However, since I'm iterating over the same list, the indexes (range) are not valid any more for the new list. Does anybody has some suggestions on how to delete the elements properly? Best wishes From utente at esempio.net Wed May 19 07:00:01 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 13:00:01 +0200 Subject: remove elements incrementally from a list In-Reply-To: References: Message-ID: <4bf3c4b1$0$40285$4fafbaef@reader2.news.tin.it> Javier Montoya ha scritto: > Dear all, > > I've a list of float numbers and I would like to delete incrementally > a set of elements in a given range of indexes, sth. like: > > for j in range(beginIndex, endIndex+1): > print ("remove [%d] => val: %g" % (j, myList[j])) > del myList[j] > > However, since I'm iterating over the same list, the indexes (range) > are not valid any more for the new list. > Does anybody has some suggestions on how to delete the elements > properly? clone the list, and then loop over the copy while deleting from the original bye From solderluke at gmail.com Wed May 19 07:24:27 2010 From: solderluke at gmail.com (zLuke) Date: Wed, 19 May 2010 04:24:27 -0700 (PDT) Subject: multiprocessing module - could it use google protocol buffers? Message-ID: <210a0635-c5f5-48ca-8696-760e1bf2b361@p17g2000vbe.googlegroups.com> Does it make sense to be able to substitute the pickling action in the multiprocessing module with google protocol buffers instead? If so, has anyone thought how to do it? I wanted some operation more compact/ faster than pickling for ipc of data. Also, has anyone built any wrappers for the multiprocessing module that gives a simple pp flavor kind of construct? Curious, zLuke From breamoreboy at yahoo.co.uk Wed May 19 07:38:16 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 19 May 2010 12:38:16 +0100 Subject: remove elements incrementally from a list In-Reply-To: References: Message-ID: On 19/05/2010 11:53, Javier Montoya wrote: > Dear all, > > I've a list of float numbers and I would like to delete incrementally > a set of elements in a given range of indexes, sth. like: > > for j in range(beginIndex, endIndex+1): > print ("remove [%d] => val: %g" % (j, myList[j])) > del myList[j] > > However, since I'm iterating over the same list, the indexes (range) > are not valid any more for the new list. > Does anybody has some suggestions on how to delete the elements > properly? > > Best wishes You can delete the lot in one hit using a slice, see section 5.2 here http://docs.python.org/tutorial/datastructures.html Regards. Mark Lawrence From shahmed at sfwmd.gov Wed May 19 07:47:41 2010 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Wed, 19 May 2010 07:47:41 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> Message-ID: <77F33A87D54B2F47AB06A81DA7B5252736D7C9@EXCHVS02.ad.sfwmd.gov> -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of Simon Brunning Sent: Wednesday, May 19, 2010 6:13 AM To: python-list Subject: Re: Reading data from a Microsoft Access 2003 database On 19 May 2010 10:28:15 UTC+1, Jimoid wrote: > I use Ubuntu 64 bit and need to develop a programme (ideally in > Python) to work on data that is contained in a Microsoft Access 2003 > database. I do not need to modify the database, simply read a few > columns of data from some tables. mxODBC might well be what you are looking for, -- Cheers, Simon B. -- Or you can use pyodbc DBfile = '/path/*.mdb conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+DBfile, autocommit=True) cursor = conn.cursor() Thanks Shakir From schaffer at optonline.net Wed May 19 08:05:49 2010 From: schaffer at optonline.net (Les Schaffer) Date: Wed, 19 May 2010 08:05:49 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> Message-ID: <4bf3d419$0$31275$607ed4bc@cv.net> Jimoid wrote: > I use Ubuntu 64 bit and need to develop a programme (ideally in > Python) to work on data that is contained in a Microsoft Access 2003 > database. I do not need to modify the database, simply read a few > columns of data from some tables. this worked like a charm for me: http://code.activestate.com/recipes/528868-extraction-and-manipulation-class-for-microsoft-ac/ Les From awilliam at whitemice.org Wed May 19 08:17:58 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Wed, 19 May 2010 08:17:58 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: <4bf3d419$0$31275$607ed4bc@cv.net> References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> Message-ID: <1274271478.4282.1.camel@linux-yu4c.site> On Wed, 2010-05-19 at 08:05 -0400, Les Schaffer wrote: > Jimoid wrote: > > > I use Ubuntu 64 bit and need to develop a programme (ideally in > > Python) to work on data that is contained in a Microsoft Access 2003 > > database. I do not need to modify the database, simply read a few > > columns of data from some tables. > > this worked like a charm for me: > http://code.activestate.com/recipes/528868-extraction-and-manipulation-class-for-microsoft-ac/ The OP: "I use Ubuntu 64 bit" Does something that contains "import win32com.client" work on anything other than Windows? -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From awilliam at whitemice.org Wed May 19 08:23:20 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Wed, 19 May 2010 08:23:20 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> Message-ID: <1274271800.4282.6.camel@linux-yu4c.site> On Wed, 2010-05-19 at 02:28 -0700, Jimoid wrote: > Hi All, > I use Ubuntu 64 bit and need to develop a programme (ideally in > Python) to work on data that is contained in a Microsoft Access 2003 > database. I do not need to modify the database, simply read a few > columns of data from some tables. > Google hasn't been able to offer me a suitable solution to this Google is a poor way to look for such things. It is better to go to Freshmeat / SourceForge or PyPI directly. Try mdbtools is your best bet unless you are willing to pay for the EasySoft drivers. I've had mixed success with mdbtools; if all you need to do is extract data their ODBC driver will probably work. If you are willing to use Jython (Python on the JVM) you have a *lot* more options for this kind of thing. > problem, and although there are some references to this problem in the > archives of this group, they are mainly very old and I wonder if there > is anything more recent that members could suggest to me? > Python would be my language of choice, however if someone has any > other suggestions then I'm open to ideas. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From mouadino at gmail.com Wed May 19 08:32:58 2010 From: mouadino at gmail.com (mouadino) Date: Wed, 19 May 2010 05:32:58 -0700 (PDT) Subject: abc don't play well with private method References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com> <4be18d3d$0$19014$426a34cc@news.free.fr> <4bf2af74$0$24527$426a74cc@news.free.fr> Message-ID: <0be11297-65b3-4943-a361-80ee04953b78@r9g2000vbk.googlegroups.com> Hello, and thank you for ALL the informations. i think i was reading the wrong documents :) For my use of ABC, i wanted to implement a plugin interface with the ABC, in first i define a Base class (ABC) that other class inherit(implement) so that they can be interfaced as plugins. but i did have some confusing about the privates method . thank you all again. Khalil_ibn_Ahmad (http://en.wikipedia.org/wiki/Khalil_ibn_Ahmad) sayed : They are 4 kind of man : the one that know that he don't know, this is a ignorant so teach him the one that know that he know, this is a savant so take from him the knowledge the one that don't know that he know, this one has forget so remind him the one that don't know that he don't know , this is a fool From steveo at syslang.net Wed May 19 09:47:22 2010 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 19 May 2010 09:47:22 -0400 Subject: remove elements incrementally from a list In-Reply-To: References: Message-ID: <4BF3EBEA.7000903@syslang.net> On 5/19/2010 6:53 AM, Javier Montoya wrote: > I've a list of float numbers and I would like to delete incrementally > a set of elements in a given range of indexes, sth. like: > > for j in range(beginIndex, endIndex+1): > print ("remove [%d] => val: %g" % (j, myList[j])) > del myList[j] > > However, since I'm iterating over the same list, the indexes (range) > are not valid any more for the new list. > Does anybody has some suggestions on how to delete the elements > properly? How about using numpy? to_be_deleted is an array of indexes to be deleted from myList. You seem to already have that list created but your list is contiguous. Just in case it isn't, you can say stuff like: to_be_deleted = numpy.where( myList > allowed_or_something ) myList = numpy.delete( myList, to_be_deleted ) -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From schaffer at optonline.net Wed May 19 10:00:15 2010 From: schaffer at optonline.net (Les Schaffer) Date: Wed, 19 May 2010 10:00:15 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> Message-ID: <4bf3eeeb$0$31263$607ed4bc@cv.net> Adam Tauno Williams wrote: > The OP: "I use Ubuntu 64 bit" woops, my bad ... From steve at REMOVE-THIS-cybersource.com.au Wed May 19 10:06:44 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 May 2010 14:06:44 GMT Subject: remove elements incrementally from a list References: Message-ID: <4bf3f074$0$27861$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 03:53:44 -0700, Javier Montoya wrote: > Dear all, > > I've a list of float numbers and I would like to delete incrementally a > set of elements in a given range of indexes, sth. like: > > for j in range(beginIndex, endIndex+1): > print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j] > > However, since I'm iterating over the same list, the indexes (range) are > not valid any more for the new list. Does anybody has some suggestions > on how to delete the elements properly? Just delete the slice: del myList[beginIndex:endIndex+1] For small lists where you are deleting small chunks, this is the simplest, most straight-forward way. Alternatively, create a new list excluding the bits you would have deleted, and assign it in place: myList[:] = myList[:beginIndex] + myList[endIndex+1:] Note carefully that you aren't just re-binding the name "myList", but assigning to the slice myList[:]. Then there is the old-fashioned way: iterate over the list backwards, deleting from the end towards the front. for j in range(endIndex, beginIndex-1, -1): del myList[j] If your list is HUGE and you have very little memory, this is probably the least worst way. It might be slow, but it will work. Finally, we have this: myList[beginIndex:] = myList[endIndex+1:] -- Steven From ninmonkeys at gmail.com Wed May 19 10:21:20 2010 From: ninmonkeys at gmail.com (Jake b) Date: Wed, 19 May 2010 09:21:20 -0500 Subject: View Html/ py code in a zip as HTML/text ? ( for phone ) Message-ID: I'm trying to figure out the best way to view python snippets / smaller files on the itouch/iPhone. I'm reading a new projects docs, but it's not easy to view the zip. It can't view zip files. Say I want to read pyglet examples, I need unzip at least one file and serve that. If it is text/HTML/py , then view in pastebin. Is there a trick to do this? Or maybe for certain sites. I thought I had seen a way google did it to a zip not hosted on google code, but can't find it. 1) is there existing web app to do this? 2) if not, I am on wifi, with apache mod-wsgi python enabled, so I could use that? -- Jake From kcronline at gmail.com Wed May 19 10:21:48 2010 From: kcronline at gmail.com (Kevin Rea) Date: Wed, 19 May 2010 10:21:48 -0400 Subject: Python Script for Website Mirroring Message-ID: Hello Folks: Can you please point me to a decent Python script(s) that I could customize to do automatic Website mirroring? Thanks Much! Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Wed May 19 10:34:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 May 2010 14:34:37 GMT Subject: Global variables for python applications References: <2010051900165614229-tomfsessile@gmailcom> Message-ID: <4bf3f6fc$0$27861$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 00:16:56 -0700, TomF wrote: > Let's say you have a bunch of globals, one of which is a verbose flag. > If I understand the difference, using a module gbls.py: > > # in gbls.py > verbose = False > # elsewhere: > import gbls > gbls.verbose = True > > Using a class: > > # In the main module: > class gbls(object): > def __init__(self, verbose=False): > self.verbose = verbose > > my_globals = gbls.gbls(verbose=True) > ... > some_function(my_globals, ...) > > > If this is what you have in mind, I'm not really seeing how one is good > practice and the other is bad. The OOP method is more verbose (no pun > intended) and I don't see how I'm any less likely to shoot myself in the > foot with it. Exactly! Both are considered harmful. Best is to avoid the use of globals if possible, not to disguise them by wrapping them in a class. The second case (using a class) is slightly less harmful, because you can set up multiple global namespaces and do this: some_function(my_globals, ...) some_function(other_globals, ...) which at least allows you to replace the globals on demand, but it is still somewhat of a code-smell. Best is to find a way of doing without them. (Note that global constants and functions are usually fine.) Unfortunately, it's rarely possible to do entirely without global settings, except in trivial applications. But what you can do is use Python's dynamic programming to reduce the need to keep globals hanging around: # Untested. def verbose_print(arg, level, verbosity=1): if level <= verbosity: print arg def my_function(arg): my_print(arg, level=2) return arg.upper() if __name__ == '__main__': if '--verbose' in sys.argv: my_print = functools.partial(verbose_print, verbosity=2) elif '--quiet' in sys.argv: my_print = functools.partial(verbose_print, verbosity=0) my_function("hello world") Note that although there is no verbosity global setting, every function that calls my_print will do the right thing (unless I've got the test backwards...), and if a function needs to override the implicit verbosity setting, it can just call verbose_print directly. -- Steven From thomas.fischer at gmail.com Wed May 19 10:41:38 2010 From: thomas.fischer at gmail.com (pilgrim773) Date: Wed, 19 May 2010 07:41:38 -0700 (PDT) Subject: Delete files from FTP Server older then 7 days. Using ftputil and ftplib. Message-ID: <6da6fa93-9298-4577-89b5-d58cb126d6fe@b21g2000vbh.googlegroups.com> Hello I am new to Python programming. I need a write a script which will delete files from a FTP server after they have reached a certain age, like 7 days for example. I have prepared this code below, but I get an error message: The system cannot find the path specified: '/test123/*.*' Probably someone can help me further? Thank you in advance! import os, time, ftputil from ftplib import FTP ftp = FTP('127.0.0.1') print "Automated FTP Maintainance" print 'Logging in.' ftp.login('admin', 'admin') # This is the directory that we want to go to directory = 'test123' print 'Changing to:' + directory ftp.cwd(directory) files = ftp.retrlines('LIST') print 'List of Files:' + files # ftp.remove('LIST') #------------------------------------------- now = time.time() for f in os.listdir(directory): if os.stat(f).st_mtime < now - 7 * 86400: if os.directory.isfile(f): os.remove(os.directory.join(directory, f)) #except: #exit ("Cannot delete files") #------------------------------------------- print 'Closing FTP connection' ftp.close() From tjreedy at udel.edu Wed May 19 11:02:38 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 May 2010 11:02:38 -0400 Subject: __str__ for each function in a class In-Reply-To: References: Message-ID: On 5/19/2010 1:14 AM, Vincent Davis wrote: > > I am sure this is easy but I am not sure how to do it and google was > failing me. > Lets say I have a class() with an def x() and def y() and I want > print(class.x) and (class.y) to have custom prints (__str__) how do I do > this > For example > class C(object): > def __init__(self, new): > self.letter = dict(a=1,b=2,c=3, amin=np.amin) > self.new = new > self._x = None > self._Y = None > > @property > def x(self): > """I'm the 'x' property.""" > self._x = self.new > return self._x > > @property > def y(self): > """I'm the 'x' property.""" > self._y = self.new*-1 > return self._y > > ....... > >>> print(class.x) 'class' is a keyword, so this is a syntax error. Did you mean C.x? > ****x**** In any case, the printing of an object ob is controlled by type(ob).__str__ and type(ob).__repr__, so you can only control the printing of instances of custom type. You cannot replace methods of builtin classes. Terry Jan Reedy From tjreedy at udel.edu Wed May 19 11:07:33 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 May 2010 11:07:33 -0400 Subject: help need to write a python spell checker In-Reply-To: References: Message-ID: On 5/19/2010 3:17 AM, CM wrote: > I love how he just copied and pasted the assignment without any other > remarks. Yeah, that way he did not mess it up ;-). From contact at xavierho.com Wed May 19 11:09:24 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 20 May 2010 01:09:24 +1000 Subject: __str__ for each function in a class In-Reply-To: References: Message-ID: On 5/19/2010 1:14 AM, Vincent Davis wrote: > class C(object): >> def __init__(self, new): >> self.letter = dict(a=1,b=2,c=3, amin=np.amin) >> self.new = new >> self._x = None >> self._Y = None >> >> @property >> def x(self): >> """I'm the 'x' property.""" >> self._x = self.new >> return self._x >> > I just wanted to point out that your self._x = self.new does not give you a new object. Instead, _x is assigned a reference that points to this object called 'new', which is passed in during the class initialisation. I think your variable naming needs some improvement to show/correct your understanding. Also, you can just use `x` and `y` for the variable names; you don't need the underscore. If you want to use a pseudo-private variable, use __x (double prefix underscore) instead. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmontoyaz at gmail.com Wed May 19 11:29:19 2010 From: jmontoyaz at gmail.com (Javier Montoya) Date: Wed, 19 May 2010 08:29:19 -0700 (PDT) Subject: remove elements incrementally from a list References: <4bf3f074$0$27861$c3e8da3@news.astraweb.com> Message-ID: On May 19, 4:06?pm, Steven D'Aprano wrote: > On Wed, 19 May 2010 03:53:44 -0700, Javier Montoya wrote: > > Dear all, > > > I've a list of float numbers and I would like to delete incrementally a > > set of elements in a given range of indexes, sth. like: > > > for j in range(beginIndex, endIndex+1): > > ? ?print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j] > > > However, since I'm iterating over the same list, the indexes (range) are > > not valid any more for the new list. Does anybody has some suggestions > > on how to delete the elements properly? > > Just delete the slice: > > del myList[beginIndex:endIndex+1] > > For small lists where you are deleting small chunks, this is the > simplest, most straight-forward way. > > Alternatively, create a new list excluding the bits you would have > deleted, and assign it in place: > > myList[:] = myList[:beginIndex] + myList[endIndex+1:] > > Note carefully that you aren't just re-binding the name "myList", but > assigning to the slice myList[:]. > > Then there is the old-fashioned way: iterate over the list backwards, > deleting from the end towards the front. > > for j in range(endIndex, beginIndex-1, -1): > ? ? del myList[j] > > If your list is HUGE and you have very little memory, this is probably > the least worst way. It might be slow, but it will work. > > Finally, we have this: > > myList[beginIndex:] = myList[endIndex+1:] > > -- > Steven Hi guys, A big thanks to everybody, it's amazing! Cheers From doesnotexist at franzoni.invalid Wed May 19 11:42:38 2010 From: doesnotexist at franzoni.invalid (Alan Franzoni) Date: Wed, 19 May 2010 15:42:38 GMT Subject: abc for generators? Message-ID: Hello, I was looking for an ABC for generators in python. While there's a types.GeneratorType type object - which can't be used directly and it's not an abc - and many collections-related ABCs in the collections module, there's no way to say a user-defined class as a generator, even though it could expose the very same interface as a builtin, yield-based generator. I think it would be pretty useful. comments? -- Alan Franzoni contact me at public@[mysurname].eu From python at mrabarnett.plus.com Wed May 19 11:43:00 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 19 May 2010 16:43:00 +0100 Subject: Delete files from FTP Server older then 7 days. Using ftputil and ftplib. In-Reply-To: <6da6fa93-9298-4577-89b5-d58cb126d6fe@b21g2000vbh.googlegroups.com> References: <6da6fa93-9298-4577-89b5-d58cb126d6fe@b21g2000vbh.googlegroups.com> Message-ID: <4BF40704.3000907@mrabarnett.plus.com> pilgrim773 wrote: > Hello I am new to Python programming. I need a write a script which > will delete files from a FTP server after they have reached a certain > age, like 7 days for example. I have prepared this code below, but I > get an error message: > The system cannot find the path specified: '/test123/*.*' Probably > someone can help me further? Thank you in advance! > > import os, time, ftputil > from ftplib import FTP > > ftp = FTP('127.0.0.1') > print "Automated FTP Maintainance" > print 'Logging in.' > ftp.login('admin', 'admin') > > # This is the directory that we want to go to > directory = 'test123' > print 'Changing to:' + directory > ftp.cwd(directory) > files = ftp.retrlines('LIST') > print 'List of Files:' + files > # ftp.remove('LIST') > It's better to pass the full filename instead of changing the directory because it means that you don't need to keep track of which directory you're currently in, for example: files = ftp.retrlines(directory + '/LIST') > #------------------------------------------- > now = time.time() > for f in os.listdir(directory): > if os.stat(f).st_mtime < now - 7 * 86400: > if os.directory.isfile(f): > os.remove(os.directory.join(directory, f)) The os module works with _local_ files, not the remote files on a server. You can list the files and get info about them like this: reply = [] ftp.retrlines("LIST " + directory, reply.append) 'reply' will be a list of lines, one per file, which you can then parse. It shouldn't be too difficult to write a function to hide the messy details. :-) > #except: > #exit ("Cannot delete files") Bare excepts are almost always a very bad idea. > #------------------------------------------- > > print 'Closing FTP connection' > ftp.close() > From enleverLesX_XXmcX at XmclavXeauX.com.invalid Wed May 19 12:12:08 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Wed, 19 May 2010 18:12:08 +0200 Subject: Discover PyH References: Message-ID: <4bf40ddd$0$2975$ba4acef3@reader.news.orange.fr> Bonsoir ! La d?marche me semble int?ressante. Je testerai le module quand j'aurai un peu de temps. @-salutations -- Michel Claveau From cmertes at techfak.uni-bielefeld.de Wed May 19 12:23:18 2010 From: cmertes at techfak.uni-bielefeld.de (Christian Mertes) Date: Wed, 19 May 2010 18:23:18 +0200 Subject: What's the matter with docs.python.org? Message-ID: <1274286198.6623.351.camel@Inara> by kjon 2010-03-24T16:40:21+00:00. > In Philip Semanchuk writes: > >On Mar 24, 2010, at 12:05 PM, kj wrote: > >> In the last couple of weeks, docs.python.org has been down repeatedly > >> (like right now). Has anyone else noticed this? > >http://downforeveryoneorjustme.com/docs.python.org > Very handy. Thanks! > ~K Hey kjon, I just found your mail in the archives because I've been experiencing the same weird problems and I couldn't believe they wouldn't fix their server for such a long time. I'd like to know what downforeveryoneorjustme.com does because it's so lightning fast. Pinging the server? Works for me. Looking for port 80? It's open. Connecting to it and getting a web page? That's where things start to get interesting: > $ telnet docs.python.org 80 > Trying 2001:888:2000:d::a2... > Trying 82.94.164.162... > Connected to docs.python.org. > Escape character is '^]'. > GET / HTTP/1.0 > > > > Connection closed by foreign host. ... after a really long time. The server wouldn't serve me. Opera reports a network error right away though, not waiting for a timeout. And the best part: Chrome and Firefox just get me the website. Wireshark reveals that both latter browsers get a "304 Not Modified" response and then do a lot of weird stuff involving DNS as well as HTTP to finally deliver a web page. Opera does no such thing but only sends a request to 2001:888:2000:d::a2. Yeah, right, that's an IPv6 address. I really don't understand the details of what's going on here but chances are that you also use Opera, kjon and those who replied to you didn't? I reported docs.python.org as a broken page to the Opera devs but I'm also Ccing this mail to the server admin because this seems to be a more complex problem than just a broken (if at all) web browser. Best regards, Christian -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 185 bytes Desc: This is a digitally signed message part URL: From hari2981 at gmail.com Wed May 19 12:40:01 2010 From: hari2981 at gmail.com (Harikrishnan R) Date: Wed, 19 May 2010 22:10:01 +0530 Subject: Import Module Message-ID: Hi , I have a file a.py contains from one.two import abc -------------------------------------------- is there any way to find out "one.two" the import Path of abc. ? I don't want one.two.abc . Any function or attribute which directly give one.two ? -Regards -- Harikrishan R http://harikrishnanr.wordpress.com/ From thudfoo at opensuse.us Wed May 19 12:54:13 2010 From: thudfoo at opensuse.us (member thudfoo) Date: Wed, 19 May 2010 09:54:13 -0700 Subject: What's the matter with docs.python.org? In-Reply-To: <1274286198.6623.351.camel@Inara> References: <1274286198.6623.351.camel@Inara> Message-ID: On Wed, May 19, 2010 at 9:23 AM, Christian Mertes wrote: > by kjon 2010-03-24T16:40:21+00:00. >> In Philip Semanchuk writes: >> >On Mar 24, 2010, at 12:05 PM, kj wrote: >> >> In the last couple of weeks, docs.python.org has been down repeatedly >> >> (like right now). Has anyone else noticed this? >> >http://downforeveryoneorjustme.com/docs.python.org >> Very handy. Thanks! >> ~K > > Hey kjon, > > I just found your mail in the archives because I've been experiencing the > same weird problems and I couldn't believe they wouldn't fix their server > for such a long time. I'd like to know what downforeveryoneorjustme.com does > because it's so lightning fast. Pinging the server? Works for me. Looking for > port 80? It's open. Connecting to it and getting a web page? That's where things > start to get interesting: > >> $ telnet docs.python.org 80 >> Trying 2001:888:2000:d::a2... >> Trying 82.94.164.162... >> Connected to docs.python.org. >> Escape character is '^]'. >> GET / HTTP/1.0 >> >> >> >> Connection closed by foreign host. > > ... after a really long time. The server wouldn't serve me. Opera reports a > network error right away though, not waiting for a timeout. And the best part: > Chrome and Firefox just get me the website. Wireshark reveals that both latter > browsers get a "304 Not Modified" response and then do a lot of weird stuff involving > DNS as well as HTTP to finally deliver a web page. Opera does no such thing but only > sends a request to 2001:888:2000:d::a2. Yeah, right, that's an IPv6 address. > I really don't understand the details of what's going on here but chances are > that you also use Opera, kjon and those who replied to you didn't? > > I reported docs.python.org as a broken page to the Opera devs but I'm also Ccing this > mail to the server admin because this seems to be a more complex problem than just > a broken (if at all) web browser. > > Best regards, > > ? ? ? ?Christian > Worked for me: ~/isos2burn> telnet docs.python.org 80 Trying 82.94.164.162... Connected to docs.python.org. Escape character is '^]'. GET/HTTP/1.0 302 Found

Found

The document has moved here.


Apache/2.2.9 (Debian) DAV/2 SVN/1.5.1 mod_ssl/2.2.9 OpenSSL/0.9.8g mod_wsgi/2.5 Python/2.5.2 Server at dinsdale.python.org Port 80
Connection closed by foreign host. ~/isos2burn> date Wed May 19 09:49:11 PDT 2010 From python at bdurham.com Wed May 19 13:00:22 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 19 May 2010 13:00:22 -0400 Subject: How to determine subprocess.Popen() failed when shell=True In-Reply-To: <1274129147.11923.1375533733@webmail.messagingengine.com> References: <1274129147.11923.1375533733@webmail.messagingengine.com> Message-ID: <1274288422.22019.1375896829@webmail.messagingengine.com> For the archives - solution posted at http://stackoverflow.com/questions/2861548/how-to-determine-subprocess-popen-failed-when-shelltrue Malcolm From jjposner at optimum.net Wed May 19 13:06:11 2010 From: jjposner at optimum.net (John Posner) Date: Wed, 19 May 2010 13:06:11 -0400 Subject: how to cause a request for a missing class attribute cause its calculation In-Reply-To: References: Message-ID: <4BF41A83.8010805@optimum.net> On 5/18/2010 4:54 PM, Chris Rebert wrote: > Suggested reading: http://docs.python.org/library/functions.html#property I've placed a revision to this official *property* documentation at: http://wiki.python.org/moin/AlternativeDescriptionOfProperty There's also a gentle (I hope) intro to the *property* feature on the Wiki: http://wiki.python.org/moin/ComputedAttributesUsingPropertyObjects -John From utente at esempio.net Wed May 19 13:11:51 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 19:11:51 +0200 Subject: ipython question Message-ID: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> In [39]: def f(): ....: return 42 ....: In [40]: %psource f No source found for f In [41]: i expected to see the source... From cjw at ncf.ca Wed May 19 13:19:44 2010 From: cjw at ncf.ca (cjw) Date: Wed, 19 May 2010 13:19:44 -0400 Subject: Access to comp.lang.python In-Reply-To: References: Message-ID: <4BF41DB0.6050505@ncf.ca> On 18-May-10 19:27 PM, Tim Chase wrote: > On 05/15/2010 05:34 PM, cjw wrote: >> It seems that messages are coming from a number of sources, such as >> gmane and google groups. >> >> The problem is that many messages seem to get unlinked from their >> threads. >> >> I use Thunderbird 3.0.5 and wonder whether the problem lies with the >> merge process, the server or my reader. > > While others have told you about using gmane or other sources (direct > email, etc), I haven't seen anything fly by regarding the "unlinked from > their threads" portion of your question. Thunderbird 2.0 -> 3.0 changed > the default value for mail.strict_threading from False to True. Pulling > up the config editor (essentially the about:config, buried in the > options->advanced stuff, I think; or perhaps I have the "about:config" > plugin to do that) allows you to toggle this value back to "True". This > setting controls whether threads are defined *only* by the mail header > (strict=True), or whether TB also tries to guess based on the Subject > header (strict=False). > > Toggle it (and perhaps restart TB?) and see if that helps rectify the > threading. There are a lot of folks here on c.l.p that use broken > newsreaders that don't correctly set news/threading headers. > > -tkc > > > Thanks, mine is already set to "true". Colin W. From cjw at ncf.ca Wed May 19 13:19:44 2010 From: cjw at ncf.ca (cjw) Date: Wed, 19 May 2010 13:19:44 -0400 Subject: Access to comp.lang.python In-Reply-To: References: Message-ID: <4BF41DB0.6050505@ncf.ca> On 18-May-10 19:27 PM, Tim Chase wrote: > On 05/15/2010 05:34 PM, cjw wrote: >> It seems that messages are coming from a number of sources, such as >> gmane and google groups. >> >> The problem is that many messages seem to get unlinked from their >> threads. >> >> I use Thunderbird 3.0.5 and wonder whether the problem lies with the >> merge process, the server or my reader. > > While others have told you about using gmane or other sources (direct > email, etc), I haven't seen anything fly by regarding the "unlinked from > their threads" portion of your question. Thunderbird 2.0 -> 3.0 changed > the default value for mail.strict_threading from False to True. Pulling > up the config editor (essentially the about:config, buried in the > options->advanced stuff, I think; or perhaps I have the "about:config" > plugin to do that) allows you to toggle this value back to "True". This > setting controls whether threads are defined *only* by the mail header > (strict=True), or whether TB also tries to guess based on the Subject > header (strict=False). > > Toggle it (and perhaps restart TB?) and see if that helps rectify the > threading. There are a lot of folks here on c.l.p that use broken > newsreaders that don't correctly set news/threading headers. > > -tkc > > > Thanks, mine is already set to "true". Colin W. From cjw at ncf.ca Wed May 19 13:21:37 2010 From: cjw at ncf.ca (cjw) Date: Wed, 19 May 2010 13:21:37 -0400 Subject: another question about classes and subclassing In-Reply-To: References: Message-ID: On 18-May-10 17:51 PM, Alex Hall wrote: > Hi again all, > More about classes. I am still looking into my battleship game, and I > will have several different craft. All craft have common attribs > (position, alive, and so on) but each craft may be a surface ship, > submarine, or airplane. All three are craft, but a submarine can be > submerged or not, which does not apply to a surface ship or a plane, > while a plane can be airborne or not, which is not applicable to the > other two. Is there any advantage to creating a craft class: > > class craft(): > #has attribs common to any and all craft > #end class > > then doing something like: > > class submarine(craft): > #sub-specific attribs > #end class > > How would I create a submarine, and then get at the craft-level > attribs? Come to think of it, how would I pass anything to the craft > constructor (position and alive, for example) when creating a new > submarine object? Am I even doing this right to make submarine a > subclass of craft? Thanks. > Looks OK to me. Colin W. From pavlovevidence at gmail.com Wed May 19 13:24:41 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 19 May 2010 10:24:41 -0700 (PDT) Subject: abc for generators? References: Message-ID: On May 19, 8:42?am, Alan Franzoni wrote: > Hello, > I was looking for an ABC for generators in python. While there's a > types.GeneratorType type object - which can't be used directly ?and it's > not an abc - and many collections-related ABCs in the collections > module, there's no way to say a user-defined class as a generator, even > though it could expose the very same interface as a builtin, yield-based > generator. > > I think it would be pretty useful. > > comments? collections.Iterator You don't actually need abc's to write custom iterators, BTW, the following is an iterator for instance. class Noise: def __iter__(self): return self def __next__(self): return random.random() which is equivalent to the generator def Noise(): while True: yield random.random() Carl Banks From rsomerville at sjgeophysics.com Wed May 19 13:54:55 2010 From: rsomerville at sjgeophysics.com (Robert Somerville) Date: Wed, 19 May 2010 10:54:55 -0700 Subject: Best XML python package to learn for Ubuntu Linux ? Message-ID: <4BF425EF.3070207@sjgeophysics.com> Hi; I am about to get my feet wet with Python XML, there appears to be many libraries ... can someone recommend a good package to use on Ubuntu ??? regards; Robert Somerville From philip at semanchuk.com Wed May 19 14:06:51 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 19 May 2010 14:06:51 -0400 Subject: Best XML python package to learn for Ubuntu Linux ? In-Reply-To: <4BF425EF.3070207@sjgeophysics.com> References: <4BF425EF.3070207@sjgeophysics.com> Message-ID: On May 19, 2010, at 1:54 PM, Robert Somerville wrote: > Hi; > > I am about to get my feet wet with Python XML, there appears to be > many libraries ... can someone recommend > a good package to use on Ubuntu ??? Hi Robert, xml.etree.ElementTree is in the Python standard library as of version 2.5. It was a popular 3rd party package even before it became part of the standard library, so a lot of code uses it. It's a good place to start. HTH Philip From cmertes at techfak.uni-bielefeld.de Wed May 19 14:30:42 2010 From: cmertes at techfak.uni-bielefeld.de (Christian Mertes) Date: Wed, 19 May 2010 20:30:42 +0200 Subject: What's the matter with docs.python.org? In-Reply-To: References: <1274286198.6623.351.camel@Inara> Message-ID: <1274293842.7713.32.camel@Inara> On Mi, 2010-05-19 at 09:54 -0700, member thudfoo wrote: > Worked for me: > > ~/isos2burn> telnet docs.python.org 80 > Trying 82.94.164.162... > Connected to docs.python.org. > Escape character is '^]'. > GET/HTTP/1.0 > > > 302 Found > >

Found

>

The document has moved here.

>
>
Apache/2.2.9 (Debian) DAV/2 SVN/1.5.1 mod_ssl/2.2.9 > OpenSSL/0.9.8g mod_wsgi/2.5 Python/2.5.2 Server at dinsdale.python.org > Port 80
> Interesting. You did read the content you got though, didn't you? Regards, Christian -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 185 bytes Desc: This is a digitally signed message part URL: From backgoodoo at gmail.com Wed May 19 14:38:09 2010 From: backgoodoo at gmail.com (Back9) Date: Wed, 19 May 2010 11:38:09 -0700 (PDT) Subject: how to preserve hex value Message-ID: <288ca40f-e167-4f1f-bc9b-fdb9ed612587@m33g2000vbi.googlegroups.com> Hi, When converting a hex value, I'd like to preserve the decimal position. For example, 0x0A is converted to 0A not just A in string. How do I do this? TIA From g.rodola at gmail.com Wed May 19 14:41:34 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Wed, 19 May 2010 20:41:34 +0200 Subject: Delete files from FTP Server older then 7 days. Using ftputil and ftplib. In-Reply-To: <6da6fa93-9298-4577-89b5-d58cb126d6fe@b21g2000vbh.googlegroups.com> References: <6da6fa93-9298-4577-89b5-d58cb126d6fe@b21g2000vbh.googlegroups.com> Message-ID: 2010/5/19 pilgrim773 : > Hello I am new to Python programming. I need a write a script which > will delete files from a FTP server after they have reached a certain > age, like 7 days for example. I have prepared this code below, but I > get an error message: > The system cannot find the path specified: '/test123/*.*' Probably > someone can help me further? Thank you in advance! > > import os, time, ftputil > from ftplib import FTP > > ftp = FTP('127.0.0.1') > print "Automated FTP Maintainance" > print 'Logging in.' > ftp.login('admin', 'admin') > > # This is the directory that we want to go to > directory = 'test123' > print 'Changing to:' + directory > ftp.cwd(directory) > files = ftp.retrlines('LIST') > print 'List of Files:' + files > # ftp.remove('LIST') > > #------------------------------------------- > now = time.time() > for f in os.listdir(directory): > if os.stat(f).st_mtime < now - 7 * 86400: > if os.directory.isfile(f): > os.remove(os.directory.join(directory, f)) > #except: > #exit ("Cannot delete files") > #------------------------------------------- > > print 'Closing FTP connection' > ftp.close() > > -- > http://mail.python.org/mailman/listinfo/python-list > Instead of parsing the LIST response you can use MDTM command instead (if the server supports it) which returns a standardized time-like response for every file (ftp.sendcmd('MDTM filename')). Alternatively you can do as you're doing now but using MLSD instead of LIST (again, the server must support it). MLSD returns something like this: type=file;size=156;perm=r;modify=20071029155301;unique=801cd2; music.mp3 type=dir;size=0;perm=el;modify=20071127230206;unique=801e33; ebooks type=file;size=211;perm=r;modify=20071103093626;unique=801e32; module.py This would also be a lot cheaper in terms of data exchanged between client and server and hence faster as you proceed "per-directory" instead of "per-file in every directory". Note that if the server is RFC-compliant both MDTM and MLSD times are expressed as GMT times so an extra conversion to your local time may be necessary. Hope this helps, --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From thudfoo at opensuse.us Wed May 19 15:01:27 2010 From: thudfoo at opensuse.us (member thudfoo) Date: Wed, 19 May 2010 12:01:27 -0700 Subject: how to preserve hex value In-Reply-To: <288ca40f-e167-4f1f-bc9b-fdb9ed612587@m33g2000vbi.googlegroups.com> References: <288ca40f-e167-4f1f-bc9b-fdb9ed612587@m33g2000vbi.googlegroups.com> Message-ID: On Wed, May 19, 2010 at 11:38 AM, Back9 wrote: > Hi, > > When converting a hex value, I'd like to preserve the decimal > position. > For example, 0x0A is converted to 0A not just A in string. > > How do I do this? > > TIA > -- > http://mail.python.org/mailman/listinfo/python-list > |109> '%02X' % 10 <109> '0A' From jcd at sdf.lonestar.org Wed May 19 15:06:39 2010 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Wed, 19 May 2010 15:06:39 -0400 Subject: how to preserve hex value In-Reply-To: <288ca40f-e167-4f1f-bc9b-fdb9ed612587@m33g2000vbi.googlegroups.com> References: <288ca40f-e167-4f1f-bc9b-fdb9ed612587@m33g2000vbi.googlegroups.com> Message-ID: <1274295999.4704.18.camel@jcdyer-laptop> On Wed, 2010-05-19 at 11:38 -0700, Back9 wrote: > Hi, > > When converting a hex value, I'd like to preserve the decimal > position. > For example, 0x0A is converted to 0A not just A in string. > > How do I do this? > > TIA I'm not sure I understand what your use case is, but generally speaking, it is better to treat hex values as integers (which they are) than as string (which they are not). 0x0a is an integer value of ten. There is no change of decimal position gained by prepending a zero digit. It means exactly the same thing. If you know how large a chunk is, you can multiply (or bit-shift) and add to get the behavior you're looking for. def concat(byte1, byte2): return (byte1 << 8) + byte2 >>> hex(concat(0x43, 0x0a)) 0x430a One common use case is when using hex notation to represent sequences of bytes. In this case, you may want to work with a byte string instead. To concatenate your numbers this way, convert each number to a byte using chr(x) (Python 2.x) To print it as hex, do something like this: def bytestring_to_hex(s): return '0x + ''.join('%02x' % ord(x) for x in s) However, if you need an arbitrary number of zeros preserved, you're out of luck. They are semantically meaningless in python. (Is semantically meaningless redundant?) Cheers, Cliff From utente at esempio.net Wed May 19 15:58:04 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 21:58:04 +0200 Subject: function that counts... Message-ID: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> ... how many positive integers less than n have digits that sum up to m: In [197]: def prttn(m, n): tot = 0 for i in range(n): s = str(i) sum = 0 for j in range(len(s)): sum += int(s[j]) if sum == m: tot += 1 return tot .....: In [207]: prttn(25, 10000) Out[207]: 348 any suggestion for pythonizin' it? bye From robert.kern at gmail.com Wed May 19 16:01:34 2010 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 19 May 2010 15:01:34 -0500 Subject: ipython question In-Reply-To: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> References: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> Message-ID: On 5/19/10 12:11 PM, superpollo wrote: > In [39]: def f(): > ....: return 42 > ....: > > In [40]: %psource f > No source found for f > > In [41]: > > i expected to see the source... You will want to ask IPython questions on the IPython mailing list: http://mail.scipy.org/mailman/listinfo/ipython-user The reason you do not get the source is because there is no file that contains functions defined in the interactive interpreter. %psource uses the inspect module, and the inspect module explicitly only looks in real files using the linecache module. IPython could be modified to inject fake files into the linecache, but that's a chunk of work. I am sure they would be happy to incorporate a patch if you were to provide it to them. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From utente at esempio.net Wed May 19 16:10:43 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:10:43 +0200 Subject: ipython question In-Reply-To: References: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> Message-ID: <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> Robert Kern ha scritto: > On 5/19/10 12:11 PM, superpollo wrote: >> In [39]: def f(): >> ....: return 42 >> ....: >> >> In [40]: %psource f >> No source found for f >> >> In [41]: >> >> i expected to see the source... > > You will want to ask IPython questions on the IPython mailing list: > > http://mail.scipy.org/mailman/listinfo/ipython-user > > The reason you do not get the source is because there is no file that > contains functions defined in the interactive interpreter. %psource uses > the inspect module, and the inspect module explicitly only looks in real > files but still: In [218]: def f(): .....: return 42 .....: In [219]: %save tmp.py 218 File `tmp.py` exists. Overwrite (y/[N])? y The following commands were written to file `tmp.py`: def f(): return 42 In [220]: !cat tmp.py def f(): return 42 In [221]: %psource f No source found for f From utente at esempio.net Wed May 19 16:14:43 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:14:43 +0200 Subject: ipython question In-Reply-To: <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bf446b4$0$31377$4fafbaef@reader1.news.tin.it> superpollo ha scritto: > Robert Kern ha scritto: >> On 5/19/10 12:11 PM, superpollo wrote: >>> In [39]: def f(): >>> ....: return 42 >>> ....: >>> >>> In [40]: %psource f >>> No source found for f >>> >>> In [41]: >>> >>> i expected to see the source... >> >> You will want to ask IPython questions on the IPython mailing list: >> >> http://mail.scipy.org/mailman/listinfo/ipython-user >> >> The reason you do not get the source is because there is no file that >> contains functions defined in the interactive interpreter. %psource >> uses the inspect module, and the inspect module explicitly only looks >> in real files > > but still: > > In [218]: def f(): > .....: return 42 > .....: > > In [219]: %save tmp.py 218 > File `tmp.py` exists. Overwrite (y/[N])? y > The following commands were written to file `tmp.py`: > def f(): > return 42 > > > In [220]: !cat tmp.py > def f(): > return 42 > > In [221]: %psource f > No source found for f maybe i got it: In [230]: import tmp In [231]: %psource tmp.f def f(): return 42 From malaclypse2 at gmail.com Wed May 19 16:14:54 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 19 May 2010 16:14:54 -0400 Subject: function that counts... In-Reply-To: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: > ... how many positive integers less than n have digits that sum up to m: ... > any suggestion for pythonizin' it? This is how I would do it: def prttn(m, n): """How many positive integers less than n have digits that sum up to m""" total = 0 for testval in range(n): sumofdigits = sum(int(char) for char in str(testval)) if sumofdigits == m: total += 1 return total I added a docstring to the function, saying what it does, and what the arguments are supposed to represent. I also moved the convert-to-string-and-sum-the-digits logic into a single generator expression that's passed to the builtin sum function. Oh, and I tried to use slightly more expressive variable names. -- Jerry From robert.kern at gmail.com Wed May 19 16:24:13 2010 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 19 May 2010 15:24:13 -0500 Subject: ipython question In-Reply-To: <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: On 5/19/10 3:10 PM, superpollo wrote: > Robert Kern ha scritto: >> On 5/19/10 12:11 PM, superpollo wrote: >>> In [39]: def f(): >>> ....: return 42 >>> ....: >>> >>> In [40]: %psource f >>> No source found for f >>> >>> In [41]: >>> >>> i expected to see the source... >> >> You will want to ask IPython questions on the IPython mailing list: >> >> http://mail.scipy.org/mailman/listinfo/ipython-user >> >> The reason you do not get the source is because there is no file that >> contains functions defined in the interactive interpreter. %psource >> uses the inspect module, and the inspect module explicitly only looks >> in real files > > but still: > > In [218]: def f(): > .....: return 42 > .....: > > In [219]: %save tmp.py 218 > File `tmp.py` exists. Overwrite (y/[N])? y > The following commands were written to file `tmp.py`: > def f(): > return 42 > > > In [220]: !cat tmp.py > def f(): > return 42 > > In [221]: %psource f > No source found for f So? The function object f knows nothing about the file tmp.py. If you were to import tmp and then ask for %psource tmp.f, it should work. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From lists at necoro.eu Wed May 19 16:24:42 2010 From: lists at necoro.eu (=?UTF-8?B?UmVuw6kgJ05lY29ybycgTmV1bWFubg==?=) Date: Wed, 19 May 2010 22:24:42 +0200 Subject: function that counts... In-Reply-To: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4BF4490A.50007@necoro.eu> Am 19.05.2010 21:58, schrieb superpollo: > ... how many positive integers less than n have digits that sum up to m: > > In [197]: def prttn(m, n): > tot = 0 > for i in range(n): > s = str(i) > sum = 0 > for j in range(len(s)): > sum += int(s[j]) > if sum == m: > tot += 1 > return tot > .....: > > In [207]: prttn(25, 10000) > Out[207]: 348 > > any suggestion for pythonizin' it? > > bye An idea would be: >>> def prttn(m, n): ... return sum(1 for x in range(n) if sum(map(int, str(x))) == m) A small oneliner :) (I first had "return len([x for x in ...])" but the above avoids creating an intermediate list) - Ren? -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From utente at esempio.net Wed May 19 16:25:31 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:25:31 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> Jerry Hill ha scritto: > On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: >> ... how many positive integers less than n have digits that sum up to m: > ... >> any suggestion for pythonizin' it? > > This is how I would do it: > > def prttn(m, n): > """How many positive integers less than n have digits that sum up to m""" > total = 0 > for testval in range(n): > sumofdigits = sum(int(char) for char in str(testval)) this line gives me this: TypeError: 'int' object is not callable is it some new feature in >2.5 ? > if sumofdigits == m: > total += 1 > return total > > I added a docstring to the function, saying what it does, and what the > arguments are supposed to represent. I also moved the > convert-to-string-and-sum-the-digits logic into a single generator > expression that's passed to the builtin sum function. Oh, and I tried > to use slightly more expressive variable names. > From utente at esempio.net Wed May 19 16:30:56 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:30:56 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bf44a80$0$31377$4fafbaef@reader1.news.tin.it> Ren? 'Necoro' Neumann ha scritto: > Am 19.05.2010 21:58, schrieb superpollo: >> ... how many positive integers less than n have digits that sum up to m: >> >> In [197]: def prttn(m, n): >> tot = 0 >> for i in range(n): >> s = str(i) >> sum = 0 >> for j in range(len(s)): >> sum += int(s[j]) >> if sum == m: >> tot += 1 >> return tot >> .....: >> >> In [207]: prttn(25, 10000) >> Out[207]: 348 >> >> any suggestion for pythonizin' it? >> >> bye > > An idea would be: > >>>> def prttn(m, n): > ... return sum(1 for x in range(n) if sum(map(int, str(x))) == m) TypeError: 'int' object is not callable on 2.5.4 > > A small oneliner :) > > (I first had "return len([x for x in ...])" but the above avoids > creating an intermediate list) > > - Ren? > From news1234 at free.fr Wed May 19 16:32:14 2010 From: news1234 at free.fr (News123) Date: Wed, 19 May 2010 22:32:14 +0200 Subject: Installing Lightweight Python In-Reply-To: <5b9dd21e-43c7-4603-90a7-51299e1a599b@f13g2000vbm.googlegroups.com> References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com> <5b9dd21e-43c7-4603-90a7-51299e1a599b@f13g2000vbm.googlegroups.com> Message-ID: <4bf44ace$0$20283$426a34cc@news.free.fr> Nima Mohammadi wrote: > Well, I tried to run Python with -v option. It seems that python26.zip > is partially loaded but can't be used, because zlib is "unavailable". This is normal. the zip library itself cannot be zipped, as it is needed to unzip and extract th other libs. > > nima at nima-desktop:~/py$ ./bin/python -v > Could not find platform independent libraries > Could not find platform dependent libraries > Consider setting $PYTHONHOME to [:] > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > # zipimport: found 2509 names in /home/nima/py/lib/python26.zip > # zipimport: zlib UNAVAILABLE > 'import site' failed; traceback: > zipimport.ZipImportError: can't decompress data; zlib not available > # zipimport: zlib UNAVAILABLE > > Python 2.6.5 (r265:79063, May 17 2010, 18:36:54) > [GCC 4.4.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.path > ['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/', > '/home/nima/py/lib/python2.6/plat-linux2', '/home/nima/py/lib/ > python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old', '/home/nima/ > py/lib/lib-dynload'] > > > -- > Yours sincerely, > Nima Mohammadi From malaclypse2 at gmail.com Wed May 19 16:46:43 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 19 May 2010 16:46:43 -0400 Subject: function that counts... In-Reply-To: <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: On Wed, May 19, 2010 at 4:25 PM, superpollo wrote: > Jerry Hill ha scritto: >> ? ? ? ?sumofdigits = sum(int(char) for char in str(testval)) > > this line gives me this: > > TypeError: 'int' object is not callable > > is it some new feature in >2.5 ? No, sum() has been a builtin since Python 2.3. Based on your first post, you have probably shadowed the builtin "sum" function by assigning an integer to a variable named "sum". -- Jerry From dickinsm at gmail.com Wed May 19 16:48:46 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 19 May 2010 13:48:46 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf44a80$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <325e30b0-f7d4-4bed-9da8-d5b1e4fe0c5a@p17g2000vbe.googlegroups.com> On May 19, 9:30?pm, superpollo wrote: > Ren? 'Necoro' Neumann ha scritto: > > An idea would be: > > >>>> def prttn(m, n): > > ... ? ? ? ?return sum(1 for x in range(n) if sum(map(int, str(x))) == m) > > TypeError: 'int' object is not callable > > on 2.5.4 The TypeError is almost certainly because you've created a integer 'sum' variable in your script/interpreter session, hiding the built-in sum function. -- Mark From utente at esempio.net Wed May 19 16:58:22 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:58:22 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bf450ef$0$31372$4fafbaef@reader1.news.tin.it> Jerry Hill ha scritto: > On Wed, May 19, 2010 at 4:25 PM, superpollo wrote: >> Jerry Hill ha scritto: >>> sumofdigits = sum(int(char) for char in str(testval)) >> this line gives me this: >> >> TypeError: 'int' object is not callable >> >> is it some new feature in >2.5 ? > > No, sum() has been a builtin since Python 2.3. Based on your first > post, you have probably shadowed the builtin "sum" function by > assigning an integer to a variable named "sum". o my... thanks! In [266]: del(sum) In [267]: def prttn2(m, n): """How many positive integers less than n have digits that sum up to m""" total = 0 for testval in range(n): sumofdigits = sum(int(char) for char in str(testval)) if sumofdigits == m: total += 1 return total .....: In [275]: def prttn3(m, n): return sum(1 for x in range(n) if sum(map(int, str(x))) == m) .....: In [277]: prttn(25, 10000) Out[277]: 348 In [278]: prttn2(25, 10000) Out[278]: 348 In [279]: prttn3(25, 10000) Out[279]: 348 ok, bye! From utente at esempio.net Wed May 19 16:58:40 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:58:40 +0200 Subject: function that counts... In-Reply-To: <325e30b0-f7d4-4bed-9da8-d5b1e4fe0c5a@p17g2000vbe.googlegroups.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf44a80$0$31377$4fafbaef@reader1.news.tin.it> <325e30b0-f7d4-4bed-9da8-d5b1e4fe0c5a@p17g2000vbe.googlegroups.com> Message-ID: <4bf45101$0$31372$4fafbaef@reader1.news.tin.it> Mark Dickinson ha scritto: > On May 19, 9:30 pm, superpollo wrote: >> Ren? 'Necoro' Neumann ha scritto: >>> An idea would be: >>>>>> def prttn(m, n): >>> ... return sum(1 for x in range(n) if sum(map(int, str(x))) == m) >> TypeError: 'int' object is not callable >> >> on 2.5.4 > > The TypeError is almost certainly because you've created a integer > 'sum' variable in your script/interpreter session, hiding the built-in > sum function. thx From doesnotexist at franzoni.invalid Wed May 19 17:27:50 2010 From: doesnotexist at franzoni.invalid (Alan Franzoni) Date: Wed, 19 May 2010 21:27:50 GMT Subject: abc for generators? In-Reply-To: References: Message-ID: On 5/19/10 7:24 PM, Carl Banks wrote: > collections.Iterator That would just support the next() method. But enhanced generators interface - supporting coroutines as well - include send(), throw() and close(). -- Alan Franzoni contact me at public@[mysurname].eu From lists at necoro.eu Wed May 19 17:31:51 2010 From: lists at necoro.eu (=?UTF-8?B?UmVuw6kgJ05lY29ybycgTmV1bWFubg==?=) Date: Wed, 19 May 2010 23:31:51 +0200 Subject: function that counts... In-Reply-To: <4bf450ef$0$31372$4fafbaef@reader1.news.tin.it> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> <4bf450ef$0$31372$4fafbaef@reader1.news.tin.it> Message-ID: <4BF458C7.6090200@necoro.eu> Am 19.05.2010 22:58, schrieb superpollo: > > In [277]: prttn(25, 10000) > Out[277]: 348 > > In [278]: prttn2(25, 10000) > Out[278]: 348 > > In [279]: prttn3(25, 10000) > Out[279]: 348 > > ok, bye! Just because I was curios: necoro at Zakarumiy ~ % python -m timeit "import test; test.prttn(25,10000)" 10 loops, best of 3: 108 msec per loop necoro at Zakarumiy ~ % python -m timeit "import test; test.prttn2(25,10000)" 10 loops, best of 3: 157 msec per loop necoro at Zakarumiy ~ % python -m timeit "import test; test.prttn3(25,10000)" 10 loops, best of 3: 137 msec per loop Note: This is probably not representative ... just a quick check to get a raw feeling. - Ren? -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From steve-REMOVE-THIS at cybersource.com.au Wed May 19 17:45:44 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 May 2010 21:45:44 GMT Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> <4bf450ef$0$31372$4fafbaef@reader1.news.tin.it> Message-ID: <4bf45c08$0$8837$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 22:58:22 +0200, superpollo wrote: > In [266]: del(sum) del is a statement, not a function, so the brackets are pointless. This is like writing: x = (1) instead of x = 1 `del sum` is all you need. -- Steven From steve-REMOVE-THIS at cybersource.com.au Wed May 19 17:51:23 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 May 2010 21:51:23 GMT Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: > ... how many positive integers less than n have digits that sum up to m: > > In [197]: def prttn(m, n): Does the name "prttn" mean anything? I'm afraid I keep reading it as a mispelling of "print n". [...] > s = str(i) > sum = 0 > for j in range(len(s)): > sum += int(s[j]) Rather than iterating over an index j = 0, 1, 2, ... and then fetching the jth character of the string, you can iterate over the characters directly. So the inner loop is better written: for c in s: sum += int(c) -- Steven From leehwasoo at gmail.com Wed May 19 17:53:40 2010 From: leehwasoo at gmail.com (Back9) Date: Wed, 19 May 2010 14:53:40 -0700 (PDT) Subject: struct Message-ID: <8a4bba29-b5ca-49ed-806f-9e7a87f28ecf@u7g2000vbq.googlegroups.com> Can anyone explain the difference between f and d in struct unpack? When using them, some data work in either one not both. To me it seems to be same, TIA From gherron at islandtraining.com Wed May 19 18:07:41 2010 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 19 May 2010 15:07:41 -0700 Subject: struct In-Reply-To: <8a4bba29-b5ca-49ed-806f-9e7a87f28ecf@u7g2000vbq.googlegroups.com> References: <8a4bba29-b5ca-49ed-806f-9e7a87f28ecf@u7g2000vbq.googlegroups.com> Message-ID: <4BF4612D.3070201@islandtraining.com> On 05/19/2010 02:53 PM, Back9 wrote: > Can anyone explain the difference between f and d in struct unpack? > When using them, some data work in either one not both. > To me it seems to be same, > > TIA > 'f' is single precision float (32 bits), and 'd' is a double precision float (64 bits) Gary Herron From iurisilvio at gmail.com Wed May 19 18:12:30 2010 From: iurisilvio at gmail.com (Iuri) Date: Wed, 19 May 2010 19:12:30 -0300 Subject: compile() error Message-ID: >>> compile("for i in [1,2,3]:\n pass\n#end\n", "test_file.py", "exec") at 0x266a378, file "test_file.py", line 1> >>> compile("for i in [1,2,3]:\n pass\n#end", "test_file.py", "exec") Traceback (most recent call last): File "", line 1, in File "", line 2, in cptest File "test_file.py", line 3 #end ^ SyntaxError: invalid syntax I guess these commands explain the problem. Any ideas about what is happening? Regards, iuri -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin at python.org Wed May 19 18:31:31 2010 From: benjamin at python.org (Benjamin Peterson) Date: Wed, 19 May 2010 22:31:31 +0000 (UTC) Subject: compile() error References: Message-ID: Iuri gmail.com> writes: > Any ideas about what is happening? Until Python 2.7/3.2, compile() does't like sources which don't end in a newline. From vincent at vincentdavis.net Wed May 19 18:35:42 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Wed, 19 May 2010 16:35:42 -0600 Subject: Python Script for Website Mirroring In-Reply-To: References: Message-ID: Probably need a little more info to help. Are you running both sites, are there database involved....? If it is a simple site you could just transfer with ftp and have the script updated any urls. Vincent On Wed, May 19, 2010 at 8:21 AM, Kevin Rea wrote: > Hello Folks: > > Can you please point me to a decent Python script(s) that I could customize > to do automatic Website mirroring? > > Thanks Much! > Kevin > > -- > http://mail.python.org/mailman/listinfo/python-list > > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From iurisilvio at gmail.com Wed May 19 18:39:42 2010 From: iurisilvio at gmail.com (Iuri) Date: Wed, 19 May 2010 19:39:42 -0300 Subject: compile() error In-Reply-To: References: Message-ID: Thanks, Benjamin. I used Python 2.6 to these tests. []s iuri On Wed, May 19, 2010 at 7:31 PM, Benjamin Peterson wrote: > Iuri gmail.com> writes: > > Any ideas about what is happening? > > Until Python 2.7/3.2, compile() does't like sources which don't end in a > newline. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cmertes at techfak.uni-bielefeld.de Wed May 19 18:49:34 2010 From: cmertes at techfak.uni-bielefeld.de (Christian Mertes) Date: Thu, 20 May 2010 00:49:34 +0200 Subject: Python Script for Website Mirroring In-Reply-To: References: Message-ID: <1274309374.7713.300.camel@Inara> On Mi, 2010-05-19 at 16:35 -0600, Vincent Davis wrote: > If it is a simple site you could just transfer with ftp Or rsync -a or wget -m ... like tools that were specifically made for this task. Therefore something like subprocess.call(["rsync", "-az", "-e", "ssh", "--delete", source, target]) should be part of your Python script I guess ;) Regards, Christian -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 185 bytes Desc: This is a digitally signed message part URL: From kaklis at gmail.com Wed May 19 18:54:01 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Wed, 19 May 2010 15:54:01 -0700 (PDT) Subject: client server console app with cmd library Message-ID: <5577f90a-e8d9-43b4-bad5-9a10b17a2fdd@e28g2000vbd.googlegroups.com> Hi to all, i need some hints about a console application i' m trying. I want to make it act as a client and as a server at a same time. And since it is a console application i' m using cmd library. I want something that works like asterisk. while working with my app i want to listen for incoming requests, that they appear automatically at my console. Any design considerations? Do i have to use threads? Please i want your advice. Any examples somewhere? Thanks in advance! Antonis From rhodri at wildebst.demon.co.uk Wed May 19 19:27:24 2010 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 20 May 2010 00:27:24 +0100 Subject: What's the matter with docs.python.org? References: Message-ID: On Wed, 19 May 2010 17:23:18 +0100, Christian Mertes wrote: > I reported docs.python.org as a broken page to the Opera devs but I'm > also Ccing this > mail to the server admin because this seems to be a more complex problem > than just > a broken (if at all) web browser. It's been working fine for me, using Opera on Window and Ubuntu, for the last week or so. -- Rhodri James *-* Wildebeeste Herder to the Masses From aahz at pythoncraft.com Wed May 19 19:41:10 2010 From: aahz at pythoncraft.com (Aahz) Date: 19 May 2010 16:41:10 -0700 Subject: Classes and threading References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> <85hla5FjqlU2@mid.individual.net> Message-ID: In article , Christian Heimes wrote: >> >> class nThread(threading.Thread): >> def __init__(self, *args, **kwds): >> threading.Thread.__init__(self, *args, **kwds) >> # your other stuff here > >Since Thread is a new style class, this should read: > >class NThread(threading.thread): > def __init__(self, *args, **kwargs): > super(NThread, self).__init__(*args, **kwargs) "Should" is too strong. There are plenty of reasons for wanting to avoid the mess of super(). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From aahz at pythoncraft.com Wed May 19 19:42:49 2010 From: aahz at pythoncraft.com (Aahz) Date: 19 May 2010 16:42:49 -0700 Subject: What's the matter with docs.python.org? References: Message-ID: In article , Christian Mertes wrote: > > $ telnet docs.python.org 80 > Trying 2001:888:2000:d::a2... > Trying 82.94.164.162... > Connected to docs.python.org. > Escape character is '^]'. IPv6 has sometimes been problematical -- try disabling it. Also, I think you need to pass the host HTTP header to access docs.python.org -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From jurgen.erhard at gmail.com Wed May 19 19:58:59 2010 From: jurgen.erhard at gmail.com (=?UTF-8?Q?J=C3=BCrgen_Erhard?=) Date: Thu, 20 May 2010 01:58:59 +0200 Subject: KaPy -- Karlsruhe Python User Group meeting, 2010-05-21, 19:00 Message-ID: The Karlsruhe Python User Group (KaPy) meets again. Friday, 2010-04-16 (May 21st) at 19:00 (7pm) in the rooms of Entropia eV (the local affiliate of the CCC). See http://entropia.de/wiki/Anfahrt on how to get there. For your calendars: meetings are held monthly, on the 3rd Friday. Bye, J PS: Sorry for the late announcement. From pavlovevidence at gmail.com Wed May 19 20:04:16 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 19 May 2010 17:04:16 -0700 (PDT) Subject: abc for generators? References: Message-ID: <84f37e28-76aa-4b86-918d-d52d3860b180@c13g2000vbr.googlegroups.com> On May 19, 2:27?pm, Alan Franzoni wrote: > On 5/19/10 7:24 PM, Carl Banks wrote: > > > collections.Iterator > > That would just support the next() method. But enhanced generators > interface - supporting coroutines as well - include send(), throw() and > close(). Hmm, don't know. Maybe you could contribute one, it sounds like a rather unobjectionable idea likely to be accepted into Python. Carl Banks From tjreedy at udel.edu Wed May 19 20:09:23 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 May 2010 20:09:23 -0400 Subject: ipython question In-Reply-To: <4bf446b4$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> <4bf446b4$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: On 5/19/2010 4:14 PM, superpollo wrote: >> In [219]: %save tmp.py 218 >> File `tmp.py` exists. Overwrite (y/[N])? y >> The following commands were written to file `tmp.py`: >> def f(): >> return 42 >> >> >> In [220]: !cat tmp.py >> def f(): >> return 42 >> >> In [221]: %psource f >> No source found for f > > maybe i got it: > > In [230]: import tmp > > In [231]: %psource tmp.f > def f(): > return 42 I use IDLE, write functions and other code as desired in a temp file to begin with, hit F5, and the window with source stays around until closef it and the file until deleted. From steve-REMOVE-THIS at cybersource.com.au Wed May 19 20:52:06 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 20 May 2010 00:52:06 GMT Subject: compile() error References: Message-ID: <4bf487b5$0$8837$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 22:31:31 +0000, Benjamin Peterson wrote: > Iuri gmail.com> writes: >> Any ideas about what is happening? > > Until Python 2.7/3.2, compile() does't like sources which don't end in a > newline. Are you sure about that? >>> x = compile("print __import__('sys').version, 'see ma, no newline'", "", "single") >>> exec x 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] see ma, no newline The original post isn't showing up for me, so I don't know the full context, but it seems to me that compile can deal with the lack of newline. >>> x = compile("""import sys ... print sys.version ... print 'see ma, still no final newline!'""", "", "exec") >>> exec x 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] see ma, still no final newline! -- Steven From Eric_Dexter at msn.com Wed May 19 20:57:22 2010 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Wed, 19 May 2010 17:57:22 -0700 (PDT) Subject: links button gone from python.org Message-ID: <290f2f31-0893-469a-a12c-49eff9ffbf6f@y21g2000vba.googlegroups.com> I noticed that that the link to that section is gone. The page seems to be there when I use the url that is stored on my computer. Unrelated but I will mention that It is sad to see that dr dobs python newsletter has vanished, I enjoyed reading that from time to time. From iurisilvio at gmail.com Wed May 19 21:06:14 2010 From: iurisilvio at gmail.com (Iuri) Date: Wed, 19 May 2010 22:06:14 -0300 Subject: compile() error In-Reply-To: <4bf487b5$0$8837$c3e8da3@news.astraweb.com> References: <4bf487b5$0$8837$c3e8da3@news.astraweb.com> Message-ID: Steven, it works fine to some cases. I have problem only when last line is a comment and before it I have an indentation. It is a specific case, and it is not a common case. >>> compile("for i in [1,2,3]:\n pass\n#end", "test_file.py", "exec") What I understanded about Benjamin's answer is compile() without a new line at the end has an indetermined behaviour, so in some cases it works. Iuri de Silvio On Wed, May 19, 2010 at 9:52 PM, Steven D'Aprano < steve-REMOVE-THIS at cybersource.com.au> wrote: > On Wed, 19 May 2010 22:31:31 +0000, Benjamin Peterson wrote: > > > Iuri gmail.com> writes: > >> Any ideas about what is happening? > > > > Until Python 2.7/3.2, compile() does't like sources which don't end in a > > newline. > > > Are you sure about that? > > > >>> x = compile("print __import__('sys').version, 'see ma, no newline'", > "", "single") > >>> exec x > 2.5 (r25:51908, Nov 6 2007, 16:54:01) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] see ma, no newline > > > The original post isn't showing up for me, so I don't know the full > context, but it seems to me that compile can deal with the lack of > newline. > > > >>> x = compile("""import sys > ... print sys.version > ... print 'see ma, still no final newline!'""", "", "exec") > >>> exec x > 2.5 (r25:51908, Nov 6 2007, 16:54:01) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] > see ma, still no final newline! > > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Wed May 19 21:12:24 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 19 May 2010 21:12:24 -0400 Subject: compile() error In-Reply-To: <4bf487b5$0$8837$c3e8da3@news.astraweb.com> References: <4bf487b5$0$8837$c3e8da3@news.astraweb.com> Message-ID: On Wed, May 19, 2010 at 8:52 PM, Steven D'Aprano wrote: > On Wed, 19 May 2010 22:31:31 +0000, Benjamin Peterson wrote: >> Iuri gmail.com> writes: >>> Any ideas about what is happening? >> >> Until Python 2.7/3.2, compile() does't like sources which don't end in a >> newline. It appears to be this bug: http://bugs.python.org/issue1184112 which is still open. Maybe a fix got checked in without the bug being closed? I don't have 2.7 or 3.2 here to test with. > The original post isn't showing up for me, so I don't know the full > context, but it seems to me that compile can deal with the lack of > newline. The original example was: compile("for i in [1,2,3]:\n pass\n#end", "test_file.py", "exec") Bug 1184112 is only triggered with an indented block followed by a comment with no newline following the comment. -- Jerry From frank.zhu.mingyu at gmail.com Wed May 19 21:14:00 2010 From: frank.zhu.mingyu at gmail.com (frank zhu) Date: Wed, 19 May 2010 21:14:00 -0400 Subject: Fwd: question on logging module - solved Message-ID: FYI. ---------- Forwarded message ---------- From: Cameron Simpson Date: Wed, May 19, 2010 at 6:18 PM Subject: Re: question on logging module To: frank zhu On 19May2010 11:55, frank zhu wrote: | Thanks Cameron. That was the problem. I copied the sample code and named it | logging.py. which was bad. You might want to post this info to the list to save follow-on discussion. One way to check that what you want actually happened is like this: [/Users/cameron]g4*> python Python 2.6.5 (r265:79063, May 17 2010, 14:44:07) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> sorted(logging.__dict__.keys()) which will report the names in what you imported. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From Rick at home.com Wed May 19 21:35:03 2010 From: Rick at home.com (Rick at home.com) Date: Wed, 19 May 2010 21:35:03 -0400 Subject: Display file names in Tkinter Listbox Message-ID: Hello, My first attenpt at a simple python Tkinter application. I wanted to see how to load file names into a listbox from a menu. This is what I got until the part of displaying the file names in a listbox, which I could not figfure out how to do? Any help would be appreciated. Trying to do this as simple as possible to understand. The "print fileNames" does work but how to display it in listbox? from Tkinter import * from tkFileDialog import askopenfilenames class MyCode: def __init__(self): root = Tk() menubar = Menu(root) filemenu = Menu(menubar) lbox = Listbox(root, width=50).pack() menubar.add_cascade(label='File', menu=filemenu) filemenu.add_command(label='New Project') filemenu.add_command(label='Load Files...', command=self.OnLoad) filemenu.add_command(label='Exit', command=root.quit) root.config(menu=menubar) root.mainloop() def OnLoad(self): fileNames = askopenfilenames(filetypes=[('Split Files', '*')]) print fileNames myApp = MyCode() From chardster at gmail.com Wed May 19 21:36:22 2010 From: chardster at gmail.com (Richard Thomas) Date: Wed, 19 May 2010 18:36:22 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <75cf168b-9d67-4602-9201-774cc8dd48e9@z33g2000vbb.googlegroups.com> For this kind of problem you should avoid all that stringification. I find it best to deal with sequences of digits of a fixed length and go from there. For example: def count1(m, n, cache={}): """Number of digit sequences of length `n` summing to `m`.""" if n < 0 or m < 0: return 0 elif n == 0: return int(m == 0) elif (m, n) in cache: return cache[m, n] # This is an optimisation using the combinatoric choose function. #elif m < 10: # result = choose(n + m - 1, n - 1) else: result = 0 for digit in xrange(min(10, m + 1)): result += count1(m - digit, n - 1) cache[m, n] = result return result Notice the caching of results. With this we can compute the required thing quite easily: def count2(m, n): """Number of numbers less than `n` whose digits sum to `m`.""" result = 0 digits = map(int, str(n)) length = len(digits) for idx, digit in enumerate(digits): for seq_digit in xrange(digit): seq_limit = m - seq_digit seq_length = length - idx - 1 result += count1(seq_limit, seq_length) m -= digit return result Essentially we move through the number left to right, choose digits less than the digit in the number and count digit sequences to fill the remainder. Then fix the actual digit and step forward. An approach like this avoids the relatively slow stringification process and makes decent use of caching and iteration (both easy and efficient in Python). In [1]: count2(25, 10000) Out[1]: 348 In [2]: timeit count2(25, 10000) 100000 loops, best of 3: 12.6 us per loop From nobrac at nospam.tampabay.rr.com Wed May 19 22:27:39 2010 From: nobrac at nospam.tampabay.rr.com (Carbon) Date: 20 May 2010 02:27:39 GMT Subject: Newbie Alert: subprocess.call Message-ID: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> I am new to Python and am trying to write a GUI wrapper script in python 2.5 to get username and passwords from Linux users to send as options to run an app on a 2X terminal server. I came across the easygui module and its multpasswordbox function, which made popping a dialog box and storing the usernames very painless. However, subprocess.call as implemented below doesn't work. For some reason the "-s ts.mycompany.org:80" parameter is being interpreted differently by the application when sent from the python script than it does when sent from the BASH script below. The :80 is the default port so it isn't technically required, but the script doesn't work without it either. Any ideas where I should look? Is subprocess.call the best way to do what I want? Any advice would be most appreciated. Here's the broken bit: print "Reply was:", fieldValues print "Reply was:", fieldValues[0], fieldValues[1] subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u fieldValues [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d corp", "-S local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"]) Output: me at work:~/bin$ ./demo2.py Reply was: ['MyUsername', 'MyPassword'] Reply was: MyUsername MyPassword ERROR in CTcpConnector: ts.mycompany.org: unable to resolve host Error 7: TCP/IP connection: unable to resolve host. This BASH script runs correctly: me at work:~/bin$ cat 2xconnect #!/bin/bash USER=$1 PASS=$2 /opt/2X/Client/bin/appserverclient \ -u "$USER" \ -p "$PASS" \ -s ts.mycompany.org:80 \ -d corp \ -S local \ -c 16 \ -e 0xF \ -l 0x0409 \ -m 2G \ -a "#1" From pmaupin at gmail.com Wed May 19 22:38:07 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Wed, 19 May 2010 19:38:07 -0700 (PDT) Subject: Newbie Alert: subprocess.call References: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> Message-ID: On May 19, 9:27?pm, Carbon wrote: > I am new to Python and am trying to write a GUI wrapper script in python > 2.5 to get username and passwords from Linux users to send as options to > run an app on a 2X terminal server. I came across the easygui module and > its multpasswordbox function, which made popping a dialog box and storing > the usernames very painless. > > However, subprocess.call as implemented below doesn't work. For some > reason the "-s ts.mycompany.org:80" parameter is being interpreted > differently by the application when sent from the python script than it > does when sent from the BASH script below. The :80 is the default port so > it isn't technically required, but the script doesn't work without it > either. > > Any ideas where I should look? Is subprocess.call the best way to do what > I want? Any advice would be most appreciated. > > Here's the broken bit: > > print "Reply was:", fieldValues > print "Reply was:", fieldValues[0], fieldValues[1] > > subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u fieldValues > [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d corp", "-S > local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"]) > > Output: > > me at work:~/bin$ ./demo2.py > Reply was: ['MyUsername', 'MyPassword'] > Reply was: MyUsername MyPassword > > ERROR in CTcpConnector: ?ts.mycompany.org: unable to resolve host > Error 7: TCP/IP connection: unable to resolve host. > > This BASH script runs correctly: > me at work:~/bin$ cat 2xconnect > #!/bin/bash > > USER=$1 > PASS=$2 > > /opt/2X/Client/bin/appserverclient \ > -u "$USER" \ > -p "$PASS" \ > -s ts.mycompany.org:80 \ > -d corp \ > -S local \ > -c 16 \ > -e 0xF \ > -l 0x0409 \ > -m 2G \ > -a "#1" I think, for example, instead of "-d corp", you want "-d" and "corp" in your list. I usually make a string like I would pass to bash, and then do .split() on it to get the list. This works fine unless you need embedded spaces anywhere. Regards, Pat From ben+python at benfinney.id.au Wed May 19 23:28:12 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 20 May 2010 13:28:12 +1000 Subject: Newbie Alert: subprocess.call References: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> Message-ID: <87mxvvgskz.fsf@benfinney.id.au> Patrick Maupin writes: > On May 19, 9:27?pm, Carbon wrote: > > subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u > > fieldValues [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d > > corp", "-S local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"]) As Patrick says, you need to give the arguments to the command as the shell would pass them. That means option arguments separate from value arguments, etc. > I think, for example, instead of "-d corp", you want "-d" and "corp" > in your list. Right. > I usually make a string like I would pass to bash, and then do > .split() on it to get the list. This works fine unless you need > embedded spaces anywhere. Better is to use ?shlex.split? to split the string as a shell parser would do . -- \ ?Not using Microsoft products is like being a non-smoker 40 or | `\ 50 years ago: You can choose not to smoke, yourself, but it's | _o__) hard to avoid second-hand smoke.? ?Michael Tiemann | Ben Finney From python at bdurham.com Wed May 19 23:34:13 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 19 May 2010 23:34:13 -0400 Subject: How to unescape a raw string? Message-ID: <1274326453.19171.1375982237@webmail.messagingengine.com> How can I unescape a raw string so that it behaves as a non-raw string? For example, if I read the string "\n\t A B C\" D E F \xa0 \u1234" from a text file, how can I convert (unescape?) this string so that \n, \t, \", \x, and \u get converted to a newline, tab, double quote, hex encoded and unicode encoded chars? I know I can do this explictly via a series of .replace() methods, but certainly there must be a built-in way to do this on a generic basis? Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed May 19 23:36:32 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 19 May 2010 20:36:32 -0700 Subject: Newbie Alert: subprocess.call In-Reply-To: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> References: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> Message-ID: On Wed, May 19, 2010 at 7:27 PM, Carbon wrote: > I am new to Python and am trying to write a GUI wrapper script in python > 2.5 to get username and passwords from Linux users to send as options to > run an app on a 2X terminal server. I came across the easygui module and > its multpasswordbox function, which made popping a dialog box and storing > the usernames very painless. > > However, subprocess.call as implemented below doesn't work. For some > reason the "-s ts.mycompany.org:80" parameter is being interpreted > differently by the application when sent from the python script than it > does when sent from the BASH script below. The :80 is the default port so > it isn't technically required, but the script doesn't work without it > either. > > Any ideas where I should look? Is subprocess.call the best way to do what > I want? Any advice would be most appreciated. > > > Here's the broken bit: > > print "Reply was:", fieldValues > print "Reply was:", fieldValues[0], fieldValues[1] > > subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u fieldValues > [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d corp", "-S > local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"]) RTFineM (http://docs.python.org/library/subprocess.html#subprocess.Popen ). Verbatim quote, emphasis mine: >>> command_line = raw_input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print args ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success! ***Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements***, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements. Cheers, Chris -- http://blog.rebertia.com From jjposner at optimum.net Wed May 19 23:40:06 2010 From: jjposner at optimum.net (John Posner) Date: Wed, 19 May 2010 23:40:06 -0400 Subject: function that counts... In-Reply-To: <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> Message-ID: <4bf4af26$0$7594$607ed4bc@cv.net> On 5/19/2010 5:51 PM, Steven D'Aprano wrote: > On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: > > > Rather than iterating over an index j = 0, 1, 2, ... and then fetching > the jth character of the string, you can iterate over the characters > directly. So the inner loop is better written: > > for c in s: > sum += int(c) > Or, as a one-liner (and not shadowing the built-in *sum* function): mysum = sum(map(int, str(i))) -John From clp2 at rebertia.com Wed May 19 23:42:55 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 19 May 2010 20:42:55 -0700 Subject: How to unescape a raw string? In-Reply-To: <1274326453.19171.1375982237@webmail.messagingengine.com> References: <1274326453.19171.1375982237@webmail.messagingengine.com> Message-ID: On Wed, May 19, 2010 at 8:34 PM, wrote: > How can I unescape a raw string so that it behaves as a non-raw string? That's not what the notion of raw strings in Python technically means, but anyway... > For example, if I read the string "\n\t A B C\" D E F \xa0 \u1234" I'll assume you're quoting the file contents itself verbatim here, rather than a Python string literal (which would require doubling up on the backslashes). > from a > text file, how can I convert (unescape?) this string so that \n, \t, \", \x, > and \u get converted to a newline, tab, double quote, hex encoded and > unicode encoded chars? > > I know I can do this explictly via a series of .replace() methods, but > certainly there must be a built-in way to do this on a generic basis? new_string = your_string.decode('string_escape') Cheers, Chris -- http://blog.rebertia.com From python at bdurham.com Wed May 19 23:53:59 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 19 May 2010 23:53:59 -0400 Subject: Best practice for string substition with gettext Message-ID: <1274327639.21961.1375982987@webmail.messagingengine.com> Looking for best practice advice on what string substitution technique to use when using gettext(). Or do all techniques apply equally? I can think of at least 3 string techniques: 1. Classic "%" based formatting: "My name is %(name)s" % locals() 2. .format() based formatting: "My name is {name}".format( locals() ) 3. string.Template.safe_substitute() import string template = string.Template( "My name is ${name}" ) template.safe_substitute( locals() ) The advantage of the string.Template technique is that a translated string with with an incorrectly spelled variable reference can still yield a usable string value while the other techniques unconditionally raise an exception. The downside of the string.Template technique appears to be the inability for one to customize how a variable is formatted (padding, justification, width, etc). Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Thu May 20 00:13:28 2010 From: python at bdurham.com (python at bdurham.com) Date: Thu, 20 May 2010 00:13:28 -0400 Subject: How to unescape a raw string? In-Reply-To: References: <1274326453.19171.1375982237@webmail.messagingengine.com> Message-ID: <1274328808.24186.1375984875@webmail.messagingengine.com> Hi Chris, > That's not what the notion of raw strings in Python technically means, but anyway... Agree - I was having a difficult time trying to describe my dilemma - thanks for hanging in there with my rather awkward intro :) > I'll assume you're quoting the file contents itself verbatim here, rather than a Python string literal (which would require doubling up on the backslashes). Yes. > new_string = your_string.decode('string_escape') That's just the clue I needed. The actual decoder I needed turned out to be 'unicode_escape' because of my embedded \uxxxx markup. new_string = your_string.decode('unicode_escape') Thank you for your help Chris! Regards, Malcolm From pmaupin at gmail.com Thu May 20 00:29:29 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Wed, 19 May 2010 21:29:29 -0700 (PDT) Subject: Newbie Alert: subprocess.call References: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> <87mxvvgskz.fsf@benfinney.id.au> Message-ID: On May 19, 10:28?pm, Ben Finney wrote: > Better is to use ?shlex.split? to split the string as a shell parser > would do . Good point. I always forget about shlex.split because I'm usually passing (relatively) constant strings with no funny quoting. Regards, Pat From wuwei23 at gmail.com Thu May 20 00:40:19 2010 From: wuwei23 at gmail.com (alex23) Date: Wed, 19 May 2010 21:40:19 -0700 (PDT) Subject: help need to write a python spell checker References: <49bffe0f-00a7-47a2-a857-1c1e35ac8870@p17g2000vbe.googlegroups.com> Message-ID: <9450223d-70ab-4b57-9dc7-0a34016c64d8@11g2000prv.googlegroups.com> Patrick Maupin wrote: > Although it makes > perfect sense, I never really thought much about the possibility that > the school year would be "upside down" "down under"... Yes, having the school year run within the actual year instead of across two is such a topsy-turvy concept, it's pretty obvious the blood is constantly rushing to our heads ;) From jmcmonagle at NO.SPAM.velseis.com.au Thu May 20 01:36:59 2010 From: jmcmonagle at NO.SPAM.velseis.com.au (John McMonagle) Date: Thu, 20 May 2010 15:36:59 +1000 Subject: Display file names in Tkinter Listbox In-Reply-To: References: Message-ID: <4BF4CA7B.6000008@NO.SPAM.velseis.com.au> Rick at home.com wrote: > Hello, > > My first attenpt at a simple python Tkinter application. I wanted to > see how to load file names into a listbox from a menu. This is what I > got until the part of displaying the file names in a listbox, which I > could not figfure out how to do? > > Any help would be appreciated. Trying to do this as simple as possible > to understand. > > The "print fileNames" does work but how to display it in listbox? > > from Tkinter import * > from tkFileDialog import askopenfilenames > > class MyCode: > def __init__(self): > root = Tk() > > menubar = Menu(root) > filemenu = Menu(menubar) > > lbox = Listbox(root, width=50).pack() Your problem is the above line of code. Here you are assigning the return value of the pack (None if I recall). Later when you want to put things in the Listbox you don't have the widget reference anymore. It's probably a good idea to make the Listbox widget an attribute of your class so you can use it in class methods without having to pass it as an argument. So, change the above line of code to: self.lbox = Listbox(root, width=50) self.lbox.pack() > > menubar.add_cascade(label='File', menu=filemenu) > filemenu.add_command(label='New Project') > filemenu.add_command(label='Load Files...', command=self.OnLoad) > > > filemenu.add_command(label='Exit', command=root.quit) > > root.config(menu=menubar) > > root.mainloop() > > > def OnLoad(self): > fileNames = askopenfilenames(filetypes=[('Split Files', '*')]) > print fileNames > Now that you've got a reference to your Listbox widget that is an attribute of your class, you should be able to insert the file names into the Listbox like so. self.lbox.insert(0, fileNames) Regards, John From sanamsingh at hotmail.com Thu May 20 01:51:19 2010 From: sanamsingh at hotmail.com (sanam singh) Date: Thu, 20 May 2010 05:51:19 +0000 Subject: error importing numpy Message-ID: Hi, when i import numpy in python i get following error : Python 2.6.5 (r265:79063, May 2 2010, 10:47:11) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy Traceback (most recent call last): File "", line 1, in ImportError: No module named numpy however when i do sudo apt-get install python-numpy i get : Reading package lists... Done Building dependency tree Reading state information... Done python-numpy is already the newest version. 0 upgraded, 0 newly installed, 0 to remove and 118 not upgraded. please help me . Thanks. _________________________________________________________________ Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rogerb at rogerbinns.com Thu May 20 01:58:34 2010 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 19 May 2010 22:58:34 -0700 Subject: Loading C extension from memory In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/13/2010 06:14 AM, mk wrote: > I wonder if there is a way to load C extension from in-memory object, > not from the file on the disk? > > I'm asking bc I would like to download C extensions over network and > load them into Python interpreter (without storing the C extension in > file on the disk). You could download the C source over the network, compile and use that. It has the advantage of working on all platforms where you have a compiler so you wouldn't have to have the same extension compiled for Mac, Linux, Windows, 32 and 64 bit. If the local machine doesn't have a compiler you can even use libtcc or something newer. For example see this 3 year old page, as well as links at the bottom: http://www.cs.tut.fi/~ask/cinpy/ Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iEYEARECAAYFAkv0z4UACgkQmOOfHg372QQ1UQCg2+ODiHMzi36//gG3gK6j4Uib 2u8AoMI2LXU7BFYa7Jn5b+vF42/EnNYU =RWO+ -----END PGP SIGNATURE----- From lists at cheimes.de Thu May 20 02:17:26 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 May 2010 08:17:26 +0200 Subject: Loading C extension from memory In-Reply-To: References: Message-ID: mk wrote: > I wonder if there is a way to load C extension from in-memory object, > not from the file on the disk? No, that's not possible since Python depends on the operating system. A lot of operating systems require a physical file to load the shared library from. Python uses dlopen() on most Un*x platforms and LoadLibraryEx() on Windows. From cmertes at techfak.uni-bielefeld.de Thu May 20 02:19:07 2010 From: cmertes at techfak.uni-bielefeld.de (Christian Mertes) Date: Thu, 20 May 2010 08:19:07 +0200 Subject: What's the matter with docs.python.org? In-Reply-To: References: Message-ID: <1274336347.4612.40.camel@Inara> On Mi, 2010-05-19 at 16:42 -0700, Aahz wrote: > > IPv6 has sometimes been problematical -- try disabling it. Wow, can I have that on a t-shirt? ;) > Also, I think you need to pass the host HTTP header to access > docs.python.org Look, I don't really want to read Python docs via telnet. I basically wanted to point out that there is strange behaviour and someone might feel responsible and look into it. Unfortunately the webmaster at docs.python.org address doesn't seem to work which might be explained by the fact that there is no mx record for this domain. Anyway, it currently works with both Opera and I-sit-in-Siberia-style telnet. Have a nice day, Christian PS: I think I'll get off the list again because with my broken evolution mail filters it's just too much traffic. So if there should be another reply, please put me in the Cc. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 185 bytes Desc: This is a digitally signed message part URL: From gherron at islandtraining.com Thu May 20 02:30:50 2010 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 19 May 2010 23:30:50 -0700 Subject: How to unescape a raw string? In-Reply-To: <1274326453.19171.1375982237@webmail.messagingengine.com> References: <1274326453.19171.1375982237@webmail.messagingengine.com> Message-ID: <4BF4D71A.6030201@islandtraining.com> On 05/19/2010 08:34 PM, python at bdurham.com wrote: > How can I unescape a raw string so that it behaves as a non-raw string? > For example, if I read the string "\n\t A B C\" D E F \xa0 \u1234" > from a text file, how can I convert (unescape?) this string so that > \n, \t, \", \x, and \u get converted to a newline, tab, double quote, > hex encoded and unicode encoded chars? > I know I can do this explictly via a series of .replace() methods, but > certainly there must be a built-in way to do this on a generic basis? > Thank you, > Malcolm That question makes no sense -- a string is a string is a string in Python. The syntax you use to specify the string (for instance, raw or not, hex characters or not, or one or another quote choice) is irrelevant and completely forgotten once the string is internal. No need to use replace, the \n is already stored as a newline, and the \t as a tab and so on. Various methods of output may or may not convert those characters back into \n and \t and so on. But that's a matter of output not internal storage. So tell us what you're trying to accomplish -- and better also tell us Python2 or Python3? Gary Herron -------------- next part -------------- An HTML attachment was scrubbed... URL: From cosmeticsafrolatino003 at gmail.com Thu May 20 02:51:54 2010 From: cosmeticsafrolatino003 at gmail.com (cosmeticsafrolatino) Date: Wed, 19 May 2010 23:51:54 -0700 (PDT) Subject: helo Message-ID: hi From jimmy.cullen at gmail.com Thu May 20 03:37:20 2010 From: jimmy.cullen at gmail.com (Jimoid) Date: Thu, 20 May 2010 00:37:20 -0700 (PDT) Subject: Reading data from a Microsoft Access 2003 database References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> <4bf3eeeb$0$31263$607ed4bc@cv.net> Message-ID: <3c40f8d8-b29c-484f-b5b3-6dff0f68a032@m21g2000vbr.googlegroups.com> Thanks to all for your helpful suggestions. So far I have installed and played around with mdbtools, and it appears that I can use this from the shell to extract the information I need, e.g. mdb-export for dumping an entire table or mdb-sql to run a query. I am also interested by mxODBC and pyodbc as these seem to be python only solutions, so could be useful for platform independent python solutions (it may be that my programme will be used by some Windows users, if it is successful). To give it a bit of context, I am extracting data from the on-board flight planning software from an aerial survey plane (the Access database). I will extract the GPS data for each image taken so that I can then georeference the images. Cheers, Jimmy From martin.hellwig at dcuktec.org Thu May 20 03:39:05 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 20 May 2010 08:39:05 +0100 Subject: 250 In-Reply-To: References: Message-ID: On 05/20/10 07:51, cosmeticsafrolatino wrote: > hi 250 locahost.local Hello WimaxUser3645-219.wateen.net [110.36.45.219], pleased to meet you From jimmy.cullen at gmail.com Thu May 20 05:45:10 2010 From: jimmy.cullen at gmail.com (Jimoid) Date: Thu, 20 May 2010 02:45:10 -0700 (PDT) Subject: Reading data from a Microsoft Access 2003 database References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> <4bf3eeeb$0$31263$607ed4bc@cv.net> <3c40f8d8-b29c-484f-b5b3-6dff0f68a032@m21g2000vbr.googlegroups.com> Message-ID: <16c9daac-293a-4cb6-b847-489e696682bd@c11g2000vbe.googlegroups.com> I've now had a closer look at both pyODBC and mxODBC and it seems to me that they both require the database to be running to be able to query it. Is this correct? If so I think I will have to use mdb-* as the database I want to query is not running. Cheers, Jimmy From t.lehmann at rtsgroup.net Thu May 20 05:49:06 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Thu, 20 May 2010 02:49:06 -0700 (PDT) Subject: intervall of about 1 second for xmlrpc calls? Message-ID: Hi, I'm wondering about the behavior. Running this example - it looks like - that each rpc call is triggered in a visible interval (about one second). What's wrong? Thomas APPENDIX: import threading from xmlrpc.server import SimpleXMLRPCServer import xmlrpc.client class MyServer(threading.Thread): def __init__(self, host, port): threading.Thread.__init__(self) self.server = SimpleXMLRPCServer((host, port)) self.server.register_function(self.is_even, "is_even") self.server.register_function(self.stop, "stop_server") def run(self): print("server: waiting for requests...") self.server.serve_forever() print("server: is down.") def stop(self): print("server: shutdown requested...") self.stoptimer = threading.Timer(1, self.server.shutdown) self.stoptimer.start() return "done." def is_even(self, n): print("server: check %d to be even" % (n)) return n%2 == 0 # server as thread server = MyServer("localhost", 1234) server.start() # client code serverProxy = xmlrpc.client.ServerProxy("http://localhost:1234") for n in range(1,2+1): print("%d is %s" % (n, ["odd", "even"][serverProxy.is_even(n)])) serverProxy.stop_server() From apardon at forel.vub.ac.be Thu May 20 06:07:51 2010 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 May 2010 10:07:51 GMT Subject: Transferring an exception from one thread to an other. Message-ID: I have a numver of tarfiles on a remote host that I need to process and that I fetch via FTP. I wrote the following as a test to see how I would best approach this. (I'm using python 2.5) -------------------------------- ftptst1 -------------------------------- import tarfile as tar from ftplib import FTP, error_perm as FTPError, error_temp as FTPProblem from socket import error as SocketError ftp = FTP(host, user, password) def gettarfile(rfn): import tempfile tfl = tempfile.TemporaryFile() ftp.retrbinary("RETR %s" % (rfn,), tfl.write) tfl.seek(0) return tar.open(mode = "r:bz2", fileobj = tfl) def process(): for rfn in ("testfile.tbz", "nosuchfile"): try: tf = gettarfile(rfn) for tarinfo in tf: print tarinfo.name print except Exception: print "Something went wrong with '%s'" % rfn process() ------------------------------------------------------------------------- Executing this gives me this result: testfile/ testfile/tstfl.0 Something went wrong with 'nosuchfile' However the tarfile can be to big to store localy. That is why I rewrote the above as follows: -------------------------------- ftptst2 -------------------------------- import tarfile as tar from ftplib import FTP, error_perm as FTPError, error_temp as FTPProblem from socket import error as SocketError ftp = FTP("nestor", "apardon", "0nZM,F!m") def connect(lfl, rfn): ftp.retrbinary("RETR %s" % (rfn,), lfl.write) lfl.close() def gettarfile(rfn): import os, threading rfd, wfd = os.pipe() wfl = os.fdopen(wfd, "w") rfl = os.fdopen(rfd, "r") xfer = threading.Thread(target = connect, args = (wfl, rfn)) xfer.setDaemon(True) xfer.start() return tar.open(mode = "r|bz2", fileobj = rfl) def process(): for rfn in ("testfile.tbz", "nosuchfile"): try: tf = gettarfile(rfn) for tarinfo in tf: print tarinfo.name print except Exception: print "Something went wrong with '%s'" % rfn process() ------------------------------------------------------------------------- Executing this new test gives this result: testfile/ testfile/tstfl.0 Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner self.run() File "/usr/lib/python2.5/threading.py", line 446, in run self.__target(*self.__args, **self.__kwargs) File "ftptst2", line 10, in connect ftp.retrbinary("RETR %s" % (rfn,), lfl.write) File "/usr/lib/python2.5/ftplib.py", line 390, in retrbinary conn = self.transfercmd(cmd, rest) File "/usr/lib/python2.5/ftplib.py", line 356, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "/usr/lib/python2.5/ftplib.py", line 327, in ntransfercmd resp = self.sendcmd(cmd) File "/usr/lib/python2.5/ftplib.py", line 241, in sendcmd return self.getresp() File "/usr/lib/python2.5/ftplib.py", line 216, in getresp raise error_perm, resp error_perm: 550 nosuchfile: No such file or directory. Now I totally understand what is happening. What is less clear is how best to fix ftptst2, so that it behaves like ftptst1 in case of ftp problems. I know about the PyThreadState_SetAsyncExc function; would this be an acceptable solution here by catching the excption in the xfer/connect thread and raising them in the main thread? Is there an other possibility of combining ftplib and tarfile, that doesn't need threads but also doesn't need to store the remote file locally? Any other suggestion? -- Antoon Pardon From t.lehmann at rtsgroup.net Thu May 20 06:40:46 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Thu, 20 May 2010 03:40:46 -0700 (PDT) Subject: intervall of about 1 second for xmlrpc calls? References: Message-ID: > What's wrong? > Obviously there's a problem with "localhost". When using the IP of my machine everything is working fast. From t.lehmann at rtsgroup.net Thu May 20 06:58:57 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Thu, 20 May 2010 03:58:57 -0700 (PDT) Subject: Problem with an huge dictionary References: Message-ID: <70b8f82e-2dfe-4403-ae77-cb4d005578f1@y12g2000vbr.googlegroups.com> > > The question is: > Is there a limit on the number of entries a dictionary can have i > jython? > > I wrote a little app where my data is stored in a huge dictionary > (11746 entries) generated with a python script. > When I try to import the dictionary, jython complains with the > following message: > 1) You did not say what you have saved (content of your dictionary). 2) You did not say how you have saved. >From the callstack - also I have never used jython - it looks like that there is a try to create a class. It looks like - I may be wrong - that you have saved user objects in your dictionary - have you? If so you might fail on loading those objects - especially when your program does not have the code for it. More details are required... From nobody at nowhere.nil Thu May 20 07:02:53 2010 From: nobody at nowhere.nil (Christian Stapfer) Date: Thu, 20 May 2010 13:02:53 +0200 Subject: Drawing glyphs based on their index (NOT their character code) Message-ID: Here's an interesting little problem: I am given a master.ttf font file and a subset file subset.ttf of that font, and I am asked to map indices of all the glyphs in subset.ttf to the corresponding indices in master.ttf. The subset font file is the result of a pipeline of 3 tools (pdflatex, Adobe Reader, and the Microsoft XPS Document Writer). The resulting document format (XAML) holds indices into subset.ttf, and in order to display that document with reference to master.ttf, I need to do this mapping of indices: subset -> master. (Carrying subset.ttf along with the XAML code is not an option, I think, because I need to be able to support copy and paste of small snippets from that document through a shared whiteboard.) I have tried to parse the two font files to the point of having the x- and y-coordinate points of the outlines of glyphs handy. But, unfortunately, subset.ttf has been processed in a way that makes it very difficult to compare its glyph outlines with the outlines of glyphs in master.ttf. So my next best idea is to draw the various glyphs as, 16x16 B/W images, say, and use the 16*16 bits (that is, 16 ints or 8 longs) that result from this as a sufficiently precise description of the glyph to do the necessary comparisons. PIL would be great for this, except for one "little" problem: I need to be able to draw glyphs based on their index, not based on their character code. Any ideas to get around that limitation of PIL's drawing primitives? Thanks in advance, Christian From sanamsingh at hotmail.com Thu May 20 07:45:37 2010 From: sanamsingh at hotmail.com (sanam singh) Date: Thu, 20 May 2010 11:45:37 +0000 Subject: Error regarding numpy Message-ID: hi, when i import numpy i get following error >>> import numpy Traceback (most recent call last): File "/usr/lib/wingide-personal3.2/src/debug/tserver/_sandbox.py", line 1, in # Used internally for debug sandbox under external interpreter File "/usr/lib/python2.6/dist-packages/numpy/__init__.py", line 130, in import add_newdocs File "/usr/lib/python2.6/dist-packages/numpy/add_newdocs.py", line 9, in from lib import add_newdoc File "/usr/lib/python2.6/dist-packages/numpy/lib/__init__.py", line 152, in from type_check import * File "/usr/lib/python2.6/dist-packages/numpy/lib/type_check.py", line 8, in import numpy.core.numeric as _nx File "/usr/lib/python2.6/dist-packages/numpy/core/__init__.py", line 5, in import multiarray ImportError: /usr/lib/python2.6/dist-packages/numpy/core/multiarray.so: undefined symbol: _PyUnicodeUCS4_IsWhitespace please help me. Cheers _________________________________________________________________ Hotmail: Free, trusted and rich email service. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From awilliam at whitemice.org Thu May 20 07:51:14 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Thu, 20 May 2010 07:51:14 -0400 Subject: intervall of about 1 second for xmlrpc calls? In-Reply-To: References: Message-ID: <1274356274.7639.1.camel@linux-yu4c.site> On Thu, 2010-05-20 at 03:40 -0700, Thomas Lehmann wrote: > > What's wrong? > Obviously there's a problem with "localhost". When using the IP of my > machine everything is working fast. You box may first be trying to connect to ::1 (ipv6) and when that fails it falls back to 127.0.0.1. Make sure IPv6 is properly configured/enabled and try the script again. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From mftian at gmail.com Thu May 20 08:56:07 2010 From: mftian at gmail.com (Xie&Tian) Date: Thu, 20 May 2010 20:56:07 +0800 Subject: why struct.pack behave like this Message-ID: Hi When I use struct to pack binary data, I found this interesting behaviour: >>> import struct >>> struct.pack('B', 1) '\x01' >>> struct.pack('H', 200) '\xc8\x00' >>> struct.pack('BH',1, 200) '\x01\x00\xc8\x00' >>> struct.calcsize('BH') 4 Why does "struct.pack('BH',1, 200)" come out with an extra "\x00"? -- Luyun Xie http://magefromhell.blogspot.com/ (http://blog.hellmage.info/) -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at nowhere.nil Thu May 20 10:08:29 2010 From: nobody at nowhere.nil (Christian Stapfer) Date: Thu, 20 May 2010 16:08:29 +0200 Subject: Drawing glyphs based on their index (NOT their character code) In-Reply-To: References: Message-ID: <4f3f0$4bf54263$544ba447$24070@news.hispeed.ch> "Christian Stapfer" schrieb im Newsbeitrag news:b7256$4bf516e1$544ba447$20752 at news.hispeed.ch... > Here's an interesting little problem: I am given a master.ttf font file > and a subset file subset.ttf of that font, and I am asked to map indices > of all the glyphs in subset.ttf to the corresponding indices in > master.ttf. The subset font file is the result of a pipeline of 3 tools > (pdflatex, Adobe Reader, and the Microsoft XPS Document Writer). > So my next best idea is to draw the various glyphs as, 16x16 B/W images, > say, and use the 16*16 bits (that is, 16 ints or 8 longs) that result from > this as a sufficiently precise description of the glyph to do the > necessary comparisons. > > PIL would be great for this, except for one "little" problem: I need to be > able to draw glyphs based on their index, not based on their character > code. > > Any ideas to get around that limitation of PIL's drawing primitives? To answer my own question: I might parse the cmap table of the ttf file, and then invert that mapping char->index. I think that's going to be the next approach that I will try. Regards, Christian From gherron at islandtraining.com Thu May 20 10:20:15 2010 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 20 May 2010 07:20:15 -0700 Subject: Import Module In-Reply-To: References: Message-ID: <4BF5451F.5030904@islandtraining.com> On 05/19/2010 09:40 AM, Harikrishnan R wrote: > Hi , > I have a file a.py contains > > from one.two import abc > -------------------------------------------- > is there any way to find out "one.two" the import Path of abc. ? > I don't want one.two.abc . Any function or attribute which directly > give one.two ? > > -Regards > > What's so hard about computing what you want from what your can get. Since abc.__module__ gives gives you too much, trim it down -- perhaps even with os.path.splitext, although that's not what what splitext was meant for. os.path.splitext(abc.__module__)[0] Gary Herron From utente at esempio.net Thu May 20 10:37:41 2010 From: utente at esempio.net (superpollo) Date: Thu, 20 May 2010 16:37:41 +0200 Subject: function that counts... In-Reply-To: <4bf45c08$0$8837$c3e8da3@news.astraweb.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> <4bf450ef$0$31372$4fafbaef@reader1.news.tin.it> <4bf45c08$0$8837$c3e8da3@news.astraweb.com> Message-ID: <4bf54935$0$12123$4fafbaef@reader4.news.tin.it> Steven D'Aprano ha scritto: > On Wed, 19 May 2010 22:58:22 +0200, superpollo wrote: > >> In [266]: del(sum) > > > del is a statement, not a function, so the brackets are pointless. This > is like writing: > > x = (1) > > instead of > > x = 1 > > `del sum` is all you need. sorry about that, thanks a lot! bye From utente at esempio.net Thu May 20 10:38:55 2010 From: utente at esempio.net (superpollo) Date: Thu, 20 May 2010 16:38:55 +0200 Subject: function that counts... In-Reply-To: <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> Message-ID: <4bf5497f$0$12123$4fafbaef@reader4.news.tin.it> Steven D'Aprano ha scritto: > On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: > >> ... how many positive integers less than n have digits that sum up to m: >> >> In [197]: def prttn(m, n): > > Does the name "prttn" mean anything? I'm afraid I keep reading it as a > mispelling of "print n". pArtItIOn > > > [...] >> s = str(i) >> sum = 0 >> for j in range(len(s)): >> sum += int(s[j]) > > Rather than iterating over an index j = 0, 1, 2, ... and then fetching > the jth character of the string, you can iterate over the characters > directly. So the inner loop is better written: > > for c in s: > sum += int(c) d'oh! some day i will learn to speak pythonese! thanks bye From utente at esempio.net Thu May 20 10:40:35 2010 From: utente at esempio.net (superpollo) Date: Thu, 20 May 2010 16:40:35 +0200 Subject: function that counts... In-Reply-To: <75cf168b-9d67-4602-9201-774cc8dd48e9@z33g2000vbb.googlegroups.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <75cf168b-9d67-4602-9201-774cc8dd48e9@z33g2000vbb.googlegroups.com> Message-ID: <4bf549e3$0$12123$4fafbaef@reader4.news.tin.it> Richard Thomas ha scritto: > For this kind of problem you should avoid all that stringification. I > find it best to deal with sequences of digits of a fixed length and go > from there. For example: > > def count1(m, n, cache={}): > """Number of digit sequences of length `n` summing to `m`.""" > if n < 0 or m < 0: > return 0 > elif n == 0: > return int(m == 0) > elif (m, n) in cache: > return cache[m, n] > # This is an optimisation using the combinatoric choose function. > #elif m < 10: > # result = choose(n + m - 1, n - 1) > else: > result = 0 > for digit in xrange(min(10, m + 1)): > result += count1(m - digit, n - 1) > cache[m, n] = result > return result > > Notice the caching of results. With this we can compute the required > thing quite easily: > > def count2(m, n): > """Number of numbers less than `n` whose digits sum to `m`.""" > result = 0 > digits = map(int, str(n)) > length = len(digits) > for idx, digit in enumerate(digits): > for seq_digit in xrange(digit): > seq_limit = m - seq_digit > seq_length = length - idx - 1 > result += count1(seq_limit, seq_length) > m -= digit > return result > > Essentially we move through the number left to right, choose digits > less than the digit in the number and count digit sequences to fill > the remainder. Then fix the actual digit and step forward. > > An approach like this avoids the relatively slow stringification > process and makes decent use of caching and iteration (both easy and > efficient in Python). > > In [1]: count2(25, 10000) > Out[1]: 348 > > In [2]: timeit count2(25, 10000) > 100000 loops, best of 3: 12.6 us per loop wow. impressive, thanks. From davea at ieee.org Thu May 20 11:44:00 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 20 May 2010 11:44:00 -0400 Subject: why struct.pack behave like this In-Reply-To: References: Message-ID: <4BF558C0.2050101@ieee.org> Xie&Tian wrote: > Hi > > When I use struct to pack binary data, I found this interesting behaviour: > > >>>> import struct >>>> struct.pack('B', 1) >>>> > '\x01' > >>>> struct.pack('H', 200) >>>> > '\xc8\x00' > >>>> struct.pack('BH',1, 200) >>>> > '\x01\x00\xc8\x00' > >>>> struct.calcsize('BH') >>>> > 4 > > Why does "struct.pack('BH',1, 200)" come out with an extra "\x00"? > > > To quote the help: >>By default, C numbers are represented in the machine?s native format and byte order, >>and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). C's standard rules say that when a smaller type is followed by a larger one, padding is used so that the second field is aligned according to its size. So a H type will be aligned to a 2byte boundary. If you had two B's before it, no padding would be added. In C, you can use a compiler switch or a pragma to override standard alignment. Similarly, here you can use a prefix like "=" to override the native alignment rules. DaveA From sit at home.com Thu May 20 11:58:51 2010 From: sit at home.com (sit at home.com) Date: Thu, 20 May 2010 11:58:51 -0400 Subject: Display file names in Tkinter Listbox References: <4BF4CA7B.6000008@NO.SPAM.velseis.com.au> Message-ID: On Thu, 20 May 2010 15:36:59 +1000, John McMonagle wrote: >Rick at home.com wrote: >> Hello, >> >> My first attenpt at a simple python Tkinter application. I wanted to >> see how to load file names into a listbox from a menu. This is what I >> got until the part of displaying the file names in a listbox, which I >> could not figfure out how to do? >> >> Any help would be appreciated. Trying to do this as simple as possible >> to understand. >> >> The "print fileNames" does work but how to display it in listbox? >> >> from Tkinter import * >> from tkFileDialog import askopenfilenames >> >> class MyCode: >> def __init__(self): >> root = Tk() >> >> menubar = Menu(root) >> filemenu = Menu(menubar) >> >> lbox = Listbox(root, width=50).pack() > >Your problem is the above line of code. > >Here you are assigning the return value of the pack (None if I recall). > >Later when you want to put things in the Listbox you don't have the >widget reference anymore. > >It's probably a good idea to make the Listbox widget an attribute of >your class so you can use it in class methods without having to pass it >as an argument. > >So, change the above line of code to: > > self.lbox = Listbox(root, width=50) > self.lbox.pack() > >> >> menubar.add_cascade(label='File', menu=filemenu) >> filemenu.add_command(label='New Project') >> filemenu.add_command(label='Load Files...', command=self.OnLoad) >> >> >> filemenu.add_command(label='Exit', command=root.quit) >> >> root.config(menu=menubar) >> >> root.mainloop() >> >> >> def OnLoad(self): >> fileNames = askopenfilenames(filetypes=[('Split Files', '*')]) >> print fileNames >> > >Now that you've got a reference to your Listbox widget that is an >attribute of your class, you should be able to insert the file names >into the Listbox like so. > > self.lbox.insert(0, fileNames) > >Regards, > >John Thank you John for your reply. I have made the modifications and it does print inside the listbox, however they are all printed on the same line. My files are named Name.0 Name.1 Name.2 Name.3 etc so I would like them to be printed sorted on a separate line. When I did a type(fileNames) it showed me that it was in unicode and printed character per line, so I tried it this way listFileNames = str(fileNames).split(' ') for fileName in listFileNames: self.lbox.insert(0, fileName) it works but does not print sorted. it prints name.2 name.1 name.0 name.3 Thank you for all your help. From ppearson at nowhere.invalid Thu May 20 12:06:33 2010 From: ppearson at nowhere.invalid (Peter Pearson) Date: 20 May 2010 16:06:33 GMT Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <85l509Fpe7U1@mid.individual.net> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: > ... how many positive integers less than n have digits that sum up to m: If it's important for the function to execute quickly for large n, you might get a useful speedup by testing only every ninth integer, since any two integers whose digits add up to m differ by a multiple of 9. A simple application of this observation would be to test range( m % 9, n, 9 ) rather than testing range( 1, n ). I suspect that further applications of number theory would provide additional, substantial speedups, but this wanders away from the subject of Python. -- To email me, substitute nowhere->spamcop, invalid->net. From victorsubervi at gmail.com Thu May 20 12:26:24 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 20 May 2010 12:26:24 -0400 Subject: Strange MySQL Problem Message-ID: Hi; I have this code: #!/usr/bin/python import cgitb; cgitb.enable() import cgi import sys,os sys.path.append(os.getcwd()) import MySQLdb from login import login def create_edit_passengers4(): print "Content-Type: text/html" print print ''' ''' user, passwd, db, host = login() database = MySQLdb.connect(host, user, passwd, db) cursor = database.cursor() form = cgi.FieldStorage() cursor.execute('create table if not exists Passengers (id int(11) auto_increment primary key, flights_id int(11) not null, customer_id int(11) not null, foreign key (id) references Flights (flights_id), foreign key (id) references Customers (customer_id), name varchar(40), weight int) engine=InnoDB;') new_passengers = int(form.getfirst('new_passengers')) i = 0 while i < new_passengers: cursor.execute('insert into Passengers values (Null, %s, %s, "%s", %s);' % (form.getfirst('%d:flight' % i), form.getfirst('%d:customer' % i), form.getfirst('%d:name' % i, ''), form.getfirst('%d:weight' % i))) i += 1 print "All passenger information has successfully been added." cursor.close() print "\n" create_edit_passengers4() Now, it throws no errors; however, it doesn't insert. If I print out the insert statement to screen and then manually insert it in MySQL it inserts. Huh?? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From angel.gutierrez.rodriguez at gmail.com Thu May 20 12:32:21 2010 From: angel.gutierrez.rodriguez at gmail.com (Angel) Date: Thu, 20 May 2010 09:32:21 -0700 (PDT) Subject: Python 2.6.1 + wxPython 2.8.9.1 compiled form source Message-ID: Hi, I have a Red Hat 4.6 machone and I compiled and installed python 2.6.1 from source. Then, I compiled wxPython 2.8.9.1 form source too. And then, when I try to run it: # python Python 2.6.1 (r261:67515, Mar 4 2009, 20:10:49) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import wx Aborted Any hint? Anything I am missing? Anyhere to check? Read? Thanks in advance. This in my environment: LD_LIBRARY_PATH=/opt/wxPython/2.8.9.1/lib:/opt/python/2.6.1/lib:/opt/ hpmpi/lib/linux_amd64:/opt/intel/cce/10.1.008/lib:/opt/intel/fce/ 10.1.008/lib:/lib:/lib64:/usr/lib:/usr/lib64:/usr/X11R6/lib:/usr/X11R6/ lib64:/usr/local/lib:/usr/local/lib64 PATH=/opt/wxPython/2.8.9.1/bin:/opt/python/2.6.1/bin:/root/aaks/bin:/ opt/hpmpi/bin:/opt/intel/cce/10.1.008/bin:/opt/intel/fce/10.1.008/bin:/ usr/local/bin:/usr/local/X11/bin:/opt/torque/2.3.6/bin:/opt/torque/ 2.3.6/sbin:/usr/java/jdk1.6.0_12/bin:/usr/local/sbin:/usr/local/bin:/ sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/etc:/usr/etc:/usr/local/ etc:.:/opt/maui/3.2.6p21/sbin:/opt/maui/3.2.6p21/bin:/root/bin:/opt/ pdsh/2.17/bin PYTHONPATH=/opt/wxPython/2.8.9.1:/opt/python/2.6.1 And.. a verbose output: # python -vv # installing zipimport hook import zipimport # builtin # installed zipimport hook # trying /opt/wxPython/2.8.9.1/site.so # trying /opt/wxPython/2.8.9.1/sitemodule.so # trying /opt/wxPython/2.8.9.1/site.py # trying /opt/wxPython/2.8.9.1/site.pyc # trying /opt/python/2.6.1/site.so # trying /opt/python/2.6.1/sitemodule.so # trying /opt/python/2.6.1/site.py # trying /opt/python/2.6.1/site.pyc # trying /opt/python/2.6.1/lib/python2.6/site.so # trying /opt/python/2.6.1/lib/python2.6/sitemodule.so # trying /opt/python/2.6.1/lib/python2.6/site.py # /opt/python/2.6.1/lib/python2.6/site.pyc matches /opt/python/2.6.1/ lib/python2.6/site.py import site # precompiled from /opt/python/2.6.1/lib/python2.6/ site.pyc # trying /opt/wxPython/2.8.9.1/os.so # trying /opt/wxPython/2.8.9.1/osmodule.so # trying /opt/wxPython/2.8.9.1/os.py # trying /opt/wxPython/2.8.9.1/os.pyc # trying /opt/python/2.6.1/os.so # trying /opt/python/2.6.1/osmodule.so # trying /opt/python/2.6.1/os.py # trying /opt/python/2.6.1/os.pyc # trying /opt/python/2.6.1/lib/python2.6/os.so # trying /opt/python/2.6.1/lib/python2.6/osmodule.so # trying /opt/python/2.6.1/lib/python2.6/os.py # /opt/python/2.6.1/lib/python2.6/os.pyc matches /opt/python/2.6.1/lib/ python2.6/os.py import os # precompiled from /opt/python/2.6.1/lib/python2.6/os.pyc import errno # builtin import posix # builtin # trying /opt/wxPython/2.8.9.1/posixpath.so # trying /opt/wxPython/2.8.9.1/posixpathmodule.so # trying /opt/wxPython/2.8.9.1/posixpath.py # trying /opt/wxPython/2.8.9.1/posixpath.pyc # trying /opt/python/2.6.1/posixpath.so # trying /opt/python/2.6.1/posixpathmodule.so # trying /opt/python/2.6.1/posixpath.py # trying /opt/python/2.6.1/posixpath.pyc # trying /opt/python/2.6.1/lib/python2.6/posixpath.so # trying /opt/python/2.6.1/lib/python2.6/posixpathmodule.so # trying /opt/python/2.6.1/lib/python2.6/posixpath.py # /opt/python/2.6.1/lib/python2.6/posixpath.pyc matches /opt/python/ 2.6.1/lib/python2.6/posixpath.py import posixpath # precompiled from /opt/python/2.6.1/lib/python2.6/ posixpath.pyc # trying /opt/wxPython/2.8.9.1/stat.so # trying /opt/wxPython/2.8.9.1/statmodule.so # trying /opt/wxPython/2.8.9.1/stat.py # trying /opt/wxPython/2.8.9.1/stat.pyc # trying /opt/python/2.6.1/stat.so # trying /opt/python/2.6.1/statmodule.so # trying /opt/python/2.6.1/stat.py # trying /opt/python/2.6.1/stat.pyc # trying /opt/python/2.6.1/lib/python2.6/stat.so # trying /opt/python/2.6.1/lib/python2.6/statmodule.so # trying /opt/python/2.6.1/lib/python2.6/stat.py # /opt/python/2.6.1/lib/python2.6/stat.pyc matches /opt/python/2.6.1/ lib/python2.6/stat.py import stat # precompiled from /opt/python/2.6.1/lib/python2.6/ stat.pyc # trying /opt/wxPython/2.8.9.1/genericpath.so # trying /opt/wxPython/2.8.9.1/genericpathmodule.so # trying /opt/wxPython/2.8.9.1/genericpath.py # trying /opt/wxPython/2.8.9.1/genericpath.pyc # trying /opt/python/2.6.1/genericpath.so # trying /opt/python/2.6.1/genericpathmodule.so # trying /opt/python/2.6.1/genericpath.py # trying /opt/python/2.6.1/genericpath.pyc # trying /opt/python/2.6.1/lib/python2.6/genericpath.so # trying /opt/python/2.6.1/lib/python2.6/genericpathmodule.so # trying /opt/python/2.6.1/lib/python2.6/genericpath.py # /opt/python/2.6.1/lib/python2.6/genericpath.pyc matches /opt/python/ 2.6.1/lib/python2.6/genericpath.py import genericpath # precompiled from /opt/python/2.6.1/lib/python2.6/ genericpath.pyc # trying /opt/wxPython/2.8.9.1/warnings.so # trying /opt/wxPython/2.8.9.1/warningsmodule.so # trying /opt/wxPython/2.8.9.1/warnings.py # trying /opt/wxPython/2.8.9.1/warnings.pyc # trying /opt/python/2.6.1/warnings.so # trying /opt/python/2.6.1/warningsmodule.so # trying /opt/python/2.6.1/warnings.py # trying /opt/python/2.6.1/warnings.pyc # trying /opt/python/2.6.1/lib/python2.6/warnings.so # trying /opt/python/2.6.1/lib/python2.6/warningsmodule.so # trying /opt/python/2.6.1/lib/python2.6/warnings.py # /opt/python/2.6.1/lib/python2.6/warnings.pyc matches /opt/python/ 2.6.1/lib/python2.6/warnings.py import warnings # precompiled from /opt/python/2.6.1/lib/python2.6/ warnings.pyc # trying /opt/wxPython/2.8.9.1/linecache.so # trying /opt/wxPython/2.8.9.1/linecachemodule.so # trying /opt/wxPython/2.8.9.1/linecache.py # trying /opt/wxPython/2.8.9.1/linecache.pyc # trying /opt/python/2.6.1/linecache.so # trying /opt/python/2.6.1/linecachemodule.so # trying /opt/python/2.6.1/linecache.py # trying /opt/python/2.6.1/linecache.pyc # trying /opt/python/2.6.1/lib/python2.6/linecache.so # trying /opt/python/2.6.1/lib/python2.6/linecachemodule.so # trying /opt/python/2.6.1/lib/python2.6/linecache.py # /opt/python/2.6.1/lib/python2.6/linecache.pyc matches /opt/python/ 2.6.1/lib/python2.6/linecache.py import linecache # precompiled from /opt/python/2.6.1/lib/python2.6/ linecache.pyc # trying /opt/wxPython/2.8.9.1/types.so # trying /opt/wxPython/2.8.9.1/typesmodule.so # trying /opt/wxPython/2.8.9.1/types.py # trying /opt/wxPython/2.8.9.1/types.pyc # trying /opt/python/2.6.1/types.so # trying /opt/python/2.6.1/typesmodule.so # trying /opt/python/2.6.1/types.py # trying /opt/python/2.6.1/types.pyc # trying /opt/python/2.6.1/lib/python2.6/types.so # trying /opt/python/2.6.1/lib/python2.6/typesmodule.so # trying /opt/python/2.6.1/lib/python2.6/types.py # /opt/python/2.6.1/lib/python2.6/types.pyc matches /opt/python/2.6.1/ lib/python2.6/types.py import types # precompiled from /opt/python/2.6.1/lib/python2.6/ types.pyc # trying /opt/wxPython/2.8.9.1/UserDict.so # trying /opt/wxPython/2.8.9.1/UserDictmodule.so # trying /opt/wxPython/2.8.9.1/UserDict.py # trying /opt/wxPython/2.8.9.1/UserDict.pyc # trying /opt/python/2.6.1/UserDict.so # trying /opt/python/2.6.1/UserDictmodule.so # trying /opt/python/2.6.1/UserDict.py # trying /opt/python/2.6.1/UserDict.pyc # trying /opt/python/2.6.1/lib/python2.6/UserDict.so # trying /opt/python/2.6.1/lib/python2.6/UserDictmodule.so # trying /opt/python/2.6.1/lib/python2.6/UserDict.py # /opt/python/2.6.1/lib/python2.6/UserDict.pyc matches /opt/python/ 2.6.1/lib/python2.6/UserDict.py import UserDict # precompiled from /opt/python/2.6.1/lib/python2.6/ UserDict.pyc # trying /opt/wxPython/2.8.9.1/_abcoll.so # trying /opt/wxPython/2.8.9.1/_abcollmodule.so # trying /opt/wxPython/2.8.9.1/_abcoll.py # trying /opt/wxPython/2.8.9.1/_abcoll.pyc # trying /opt/python/2.6.1/_abcoll.so # trying /opt/python/2.6.1/_abcollmodule.so # trying /opt/python/2.6.1/_abcoll.py # trying /opt/python/2.6.1/_abcoll.pyc # trying /opt/python/2.6.1/lib/python2.6/_abcoll.so # trying /opt/python/2.6.1/lib/python2.6/_abcollmodule.so # trying /opt/python/2.6.1/lib/python2.6/_abcoll.py # /opt/python/2.6.1/lib/python2.6/_abcoll.pyc matches /opt/python/ 2.6.1/lib/python2.6/_abcoll.py import _abcoll # precompiled from /opt/python/2.6.1/lib/python2.6/ _abcoll.pyc # trying /opt/wxPython/2.8.9.1/abc.so # trying /opt/wxPython/2.8.9.1/abcmodule.so # trying /opt/wxPython/2.8.9.1/abc.py # trying /opt/wxPython/2.8.9.1/abc.pyc # trying /opt/python/2.6.1/abc.so # trying /opt/python/2.6.1/abcmodule.so # trying /opt/python/2.6.1/abc.py # trying /opt/python/2.6.1/abc.pyc # trying /opt/python/2.6.1/lib/python2.6/abc.so # trying /opt/python/2.6.1/lib/python2.6/abcmodule.so # trying /opt/python/2.6.1/lib/python2.6/abc.py # /opt/python/2.6.1/lib/python2.6/abc.pyc matches /opt/python/2.6.1/ lib/python2.6/abc.py import abc # precompiled from /opt/python/2.6.1/lib/python2.6/abc.pyc # trying /opt/wxPython/2.8.9.1/copy_reg.so # trying /opt/wxPython/2.8.9.1/copy_regmodule.so # trying /opt/wxPython/2.8.9.1/copy_reg.py # trying /opt/wxPython/2.8.9.1/copy_reg.pyc # trying /opt/python/2.6.1/copy_reg.so # trying /opt/python/2.6.1/copy_regmodule.so # trying /opt/python/2.6.1/copy_reg.py # trying /opt/python/2.6.1/copy_reg.pyc # trying /opt/python/2.6.1/lib/python2.6/copy_reg.so # trying /opt/python/2.6.1/lib/python2.6/copy_regmodule.so # trying /opt/python/2.6.1/lib/python2.6/copy_reg.py # /opt/python/2.6.1/lib/python2.6/copy_reg.pyc matches /opt/python/ 2.6.1/lib/python2.6/copy_reg.py import copy_reg # precompiled from /opt/python/2.6.1/lib/python2.6/ copy_reg.pyc # trying /opt/wxPython/2.8.9.1/sitecustomize.so # trying /opt/wxPython/2.8.9.1/sitecustomizemodule.so # trying /opt/wxPython/2.8.9.1/sitecustomize.py # trying /opt/wxPython/2.8.9.1/sitecustomize.pyc # trying /opt/python/2.6.1/sitecustomize.so # trying /opt/python/2.6.1/sitecustomizemodule.so # trying /opt/python/2.6.1/sitecustomize.py # trying /opt/python/2.6.1/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-tk/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-tk/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-old/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/ sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-old/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/ sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/ sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/sitecustomize.pyc # trying /opt/wxPython/2.8.9.1/usercustomize.so # trying /opt/wxPython/2.8.9.1/usercustomizemodule.so # trying /opt/wxPython/2.8.9.1/usercustomize.py # trying /opt/wxPython/2.8.9.1/usercustomize.pyc # trying /opt/python/2.6.1/usercustomize.so # trying /opt/python/2.6.1/usercustomizemodule.so # trying /opt/python/2.6.1/usercustomize.py # trying /opt/python/2.6.1/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-tk/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-tk/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-old/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/ usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-old/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/ usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/ usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/usercustomize.pyc # trying /opt/wxPython/2.8.9.1/encodings.so # trying /opt/wxPython/2.8.9.1/encodingsmodule.so # trying /opt/wxPython/2.8.9.1/encodings.py # trying /opt/wxPython/2.8.9.1/encodings.pyc # trying /opt/python/2.6.1/encodings.so # trying /opt/python/2.6.1/encodingsmodule.so # trying /opt/python/2.6.1/encodings.py # trying /opt/python/2.6.1/encodings.pyc import encodings # directory /opt/python/2.6.1/lib/python2.6/encodings # trying /opt/python/2.6.1/lib/python2.6/encodings/__init__.so # trying /opt/python/2.6.1/lib/python2.6/encodings/__init__module.so # trying /opt/python/2.6.1/lib/python2.6/encodings/__init__.py # /opt/python/2.6.1/lib/python2.6/encodings/__init__.pyc matches /opt/ python/2.6.1/lib/python2.6/encodings/__init__.py import encodings # precompiled from /opt/python/2.6.1/lib/python2.6/ encodings/__init__.pyc # trying /opt/python/2.6.1/lib/python2.6/encodings/codecs.so # trying /opt/python/2.6.1/lib/python2.6/encodings/codecsmodule.so # trying /opt/python/2.6.1/lib/python2.6/encodings/codecs.py # trying /opt/python/2.6.1/lib/python2.6/encodings/codecs.pyc # trying /opt/wxPython/2.8.9.1/codecs.so # trying /opt/wxPython/2.8.9.1/codecsmodule.so # trying /opt/wxPython/2.8.9.1/codecs.py # trying /opt/wxPython/2.8.9.1/codecs.pyc # trying /opt/python/2.6.1/codecs.so # trying /opt/python/2.6.1/codecsmodule.so # trying /opt/python/2.6.1/codecs.py # trying /opt/python/2.6.1/codecs.pyc # trying /opt/python/2.6.1/lib/python2.6/codecs.so # trying /opt/python/2.6.1/lib/python2.6/codecsmodule.so # trying /opt/python/2.6.1/lib/python2.6/codecs.py # /opt/python/2.6.1/lib/python2.6/codecs.pyc matches /opt/python/2.6.1/ lib/python2.6/codecs.py import codecs # precompiled from /opt/python/2.6.1/lib/python2.6/ codecs.pyc import _codecs # builtin # trying /opt/python/2.6.1/lib/python2.6/encodings/encodings.so # trying /opt/python/2.6.1/lib/python2.6/encodings/encodingsmodule.so # trying /opt/python/2.6.1/lib/python2.6/encodings/encodings.py # trying /opt/python/2.6.1/lib/python2.6/encodings/encodings.pyc # trying /opt/python/2.6.1/lib/python2.6/encodings/aliases.so # trying /opt/python/2.6.1/lib/python2.6/encodings/aliasesmodule.so # trying /opt/python/2.6.1/lib/python2.6/encodings/aliases.py # /opt/python/2.6.1/lib/python2.6/encodings/aliases.pyc matches /opt/ python/2.6.1/lib/python2.6/encodings/aliases.py import encodings.aliases # precompiled from /opt/python/2.6.1/lib/ python2.6/encodings/aliases.pyc # trying /opt/python/2.6.1/lib/python2.6/encodings/__builtin__.so # trying /opt/python/2.6.1/lib/python2.6/encodings/ __builtin__module.so # trying /opt/python/2.6.1/lib/python2.6/encodings/__builtin__.py # trying /opt/python/2.6.1/lib/python2.6/encodings/__builtin__.pyc # trying /opt/python/2.6.1/lib/python2.6/encodings/utf_8.so # trying /opt/python/2.6.1/lib/python2.6/encodings/utf_8module.so # trying /opt/python/2.6.1/lib/python2.6/encodings/utf_8.py # /opt/python/2.6.1/lib/python2.6/encodings/utf_8.pyc matches /opt/ python/2.6.1/lib/python2.6/encodings/utf_8.py import encodings.utf_8 # precompiled from /opt/python/2.6.1/lib/ python2.6/encodings/utf_8.pyc Python 2.6.1 (r261:67515, Mar 4 2009, 20:10:49) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. # trying readline.so # trying readlinemodule.so # trying readline.py # trying readline.pyc # trying /opt/wxPython/2.8.9.1/readline.so # trying /opt/wxPython/2.8.9.1/readlinemodule.so # trying /opt/wxPython/2.8.9.1/readline.py # trying /opt/wxPython/2.8.9.1/readline.pyc # trying /opt/python/2.6.1/readline.so # trying /opt/python/2.6.1/readlinemodule.so # trying /opt/python/2.6.1/readline.py # trying /opt/python/2.6.1/readline.pyc # trying /opt/python/2.6.1/lib/python2.6/readline.so # trying /opt/python/2.6.1/lib/python2.6/readlinemodule.so # trying /opt/python/2.6.1/lib/python2.6/readline.py # trying /opt/python/2.6.1/lib/python2.6/readline.pyc # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/readline.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/readlinemodule.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/readline.py # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/readline.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-tk/readline.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/readlinemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/readline.py # trying /opt/python/2.6.1/lib/python2.6/lib-tk/readline.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-old/readline.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/readlinemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/readline.py # trying /opt/python/2.6.1/lib/python2.6/lib-old/readline.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/readline.so dlopen("/opt/python/2.6.1/lib/python2.6/lib-dynload/readline.so", 2); import readline # dynamically loaded from /opt/python/2.6.1/lib/ python2.6/lib-dynload/readline.so >>> import wx # trying wx.so # trying wxmodule.so # trying wx.py # trying wx.pyc # trying /opt/wxPython/2.8.9.1/wx.so # trying /opt/wxPython/2.8.9.1/wxmodule.so # trying /opt/wxPython/2.8.9.1/wx.py # trying /opt/wxPython/2.8.9.1/wx.pyc # trying /opt/python/2.6.1/wx.so # trying /opt/python/2.6.1/wxmodule.so # trying /opt/python/2.6.1/wx.py # trying /opt/python/2.6.1/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/wx.so # trying /opt/python/2.6.1/lib/python2.6/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/wx.py # trying /opt/python/2.6.1/lib/python2.6/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/wx.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/wx.py # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-tk/wx.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/wx.py # trying /opt/python/2.6.1/lib/python2.6/lib-tk/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-old/wx.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/wx.py # trying /opt/python/2.6.1/lib/python2.6/lib-old/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/wx.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/wx.py # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx.pyc import wx # directory /opt/python/2.6.1/lib/python2.6/site-packages/ wx-2.8-gtk2-unicode/wx # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__init__.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__init__module.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__init__.py # /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/ __init__.pyc matches /opt/python/2.6.1/lib/python2.6/site-packages/ wx-2.8-gtk2-unicode/wx/__init__.py import wx # precompiled from /opt/python/2.6.1/lib/python2.6/site- packages/wx-2.8-gtk2-unicode/wx/__init__.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__version__.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__version__module.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__version__.py # /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/ __version__.pyc matches /opt/python/2.6.1/lib/python2.6/site-packages/ wx-2.8-gtk2-unicode/wx/__version__.py import wx.__version__ # precompiled from /opt/python/2.6.1/lib/ python2.6/site-packages/wx-2.8-gtk2-unicode/wx/__version__.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/wx.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/wx.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/_core.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/_coremodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/_core.py # /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/ _core.pyc matches /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8- gtk2-unicode/wx/_core.py import wx._core # precompiled from /opt/python/2.6.1/lib/python2.6/ site-packages/wx-2.8-gtk2-unicode/wx/_core.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/_core_.so dlopen("/opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/_core_.so", 2); # trying swig_runtime_data2.so # trying swig_runtime_data2module.so # trying swig_runtime_data2.py # trying swig_runtime_data2.pyc # trying /opt/wxPython/2.8.9.1/swig_runtime_data2.so # trying /opt/wxPython/2.8.9.1/swig_runtime_data2module.so # trying /opt/wxPython/2.8.9.1/swig_runtime_data2.py # trying /opt/wxPython/2.8.9.1/swig_runtime_data2.pyc # trying /opt/python/2.6.1/swig_runtime_data2.so # trying /opt/python/2.6.1/swig_runtime_data2module.so # trying /opt/python/2.6.1/swig_runtime_data2.py # trying /opt/python/2.6.1/swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-tk/swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/ swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/lib-tk/swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-old/swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/ swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/lib-old/ swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/ swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/ swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/swig_runtime_data2.pyc Aborted From utente at esempio.net Thu May 20 12:33:17 2010 From: utente at esempio.net (superpollo) Date: Thu, 20 May 2010 18:33:17 +0200 Subject: function that counts... In-Reply-To: <85l509Fpe7U1@mid.individual.net> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <85l509Fpe7U1@mid.individual.net> Message-ID: <4bf5644e$0$12129$4fafbaef@reader4.news.tin.it> Peter Pearson ha scritto: > On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: >> ... how many positive integers less than n have digits that sum up to m: > > If it's important for the function to execute quickly for large n, > you might get a useful speedup by testing only every ninth integer, > since any two integers whose digits add up to m differ by a multiple > of 9. A simple application of this observation would be to test > range( m % 9, n, 9 ) rather than testing range( 1, n ). > > I suspect that further applications of number theory would > provide additional, substantial speedups, but this wanders > away from the subject of Python. > great suggestion, thanks! From invalid at invalid.invalid Thu May 20 12:39:38 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 20 May 2010 16:39:38 +0000 (UTC) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> <4bf5497f$0$12123$4fafbaef@reader4.news.tin.it> Message-ID: On 2010-05-20, superpollo wrote: > Steven D'Aprano ha scritto: >> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: >> >>> ... how many positive integers less than n have digits that sum up to m: >>> >>> In [197]: def prttn(m, n): >> >> Does the name "prttn" mean anything? I'm afraid I keep reading it as a >> mispelling of "print n". > > pArtItIOn One might be tempted to suggest the name "partition". This isn't Fortran-IV. ;) -- Grant Edwards grant.b.edwards Yow! I've got a COUSIN at who works in the GARMENT gmail.com DISTRICT ... From python at mrabarnett.plus.com Thu May 20 12:56:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 20 May 2010 17:56:59 +0100 Subject: Strange MySQL Problem In-Reply-To: References: Message-ID: <4BF569DB.9010601@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > I have this code: > > #!/usr/bin/python > > import cgitb; cgitb.enable() > import cgi > import sys,os > sys.path.append(os.getcwd()) > import MySQLdb > from login import login > > def create_edit_passengers4(): > print "Content-Type: text/html" > print > print ''' > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> > > > > ''' > user, passwd, db, host = login() > database = MySQLdb.connect(host, user, passwd, db) > cursor = database.cursor() > form = cgi.FieldStorage() > cursor.execute('create table if not exists Passengers (id int(11) > auto_increment primary key, flights_id int(11) not null, customer_id > int(11) not null, foreign key (id) references Flights (flights_id), > foreign key (id) references Customers (customer_id), name varchar(40), > weight int) engine=InnoDB;') > new_passengers = int(form.getfirst('new_passengers')) > i = 0 > while i < new_passengers: > cursor.execute('insert into Passengers values (Null, %s, %s, "%s", > %s);' % (form.getfirst('%d:flight' % i), form.getfirst('%d:customer' % > i), form.getfirst('%d:name' % i, ''), form.getfirst('%d:weight' % i))) When performing SQL operations, don't insert the values using Python's string formatting, because that makes it vulnerable to SQL-injection attacks, ie don't do this: cursor.execute(sql_command % values) do this: cursor.execute(sql_command, values) > i += 1 > print "All passenger information has successfully been added." > cursor.close() > print "\n" > > create_edit_passengers4() > > Now, it throws no errors; however, it doesn't insert. If I print out the > insert statement to screen and then manually insert it in MySQL it > inserts. Huh?? > I think you need to 'commit' any changes to do to the database. From lists at cheimes.de Thu May 20 13:21:18 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 May 2010 19:21:18 +0200 Subject: Strange MySQL Problem In-Reply-To: <4BF569DB.9010601@mrabarnett.plus.com> References: <4BF569DB.9010601@mrabarnett.plus.com> Message-ID: MRAB wrote: > I think you need to 'commit' any changes to do to the database. Yeah, you are right. Also some RDBMS don't support DDL and DML statements inside one transaction. You may need to commit and begin after the create table DDL. Christian From victorsubervi at gmail.com Thu May 20 13:29:24 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 20 May 2010 13:29:24 -0400 Subject: Strange MySQL Problem In-Reply-To: <4BF569DB.9010601@mrabarnett.plus.com> References: <4BF569DB.9010601@mrabarnett.plus.com> Message-ID: On Thu, May 20, 2010 at 12:56 PM, MRAB wrote: > > When performing SQL operations, don't insert the values using Python's > string formatting, because that makes it vulnerable to SQL-injection > attacks, ie don't do this: > > cursor.execute(sql_command % values) > > do this: > > cursor.execute(sql_command, values) Oh, thank you! > I think you need to 'commit' any changes to do to the database. > Caught by the commit again. Yes, thanks. beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From tomf.sessile at gmail.com Thu May 20 14:17:11 2010 From: tomf.sessile at gmail.com (TomF) Date: Thu, 20 May 2010 11:17:11 -0700 Subject: Global variables for python applications References: <2010051900165614229-tomfsessile@gmailcom> <4bf3f6fc$0$27861$c3e8da3@news.astraweb.com> Message-ID: <2010052011171175-tomfsessile@gmailcom> On 2010-05-19 07:34:37 -0700, Steven D'Aprano said: > # Untested. > def verbose_print(arg, level, verbosity=1): > if level <= verbosity: > print arg > > def my_function(arg): > my_print(arg, level=2) > return arg.upper() > > if __name__ == '__main__': > if '--verbose' in sys.argv: > my_print = functools.partial(verbose_print, verbosity=2) > elif '--quiet' in sys.argv: > my_print = functools.partial(verbose_print, verbosity=0) > > my_function("hello world") > > > Note that although there is no verbosity global setting, every function > that calls my_print will do the right thing (unless I've got the test > backwards...), and if a function needs to override the implicit verbosity > setting, it can just call verbose_print directly. From utente at esempio.net Thu May 20 14:36:58 2010 From: utente at esempio.net (superpollo) Date: Thu, 20 May 2010 20:36:58 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> <4bf5497f$0$12123$4fafbaef@reader4.news.tin.it> Message-ID: <4bf5814b$0$12129$4fafbaef@reader4.news.tin.it> Grant Edwards ha scritto: > On 2010-05-20, superpollo wrote: >> Steven D'Aprano ha scritto: >>> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: >>> >>>> ... how many positive integers less than n have digits that sum up to m: >>>> >>>> In [197]: def prttn(m, n): >>> Does the name "prttn" mean anything? I'm afraid I keep reading it as a >>> mispelling of "print n". >> pArtItIOn > > One might be tempted to suggest the name "partition". no kidding: i was afraid to use some reserved word... From emile at fenx.com Thu May 20 15:19:48 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 20 May 2010 12:19:48 -0700 Subject: 250 In-Reply-To: References: Message-ID: On 5/20/2010 12:39 AM Martin P. Hellwig said... > On 05/20/10 07:51, cosmeticsafrolatino wrote: >> hi > 250 locahost.local Hello WimaxUser3645-219.wateen.net [110.36.45.219], > pleased to meet you :) From invalid at invalid.invalid Thu May 20 15:53:42 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 20 May 2010 19:53:42 +0000 (UTC) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> <4bf5497f$0$12123$4fafbaef@reader4.news.tin.it> <4bf5814b$0$12129$4fafbaef@reader4.news.tin.it> Message-ID: On 2010-05-20, superpollo wrote: > Grant Edwards ha scritto: >> On 2010-05-20, superpollo wrote: >>> Steven D'Aprano ha scritto: >>>> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: >>>> >>>>> ... how many positive integers less than n have digits that sum up to m: >>>> >>>> Does the name "prttn" mean anything? I'm afraid I keep reading it as >>>> a mispelling of "print n". >>> >>> pArtItIOn >> >> One might be tempted to suggest the name "partition". > > no kidding: i was afraid to use some reserved word... Since Python is interactive, and you don't get charged for each time you run your deck through the reader, that's easy enough to check: $ python Python 2.6.4 (r264:75706, Mar 1 2010, 10:33:43) [GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> partition Traceback (most recent call last): File "", line 1, in NameError: name 'partition' is not defined >>> sum >>> int >>> file Lest my allusions to Fortran IV be lost upon the less grizzled, only the first 6 characters were significant in Fortran IV identifiers, and removing all of the vowels from a longer word was an idiomatic way to create an identifier with a length <= 6. IIRC, the number 6 was originally chosen because that's how many 6-bit characters you could hold in a single 36-bit CPU register. That way when writing a compiler/link/assembly you could compare two identifiers using a single "CMP" instruction. I'm not sure why 36-bits was such a popular ALU width, but many different vendors sold 36-bit machines back in the day. -- Grant Edwards grant.b.edwards Yow! Hand me a pair of at leather pants and a CASIO gmail.com keyboard -- I'm living for today! From emelysite at gmail.com Thu May 20 16:34:39 2010 From: emelysite at gmail.com (women) Date: Thu, 20 May 2010 13:34:39 -0700 (PDT) Subject: Save the message Important Links Message-ID: Save the message Important Links Infertility treatment for free http://echance.info/cj/fb.htm download youtube free and fast http://echance.info/cj/youtube.htm Get mobile talk for free http://echance.info/cj/freephone.htm Call any phone or mobile for free http://echance.info/cj/callphone.htm About your finances to reach in less than an hour Less commission for money transfer http://echance.info/cj/100dayloans.htm The best way to protect your site http://echance.info/cj/sitelock.htm http://echance.info/cj/fasthost.htm http://echance.info/cj/freegames.htm From emelysite at gmail.com Thu May 20 16:36:12 2010 From: emelysite at gmail.com (women) Date: Thu, 20 May 2010 13:36:12 -0700 (PDT) Subject: Infertility treatment for free Message-ID: Infertility treatment for free Bearing and speed of fertilization http://echance.info/cj/fb.htm From emelysite at gmail.com Thu May 20 16:37:04 2010 From: emelysite at gmail.com (women) Date: Thu, 20 May 2010 13:37:04 -0700 (PDT) Subject: Bearing and speed of fertilization Message-ID: <3aaab65d-fce9-4f63-9f6f-dcceb2500b3c@q13g2000vbm.googlegroups.com> Infertility treatment for free Bearing and speed of fertilization http://echance.info/cj/fb.htm From emelysite at gmail.com Thu May 20 16:37:30 2010 From: emelysite at gmail.com (women) Date: Thu, 20 May 2010 13:37:30 -0700 (PDT) Subject: download youtube free and fast Message-ID: <438723d2-ca4c-4db5-9885-dd0f4e5c5529@l6g2000vbo.googlegroups.com> download youtube free and fast http://echance.info/cj/youtube.htm From news1234 at free.fr Thu May 20 16:46:59 2010 From: news1234 at free.fr (News123) Date: Thu, 20 May 2010 22:46:59 +0200 Subject: intervall of about 1 second for xmlrpc calls? In-Reply-To: References: Message-ID: <4bf59fc3$0$23895$426a74cc@news.free.fr> Hi Adam, Adam Tauno Williams wrote: > On Thu, 2010-05-20 at 03:40 -0700, Thomas Lehmann wrote: >>> What's wrong? >> Obviously there's a problem with "localhost". When using the IP of my >> machine everything is working fast. I think you're right. localhost with IPV6 was also a problem for me. At least it was for me on a windows 7 host. I 'solved' the problem by disabling IPV6, but this is a workaround, not a proper solution. > > You box may first be trying to connect to ::1 (ipv6) and when that fails > it falls back to 127.0.0.1. Make sure IPv6 is properly > configured/enabled and try the script again. Do you know why the default config of IPV6 could be wrong on a windows 7 host? Having no experience with IPV6: How should it be configured? How to detect issues? thanks N From awilliam at whitemice.org Thu May 20 16:58:03 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Thu, 20 May 2010 16:58:03 -0400 Subject: intervall of about 1 second for xmlrpc calls? In-Reply-To: <4bf59fc3$0$23895$426a74cc@news.free.fr> References: <4bf59fc3$0$23895$426a74cc@news.free.fr> Message-ID: <1274389083.7821.4.camel@linux-yu4c.site> On Thu, 2010-05-20 at 22:46 +0200, News123 wrote: > Hi Adam, > Adam Tauno Williams wrote: > > On Thu, 2010-05-20 at 03:40 -0700, Thomas Lehmann wrote: > >>> What's wrong? > >> Obviously there's a problem with "localhost". When using the IP of my > >> machine everything is working fast. > I think you're right. > localhost with IPV6 was also a problem for me. At least it was for me > on a windows 7 host. > I 'solved' the problem by disabling IPV6, but this is a workaround, not > a proper solution. > > You box may first be trying to connect to ::1 (ipv6) and when that fails > > it falls back to 127.0.0.1. Make sure IPv6 is properly > > configured/enabled and try the script again. > Do you know why the default config of IPV6 could be wrong on a windows > 7 host? No. This would seem to have something to do with the resolver. If you do a nslookup for localhost what does it say. > Having no experience with IPV6: Have lots, it's really nice. Once you get most things cut over. > How should it be configured? > How to detect issues? Does nslookup localhost return the correct result? That might depend on your DNS server - not your local host. Also "ping ::1"? -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From db3l.net at gmail.com Thu May 20 17:11:55 2010 From: db3l.net at gmail.com (David Bolen) Date: Thu, 20 May 2010 17:11:55 -0400 Subject: What's the matter with docs.python.org? References: Message-ID: Christian Mertes writes: > On Mi, 2010-05-19 at 16:42 -0700, Aahz wrote: >> Also, I think you need to pass the host HTTP header to access >> docs.python.org > > Look, I don't really want to read Python docs via telnet. I basically > wanted to point out that there is strange behaviour and someone might > feel responsible and look into it. I think the point is that if you are going to use telnet as a diagnostic tool you need to more accurately represent the browser. I just tried and using the Host header renders a completely different response than not (presumably because the server is using virtual hosting). With an appropriate "Host: docs.python.org" you get the actual documentation home page, without it you get the "page has moved" text you saw. It may or may not have anything to do with the original problem, but it probably does explain the response you got when you tried to use telnet as a test tool. -- David From jmcmonagle at NO.SPAM.velseis.com.au Thu May 20 18:02:30 2010 From: jmcmonagle at NO.SPAM.velseis.com.au (John McMonagle) Date: Fri, 21 May 2010 08:02:30 +1000 Subject: Display file names in Tkinter Listbox In-Reply-To: References: <4BF4CA7B.6000008@NO.SPAM.velseis.com.au> Message-ID: <4BF5B176.5040006@NO.SPAM.velseis.com.au> sit at home.com wrote: > I have made the modifications and it does print inside the listbox, > however they are all printed on the same line. > Sorry, I didn't realize askopenfilenames returned the filenames as a whitespace separated string, on my system they are returned as a tuple of strings. > My files are named Name.0 Name.1 Name.2 Name.3 etc so I would like > them to be printed sorted on a separate line. When I did a > type(fileNames) it showed me that it was in unicode and printed > character per line, so I tried it this way > > listFileNames = str(fileNames).split(' ') > for fileName in listFileNames: > self.lbox.insert(0, fileName) > > it works but does not print sorted. > > it prints > > name.2 > name.1 > name.0 > name.3 > > You obviously need to sort the list before you loop over the items and add them to your listbox. listFileNames = sorted(str(filenames).split() Regards, John From tdelaney at avaya.com Thu May 20 18:42:56 2010 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 21 May 2010 06:42:56 +0800 Subject: Picking a license In-Reply-To: <87ocgciotv.fsf@benfinney.id.au> References: <87r5ldbw3k.fsf@benfinney.id.au> <87fx1qji9t.fsf@benfinney.id.au> <87ocgciotv.fsf@benfinney.id.au> Message-ID: From: Ben Finney > This thread is already off-topic and too long. I'm conflicted about my role in that; > I have endeavoured only to address falsehoods that IMO were not otherwise being addressed. > > So I'll try to keep this brief. > > Ethan Furman writes: > >> This doesn't make sense to me, but I'm willing to learn -- how do you >> do this in practice? Are you really selling the software > > Perhaps in private email we can discuss what you mean by "really selling the software"; > it's too off-topic here. By my understanding of that term, yes, I am selling software. > >> or rather selling things like setup, support, new code (or time to >> code), etc? > >All of the above, depending on the project. Considering that's one of the only two interesting things that have come out of this discussion, if you're willing to discuss that in public (in another thread) I'd be very interested in reading it. BTW, the other interesting thing is the inadvertent license violations where I tend to think Pat has the right interpretation, but am not sure. For the record, I tend to be in favour of permissive licenses both for releasing my own code and using others' (not least because I am employed by a company and it makes my work easier), but there are good reasons for using any license so long as you understand the consequences of your decision. Tim Delaney From sit at home.com Thu May 20 19:26:41 2010 From: sit at home.com (sit at home.com) Date: Thu, 20 May 2010 19:26:41 -0400 Subject: Display file names in Tkinter Listbox References: <4BF4CA7B.6000008@NO.SPAM.velseis.com.au> <4BF5B176.5040006@NO.SPAM.velseis.com.au> Message-ID: On Fri, 21 May 2010 08:02:30 +1000, John McMonagle wrote: >sit at home.com wrote: > >> I have made the modifications and it does print inside the listbox, >> however they are all printed on the same line. >> > >Sorry, I didn't realize askopenfilenames returned the filenames as a >whitespace separated string, on my system they are returned as a tuple >of strings. > > >> My files are named Name.0 Name.1 Name.2 Name.3 etc so I would like >> them to be printed sorted on a separate line. When I did a >> type(fileNames) it showed me that it was in unicode and printed >> character per line, so I tried it this way >> >> listFileNames = str(fileNames).split(' ') >> for fileName in listFileNames: >> self.lbox.insert(0, fileName) >> >> it works but does not print sorted. >> >> it prints >> >> name.2 >> name.1 >> name.0 >> name.3 >> >> > >You obviously need to sort the list before you loop over the items and >add them to your listbox. > >listFileNames = sorted(str(filenames).split() > > >Regards, > >John Thank you, it worked From catphive at catphive.net Thu May 20 19:57:40 2010 From: catphive at catphive.net (Brendan Miller) Date: Thu, 20 May 2010 16:57:40 -0700 Subject: starting repl programmatically Message-ID: I have a python script that sets up some environmental stuff. I would then like to be able to change back to interactive mode and use that environment. What's the best way to do that? From catphive at catphive.net Thu May 20 20:11:17 2010 From: catphive at catphive.net (Brendan Miller) Date: Thu, 20 May 2010 17:11:17 -0700 Subject: starting repl programmatically In-Reply-To: References: Message-ID: python -i myscript.py almost does what I want. The only problem is if I exit with exit(0) it does *not* enter interactive mode. I have to run off the end of the script as near as I can tell. Is there another way to exit without breaking python -i? On Thu, May 20, 2010 at 4:57 PM, Brendan Miller wrote: > I have a python script that sets up some environmental stuff. I would > then like to be able to change back to interactive mode and use that > environment. What's the best way to do that? > From stef.mientki at gmail.com Thu May 20 20:13:30 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 21 May 2010 02:13:30 +0200 Subject: Ugly modification of a class, can it be done better ? Message-ID: <4BF5D02A.9070600@gmail.com> hello, This might be a strange question, but as a practical guy, I'm not searching for the best solution, but for a practical solution. I've a class which I've used very extensively. Now I want to extend that class with an action on a double click event, but that action is determined by the main program. Normally I would create an derived class and add that specific action. But I find it too much effort in this specific case, half of the instances need the extension, half of it dont. So I want to change the behavior of the class dynamically. I've done it by adding a global variable (Base_Grid_Double_Click) in the module, initial set to None, but can be changed by the main program to some callback function. (see the code below) Is this a valid construction ( sorry I'm not a programmer), or are there better ways to accomplish similar dynamic behavior ? thanks, Stef Mientki #== module grid_library == Base_Grid_Double_Click = None class Base_Grid ( wx.grid.Grid ) : def __init__ ( self, .... self.Bind ( gridlib.EVT_GRID_CELL_LEFT_DCLICK , self._On_Double_Click ) def _On_Double_Click ( self, event ) : if Base_Grid_Double_Click : Row = event.Row Col = event.Col Col_Label = self.GetColLabelValue ( Col ) Row_Label = self.GetRowLabelValue ( Row ) Base_Grid_Double_Click ( self.GetCellValue ( Row, Col ), Col_Label, Row_Label ) else : event.Skip () -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu May 20 20:20:07 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 May 2010 00:20:07 GMT Subject: starting repl programmatically References: Message-ID: <4bf5d1b7$0$27861$c3e8da3@news.astraweb.com> On Thu, 20 May 2010 16:57:40 -0700, Brendan Miller wrote: > I have a python script that sets up some environmental stuff. I would > then like to be able to change back to interactive mode and use that > environment. What's the best way to do that? On most(?) Linux distros, `man python` is your friend. (Like all well- behaviour apps, python should come with a man page.) `python --help` is useful too, and will be platform independent. Both tell me that you want to pass -i as an option to enter the interactive interpreter after running a module or command: [steve at sylar ~]$ python -c "print 'hello world'; x = 2" hello world [steve at sylar ~]$ python -i -c "print 'hello world'; x = 2" hello world >>> x 2 You can also set an environment variable to force the same behaviour. See the help for details. -- Steven From jackdied at gmail.com Thu May 20 20:30:54 2010 From: jackdied at gmail.com (Jack Diederich) Date: Thu, 20 May 2010 20:30:54 -0400 Subject: Ugly modification of a class, can it be done better ? In-Reply-To: <4BF5D02A.9070600@gmail.com> References: <4BF5D02A.9070600@gmail.com> Message-ID: On Thu, May 20, 2010 at 8:13 PM, Stef Mientki wrote: > hello, > > This might be a strange question, but as a practical guy, I'm not searching > for the best solution, but for a practical solution. > > I've a class which I've used very extensively. > Now I want to extend that class with an action on a double click event, but > that action is determined by the main program. > Normally I would create an derived class and add that specific action. > But I find it too much effort in this specific case, half of the instances > need the extension, half of it dont. > So I want to change the behavior of the class dynamically. > I've done it by adding a global variable (Base_Grid_Double_Click) in the > module, > initial set to None, > but can be changed by the main program to some callback function. > (see the code below) > Is this a valid construction ( sorry I'm not a programmer), > or are there better ways to accomplish similar dynamic behavior ? > You can have two classes and then just change the class of the instances that need it. class A(object): def method1(self): pass class B(A): def method2(self): pass ob = A() # click happens ob.__class__ = B -Jack From pmaupin at gmail.com Thu May 20 20:35:06 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 20 May 2010 17:35:06 -0700 (PDT) Subject: starting repl programmatically References: Message-ID: On May 20, 6:57?pm, Brendan Miller wrote: > I have a python script that sets up some environmental stuff. I would > then like to be able to change back to interactive mode and use that > environment. What's the best way to do that? >>> import cmd >>> class MyCmd(cmd.Cmd): ... def default(self, line): ... exec line in globals() ... >>> MyCmd().cmdloop() (Cmd) s = 'The answer is probably to use %s' (Cmd) print s % 'the cmd module' The answer is probably to use the cmd module (Cmd) Regards, Pat From steve at REMOVE-THIS-cybersource.com.au Thu May 20 20:51:34 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 May 2010 00:51:34 GMT Subject: starting repl programmatically References: Message-ID: <4bf5d915$0$27861$c3e8da3@news.astraweb.com> On Thu, 20 May 2010 17:11:17 -0700, Brendan Miller wrote: > python -i myscript.py > > almost does what I want. The only problem is if I exit with exit(0) it > does *not* enter interactive mode. I have to run off the end of the > script as near as I can tell. Is there another way to exit without > breaking python -i? Upgrade to Python 2.6 and it will work as expected. [steve at sylar ~]$ python2.6 -i -c "import sys; sys.exit(0)" Traceback (most recent call last): File "", line 1, in SystemExit: 0 >>> If you're stuck with 2.5, you can wrap your script in a try...except and catch the exit: [steve at sylar ~]$ python -i -c "import sys > try: > x = 2 > sys.exit(0) > except SystemExit: > pass > " >>> x 2 The only side-effect I can think of is that you may lose any non-zero result codes, but you probably do that after entering interactive mode anyway. If you want to be fancy, you can inspect the state of the environment variable and Python options inside the except block, and re-raise if necessary. Untested: except SystemExit: if os.getenv('PYTHONINSPECT'): pass else: raise I can't find a way to check for a -i switch from inside Python 2.5. There is a sys.flags but it is only available in Python 2.6 or higher. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu May 20 21:27:59 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 May 2010 01:27:59 GMT Subject: Ugly modification of a class, can it be done better ? References: <4BF5D02A.9070600@gmail.com> Message-ID: <4bf5e19e$0$27861$c3e8da3@news.astraweb.com> Sorry for breaking threading, but Stef's original post has not come through to me. > On Thu, May 20, 2010 at 8:13 PM, Stef Mientki > wrote: >> So I want to change the behavior of the class dynamically. I've done it >> by adding a global variable (Base_Grid_Double_Click) in the module, >> initial set to None, >> but can be changed by the main program to some callback function. (see >> the code below) How is this supposed to work? If you have *one* global, then *every* instance will see the same setting. To change it dynamically, you enter a nightmare world of having to save the global, modify it, then restore it, every single time. Trust me, I've been there, this is the *worst* way of programming. This is why object oriented inheritance was invented, to escape this nonsense! The first thing is to make the callback specific to the class, not global. Why does your printing code need access to the callback that handles double-clicking on a grid? It doesn't! So don't give it that access (at least, not easy access). Put the callback in the class. class MyClass: callback = None def method(self, *args): if self.callback is None: behaviour_with_no_callback() else: behaviour_with_callback() Now if you want to apply a callback to some instances, and not others, it is totally simple: red = MyClass() blue = MyClass() red.callback = my_callback_function and you're done. If you have lots of instances that use the same callback? Make a subclass. class MyDottedClass(MyClass): pass red = MyClass() blue = MyClass() red_with_green_dots = MyDottedClass() blue_with_green_dots = MyDottedClass() MyDottedClass.callback = dotted_callback And now all the dot instances will use the same callback without effecting the undotted instances. What to change them all to use a different behaviour? MyDottedClass.callback = something_different and now they all change, again without effecting the undotted instances. >> Is this a valid construction ( sorry I'm not a programmer), or are >> there better ways to accomplish similar dynamic behavior ? Of course you're a programmer! You're writing programs, aren't you? -- Steven From darcy at druid.net Thu May 20 22:11:42 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 20 May 2010 22:11:42 -0400 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> <4bf5497f$0$12123$4fafbaef@reader4.news.tin.it> <4bf5814b$0$12129$4fafbaef@reader4.news.tin.it> Message-ID: <20100520221142.3b810d8d.darcy@druid.net> On Thu, 20 May 2010 19:53:42 +0000 (UTC) Grant Edwards wrote: > Since Python is interactive, and you don't get charged for each time > you run your deck through the reader, that's easy enough to check: Whoa! For a moment there I thought it was 1969. :-) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From mehgcap at gmail.com Thu May 20 22:56:42 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 20 May 2010 22:56:42 -0400 Subject: optional argument to a subclass of a class Message-ID: Hi all, I am now trying to allow my classes, all of which subclass a single class (if that is the term), to provide optional arguments. Here is some of my code: class Craft(): def __init__(self, name, isAircraft=False, id=helpers.id(), hits=0, weapons=[]): self.name=name self.id=id self.hits=hits self.weapons=weapons self.isAircraft=isAircraft #end def #end class #now a class for each type of craft in the game #each will subclass the Craft class, but each also has its own settings class Battleship(Craft): def __init__(self, name, maxHits): Craft.__init__(self, name) self.maxHits=maxHits self.length=maxHits #in Battleship, each ship's length is the same as how many times it can be hit #end def #end class I want to be able to say something like b=Battleship("battleship1", 4, weapons=["missile1","missile2"]) When I do that, though, I get a traceback on the above line saying "type error: __init__() got an unexpected keyword argument 'weapons'". What did I do wrong / what do I need to change so that any Craft (Battleship, Carrier, and so on) can optionally provide a list of weapons, or any other arguments to which I assign default values in my Craft class? I hope this makes sense. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From pmaupin at gmail.com Thu May 20 23:04:53 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 20 May 2010 20:04:53 -0700 (PDT) Subject: optional argument to a subclass of a class References: Message-ID: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> On May 20, 9:56?pm, Alex Hall wrote: > Hi all, > I am now trying to allow my classes, all of which subclass a single > class (if that is the term), to provide optional arguments. Here is > some of my code: > > class Craft(): > ?def __init__(self, > ?name, > ?isAircraft=False, > ?id=helpers.id(), > ?hits=0, > ?weapons=[]): > ? self.name=name > ? self.id=id > ? self.hits=hits > ? self.weapons=weapons > ? self.isAircraft=isAircraft > ?#end def > #end class > > #now a class for each type of craft in the game > #each will subclass the Craft class, but each also has its own settings > > class Battleship(Craft): > ?def __init__(self, > ?name, > ?maxHits): > ? Craft.__init__(self, name) > ? self.maxHits=maxHits > ? self.length=maxHits #in Battleship, each ship's length is the same > as how many times it can be hit > ?#end def > #end class > > I want to be able to say something like > b=Battleship("battleship1", 4, weapons=["missile1","missile2"]) > When I do that, though, I get a traceback on the above line saying > "type error: __init__() got an unexpected keyword argument 'weapons'". > What did I do wrong / what do I need to change so that any Craft > (Battleship, Carrier, and so on) can optionally provide a list of > weapons, or any other arguments to which I assign default values in my > Craft class? I hope this makes sense. > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg... at gmail.com;http://www.facebook.com/mehgcap You overrode the __init__method from the superclass. One thing you can do is in battleship, you can accept additional keyword arguments: def __init__(self, name, ..., **kw): Then you could invoke the superclass's init: Craft.__init__(self, name, **kw) Regards, Pat From mehgcap at gmail.com Thu May 20 23:35:01 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 20 May 2010 23:35:01 -0400 Subject: optional argument to a subclass of a class In-Reply-To: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> Message-ID: On 5/20/10, Patrick Maupin wrote: > On May 20, 9:56 pm, Alex Hall wrote: >> Hi all, >> I am now trying to allow my classes, all of which subclass a single >> class (if that is the term), to provide optional arguments. Here is >> some of my code: >> >> class Craft(): >> def __init__(self, >> name, >> isAircraft=False, >> id=helpers.id(), >> hits=0, >> weapons=[]): >> self.name=name >> self.id=id >> self.hits=hits >> self.weapons=weapons >> self.isAircraft=isAircraft >> #end def >> #end class >> >> #now a class for each type of craft in the game >> #each will subclass the Craft class, but each also has its own settings >> >> class Battleship(Craft): >> def __init__(self, >> name, >> maxHits): >> Craft.__init__(self, name) >> self.maxHits=maxHits >> self.length=maxHits #in Battleship, each ship's length is the same >> as how many times it can be hit >> #end def >> #end class >> >> I want to be able to say something like >> b=Battleship("battleship1", 4, weapons=["missile1","missile2"]) >> When I do that, though, I get a traceback on the above line saying >> "type error: __init__() got an unexpected keyword argument 'weapons'". >> What did I do wrong / what do I need to change so that any Craft >> (Battleship, Carrier, and so on) can optionally provide a list of >> weapons, or any other arguments to which I assign default values in my >> Craft class? I hope this makes sense. >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehg... at gmail.com;http://www.facebook.com/mehgcap > > You overrode the __init__method from the superclass. I know, I thought I had to in order to make all of Craft's attribs available to the Battleship. Is that not the case? > > One thing you can do is in battleship, you can accept additional > keyword arguments: > > def __init__(self, name, ..., **kw): > > Then you could invoke the superclass's init: > > Craft.__init__(self, name, **kw) So how do I get at anything inside **kw? Is it a list? > > Regards, > Pat > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From wuwei23 at gmail.com Thu May 20 23:50:54 2010 From: wuwei23 at gmail.com (alex23) Date: Thu, 20 May 2010 20:50:54 -0700 (PDT) Subject: optional argument to a subclass of a class References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> Message-ID: <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> Patrick Maupin wrote: > One thing you can do is in battleship, you can accept additional > keyword arguments: > > ? ? def __init__(self, name, ..., **kw): > > Then you could invoke the superclass's init: > > ? ? Craft.__init__(self, name, **kw) _All_ of which is covered in the tutorial. At what point do we expect people to actually put some effort into learning the language themselves? Is this why we're constantly spammed with "write my code for me" requests? If you're asking _basic_ "how do I" questions, and you don't even have the common sense to read through the support docs before doing so, then you really should be directing questions here: http://mail.python.org/mailman/listinfo/tutor From pmaupin at gmail.com Thu May 20 23:51:21 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 20 May 2010 20:51:21 -0700 (PDT) Subject: optional argument to a subclass of a class References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> Message-ID: <9c894192-e758-49f3-91e9-ca2554c90b10@j9g2000vbp.googlegroups.com> On May 20, 10:35?pm, Alex Hall wrote: > So how do I get at anything inside **kw? Is it a list? It's a dictionary. Use *args for a list. (As with self, the name is whatever you want to use, but some sort of consistency is nice.) One of the cool things about Python is how easy it is to play at the command prompt: >>> def foo(x=3, y=7): ... print x,y ... >>> def sam(**kw): ... print kw ... foo(**kw) ... >>> sam(x=5) {'x': 5} 5 7 >>> sam(y='hi there') {'y': 'hi there'} 3 hi there >>> sam(z=42) {'z': 42} Traceback (most recent call last): File "", line 1, in File "", line 3, in sam TypeError: foo() got an unexpected keyword argument 'z' >>> Regards, Pat From mehgcap at gmail.com Fri May 21 00:22:11 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 00:22:11 -0400 Subject: optional argument to a subclass of a class In-Reply-To: <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> Message-ID: On 5/20/10, alex23 wrote: > Patrick Maupin wrote: >> One thing you can do is in battleship, you can accept additional >> keyword arguments: >> >> def __init__(self, name, ..., **kw): >> >> Then you could invoke the superclass's init: >> >> Craft.__init__(self, name, **kw) > > _All_ of which is covered in the tutorial. At what point do we expect > people to actually put some effort into learning the language > themselves? Is this why we're constantly spammed with "write my code > for me" requests? I am certainly NOT asking anyone to write my code for me. In fact, I almost never copy and paste code, since writing it myself helps me to both remember it and examine it to see what is going on and figure out why it works. I am basically teaching myself Python; my experience is in Java (basic), JS (somewhat advanced), and a smattering of other languages. I have rarely dealt with classes before, and certainly not sub-classing. I have googled all of this and have read the docs and tutorials, but nothing made sense enough for me to figure out why I would be getting my particular error. I have since updated each ship's __init__ to accept all the arguments that Craft accepts so that I can support all optional arguments, but I thought subclassing was supposed to take care of this for me... Suppose not. > > If you're asking _basic_ "how do I" questions, and you don't even have > the common sense to read through the support docs before doing so, > then you really should be directing questions here: > http://mail.python.org/mailman/listinfo/tutor Again, I have read the docs. I often find them quite useful, but there are times where a new concept, in a relatively new language, just will not work and a doc is not going to say "at this point in your code, you should to A instead of B, because..." > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From dpalmboom at evafoam.co.za Fri May 21 02:03:43 2010 From: dpalmboom at evafoam.co.za (dpalmboom) Date: Fri, 21 May 2010 08:03:43 +0200 Subject: Help with PyQt4 tabwidget setup Message-ID: I am creating an application and I'm busy designing the main layout on the main window. What I would like to do is the following: Create a QTabWidget with a QVBoxLayout already inside it and also a scrollbar inside it. When a user triggers a menu item, a QDockWidget must be created and inserted into the QVBoxLayout, but it must not stretch to the bottom of the QTabWidget. The QDockWidget must keep a set size in the QVBoxLayout. When the user triggers another menu item, the next QDockWidget must go above or below the existing QDockWidgets in the QVBoxLayout. I currently have the following code for the QTabWidget: class PaneTabWidget(PyQt4.QtGui.QTabWidget): def __init__(self, tabs, parent=None): """ A tabwidget to go inside a Pane. """ super(PaneTabWidget, self).__init__(parent) for tab in tabs: if tab == "Properties": self.propertiesBin() elif tab == "Schedule": self.scheduleBin() elif tab == "Pricelist": self.pricelistBin() def setLayoutAndScrollBar(self, page): pass def addPanel(self, panel, type): self.addTab(panel, type) def propertiesBin(self): self.page = PyQt4.QtGui.QWidget() self.addTab(self.page, "Properties") self.setLayoutAndScrollBar(self.page) Right now, the dockwidget gets put into a new tab in the tab widget, but I would like to put it into an existing QVBoxLayout. I currently have a blank QWidget as a "placeholder" page of the tabwidget. If anyone can help me with this, it would be greatly appreciated. Thanks From chricki at gmx.net Fri May 21 02:51:44 2010 From: chricki at gmx.net (chris) Date: Fri, 21 May 2010 08:51:44 +0200 Subject: socket.getsockopt() and SO_ORIGINAL_DST Message-ID: Hi guys, On netfilter-based NAT systems there is theoretically a possibility to retrieve the original address *after* NAT'ing a connection. In C, this can be done as in squid, a transparent HTTP proxy: http://paste.pocoo.org/show/216495/ I'd like to do the same in Python. So I started with a small script: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 2626)) s.listen(1) conn, addr = s.accept() dst = conn.getsockopt(socket.SOL_IP, socket.SO_ORIGINAL_DST) Since SO_ORIGINAL_DST is not defined in socket.py, the program fails: AttributeError: 'module' object has no attribute 'SO_ORIGINAL_DST' So I thought I'd be smart and look up the constant myself. Indeed, I found it to be defined in: /usr/include/linux/netfilter_ipv4.h:75:#define SO_ORIGINAL_DST 80 I replaced the getsockopt() call with dst = conn.getsockopt(socket.SOL_IP, 80) and ran into a new problem: Traceback (most recent call last): File "listen.py", line 14, in dst = conn.getsockopt(socket.SOL_IP, 80) File "", line 1, in getsockopt socket.error: [Errno 22] Invalid argument In C, everything works fine. But I really need this problem to be solved in Python. Do you have any ideas? Thanks for any support in advance and regards, Chris PS: I know there are ugly work-arounds to parse /proc/net/ip_conntrack to do this job, but I will defenitely avoid that. From rnlatimer at gmail.com Fri May 21 03:19:56 2010 From: rnlatimer at gmail.com (Neal) Date: Fri, 21 May 2010 00:19:56 -0700 (PDT) Subject: Solutions for finding the 1000th prime Message-ID: I'm doing the MIT OpenCourseWare class that this assignment hails from and I don't doubt that its a relatively common assignment. Upon searching for it for some ideas of why my program wouldn't work one of the top results is this a thread from this group full of derision and sarcasm. Believe me I understand that the people here don't want to do another person's homework but for someone who isn't going to be coding for a living or is a hobbyist like I am, there could be some useful information. Eventually I figured out what I was doing wrong, and I was hoping to add some insight. At this point in the lectures about all we've learned to deal with as far as commands are: while, if, else, elif and some boolean operators. I started defining three variables I would need: One to count how many primes I have Which number I'm currently checking to be a prime Current number I'm dividing by as my checker The assignment states that its easiest to check all odd integers > 1 but not to forget that 2 is a prime, easiest probably just to start your counter at 1, I didn't but it took an extra 3 lines just to get my counter to 1, and then get to the next number I'm checking all without being in a usable loop. You start your loop with the stated condition, no need for it to run any more past counting the 1000th prime. You could have your program check to see if a number is divisible by every number less than itself and if so moving on to your next number. However you do know that any number isn't going to be divisible by another number in that sequence until it reaches itself divided by 2. If you keep in mind though that we are only dealing with odd numbers, you know that they will not be divisible by two, so instead we can move on to itself divided by 3. Every iteration of the loop when it finds a prime, needs to increase the count, move onto the next candidate you're checking, and redefine the divisor you're starting to check next time around. If a number is determined not to be a prime you need to move onto the next candidate and redefine your divisor (which is where I was stuck for a long time writing this program). If your not sure that the number is a prime or not a prime you simply need to redefine the divisor and continue the loop. From steve at REMOVE-THIS-cybersource.com.au Fri May 21 03:43:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 May 2010 07:43:37 GMT Subject: optional argument to a subclass of a class References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> Message-ID: <4bf639a9$0$27861$c3e8da3@news.astraweb.com> On Thu, 20 May 2010 23:35:01 -0400, Alex Hall wrote: >> You overrode the __init__method from the superclass. > > I know, I thought I had to in order to make all of Craft's attribs > available to the Battleship. Is that not the case? No, the opposite in fact. One of the basic features of objects (at least as implemented by Python, and many other languages) is inheritance. That is, a class inherits behaviour and state (methods and attributes) from its parent class (or classes). So if you have a class A and a subclass B, B inherits behaviour from A: >>> class A: ... def method(self): ... print("method in A") ... >>> class B(A): ... pass ... >>> b = B() >>> b.method() method in A But if you override method, then Python doesn't *automatically* call the parent's method. How can it know where to call it, and what to do with the result? Should it call it before the new method, or after, or somewhere in the middle? It's impossible to tell. >>> class C(A): ... def method(self): ... print("called from C") ... >>> c = C() >>> c.method() called from C If you want both behaviours, then you have to explicitly call the parent class, and pass the current instance as an argument: >>> class D(A): ... def method(self): ... print("called from D") ... A.method(self) ... >>> d = D() >>> d.method() called from D method in A Exactly the same rules apply to __init__, with the added complication that frequently you want to modify the function signature: >>> class Sandwich: ... def __init__(self, filling, bread='white'): ... self.filling = filling ... self.bread = bread ... def __str__(self): ... return ("%s on two slices of %s bread" % ... (self.filling, self.bread)) ... >>> s = Sandwich("cheese", "rye") >>> print(s) cheese on two slices of rye bread >>> >>> class BLT(Sandwich): ... def __init__(self): ... Sandwich.__init__(self, "bacon, lettuce and tomato", ... "sour dough") ... >>> b = BLT() >>> print(b) bacon, lettuce and tomato on two slices of sour dough bread Hope this helps. -- Steven From __peter__ at web.de Fri May 21 04:07:47 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2010 10:07:47 +0200 Subject: optional argument to a subclass of a class References: Message-ID: Alex Hall wrote: > Hi all, > I am now trying to allow my classes, all of which subclass a single > class (if that is the term), to provide optional arguments. Here is > some of my code: > > class Craft(): > def __init__(self, > name, > isAircraft=False, > id=helpers.id(), > hits=0, > weapons=[]): > self.name=name > self.id=id > self.hits=hits > self.weapons=weapons > self.isAircraft=isAircraft > #end def > #end class > > > #now a class for each type of craft in the game > #each will subclass the Craft class, but each also has its own settings > > class Battleship(Craft): > def __init__(self, > name, > maxHits): > Craft.__init__(self, name) > self.maxHits=maxHits > self.length=maxHits #in Battleship, each ship's length is the same > as how many times it can be hit > #end def > #end class > > > I want to be able to say something like > b=Battleship("battleship1", 4, weapons=["missile1","missile2"]) > When I do that, though, I get a traceback on the above line saying > "type error: __init__() got an unexpected keyword argument 'weapons'". > What did I do wrong / what do I need to change so that any Craft > (Battleship, Carrier, and so on) can optionally provide a list of > weapons, or any other arguments to which I assign default values in my > Craft class? I hope this makes sense. You have to repeat the arguments for the base class in the Battleship initializer. Battleship(...) will only invoke Battleship.__init__(...), not Craft.__init__(...) -- so you have to do that explicitly inside Battleship.__init__() while passing along all parameters it is supposed to process. As simplified example: class Craft(object): def __init__(self, name, id=None, weapons=None): if id is None: id = helpers.id() if weapons is None: weapons = [] self.name = name self.id = id self.weapons = weapons class Battleship(Craft): def __init__(self, name, id=None, weapons=None, max_hits=None): Craft.__init__(self, name, id, weapons) self.max_hits = max_hits Notice how using None to signal that a value was not provided simplifies things; without it you'd have to put a meanigful default for weapons into both the Craft and Battleship class. If you want a unique id for every Craft providing helpers.id() as a default is just wrong; default arguments are calculated once and you would end up with the same id for every Craft instance. Peter From chricki at gmx.net Fri May 21 04:26:04 2010 From: chricki at gmx.net (chris) Date: Fri, 21 May 2010 10:26:04 +0200 Subject: socket.getsockopt() and SO_ORIGINAL_DST In-Reply-To: References: Message-ID: Hi guys, I found a solution myself in O'Reilly's Security Power Tools. It works seamlessly as follows: from socket import * SO_ORIGINAL_DST = 80 s = socket(AF_INET, SOCK_STREAM) s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) s.bind(('192.168.255.254', 80)) s.listen(1) conn, addr = s.accept() dst = conn.getsockopt(SOL_IP, SO_ORIGINAL_DST, 16) srv_port, srv_ip = struct.unpack("!2xH4s8x", dst) print "original %s:%d" % (inet_ntoa(srv_ip), srv_port) Basically, my fault was not specifying the buffer length :( Have fun with it, whoever needs it. Regards, Chris chris wrote: > Hi guys, > > On netfilter-based NAT systems there is theoretically a possibility to > retrieve the original address *after* NAT'ing a connection. In C, this > can be done as in squid, a transparent HTTP proxy: > > http://paste.pocoo.org/show/216495/ > > > I'd like to do the same in Python. So I started with a small script: > > import socket > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind(('', 2626)) > s.listen(1) > conn, addr = s.accept() > dst = conn.getsockopt(socket.SOL_IP, socket.SO_ORIGINAL_DST) > > > > Since SO_ORIGINAL_DST is not defined in socket.py, the program fails: > AttributeError: 'module' object has no attribute 'SO_ORIGINAL_DST' > > So I thought I'd be smart and look up the constant myself. Indeed, I > found it to be defined in: > > /usr/include/linux/netfilter_ipv4.h:75:#define SO_ORIGINAL_DST 80 > > I replaced the getsockopt() call with > > dst = conn.getsockopt(socket.SOL_IP, 80) > > and ran into a new problem: > > Traceback (most recent call last): > File "listen.py", line 14, in > dst = conn.getsockopt(socket.SOL_IP, 80) > File "", line 1, in getsockopt > socket.error: [Errno 22] Invalid argument > > > In C, everything works fine. But I really need this problem to be solved > in Python. Do you have any ideas? > > Thanks for any support in advance and regards, > Chris > > PS: I know there are ugly work-arounds to parse /proc/net/ip_conntrack > to do this job, but I will defenitely avoid that. > From __peter__ at web.de Fri May 21 04:36:31 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2010 10:36:31 +0200 Subject: Solutions for finding the 1000th prime References: Message-ID: Neal wrote: > I'm doing the MIT OpenCourseWare class that this assignment hails from > and I don't doubt that its a relatively common assignment. Upon > searching for it for some ideas of why my program wouldn't work one of > the top results is this a thread from this group full of derision and > sarcasm. Believe me I understand that the people here don't want to do > another person's homework but for someone who isn't going to be coding > for a living or is a hobbyist like I am, there could be some useful > information. Eventually I figured out what I was doing wrong, and I > was hoping to add some insight. At this point in the lectures about > all we've learned to deal with as far as commands are: while, if, > else, elif and some boolean operators. I'd like to bring your attention to my contribution to the above-mentioned thread. http://mail.python.org/pipermail/python-list/2009-November/1226626.html I posted it late in the thread's life because like you I disliked the direction the "discussion" was taking. My answer is not so much about an efficient solution to the actual problem, but more about how to approach a programming problem that initially seems to be over your head. As a long time reader I can confirm that if you show that you have made a minimum effort to solve even "homeworky" problems you usually get constructive hints on comp.lang.python. There is also a mailing list http://mail.python.org/mailman/listinfo/tutor for the absolute beginner. Peter From rafalgulinski at gmail.com Fri May 21 05:10:36 2010 From: rafalgulinski at gmail.com (rav) Date: Fri, 21 May 2010 02:10:36 -0700 (PDT) Subject: intervall of about 1 second for xmlrpc calls? References: Message-ID: I had similar problem with SimpleXMLRPCServer Create the request handler class class ExtendedXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): # originally this one was slowing down my server A LOT due to DNS settings!!! def log_request(self, *args): pass and put it in your SimpleXMLRPCServer constructor (...) class MyServer(threading.Thread): def __init__(self, host, port): threading.Thread.__init__(self) self.server = SimpleXMLRPCServer((host, port), ExtendedXMLRPCRequestHandler) self.server.register_function(self.is_even, "is_even") self.server.register_function(self.stop, "stop_server") (...) I would also change all 'localhost' occurences in the code to ip '127.0.0.1'. Good luck! Rafal From samuelrobertson at gmail.com Fri May 21 05:23:09 2010 From: samuelrobertson at gmail.com (sam) Date: Fri, 21 May 2010 02:23:09 -0700 (PDT) Subject: CGI python 3 write RAW BINARY References: <4bd8ae7e$0$27615$ba4acef3@reader.news.orange.fr> <4bd96540$0$27597$ba4acef3@reader.news.orange.fr> <4bd9b4c2$0$27606$ba4acef3@reader.news.orange.fr> <4bd9fc1a$0$2980$ba4acef3@reader.news.orange.fr> <4bdc07d4$0$2980$ba4acef3@reader.news.orange.fr> <4be424a8$0$27586$ba4acef3@reader.news.orange.fr> Message-ID: On May 7, 7:33?am, Dodo wrote: > Le 01/05/2010 12:52, Dodo a ?crit : > > > > > > > Le 30/04/2010 17:52, Antoine Pitrou a ?crit : > >> Le Thu, 29 Apr 2010 23:37:32 +0200, Dodo a ?crit : > >>> ....I don't get a thing. > >>> Now with the fix : > >>> All browsers shows a different thing, but not the image! > >>>http://ddclermont.homeip.net/misc/python/ > > >>> If I save it to computer : > >>> * Windows image viewer won't read it > >>> * Irfanview can read it without problems > > >> Did you set the content-type and content-length in the HTTP headers? > >> Can you post your code? > > > I didn't know about content-lenght > > Here's the new code (I used a fixed image patch to make sure this is not > > the source of the problem) > > > #!/usr/bin/python3 > > import cgi, sys, cgitb > > cgitb.enable() > > > f = open("/home/dodo/54.jpg", "rb") > > data = f.read() > > l = len(data) > > f.close() > > > print("Content-type:image/jpg\nContent-length:%d\n\n" % l) > > > sys.stdout.flush() > > sys.stdout.buffer.write( data ) > > > Dorian > > Anyone? Yes for windows you need to call this before you write it out. And yes its totally retarded that you have to do this. The whole point of python is that I don't have to worry about the particular system its running on. def __SetStdOutForWindowsToBinaryMode(): # Without this method a windows server will translate '\n' into '\r\n' # even for binary output. This probably isn't needed on linux servers # so the exception will be caught harmlessly. # At some point we may have to worry about switching this mode *back* to original # (see http://bytes.com/topic/python/answers/30987-cgi-proplem-displaying-image) try: import msvcrt,os msvcrt.setmode( 1, os.O_BINARY ) # 1 = stdout; use 0 for stdin except ImportError: pass From kaklis at gmail.com Fri May 21 06:12:03 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 21 May 2010 03:12:03 -0700 (PDT) Subject: client server console app with cmd library References: <5577f90a-e8d9-43b4-bad5-9a10b17a2fdd@e28g2000vbd.googlegroups.com> Message-ID: <25d0000c-acaf-43b5-ab97-f91c9d79b0e3@k31g2000vbu.googlegroups.com> On May 20, 1:54?am, "kak... at gmail.com" wrote: > Hi to all, > i need some hints about a console application i' m trying. > I want to make it act as a client and as a server at a same time. > And since it is a console application i' m using cmd library. > I want something that works like asterisk. while working with my app > i want to listen for incoming requests, that they appear automatically > at my console. > Any design considerations? > Do i have to use threads? > Please i want your advice. > Any examples somewhere? > > Thanks in advance! > Antonis Hi again. I wonder is my question stupid, or what i want can't be done? From doctoresam at gmail.com Fri May 21 06:21:11 2010 From: doctoresam at gmail.com (Deep_Feelings) Date: Fri, 21 May 2010 03:21:11 -0700 (PDT) Subject: where are the program that are written in python? Message-ID: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> python is not a new programming language ,it has been there for the last .... 15+ years or so ? right ? however by having a look at this page http://wiki.python.org/moin/Applications i could not see many programs written in python (i will be interested more in COMMERCIAL programs written in python ). and to be honest ,i tried some of the programs in that list and all the programs that i tried either dead projects or so buggy ! 1- where are the programs that is written in python ? 2- python is high productivity language : why there are no commercial programs written in python ? is python a valid practical programming language ? why it is not used in commercial software ? please don't mention programs where python was used as a glue ,those programs are not actually written in python. any help will be appreciated thank you From simon at brunningonline.net Fri May 21 06:35:40 2010 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 21 May 2010 11:35:40 +0100 Subject: where are the program that are written in python? In-Reply-To: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On 21 May 2010 11:21:11 UTC+1, Deep_Feelings wrote: > 1- where are the programs that is written in python ? > 2- python is high productivity language : why there are no commercial > programs written in python ? See http://www.python.org/about/success/ -- Cheers, Simon B. From martin.hellwig at dcuktec.org Fri May 21 06:37:42 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 21 May 2010 11:37:42 +0100 Subject: where are the program that are written in python? In-Reply-To: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On 05/21/10 11:21, Deep_Feelings wrote: > python is not a new programming language ,it has been there for the > last .... 15+ years or so ? right ? Yeah about the same as Java > > however by having a look at this page http://wiki.python.org/moin/Applications > i could not see many programs written in python (i will be interested > more in COMMERCIAL programs written in python ). and to be honest ,i > tried some of the programs in that list and all the programs that i > tried either dead projects or so buggy ! It's a wiki, if anybody is interested they could change the page, I actually have never looked at it. > > 1- where are the programs that is written in python ? > 2- python is high productivity language : why there are no commercial > programs written in python ? > > is python a valid practical programming language ? > why it is not used in commercial software ? My experience is that Python is the FreeBSD of the programming languages. For example, the average user knows mac and windows, the average admin knows there is also something like linux, and the average linux admin knows there is also something like BSD. > > please don't mention programs where python was used as a glue ,those > programs are not actually written in python. Python is used in a lot in custom applications, while off the shelve software needs a lot of buzzwords to shift any market interest. I have participated in a couple of 'pure' Python programs, used by Airbus, Randstad and a whole fleet of small firms. But yes, off the shelve software seems to be either written in Java or any .net equivalent. > > any help will be appreciated > > thank you hth -- mph From ninmonkeys at gmail.com Fri May 21 06:49:37 2010 From: ninmonkeys at gmail.com (Jake b) Date: Fri, 21 May 2010 05:49:37 -0500 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: did this not go to the list? Arg, reply does in other mailing list. On Fri, May 21, 2010 at 5:48 AM, Jake b wrote: > I took it as game-domain only question: > I don't know of any big game written in python. ( meaning python code, > using c++ libs. ) Verses games that at their is in c++ , calling a scripting > language under the hood. > Even if a game is written at its base in python, it still uses python > libraries which can use c++ under the hood. > > WoW had a huge amount of logic, in LUA combined with xml. Was cool seeing > the crazy things implemented. > > There are a lot that use a c++ engine, with a scripting engine under the > hood. python, lua, unrealscript, etc... Civ4 uses python for map generation. > Not sure how much else? > Wouldn't be surprised, alpha centauria even had text files you could mod > the game with. > > Unreal games: U, UT, UT2k4, etc.. (since before UT original, use > scripting(unreal script) to control basically everything.) There are > classes, and methods that 'do the work' in c++ for speed. > > From development point, You're on a deadline, if your company all know the > existing language/engine/api, there isn't much incentive to learn a new api, > and convert existing code, and not having all the previous examples, and > api's. [ That can even mean using game engine X, even if Y is in the same > language, and is technically better. ] > > > -- > Jake > -- Jake -------------- next part -------------- An HTML attachment was scrubbed... URL: From ninmonkeys at gmail.com Fri May 21 06:54:59 2010 From: ninmonkeys at gmail.com (Jake b) Date: Fri, 21 May 2010 05:54:59 -0500 Subject: client server console app with cmd library In-Reply-To: <25d0000c-acaf-43b5-ab97-f91c9d79b0e3@k31g2000vbu.googlegroups.com> References: <5577f90a-e8d9-43b4-bad5-9a10b17a2fdd@e28g2000vbd.googlegroups.com> <25d0000c-acaf-43b5-ab97-f91c9d79b0e3@k31g2000vbu.googlegroups.com> Message-ID: Networking can be hard. I'd suggest checking out these libs. pygame mastermind: http://www.pygame.org/project-Mastermind+Networking+Lib-859-1773.html podSixNet : http://mccormick.cx/projects/PodSixNet/ twisted: http://wiki.python.org/moin/Twisted-Examples lots of references in the answers to this StackOverflow post: http://stackoverflow.com/questions/78704/good-python-network-programing-resource Twisted is the hardest in that list to get into. -- Jake -------------- next part -------------- An HTML attachment was scrubbed... URL: From doctoresam at gmail.com Fri May 21 07:12:18 2010 From: doctoresam at gmail.com (Deep_Feelings) Date: Fri, 21 May 2010 04:12:18 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> On May 21, 1:35?pm, Simon Brunning wrote: > On 21 May 2010 11:21:11 UTC+1, Deep_Feelings wrote: > > Seehttp://www.python.org/about/success/ thankx for reply. from that list i have a feeling that python is acting only as "quick and dirty work" nothing more ! From stefan_ml at behnel.de Fri May 21 07:13:10 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 21 May 2010 13:13:10 +0200 Subject: [ANN] oStri: Cython optimized String object In-Reply-To: <20100521063717.GD37105@mail.fu-manchu.org> References: <20100521063717.GD37105@mail.fu-manchu.org> Message-ID: Mike 'Fuzzy' Partin, 21.05.2010 08:37: > Optimized String-like Object is kind of a misnomer in that, the object > provided is a subclass of the base str type, adding optimized (Cython > bindings to the standard (POSIX) libc regex and string functions) > match() and sub() methods. Hi, could you give an idea what the advantage of this package is? Why would one want to use it? Also, while the main class is a subclass of str, it doesn't take advantage of that fact at all. Stefan From news1234 at free.fr Fri May 21 07:19:40 2010 From: news1234 at free.fr (News123) Date: Fri, 21 May 2010 13:19:40 +0200 Subject: where are the program that are written in python? In-Reply-To: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: <4bf66c4c$0$22462$426a74cc@news.free.fr> Deep_Feelings wrote: > On May 21, 1:35 pm, Simon Brunning wrote: >> On 21 May 2010 11:21:11 UTC+1, Deep_Feelings wrote: >> >> Seehttp://www.python.org/about/success/ > > thankx for reply. > > from that list i have a feeling that python is acting only as "quick > and dirty work" nothing more ! Too bad, that still nobody feels insulted isn't it? From sunckell at gmail.com Fri May 21 07:20:25 2010 From: sunckell at gmail.com (Chad Kellerman) Date: Fri, 21 May 2010 07:20:25 -0400 Subject: unique values of a Dictionary list (removing duplicate elements of a list) Message-ID: Python users, I am parsing an AIX trace file and creating a dictionary containing keys (PIDS) and values (a list of TIDS). With PIDS being unique process ids and TIDS, being a list of thread ids. My function populates the keys so that they are unique, but my list contains duplicates. Can someone point me in the right direction so that my dictionary value does not contain duplicate elements? here is what I got. -------------------------------- pidtids = {} # --- function to add pid and tid to a dictionary def addpidtids(pid,tid): pidtids.setdefault(pid,[]).append(tid) # --- function to parse a file def grep(pattern, fileObj, include_line_nums=False): r=[] compgrep = re.compile(pattern) for line_num, line in enumerate(fileObj): if compgrep.search(line): info = line.split() p = info[7].lstrip("pid=") t = info[8].lstrip("tid=") addpidtids(p,t) # process trace.int tf = open(tracefile, 'r') grep("cmd=java pid",tf) tf.close() -------------------------------- Any help would be greatly appreciated. Thanks, Chad -- A grasshopper walks into a bar and the bartender says "Hey, we have a drink named after you." And the grasshopper says "Really, You have a drink named Murray?" -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Fri May 21 07:22:27 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 21 May 2010 21:22:27 +1000 Subject: where are the program that are written in python? In-Reply-To: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: On Fri, May 21, 2010 at 9:12 PM, Deep_Feelings wrote: > thankx for reply. > > from that list i have a feeling that python is acting only as "quick > and dirty work" nothing more ! > You might have just offended a lot of people on the list here.... Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon at brunningonline.net Fri May 21 07:28:34 2010 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 21 May 2010 12:28:34 +0100 Subject: where are the program that are written in python? In-Reply-To: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: On 21 May 2010 12:12:18 UTC+1, Deep_Feelings wrote: > from that list i have a feeling that python is acting only as "quick > and dirty work" nothing more ! Really? Well, in any case, I can tell you that I know of a number of large commercial web sites built with Django. I just can't tell you what they are. ;-) -- Cheers, Simon B. From wolfgang at rohdewald.de Fri May 21 07:32:12 2010 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Fri, 21 May 2010 13:32:12 +0200 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <201005211332.12853.wolfgang@rohdewald.de> On Freitag 21 Mai 2010, Jake b wrote: > > I don't know of any big game written in python. ( meaning > > python code, using c++ libs would you call 8702 python statements big? If so, Kajongg would be a candidate. -- Wolfgang From __peter__ at web.de Fri May 21 07:50:06 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2010 13:50:06 +0200 Subject: unique values of a Dictionary list (removing duplicate elements of a list) References: Message-ID: Chad Kellerman wrote: > Python users, > I am parsing an AIX trace file and creating a dictionary containing > keys (PIDS) and values (a list of TIDS). With PIDS being unique process > ids > and TIDS, being a list of thread ids. My function populates the keys so > that they are unique, but my list contains duplicates. > > Can someone point me in the right direction so that my dictionary > value > does not contain duplicate elements? > > > here is what I got. > > -------------------------------- > > pidtids = {} > > # --- function to add pid and tid to a dictionary > def addpidtids(pid,tid): > pidtids.setdefault(pid,[]).append(tid) Use a set instead of a list (and maybe a defaultdict): from collections import defaultdict pidtids = defaultdict(set) def addpidtids(pid, tid): pidtids[pid].add(tid) Peter From sunckell at gmail.com Fri May 21 08:07:49 2010 From: sunckell at gmail.com (Chad Kellerman) Date: Fri, 21 May 2010 08:07:49 -0400 Subject: unique values of a Dictionary list (removing duplicate elements of a list) In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__peter__ at web.de> wrote: > Chad Kellerman wrote: > > > Python users, > > I am parsing an AIX trace file and creating a dictionary containing > > keys (PIDS) and values (a list of TIDS). With PIDS being unique process > > ids > > and TIDS, being a list of thread ids. My function populates the keys so > > that they are unique, but my list contains duplicates. > > > > Can someone point me in the right direction so that my dictionary > > value > > does not contain duplicate elements? > > > > > > here is what I got. > > > > -------------------------------- > > > > pidtids = {} > > > > # --- function to add pid and tid to a dictionary > > def addpidtids(pid,tid): > > pidtids.setdefault(pid,[]).append(tid) > > Use a set instead of a list (and maybe a defaultdict): > > from collections import defaultdict > > pidtids = defaultdict(set) > > def addpidtids(pid, tid): > pidtids[pid].add(tid) > > Peter > Thanks. I guess I should have posted this in my original question. I'm on 2.4.3 looks like defautldict is new in 2.5. I'll see if I can upgrade. Thanks again. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- A grasshopper walks into a bar and the bartender says "Hey, we have a drink named after you." And the grasshopper says "Really, You have a drink named Murray?" -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri May 21 08:13:53 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 08:13:53 -0400 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On 5/21/10, Peter Otten <__peter__ at web.de> wrote: > Alex Hall wrote: > >> Hi all, >> I am now trying to allow my classes, all of which subclass a single >> class (if that is the term), to provide optional arguments. Here is >> some of my code: >> >> class Craft(): >> def __init__(self, >> name, >> isAircraft=False, >> id=helpers.id(), >> hits=0, >> weapons=[]): >> self.name=name >> self.id=id >> self.hits=hits >> self.weapons=weapons >> self.isAircraft=isAircraft >> #end def >> #end class >> >> >> #now a class for each type of craft in the game >> #each will subclass the Craft class, but each also has its own settings >> >> class Battleship(Craft): >> def __init__(self, >> name, >> maxHits): >> Craft.__init__(self, name) >> self.maxHits=maxHits >> self.length=maxHits #in Battleship, each ship's length is the same >> as how many times it can be hit >> #end def >> #end class >> >> >> I want to be able to say something like >> b=Battleship("battleship1", 4, weapons=["missile1","missile2"]) >> When I do that, though, I get a traceback on the above line saying >> "type error: __init__() got an unexpected keyword argument 'weapons'". >> What did I do wrong / what do I need to change so that any Craft >> (Battleship, Carrier, and so on) can optionally provide a list of >> weapons, or any other arguments to which I assign default values in my >> Craft class? I hope this makes sense. > > You have to repeat the arguments for the base class in the Battleship > initializer. Battleship(...) will only invoke Battleship.__init__(...), not > Craft.__init__(...) -- so you have to do that explicitly inside > Battleship.__init__() while passing along all parameters it is supposed to > process. As simplified example: > > class Craft(object): > def __init__(self, name, id=None, weapons=None): > if id is None: > id = helpers.id() > if weapons is None: > weapons = [] > self.name = name > self.id = id > self.weapons = weapons > > class Battleship(Craft): > def __init__(self, name, id=None, weapons=None, max_hits=None): > Craft.__init__(self, name, id, weapons) > self.max_hits = max_hits > > Notice how using None to signal that a value was not provided simplifies > things; without it you'd have to put a meanigful default for weapons into > both the Craft and Battleship class. If you want a unique id for every Craft > providing helpers.id() as a default is just wrong; default arguments are > calculated once and you would end up with the same id for every Craft > instance. Yes, I found that out the hard way :), but it made perfect sense as soon as I realized that I was not getting unique IDs; the class() statement is just a fancy function call in Python, as I understand it, so of course it would be called only once, not each time I make a new instance. > > Peter > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From awilliam at whitemice.org Fri May 21 08:16:27 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 21 May 2010 08:16:27 -0400 Subject: intervall of about 1 second for xmlrpc calls? In-Reply-To: References: Message-ID: <1274444187.7777.0.camel@linux-yu4c.site> On Fri, 2010-05-21 at 02:10 -0700, rav wrote: > I had similar problem with SimpleXMLRPCServer > Create the request handler class > class ExtendedXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): > # originally this one was slowing down my server A LOT due to DNS > settings!!! > def log_request(self, *args): > pass > and put it in your SimpleXMLRPCServer constructor > (...) > class MyServer(threading.Thread): > def __init__(self, host, port): > threading.Thread.__init__(self) > self.server = SimpleXMLRPCServer((host, port), > ExtendedXMLRPCRequestHandler) > self.server.register_function(self.is_even, "is_even") > self.server.register_function(self.stop, "stop_server") > (...) > I would also change all 'localhost' occurences in the code to ip > '127.0.0.1'. Or the better solution is to fix your resolver. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From awilliam at whitemice.org Fri May 21 08:37:14 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 21 May 2010 08:37:14 -0400 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <1274445434.7777.20.camel@linux-yu4c.site> On Fri, 2010-05-21 at 11:37 +0100, Martin P. Hellwig wrote: > On 05/21/10 11:21, Deep_Feelings wrote: > > however by having a look at this page http://wiki.python.org/moin/Applications > > i could not see many programs written in python (i will be interested > > more in COMMERCIAL programs written in python ). and to be honest ,i > > tried some of the programs in that list and all the programs that i > > tried either dead projects or so buggy ! Most projects are dead projects; that is just the natural state of things regardless of language. Just browse Sourceforge for awhile. > It's a wiki, if anybody is interested they could change the page, I > actually have never looked at it. I've looked it over, there is some interesting stuff. But why contribute a story when you could be coding on your project! A perennial problem. :) > > 1- where are the programs that is written in python ? > > 2- python is high productivity language : why there are no commercial > > programs written in python ? > > is python a valid practical programming language ? > > why it is not used in commercial software ? I suppose it depends on your use of the term "used". It is used a *lot* in the SOA / Workflow world - in the form of Jython. That provides a very nice way to extend Java applications [it is still Python! Python is a language, not a runtime]. In general to 'core' of large applications are, IMO, easier to maintain in the more rigid statically typed languages as the toolchain can do more work for you. Of course someone here will have a fit about that statement. > > please don't mention programs where python was used as a glue Why not? And what about Gwibber? Zeitgeist? BitTorrent? Zope/Plone? Those are all certainly "real" applications. Zope is almost an industry unto itself. > ,those programs are not actually written in python. I think your distinction is not valid. "glue" is a vital part of every enterprise. And the sophistication of some "glue" certainly surpasses many "applications". > Python is used in a lot in custom applications, while off the shelve > software needs a lot of buzzwords to shift any market interest. > I have participated in a couple of 'pure' Python programs, used by > Airbus, Randstad and a whole fleet of small firms. But yes, off the > shelve software seems to be either written in Java or any .net equivalent. is an interesting read. Certainly the 'packaging' mechanism is less end-user friendly than .NET. I personally would not choose to create an end-user application in Python; but it has become my first choice for server-side development. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From awilliam at whitemice.org Fri May 21 08:46:33 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 21 May 2010 08:46:33 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> <4bf3eeeb$0$31263$607ed4bc@cv.net> <3c40f8d8-b29c-484f-b5b3-6dff0f68a032@m21g2000vbr.googlegroups.com> <16c9daac-293a-4cb6-b847-489e696682bd@c11g2000vbe.googlegroups.com> Message-ID: <1274445993.7777.23.camel@linux-yu4c.site> On Thu, 2010-05-20 at 22:58 -0700, Dennis Lee Bieber wrote: > On Thu, 20 May 2010 02:45:10 -0700 (PDT), Jimoid > declaimed the following in > gmane.comp.python.general: > > I've now had a closer look at both pyODBC and mxODBC and it seems to > > me that they both require the database to be running to be able to > > query it. Is this correct? If so I think I will have to use mdb-* as > > the database I want to query is not running. > To my knowledge, all "ODBC" modules (in any language) rely upon a > DBMS specific driver. Correct (of course, so does DB-API if you are using a 'native' Python connection). > Where the DB-API definition defines the common > Python side of a database interface, ODBC defines a common OS-level > interface to the DBMS, using a named driver (driver specified in the > connection string or, for Windows, externally with the connection string > specifying the connection definition) There is no distinction between how ODBC operates on Windows or LINUX. Both use the same connection strings [provided the drivers have the same names]. > to translate ODBC calls into actual DBMS calls. Yes, just like a DB-API provider, except that the 'translation' happens in the ODBC driver. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From sunckell at gmail.com Fri May 21 09:17:25 2010 From: sunckell at gmail.com (Chad Kellerman) Date: Fri, 21 May 2010 09:17:25 -0400 Subject: unique values of a Dictionary list (removing duplicate elements of a list) In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 8:07 AM, Chad Kellerman wrote: > > > On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__peter__ at web.de> wrote: > >> Chad Kellerman wrote: >> >> > Python users, >> > I am parsing an AIX trace file and creating a dictionary >> containing >> > keys (PIDS) and values (a list of TIDS). With PIDS being unique process >> > ids >> > and TIDS, being a list of thread ids. My function populates the keys so >> > that they are unique, but my list contains duplicates. >> > >> > Can someone point me in the right direction so that my dictionary >> > value >> > does not contain duplicate elements? >> > >> > >> > here is what I got. >> > >> > -------------------------------- >> > >> > pidtids = {} >> > >> > # --- function to add pid and tid to a dictionary >> > def addpidtids(pid,tid): >> > pidtids.setdefault(pid,[]).append(tid) >> >> Use a set instead of a list (and maybe a defaultdict): >> >> from collections import defaultdict >> >> pidtids = defaultdict(set) >> >> def addpidtids(pid, tid): >> pidtids[pid].add(tid) >> >> Peter >> > > Thanks. I guess I should have posted this in my original question. > > I'm on 2.4.3 looks like defautldict is new in 2.5. > > I'll see if I can upgrade. > > Thanks again. > instead of upgrading.. (probably be faster to use techniques in available 2.4.3) Couldn't I check to see if the pid exists (has_key I believe) and then check if the tid is a value, in the the list for that key, prior to passing it to the function? Or would that be too 'expensive'? > > > >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > A grasshopper walks into a bar and the bartender says "Hey, we have a drink > named after you." And the grasshopper says "Really, You have a drink named > Murray?" > -- A grasshopper walks into a bar and the bartender says "Hey, we have a drink named after you." And the grasshopper says "Really, You have a drink named Murray?" -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri May 21 09:46:55 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2010 15:46:55 +0200 Subject: unique values of a Dictionary list (removing duplicate elements of a list) References: Message-ID: Chad Kellerman wrote: > On Fri, May 21, 2010 at 8:07 AM, Chad Kellerman > wrote: > >> >> >> On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__peter__ at web.de> wrote: >> >>> Chad Kellerman wrote: >>> >>> > Python users, >>> > I am parsing an AIX trace file and creating a dictionary >>> containing >>> > keys (PIDS) and values (a list of TIDS). With PIDS being unique >>> > process ids >>> > and TIDS, being a list of thread ids. My function populates the keys >>> > so that they are unique, but my list contains duplicates. >>> > >>> > Can someone point me in the right direction so that my dictionary >>> > value >>> > does not contain duplicate elements? >>> > >>> > >>> > here is what I got. >>> > >>> > -------------------------------- >>> > >>> > pidtids = {} >>> > >>> > # --- function to add pid and tid to a dictionary >>> > def addpidtids(pid,tid): >>> > pidtids.setdefault(pid,[]).append(tid) >>> >>> Use a set instead of a list (and maybe a defaultdict): >>> >>> from collections import defaultdict >>> >>> pidtids = defaultdict(set) >>> >>> def addpidtids(pid, tid): >>> pidtids[pid].add(tid) >>> >>> Peter >>> >> >> Thanks. I guess I should have posted this in my original question. >> >> I'm on 2.4.3 looks like defautldict is new in 2.5. >> >> I'll see if I can upgrade. >> >> Thanks again. >> > > > instead of upgrading.. (probably be faster to use techniques in available > 2.4.3) > > Couldn't I check to see if the pid exists (has_key I believe) and then > check if the tid is a value, in the the list for that key, prior to > passing it to the function? > > Or would that be too 'expensive'? No. pidtids = {} def addpidtids(pid, tid): if pid in pidtids: pidtids[pid].add(tid) else: pidtids[pid] = set((tid,)) should be faster than def addpidtids(pid, tid): pidtids.setdefault(pid, set()).add(tid) and both should work in python2.4. Peter From invalid at invalid.invalid Fri May 21 10:20:39 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 21 May 2010 14:20:39 +0000 (UTC) Subject: Another "Go is Python-like" article. Message-ID: In a recent Reg article, there's yet more yammering on about how Go is somehow akin to Python -- referring to Go as a "Python-C++" crossbreed. http://www.theregister.co.uk/2010/05/20/go_in_production_at_google/ I still don't get it. What about Go, exactly, do people see as Phython-like? Go doesn't seem to have any of the salient features (either syntactic or semantic) of Python other than garbage collection. How is Go not just warmed-over Java? -- Grant Edwards grant.b.edwards Yow! RELATIVES!! at gmail.com From cournape at gmail.com Fri May 21 11:30:11 2010 From: cournape at gmail.com (David Cournapeau) Date: Sat, 22 May 2010 00:30:11 +0900 Subject: Another "Go is Python-like" article. In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 11:20 PM, Grant Edwards wrote: > In a recent Reg article, there's yet more yammering on about how Go is > somehow akin to Python -- referring to Go as a "Python-C++" crossbreed. > > http://www.theregister.co.uk/2010/05/20/go_in_production_at_google/ > > I still don't get it. > > What about Go, exactly, do people see as Phython-like? I guess the type system without a strict hierarchy, as well as very fast compilation enabling fast iteration. Granted, a lot of languages have those features nowadays, and I doubt anyone would speaks about it if it was not where it was coming from. The fact that google feels the need to create a new system programming language is maybe the most interesting fact of it ? cheers, David From timoverbeek10 at gmail.com Fri May 21 11:50:56 2010 From: timoverbeek10 at gmail.com (timo verbeek) Date: Fri, 21 May 2010 08:50:56 -0700 (PDT) Subject: creating addon system Message-ID: What is the easiest way in python to create a addon system? I found to easy ways: * using a import system like this: for striper in stripers: if striper["enabled"]: exec("from strip import %s as _x"%striper["striper"]) string = _x.start(string) * using exec for striper in stripers: if striper["enabled"]: use=open(stripper) exec(use) Do you now is the best way? From keobox at gmail.com Fri May 21 11:54:44 2010 From: keobox at gmail.com (keobox) Date: Fri, 21 May 2010 08:54:44 -0700 (PDT) Subject: Problem with an huge dictionary References: <70b8f82e-2dfe-4403-ae77-cb4d005578f1@y12g2000vbr.googlegroups.com> Message-ID: <40f4fe52-c4e9-43c6-b0be-4fd6da91555d@c11g2000vbe.googlegroups.com> On 20 Mag, 12:58, Thomas Lehmann wrote: > > The question is: > > Is there a limit on the number of entries a dictionary can have i > > jython? > > > I wrote a little app where my data is stored in a huge dictionary > > (11746 entries) generated with a python script. > > When I try to import the dictionary, jython complains with the > > following message: > > 1) You did not say what you have saved (content of your dictionary). - As you can see I received the error when I tried to import jmoco_event_data.py module from the jython interpreter prompt. - The "import" will cause the module compilation, jython will produce a .class file instead of .pyc. - jmoco_event_data.py contains 4 dictionaries: typesValToName={ 220:'EMS_EVENT_EMS_INTERNAL_BASE', 221:'EMS_EVENT_INTERNAL_TYPE_BASE', 222:'EMS_EVENT_INTERNAL_N_E_P_M_EVENT', 223:'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD', 224:'EMS_EVENT_NE_SPECIFIC_BASE', ... 11746 entries int key: string value } typesNameToVal={ 'EMS_EVENT_EMS_INTERNAL_BASE':220, 'EMS_EVENT_INTERNAL_TYPE_BASE':221, 'EMS_EVENT_INTERNAL_N_E_P_M_EVENT':222, 'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD':223, 'EMS_EVENT_NE_SPECIFIC_BASE':224, ... total 11746 entries string key: int value } causesValToName={ 0:'NOT_APPLICABLE_UNKNOWN', 1:'SOFTWARE_CAUSE_UNKNOWN', 2:'ABSENT_MODULE', 3:'FAULTY_MODULE', ... 483 entries int key: string value } causesNameToVal={ 'NOT_APPLICABLE_UNKNOWN':0, 'SOFTWARE_CAUSE_UNKNOWN':1, 'ABSENT_MODULE':2, 'FAULTY_MODULE':3, ... 483 entries string key: int value } > 2) You did not say how you have saved. The dictionaries are in the jmoco_event_data.py module. > From the callstack - also I have never used jython - it looks like > that > there is a try to create a class. It looks like - I may be wrong - > that > you have saved user objects in your dictionary - have you? Nope, the dictionaries are only int to string mappings and string to int mappings > If so you might fail on loading those objects - especially when your > program > does not have the code for it. The failure happens during module's import, so my question is: Is jython able to handle such big dictionaries? > More details are required... jmoco_event_data.py has a size of roughly 700KB. From albert at spenarnc.xs4all.nl Fri May 21 12:02:23 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 21 May 2010 16:02:23 GMT Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf5814b$0$12129$4fafbaef@reader4.news.tin.it> Message-ID: In article , Grant Edwards wrote: > >Lest my allusions to Fortran IV be lost upon the less grizzled, only >the first 6 characters were significant in Fortran IV identifiers, and >removing all of the vowels from a longer word was an idiomatic way to >create an identifier with a length <= 6. > >IIRC, the number 6 was originally chosen because that's how many 6-bit >characters you could hold in a single 36-bit CPU register. That way >when writing a compiler/link/assembly you could compare two >identifiers using a single "CMP" instruction. > >I'm not sure why 36-bits was such a popular ALU width, but many >different vendors sold 36-bit machines back in the day. 16 bit mini computers were popular: the pdp11. Now 3 FORTRAN char's fitted in one word (radix 40). At least it helped to shoe horn identifier names into two words. > >-- >Grant Edwards grant.b.edwards Yow! Hand me a pair of > at leather pants and a CASIO > gmail.com keyboard -- I'm living > for today! -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From python at bdurham.com Fri May 21 12:04:11 2010 From: python at bdurham.com (python at bdurham.com) Date: Fri, 21 May 2010 12:04:11 -0400 Subject: string.Template.safe_substitute() with % type formatting? Message-ID: <1274457851.6768.1376258583@webmail.messagingengine.com> Python 2.6: Is there a programming technique or 3rd party formatting module that supports string.Template.safe_substitute() type string substituion with % type formatting rules for width, decimals, justification, etc? Or do I need to use a 3rd party template engine to get the best of both worlds? Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From albert at spenarnc.xs4all.nl Fri May 21 12:43:00 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 21 May 2010 16:43:00 GMT Subject: help need to write a python spell checker References: Message-ID: In article , Terry Reedy wrote: >On 5/19/2010 3:17 AM, CM wrote: >> I love how he just copied and pasted the assignment without any other >> remarks. > >Yeah, that way he did not mess it up ;-). OTOH it may be a copyright infringement. Or is posting an assignment to a newsgroup "fair use"? Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From jason.scheirer at gmail.com Fri May 21 12:51:34 2010 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Fri, 21 May 2010 09:51:34 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <03cb4e4e-23c9-4525-ab60-c67312038631@s4g2000prh.googlegroups.com> On May 21, 3:21?am, Deep_Feelings wrote: > python is not a new programming language ,it has been there for the > last .... 15+ years or so ? right ? > > however by having a look at this pagehttp://wiki.python.org/moin/Applications > i could not see many programs written in python (i will be interested > more in COMMERCIAL programs written in python ). and to be honest ,i > tried some of the programs in that list and all the programs that i > tried either dead projects or so buggy ! > > 1- where are the programs that is written in python ? > 2- python is high productivity language : why there are no commercial > programs written in python ? > > is python a valid practical programming language ? > why it is not used in commercial software ? > > please don't mention programs where python was used as a glue ,those > programs are not actually written in python. > > any help will be appreciated > > thank you I write commercial software full-time in Python (well, mixed with C++) at ESRI. I have been able to make a living developing in Python full time at various places for the last 4 years. I can assure you that there is plenty of commercial software out there that uses Python. The reason you don't *see* it is because the development language for a commercial product is a lot less important than the functionality of the product, so "WRITTEN IN PYTHON!!!!" is likely not going to be a bullet point on a marketing slide. And quite frankly, it should be a trade secret for the companies enlightened enough to use it as their language of choice because it is to productive that it provides a competitive advantage. From nagle at animats.com Fri May 21 13:29:40 2010 From: nagle at animats.com (John Nagle) Date: Fri, 21 May 2010 10:29:40 -0700 Subject: Strange MySQL Problem In-Reply-To: References: <4BF569DB.9010601@mrabarnett.plus.com> Message-ID: <4bf6bd55$0$1587$742ec2ed@news.sonic.net> Christian Heimes wrote: > MRAB wrote: >> I think you need to 'commit' any changes to do to the database. > > Yeah, you are right. > Also some RDBMS don't support DDL and DML statements inside one > transaction. You may need to commit and begin after the create table DDL. > > Christian Er, yes. Generally, you don't try a create on every insert transaction. Since your create has foreign keys, it will fail if the other tables don't already exist. So you need to have a more organized way of setting up the database. InnoDB is a proper transaction database. You must commit after insert or the inserts will be properly rolled back and undone after database disconnect. John Nagle From victorsubervi at gmail.com Fri May 21 13:31:04 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 21 May 2010 13:31:04 -0400 Subject: Another Strange MySQL Problem Message-ID: Hi; When I try to execute this code from my Python script, I get this error: Traceback (most recent call last): File "/var/www/html/creative.vi/clients/sea-flight/reservations/create_edit_bags3.py", line 38, in ? create_edit_bags3() File "/var/www/html/creative.vi/clients/sea-flight/reservations/create_edit_bags3.py", line 32, in create_edit_bags3 cursor.execute('insert into Baggage values (Null, %s, %s, %s, %s)', (flight_id, customer_id, weight, ticket_no)) File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue OperationalError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`seaflight/Baggage`, CONSTRAINT `Baggage_ibfk_2` FOREIGN KEY (`customer_id`) REFERENCES `Customers` (`id`))') However, when I try from the MySQL prompt after duly printing it out from the code, it works. Why? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri May 21 13:52:16 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2010 13:52:16 -0400 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On 5/20/2010 10:56 PM, Alex Hall wrote: A couple of style comments for you to consider. > class Craft(): > def __init__(self, > name, > isAircraft=False, > id=helpers.id(), > hits=0, > weapons=[]): Not indenting lines after def makes the code harder to read for me, and, I expect, many others here who use indentation as a cue. If you want one param per line, give them extra indents if you want. > self.name=name > self.id=id > self.hits=hits > self.weapons=weapons > self.isAircraft=isAircraft > #end def > #end class #end markers are fine for private code but are distracting noise to me, and, I expect, other experienced Python coders. Terry Jan Reedy From mehgcap at gmail.com Fri May 21 14:08:39 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 14:08:39 -0400 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On 5/21/10, Terry Reedy wrote: > On 5/20/2010 10:56 PM, Alex Hall wrote: > > A couple of style comments for you to consider. > >> class Craft(): >> def __init__(self, >> name, >> isAircraft=False, >> id=helpers.id(), >> hits=0, >> weapons=[]): > > Not indenting lines after def makes the code harder to read for me, and, > I expect, many others here who use indentation as a cue. If you want one > param per line, give them extra indents if you want. Good point, I had not considered that; Python's relyance on indentation made me think that indenting past the level of the class would cause problems. > >> self.name=name >> self.id=id >> self.hits=hits >> self.weapons=weapons >> self.isAircraft=isAircraft >> #end def >> #end class > > #end markers are fine for private code but are distracting noise to me, > and, I expect, other experienced Python coders. I will try to remember to remove them for posting, but I find them immensely helpful; using a screen reader, and so not being able to look at code and see the indentation, means that I have to have a way to tell myself where things end, much like braces in other languages. When I post here I will try to remove them, but for code I zip and put on my website they have to stay since I rely on them and the zip is just what I am working on at the time, plus there are a lot of those comments to remove from an entire project. > > Terry Jan Reedy > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From lists at cheimes.de Fri May 21 14:10:34 2010 From: lists at cheimes.de (Christian Heimes) Date: Fri, 21 May 2010 20:10:34 +0200 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: Am 21.05.2010 04:56, schrieb Alex Hall: > Hi all, > I am now trying to allow my classes, all of which subclass a single > class (if that is the term), to provide optional arguments. Here is > some of my code: > > class Craft(): > def __init__(self, > name, > isAircraft=False, > id=helpers.id(), > hits=0, > weapons=[]): I hope you are aware that helpers.id() is called just once when the *class* is defined and that the list weapons is shared across all instances of the craft class. :) Have you read about *args and **kwargs in the Python docs? I bet you find them useful for your problem. Christian From rnlatimer at gmail.com Fri May 21 14:12:14 2010 From: rnlatimer at gmail.com (Neal) Date: Fri, 21 May 2010 11:12:14 -0700 (PDT) Subject: Solutions for finding the 1000th prime References: Message-ID: <44049f3a-3fdd-4d64-953a-9445f4707b31@o39g2000vbd.googlegroups.com> You did provide a very constructive answer and I do apologize for generalizing the group or all the posts. And while the original poster did not seem to have made much of an effort, the tone of the initial response of that thread turns off anyone else who may be willing to make that effort. I also want people who may have forgotten to understand how early this problem shows up in an Introduction to Computer Science course. In this class its the second assignment, right after the obligatory 'Hello World!' variant. I'm sure that while finding solutions and new keywords is integral to learning how to program in a language, defining the a function isn't a tool that has been introduced quite yet, as simple as it may seem. Thank you for the link to the mailing list as well. From tjreedy at udel.edu Fri May 21 14:16:40 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2010 14:16:40 -0400 Subject: where are the program that are written in python? In-Reply-To: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: On 5/21/2010 7:12 AM, Deep_Feelings wrote: > On May 21, 1:35 pm, Simon Brunning wrote: >> On 21 May 2010 11:21:11 UTC+1, Deep_Feelings wrote: >> >> Seehttp://www.python.org/about/success/ > > thankx for reply. > > from that list i have a feeling that python is acting only as "quick > and dirty work" nothing more ! Try 'quick and clean' and you would be more accurate. But that would not be so trollish, would it? tjr From pmaupin at gmail.com Fri May 21 14:20:04 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 21 May 2010 11:20:04 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On May 21, 5:21?am, Deep_Feelings wrote: > i could not see many programs written in python Well you could try PyPi, or even a search on googlecode. > (i will be interested > more in COMMERCIAL programs written in python ). What do you mean by commercial, and why? > and to be honest ,i > tried some of the programs in that list and all the programs that i > tried either dead projects or so buggy ! So, you want us to believe that you desperately want to pay someone for working Python software, but are finding it hard to find some? > 1- where are the programs that is written in python ? All over the place. > 2- python is high productivity language : why there are no commercial > programs written in python ? There are a lot of commercial programs written in Python. But any company which thinks it has a lock on some kind of super secret sauce isn't going to use Python, because it's very easy to reverse engineer even compiled Python programs. Also, any company in a competitive market where execution speed is extremely important might choose some other language because, frankly, the fact that a development tool is highly productive is not something that the end user directly cares about. (But the up-front choice of another language simply for speed, rather than prototyping with Python and then recoding the slow bits, would probably be a decision borne of ignorance.) > is python a valid practical programming language ? Absolutely. I've been using it heavily for 11 years, for real work, for which I get paid. > why it is not used in commercial software ? What makes you think that it's not? Is this some kind of "big lie" strategy? To what end? > any help will be appreciated It's hard to help when you don't describe the problem. Reading between the lines, the most charitable and probable interpretation of your problem I can come up with is that you think you're going to create a multi-billion dollar computer program and you're desperately trying to validate your preconceived notion that Python isn't the language to write it in. Sorry, but I can't help with that. Regards, Pat From krister.svanlund at gmail.com Fri May 21 14:32:46 2010 From: krister.svanlund at gmail.com (Krister Svanlund) Date: Fri, 21 May 2010 20:32:46 +0200 Subject: creating addon system In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 5:50 PM, timo verbeek wrote: > What is the easiest way in python to create a addon system? > I found to easy ways: > * using a import system like this: > ? ? ? for striper in stripers: > ? ? ? ?if striper["enabled"]: > ? ? ? ? ? ?exec("from strip import %s as _x"%striper["striper"]) > ? ? ? ? ? ?string = _x.start(string) > * using exec > ? ? ? for striper in stripers: > ? ? ? ?if striper["enabled"]: > ? ? ? ? ? ?use=open(stripper) > ? ? ? ? ? ?exec(use) > > Do you now is the best way? > -- > http://mail.python.org/mailman/listinfo/python-list > Check this one out: http://docs.python.org/library/functions.html#__import__ From mehgcap at gmail.com Fri May 21 14:38:16 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 14:38:16 -0400 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On 5/21/10, Christian Heimes wrote: > Am 21.05.2010 04:56, schrieb Alex Hall: >> Hi all, >> I am now trying to allow my classes, all of which subclass a single >> class (if that is the term), to provide optional arguments. Here is >> some of my code: >> >> class Craft(): >> def __init__(self, >> name, >> isAircraft=False, >> id=helpers.id(), >> hits=0, >> weapons=[]): > > I hope you are aware that helpers.id() is called just once when the > *class* is defined and that the list weapons is shared across all > instances of the craft class. :) I know id is called once, but what do you mean weapons is shared? > > Have you read about *args and **kwargs in the Python docs? I bet you > find them useful for your problem. > > Christian > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From debatem1 at gmail.com Fri May 21 14:40:05 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 21 May 2010 11:40:05 -0700 Subject: where are the program that are written in python? In-Reply-To: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: On Fri, May 21, 2010 at 4:12 AM, Deep_Feelings wrote: > On May 21, 1:35?pm, Simon Brunning wrote: >> On 21 May 2010 11:21:11 UTC+1, Deep_Feelings wrote: >> >> Seehttp://www.python.org/about/success/ > > thankx for reply. > > from that list i have a feeling that python is acting only as "quick > and dirty work" nothing more ! Yeah, there's not really a lot of industry support. If only we could get a huge search engine like bing to use python extensively we'd be in a lot better shape. Geremy Condra From python.list at tim.thechases.com Fri May 21 14:40:49 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 21 May 2010 13:40:49 -0500 Subject: Another Strange MySQL Problem In-Reply-To: References: Message-ID: <4BF6D3B1.2070605@tim.thechases.com> On 05/21/2010 12:31 PM, Victor Subervi wrote: > cursor.execute('insert into Baggage values (Null, %s, %s, %s, > %s)', (flight_id, customer_id, weight, ticket_no)) You're trying to insert stuff... > OperationalError: (1452, 'Cannot add or update a child row: a foreign > key constraint fails (`seaflight/Baggage`, CONSTRAINT `Baggage_ibfk_2` > FOREIGN KEY (`customer_id`) REFERENCES `Customers` (`id`))') But the value you're giving for the customer_id doesn't exist in the Customers table (as mandated by the FK). Or perhaps the column-order for Baggage isn't what you think it is. I always specify it explicitly: INSERT INTO Baggage ( something, flight_id, customer_id, weight, ticket_no ) VALUES (Null, %s, %s, %s, %s) just in case the table column-order ever changes during a database update. -tkc From tjreedy at udel.edu Fri May 21 14:47:53 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2010 14:47:53 -0400 Subject: where are the program that are written in python? In-Reply-To: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On 5/21/2010 6:21 AM, Deep_Feelings wrote: > python is not a new programming language ,it has been there for the > last .... 15+ years or so ? right ? > > however by having a look at this page http://wiki.python.org/moin/Applications > i could not see many programs written in python (i will be interested > more in COMMERCIAL programs written in python ). and to be honest ,i There are two kinds of 'commercial' programs. 1. The vast majority are proprietary programs kept within a company for its own use. As long as these work as intended, they are mostly invisible to the outside world. 2. Programs sold to anyone who wants them. Python trades programmer speed for execution speed. If a successful Python program is going to be run millions of times, it makes economic sense to convert time-hogging parts to (for instance) C. In fact, this is a consideration in deciding what functions should be builtin and which stdlib modules are written or rewritten in C. Programs being sold tend to be compared to competitors on speed with perhaps more weight than they rationally should. Speed is easier to measure than, for instance, lack of bugs. Python programs can be and sometimes are distributed as .exe files. The users of such neither know nor care that some of the source is Python. > tried some of the programs in that list and all the programs that i > tried either dead projects or so buggy ! > > 1- where are the programs that is written in python ? Mostly kept private. For instance, GvR, Python's inventor, spent part of his first year at Google writing a neat-looking programmer console program in Python (Mondrian) designed to improve the productivity of Google programmers. As far as I know, Google has not released it. > please don't mention programs where python was used as a glue ,those > programs are not actually written in python. A C program glues together micro-coded functions. Even a 'pure' CPython program glues together C-coded functions. Some are in builtins, some are imported from the stdlib, and some can be imported from 3rd party packages. The extensibility of CPython is part of its design. Terry Jan Reedy From __peter__ at web.de Fri May 21 14:48:27 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2010 20:48:27 +0200 Subject: optional argument to a subclass of a class References: Message-ID: Alex Hall wrote: > On 5/21/10, Christian Heimes wrote: >> Am 21.05.2010 04:56, schrieb Alex Hall: >>> Hi all, >>> I am now trying to allow my classes, all of which subclass a single >>> class (if that is the term), to provide optional arguments. Here is >>> some of my code: >>> >>> class Craft(): >>> def __init__(self, >>> name, >>> isAircraft=False, >>> id=helpers.id(), >>> hits=0, >>> weapons=[]): >> >> I hope you are aware that helpers.id() is called just once when the >> *class* is defined and that the list weapons is shared across all >> instances of the craft class. :) > I know id is called once, but what do you mean weapons is shared? All Craft instances for which you don't provide a weapons argument explicitly will share the same list. If you later append a weapon to that list all these Craft instances will see this change and get the extra weapon: a = Craft("first") b = Craft("second") a.weapons.append("surprise") print b.weapons # ['surprise'] Peter From clp2 at rebertia.com Fri May 21 14:49:15 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 May 2010 11:49:15 -0700 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 11:38 AM, Alex Hall wrote: > On 5/21/10, Christian Heimes wrote: >> Am 21.05.2010 04:56, schrieb Alex Hall: >>> Hi all, >>> I am now trying to allow my classes, all of which subclass a single >>> class (if that is the term), to provide optional arguments. Here is >>> some of my code: >>> >>> class Craft(): >>> ? def __init__(self, >>> ? name, >>> ? isAircraft=False, >>> ? id=helpers.id(), >>> ? hits=0, >>> ? weapons=[]): >> >> I hope you are aware that helpers.id() is called just once when the >> *class* is defined and that the list weapons is shared across all >> instances of the craft class. :) > I know id is called once, but what do you mean weapons is shared? Read the "Important warning" on http://docs.python.org/tutorial/controlflow.html#default-argument-values `weapons` will be the *exact same list object* for all Craft instances the way you have it currently (i.e. it will not be copied and changes to it will affect all Crafts). Cheers, Chris -- http://blog.rebertia.com From python.list at tim.thechases.com Fri May 21 14:57:27 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 21 May 2010 13:57:27 -0500 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: <4BF6D797.307@tim.thechases.com> On 05/21/2010 01:40 PM, geremy condra wrote: >>> See http://www.python.org/about/success/ >> >> thankx for reply. >> >> from that list i have a feeling that python is acting only as "quick >> and dirty work" nothing more ! > > Yeah, there's not really a lot of industry support. If only we could > get a huge search engine like bing to use python extensively we'd > be in a lot better shape. Or if an organization known to hire a bunch of rocket-scientists were to use Python...that would make it a real language... -tkc http://www.python.org/about/success/usa/ From clp2 at rebertia.com Fri May 21 15:01:43 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 May 2010 12:01:43 -0700 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 11:49 AM, Chris Rebert wrote: > On Fri, May 21, 2010 at 11:38 AM, Alex Hall wrote: >> On 5/21/10, Christian Heimes wrote: >>> Am 21.05.2010 04:56, schrieb Alex Hall: >>>> Hi all, >>>> I am now trying to allow my classes, all of which subclass a single >>>> class (if that is the term), to provide optional arguments. Here is >>>> some of my code: >>>> >>>> class Craft(): >>>> ? def __init__(self, >>>> ? name, >>>> ? isAircraft=False, >>>> ? id=helpers.id(), >>>> ? hits=0, >>>> ? weapons=[]): >>> >>> I hope you are aware that helpers.id() is called just once when the >>> *class* is defined and that the list weapons is shared across all >>> instances of the craft class. :) >> I know id is called once, but what do you mean weapons is shared? > > Read the "Important warning" on > http://docs.python.org/tutorial/controlflow.html#default-argument-values > `weapons` will be the *exact same list object* for all Craft instances > the way you have it currently (i.e. it will not be copied and changes > to it will affect all Crafts). Er, all Craft instances /where you didn't pass an explicit `weapons` argument to the constructor/, that is. - Chris From ethan at stoneleaf.us Fri May 21 15:20:59 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 21 May 2010 12:20:59 -0700 Subject: optional argument to a subclass of a class In-Reply-To: References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> Message-ID: <4BF6DD1B.2070406@stoneleaf.us> Alex Hall wrote: > On 5/20/10, alex23 wrote: > I have since updated each ship's > __init__ to accept all the arguments that Craft accepts so that I can > support all optional arguments, Ick. Now you'll have to change several things if you make one change to the Craft class. Better to do it this way: [borrowing Peter's example] class Craft(object): def __init__(self, name, id=None, weapons=None): if id is None: id = helpers.id() if weapons is None: weapons = [] self.name = name self.id = id self.weapons = weapons class Battleship(Craft): def __init__(self, name, max_hits=None, **kwds): Craft.__init__(self, name, **kwds) self.max_hits = max_hits Notice the **kwds in Battleships's init, both in the parameter line, and in the call to Craft's init. This way all keyword arguments that Battleship doesn't directly support will be passed through to Craft. ~Ethan~ From awilliam at whitemice.org Fri May 21 15:43:10 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 21 May 2010 15:43:10 -0400 Subject: creating addon system In-Reply-To: References: Message-ID: <1274470990.9614.2.camel@linux-yu4c.site> On Fri, 2010-05-21 at 08:50 -0700, timo verbeek wrote: > What is the easiest way in python to create a addon system? > I found to easy ways: > * using a import system like this: > for striper in stripers: > if striper["enabled"]: > exec("from strip import %s as _x"%striper["striper"]) > string = _x.start(string) This is how I chose to do it. Just walking a list of bundles and discover the available classes [as plugins]. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From mehgcap at gmail.com Fri May 21 16:09:56 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 16:09:56 -0400 Subject: optional argument to a subclass of a class In-Reply-To: <4BF6DD1B.2070406@stoneleaf.us> References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> <4BF6DD1B.2070406@stoneleaf.us> Message-ID: On 5/21/10, Ethan Furman wrote: > Alex Hall wrote: >> On 5/20/10, alex23 wrote: >> I have since updated each ship's >> __init__ to accept all the arguments that Craft accepts so that I can >> support all optional arguments, > > Ick. Now you'll have to change several things if you make one change to > the Craft class. Better to do it this way: > > [borrowing Peter's example] > > class Craft(object): Curious: I do not pass Craft this "object" keyword and I have no problems. What is it for? Just a convention, something like self being called self? > def __init__(self, name, id=None, weapons=None): > if id is None: > id = helpers.id() > if weapons is None: > weapons = [] > self.name = name > self.id = id > self.weapons = weapons > > class Battleship(Craft): > def __init__(self, name, max_hits=None, **kwds): > Craft.__init__(self, name, **kwds) > self.max_hits = max_hits > > > > Notice the **kwds in Battleships's init, both in the parameter line, and > in the call to Craft's init. This way all keyword arguments that > Battleship doesn't directly support will be passed through to Craft. Thanks, the **kwords makes sense!! I implemented it much as you described, and life is much easier; each ship or aircraft now has a simple constructor, and I am still free to change any attrib I want later or at creation time. A very powerful concept, and I now have 2-line constructors. class Battleship(Craft): def __init__(self, name, **kwords): Craft.__init__(self, name, maxHits=4, **kwords) #call the superclass's __init__ class Carrier(Craft): def __init__(self, name, **kwords): Craft.__init__(self, name, maxHits=5, **kwords) #call the superclass's __init__ > > ~Ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From clp2 at rebertia.com Fri May 21 17:28:06 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 May 2010 14:28:06 -0700 Subject: optional argument to a subclass of a class In-Reply-To: References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> <4BF6DD1B.2070406@stoneleaf.us> Message-ID: On Fri, May 21, 2010 at 1:09 PM, Alex Hall wrote: > On 5/21/10, Ethan Furman wrote: >> Alex Hall wrote: >>> On 5/20/10, alex23 wrote: >>> I have since updated each ship's >>> __init__ to accept all the arguments that Craft accepts so that I can >>> support all optional arguments, >> >> Ick. ?Now you'll have to change several things if you make one change to >> the Craft class. ?Better to do it this way: >> >> [borrowing Peter's example] >> >> class Craft(object): > Curious: I do not pass Craft this "object" keyword and I have no > problems. What is it for? Just a convention, something like self being > called self? It causes the class to be "new-style". See http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes Cheers, Chris -- http://blog.rebertia.com From bkasterm at gmail.com Fri May 21 17:51:52 2010 From: bkasterm at gmail.com (Bart Kastermans) Date: Fri, 21 May 2010 15:51:52 -0600 Subject: First Tkinter script: requesting comments Message-ID: <87d3wokjnr.fsf@kasterma.Colorado.EDU> I wrote a first script using Tkinter. As I am new to its use, I am only just feeling my way around. I would very much like comments on the design of the script (and in fact any other comments on my code would also be very welcome). I have it posted (with syntax coloring) at: http://kasterma.wordpress.com/2010/05/21/first-experiments-with-tkinter/ But will also include it here for convenience. Thanks for any help, Best, Bart *********************** #!/usr/bin/env python # # Getting a list of students and grades displayed so that grades can # be updated, and we poll these changes (so that in the future we can # act on it). # # Bart Kastermans, www.bartk.nl """ Design of the window +-------------------------------------------------------------+ | root | | +------------------------------------------------------+ | | | title_frame | | | | +------------------------------+ | | | | | Label(title) | | | | | | | | | | | +------------------------------+ | | | +------------------------------------------------------+ | | +------------------------------------------------------+ | | | exam_grades_frames | | | | +-------------------------------------------------+ | | | | | Frame(ex) | | | | | | +--------------------+ +---------------------+ | | | | | | | Entry(name) | | Entry(grade) | | | | | | | | | | | | | | | | | +--------------------+ +---------------------+ | | | | | +-------------------------------------------------+ | | | | | | | +------------------------------------------------------+ | | | | +---------------------+ | | | quit_button | | | | | | | +---------------------+ | +-------------------------------------------------------------+ """ from Tkinter import * # global info for this specific example # four students no_stud = 4 exam_grades = [1,2,3,4] names = ["Ben", "Jim", "James", "Mel"] # upper bound for name length max_name_len = max (map (len, names)) # set up root window root = Tk() root.geometry ("400x400") exam_grades_string = map (lambda x: StringVar (root,str (x)), exam_grades) names_string = map (lambda x: StringVar (root, x), names) def setup (): """ setup the window with the list of students. This is test-code to figure out what the app finally should look like. """ # title frame, with title Grade Correction in it title_frame = Frame(root) title_frame.pack (fill=X) w = Label (title_frame, text = "Grade Correction", font = ("Helvetica", 25)) w.pack (side=LEFT) # from to hold the list of grades exam_grades_frame = Frame (root) exam_grades_frame.pack (fill=BOTH) exam_label = Label (exam_grades_frame, text="EXAMS") exam_label.pack () # set up the list of grades for i in range (0,no_stud): # a frame per student ex = Frame (exam_grades_frame) ex.pack () # name on the left name = Entry (ex, textvariable=names_string[i], width=max_name_len+2) name.config (state=DISABLED) name.pack (side=LEFT) # grade next to it grade = Entry (ex, textvariable=exam_grades_string [i], width=4) grade.pack (side=LEFT) # button to quit the application qb = Button (root) qb ['text'] = "quit" qb ['command'] = root.quit qb.pack () def to_int (st): """ helper function to convert strings to integers. Empty string represents 0. """ if len (st) == 0: return 0 else: return int (st) def get_curr_grades (): """ extract the grades from exam_grades_string. exam_grades_string consists of StringVar that get updated when the fields are updated in the GUI. """ grades = [] for i in range (0, no_stud): grades.append (exam_grades_string [i].get()) return grades # get the current grades curr_grades = map (to_int, get_curr_grades ()) def poll_exams (): """ function that keeps polling the current grades, looking for changes""" global curr_grades new_grades = map (to_int, get_curr_grades ()) if new_grades != curr_grades: print new_grades curr_grades = new_grades root.after( 250, poll_exams) # window setup setup () # start the polling poll_exams () # start the eventloop root.mainloop () # do cleanup root.destroy () sys.exit () From python at bdurham.com Fri May 21 18:01:58 2010 From: python at bdurham.com (python at bdurham.com) Date: Fri, 21 May 2010 18:01:58 -0400 Subject: gettext compatible, public domain collections of translations for strings commonly used in software applications? Message-ID: <1274479318.27084.1376307219@webmail.messagingengine.com> It seems to me that there must be some public domain collection of translated strings that could be searched for 1:1 or fuzzy translations for strings commonly used in software applications? Is there a technical and copyright friendly (LGPL licensed?) way to query services like Google's Translator Toolkit, LaunchPad, Mygengo, etc. to find translations for common strings? I've tried to google this topic without success. Example: public domain po (translation|translations) Thanks, Malcolm From mehgcap at gmail.com Fri May 21 18:27:33 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 18:27:33 -0400 Subject: optional argument to a subclass of a class In-Reply-To: References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> <4BF6DD1B.2070406@stoneleaf.us> Message-ID: On 5/21/10, Chris Rebert wrote: > On Fri, May 21, 2010 at 1:09 PM, Alex Hall wrote: >> On 5/21/10, Ethan Furman wrote: >>> Alex Hall wrote: >>>> On 5/20/10, alex23 wrote: >>>> I have since updated each ship's >>>> __init__ to accept all the arguments that Craft accepts so that I can >>>> support all optional arguments, >>> >>> Ick. Now you'll have to change several things if you make one change to >>> the Craft class. Better to do it this way: >>> >>> [borrowing Peter's example] >>> >>> class Craft(object): >> Curious: I do not pass Craft this "object" keyword and I have no >> problems. What is it for? Just a convention, something like self being >> called self? > > It causes the class to be "new-style". See > http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes Oh, I see. Thanks. > > Cheers, > Chris > -- > http://blog.rebertia.com > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From zac256 at gmail.com Fri May 21 19:22:52 2010 From: zac256 at gmail.com (Zac Burns) Date: Fri, 21 May 2010 16:22:52 -0700 Subject: Traceback spoofing Message-ID: Why can't I inherit from traceback to 'spoof' tracebacks? I would like to create a traceback that is save-able to re-raise exceptions later without leaking all the locals. (I'm sure this idea has been discussed before but I can't find it anymore.) class Traceback(types.TracebackType): pass TypeError: Error when calling the metaclass bases type 'traceback' is not an acceptable base type -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer Zindagi Games -------------- next part -------------- An HTML attachment was scrubbed... URL: From bryanjugglercryptographer at yahoo.com Fri May 21 19:41:53 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Fri, 21 May 2010 16:41:53 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <85l509Fpe7U1@mid.individual.net> Message-ID: <6025dfa5-bc54-412d-98e2-71d2ad4540a6@11g2000prv.googlegroups.com> Peter Pearson wrote: > If it's important for the function to execute quickly for large n, > you might get a useful speedup by testing only every ninth integer, Our standards for "quickly" and "large" seem kind of thin. > I suspect that further applications of number theory would > provide additional, substantial speedups, but this wanders > away from the subject of Python. I was thinking combinatorics more than number theory. I didn't find a neat formula, but I came up with a recursive memo-izing algorithm that handles 100-digit n's. I tested this against the initial algorithm plus Peter Pearson's optimization for numbers up to several thousand, and it agrees... well, after I fixed stuff that is. -Bryan Olson # ----------- _nds = {} def ndsums(m, d): """ How many d-digit ints' digits sum to m? """ assert m >= 0 and d >= 0 if m > d * 9: return 0 if m == 0 or d == 1: return 1 if (m, d) not in _nds: _nds[(m, d)] = sum(ndsums(m - i, d - 1) for i in range(min(10, m + 1))) return _nds[(m, d)] def prttn(m, n): assert m > 0 and n > 0 def inner(m, dls): if not dls: return 1 if m == 0 else 0 count = 0 msd, rest = dls[0], dls[1:] for d in range(msd): if m >= d: count += ndsums(m - d, len(dls) - 1) count += inner(m - msd, dls[1:]) return count return inner(m, [int(c) for c in str(n - 1)]) pi100 = 3141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067 print(prttn(500, pi100)) From steve at REMOVE-THIS-cybersource.com.au Fri May 21 20:13:27 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 May 2010 00:13:27 GMT Subject: gettext compatible, public domain collections of translations for strings commonly used in software applications? References: Message-ID: <4bf721a7$0$27861$c3e8da3@news.astraweb.com> On Fri, 21 May 2010 18:01:58 -0400, python wrote: > It seems to me that there must be some public domain collection of > translated strings that could be searched for 1:1 or fuzzy translations > for strings commonly used in software applications? There must be? Is that a law of nature or something? "I want it, so it must exist, QED." > Is there a technical and copyright friendly (LGPL licensed?) way to > query services like Google's Translator Toolkit, LaunchPad, Mygengo, > etc. to find translations for common strings? You would need to check the licence terms and conditions for those services. It's not enough to have LGPL-licenced software to access Translator Toolkit, if Google put limits or prohibitions on access. You will need to check the services in question to see if they publish an API for programmatically using their software. -- Steven From aahz at pythoncraft.com Fri May 21 21:20:44 2010 From: aahz at pythoncraft.com (Aahz) Date: 21 May 2010 18:20:44 -0700 Subject: links button gone from python.org References: <290f2f31-0893-469a-a12c-49eff9ffbf6f@y21g2000vba.googlegroups.com> Message-ID: In article <290f2f31-0893-469a-a12c-49eff9ffbf6f at y21g2000vba.googlegroups.com>, Eric_Dexter at msn.com wrote: > >I noticed that that the link to that section is gone. The page >seems to be there when I use the url that is stored on my computer. What are you talking about? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From tjreedy at udel.edu Fri May 21 21:42:19 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2010 21:42:19 -0400 Subject: Traceback spoofing In-Reply-To: References: Message-ID: On 5/21/2010 7:22 PM, Zac Burns wrote: > Why can't I inherit from traceback to 'spoof' tracebacks? Because a) they are, at least in part, an internal implementation detail of CPython, and b) even if you could, Python would use the builtin original with exceptions, and c) you can probably do anything sensible you want with them by wrapping them, as in, define a class with a traceback as the main instance attribute. From aahz at pythoncraft.com Fri May 21 21:45:05 2010 From: aahz at pythoncraft.com (Aahz) Date: 21 May 2010 18:45:05 -0700 Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: In article , Patrick Maupin wrote: > >There are a lot of commercial programs written in Python. But any >company which thinks it has a lock on some kind of super secret sauce >isn't going to use Python, because it's very easy to reverse engineer >even compiled Python programs. That's not always true. Both my employer (Egnyte) and one of our main competitors (Dropbox) use Python in our clients. We don't care much because using our servers is a requirement of the client. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From exarkun at twistedmatrix.com Fri May 21 22:12:43 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sat, 22 May 2010 02:12:43 -0000 Subject: Traceback spoofing In-Reply-To: References: Message-ID: <20100522021243.2209.112058618.divmod.xquotient.508@localhost.localdomain> On 01:42 am, tjreedy at udel.edu wrote: >On 5/21/2010 7:22 PM, Zac Burns wrote: >>Why can't I inherit from traceback to 'spoof' tracebacks? > >Because a) they are, at least in part, an internal implementation >detail of CPython, But you can just say this about anything, since there is no Python specification. So it's mostly meaningless. >and b) even if you could, Python would use the builtin original with >exceptions, Only if it were implemented that way. One could certainly an implementation with different behavior. >and c) you can probably do anything sensible you want with them by >wrapping them, as in, define a class with a traceback as the main >instance attribute. Except you can't re-raise them. Something like this feature has been proposed before. The only objects that I've ever heard raised are that it's harder to implement on CPython than anyone is willing to tackle. Jean-Paul From ben+python at benfinney.id.au Fri May 21 22:12:50 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 May 2010 12:12:50 +1000 Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <87mxvsfzvh.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > In article , > Patrick Maupin wrote: > > > >There are a lot of commercial programs written in Python. But any > >company which thinks it has a lock on some kind of super secret sauce > >isn't going to use Python, because it's very easy to reverse engineer > >even compiled Python programs. > > That's not always true. Both my employer (Egnyte) and one of our main > competitors (Dropbox) use Python in our clients. We don't care much > because using our servers is a requirement of the client. Doesn't that mean those companies don't fit the above description? That is, neither of them ?thinks it has a lock on some kind of super secret sauce? in the programs. So they don't seem to be counter-examples. -- \ ?The right to search for truth implies also a duty; one must | `\ not conceal any part of what one has recognized to be true.? | _o__) ?Albert Einstein | Ben Finney From zac256 at gmail.com Fri May 21 22:35:23 2010 From: zac256 at gmail.com (Zac Burns) Date: Fri, 21 May 2010 19:35:23 -0700 Subject: Traceback spoofing In-Reply-To: <20100522021243.2209.112058618.divmod.xquotient.508@localhost.localdomain> References: <20100522021243.2209.112058618.divmod.xquotient.508@localhost.localdomain> Message-ID: > Except you can't re-raise them. > Yes, I should have noted that in the original post: >>> raise RuntimeError, 'X', wrapped_traceback Traceback (most recent call last): File "", line 1, in TypeError: raise: arg 3 must be a traceback or None Does someone know where the thread went about it being hard to implement? I'm interested to see what makes it difficult. -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer Zindagi Games -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri May 21 23:03:39 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 22 May 2010 13:03:39 +1000 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <4bf749ef@dnews.tpgi.com.au> On 05/22/10 04:47, Terry Reedy wrote: > On 5/21/2010 6:21 AM, Deep_Feelings wrote: >> python is not a new programming language ,it has been there for the >> last .... 15+ years or so ? right ? >> >> however by having a look at this page >> http://wiki.python.org/moin/Applications >> i could not see many programs written in python (i will be interested >> more in COMMERCIAL programs written in python ). and to be honest ,i > > There are two kinds of 'commercial' programs. > 1. The vast majority are proprietary programs kept within a company for > its own use. As long as these work as intended, they are mostly > invisible to the outside world. > 2. Programs sold to anyone who wants them. > > Python trades programmer speed for execution speed. If a successful > Python program is going to be run millions of times, it makes economic > sense to convert time-hogging parts to (for instance) C. In fact, this > is a consideration in deciding what functions should be builtin and > which stdlib modules are written or rewritten in C. > > Programs being sold tend to be compared to competitors on speed with > perhaps more weight than they rationally should. Speed is easier to > measure than, for instance, lack of bugs. doubting python's speed? Look at Mercurial vs. SVN; Mercurial is written in Python while SVN in C. Mercurial beats SVN in speed by several orders of magnitude. One of Mercurial's design goal was to be faster than SVN, if the programmers have naively believed that choice of language would matter to program's speed, they'd choose to write Mercurial in assembly instead (the same argument applies to Git, written in shell scripts). Now, you may think this is an unfair comparison, since Mercurial is hype and new, SVN is antiquated and old. But it shows that in real-life, the language being inherently slow often dosn't matter. What matters more are the choice of data structure and algorithm, I/O speed, network latency, and development speed. From johnroth1 at gmail.com Fri May 21 23:26:56 2010 From: johnroth1 at gmail.com (John Roth) Date: Fri, 21 May 2010 20:26:56 -0700 (PDT) Subject: Another "Go is Python-like" article. References: Message-ID: On May 21, 8:20?am, Grant Edwards wrote: > In a recent Reg article, there's yet more yammering on about how Go is > somehow akin to Python -- referring to Go as a "Python-C++" crossbreed. > > http://www.theregister.co.uk/2010/05/20/go_in_production_at_google/ > > I still don't get it. > > What about Go, exactly, do people see as Phython-like? > > Go doesn't seem to have any of the salient features (either syntactic > or semantic) of Python other than garbage collection. > > How is Go not just warmed-over Java? > > -- > Grant Edwards ? ? ? ? ? ? ? grant.b.edwards ? ? ? ?Yow! RELATIVES!! > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? gmail.com ? ? ? ? ? ? Actually, Go seems to be more C implemented the way the C developers would have done it if they knew then what they know now. That's not a joke - look at the names on the development team. I haven't a clue how anyone can think it's similar to Python. Or Java, for that matter. John Roth From clp2 at rebertia.com Fri May 21 23:30:43 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 May 2010 20:30:43 -0700 Subject: where are the program that are written in python? In-Reply-To: <4bf749ef@dnews.tpgi.com.au> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> Message-ID: On Fri, May 21, 2010 at 8:03 PM, Lie Ryan wrote: > On 05/22/10 04:47, Terry Reedy wrote: >> On 5/21/2010 6:21 AM, Deep_Feelings wrote: >>> python is not a new programming language ,it has been there for the >>> last .... 15+ years or so ? right ? >>> >>> however by having a look at this page >>> http://wiki.python.org/moin/Applications >>> i could not see many programs written in python (i will be interested >>> more in COMMERCIAL programs written in python ). and to be honest ,i >> >> There are two kinds of 'commercial' programs. >> 1. The vast majority are proprietary programs kept within a company for >> its own use. As long as these work as intended, they are mostly >> invisible to the outside world. >> 2. Programs sold to anyone who wants them. >> >> Python trades programmer speed for execution speed. If a successful >> Python program is going to be run millions of times, it makes economic >> sense to convert time-hogging parts to (for instance) C. ?In fact, this >> is a consideration in deciding what functions should be builtin and >> which stdlib modules are written or rewritten in C. >> >> Programs being sold tend to be compared to competitors on speed with >> perhaps more weight than they rationally should. Speed is easier to >> measure than, for instance, lack of bugs. > > doubting python's speed? Look at Mercurial vs. SVN; Mercurial is written > in Python while SVN in C. Mercurial beats SVN in speed by several orders > of magnitude. Erm, in fairness, I recall hearing that some speed-critical bits of hg are written in C. It does lend credence to the "Python as glue language" argument though; I doubt hg's extensibility and friendly interface would have been as easy to implement it C (particularly the slick instant-server feature). Cheers, Chris -- http://blog.rebertia.com From pengyu.ut at gmail.com Fri May 21 23:47:42 2010 From: pengyu.ut at gmail.com (Peng Yu) Date: Fri, 21 May 2010 22:47:42 -0500 Subject: How to show the current line number with pdb.set_trace() Message-ID: After starting pdb.set_trace(), python doens't show line number. Could you let me know how to print the number by default so that I know where the current line is? -- Regards, Peng From pavlovevidence at gmail.com Sat May 22 00:49:39 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 21 May 2010 21:49:39 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On May 21, 3:21?am, Deep_Feelings wrote: > please don't mention programs where python was used as a glue ,those > programs are not actually written in python. I hate to answer a troll, but I'll just mention that when people talk about a "glue language", they're not talking about using some Python code to connect two big systems together (although Python is good for that). What they are saying is that Python is a good language to serve as high-level logic interfacing lots of different library codes--often but not always written in faster languages--together in one program. In that case, yes, the program is written in Python. The word "glue" is probably not the best metaphor, since to most people it means "something you use to connect two objects together". A better metaphor would be like a "substrate language". A lot of materials do use a form of glue as the substrate, but never mind that. Carl Banks From sturla at molden.no Sat May 22 02:15:37 2010 From: sturla at molden.no (sturlamolden) Date: Fri, 21 May 2010 23:15:37 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On 21 Mai, 12:21, Deep_Feelings wrote: > 1- where are the programs that is written in python ? You could search for them with Google and download your results Bittorrent. > is python a valid practical programming language ? No, it is probably Turing incomplete. From __peter__ at web.de Sat May 22 02:15:39 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 May 2010 08:15:39 +0200 Subject: Problem with an huge dictionary References: <70b8f82e-2dfe-4403-ae77-cb4d005578f1@y12g2000vbr.googlegroups.com> <40f4fe52-c4e9-43c6-b0be-4fd6da91555d@c11g2000vbe.googlegroups.com> Message-ID: keobox wrote: > On 20 Mag, 12:58, Thomas Lehmann wrote: >> > The question is: >> > Is there a limit on the number of entries a dictionary can have i >> > jython? >> >> > I wrote a little app where my data is stored in a huge dictionary >> > (11746 entries) generated with a python script. >> > When I try to import the dictionary, jython complains with the >> > following message: >> >> 1) You did not say what you have saved (content of your dictionary). > > - As you can see I received the error when I tried to import > jmoco_event_data.py module from the jython interpreter prompt. > - The "import" will cause the module compilation, jython will produce > a .class file instead of .pyc. > - jmoco_event_data.py contains 4 dictionaries: > > typesValToName={ > 220:'EMS_EVENT_EMS_INTERNAL_BASE', > 221:'EMS_EVENT_INTERNAL_TYPE_BASE', > 222:'EMS_EVENT_INTERNAL_N_E_P_M_EVENT', > 223:'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD', > 224:'EMS_EVENT_NE_SPECIFIC_BASE', > ... 11746 entries int key: string value > } > > typesNameToVal={ > 'EMS_EVENT_EMS_INTERNAL_BASE':220, > 'EMS_EVENT_INTERNAL_TYPE_BASE':221, > 'EMS_EVENT_INTERNAL_N_E_P_M_EVENT':222, > 'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD':223, > 'EMS_EVENT_NE_SPECIFIC_BASE':224, > ... total 11746 entries string key: int value > } > > causesValToName={ > 0:'NOT_APPLICABLE_UNKNOWN', > 1:'SOFTWARE_CAUSE_UNKNOWN', > 2:'ABSENT_MODULE', > 3:'FAULTY_MODULE', > ... 483 entries int key: string value > } > > causesNameToVal={ > 'NOT_APPLICABLE_UNKNOWN':0, > 'SOFTWARE_CAUSE_UNKNOWN':1, > 'ABSENT_MODULE':2, > 'FAULTY_MODULE':3, > ... 483 entries string key: int value > } > >> 2) You did not say how you have saved. > > The dictionaries are in the jmoco_event_data.py module. > >> From the callstack - also I have never used jython - it looks like >> that >> there is a try to create a class. It looks like - I may be wrong - >> that >> you have saved user objects in your dictionary - have you? > > Nope, the dictionaries are only int to string mappings and string to > int mappings > >> If so you might fail on loading those objects - especially when your >> program >> does not have the code for it. > > The failure happens during module's import, so my question is: Is > jython able to handle such big dictionaries? The problem seems to be the size of the code, i. e. the dict literal rather than the size of the dictionary. With a slightly smaller dict I get $ cat make_dict_source.py from itertools import chain, count, islice def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument("n", type=int, default=100) parser.add_argument("py") args = parser.parse_args() prefix = ["data = {\n"] suffix = ["}\n"] pairs = ("'enum_whatever_{0}': {0},\n".format(i) for i in count()) pairs = islice(pairs, args.n) with open(args.py, "w") as outstream: lines = chain(prefix, pairs, suffix) outstream.writelines(lines) if __name__ == "__main__": main() $ python make_dict_source.py 4000 tmp.py $ jython tmp.py Traceback (innermost last): (no code object) at line 0 java.lang.ClassFormatError: Invalid method Code length 71912 in class file org/python/pycode/_pyx0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:632) at org.python.core.BytecodeLoader2.loadClassFromBytes(Unknown Source) at org.python.core.BytecodeLoader.makeClass(Unknown Source) at org.python.core.BytecodeLoader.makeCode(Unknown Source) at org.python.core.Py.compile_flags(Unknown Source) at org.python.core.Py.compile_flags(Unknown Source) at org.python.core.__builtin__.execfile_flags(Unknown Source) at org.python.util.PythonInterpreter.execfile(Unknown Source) at org.python.util.jython.main(Unknown Source) java.lang.ClassFormatError: java.lang.ClassFormatError: Invalid method Code length 71912 in class file org/python/pycode/_pyx0 $ jython --version Jython 2.2.1 on java1.6.0_0 Jython seems to generate a method that is bigger than the 64K allowed by Java. The simplest workaround is probably to let your module read the dict data from a separate file in e. g. csv format. Peter From sturla at molden.no Sat May 22 02:20:31 2010 From: sturla at molden.no (sturlamolden) Date: Fri, 21 May 2010 23:20:31 -0700 (PDT) Subject: Another "Go is Python-like" article. References: Message-ID: On 21 Mai, 16:20, Grant Edwards wrote: > I still don't get it. > > What about Go, exactly, do people see as Phython-like? > > Go doesn't seem to have any of the salient features (either syntactic > or semantic) of Python other than garbage collection. > > How is Go not just warmed-over Java? Go is Algol 68. Reinventing the wheel is always fun. From pmaupin at gmail.com Sat May 22 02:25:53 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 21 May 2010 23:25:53 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <48616f72-3a7e-4b04-aabc-49acd853e01b@j9g2000vbp.googlegroups.com> On May 21, 8:45?pm, a... at pythoncraft.com (Aahz) wrote: > In article , > Patrick Maupin ? wrote: > >There are a lot of commercial programs written in Python. ?But any > >company which thinks it has a lock on some kind of super secret sauce > >isn't going to use Python, because it's very easy to reverse engineer > >even compiled Python programs. ? > > That's not always true. ?Both my employer (Egnyte) and one of our main > competitors (Dropbox) use Python in our clients. ?We don't care much > because using our servers is a requirement of the client. Absolutely. I wrote my post after the OP's second post, and from that short, derisive tome, I inferred that the OP's definition of "commercial" was quite narrow, so I was trying to respond on the basis of what he would consider "commercial," which BTW, probably wouldn't include a lot of programs that, e.g. Google uses to make money. Regards, Pat From pmaupin at gmail.com Sat May 22 02:29:37 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 21 May 2010 23:29:37 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <87mxvsfzvh.fsf@benfinney.id.au> Message-ID: <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> On May 21, 9:12?pm, Ben Finney wrote: > a... at pythoncraft.com (Aahz) writes: > > In article , > > Patrick Maupin ? wrote: > > > >There are a lot of commercial programs written in Python. ?But any > > >company which thinks it has a lock on some kind of super secret sauce > > >isn't going to use Python, because it's very easy to reverse engineer > > >even compiled Python programs. ? > > > That's not always true. ?Both my employer (Egnyte) and one of our main > > competitors (Dropbox) use Python in our clients. ?We don't care much > > because using our servers is a requirement of the client. > > Doesn't that mean those companies don't fit the above description? That > is, neither of them ?thinks it has a lock on some kind of super secret > sauce? in the programs. So they don't seem to be counter-examples. Just because someone has competition doesn't mean they don't think they have secret sauce. I think Aahz's main point was that in his sub- industry, the secret sauce is guarded by not actually letting the customer have access to executable code, other than through the network. Regards, Pat From moijes12 at gmail.com Sat May 22 03:38:54 2010 From: moijes12 at gmail.com (moijes12) Date: Sat, 22 May 2010 00:38:54 -0700 (PDT) Subject: getting local area connection information through python in windows Message-ID: <4ca22888-4e76-48ee-a7da-884e30b294f0@e34g2000pra.googlegroups.com> Hi I need to get the details of Local Area connection information(network interface) like packets sent,packets recieved,duration etc. I have to do this in Windows using python. I tried looking under the socket module and also googling,but did not find anything that I could use for windows,though I did find something for linux.I have to somehow use the socket module for this. Please help me in cracking this. Regards Moses From sturla at molden.no Sat May 22 03:43:09 2010 From: sturla at molden.no (sturlamolden) Date: Sat, 22 May 2010 00:43:09 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On 21 Mai, 20:20, Patrick Maupin wrote: > There are a lot of commercial programs written in Python. ?But any > company which thinks it has a lock on some kind of super secret sauce > isn't going to use Python, because it's very easy to reverse engineer > even compiled Python programs. Decompiling Java or .NET bytecode isn't rocket science either. > Also, any company in a competitive > market where execution speed is extremely important might choose some > other language because, frankly, the fact that a development tool is > highly productive is not something that the end user directly cares > about. ? That only applies to CPU bound program code (most program code is I/O bound), and only to computational bottlenecks (usually less than 5% of the code) in the CPU bound programs. Today, most programs are I/O bound: You don't get a faster network connection or harddrive by using C. In this case, performance depends on other factors than choice of language. That is why Mercurial (written in Python) can be much faster than SVN (written in C). For computational bottlenecks we might want to try high-performance numerical libraries first. If that does not help, we can try to replace some Python with C. Python as "glue" does not mean Python is inferior to C. It just means it is a PITA to write C or Fortran all the time. I value my own time a lot more than a few extra CPU cycles. Who cares about speed where it is not needed? There are also a lot of uneducated FUD about the GIL: First, for I/O bound programs the GIL is not an issue, as threads that are blocked and waiting for I/O do not compete for the GIL. (That should be rather obvious, but my guesstimate is that most programmers do not understand this.) Second, for CPU bound programs the GIL is not an issue either: Fine-grained parallelization is done elsewhere than Python, e.g. hidden inside numerical libraries or implemented with OpenMP pragmas in C code. Course-grained parallelization can be done in Python using Python threads, as the GIL can be released in C using a couple of macros (or using ctypes.CDLL). In practice, the GIL rarely impairs anything, but create a lot of FUD form persons who do not understand the problem. From sturla at molden.no Sat May 22 04:12:56 2010 From: sturla at molden.no (sturlamolden) Date: Sat, 22 May 2010 01:12:56 -0700 (PDT) Subject: getting local area connection information through python in windows References: <4ca22888-4e76-48ee-a7da-884e30b294f0@e34g2000pra.googlegroups.com> Message-ID: <5669d4b6-6a4e-4da0-9357-01a298acf0f1@j27g2000vbp.googlegroups.com> On 22 Mai, 09:38, moijes12 wrote: > I need to get the details of Local Area connection information(network > interface) like packets sent,packets recieved,duration etc. I have to > do this in Windows using python. >>> import subprocess as sp >>> p = sp.Popen("netstat -s", shell=False, bufsize=4096, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE) >>> print ''.join(p.stdout.readlines()) >>> p.terminate() There are other switches for the netstat command as well. From moijes12 at gmail.com Sat May 22 04:17:50 2010 From: moijes12 at gmail.com (moijes12) Date: Sat, 22 May 2010 01:17:50 -0700 (PDT) Subject: getting local area connection information through python in windows References: <4ca22888-4e76-48ee-a7da-884e30b294f0@e34g2000pra.googlegroups.com> <5669d4b6-6a4e-4da0-9357-01a298acf0f1@j27g2000vbp.googlegroups.com> Message-ID: On May 22, 1:12?pm, sturlamolden wrote: > On 22 Mai, 09:38, moijes12 wrote: > > > I need to get the details of Local Area connection information(network > > interface) like packets sent,packets recieved,duration etc. I have to > > do this in Windows using python. > >>> import subprocess as sp > >>> p = sp.Popen("netstat -s", shell=False, bufsize=4096, > > ? ? ? ? ? ? ? stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE) > > >>> print ''.join(p.stdout.readlines()) > >>> p.terminate() > > There are other switches for the netstat command as well. Thanks Moses From michele.simionato at gmail.com Sat May 22 04:49:39 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 22 May 2010 01:49:39 -0700 (PDT) Subject: help with the Python 3 version of the decorator module Message-ID: I have finally decided to port the decorator module to Python 3. Changing the module was zero effort (2to3 worked) but changing the documentation was quite an effort, since I had to wait for docutils/ pygements to support Python 3 and to change all my custom build process. Also, I am relying on distribute for installing on Python 3. I would welcome feedback for people using Python 3 on various platforms (including Windows) to see if they can install the module and how much of effort it is. Here is the tarball: http://micheles.googlecode.com/files/decorator-3.2beta.tar.gz Here is the documentation: http://micheles.googlecode.com/hg/decorator/index.html The installation process should work for Python 2.4, 2.5, 2.6, 2.7, 3.0, 3.1 and all platforms were Python runs, but I have only tested it on Linux for Python 2.6 and 3.1. The module has no relevant changes, so I expect problems only from the building process, if any. I am not sure of what will happen if you do not have distribute or if you have a previous version of the module, or if you use pip or something else (even in Python 2.X). The packaging in Python has become a real mess! TIA for you help, Michele Simionato From dragonlordnld at gmail.com Sat May 22 05:43:17 2010 From: dragonlordnld at gmail.com (Dragon Lord) Date: Sat, 22 May 2010 02:43:17 -0700 (PDT) Subject: Urllib2: Only a partial page retrieved Message-ID: <77019685-3bf4-4d0c-9fd7-13ed8e84e102@y12g2000vbg.googlegroups.com> I am trying to download a few IEEE pages by using urllib2, but with certain pages I get only the first part of the page. With other pages from the same server and url (just another pageID) I get the right results. The difference between these pages seems to be the date the paper for which the page is was published. Any papers from before 2000 end just before the date, pages from 2000 and later and at <\html>. Two example URLs: Does not work: http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=517048 Does work: http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=854728 I tried both urlopen and urlretrieve and tried both urllib and urllib2. With urlopen I tried both .read() and .read(10000) to make sure I got the whole page, but nothing helped. Sample code: import urllib2 response = urllib2.urlopen("http://ieeexplore.ieee.org/xpl/ freeabs_all.jsp?arnumber=517048") html = response.read() print html The cutoff is allways at the same location: just after the label "Meeting date" and before the date itself. Could it be that something is interpreted as and eof command or something like that? example of the cutoff point with a bad page:
Meeting Date: example of the cutoff point with a good page:
Meeting Date: 13 jun 2000 The bad pages do continue after this point btw. if you use a webbrowser, it does not seem to be a server problem. From doctoresam at gmail.com Sat May 22 05:44:57 2010 From: doctoresam at gmail.com (Deep_Feelings) Date: Sat, 22 May 2010 02:44:57 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: thank you very much ,your reply guys are very nice and informative. hope you best luck in your life From sanamsingh at hotmail.com Sat May 22 05:50:15 2010 From: sanamsingh at hotmail.com (sanam singh) Date: Sat, 22 May 2010 09:50:15 +0000 Subject: help req setting breakpoints in gdb Message-ID: Hi, I am using wingide to debug my python code. To debug my c code when i attach wingide to ddd. It is all done successfully. However when i try to set a beak point in gdb i get following error : (gdb) break /home/sa/mygr/gnuradio-core/src/lib/general/gr_gr_deinterleave.cc:13 No source file named /home/sa/mygr/gnuradio-core/src/lib/general/gr_gr_deinterleave.cc. however the file really exists there. Secondly, when after attach i simply give the command : (gdb) break 13 Breakpoint 4 at 0x805a0f5: file ./Modules/python.c, line 13. where as i am running my program from a different folder. Please help me. Cheers. _________________________________________________________________ Hotmail: Trusted email with powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Sat May 22 06:00:54 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 22 May 2010 03:00:54 -0700 (PDT) Subject: Another "Go is Python-like" article. References: Message-ID: On May 21, 4:20?pm, Grant Edwards wrote: > > What about Go, exactly, do people see as Python-like? The philosophy of keeping things simple. I find the concurrency mechanism quite Pythonic. Moreover Go interfaces are quite akin to Python duck typing, but better. There also things which are quite different from Python e.g. the attitude towards exceptions. In theory Go should be akin to C, but my gut feeling is that in practice programming in it should not feel too much different from programming in Python (but I do not have first hand experience). Michele Simionato From timoverbeek10 at gmail.com Sat May 22 06:06:33 2010 From: timoverbeek10 at gmail.com (timo verbeek) Date: Sat, 22 May 2010 03:06:33 -0700 (PDT) Subject: creating addon system References: Message-ID: Is there not an other way to create a fast addon system? A module or something like that From inigoserna at gmail.com Sat May 22 06:16:38 2010 From: inigoserna at gmail.com (=?UTF-8?B?ScOxaWdvIFNlcm5h?=) Date: Sat, 22 May 2010 12:16:38 +0200 Subject: ANN: lfm v2.2 Message-ID: Hi, after 6 months of laziness while code was complete in my computer but didn't have enough time, I'm releasing a new version of lfm now. Description: ========= Last File Manager is a simple but powerful file manager for the UNIX console. It's written in Python, using curses module. Licensed under GNU Public License version 3. Some of the features you could find in lfm: - console-based file manager for UNIX platforms - 1-pane or 2-pane view - tabs - bookmarks - history - vfs for compressed files - dialogs with entry completion - fast access to the shell - direct integration of find/grep, df and other tools - color files by extension - fast file viewer with text and binary modes - ...and many others Download it from: ============= http://inigo.katxi.org/devel/lfm (home server) or http://code.google.com/p/lfm/ or from http://www.terra.es/personal7/inigoserna/lfm when crap ISP updates its cache. Changes since last version: ==================== + New features - use 2 progress bars in copy/move/delete dialog, one for files count and other for files size - added recursive chmod chown chgrp - faster cursor movement . Ctrl-l: center cursor in panel, so now edit-link is in 'L' . Ctrl-cursor_up, Ctrl-P: move cursor 1/4th of page up . Ctrl-cursor_down, Ctrl-N: move cursor 1/4th of page down . P: move cursor 1/4th of page up in other panel . N: move cursor 1/4th of page down in other panel - file_menu new feature: a -> backup file. You can specify the extension to use in .lfmrc - added support for .xz compressed files - Unicode & Encodings . rewrite all internals to use unicode strings, but employ terminal encoding (f.e. utf-8) to interact with the user or to display contents in ncurses functions or to run commands in shell . when lfm detects a file with invalid encoding name it asks the user to convert it (can be automatic with the proper option in the configuration, automatic_file_encoding_conversion, default 0 (ask)). If not converted, lfm will display the file but won't operate on it. . try more encodings when we get a filename with strange characters . lfm will check and require a valid encoding before running - Pyview: . completely rewritten. Code is shorter and more beautiful now Uses a new FileCache class to accelerate the retrieving of file lines . displays contents between 2 and 4 times faster . new command line flag -s/--stdin to force reading from stdin. Now pyview doesn't wait for stdin input by default, so it starts much faster. eg. $ ps efax | pyview -s + Minor changes - add color entries for directories and exe_files - expand ~ to user home - make Tree follow .dotfiles behaviour, new keybinding Ctrl-H - dialogs are bigger now - show filesystem info rewritten - show file info rewritten, now it shows correctly information from fuse-mounted volumes - added new "ebook" category, filetypes and formats + About the code - since python v2.6+, popen* is deprecated, so make lfm check python version and use popen* or subprocess accordingly - correct some python idioms - clean code + Documentation - Added "Files Name Encoding" and "FAQ" sections - Added information about keybindings in permissions window - Updated some other minor changes: wide char support, vfs, thanks + lots of bugs fixed: - file system information was not showed correctly sometimes - devices major and minor numbers were not showed correctly - crash in goto_dir if there aren't any historic entries - crash in a void EntryLine after pressing BACKSPACE on some platforms - unzip => overwrite files without prompting ("unzip -o" option) to avoid ethernal waiting, as messages can not be seen by user - fix make_dir error message - recompressing a vfs compressed file leave some garbage on temporary dir - don't try to copy fifo/socket/block-dev/char-dev files - crash when we don't have enough permissions to write to dest - show_dirs_size: don't show in stderr if we don't have perms for a dir - can't browse /home/ as root if .gvfs is present - EntryLine: non-ascii chars are not showed correctly - lfm crashes with invalid encoding filenames - increment owner and group space to avoid ugly look in 1-pane view - when moving files, don't delete source if some error or if we don't overwrite destination Of course, all comments, suggestions, etc. are welcome. Best regards, I?igo Serna From python.list at tim.thechases.com Sat May 22 07:28:36 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 22 May 2010 06:28:36 -0500 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <4BF7BFE4.3090806@tim.thechases.com> On 05/22/2010 02:43 AM, sturlamolden wrote: > That only applies to CPU bound program code (most program code is I/O > bound), and only to computational bottlenecks (usually less than 5% of > the code) in the CPU bound programs. Today, most programs are I/O > bound: You don't get a faster network connection or harddrive by using > C. In this case, performance depends on other factors than choice of > language. That is why Mercurial (written in Python) can be much faster > than SVN (written in C). > > For computational bottlenecks we might want to try high-performance > numerical libraries first. If that does not help, we can try to > replace some Python with C. Just as an aside, last I checked, mercurial had some core code in C for speed. But that doesn't negate your line of reasoning, rather it cements it -- they found it was most productive to work in Python, but needed the core bits to improve in speed so rewrote them in C. I'd also include that a change in algorithm can be a big help for speeding up CPU-bound code. It doesn't matter much if you're using Python or hand-coding that inner loop in C/ASM, if you're using a O(2^N) algorithm. I find it easier to write good/speedy algorithms in Python because I have a toolkit of built-in data-types (sets, dicts, lists, etc) that I can reach for, without making sure I've added-on certain C libraries. -tkc From fabiofz at gmail.com Sat May 22 09:03:19 2010 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sat, 22 May 2010 10:03:19 -0300 Subject: Do any debuggers support "edit and continue?" In-Reply-To: References: Message-ID: On Wed, May 12, 2010 at 2:42 PM, Joel Koltner wrote: > Just curious... in Microsoft's Visual Studio (and I would presume some other > tools), for many languages (both interpreted and compiled!) there's an "edit > and conitnue" option that, when you hit a breakpoint, allows you to modify a > line of code before it's actually executed. > > Does any Python debugger support this feature? ?Being an interpreted > language it doesn't seem like it would necessarily be too onerous to > support? ?It'd be quite handy in that, especially if you hit a breakpoint > due to the interpreter throwing an error, you could fix just the line in > question and keep going, rather than having to stop the entire program, fix > the line, and then run again and potentially kill a bunch of time getting > the program back into the same "state." Just for the record, Pydev had that from 1.4.8 to 1.5.5, but it was removed because it could be a bit unpredictable (it relied on xreload.py). So, now what you can still do is change your variables / write any code in the console / use the jump to re-execute something (in the interface it's Run > Run to line -- or Ctrl+R) which is what you usually need when experimenting (I still think the edit and continue would be a nice feature, but the current state of xreload is not really good for that -- and I'm not sure if it'll ever be -- although I do have some alternatives in mind that would improve that support greatly, some things could never be really fixed, such as changing the value of an int constant that's been already assigned to somewhere else -- anyways, I've got my hands on some other things right now, so, there's currently no plan for that being supported (again)). Cheers, Fabio p.s.: I think I'd be able to do it before reaching the whole $ 500,000 in funding :) From victorsubervi at gmail.com Sat May 22 09:51:04 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 22 May 2010 09:51:04 -0400 Subject: Another Strange MySQL Problem In-Reply-To: <4BF6D3B1.2070605@tim.thechases.com> References: <4BF6D3B1.2070605@tim.thechases.com> Message-ID: On Fri, May 21, 2010 at 2:40 PM, Tim Chase wrote: > On 05/21/2010 12:31 PM, Victor Subervi wrote: > >> cursor.execute('insert into Baggage values (Null, %s, %s, %s, >> %s)', (flight_id, customer_id, weight, ticket_no)) >> > > You're trying to insert stuff... > > > OperationalError: (1452, 'Cannot add or update a child row: a foreign >> key constraint fails (`seaflight/Baggage`, CONSTRAINT `Baggage_ibfk_2` >> FOREIGN KEY (`customer_id`) REFERENCES `Customers` (`id`))') >> > > But the value you're giving for the customer_id doesn't exist in the > Customers table (as mandated by the FK). Or perhaps the column-order for > Baggage isn't what you think it is. I always specify it explicitly: > > INSERT INTO Baggage ( > something, flight_id, customer_id, weight, ticket_no > ) VALUES (Null, %s, %s, %s, %s) > > just in case the table column-order ever changes during a database update. > As it turns out, my error was confusing my tables Customers and Passengers. I was calling customer_id when I should have been calling passenger_id, which is why MySQL couldn't find the correct values <:-} beno > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Sat May 22 09:55:25 2010 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 May 2010 15:55:25 +0200 Subject: creating addon system In-Reply-To: References: Message-ID: Am 22.05.2010 12:06, schrieb timo verbeek: > Is there not an other way to create a fast addon system? > A module or something like that How fancy are your requirements? People have written numerous plugin systems, from simple to use ones like CherryPy's tool system up to a complex component architecture like zope.component. I recommend against exec() and execfile(). It makes debugging and testing harder and it has security concern, too. Christian From bryanjugglercryptographer at yahoo.com Sat May 22 10:18:33 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sat, 22 May 2010 07:18:33 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <85l509Fpe7U1@mid.individual.net> <6025dfa5-bc54-412d-98e2-71d2ad4540a6@11g2000prv.googlegroups.com> Message-ID: <041e63e5-8d83-4286-ae2d-7c38f18d8139@s13g2000prc.googlegroups.com> I wrote: > I came up with a recursive memo-izing algorithm that > handles 100-digit n's. [...] I made a couple improvements. Code below. -Bryan #--------------------- _nds = {} def ndsums(m, d): """ Count d-digit ints with digits suming to m. """ assert m >= 0 and d >= 0 m = min(m, d * 9 - m) # exploit symmetry if m < 0: return 0 if m == 0 or d == 1: return 1 if (m, d) not in _nds: _nds[(m, d)] = sum(ndsums(m - i, d - 1) for i in range(min(10, m + 1))) return _nds[(m, d)] def prttn(m, n): assert m >= 0 and n > 0 count = 0 dls = [int(c) for c in reversed(str(n))] while dls: msd = dls.pop() count += sum(ndsums(m - d, len(dls)) for d in range(min(msd, m + 1))) m -= msd return count #---------------------- # Testing from bisect import bisect_right def slow_prttn(m, n): return sum(1 for k in range(m % 9, n, 9) if sum(int(i) for i in str(k)) == m) _sums = [0, {}] def tab_prttn(m, n): upto, sums = _sums if n >= upto: for i in range(upto, n): dsum = sum(int(c) for c in str(i)) sums.setdefault(dsum, []).append(i) _sums[0] = n if m not in sums: return 0 return bisect_right(sums[m], n - 1) for n in range(1, 1234567): digits = [int(c) for c in str(n)] for m in range(9 * len(digits)): count = tab_prttn(m, n) assert prttn(m, n) == count if n < 500: assert slow_prttn(m, n) == count if count == 0: break if n % 1000 == 0: print('Tested to:', n) From victorsubervi at gmail.com Sat May 22 10:25:56 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 22 May 2010 10:25:56 -0400 Subject: Just To Be Sure...MySQL Message-ID: Hi; A lister recently responded to my post concerning mysl commands of the following type: cursor.execute('insert into foo values (%s, %s)' % (bar, something)) stating that I need to eliminate the "%" to prevent injection attacks, thus: cursor.execute('insert into foo values (%s, %s)', (bar, something)) My question is simply this: Is that advice good for *all* mysql commands? Or are there some where the "%" is necessary and a comma would fail? I need to update lots of mysql commands. If I can do it without harmful consequences, I'll do it across the board. Otherwise, I'll have to test each one. TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sat May 22 11:09:05 2010 From: aahz at pythoncraft.com (Aahz) Date: 22 May 2010 08:09:05 -0700 Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: In article , Tim Chase wrote: > >I'd also include that a change in algorithm can be a big help for >speeding up CPU-bound code. It doesn't matter much if you're using >Python or hand-coding that inner loop in C/ASM, if you're using a >O(2^N) algorithm. Rewriting an algorithm also helps I/O-bound code when you're doing something stupid like querying a DB multiple times for each record instead of caching the result. Also, rewriting your algorithm to just pull the entire DB into RAM helps, too. (If you know your dataset must fit into RAM, anyway, in order to process your algorithm.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From sturla at molden.no Sat May 22 11:21:56 2010 From: sturla at molden.no (sturlamolden) Date: Sat, 22 May 2010 08:21:56 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <266505bb-30dc-4a37-9eea-d309f91087a6@p17g2000vbe.googlegroups.com> On 22 Mai, 17:09, a... at pythoncraft.com (Aahz) wrote: > Rewriting an algorithm also helps I/O-bound code Yes it does, if it involves how we do I/O. Algorithms are just as important for I/O bound as they are for compute bound code. But implementing an algorithm in C as opposed to Python would not improve nearly as much for I/O bound as it could do for compute bound code. From lists at cheimes.de Sat May 22 12:06:30 2010 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 May 2010 18:06:30 +0200 Subject: Just To Be Sure...MySQL In-Reply-To: References: Message-ID: > A lister recently responded to my post concerning mysl commands of the > following type: > > cursor.execute('insert into foo values (%s, %s)' % (bar, something)) > > stating that I need to eliminate the "%" to prevent injection attacks, thus: > > cursor.execute('insert into foo values (%s, %s)', (bar, something)) > > My question is simply this: Is that advice good for *all* mysql commands? Or > are there some where the "%" is necessary and a comma would fail? I need to > update lots of mysql commands. If I can do it without harmful consequences, > I'll do it across the board. Otherwise, I'll have to test each one. > TIA, > beno You *MUST NOT* use string formatting for SQL commands unless you carefully quote and validate the strings. Otherwise your SQL application is vulnerable to SQL injection attacks. SQL injections are one of the most common and devastating attacks for web applications these days. Example: "Select * from Users where uid = %s" % uid uid = "1; DROP Table users;" Guess what happens here ... So yes, you must use the special syntax for all your commands. The DBA takes care of quoting. But you can't use the % replacement character for anything than the variable part of a DQL or DML statement. Variable parts are the right side of a WHERE, HAVING, SET and (IIRC) ORDER BY clause and the body of a VALUES block. But you can't do "Select * FROM %". Christian From awilliam at whitemice.org Sat May 22 12:09:18 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Sat, 22 May 2010 12:09:18 -0400 Subject: Just To Be Sure...MySQL In-Reply-To: References: Message-ID: <1274544558.10069.1.camel@linux-yu4c.site> On Sat, 2010-05-22 at 18:06 +0200, Christian Heimes wrote: > > A lister recently responded to my post concerning mysl commands of the > > following type: > > > > cursor.execute('insert into foo values (%s, %s)' % (bar, something)) > > > > stating that I need to eliminate the "%" to prevent injection attacks, thus: > > > > cursor.execute('insert into foo values (%s, %s)', (bar, something)) > > > > My question is simply this: Is that advice good for *all* mysql commands? Or > > are there some where the "%" is necessary and a comma would fail? I need to > > update lots of mysql commands. If I can do it without harmful consequences, > > I'll do it across the board. Otherwise, I'll have to test each one. > > TIA, > > beno > > You *MUST NOT* use string formatting for SQL commands unless you +1 And they are hideous code. Use an ORM: > carefully quote and validate the strings. Otherwise your SQL application > is vulnerable to SQL injection attacks. SQL injections are one of the > most common and devastating attacks for web applications these days. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From lists at cheimes.de Sat May 22 12:18:36 2010 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 May 2010 18:18:36 +0200 Subject: Just To Be Sure...MySQL In-Reply-To: <1274544558.10069.1.camel@linux-yu4c.site> References: <1274544558.10069.1.camel@linux-yu4c.site> Message-ID: Am 22.05.2010 18:09, schrieb Adam Tauno Williams: > On Sat, 2010-05-22 at 18:06 +0200, Christian Heimes wrote: >>> A lister recently responded to my post concerning mysl commands of the >>> following type: >>> >>> cursor.execute('insert into foo values (%s, %s)' % (bar, something)) >>> >>> stating that I need to eliminate the "%" to prevent injection attacks, thus: >>> >>> cursor.execute('insert into foo values (%s, %s)', (bar, something)) >>> >>> My question is simply this: Is that advice good for *all* mysql commands? Or >>> are there some where the "%" is necessary and a comma would fail? I need to >>> update lots of mysql commands. If I can do it without harmful consequences, >>> I'll do it across the board. Otherwise, I'll have to test each one. >>> TIA, >>> beno >> >> You *MUST NOT* use string formatting for SQL commands unless you > > +1 > > And they are hideous code. > > Use an ORM: How about using a proper RDBMS that supports SQL standards, triggers, foreign keys and functions first? :) From dragonlordnld at gmail.com Sat May 22 12:24:32 2010 From: dragonlordnld at gmail.com (Dragon Lord) Date: Sat, 22 May 2010 09:24:32 -0700 (PDT) Subject: Urllib2: Only a partial page retrieved References: <77019685-3bf4-4d0c-9fd7-13ed8e84e102@y12g2000vbg.googlegroups.com> Message-ID: Oops, het "Good" page is alos handled wrongly. The papers from 2000 are handled wrong too so a real example of a well performing page: http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=5206867 On May 22, 11:43?am, Dragon Lord wrote: > I am trying to download a few IEEE pages by using urllib2, but with > certain pages I get only the first part of the page. With other pages > from the same server and url (just another pageID) I get the right > results. The difference between these pages seems to be the date the > paper for which the page is was published. Any papers from before 2000 > end just before the date, pages from 2000 and later and at <\html>. > > Two example URLs: > > Does not work:http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=517048 > Does work:http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=854728 > > I tried both urlopen and urlretrieve and tried both urllib and > urllib2. With urlopen I tried both .read() and .read(10000) to make > sure I got the whole page, but nothing helped. > Sample code: > > import urllib2 > response = urllib2.urlopen("http://ieeexplore.ieee.org/xpl/ > freeabs_all.jsp?arnumber=517048") > html = response.read() > print html > > The cutoff is allways at the same location: just after the label > "Meeting date" and before the date itself. Could it be that something > is interpreted as and eof command or something like that? > > example of the cutoff point with a bad page: >
Meeting Date: > > example of the cutoff point with a good page: >
Meeting Date: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 13 jun 2000 > > The bad pages do continue after this point btw. if you use a > webbrowser, it does not seem to be a server problem. From ntwrkd at gmail.com Sat May 22 14:01:35 2010 From: ntwrkd at gmail.com (ntwrkd) Date: Sat, 22 May 2010 11:01:35 -0700 Subject: bash-style auto completion in command line program. use rlcomplete? Message-ID: I am trying to create a bash-style auto completion in a simple command-line and script-based program i created using cmd. I saw http://docs.python.org/library/rlcompleter.html, which I'm thinking is the way to go for my program to intercept the tab key. Would anyone have thoughts on this? I wish cmd or cmd2 had this functionality built-in. Thanks in advance. From pmaupin at gmail.com Sat May 22 14:45:51 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 22 May 2010 11:45:51 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <9584607c-1aea-42b1-9671-19a2b51a5e17@l6g2000vbo.googlegroups.com> On May 22, 2:43?am, sturlamolden wrote: > On 21 Mai, 20:20, Patrick Maupin wrote: > > Also, any company in a competitive > > market where execution speed is extremely important might choose some > > other language because, frankly, the fact that a development tool is > > highly productive is not something that the end user directly cares > > about. ? > > That only applies to CPU bound program code (most program code is I/O > bound), and only to computational bottlenecks (usually less than 5% of > the code) in the CPU bound programs. Today, most programs are I/O > bound: You don't get a faster network connection or harddrive by using > C. In this case, performance depends on other factors than choice of > language. That is why Mercurial (written in Python) can be much faster > than SVN (written in C). > > For computational bottlenecks we might want to try high-performance > numerical libraries first. If that does not help, we can try to > replace some Python with C. Python as "glue" does not mean Python is > inferior to C. It just means it is a PITA to write C or Fortran all > the time. I value my own time a lot more than a few extra CPU cycles. > Who cares about speed where it is not needed? I think we're in violent agreement here -- you neglected to quote the part where I said "(But the up-front choice of another language simply for speed, rather than prototyping with Python and then recoding the slow bits, would probably be a decision borne of ignorance.)" Regards, Pat From tjreedy at udel.edu Sat May 22 14:49:26 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 May 2010 14:49:26 -0400 Subject: where are the program that are written in python? In-Reply-To: <4bf749ef@dnews.tpgi.com.au> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> Message-ID: On 5/21/2010 11:03 PM, Lie Ryan wrote: > On 05/22/10 04:47, Terry Reedy wrote: >> On 5/21/2010 6:21 AM, Deep_Feelings wrote: >>> python is not a new programming language ,it has been there for the >>> last .... 15+ years or so ? right ? >>> >>> however by having a look at this page >>> http://wiki.python.org/moin/Applications >>> i could not see many programs written in python (i will be interested >>> more in COMMERCIAL programs written in python ). and to be honest ,i >> >> There are two kinds of 'commercial' programs. >> 1. The vast majority are proprietary programs kept within a company for >> its own use. As long as these work as intended, they are mostly >> invisible to the outside world. >> 2. Programs sold to anyone who wants them. >> >> Python trades programmer speed for execution speed. If a successful >> Python program is going to be run millions of times, it makes economic >> sense to convert time-hogging parts to (for instance) C. In fact, this >> is a consideration in deciding what functions should be builtin and >> which stdlib modules are written or rewritten in C. >> >> Programs being sold tend to be compared to competitors on speed with >> perhaps more weight than they rationally should. Speed is easier to >> measure than, for instance, lack of bugs. > > doubting python's speed? The is a somewhat bizarre response to me. I have been promoting Python for about 13 years, since I dubbed it 'executable pseudocode', which is to say, easy to write, read, understand, and improve. I am also a realist. Any fixed (C)Python program can be sped up, at least a bit, and possibly more, by recoding in C. At minimum, the bytecodes can be replaced by the C code and C-API calls that they get normally get translated into. Ints can be unboxed. Etcetera. This tend to freeze a program, which is fine when development is finished. I believe Raymond wrote each itertool (or at least most) in Python first, then rewrote each in C for speed, since they are intented to be repeatedly used components of other Python programs. He is not 'doubting Python's speed', just being realistic. > Look at Mercurial vs. SVN; Neither are being sold, as far as I know. > Mercurial is written in Python while SVN in C. > Mercurial beats SVN in speed by several orders > of magnitude. Because, as I said, and as you explain further, Python favors programmer speed, including speed of testing new algorithms, over raw execution speed of current algorithms. (Current) speed is (also) easier to test than improvability and hence possible speed improvements. > > One of Mercurial's design goal was to be faster than SVN, if the > programmers have naively believed that choice of language would matter > to program's speed, they'd choose to write Mercurial in assembly instead > (the same argument applies to Git, written in shell scripts). > > Now, you may think this is an unfair comparison, since Mercurial is hype > and new, SVN is antiquated and old. But it shows that in real-life, the > language being inherently slow often dosn't matter. What matters more > are the choice of data structure and algorithm, I/O speed, network > latency, and development speed. If and when mercurial deveopment slows down, some of its developers might consider whether any of the utility functions written in Python might usefully be rewritten in C. One of the intentional virtues of Python is that one can transparently convert part or all of a module *without changing* the import and use of the module. Terry Jan Reedy From pmaupin at gmail.com Sat May 22 15:13:30 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 22 May 2010 12:13:30 -0700 (PDT) Subject: Another "Go is Python-like" article. References: Message-ID: <7c1d7e0e-eb2b-411d-bc7c-7e12a247ee8b@e21g2000vbl.googlegroups.com> On May 22, 5:00?am, Michele Simionato wrote: > On May 21, 4:20?pm, Grant Edwards wrote: > > > What about Go, exactly, do people see as Python-like? > > The philosophy of keeping things simple. I find the concurrency > mechanism quite Pythonic. That's nice. > Moreover Go interfaces are quite akin to Python duck typing, but > better. That's nice too. > There also things which are quite different from Python e.g. > the attitude towards exceptions. That's a biggie. One of the beautiful things about Python is how it lets me incrementally deal with incompletely specified problems -- "here's some source data -- go do something useful with it". The FAQ discusses why the go language deliberately leaves out assert -- the developers rightly view assert statements as problematic in achieving 5 nines in a server environment, and they (somewhat incorrectly IMO) view them as problematic when testing things. Looking at their rationale, it is appears that one or more of the primary go developers had to deal way too often with people who overuse and abuse exceptions, so they are reverting to an almost childish "I'll fix their little red wagon! When they have to use *my* language, they won't be able to do that anymore!" kind of mentality. Another possibility is that they viewed the complexity of exceptions as interfering with their primary goals, and felt it necessary to rationalize their absence after the fact. For some kinds of programming, the lack of exceptions wouldn't keep me from programming Pythonically, but for huge classes of problems, it would. That's a big deal for me personally -- although I like to have lots of tools in my toolbox, the one I reach for when doing exploratory programming is probably going to have exceptions. And guess what? If the exploratory programming winds up being "good enough" (as often happens), then no recoding is required. > In theory Go should be akin to C, > but my gut feeling is that in practice programming in it should not > feel too much different from > programming in Python (but I do not have first hand experience). For well-specified problems, I might be able to agree with you, but I'm not sure. Even then, sometimes I build stuff incrementally, trying out various kinds of internal interfaces. During that development process, exceptions are a valuable mechanism for ensuring that both sides of an interface agree on the contract. (Obviously, unit testing is useful in this as well, but premature unit testing can add friction that makes it difficult to converge on an optimal design -- it's no fun to be continually rearchitecting unit tests because of other design decisions.) What will be interesting to see is if a culture develops inside google where people prototype in Python or some other language and then implement the final cut in go. If this happens often enough and the cost of recoding the final implementation is deemed high enough, then the natural question will be "What can we add to go to make it a better prototyping language?" Regards, Pat From pmaupin at gmail.com Sat May 22 15:39:27 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 22 May 2010 12:39:27 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> Message-ID: On May 22, 1:49?pm, Terry Reedy wrote: > Because, as I said, and as you explain further, Python favors programmer > speed, including speed of testing new algorithms, over raw execution > speed of current algorithms. (Current) speed is (also) easier to test > than improvability and hence possible speed improvements. First of all, I don't think you and Lie have any basic disagreements. The key realization is that the quantitative difference in programmer speed you mention is so large (orders of magnitude) that, for many classes of problems, it is not just *possible*, but actually *probable*, that a Python implementation *will be faster* than a C implementation. Yes, you are absolutely correct that most Python programs can be made faster by adding a bit of C, but that doesn't negate the fact that if I can throw 'x' man-hours at a problem, for lots of real-world values of 'x' and of 'the problem', a pure Python implementation will run rings around a pure C implementation, assuming the C implementation even works by the time I've burned through 'x' hours. I discussed this a bit on this newsgroup over five years ago, and the points are still pertinent: http://groups.google.com/group/comp.lang.python/msg/910a54ddec946567 > If and when mercurial deveopment slows down, some of its developers > might consider whether any of the utility functions written in Python > might usefully be rewritten in C. One of the intentional virtues of > Python is that one can transparently convert part or all of a module > *without changing* the import and use of the module. I don't even think that Mercurial development has to slow down to decide to recode a few things in C. A tiny bit of C at the right place can often provide more than enough leverage to be worthwhile, and be small enough to throw away if need be. Regards, Pat From pmaupin at gmail.com Sat May 22 15:40:36 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 22 May 2010 12:40:36 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> Message-ID: On May 21, 10:30?pm, Chris Rebert wrote: > Erm, in fairness, I recall hearing that some speed-critical bits of hg > are written in C. It does lend credence to the "Python as glue > language" argument though; I doubt hg's extensibility and friendly > interface would have been as easy to implement it C (particularly the > slick instant-server feature). Is C viewed as a "glue language" in those environments where it is the primary tool and sometimes some small bits are recoded into assembly language for speed? Regards, Pat From thudfoo at opensuse.us Sat May 22 15:57:43 2010 From: thudfoo at opensuse.us (member thudfoo) Date: Sat, 22 May 2010 12:57:43 -0700 Subject: bash-style auto completion in command line program. use rlcomplete? In-Reply-To: References: Message-ID: On Sat, May 22, 2010 at 11:01 AM, ntwrkd wrote: > I am trying to create a bash-style auto completion in a simple > command-line and script-based program i created using cmd. > I saw http://docs.python.org/library/rlcompleter.html, which I'm > thinking is the way to go for my program to intercept the tab key. > Would anyone have thoughts on this? > > I wish cmd or cmd2 had this functionality built-in. > It is built in. Check the cmd documentation for complete_* method of Cmd class. Following is an example of it use for a command called "open": def complete_open(self, text, line, begidx, endidx): asmfiles = glob('%s/*.asm' % ASMDIR) matches = [] for path in asmfiles: fname = os.path.basename(path) if fname.startswith(text): matches.append(fname) return matches From aahz at pythoncraft.com Sat May 22 16:34:44 2010 From: aahz at pythoncraft.com (Aahz) Date: 22 May 2010 13:34:44 -0700 Subject: Just To Be Sure...MySQL References: Message-ID: In article , Christian Heimes wrote: > >You *MUST NOT* use string formatting for SQL commands unless you >carefully quote and validate the strings. Otherwise your SQL application >is vulnerable to SQL injection attacks. SQL injections are one of the >most common and devastating attacks for web applications these days. > >Example: >"Select * from Users where uid = %s" % uid >uid = "1; DROP Table users;" > >Guess what happens here ... http://xkcd.com/327/ (Just in case there are newbies here.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From awilliam at whitemice.org Sat May 22 16:35:29 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Sat, 22 May 2010 16:35:29 -0400 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <1274560529.10069.7.camel@linux-yu4c.site> On Fri, 2010-05-21 at 11:20 -0700, Patrick Maupin wrote: > On May 21, 5:21 am, Deep_Feelings wrote: > > 2- python is high productivity language : why there are no commercial > > programs written in python ? > There are a lot of commercial programs written in Python. But any > company which thinks it has a lock on some kind of super secret sauce > isn't going to use Python, Is it [only] the aspect of being "sold" that makes software "commercial"? A better question would be is how many Python applications, in house or not, are used to facilitate commerce. Answer: a lot. I have an Open Source project with >100,000 lines of Python code [which I think qualifies as a 'real' application] . But that it is Open Source makes it non-commercial? I doubt anyone would use it outside of a commercial environment, and one of its principle goals is to serve as the backend for CRM systems [essentially commercial] and facilitate automation of business processes [essentially commercial]. The 'secret sauce' isn't the code [which is MIT licenses] but what you do with it. But since the framework is essentially general purpose - why not publish the code? I think of my Open Source code as "commercial". -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From steve at REMOVE-THIS-cybersource.com.au Sat May 22 19:14:56 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 May 2010 23:14:56 GMT Subject: Another "Go is Python-like" article. References: <7c1d7e0e-eb2b-411d-bc7c-7e12a247ee8b@e21g2000vbl.googlegroups.com> Message-ID: <4bf86570$0$27861$c3e8da3@news.astraweb.com> On Sat, 22 May 2010 12:13:30 -0700, Patrick Maupin wrote about the lack of exceptions in Go: > Looking at their rationale, it is appears that one or more of the > primary go developers had to deal way too often with people who overuse > and abuse exceptions, so they are reverting to an almost childish "I'll > fix their little red wagon! When they have to use *my* language, they > won't be able to do that anymore!" kind of mentality. Another > possibility is that they viewed the complexity of exceptions as > interfering with their primary goals, and felt it necessary to > rationalize their absence after the fact. That's two possible explanations. A third is that they genuinely believe that exceptions lead to poor programming practice and left them out, just as the designers of many other languages believe that goto leads to poor practice and leave it out as well. I don't think there's necessarily anything "childish" about choosing to leave out a language feature that you think is bad from a language you design. Indeed, when I design my killer language, the identifiers "foo" and "bar" will be reserved words, never used, and not even mentioned in the reference manual. Any program using one will simply dump core without comment. Multitudes will rejoice. -- Tim Peters, 29 Apr 1998 -- Steven From lan.rogers.book at gmail.com Sat May 22 20:16:40 2010 From: lan.rogers.book at gmail.com (Lanny) Date: Sat, 22 May 2010 17:16:40 -0700 (PDT) Subject: Help (I can't think of a better title) Message-ID: The answer may be right infront of me but I really can't figure this out. I'm trying to build a interactive fiction kind of game, silly I know but I am a fan of the genre. I'm trying to build up an index of all the rooms in the game from an outside file called roomlist.txt. The only problem is that every room ends up having four exits. Here's the code. class room() : room_id = 'room_id' name = 'room' description = 'description' item_list = exits = {} visits = 0 def leave(self, direction) global roomlist global player_current_room if direction not in player_current_room.exitskeys() : print 'There is no exit in that direction.' return 1 roomlist[self.room_id] = self player_current_room = roomlist[player_current_room.exits[direction]] print player_current_room.name if player_current_room.visits < 1 : print player_current_room.description if player_current_room.item_list != [] : stdout.write('You can see ') for item in player_current_room.item_list : stdout.write('a') if item.display_name[0] in ['a','e','i','o','u'] : stdout.write('n ' + item.display_name + ',') else : stdout.write(item.display_name + ',') pass print print 'Exits:', for way in player_current_room.exits : print way.capitalize(), print player_current_room.visits += 1 pass else : player_current_room.visits += 1 pass pass def build_rooms(room_file) : global roomlist rfile = open(room_file) tmp_builder = '' for line in rfile : tmp_builder = tmp_builder + line[:-1] pass for location in tmp_builder.rsplit('::') : if location.rsplit(';')[-1] == '' : location = location[:-1] if len(location.rsplit(';')) != 5 : if '-dev' or '-v' in argv : print location.rsplit(';')[0], 'had', len(location.rsplit(';')), 'values in it, 5 expected' for value in location.rsplit(';') : print; print value foobar.append(value) print 'A room failed to initalize due to either too much or not enough values being present in the build file' pass pass else : roomlist[location.rsplit(';')[0]] = room() roomlist[location.rsplit(';')[0]].room_id = location.rsplit(';')[0] roomlist[location.rsplit(';')[0]].name = location.rsplit(';')[1] roomlist[location.rsplit(';')[0]].description = location.rsplit(';')[2] if location.rsplit(';')[3] != 'none' : pass tmp_var = location.rsplit(';')[4] print location.rsplit(';')[0], roomlist[location.rsplit(';')[0]].exits, 'before' for way in tmp_var.rsplit(',') : roomlist[location.rsplit(';')[0]].exits[way.rsplit(':') [0]] = way.rsplit(':')[1] roomlist = {} build_rooms('room_list.txt') And here is the roomlist.txt file : start_room; Starting Room; This is the starting room, if you can read this text it means that at least one part of this beta is working.; none; north:second_room,west:aux_room; :: second_room; Second Room; Yo, Yo! This is the second room, if you can see this text a substantitally greater amount of the game is running than would have been if you didn't see this text.; apple; south:start_room; :: aux_room; Auxillary Room; No, there aren't any barbarian conscripts here, but there is a table!; none; east:start_room; Ideally roomlist['start_room'].exits would equal {'aux_room' : 'west', 'second_room' : 'north'} but it doesn't. Sorry if this is unclear or too long, but I'm really stumped why it is giving bad output From python at mrabarnett.plus.com Sat May 22 20:39:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 May 2010 01:39:25 +0100 Subject: Help (I can't think of a better title) In-Reply-To: References: Message-ID: <4BF8793D.5050605@mrabarnett.plus.com> Lanny wrote: > The answer may be right infront of me but I really can't figure this > out. > I'm trying to build a interactive fiction kind of game, silly I know > but I > am a fan of the genre. I'm trying to build up an index of all the > rooms in > the game from an outside file called roomlist.txt. The only problem is > that > every room ends up having four exits. Here's the code. > > > class room() : > room_id = 'room_id' > name = 'room' > description = 'description' > item_list = > exits = {} > visits = 0 These attributes are being defined as belonging to the class, so they will be shared by all the instances of the class. This isn't a problem for immutable items such as strings, but is for mutable items such as dicts. In short, all the rooms share the same 'exits' dict. You should really define the instance attributes (variables) in the '__init__' method. > def leave(self, direction) > global roomlist > global player_current_room > if direction not in player_current_room.exitskeys() : > print 'There is no exit in that direction.' > return 1 > roomlist[self.room_id] = self > player_current_room = > roomlist[player_current_room.exits[direction]] > print player_current_room.name > if player_current_room.visits < 1 : > print player_current_room.description > if player_current_room.item_list != [] : > stdout.write('You can see ') > for item in player_current_room.item_list : > stdout.write('a') > if item.display_name[0] in ['a','e','i','o','u'] : > stdout.write('n ' + item.display_name > + > ',') > else : > stdout.write(item.display_name + ',') > pass > > print > print 'Exits:', > for way in player_current_room.exits : > print way.capitalize(), > print > player_current_room.visits += 1 > pass > else : > player_current_room.visits += 1 > pass > pass > > def build_rooms(room_file) : > global roomlist > rfile = open(room_file) > tmp_builder = '' > for line in rfile : > tmp_builder = tmp_builder + line[:-1] > pass > for location in tmp_builder.rsplit('::') : > if location.rsplit(';')[-1] == '' : > location = location[:-1] > if len(location.rsplit(';')) != 5 : > if '-dev' or '-v' in argv : > print location.rsplit(';')[0], 'had', > len(location.rsplit(';')), 'values in it, 5 expected' > for value in location.rsplit(';') : > print; print value > foobar.append(value) > print 'A room failed to initalize due to either too > much or > not enough values being present in the build file' > pass > pass > else : > roomlist[location.rsplit(';')[0]] = room() > roomlist[location.rsplit(';')[0]].room_id = > location.rsplit(';')[0] > roomlist[location.rsplit(';')[0]].name = > location.rsplit(';')[1] > roomlist[location.rsplit(';')[0]].description = > location.rsplit(';')[2] > if location.rsplit(';')[3] != 'none' : > pass > tmp_var = location.rsplit(';')[4] > print location.rsplit(';')[0], > roomlist[location.rsplit(';')[0]].exits, 'before' > for way in tmp_var.rsplit(',') : > roomlist[location.rsplit(';')[0]].exits[way.rsplit(':') > [0]] > = way.rsplit(':')[1] > > roomlist = {} > build_rooms('room_list.txt') > > And here is the roomlist.txt file : > > start_room; > Starting Room; > This is the starting room, if you can read this text it means that at > least > one part of this beta is working.; > none; > north:second_room,west:aux_room; > :: > second_room; > Second Room; > Yo, Yo! This is the second room, if you can see this text a > substantitally > greater amount of the game is running than would have been if you > didn't see > this text.; > apple; > south:start_room; > :: > aux_room; > Auxillary Room; > No, there aren't any barbarian conscripts here, but there is a table!; > none; > east:start_room; > > Ideally roomlist['start_room'].exits would equal {'aux_room' : > 'west', > 'second_room' : 'north'} but it doesn't. Sorry if this is unclear or > too > long, but I'm really stumped why it is giving bad output From mehgcap at gmail.com Sat May 22 20:53:30 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 22 May 2010 20:53:30 -0400 Subject: Help (I can't think of a better title) In-Reply-To: <4BF8793D.5050605@mrabarnett.plus.com> References: <4BF8793D.5050605@mrabarnett.plus.com> Message-ID: On 5/22/10, MRAB wrote: > Lanny wrote: >> The answer may be right infront of me but I really can't figure this >> out. >> I'm trying to build a interactive fiction kind of game, silly I know >> but I >> am a fan of the genre. I'm trying to build up an index of all the >> rooms in >> the game from an outside file called roomlist.txt. The only problem is >> that >> every room ends up having four exits. Here's the code. >> >> >> class room() : >> room_id = 'room_id' >> name = 'room' >> description = 'description' >> item_list = >> exits = {} > > visits = 0 > > These attributes are being defined as belonging to the class, so they > will be shared by all the instances of the class. This isn't a problem > for immutable items such as strings, but is for mutable items such as > dicts. In short, all the rooms share the same 'exits' dict. > > You should really define the instance attributes (variables) in the > '__init__' method. I just ran into something similar to this in my Battleship game. I had a Craft class, which defined attributes for any craft (a recon plane, a submarine, a battleship, and so on). One such attribute was a weapons list, much like your exits dictionary; I would assign a couple weapons to a battleship, but suddenly all my ships and airplanes had those same weapons. What the great people on this list said to do was something like this: class Room(): def __init__(self, exits): if exits==None: self.exits={} else: self.exits=exits In this way, you can create a new Room object with exits, r=Room(exits_dict) or you can create a Room with no exits, and add them later: r2=Room() r2.exits["exit1"]="doorway" but the code in the __init__ method, which will get called as soon as you create a new Room object, ensures that passing an exits dictionary will set that instance's exits to what was passed in, while passing nothing will create a room with an empty dictionary (the if statement). I hope this made some sense! > >> def leave(self, direction) >> global roomlist >> global player_current_room >> if direction not in player_current_room.exitskeys() : >> print 'There is no exit in that direction.' >> return 1 >> roomlist[self.room_id] = self >> player_current_room = >> roomlist[player_current_room.exits[direction]] >> print player_current_room.name >> if player_current_room.visits < 1 : >> print player_current_room.description >> if player_current_room.item_list != [] : >> stdout.write('You can see ') >> for item in player_current_room.item_list : >> stdout.write('a') >> if item.display_name[0] in ['a','e','i','o','u'] : >> stdout.write('n ' + item.display_name >> + >> ',') >> else : >> stdout.write(item.display_name + ',') >> pass >> >> print >> print 'Exits:', >> for way in player_current_room.exits : >> print way.capitalize(), >> print >> player_current_room.visits += 1 >> pass >> else : >> player_current_room.visits += 1 >> pass >> pass >> >> def build_rooms(room_file) : >> global roomlist >> rfile = open(room_file) >> tmp_builder = '' >> for line in rfile : >> tmp_builder = tmp_builder + line[:-1] >> pass >> for location in tmp_builder.rsplit('::') : >> if location.rsplit(';')[-1] == '' : >> location = location[:-1] >> if len(location.rsplit(';')) != 5 : >> if '-dev' or '-v' in argv : >> print location.rsplit(';')[0], 'had', >> len(location.rsplit(';')), 'values in it, 5 expected' >> for value in location.rsplit(';') : >> print; print value >> foobar.append(value) >> print 'A room failed to initalize due to either too >> much or >> not enough values being present in the build file' >> pass >> pass >> else : >> roomlist[location.rsplit(';')[0]] = room() >> roomlist[location.rsplit(';')[0]].room_id = >> location.rsplit(';')[0] >> roomlist[location.rsplit(';')[0]].name = >> location.rsplit(';')[1] >> roomlist[location.rsplit(';')[0]].description = >> location.rsplit(';')[2] >> if location.rsplit(';')[3] != 'none' : >> pass >> tmp_var = location.rsplit(';')[4] >> print location.rsplit(';')[0], >> roomlist[location.rsplit(';')[0]].exits, 'before' >> for way in tmp_var.rsplit(',') : >> roomlist[location.rsplit(';')[0]].exits[way.rsplit(':') >> [0]] >> = way.rsplit(':')[1] >> >> roomlist = {} >> build_rooms('room_list.txt') >> >> And here is the roomlist.txt file : >> >> start_room; >> Starting Room; >> This is the starting room, if you can read this text it means that at >> least >> one part of this beta is working.; >> none; >> north:second_room,west:aux_room; >> :: >> second_room; >> Second Room; >> Yo, Yo! This is the second room, if you can see this text a >> substantitally >> greater amount of the game is running than would have been if you >> didn't see >> this text.; >> apple; >> south:start_room; >> :: >> aux_room; >> Auxillary Room; >> No, there aren't any barbarian conscripts here, but there is a table!; >> none; >> east:start_room; >> >> Ideally roomlist['start_room'].exits would equal {'aux_room' : >> 'west', >> 'second_room' : 'north'} but it doesn't. Sorry if this is unclear or >> too >> long, but I'm really stumped why it is giving bad output > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From pmaupin at gmail.com Sat May 22 20:58:42 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 22 May 2010 17:58:42 -0700 (PDT) Subject: Another "Go is Python-like" article. References: <7c1d7e0e-eb2b-411d-bc7c-7e12a247ee8b@e21g2000vbl.googlegroups.com> <4bf86570$0$27861$c3e8da3@news.astraweb.com> Message-ID: <82a5452f-a129-477b-8a2f-26ffa65aa190@w3g2000vbd.googlegroups.com> On May 22, 6:14?pm, Steven D'Aprano wrote: > On Sat, 22 May 2010 12:13:30 -0700, Patrick Maupin wrote about the lack > of exceptions in Go: > > > Looking at their rationale, it is appears that one or more of the > > primary go developers had to deal way too often with people who overuse > > and abuse exceptions, so they are reverting to an almost childish "I'll > > fix their little red wagon! ?When they have to use *my* language, they > > won't be able to do that anymore!" kind of mentality. Another > > possibility is that they viewed the complexity of exceptions as > > interfering with their primary goals, and felt it necessary to > > rationalize their absence after the fact. > > That's two possible explanations. A third is that they genuinely believe > that exceptions lead to poor programming practice and left them out, just > as the designers of many other languages believe that goto leads to poor > practice and leave it out as well. > > I don't think there's necessarily anything "childish" about choosing to > leave out a language feature that you think is bad from a language you > design. While I admit that "childish" is an inflammatory simplification, other than that, I think that your possible explanation is, essentially, identical to my first possibility -- why would you think exceptions were bad if you didn't have first-hand evidence of that? Regards, Pat From greg.ewing at canterbury.ac.nz Sat May 22 21:49:06 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 23 May 2010 13:49:06 +1200 Subject: where are the program that are written in python? In-Reply-To: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <85rfa9Fv65U1@mid.individual.net> Deep_Feelings wrote: > i will be interested more in COMMERCIAL programs written in python I came across a game on Big Fish Games recently (it was "The Moonstone" IIRC) that appeared to have been built using Python and py2app. -- Greg From greg.ewing at canterbury.ac.nz Sat May 22 22:21:12 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 23 May 2010 14:21:12 +1200 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> <4bf3eeeb$0$31263$607ed4bc@cv.net> <3c40f8d8-b29c-484f-b5b3-6dff0f68a032@m21g2000vbr.googlegroups.com> <16c9daac-293a-4cb6-b847-489e696682bd@c11g2000vbe.googlegroups.com> Message-ID: <85rh6gF8ceU1@mid.individual.net> >>On Thu, 20 May 2010 02:45:10 -0700 (PDT), Jimoid >> declaimed the following in >>gmane.comp.python.general: >> >>>I've now had a closer look at both pyODBC and mxODBC and it seems to >>>me that they both require the database to be running to be able to >>>query it. Is this correct? If you mean that an instance of MS Access has to be running, no, I don't think so. The ODBC driver for Access databases knows how to open .mdb files itself. I've done this myself recently, and it seems to work fine without having Access running anywhere. -- Greg From sturla at molden.no Sun May 23 01:18:50 2010 From: sturla at molden.no (sturlamolden) Date: Sat, 22 May 2010 22:18:50 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <9584607c-1aea-42b1-9671-19a2b51a5e17@l6g2000vbo.googlegroups.com> Message-ID: On 22 Mai, 20:45, Patrick Maupin wrote: > I think we're in violent agreement here -- you neglected to quote the > part where I said "(But the up-front choice of another language simply > for speed, rather than prototyping with Python and then recoding the > slow bits, would probably be a decision borne of ignorance.)" I'm not arguing against you. You're argument is almost that which Donald Knuth attributes to C.A.R. Hoare: "Premature optimization is the root of all evil in computer programming." It's very true though. From sturla at molden.no Sun May 23 01:35:42 2010 From: sturla at molden.no (sturlamolden) Date: Sat, 22 May 2010 22:35:42 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <471f9246-26e9-4e70-b0f6-288f373c9c2c@p17g2000vbe.googlegroups.com> On 22 Mai, 13:28, Tim Chase wrote: > Just as an aside, last I checked, mercurial had some core code in > C for speed. ? I've been writing scrintific software for over 10 years. I always find myself writing small pieces of C now and then. It is usally because header files are too complicated to expose to Python. I will e.g. make OpenGL calls from C, and then call the rendering routine from Python with ctypes. It saves me the work of exposing OpenGL (or whatever) to Python. There are already header files that make the API available to C. Yes I know about PyOpenGL, but then there is the speed argument: From C I can make epeated calls to functions like glVertex4f with minial loss of efficacy. Calling glVertex4f from Python (e.g. PyOpenGL) would give me the Python (and possibly ctypes) overhead for each call, which is considerable. So there is the two arguments for using C now and then: (1) Save programming time by not having to repeat header files and (2) make programs run faster by avoiding the Python overhead. Some times it matters, some times it don't. But it does not make sense to write C or C++ all the time, nor does it help to use C or C++ for I/O bound problems. From contact at xavierho.com Sun May 23 01:49:05 2010 From: contact at xavierho.com (Xavier Ho) Date: Sun, 23 May 2010 15:49:05 +1000 Subject: where are the program that are written in python? In-Reply-To: <471f9246-26e9-4e70-b0f6-288f373c9c2c@p17g2000vbe.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <471f9246-26e9-4e70-b0f6-288f373c9c2c@p17g2000vbe.googlegroups.com> Message-ID: On Sun, May 23, 2010 at 3:35 PM, sturlamolden wrote: > Yes I know about PyOpenGL, but then there is the speed argument: From > C I can make epeated calls to functions like glVertex4f with minial > loss of efficacy. Calling glVertex4f from Python (e.g. PyOpenGL) would > give me the Python (and possibly ctypes) overhead for each call, which > is considerable. > Not to counter your arguement, but I would just like to point out that calling glVertex*() repeatedly is always not as efficient as using a VBO or a display list. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From bieffe62 at gmail.com Sun May 23 03:50:43 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sun, 23 May 2010 00:50:43 -0700 (PDT) Subject: First Tkinter script: requesting comments References: <87d3wokjnr.fsf@kasterma.Colorado.EDU> Message-ID: <02f43218-98b9-4d75-bb5f-bad847d8bf3c@40g2000vbr.googlegroups.com> On 21 Mag, 23:51, Bart Kastermans wrote: > I wrote a first script using Tkinter. ?As I am new to its > use, I am only just feeling my way around. ?I would very > much like comments on the design of the script (and in fact > any other comments on my code would also be very welcome). > > I have it posted (with syntax coloring) at: > > http://kasterma.wordpress.com/2010/05/21/first-experiments-with-tkinter/ > > But will also include it here for convenience. > > Thanks for any help, > > Best, > Bart > > *********************** > > #!/usr/bin/env python > # > # Getting a list of students and grades displayed so that grades can > # be updated, and we poll these changes (so that in the future we can > # act on it). > # > # Bart Kastermans,www.bartk.nl > > """ > Design of the window > > ? ? ? +-------------------------------------------------------------+ > ? ? ? | ?root ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | > ? ? ? | ?+------------------------------------------------------+ ? | > ? ? ? | ?| title_frame ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?| ?+------------------------------+ ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?| ?| Label(title) ? ? ? ? ? ? ? ? | ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?| ?| ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?| ?+------------------------------+ ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?+------------------------------------------------------+ ? | > ? ? ? | ?+------------------------------------------------------+ ? | > ? ? ? | ?| exam_grades_frames ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | ? | > ? ? ? | ?| ?+-------------------------------------------------+ | ? | > ? ? ? | ?| ?| Frame(ex) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | | ? | > ? ? ? | ?| ?| +--------------------+ ?+---------------------+ | | ? | > ? ? ? | ?| ?| | Entry(name) ? ? ? ?| ?| Entry(grade) ? ? ? ?| | | ? | > ? ? ? | ?| ?| | ? ? ? ? ? ? ? ? ? ?| ?| ? ? ? ? ? ? ? ? ? ? | | | ? | > ? ? ? | ?| ?| +--------------------+ ?+---------------------+ | | ? | > ? ? ? | ?| ?+-------------------------------------------------+ | ? | > ? ? ? | ?| ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?+------------------------------------------------------+ ? | > ? ? ? | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | > ? ? ? | ? ? ? ? ? ? ? ? +---------------------+ ? ? ? ? ? ? ? ? ? ? | > ? ? ? | ? ? ? ? ? ? ? ? | quit_button ? ? ? ? | ? ? ? ? ? ? ? ? ? ? | > ? ? ? | ? ? ? ? ? ? ? ? | ? ? ? ? ? ? ? ? ? ? | ? ? ? ? ? ? ? ? ? ? | > ? ? ? | ? ? ? ? ? ? ? ? +---------------------+ ? ? ? ? ? ? ? ? ? ? | > ? ? ? +-------------------------------------------------------------+ > > """ > > from Tkinter import * > > # global info for this specific example > > # four students > no_stud = 4 > exam_grades = [1,2,3,4] > names = ["Ben", "Jim", "James", "Mel"] > # upper bound for name length > max_name_len = max (map (len, names)) > > # set up root window > root = Tk() > root.geometry ("400x400") > > exam_grades_string = map (lambda x: StringVar (root,str (x)), exam_grades) > > names_string = map (lambda x: StringVar (root, x), names) > > def setup (): > ? ? """ setup the window with the list of students. > > ? ? This is test-code to figure out what the app finally should look > ? ? like. > ? ? """ > > ? ? # title frame, with title Grade Correction in it > ? ? title_frame = Frame(root) > ? ? title_frame.pack (fill=X) > > ? ? w = Label (title_frame, text = "Grade Correction", font = ("Helvetica", 25)) > ? ? w.pack (side=LEFT) > > ? ? # from to hold the list of grades > ? ? exam_grades_frame = Frame (root) > ? ? exam_grades_frame.pack (fill=BOTH) > > ? ? exam_label = Label (exam_grades_frame, text="EXAMS") > ? ? exam_label.pack () > > ? ? # set up the list of grades > ? ? for i in range (0,no_stud): > ? ? ? ? # a frame per student > ? ? ? ? ex = Frame (exam_grades_frame) > ? ? ? ? ex.pack () > ? ? ? ? # name on the left > ? ? ? ? name = Entry (ex, textvariable=names_string[i], width=max_name_len+2) > ? ? ? ? name.config (state=DISABLED) > ? ? ? ? name.pack (side=LEFT) > ? ? ? ? # grade next to it > ? ? ? ? grade = Entry (ex, textvariable=exam_grades_string [i], width=4) > ? ? ? ? grade.pack (side=LEFT) > > ? ? # button to quit the application > ? ? qb = Button (root) > ? ? qb ['text'] = "quit" > ? ? qb ['command'] = root.quit > ? ? qb.pack () > > def to_int (st): > ? ? """ helper function to convert strings to integers. > > ? ? Empty string represents 0. > ? ? """ > ? ? if len (st) == 0: > ? ? ? ? return 0 > ? ? else: > ? ? ? ? return int (st) > > def get_curr_grades (): > ? ? """ extract the grades from exam_grades_string. > > ? ? exam_grades_string consists of StringVar that get updated when the > ? ? fields are updated in the GUI. > ? ? """ > ? ? grades = [] > ? ? for i in range (0, no_stud): > ? ? ? ? grades.append (exam_grades_string [i].get()) > ? ? return grades > > # get the current grades > curr_grades = map (to_int, get_curr_grades ()) > > def poll_exams (): > ? ? """ function that keeps polling the current grades, looking for changes""" > ? ? global curr_grades > ? ? new_grades = map (to_int, get_curr_grades ()) > ? ? if new_grades != curr_grades: > ? ? ? ? print new_grades > ? ? ? ? curr_grades = new_grades > ? ? root.after( 250, poll_exams) > > # window setup > setup () > > # start the polling > poll_exams () > > # start the eventloop > root.mainloop () > > # do cleanup > root.destroy () > sys.exit () It looks fine to me, except that I would do it a bit more OOP-style (can't stand the globals very much). Also, I would use labels instead of disabled text fields for student names, since they don't need to be edited. Add maybe tray to align the name and grade widgets in a 2x4 matrix using .grid() instead of .pack() ( see http://effbot.org/tkinterbook/grid.htm ) One thing I don't understand, is why you need to 'poll' continuously for changes, except for demo purpose. If this is supposed to be a window for user to enter data into the program, the standard practice is to have a separate window (not the main one), with apply and cancel buttons, where both buttons close the window but only the apply button register the change. So you need to do the stuff you do in the poll_exams function only in the callback of the apply button. On the python side, you don't need no_stud variable since you can do len(names_string). And maybe have single list of (name, grade) pairs, so youl loop would become something like: for i, (name, grade) in enumerate( names_and_grades_list ) : # use name instead of names_string[i] # use grade instead of exam_grades_string[i] Although this could slightly complicate the upgrade of grades. The usage of a small class StudentData could be in order, too. Ciao ------- FB From lie.1296 at gmail.com Sun May 23 04:19:57 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 23 May 2010 18:19:57 +1000 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> Message-ID: <4bf8e592$1@dnews.tpgi.com.au> On 05/23/10 04:49, Terry Reedy wrote: > On 5/21/2010 11:03 PM, Lie Ryan wrote: >> On 05/22/10 04:47, Terry Reedy wrote: >>> On 5/21/2010 6:21 AM, Deep_Feelings wrote: >>>> python is not a new programming language ,it has been there for the >>>> last .... 15+ years or so ? right ? >>>> >>>> however by having a look at this page >>>> http://wiki.python.org/moin/Applications >>>> i could not see many programs written in python (i will be interested >>>> more in COMMERCIAL programs written in python ). and to be honest ,i >>> >>> There are two kinds of 'commercial' programs. >>> 1. The vast majority are proprietary programs kept within a company for >>> its own use. As long as these work as intended, they are mostly >>> invisible to the outside world. >>> 2. Programs sold to anyone who wants them. >>> >>> Python trades programmer speed for execution speed. If a successful >>> Python program is going to be run millions of times, it makes economic >>> sense to convert time-hogging parts to (for instance) C. In fact, this >>> is a consideration in deciding what functions should be builtin and >>> which stdlib modules are written or rewritten in C. >>> >>> Programs being sold tend to be compared to competitors on speed with >>> perhaps more weight than they rationally should. Speed is easier to >>> measure than, for instance, lack of bugs. >> >> doubting python's speed? > > The is a somewhat bizarre response to me. I have been promoting Python > for about 13 years, since I dubbed it 'executable pseudocode', which is > to say, easy to write, read, understand, and improve. I am also a > realist. Any fixed (C)Python program can be sped up, at least a bit, and > possibly more, by recoding in C. At minimum, the bytecodes can be > replaced by the C code and C-API calls that they get normally get > translated into. Ints can be unboxed. Etcetera. This tend to freeze a > program, which is fine when development is finished. I'm not claiming Python is faster than C, but I'm just being a realists, when I say that in real life 9 out of 10 writing a program in a slow language doesn't really matter to actual program speed. I used Mercurial as an example where the developers choose an initially irrational decision of using a slow language (python) to beat the speed of a fast language (C). Of course, you can always point out the 1 case out of 10. In this cases, python can still cope with C extension, Psyco, Numpy-and-friends, Cython, or even dumping python and using full C all the way. But the point still hold, that in real life, often the language's raw speed doesn't really limit the program's speed. From nobody at nowhere.com Sun May 23 04:39:27 2010 From: nobody at nowhere.com (Nobody) Date: Sun, 23 May 2010 09:39:27 +0100 Subject: Help (I can't think of a better title) References: Message-ID: On Sat, 22 May 2010 17:16:40 -0700, Lanny wrote: > Ideally roomlist['start_room'].exits would equal {'aux_room' : 'west', > 'second_room' : 'north'} but it doesn't. Sorry if this is unclear or too > long, but I'm really stumped why it is giving bad output Just to condense a point which the other responses don't (IMHO) make particularly clear: Unlike most other OO languages, Python doesn't make instance members appear as variables within methods; you have to explicitly access them as members of "self", i.e. "self.exits" for the "exits" member of the current instance ("self"). From cournape at gmail.com Sun May 23 04:47:50 2010 From: cournape at gmail.com (David Cournapeau) Date: Sun, 23 May 2010 17:47:50 +0900 Subject: where are the program that are written in python? In-Reply-To: <4bf8e592$1@dnews.tpgi.com.au> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> <4bf8e592$1@dnews.tpgi.com.au> Message-ID: On Sun, May 23, 2010 at 5:19 PM, Lie Ryan wrote: > But the point still hold, that in real life, often the language's raw > speed doesn't really limit the program's speed. I would rather say that Python vs C does not matter until it does, and it generally does when constants factor matter (which is one way to draw the line between system programming and "general" programming). It totally depends on the applications, I don't think you can draw general arguments. David From __peter__ at web.de Sun May 23 05:18:03 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 May 2010 11:18:03 +0200 Subject: First Tkinter script: requesting comments References: <87d3wokjnr.fsf@kasterma.Colorado.EDU> <02f43218-98b9-4d75-bb5f-bad847d8bf3c@40g2000vbr.googlegroups.com> Message-ID: Francesco Bochicchio wrote: > One thing I don't understand, is why you need to 'poll' continuously > for changes, except for demo purpose. You can give the user immediate feedback on changes he makes. I'd argue that e. g. an "auto-apply" dialog with a revert button is much more usable and am surprised that this style hasn't caught on. > If this is supposed to be a window for user to enter data into the > program, the standard practice is to have a > separate window (not the main one), with apply and cancel buttons, > where both buttons close the window but only > the apply button register the change. So you need to do the stuff you > do in the poll_exams function only in the > callback of the apply button. If you want live updates you can also use StringVar.trace() instead of polling: from functools import partial def grade_changed(name, index, var, *args): new_grade = to_int(var.get()) if new_grade != exam_grades[index]: exam_grades[index] = new_grade print name, "-->", new_grade pairs = zip(names, exam_grades_string) for index, (name, var) in enumerate(pairs): var.trace("w", partial(grade_changed, name, index, var)) See also http://effbot.org/tkinterbook/variable.htm Peter From hpsmouse at gmail.com Sun May 23 05:19:40 2010 From: hpsmouse at gmail.com (hpsMouse) Date: Sun, 23 May 2010 02:19:40 -0700 (PDT) Subject: Urllib2: Only a partial page retrieved References: <77019685-3bf4-4d0c-9fd7-13ed8e84e102@y12g2000vbg.googlegroups.com> Message-ID: On 5?22?, ??5?43?, Dragon Lord wrote: > The cutoff is allways at the same location: just after the label > "Meeting date" and before the date itself. Could it be that something > is interpreted as and eof command or something like that? > > example of the cutoff point with a bad page: >
Meeting Date: > > example of the cutoff point with a good page: >
Meeting Date: I checked TCP packages, and found that the remote HTTP server send a data package with flag "PUSH", causing the client to close connection. That is exactly where the "Meeting Date: " appears. This seems not to be a bug for python, because Qt and telnet both failed in my test, so did the wget program... Most browsers use keep-alive HTTP, so the connection won't be closed. I think that's why a browser show the page correctly. From hpsmouse at gmail.com Sun May 23 05:42:04 2010 From: hpsmouse at gmail.com (hpsMouse) Date: Sun, 23 May 2010 02:42:04 -0700 (PDT) Subject: Urllib2: Only a partial page retrieved References: <77019685-3bf4-4d0c-9fd7-13ed8e84e102@y12g2000vbg.googlegroups.com> Message-ID: I know what the problem is. Server checks client's locale setting to determine how the date should be displayed. Python don't send locale information by default. So server fails at that point. If you add the following field in the HTTP request, the response will be correct: Accept-Language: en From sturla at molden.no Sun May 23 06:22:22 2010 From: sturla at molden.no (sturlamolden) Date: Sun, 23 May 2010 03:22:22 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> <4bf8e592$1@dnews.tpgi.com.au> Message-ID: On 23 Mai, 10:47, David Cournapeau wrote: > I would rather say that Python vs C does not matter until it does, I disagree. C matters because it is portable assembly code. Which means it is tedious and error prone to use, so avoiding it actually matters. Hence C matters. Knowing when and when not to use C matters a lot. From dragonlordnld at gmail.com Sun May 23 07:34:53 2010 From: dragonlordnld at gmail.com (Dragon Lord) Date: Sun, 23 May 2010 04:34:53 -0700 (PDT) Subject: Urllib2: Only a partial page retrieved References: <77019685-3bf4-4d0c-9fd7-13ed8e84e102@y12g2000vbg.googlegroups.com> Message-ID: <1eb593bc-ce04-479e-b012-53c5b55ba181@b21g2000vbh.googlegroups.com> Thanks, that works perfectly! (oh and I learnt something new too, because I tried using telnet to connect to the server :) ) On May 23, 11:42?am, hpsMouse wrote: > I know what the problem is. > > Server checks client's locale setting to determine how the date should > be displayed. Python don't send locale information by default. So > server fails at that point. > > If you add the following field in the HTTP request, the response will > be correct: > Accept-Language: en From dg1sbg at googlemail.com Sun May 23 09:46:48 2010 From: dg1sbg at googlemail.com (Frank GOENNINGER) Date: Sun, 23 May 2010 15:46:48 +0200 Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' Message-ID: Hi all: Being completely new to Python still (just about a week into it now) I tried to follow the Python 2.6.5 version documemtation aiming at setting up a logger as follows: import logging global gPIBLogger class PIBLogger(object): ''' TODO: classdocs ''' def __init__(self, logFileName): ''' Constructor ''' self.logFileName = logFileName self.logger = logging.getLogger('PIBLogger') self.logger.setLevel(logging.DEBUG) handler = logging.handlers.RotatingFileHandler(self.logFileName, maxBytes=1000000, backupCount=9) self.logger.addHandler(handler) gPIBLogger = self.logger def main(): mylogger = PIBLogger('/tmp/pib.log') gPIBLogger.debug(' Hi ') if __name__ == "__main__": main() When trying to execute main() I get: Traceback (most recent call last): File "/.../src/pib/logging.py", line 37, in main() File "/.../src/pib/logging.py", line 33, in main mylogger = PIBLogger('/tmp/pib.log') File "/...src/pib/logging.py", line 23, in __init__ self.logger = logging.getLogger('PIBLogger') AttributeError: 'module' object has no attribute 'getLogger' I double checked and yes, getLogger is there. Why is the interpreter asking for an "attribute" here ? Any hints on what I am doing wrong ? TIA! Regards Frank From simon at brunningonline.net Sun May 23 10:04:01 2010 From: simon at brunningonline.net (Simon Brunning) Date: Sun, 23 May 2010 15:04:01 +0100 Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' In-Reply-To: References: Message-ID: On 23 May 2010 14:46, Frank GOENNINGER wrote: > Traceback (most recent call last): > ?File "/.../src/pib/logging.py", line 37, in > ? ?main() Here's a clue - looks like your own module is called logging. That's what's getting imported by your import. Try naming your module something else, and you should be golden. -- Cheers, Simon B. From duncan.booth at invalid.invalid Sun May 23 10:06:22 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 May 2010 14:06:22 GMT Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' References: Message-ID: Frank GOENNINGER wrote: > > When trying to execute main() I get: > > Traceback (most recent call last): > File "/.../src/pib/logging.py", line 37, in > main() > File "/.../src/pib/logging.py", line 33, in main > mylogger = PIBLogger('/tmp/pib.log') > File "/...src/pib/logging.py", line 23, in __init__ > self.logger = logging.getLogger('PIBLogger') > AttributeError: 'module' object has no attribute 'getLogger' > > I double checked and yes, getLogger is there. Why is the interpreter > asking for an "attribute" here ? Any hints on what I am doing wrong ? > You're source file appears to be called logging.py, so when you do 'import logging' it just imports itself. The system logging.py has a getLogger function, but *your* logging.py doesn't. From philip at semanchuk.com Sun May 23 10:07:12 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 23 May 2010 10:07:12 -0400 Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' In-Reply-To: References: Message-ID: <565789B5-AB23-41C1-82CD-3434AFE3E39E@semanchuk.com> On May 23, 2010, at 9:46 AM, Frank GOENNINGER wrote: > > Hi all: > > Being completely new to Python still (just about a week into it now) I > tried to follow the Python 2.6.5 version documemtation aiming at > setting > up a logger as follows: > > > > import logging > > global gPIBLogger > > class PIBLogger(object): > ''' > TODO: classdocs > ''' > > def __init__(self, logFileName): > ''' > Constructor > ''' > self.logFileName = logFileName > self.logger = logging.getLogger('PIBLogger') > self.logger.setLevel(logging.DEBUG) > handler = > logging.handlers.RotatingFileHandler(self.logFileName, > > maxBytes=1000000, > backupCount=9) > self.logger.addHandler(handler) > gPIBLogger = self.logger > > > def main(): > mylogger = PIBLogger('/tmp/pib.log') > gPIBLogger.debug(' Hi ') > > if __name__ == "__main__": > main() > > > > When trying to execute main() I get: > > Traceback (most recent call last): > File "/.../src/pib/logging.py", line 37, in > main() > File "/.../src/pib/logging.py", line 33, in main > mylogger = PIBLogger('/tmp/pib.log') > File "/...src/pib/logging.py", line 23, in __init__ > self.logger = logging.getLogger('PIBLogger') > AttributeError: 'module' object has no attribute 'getLogger' > > I double checked and yes, getLogger is there. Why is the interpreter > asking for an "attribute" here ? Any hints on what I am doing wrong ? Short answer: Change the name of src/pib/logging.py to something else. Long answer: When Python hits the line "import logging", it first looks in the current directory and imports logging.py, which in this case is the file it's already executing. It never finds the standard library's logging module. One way you could have figured this out would be to add this as the first line of main(): print dir(logging) That would have told you what Python thought the logging module looked like, and would have perhaps recognized it as your own. Cheers Philip From filipe.bvr at gmail.com Sun May 23 11:13:54 2010 From: filipe.bvr at gmail.com (Filipe) Date: Sun, 23 May 2010 08:13:54 -0700 (PDT) Subject: |help| python 3.12 Message-ID: I'm with a problem I'm doing a program in python, it sends the following error message: File "C:/Documents and Settings/Filipe Vinicius/Desktop/Filipe/Cefet/ LP/Python/trab.sistema.academico/sistemaacademico.2010.5.23.c.py", line 40, in administrador lp = pickle.load(f) File "D:\Arquivos De Programa\Python31\lib\pickle.py", line 1365, in load encoding=encoding, errors=errors).load() EOFError What you need to do to repair this error? in my program at the part where the error is find is that: def administrador(): f = open('professores.dat', 'rb') lp = pickle.load(f) f.close() ... Note: i had already imported the pikcle library THX From buzzard at urubu.freeserve.co.uk Sun May 23 11:57:54 2010 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Sun, 23 May 2010 16:57:54 +0100 Subject: Help (I can't think of a better title) In-Reply-To: References: <4BF8793D.5050605@mrabarnett.plus.com> Message-ID: Alex Hall wrote: > On 5/22/10, MRAB wrote: >> Lanny wrote: >>> The answer may be right infront of me but I really can't figure this >>> out. >>> I'm trying to build a interactive fiction kind of game, silly I know >>> but I >>> am a fan of the genre. I'm trying to build up an index of all the >>> rooms in >>> the game from an outside file called roomlist.txt. The only problem is >>> that >>> every room ends up having four exits. Here's the code. >>> >>> >>> class room() : >>> room_id = 'room_id' >>> name = 'room' >>> description = 'description' >>> item_list = >>> exits = {} >> > visits = 0 >> >> These attributes are being defined as belonging to the class, so they >> will be shared by all the instances of the class. This isn't a problem >> for immutable items such as strings, but is for mutable items such as >> dicts. In short, all the rooms share the same 'exits' dict. >> >> You should really define the instance attributes (variables) in the >> '__init__' method. > > I just ran into something similar to this in my Battleship game. I had > a Craft class, which defined attributes for any craft (a recon plane, > a submarine, a battleship, and so on). One such attribute was a > weapons list, much like your exits dictionary; I would assign a couple > weapons to a battleship, but suddenly all my ships and airplanes had > those same weapons. What the great people on this list said to do was > something like this: > > class Room(): > def __init__(self, exits): > if exits==None: > self.exits={} > else: > self.exits=exits > > In this way, you can create a new Room object with exits, > r=Room(exits_dict) > or you can create a Room with no exits, and add them later: > r2=Room() > r2.exits["exit1"]="doorway" > > but the code in the __init__ method, which will get called as soon as > you create a new Room object, ensures that passing an exits dictionary > will set that instance's exits to what was passed in, while passing > nothing will create a room with an empty dictionary (the if > statement). I hope this made some sense! [snip] It does when when you want 'exits' to take a default value which is a mutable type (and you don't want it shared by all instances). class Room: def __init__(self, exits=None): if exits is None: self.exits = {} else: self.exits = exits Otherwise, you're fine without the if ... else. Duncan From albert at spenarnc.xs4all.nl Sun May 23 12:07:44 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 23 May 2010 16:07:44 GMT Subject: Ugly modification of a class, can it be done better ? References: <4BF5D02A.9070600@gmail.com> <4bf5e19e$0$27861$c3e8da3@news.astraweb.com> Message-ID: In article <4bf5e19e$0$27861$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >Sorry for breaking threading, but Stef's original post has not come >through to me. > >> On Thu, May 20, 2010 at 8:13 PM, Stef Mientki >> wrote: > >>> So I want to change the behavior of the class dynamically. I've done it >>> by adding a global variable (Base_Grid_Double_Click) in the module, >>> initial set to None, >>> but can be changed by the main program to some callback function. (see >>> the code below) > >How is this supposed to work? If you have *one* global, then *every* >instance will see the same setting. To change it dynamically, you enter a >nightmare world of having to save the global, modify it, then restore it, >every single time. Trust me, I've been there, this is the *worst* way of >programming. This is why object oriented inheritance was invented, to >escape this nonsense! > >The first thing is to make the callback specific to the class, not >global. Why does your printing code need access to the callback that >handles double-clicking on a grid? It doesn't! So don't give it that >access (at least, not easy access). Put the callback in the class. > >class MyClass: > callback = None > def method(self, *args): > if self.callback is None: > behaviour_with_no_callback() > else: > behaviour_with_callback() > > >Now if you want to apply a callback to some instances, and not others, it >is totally simple: > > >red = MyClass() >blue = MyClass() >red.callback = my_callback_function > >and you're done. Don't go overboard in complication. Python can handle variable functions just fine, if that is the proper solution to your problem. (In c they are called function pointers and they are unruly.) def a(b,c): return b+c def p(q,r): return q*r x=a x(3,5) 8 x=p x(3,5) 15 >-- >Steven Sorry, but couldn't respond to the original message. My newsserver doesn't have it anymore. Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From gherron at islandtraining.com Sun May 23 12:38:28 2010 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 23 May 2010 09:38:28 -0700 Subject: |help| python 3.12 In-Reply-To: References: Message-ID: <4BF95A04.5040500@islandtraining.com> On 05/23/2010 08:13 AM, Filipe wrote: > I'm with a problem I'm doing a program in python, it sends the > following error message: > > File "C:/Documents and Settings/Filipe Vinicius/Desktop/Filipe/Cefet/ > LP/Python/trab.sistema.academico/sistemaacademico.2010.5.23.c.py", > line 40, in administrador > lp = pickle.load(f) > File "D:\Arquivos De Programa\Python31\lib\pickle.py", line 1365, in > load > encoding=encoding, errors=errors).load() > EOFError > > What you need to do to repair this error? in my program at the part > where the error is find is that: > > def administrador(): > f = open('professores.dat', 'rb') > lp = pickle.load(f) > f.close() > ... > > Note: i had already imported the pikcle library > THX > EOFError means "End Of File". The file you are reading in 'professores.dat' must not contain a valid pickle -- perhaps it is empty, or created incorrectly. But that's where to look. Show us how you created that file. Gary Herron From miki.tebeka at gmail.com Sun May 23 17:30:13 2010 From: miki.tebeka at gmail.com (Miki) Date: Sun, 23 May 2010 14:30:13 -0700 (PDT) Subject: How to show the current line number with pdb.set_trace() References: Message-ID: <688562d2-93c6-4c33-b28d-73a2eda6b736@6g2000prg.googlegroups.com> Hello, > After starting pdb.set_trace(), python doens't show line number. Could > you let me know how to print the number by default so that I know > where the current line is? When you get the PDB prompt, just type "l". It'll show some code with an error on the current line. You can also type "?" for help. HTH, -- Miki From ith140 at gmail.com Sun May 23 18:30:25 2010 From: ith140 at gmail.com (Ian Hoffman) Date: Sun, 23 May 2010 15:30:25 -0700 (PDT) Subject: MySQL, Python, NumPy and formatted read Message-ID: Hello, I'm having significant Python difficulties (and I'm new to Python). I'm trying to read BLOB ASCII (numerical) data from a MySQL database using MySQLdb in a formatted fashion. The BLOB data is a sequence of numbers separated by newlines (\n), like this: 5 6 10 45 etc. When I read the data using the fetchone() command I get a single tuple. What I'd like is to somehow put the tuple into a NumPy array with each value as one element. Then I can continue to do some numerical processing. Any advice/help? From landimatte at gmail.com Sun May 23 18:54:47 2010 From: landimatte at gmail.com (Matteo Landi) Date: Mon, 24 May 2010 00:54:47 +0200 Subject: MySQL, Python, NumPy and formatted read In-Reply-To: References: Message-ID: I know anything about mysqldb and fetchone method, but it's easy to create a numpy array, given a tuple of data: >>> import numpy >>> >>> t = ('1', '2', '3') >>> numpy.array(t, int) array([1, 2, 3]) >>> I made the assumption that mysqldb.fetchone return a tuple of strings, so we need to create an array by specifying the type of the needed values. On Mon, May 24, 2010 at 12:30 AM, Ian Hoffman wrote: > Hello, > > I'm having significant Python difficulties (and I'm new to Python). > I'm trying to read BLOB ASCII (numerical) data from a MySQL database > using MySQLdb in a formatted fashion. ?The BLOB data is a sequence of > numbers separated by newlines (\n), like this: > 5 > 6 > 10 > 45 > etc. > > When I read the data using the fetchone() command I get a single > tuple. ?What I'd like is to somehow put the tuple into a NumPy array > with each value as one element. ?Then I can continue to do some > numerical processing. > > Any advice/help? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From highcar at gmail.com Sun May 23 19:56:02 2010 From: highcar at gmail.com (ken) Date: Sun, 23 May 2010 16:56:02 -0700 (PDT) Subject: python urllib mechanize post problem Message-ID: <44c348a1-aea3-423c-816e-f5492c60d993@v29g2000prb.googlegroups.com> hello ALL im making some simple python post script but it not working well. there is 2 part to have to login. first login is using 'http://mybuddy.buddybuddy.co.kr/userinfo/ UserInfo.asp' this one. and second login is using 'http://user.buddybuddy.co.kr/usercheck/ UserCheckPWExec.asp' i can login first login page, but i couldn't login second page website. and return some error 'illegal access' such like . i heard this is related with some cooke but i don't know how to implement to resolve this problem. if anyone can help me much appreciated!! Thanks! import re,sys,os,mechanize,urllib,time import datetime,socket params = urllib.urlencode({'ID':'ph896011', 'PWD':'pk1089' }) rq = mechanize.Request("http://mybuddy.buddybuddy.co.kr/userinfo/ UserInfo.asp", params) rs = mechanize.urlopen(rq) data = rs.read() logged_fail = r';history.back();' in data if not logged_fail: print 'login success' try: params = urllib.urlencode({'PASSWORD':'pk1089'}) rq = mechanize.Request("http://user.buddybuddy.co.kr/usercheck/ UserCheckPWExec.asp", params ) rs = mechanize.urlopen(rq) data = rs.read() print data except: print 'error' From andrew.tan614 at gmail.com Sun May 23 23:06:33 2010 From: andrew.tan614 at gmail.com (Andrew) Date: Sun, 23 May 2010 20:06:33 -0700 (PDT) Subject: Extended deadline (15 July 2010): CACS Singapore [EI Compendex,ISTP,IEEE Xplore] Message-ID: [ Please forward to those who may be interested. Thanks. ] ================================================================== 2010 International Congress on Computer Applications and Computational Science CACS 2010 http://irast.org/conferences/CACS/2010 4-6 December 2010, Singapore ================================================================== CACS 2010 aims to bring together researchers and scientists from academia, industry, and government laboratories to present new results and identify future research directions in computer applications and computational science. Topics of interest include, but are not limited to: Agent and Autonomous Systems Computational Biology and Bioinformatics Computer-Aided Design and Manufacturing Computer Architecture and VLSI Computer Control and Robotics Computer Graphics, Animation and Virtual Reality Computers in Education & Learning technology Computer Modeling and Simulations Computer Networks and Communications Computer Security and Privacy Computer Vision and Pattern Recognition Data Mining and Data Engineering Distributed and Services Computing Energy and Power Systems Intelligent Systems Internet and Web Systems Nano Technologies Real-Time and Embedded Systems Scientific Computing and Applications Signal, Image and Multimedia Processing Software Engineering Test Technologies CACS 2010 conference proceedings will be published by CPS which will include the conference proceedings in IEEE Xplore and submit the proceedings to Ei Compendex and ISTP for indexing. Singapore's cultural diversity reflects its colonial history and Chinese, Malay, Indian and Arab ethnicities. English is the dominant official language, which is convenient for foreign visitors. Places of interest, such as the Orchard Road district, Singapore Zoo, Night Safari, and Sentosa, attract millions of visitors a year. Singapore is a paradise for shopping, dinning, entertainment, and nightlife, with two new integrated resorts. Conference Contact: CACS at irast.org Paper Submission Deadline with Extended: 15 July 2010 Review Decision Notifications: 15 August 2010 Final Papers and Author Registration Deadline: 9 September 2010 From ith140 at gmail.com Mon May 24 00:44:30 2010 From: ith140 at gmail.com (Ian Hoffman) Date: Sun, 23 May 2010 21:44:30 -0700 (PDT) Subject: MySQL, Python, NumPy and formatted read References: Message-ID: On May 23, 6:54?pm, Matteo Landi wrote: > I know anything about mysqldb and fetchone method, but it's easy to > create a numpy array, given a tuple of data: > > > > >>> import numpy > > >>> t = ('1', '2', '3') > >>> numpy.array(t, int) > array([1, 2, 3]) > > I made the assumption that mysqldb.fetchone return a tuple of strings, > so we need to create an array by specifying the type of the needed > values. > > > > On Mon, May 24, 2010 at 12:30 AM, Ian Hoffman wrote: > > Hello, > > > I'm having significant Python difficulties (and I'm new to Python). > > I'm trying to read BLOB ASCII (numerical) data from a MySQL database > > using MySQLdb in a formatted fashion. ?The BLOB data is a sequence of > > numbers separated by newlines (\n), like this: > > 5 > > 6 > > 10 > > 45 > > etc. > > > When I read the data using the fetchone() command I get a single > > tuple. ?What I'd like is to somehow put the tuple into a NumPy array > > with each value as one element. ?Then I can continue to do some > > numerical processing. > > > Any advice/help? > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Matteo Landihttp://www.matteolandi.net/ The problem is the tuple is contained in a single value separated by newlines (only a[0] has a record), otherwise I could do as you suggest... Isn From wuwei23 at gmail.com Mon May 24 01:29:12 2010 From: wuwei23 at gmail.com (alex23) Date: Sun, 23 May 2010 22:29:12 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <85rfa9Fv65U1@mid.individual.net> Message-ID: <1c5ea366-a909-4da7-ab7a-fe30542ebfab@a27g2000prj.googlegroups.com> Gregory Ewing wrote: > I came across a game on Big Fish Games recently (it was > "The Moonstone" IIRC) that appeared to have been built using > Python and py2app. Python tends to be used more for scripting internal game logic than for every aspect of a game (which is, IMO, the right way to go about it). It's not a huge list of commercial games that does this[1], but it's a fairly classy one :) 1: http://en.wikipedia.org/wiki/Category:Python-scripted_video_games From rowinggolfer*no_spam* at googlemail.com Mon May 24 04:29:37 2010 From: rowinggolfer*no_spam* at googlemail.com (Neil Wallace) Date: Mon, 24 May 2010 08:29:37 GMT Subject: Help with PyQt4 tabwidget setup References: Message-ID: On Fri, 21 May 2010 08:03:43 +0200, dpalmboom wrote: > I am creating an application and I'm busy designing the main layout on > the main window. What I would like to do is the following: > > Create a QTabWidget with a QVBoxLayout already inside it and also a > scrollbar inside it. When a user triggers a menu item, a QDockWidget > must be created and inserted into the QVBoxLayout, but it must not > stretch to the bottom of the QTabWidget. The QDockWidget must keep a set > size in the QVBoxLayout. When the user triggers another menu item, the > next QDockWidget must go above or below the existing QDockWidgets in the > QVBoxLayout. > > I currently have the following code for the QTabWidget: > > class PaneTabWidget(PyQt4.QtGui.QTabWidget): > > def __init__(self, tabs, parent=None): > > """ > A tabwidget to go inside a Pane. > """ > > super(PaneTabWidget, self).__init__(parent) > > for tab in tabs: > > if tab == "Properties": > self.propertiesBin() > elif tab == "Schedule": > self.scheduleBin() > elif tab == "Pricelist": > self.pricelistBin() > > def setLayoutAndScrollBar(self, page): > pass > > def addPanel(self, panel, type): > self.addTab(panel, type) > > def propertiesBin(self): > self.page = PyQt4.QtGui.QWidget() > self.addTab(self.page, "Properties") > self.setLayoutAndScrollBar(self.page) > > Right now, the dockwidget gets put into a new tab in the tab widget, but > I would like to put it into an existing QVBoxLayout. I currently have a > blank QWidget as a "placeholder" page of the tabwidget. > > If anyone can help me with this, it would be greatly appreciated. > > Thanks Hi, not 100% sure what you are after, but perhaps a standard tabWidget, with a customised Scrollarea forming the panel is one way? from PyQt4 import QtGui class TabPane(QtGui.QScrollArea): def __init__(self, parent=None): super(TabPane, self).__init__(parent) frame = QtGui.QFrame(self) frame.setFixedSize(300,200) self.setWidget(frame) self.layout = QtGui.QVBoxLayout(frame) def addDock(self, title): dw = QtGui.QDockWidget(title, self) self.layout.addWidget(dw) if __name__ == "__main__": app = QtGui.QApplication([]) tab_widget = QtGui.QTabWidget() for heading in ["Properties", "Schedule", "Pricelist"]: pane = TabPane() pane.addDock("Hello World") pane.addDock("Hello Galaxy") pane.addDock("Hello Universe") tab_widget.addTab(pane , heading) tab_widget.show() app.exec_() From dg1sbg at googlemail.com Mon May 24 05:55:46 2010 From: dg1sbg at googlemail.com (Frank GOENNINGER) Date: Mon, 24 May 2010 11:55:46 +0200 Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' References: Message-ID: Simon Brunning writes: > On 23 May 2010 14:46, Frank GOENNINGER wrote: >> Traceback (most recent call last): >> ?File "/.../src/pib/logging.py", line 37, in >> ? ?main() > > Here's a clue - looks like your own module is called logging. That's > what's getting imported by your import. Try naming your module > something else, and you should be golden. Yep. That was it. Thanks !! Cheers Frank From dg1sbg at googlemail.com Mon May 24 06:00:46 2010 From: dg1sbg at googlemail.com (Frank GOENNINGER) Date: Mon, 24 May 2010 12:00:46 +0200 Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' References: Message-ID: Philip Semanchuk writes: > On May 23, 2010, at 9:46 AM, Frank GOENNINGER wrote: >> >> I double checked and yes, getLogger is there. Why is the interpreter >> asking for an "attribute" here ? Any hints on what I am doing wrong ? > > > Short answer: Change the name of src/pib/logging.py to something else. Done. > Long answer: When Python hits the line "import logging", it first > looks in the current directory and imports logging.py, which in this > case is the file it's already executing. It never finds the standard > library's logging module. > > One way you could have figured this out would be to add this as the > first line of main(): > print dir(logging) > > That would have told you what Python thought the logging module looked > like, and would have perhaps recognized it as your own. Thanks - learned a lot from your post. > > Cheers > Philip Cheers Frank From avinash.magar at gmail.com Mon May 24 07:33:37 2010 From: avinash.magar at gmail.com (adm) Date: Mon, 24 May 2010 04:33:37 -0700 (PDT) Subject: launching vi/vim from console Message-ID: <24fdad90-8c7f-412f-bb4b-23bb6592c858@a16g2000prg.googlegroups.com> I am newbie to python. Is there a way to launch vi/vim or any other editor from python console? I find editing in console very limiting. I can either have a console which launches vi and remembers it's content and then executes or invoke python interpreter from vim. Since I could not find anything I wrote this: http://python.pastebin.com/MFTHxuLe Please suggest if there is any better alternative for this. I tried googling for this but could not find anything interesting. Thanks, Adm From dirknbr at googlemail.com Mon May 24 07:56:40 2010 From: dirknbr at googlemail.com (dirknbr) Date: Mon, 24 May 2010 04:56:40 -0700 (PDT) Subject: Email in 2.6.4 Message-ID: I am trying to run from email.mime.text import MIMEText but I get an ImportError: No module named mime.text Since email was pre-installed how do I fix this? Dirk From jeanmichel at sequans.com Mon May 24 07:59:34 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 May 2010 13:59:34 +0200 Subject: launching vi/vim from console In-Reply-To: <24fdad90-8c7f-412f-bb4b-23bb6592c858@a16g2000prg.googlegroups.com> References: <24fdad90-8c7f-412f-bb4b-23bb6592c858@a16g2000prg.googlegroups.com> Message-ID: <4BFA6A26.4000708@sequans.com> adm wrote: > I am newbie to python. > Is there a way to launch vi/vim or any other editor from python > console? I find editing in console very limiting. I can either have a > console which launches vi and remembers it's content and then executes > or invoke python interpreter from vim. > > Since I could not find anything I wrote this: http://python.pastebin.com/MFTHxuLe > Please suggest if there is any better alternative for this. > I tried googling for this but could not find anything interesting. > > Thanks, > Adm > import os os.system.('vi') or you can start an ipython shell and start vi using !vi From steve at REMOVE-THIS-cybersource.com.au Mon May 24 08:13:59 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 May 2010 12:13:59 GMT Subject: Can upper() or lower() ever change the length of a string? Message-ID: <4bfa6d87$0$27861$c3e8da3@news.astraweb.com> Do unicode.lower() or unicode.upper() ever change the length of the string? The Unicode standard allows for case conversions that change length, e.g. sharp-S in German should convert to SS: http://unicode.org/faq/casemap_charprop.html#6 but I see that Python doesn't do that: >>> s = "Pa?stra?e" >>> s.upper() 'PA?STRA?E' The more I think about this, the more I think that upper/lower/title case conversions should change length (at least sometimes) and if Python doesn't do so, that's a bug. Any thoughts? -- Steven From dickinsm at gmail.com Mon May 24 08:20:18 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 24 May 2010 05:20:18 -0700 (PDT) Subject: Can upper() or lower() ever change the length of a string? References: <4bfa6d87$0$27861$c3e8da3@news.astraweb.com> Message-ID: On May 24, 1:13?pm, Steven D'Aprano wrote: > Do unicode.lower() or unicode.upper() ever change the length of the > string? >From looking at the source, in particular the fixupper and fixlower functions in Objects/unicode.c [1], it looks like not: they do a simple character-by-character replacement. [1] http://svn.python.org/view/python/trunk/Objects/unicodeobject.c?view=markup -- Mark From avinash.magar at gmail.com Mon May 24 08:31:58 2010 From: avinash.magar at gmail.com (adm) Date: Mon, 24 May 2010 05:31:58 -0700 (PDT) Subject: launching vi/vim from console References: <24fdad90-8c7f-412f-bb4b-23bb6592c858@a16g2000prg.googlegroups.com> Message-ID: <8e0c42d8-ad52-42ea-b091-0d13cd2003f7@g1g2000pro.googlegroups.com> On May 24, 4:59?pm, Jean-Michel Pichavant wrote: > adm wrote: > > I am newbie to python. > > Is there a way to launch vi/vim or any other editor from python > > console? I find editing in console very limiting. I can either have a > > console which launches vi and remembers it's content and then executes > > or invoke python interpreter from vim. > > > Since I could not find anything I wrote this:http://python.pastebin.com/MFTHxuLe > > Please suggest if there is any better alternative for this. > > I tried googling for this but could not find anything interesting. > > > Thanks, > > Adm > > import os > os.system.('vi') > > or you can start an ipython shell > ?and start vi using > !vi Thanks. I wanted something like ipython. I will give it a try. From dickinsm at gmail.com Mon May 24 08:44:21 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 24 May 2010 05:44:21 -0700 (PDT) Subject: Can upper() or lower() ever change the length of a string? References: <4bfa6d87$0$27861$c3e8da3@news.astraweb.com> Message-ID: <32fa918a-0d5a-4a4b-b0cb-d69b4ad33ab9@y21g2000vba.googlegroups.com> On May 24, 1:13?pm, Steven D'Aprano wrote: > Do unicode.lower() or unicode.upper() ever change the length of the > string? > > The Unicode standard allows for case conversions that change length, e.g. > sharp-S in German should convert to SS: > > http://unicode.org/faq/casemap_charprop.html#6 > > but I see that Python doesn't do that: > > >>> s = "Pa?stra?e" > >>> s.upper() > > 'PA?STRA?E' > > The more I think about this, the more I think that upper/lower/title case > conversions should change length (at least sometimes) and if Python > doesn't do so, that's a bug. Any thoughts? Digging a bit deeper, it looks like these methods are using the Simple_{Upper,Lower,Title}case_Mapping functions described at http://www.unicode.org/Public/5.1.0/ucd/UCD.html fields 12, 13 and 14 of the unicode data; you can see this in the source in Tools/unicode/ makeunicodedata.py, which is the Python code that generates the database of unicode properties. It contains code like: if record[12]: upper = int(record[12], 16) else: upper = char if record[13]: lower = int(record[13], 16) else: lower = char if record[14]: title = int(record[14], 16) ... and so on. I agree that it might be desirable for these operations to product the multicharacter equivalents. That idea looks like a tough sell, though: apart from backwards compatibility concerns (which could probably be worked around somehow), it looks as though it would require significant effort to implement. -- Mark From jeanmichel at sequans.com Mon May 24 09:19:33 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 May 2010 15:19:33 +0200 Subject: Email in 2.6.4 In-Reply-To: References: Message-ID: <4BFA7CE5.60000@sequans.com> dirknbr wrote: > I am trying to run > > from email.mime.text import MIMEText > > but I get an > > ImportError: No module named mime.text > > Since email was pre-installed how do I fix this? > > Dirk > Did you make sure you didn't hide the standard email module by one of your own. Check print email.__file__ /usr/lib/python2.5/email/__init__.pyc If the path is correct, you may want to look in the code, or if anything has changed in 2.6, I guess it is documented somewhere. JM From eknath.iyer at gmail.com Mon May 24 09:43:26 2010 From: eknath.iyer at gmail.com (Eknath Venkataramani) Date: Mon, 24 May 2010 19:13:26 +0530 Subject: extracting unicode text from pdfs Message-ID: I have around 45 pdfs to convert into raw text containing text in _HINDI_ . When I use the xpdf package, the generated text is very weird, so I'd like to write a program which would convert the pdf text into Unicode text as it is. The fonts used in the pdfs: name type emb sub uni object ID ------------------------------------ ----------------- --- --- --- --------- APKAPP+Usha-Bold Type 1C yes yes yes 72 0 APKBBB+Agenda-Light Type 1C yes yes yes 77 0 APKBGF+Usha Type 1C yes yes yes 41 0 APKBKJ+Agenda-Medium Type 1C yes yes yes 46 0 APKBON+Agenda-Bold Type 1C yes yes yes 49 0 For eg. in the pdf: ???? ??????? ?? when I use pdftotext, I get some very weird symbols: '... .......' while i'd like '???? ??????? ??' to be the output -- Eknath Venkataramani -------------- next part -------------- An HTML attachment was scrubbed... URL: From dirknbr at googlemail.com Mon May 24 09:59:24 2010 From: dirknbr at googlemail.com (dirknbr) Date: Mon, 24 May 2010 06:59:24 -0700 (PDT) Subject: Email in 2.6.4 References: Message-ID: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> I have now easy_installled email and I still get errors. It doesn't error on 'import email' but does on call to MimeText. import email msg = MIMEText('test') NameError: name 'MIMEText' is not defined What should I do? From python at rcn.com Mon May 24 10:14:43 2010 From: python at rcn.com (Raymond Hettinger) Date: Mon, 24 May 2010 07:14:43 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: On May 19, 12:58?pm, superpollo wrote: > ... how many positive integers less than n have digits that sum up to m: > > In [197]: def prttn(m, n): > ? ? ?tot = 0 > ? ? ?for i in range(n): > ? ? ? ? ?s = str(i) > ? ? ? ? ?sum = 0 > ? ? ? ? ?for j in range(len(s)): > ? ? ? ? ? ? ?sum += int(s[j]) > ? ? ? ? ?if sum == m: > ? ? ? ? ? ? ?tot += 1 > ? ? ?return tot > ? ? .....: > > In [207]: prttn(25, 10000) > Out[207]: 348 > > any suggestion for pythonizin' it? Your code is readable and does the job just fine. Not sure it is an improvement to reroll it into a one-liner: def prttn(m, n): return sum(m == sum(map(int, str(x))) for x in range(n)) >>> prttn(25, 10000) 348 Some people find the functional style easier to verify because of fewer auxilliary variables and each step is testable independently. The m==sum() part is not very transparent because it relies on True==1, so it's only readable if it becomes a common idiom (which it could when you're answering questions of the form "how many numbers have property x"). If speed is important, the global lookups can be localized: def prttn(m, n, map=itertools.imap, int=int, str=str, range=range): return sum(m == sum(map(int, str(x))) for x in range(n)) Raymond From simon at brunningonline.net Mon May 24 10:21:56 2010 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 24 May 2010 15:21:56 +0100 Subject: Email in 2.6.4 In-Reply-To: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> References: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> Message-ID: On 24 May 2010 14:59:24 UTC+1, dirknbr wrote: > It doesn't error on 'import email' but does on call to MimeText. > > import email > msg = MIMEText('test') > > NameError: name 'MIMEText' is not defined Here you want: msg = email.MIMEText('test') -- Cheers, Simon B. From dhananjay.nene at gmail.com Mon May 24 10:21:57 2010 From: dhananjay.nene at gmail.com (Dhananjay Nene) Date: Mon, 24 May 2010 19:51:57 +0530 Subject: [BangPypers] extracting unicode text from pdfs In-Reply-To: References: Message-ID: You may want to try out pdfminer. Its very similar to xpdf in structure and should give you the parsed data into unicode directly. On Mon, May 24, 2010 at 7:13 PM, Eknath Venkataramani wrote: > I have around 45 pdfs to convert into raw text containing text in _HINDI_ . > When I use the xpdf package, the generated text is very weird, so I'd like > to write a program which would convert the pdf text into Unicode text as it > is. > > The fonts used in the pdfs: > name type emb sub uni object > ID > ------------------------------------ ----------------- --- --- --- > --------- > APKAPP+Usha-Bold Type 1C yes yes yes 72 > 0 > APKBBB+Agenda-Light Type 1C yes yes yes 77 > 0 > APKBGF+Usha Type 1C yes yes yes 41 > 0 > APKBKJ+Agenda-Medium Type 1C yes yes yes 46 > 0 > APKBON+Agenda-Bold Type 1C yes yes yes 49 > 0 > > For eg. in the pdf: ???? ??????? ?? > when I use pdftotext, I get some very weird symbols: '... > .......' > while i'd like '???? ??????? ??' to be the output > > > -- > Eknath Venkataramani > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > http://mail.python.org/mailman/listinfo/bangpypers > -- -------------------------------------------------------- blog: http://blog.dhananjaynene.com twitter: http://twitter.com/dnene -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Mon May 24 10:22:00 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 May 2010 16:22:00 +0200 Subject: Email in 2.6.4 In-Reply-To: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> References: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> Message-ID: <4BFA8B88.4050108@sequans.com> dirknbr wrote: > I have now easy_installled email and I still get errors. > > It doesn't error on 'import email' but does on call to MimeText. > > import email > msg = MIMEText('test') > > NameError: name 'MIMEText' is not defined > > What should I do? > Using easy_install will not prevent the standard lib to be shadowed by another (user) module. did you print email.__file__ to verify the path ? Can you show us the output ? To give you an example, on a lenny python 2.5 distrib, the MIMEText class is in /usr/lib/python2.5/email/mime/text.py JM From breamoreboy at yahoo.co.uk Mon May 24 10:35:39 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 May 2010 15:35:39 +0100 Subject: Email in 2.6.4 In-Reply-To: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> References: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> Message-ID: On 24/05/2010 14:59, dirknbr wrote: > I have now easy_installled email and I still get errors. I've done this as well, but don't see why I have to. Is this a documentation bug, an installation bug or what? > > It doesn't error on 'import email' but does on call to MimeText. > > import email > msg = MIMEText('test') > > NameError: name 'MIMEText' is not defined > > What should I do? Give the fully qualified name i.e. email.mime.text.MIMEText. Regards. Mark Lawrence. From dirknbr at googlemail.com Mon May 24 10:36:59 2010 From: dirknbr at googlemail.com (Dirk Nachbar) Date: Mon, 24 May 2010 15:36:59 +0100 Subject: Email in 2.6.4 In-Reply-To: <4BFA8B88.4050108@sequans.com> References: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> <4BFA8B88.4050108@sequans.com> Message-ID: Sorry guys, I had named my file email.py and hence the error. On 24 May 2010 15:22, Jean-Michel Pichavant wrote: > dirknbr wrote: > >> I have now easy_installled email and I still get errors. >> >> >> It doesn't error on 'import email' but does on call to MimeText. >> >> import email >> msg = MIMEText('test') >> >> NameError: name 'MIMEText' is not defined >> >> What should I do? >> >> > Using easy_install will not prevent the standard lib to be shadowed by > another (user) module. > > did you print email.__file__ to verify the path ? > Can you show us the output ? > > To give you an example, on a lenny python 2.5 distrib, the MIMEText class > is in > /usr/lib/python2.5/email/mime/text.py > > JM > -- http://dirknbr.googlepages.com http://maximum-likely.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Mon May 24 10:42:06 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 24 May 2010 15:42:06 +0100 Subject: Can upper() or lower() ever change the length of a string? In-Reply-To: <32fa918a-0d5a-4a4b-b0cb-d69b4ad33ab9@y21g2000vba.googlegroups.com> References: <4bfa6d87$0$27861$c3e8da3@news.astraweb.com> <32fa918a-0d5a-4a4b-b0cb-d69b4ad33ab9@y21g2000vba.googlegroups.com> Message-ID: <4BFA903E.7060401@mrabarnett.plus.com> Mark Dickinson wrote: > On May 24, 1:13 pm, Steven D'Aprano cybersource.com.au> wrote: >> Do unicode.lower() or unicode.upper() ever change the length of the >> string? >> >> The Unicode standard allows for case conversions that change length, e.g. >> sharp-S in German should convert to SS: >> >> http://unicode.org/faq/casemap_charprop.html#6 >> >> but I see that Python doesn't do that: >> >>>>> s = "Pa?stra?e" >>>>> s.upper() >> 'PA?STRA?E' >> >> The more I think about this, the more I think that upper/lower/title case >> conversions should change length (at least sometimes) and if Python >> doesn't do so, that's a bug. Any thoughts? > > Digging a bit deeper, it looks like these methods are using the > Simple_{Upper,Lower,Title}case_Mapping functions described at > http://www.unicode.org/Public/5.1.0/ucd/UCD.html fields 12, 13 and 14 > of the unicode data; you can see this in the source in Tools/unicode/ > makeunicodedata.py, which is the Python code that generates the > database of unicode properties. It contains code like: > > if record[12]: > upper = int(record[12], 16) > else: > upper = char > if record[13]: > lower = int(record[13], 16) > else: > lower = char > if record[14]: > title = int(record[14], 16) > > ... and so on. > > I agree that it might be desirable for these operations to product the > multicharacter equivalents. That idea looks like a tough sell, > though: apart from backwards compatibility concerns (which could > probably be worked around somehow), it looks as though it would > require significant effort to implement. > If we were to make such a change, I think we should also cater for locale-specific case changes (passing the locale to 'upper', 'lower' and 'title'). For example, normally "i".upper() returns "I", but in Turkish "i".upper() should return "?" (the uppercase version of lowercase dotted i is uppercase dotted I). From jeanmichel at sequans.com Mon May 24 10:50:09 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 May 2010 16:50:09 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4BFA9221.3080905@sequans.com> Jerry Hill wrote: > On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: > >> ... how many positive integers less than n have digits that sum up to m: >> > ... > >> any suggestion for pythonizin' it? >> > > This is how I would do it: > > def prttn(m, n): > """How many positive integers less than n have digits that sum up to m""" > total = 0 > for testval in range(n): > sumofdigits = sum(int(char) for char in str(testval)) > if sumofdigits == m: > total += 1 > return total > > I added a docstring to the function, saying what it does, and what the > arguments are supposed to represent. I also moved the > convert-to-string-and-sum-the-digits logic into a single generator > expression that's passed to the builtin sum function. Oh, and I tried > to use slightly more expressive variable names. > > my favorite solutio nso far. @ OP What means prttn ? is it any Dutch word :D ? m & n are also very poors argument names. I will be difficult to name properly the function, as it is doing something ... I don't find the word, something like un-intuitive. Sounds like homework. def how_many_positive_integers_less_than_n_have_digits_that_sum_up_to_m(m, n) :o) JM PS : read http://tottinge.blogsome.com/meaningfulnames/ From landimatte at gmail.com Mon May 24 10:51:16 2010 From: landimatte at gmail.com (Matteo Landi) Date: Mon, 24 May 2010 16:51:16 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: What about avoiding the string conversion and use mod/div operations in order to create a list of digits for a number? Now that you have the sequences it's easy to count which sums up to m. On Mon, May 24, 2010 at 4:14 PM, Raymond Hettinger wrote: > On May 19, 12:58 pm, superpollo wrote: >> ... how many positive integers less than n have digits that sum up to m: >> >> In [197]: def prttn(m, n): >> tot = 0 >> for i in range(n): >> s = str(i) >> sum = 0 >> for j in range(len(s)): >> sum += int(s[j]) >> if sum == m: >> tot += 1 >> return tot >> .....: >> >> In [207]: prttn(25, 10000) >> Out[207]: 348 >> >> any suggestion for pythonizin' it? > > Your code is readable and does the job just fine. > Not sure it is an improvement to reroll it into a one-liner: > > def prttn(m, n): > return sum(m == sum(map(int, str(x))) for x in range(n)) >>>> prttn(25, 10000) > 348 > > Some people find the functional style easier to verify because of > fewer auxilliary variables and each step is testable independently. > The m==sum() part is not very transparent because it relies on > True==1, so it's only readable if it becomes a common idiom (which it > could when you're answering questions of the form "how many numbers > have property x"). > > If speed is important, the global lookups can be localized: > > def prttn(m, n, map=itertools.imap, int=int, str=str, range=range): > return sum(m == sum(map(int, str(x))) for x in range(n)) > > Raymond > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From jeanmichel at sequans.com Mon May 24 10:55:41 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 May 2010 16:55:41 +0200 Subject: Email in 2.6.4 In-Reply-To: References: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> <4BFA8B88.4050108@sequans.com> Message-ID: <4BFA936D.2060902@sequans.com> Dirk Nachbar wrote: > Sorry guys, I had named my file email.py and hence the error. > > > > On 24 May 2010 15:22, Jean-Michel Pichavant > wrote: > > dirknbr wrote: > > I have now easy_installled email and I still get errors. > > > It doesn't error on 'import email' but does on call to MimeText. > > import email > msg = MIMEText('test') > > NameError: name 'MIMEText' is not defined > > What should I do? > > > Using easy_install will not prevent the standard lib to be > shadowed by another (user) module. > > did you print email.__file__ to verify the path ? > Can you show us the output ? > > To give you an example, on a lenny python 2.5 distrib, the > MIMEText class is in > /usr/lib/python2.5/email/mime/text.py > > JM > > > > Classic error, you're not the first one, and my guess is that you won't be the last. JM From anand.shashwat at gmail.com Mon May 24 10:59:48 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Mon, 24 May 2010 20:29:48 +0530 Subject: launching vi/vim from console In-Reply-To: <8e0c42d8-ad52-42ea-b091-0d13cd2003f7@g1g2000pro.googlegroups.com> References: <24fdad90-8c7f-412f-bb4b-23bb6592c858@a16g2000prg.googlegroups.com> <8e0c42d8-ad52-42ea-b091-0d13cd2003f7@g1g2000pro.googlegroups.com> Message-ID: or in a reverse way you can open vim and use ':shell' followed by python. I prefer it that way generally On Mon, May 24, 2010 at 6:01 PM, adm wrote: > On May 24, 4:59 pm, Jean-Michel Pichavant > wrote: > > adm wrote: > > > I am newbie to python. > > > Is there a way to launch vi/vim or any other editor from python > > > console? I find editing in console very limiting. I can either have a > > > console which launches vi and remembers it's content and then executes > > > or invoke python interpreter from vim. > > > > > Since I could not find anything I wrote this: > http://python.pastebin.com/MFTHxuLe > > > Please suggest if there is any better alternative for this. > > > I tried googling for this but could not find anything interesting. > > > > > Thanks, > > > Adm > > > > import os > > os.system.('vi') > > > > or you can start an ipython shell > > and start vi using > > !vi > > Thanks. I wanted something like ipython. > I will give it a try. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nathan.alexander.rice at gmail.com Mon May 24 12:56:44 2010 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Mon, 24 May 2010 12:56:44 -0400 Subject: Most reliable/pythonic way to tell if an instance comes from a class implemented in C/etc? Message-ID: I'm trying to do some fairly deep introspection and instrumentation of instances and classes at runtime, and in order for everything to be properly behaved I need to have radically different behavior in the event that the thing passed to me is a wrapped class/instance. Is there a really good way, given an instance of a class, to determine if it is wrapped or native? Currently I check to see if it has __slots__ then try to setattr a dummy variable but I imagine there is probably a cleaner way. Nathan -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Mon May 24 13:37:58 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 24 May 2010 13:37:58 -0400 Subject: A Quick MySQL Question Message-ID: Hi; I have the following: # sql = 'alter table %s alter column %s set default "%%s";' % (store, col) # cursor.execute(sql, colValue) cursor.execute('alter table %s alter column %s set default "%s";' % (store, col, colValue)) database.commit() Now I don't like that third line, so I tried the commented out lines, but I got an MySQLdb.OperationalError that the suggested default value could not be inserted. However, when I printed it out and tried to insert directly, no problem, and the 3rd line works fine. What gives? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon May 24 14:01:59 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 May 2010 14:01:59 -0400 Subject: Can upper() or lower() ever change the length of a string? In-Reply-To: <4BFA903E.7060401@mrabarnett.plus.com> References: <4bfa6d87$0$27861$c3e8da3@news.astraweb.com> <32fa918a-0d5a-4a4b-b0cb-d69b4ad33ab9@y21g2000vba.googlegroups.com> <4BFA903E.7060401@mrabarnett.plus.com> Message-ID: On 5/24/2010 10:42 AM, MRAB wrote: > Mark Dickinson wrote: >> Digging a bit deeper, it looks like these methods are using the >> Simple_{Upper,Lower,Title}case_Mapping functions described at >> http://www.unicode.org/Public/5.1.0/ucd/UCD.html fields 12, 13 and 14 >> of the unicode data; you can see this in the source in Tools/unicode/ >> makeunicodedata.py, which is the Python code that generates the >> database of unicode properties. It contains code like: >> >> if record[12]: >> upper = int(record[12], 16) >> else: >> upper = char >> if record[13]: >> lower = int(record[13], 16) >> else: >> lower = char >> if record[14]: >> title = int(record[14], 16) >> >> ... and so on. >> >> I agree that it might be desirable for these operations to product the >> multicharacter equivalents. That idea looks like a tough sell, >> though: apart from backwards compatibility concerns (which could >> probably be worked around somehow), it looks as though it would >> require significant effort to implement. >> > If we were to make such a change, I think we should also cater for > locale-specific case changes (passing the locale to 'upper', 'lower' and > 'title'). > > For example, normally "i".upper() returns "I", but in Turkish > "i".upper() should return "?" (the uppercase version of lowercase dotted > i is uppercase dotted I). Given that the current (siimple) functions implement standard-defined functions, I think any change should be to *add* new 'complex-case-change' functions. Terry Jan Reedy From tjreedy at udel.edu Mon May 24 14:30:18 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 May 2010 14:30:18 -0400 Subject: Most reliable/pythonic way to tell if an instance comes from a class implemented in C/etc? In-Reply-To: References: Message-ID: On 5/24/2010 12:56 PM, Nathan Rice wrote: > I'm trying to do some fairly deep introspection and instrumentation of > instances and classes at runtime, and in order for everything to be > properly behaved I need to have radically different behavior in the > event that the thing passed to me is a wrapped class/instance. Is there > a really good way, given an instance of a class, to determine if it is > wrapped or native? Currently I check to see if it has __slots__ then > try to setattr a dummy variable but I imagine there is probably a > cleaner way. I am not sure what you mean by 'wrapped'. Your subject line says something different. In any case, is your universe *all* Python objects or some subset? Builtin classes, named or not, do not have dotted names >>> 1 .__class__ >>> class C: pass I believe all others do, including C-coded extension classes. >>> C().__class__ tjr From 3006nol at gmail.com Mon May 24 14:50:03 2010 From: 3006nol at gmail.com (narcissus) Date: Mon, 24 May 2010 11:50:03 -0700 (PDT) Subject: Chatroom Message-ID: Hello , I want to create a program that is one chatroom and everyone has this program can Enter into that chatroom. how can i do this? and i want gui for it too (GTK) From jessemcdonnell at verizon.net Mon May 24 14:52:39 2010 From: jessemcdonnell at verizon.net (Jesse McDonnell) Date: Mon, 24 May 2010 13:52:39 -0500 (CDT) Subject: TypeError: _new_() takes exactly 3 arguments (2 given) - what does it mean? Message-ID: <2061601704.535865.1274727159418.JavaMail.root@vms244.mailsrvcs.net> An HTML attachment was scrubbed... URL: From martin.hellwig at dcuktec.org Mon May 24 14:59:45 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 24 May 2010 19:59:45 +0100 Subject: Chatroom In-Reply-To: References: Message-ID: On 05/24/10 19:50, narcissus wrote: > Hello , I want to create a program that is one chatroom and everyone > has this program can Enter into that chatroom. how can i do this? > > and i want gui for it too (GTK) What have you tried so far? -- mph From darragh.ssa at gmail.com Mon May 24 15:04:44 2010 From: darragh.ssa at gmail.com (Kruptein) Date: Mon, 24 May 2010 12:04:44 -0700 (PDT) Subject: D-CM IDE Message-ID: <1ad60739-6e39-4883-bef8-4005dbe80373@z17g2000vbd.googlegroups.com> I'm developing an "IDE" in python (wxPython toolkit). it's an application that combines a file-manager,text-editor,sql-manager,ftp- manager and more in one simple to use GUI. I'm releasing a new version soon and I hoped that there were some folks in here that would like to test if it worked well.. It is a linux program and can be found here: https://launchpad.net/d-cm the windows version (is some releases behind the linux version) can be found here: https://launchpad.net/d-cm-win From duncan.booth at invalid.invalid Mon May 24 16:12:36 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 May 2010 20:12:36 GMT Subject: Most reliable/pythonic way to tell if an instance comes from a class implemented in C/etc? References: Message-ID: Terry Reedy wrote: > Builtin classes, named or not, do not have dotted names > > >>> 1 .__class__ > > >>> class C: pass > > I believe all others do, including C-coded extension classes. > > >>> C().__class__ > > Not quite all. Classes created by calling the type constructor directly don't have to follow that rule: >>> C = type('Fred', (object,), {}) >>> C.__name__ 'Fred' From subhakolkata1234 at gmail.com Mon May 24 16:15:01 2010 From: subhakolkata1234 at gmail.com (joy99) Date: Mon, 24 May 2010 13:15:01 -0700 (PDT) Subject: Question on Python Function Message-ID: Dear Group, I have a small question on function. If I write two functions like the following: IDLE 2.6.5 >>> def function1(n): element1=5 element2=6 add=element1+element2 print "PRINT THE ADDITION",add >>> def function2(n): element3=7 element4=22 mult=element3*element4 print "PRINT THE MULTIPLICATION",mult Can I now write a third function where the above two functions can be passed as argument or parameter? Best Regards, Subhabrata. NB: As I copied the code from IDLE to MS-Word befor posting here, codes may have slight indentation errors. From utente at esempio.net Mon May 24 16:34:18 2010 From: utente at esempio.net (superpollo) Date: Mon, 24 May 2010 22:34:18 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> Jean-Michel Pichavant ha scritto: > Jerry Hill wrote: >> On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: >> >>> ... how many positive integers less than n have digits that sum up to m: >>> >> ... >> >>> any suggestion for pythonizin' it? >>> >> >> This is how I would do it: >> >> def prttn(m, n): >> """How many positive integers less than n have digits that sum up >> to m""" >> total = 0 >> for testval in range(n): >> sumofdigits = sum(int(char) for char in str(testval)) >> if sumofdigits == m: >> total += 1 >> return total >> >> I added a docstring to the function, saying what it does, and what the >> arguments are supposed to represent. I also moved the >> convert-to-string-and-sum-the-digits logic into a single generator >> expression that's passed to the builtin sum function. Oh, and I tried >> to use slightly more expressive variable names. >> >> > my favorite solutio nso far. > > @ OP > > What means prttn ? i already answered this downthreads... > something ... I don't find the word, something like un-intuitive. Sounds > like homework. it is not. From alister.ware at ntlworld.com Mon May 24 16:45:42 2010 From: alister.ware at ntlworld.com (Alister) Date: Mon, 24 May 2010 20:45:42 GMT Subject: Question on Python Function References: Message-ID: On Mon, 24 May 2010 13:15:01 -0700, joy99 wrote: > Dear Group, > > I have a small question on function. > > If I write two functions like the following: > > IDLE 2.6.5 >>>> def function1(n): > element1=5 > element2=6 > add=element1+element2 > print "PRINT THE ADDITION",add > > >>>> def function2(n): > element3=7 > element4=22 > mult=element3*element4 > print "PRINT THE MULTIPLICATION",mult > > Can I now write a third function where the above two functions can be > passed as argument or parameter? > > Best Regards, > Subhabrata. > > NB: As I copied the code from IDLE to MS-Word befor posting here, codes > may have slight indentation errors. I don't quite see the point of your functions as they do not use their parameters in any way, but you need to set a return value IDLE 2.6.5 >>> def function1(n): element1=5 element2=6 add=element1+element2 return add >>> def function2(n): element3=7 element4=22 mult=element3*element4 return mult >>> def function3(x,y): print "add= %s mult=%s" % (x , y) >>>function3(function1(1),funtcion2(2)) -- Your digestive system is your body's Fun House, whereby food goes on a long, dark, scary ride, taking all kinds of unexpected twists and turns, being attacked by vicious secretions along the way, and not knowing until the last minute whether it will be turned into a useful body part or ejected into the Dark Hole by Mister Sphincter. We Americans live in a nation where the medical-care system is second to none in the world, unless you count maybe 25 or 30 little scuzzball countries like Scotland that we could vaporize in seconds if we felt like it. -- Dave Barry, "Stay Fit & Healthy Until You're Dead" From vlastimil.brom at gmail.com Mon May 24 16:56:34 2010 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 24 May 2010 22:56:34 +0200 Subject: Question on Python Function In-Reply-To: References: Message-ID: 2010/5/24 joy99 : > > > Dear Group, > > I have a small question on function. > > If I write two functions like the following: > > IDLE 2.6.5 >>>> def function1(n): > ? ? ? ?element1=5 > ? ? ? ?element2=6 > ? ? ? ?add=element1+element2 > ? ? ? ?print "PRINT THE ADDITION",add > > >>>> def function2(n): > ? ? ? ?element3=7 > ? ? ? ?element4=22 > ? ? ? ?mult=element3*element4 > ? ? ? ?print "PRINT THE MULTIPLICATION",mult > > Can I now write a third function where the above two functions can be > passed as argument or parameter? > > Best Regards, > Subhabrata. > > NB: As I copied the code from IDLE to MS-Word befor posting here, > codes may have slight indentation errors. > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, while it is quite unclear to me, what you are trying to achieve (what are the passed n arguments supposed to do?), you can well pass an already defined function as an argument to another function; if you want to select a function for the needed operation, if can be e.g.: def compute(arg1, arg2, fn): fn(arg1, arg2) - supposing you don't want to "return" the result but just print it as your functions do; is it what you were after or did I miss something more complex? hth vbr From alister.ware at ntlworld.com Mon May 24 17:08:14 2010 From: alister.ware at ntlworld.com (Alister) Date: Mon, 24 May 2010 21:08:14 GMT Subject: Question on Python Function References: Message-ID: <2VBKn.101377$Lg1.29534@newsfe17.ams2> On Mon, 24 May 2010 22:56:34 +0200, Vlastimil Brom wrote: > 2010/5/24 joy99 : >> >> >> Dear Group, >> >> I have a small question on function. >> >> If I write two functions like the following: >> >> IDLE 2.6.5 >>>>> def function1(n): >> ? ? ? ?element1=5 >> ? ? ? ?element2=6 >> ? ? ? ?add=element1+element2 >> ? ? ? ?print "PRINT THE ADDITION",add >> >> >>>>> def function2(n): >> ? ? ? ?element3=7 >> ? ? ? ?element4=22 >> ? ? ? ?mult=element3*element4 >> ? ? ? ?print "PRINT THE MULTIPLICATION",mult >> >> Can I now write a third function where the above two functions can be >> passed as argument or parameter? >> >> Best Regards, >> Subhabrata. >> >> NB: As I copied the code from IDLE to MS-Word befor posting here, codes >> may have slight indentation errors. -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > Hi, > while it is quite unclear to me, what you are trying to achieve (what > are the passed n arguments supposed to do?), you can well pass an > already defined function as an argument to another function; if you want > to select a function for the needed operation, if can be e.g.: > > def compute(arg1, arg2, fn): > fn(arg1, arg2) > > - supposing you don't want to "return" the result but just print it as > your functions do; > is it what you were after or did I miss something more complex? > > hth > vbr I did not realise you could pass a function like this, I am sure it could lead to some interesting programming. I am still new to OOP & the light is only just starting to switch on. analysing your examples I now realise that all function parameters are Objects & EVERYTHING(well almost anyway) is an object. It just goes to show that even when you know 1 answer to the original question You can still learn by looking at others -- "And, of course, you have the commercials where savvy businesspeople Get Ahead by using their MacIntosh computers to create the ultimate American business product: a really sharp-looking report." -- Dave Barry From subhakolkata1234 at gmail.com Mon May 24 17:39:09 2010 From: subhakolkata1234 at gmail.com (joy99) Date: Mon, 24 May 2010 14:39:09 -0700 (PDT) Subject: Question on Python Function References: Message-ID: <6ae2891c-0e15-4852-a082-4b9d8cd6f3af@t34g2000prd.googlegroups.com> On May 25, 1:56?am, Vlastimil Brom wrote: > 2010/5/24 joy99 : > > > > > > > > > Dear Group, > > > I have a small question on function. > > > If I write two functions like the following: > > > IDLE 2.6.5 > >>>> def function1(n): > > ? ? ? ?element1=5 > > ? ? ? ?element2=6 > > ? ? ? ?add=element1+element2 > > ? ? ? ?print "PRINT THE ADDITION",add > > >>>> def function2(n): > > ? ? ? ?element3=7 > > ? ? ? ?element4=22 > > ? ? ? ?mult=element3*element4 > > ? ? ? ?print "PRINT THE MULTIPLICATION",mult > > > Can I now write a third function where the above two functions can be > > passed as argument or parameter? > > > Best Regards, > > Subhabrata. > > > NB: As I copied the code from IDLE to MS-Word befor posting here, > > codes may have slight indentation errors. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Hi, > while it is quite unclear to me, what you are trying to achieve (what > are the passed n arguments supposed to do?), you can well pass an > already defined function as an argument to another function; if you > want to select a function for the needed operation, if can be e.g.: > > def compute(arg1, arg2, fn): > ? ? fn(arg1, arg2) > > - supposing you don't want to "return" the result but just print it as > your functions do; > is it what you were after or did I miss something more complex? > > hth > ? vbr- Hide quoted text - > > - Show quoted text - Dear Vlastimil, You are right. Your approach will do to me. I was trying Python Doc either I do not know where to check, or I could not find. I am trying to work out. Numbers I can pass, I was checking the last example in Python Docs with "def cheeseshop(kind, *arguments, **keywords):" if that gives me any clue. If you can kindly try. Best Regards, Subhabrata. From subhakolkata1234 at gmail.com Mon May 24 18:08:48 2010 From: subhakolkata1234 at gmail.com (joy99) Date: Mon, 24 May 2010 15:08:48 -0700 (PDT) Subject: Question on Python Function References: Message-ID: On May 25, 1:56?am, Vlastimil Brom wrote: > 2010/5/24 joy99 : > > > > > > > > > Dear Group, > > > I have a small question on function. > > > If I write two functions like the following: > > > IDLE 2.6.5 > >>>> def function1(n): > > ? ? ? ?element1=5 > > ? ? ? ?element2=6 > > ? ? ? ?add=element1+element2 > > ? ? ? ?print "PRINT THE ADDITION",add > > >>>> def function2(n): > > ? ? ? ?element3=7 > > ? ? ? ?element4=22 > > ? ? ? ?mult=element3*element4 > > ? ? ? ?print "PRINT THE MULTIPLICATION",mult > > > Can I now write a third function where the above two functions can be > > passed as argument or parameter? > > > Best Regards, > > Subhabrata. > > > NB: As I copied the code from IDLE to MS-Word befor posting here, > > codes may have slight indentation errors. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Hi, > while it is quite unclear to me, what you are trying to achieve (what > are the passed n arguments supposed to do?), you can well pass an > already defined function as an argument to another function; if you > want to select a function for the needed operation, if can be e.g.: > > def compute(arg1, arg2, fn): > ? ? fn(arg1, arg2) > > - supposing you don't want to "return" the result but just print it as > your functions do; > is it what you were after or did I miss something more complex? > > hth > ? vbr- Hide quoted text - > > - Show quoted text - Dear Vlastimir, As pointed out by Alister, I can print the values of function1 and function2 with the help of another function3, but my target is to call the "add" value of function1 and "mult" value of function2 in a third function or the values and parameters of the third function in fourth function. While calling, I am looking not only to print, but to use them or manipulate them. I hope I am bit clear now. Best Regards, Subhabrata. From pavlovevidence at gmail.com Mon May 24 18:30:37 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 24 May 2010 15:30:37 -0700 (PDT) Subject: Most reliable/pythonic way to tell if an instance comes from a class implemented in C/etc? References: Message-ID: <20a5ca44-82b5-472d-8221-acbc86f7279f@g1g2000pro.googlegroups.com> [Following up to Terry Reedy's post since I don't see the original] On May 24, 11:30?am, Terry Reedy wrote: > On 5/24/2010 12:56 PM, Nathan Rice wrote: > > > I'm trying to do some fairly deep introspection and instrumentation of > > instances and classes at runtime, and in order for everything to be > > properly behaved I need to have radically different behavior in the > > event that the thing passed to me is a wrapped class/instance. ?Is there > > a really good way, given an instance of a class, to determine if it is > > wrapped or native? ?Currently I check to see if it has __slots__ then > > try to setattr a dummy variable but I imagine there is probably a > > cleaner way. There is no foolproof way, but the simplest and most reliable way is to check the __flags__ attribute to see if it's a heap type, which all Python new-style classes are and almost all C-defined types aren't: cls.__flags__ & 512 # Py_TPFLAGS_HEAPTYPE However, in Python 2.x, old-style classes aren't types and so don't have a __flags__ attribute, so to cover that case you should check if it's a classobj. isinstance(cls,types.ClassType) So a complete function would look something like this: def is_probably_python_class(cls): return isinstance(cls,types.ClassType) \ or (isinstance(cls,type) and cls.__flags__ & 512) It's not foolproof for a couple reasons: it's possible to define heap types in C, and it's possible to define a metatype that does things differently, but I would suppose these cases are rare. Incidentally, depending on your use case, you might find it helpful also to know whether a type is a base type (meaning that it can be subclassed). You can check that with cls.__flags__ & 1024. A complete list of flags is in the include file object.h. Note that, in order to be subclassable, a type defined in C has to behave like a Python class to a certain extent. Thus you can assume a little bit more about it. Carl Banks From ian.g.kelly at gmail.com Mon May 24 18:31:13 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 24 May 2010 16:31:13 -0600 Subject: Generator expressions vs. comprehensions Message-ID: Hi all, I just ran into an interesting but rather subtle little wart today. The following expressions are not functionally equivalent, even in Python 3: tuple(iterator.next() for i in xrange(n)) tuple([iterator.next() for i in xrange(n)]) In the first case, if iterator.next() raises a StopIteration, the exception is swallowed by the generator expression. The expression evaluates to a truncated tuple, and the StopIteration is not propagated. In the second case, the StopIteration exception is propagated as expected by the list comprehension. Set and dict comprehensions also behave this way in Python 3. Is this distinction generally known? The generator expression behavior is understandable since a generator would do the same thing, but I'm disappointed that the inconsistency exists and wasn't fixed in Python 3 when we had the chance. Cheers, Ian From pavlovevidence at gmail.com Mon May 24 18:47:32 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 24 May 2010 15:47:32 -0700 (PDT) Subject: Generator expressions vs. comprehensions References: Message-ID: On May 24, 3:31?pm, Ian Kelly wrote: > Hi all, > > I just ran into an interesting but rather subtle little wart today. > The following expressions are not functionally equivalent, even in > Python 3: > > tuple(iterator.next() for i in xrange(n)) > > tuple([iterator.next() for i in xrange(n)]) > > In the first case, if iterator.next() raises a StopIteration, the > exception is swallowed by the generator expression. ?The expression > evaluates to a truncated tuple, and the StopIteration is not > propagated. > > In the second case, the StopIteration exception is propagated as > expected by the list comprehension. ?Set and dict comprehensions also > behave this way in Python 3. > > Is this distinction generally known? ?The generator expression > behavior is understandable since a generator would do the same thing, > but I'm disappointed that the inconsistency exists and wasn't fixed in > Python 3 when we had the chance. As a general rule you shouldn't call the next() method/function without arranging to catch StopIteration, unless you know the iterator will never raise StopIteration (such as it if it itertools.count()). The problem is that if a StopIteration "leaks", as it does with the generator examples, another iterator further up the stack might catch it and exit. The situation here is known. It can't be corrected, even in Python 3, without modifying iterator protocol to tie StopIteration to a specific iterator. This is possible and might be worth it to avoid hard-to- diagnose bugs but it would complicate iterator protocol, which becomes less useful as it becomes more complex. Carl Banks From pengyu.ut at gmail.com Mon May 24 18:52:13 2010 From: pengyu.ut at gmail.com (Peng Yu) Date: Mon, 24 May 2010 17:52:13 -0500 Subject: python command line manual Message-ID: I mainly check online python manual. But I feel that it would be nice if there is command line manual available (just like perl command line manual). Could you please let me know if such command line manual available? -- Regards, Peng From clp2 at rebertia.com Mon May 24 19:10:47 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 24 May 2010 16:10:47 -0700 Subject: python command line manual In-Reply-To: References: Message-ID: On Mon, May 24, 2010 at 3:52 PM, Peng Yu wrote: > I mainly check online python manual. But I feel that it would be nice > if there is command line manual available (just like perl command line > manual). Could you please let me know if such command line manual > available? 98% sure that there isn't. You could instead use a text-based console web browser such as lynx to view the online docs to much the same effect though. Cheers, Chris From python at bdurham.com Mon May 24 19:34:59 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 24 May 2010 19:34:59 -0400 Subject: Internationalizing an application via Babel Message-ID: <1274744099.30953.1376705173@webmail.messagingengine.com> I'm evaluating Babel 0.9.5 [1] under Windows (Python 2.6) and have the following questions that I haven't been able to solve through reading the documentation or googling. 1. I would like to use an _ like abbreviation for ungettext. Is there a concencus on whether one should use n_ or N_ for this? n_ does not appear to work. Babel does not extract text. N_ appears to partially work. Babel extracts text like it does for gettext, but does not format for ngettext (missing plural argument and msgstr[ n ].) 2. Is there a way to set the initial msgstr fields like the following when creating a POT file? I suspect there may be a way to do this via Babel cfg files, but I've been unable to find documentation on the Babel cfg file format. "Project-Id-Version: PROJECT VERSION\n" "Language-Team: en_US \n" 3. Is there a way to preserve 'obsolete' msgid/msgstr's in our PO files? When I use the Babel update command, newly created obsolete strings are marked with #~ prefixes, but existing obsolete message strings get deleted. Thanks, Malcolm [1] http://babel.edgewall.org/ From robin at alldunn.com Mon May 24 19:38:45 2010 From: robin at alldunn.com (Robin Dunn) Date: Mon, 24 May 2010 16:38:45 -0700 Subject: wxPython 2.8.11.0 release Message-ID: <4BFB0E05.1090101@alldunn.com> Announcing ---------- The 2.8.11.0 release of wxPython is now available for download at http://wxpython.org/download.php. This release adds Python 2.7 builds, PySlices, new pubsub implementation, lots of updates to AGW, and lots of bugs fixed. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. Source code is available as a tarball and a source RPM, as well as binaries for Python 2.5, 2.6 and 2.7, for Windows and Mac, as well some packages for various Linux distributions. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit and 64-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+. In most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.11.0 ------------------- Lots of bug fixes in both wxWidgets and wxPython. Added the context manager protocol methods to some wx classes so they can be used with the new Python 'with' statement. (The with statement is always available starting in Python 2.6, and can also be used in Python 2.5 with a __future__ import statement.) There are several wx classes where this is a natural fit, such as wx.BusyInfo. The __enter__ and __exit__ methods have also been added to wx.Dialog where it will do the dialog.Destroy() call for you. This means that you can use code like this:: with MyDialog(self, foo, bar) as dlg: if dlg.ShowModal() == wx.ID_OK: # do something with dlg values The list of wx classes that can now be used as context managers is: * wx.Dialog * wx.BusyInfo * wx.BusyCursor * wx.WindowDisabler * wx.LogNull * wx.DCTextColourChanger * wx.DCPenChanger * wx.DCBrushChanger * wx.DCClipper A new class has been added that is also a context manager, called wx.FrozenWindow. It will freeze the window passed to it upon entry to the context, and will thaw the window upon exit from the context. Applied the final version of patch #10959 to the PyCrust code. It adds many enhancements to the Py suite, inlcuding the ability to edit blocks of code (called slices) as a whole before executing them, and also the ability to execute some simple shell commands. Replaced the wx.lib.pubsub module with the new pubsub package from http://pubsub.sf.net. By default it is backwards compatible with the old pubsub module, but it also has a more advanced API available that can be switched on at import time. See the pubsub web site for more details. The wx.Effects class is deprecated. Added Python 2.7 builds for Windows and Mac. Added Debian package builds for Ubuntu 9.10 and 10.4. Many fixes and enhancements for the wx.lib.agw pacakge, including the addition of pybusyinfo, ribbon, ultimatelistctrl and zoombar. -- Robin Dunn Software Craftsman http://wxPython.org From solipsis at pitrou.net Mon May 24 19:50:48 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Tue, 25 May 2010 01:50:48 +0200 Subject: Generator expressions vs. comprehensions References: Message-ID: <20100525015048.5e0e1e8b@pitrou.net> On Mon, 24 May 2010 15:47:32 -0700 (PDT) Carl Banks wrote: > > > > Is this distinction generally known? Yes, it is. > >?The generator expression > > behavior is understandable since a generator would do the same thing, > > but I'm disappointed that the inconsistency exists and wasn't fixed in > > Python 3 when we had the chance. Why don't you use itertools.islice()? From steve at REMOVE-THIS-cybersource.com.au Mon May 24 20:06:17 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 May 2010 00:06:17 GMT Subject: python command line manual References: Message-ID: <4bfb1479$0$27861$c3e8da3@news.astraweb.com> On Mon, 24 May 2010 17:52:13 -0500, Peng Yu wrote: > I mainly check online python manual. But I feel that it would be nice if > there is command line manual available (just like perl command line > manual). Could you please let me know if such command line manual > available? >From the shell, you can call: python --help If you are using Linux, your distro probably has also installed the Python man pages, which you access with either of: man python info python And from inside the Python interactive interpreter, you can call help(obj) to get help on any object, or just help() to enter an interactive help session. -- Steven From ith140 at gmail.com Mon May 24 21:23:37 2010 From: ith140 at gmail.com (Ian Hoffman) Date: Mon, 24 May 2010 18:23:37 -0700 (PDT) Subject: MySQL, Python, NumPy and formatted read References: Message-ID: <5a958c88-38ce-4bed-9e3c-03258f8fe9ed@o12g2000vba.googlegroups.com> On May 24, 2:11?am, Dennis Lee Bieber wrote: > On Sun, 23 May 2010 21:44:30 -0700 (PDT), Ian Hoffman > declaimed the following in gmane.comp.python.general: > > > The problem is the tuple is contained in a single value separated by > > newlines (only a[0] has a record), otherwise I could do as you > > suggest... > > >>> blob = "1\n2\n3\n4\n" > >>> tple = (blob,) > >>> tple > ('1\n2\n3\n4\n',) > >>> values = [int(f) for f in tple[0].split()] > >>> values > [1, 2, 3, 4] > > -- > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ Perfect! Thanks for your help. When I tried to do what you did, I had explictly tried to for it as an array by using the array keyword in from of the loop. Everything works, and now I can move on to my next problem. Ian From wuwei23 at gmail.com Mon May 24 21:31:09 2010 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 May 2010 18:31:09 -0700 (PDT) Subject: Chatroom References: Message-ID: "Martin P. Hellwig" wrote: > What have you tried so far? Alternatively, how much is it worth to you? From afriere at yahoo.co.uk Mon May 24 21:48:13 2010 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 24 May 2010 18:48:13 -0700 (PDT) Subject: python command line manual References: Message-ID: <66be3c90-adcd-4ddd-9f1c-5054a06e8e98@40g2000pry.googlegroups.com> On May 25, 8:52?am, Peng Yu wrote: > I mainly check online python manual. But I feel that it would be nice > if there is command line manual available (just like perl command line > manual). Could you please let me know if such command line manual > available? > > -- > Regards, > Peng It's not really a manual, but if you want the documentation written into a module try 'pydoc '. This is gives you the same output as you get running help() in the python shell. From anand.shashwat at gmail.com Mon May 24 21:52:56 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Tue, 25 May 2010 07:22:56 +0530 Subject: Chatroom In-Reply-To: References: Message-ID: seems like an academic project which is worth grades On Tue, May 25, 2010 at 7:01 AM, alex23 wrote: > "Martin P. Hellwig" wrote: > > What have you tried so far? > > Alternatively, how much is it worth to you? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon May 24 22:08:40 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 25 May 2010 03:08:40 +0100 Subject: Chatroom In-Reply-To: References: Message-ID: On 24/05/2010 19:50, narcissus wrote: > Hello , I want to create a program that is one chatroom and everyone > has this program can Enter into that chatroom. how can i do this? > > and i want gui for it too (GTK) Use your favourite editor and/or IDE to create your program, run it and when you run into problems ask here or on the Python tutor ng/ml. Regards. Mark Lawrence From michele.simionato at gmail.com Tue May 25 00:12:54 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 24 May 2010 21:12:54 -0700 (PDT) Subject: Generator expressions vs. comprehensions References: Message-ID: <86661397-d5bd-487c-9132-ae1e620fb0bf@v37g2000vbv.googlegroups.com> On May 25, 12:47?am, Carl Banks wrote: > The situation here is known. ?It can't be corrected, even in Python 3, > without modifying iterator protocol to tie StopIteration to a specific > iterator. ?This is possible and might be worth it to avoid hard-to- > diagnose bugs but it would complicate iterator protocol, which becomes > less useful as it becomes more complex. The situation here is a known and could be corrected by changing the meaning of list comprehension, for instance by having [x for x in iterable] to be an alias for list(x for x in iterable). In such a way the StopIteration exception would be always swallowed and there would be consistency with generator expressions (by construction). However, the list comprehension would become non-equivalent to the corresponding for-loop with an .append, so somebody would be un happy anyway :-/ From michele.simionato at gmail.com Tue May 25 00:15:06 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 24 May 2010 21:15:06 -0700 (PDT) Subject: help with the Python 3 version of the decorator module References: Message-ID: <1ec7ecb1-ab6d-4b88-8851-f944e7e50b60@z17g2000vbd.googlegroups.com> On May 22, 10:49?am, Michele Simionato wrote: > I have finally decided to port the decorator module to Python 3. > Changing the module was zero effort (2to3 worked) but changing the > documentation was quite an effort, since I had to wait for docutils/ > pygements to support Python 3 and to change all my custom build > process. Also, I am relying on distribute for installing on Python 3. > I would welcome feedback for people using Python 3 on various > platforms (including Windows) to see if > they can install the module and how much of effort it is. > > Here is the tarball:http://micheles.googlecode.com/files/decorator-3.2beta.tar.gz > Here is the documentation:http://micheles.googlecode.com/hg/decorator/index.html > > The installation process should work for Python 2.4, 2.5, 2.6, 2.7, > 3.0, 3.1 and all platforms were Python runs, but I have only tested it > on Linux for Python 2.6 and 3.1. The module has no relevant changes, > so I expect problems only from the building process, if any. I am not > sure of what will happen if you do not have distribute or if you have > a previous version of the module, or if you use pip or something else > (even in Python 2.X). The packaging in Python has become a real mess! > > TIA for you help, > > ? ?Michele Simionato decorator-3.2.0 has been released on PyPI: http://pypi.python.org/pypi/decorator From john.d.perkins at gmail.com Tue May 25 00:34:25 2010 From: john.d.perkins at gmail.com (Six) Date: Mon, 24 May 2010 21:34:25 -0700 (PDT) Subject: Drilling down in a dict with "complex" objects Message-ID: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> I am trying to access an objects sub-object attributes. I can boil the code I am working with down to this problem section: (snip) class Pt: x = None y = None def __init__(self, x, y): self.x, self.y = x, y pass class Pts: curr_point = None next_point = None def __init__(self, n, m): self.next_point = Pt(n, m) def update(self, point): self.curr_point = self.next_point self.next_point = point class PtManage: points = {} def __init__(self): pass point = Pts(3,5) pman = PtManage() pman.points["odds"] = point print dir(pman) print pman["odds"].next_point.x (snip) It's this last line that doesn't work. What am I doing wrong? Is this a failure of the design or am I missing something obvious? How do I get down and see that "Pt" classes x attribute within the PtManage dict? From zak.mc.kraken at libero.it Tue May 25 01:15:36 2010 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Tue, 25 May 2010 07:15:36 +0200 Subject: python command line manual References: Message-ID: Peng Yu wrote: > I mainly check online python manual. But I feel that it would be nice > if there is command line manual available (just like perl command line > manual). Could you please let me know if such command line manual > available? pydoc? -- By ZeD From half.italian at gmail.com Tue May 25 01:17:46 2010 From: half.italian at gmail.com (Sean DiZazzo) Date: Mon, 24 May 2010 22:17:46 -0700 (PDT) Subject: Drilling down in a dict with "complex" objects References: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> Message-ID: <0c8b6296-9c10-491f-a630-59c857b5a8d7@y18g2000prn.googlegroups.com> On May 24, 9:34?pm, Six wrote: > I am trying to access an objects sub-object attributes. I can boil the > code I am working with down to this problem section: > (snip) > class Pt: > ? x = None > ? y = None > ? def __init__(self, x, y): > ? ? self.x, self.y = x, y > ? pass > > class Pts: > ? curr_point = None > ? next_point = None > ? def __init__(self, n, m): > ? ? self.next_point = Pt(n, m) > ? def update(self, point): > ? ? self.curr_point = self.next_point > ? ? self.next_point = point > > class PtManage: > ? points = {} > ? def __init__(self): > ? ? pass > > point = Pts(3,5) > pman = PtManage() > pman.points["odds"] = point > print dir(pman) > > print pman["odds"].next_point.x > > (snip) > > It's this last line that doesn't work. What am I doing wrong? Is this > a failure of the design or am I missing something obvious? How do I > get down and see that "Pt" classes x attribute within the PtManage > dict? Don't you mean? pman.points["odds"].next_point.x From benjamin.kaplan at case.edu Tue May 25 01:25:52 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 24 May 2010 22:25:52 -0700 Subject: Drilling down in a dict with "complex" objects In-Reply-To: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> References: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> Message-ID: On Mon, May 24, 2010 at 9:34 PM, Six wrote: > I am trying to access an objects sub-object attributes. I can boil the > code I am working with down to this problem section: > (snip) > class Pt: > ?x = None > ?y = None > ?def __init__(self, x, y): > ? ?self.x, self.y = x, y > ?pass > > class Pts: > ?curr_point = None > ?next_point = None First of all, don't do this. Python doesn't have variable declarations, only assignments. So this creates a variable called curr_point for the *class*, not for the instance. What Java calls static variables. It doesn't matter here but... > ?def __init__(self, n, m): > ? ?self.next_point = Pt(n, m) > ?def update(self, point): > ? ?self.curr_point = self.next_point > ? ?self.next_point = point > > class PtManage: > ?points = {} Here you have a single mutable dict shared by all instances of PtManage. a = PtManage() b = PtManage() a.points["a"] = Pts(3,2) print b.points > ?def __init__(self): > ? ?pass > > point = Pts(3,5) > pman = PtManage() > pman.points["odds"] = point > print dir(pman) > > print pman["odds"].next_point.x PtManage doesn't define __getitem__, so pman["odds"] won't work. pman.points["odds"] should. > > (snip) > > It's this last line that doesn't work. What am I doing wrong? Is this > a failure of the design or am I missing something obvious? How do I > get down and see that "Pt" classes x attribute within the PtManage > dict? > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Tue May 25 01:27:53 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 May 2010 01:27:53 -0400 Subject: Drilling down in a dict with "complex" objects In-Reply-To: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> References: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> Message-ID: On 5/25/2010 12:34 AM, Six wrote: > [snip] > It's this last line that doesn't work. What am I doing wrong? When posting such questios, print the traceback if there is one or otherwise describe 'does not work' in much more detail. From clp2 at rebertia.com Tue May 25 01:33:44 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 24 May 2010 22:33:44 -0700 Subject: Drilling down in a dict with "complex" objects In-Reply-To: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> References: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> Message-ID: On Mon, May 24, 2010 at 9:34 PM, Six wrote: > I am trying to access an objects sub-object attributes. I can boil the > code I am working with down to this problem section: > (snip) > class Pt: > ?x = None > ?y = None > ?def __init__(self, x, y): > ? ?self.x, self.y = x, y > ?pass > > class Pts: > ?curr_point = None > ?next_point = None > ?def __init__(self, n, m): > ? ?self.next_point = Pt(n, m) > ?def update(self, point): > ? ?self.curr_point = self.next_point > ? ?self.next_point = point > > class PtManage: > ?points = {} > ?def __init__(self): > ? ?pass > > point = Pts(3,5) > pman = PtManage() > pman.points["odds"] = point > print dir(pman) > > print pman["odds"].next_point.x > > (snip) > > It's this last line that doesn't work. What am I doing wrong? Is this > a failure of the design or am I missing something obvious? How do I > get down and see that "Pt" classes x attribute within the PtManage > dict? I suggest you read the part of Python's tutorial concerning classes (http://docs.python.org/tutorial/classes.html ). Note that "curr_point = None" and similar at the class level *does not* declare an object field, because Python does not have instance variable declarations. Here is a fixed and normalized version of the classes in your example: class Pt(object): def __init__(self, x, y): self.x, self.y = x, y class Pts(object): def __init__(self, n, m): self.curr_point = None self.next_point = Pt(n, m) def update(self, point): self.curr_point = self.next_point self.next_point = point class PtManage(object): def __init__(self): self.points = {} As for why your last line fails: > print pman["odds"].next_point.x As Sean said, you're missing a ".points": print pman.points["odds"].next_point.x Also, is there any reason for PtManage over just using a `points` dictionary directly? Cheers, Chris -- http://blog.rebertia.com From kushal.kumaran+python at gmail.com Tue May 25 02:30:58 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 25 May 2010 12:00:58 +0530 Subject: Question on Python Function In-Reply-To: References: Message-ID: On Tue, May 25, 2010 at 3:38 AM, joy99 wrote: > > > Dear Vlastimir, > > As pointed out by Alister, I can print the values of function1 and > function2 with the help of another function3, but my target is to call > the "add" value of function1 and "mult" value of function2 in a third > function or the values and parameters of the third function in fourth > function. While calling, I am looking not only to print, but to use > them or manipulate them. > > I hope I am bit clear now. > If you need to use the values in another function, you need a way to let that function get its hands on the values. Your function1 and function2 should return the values they compute instead of printing them out. -- regards, kushal From __peter__ at web.de Tue May 25 03:08:56 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 May 2010 09:08:56 +0200 Subject: Generator expressions vs. comprehensions References: <86661397-d5bd-487c-9132-ae1e620fb0bf@v37g2000vbv.googlegroups.com> Message-ID: Michele Simionato wrote: > On May 25, 12:47 am, Carl Banks wrote: >> The situation here is known. It can't be corrected, even in Python 3, >> without modifying iterator protocol to tie StopIteration to a specific >> iterator. This is possible and might be worth it to avoid hard-to- >> diagnose bugs but it would complicate iterator protocol, which becomes >> less useful as it becomes more complex. > > The situation here is a known and could be corrected by changing the > meaning of list comprehension, > for instance by having [x for x in iterable] to be an alias for list(x > for x in iterable). In such a way the StopIteration exception would be > always swallowed and there would be consistency with generator > expressions (by construction). However, the list comprehension would > become non-equivalent to the corresponding for-loop with an .append, > so somebody would be un happy anyway :-/ But the list comprehension is already non-equivalent to the for loop as the loop variable isn't leaked anymore. We do have three similar constructs with subtle differences. I think not turning the list-comp into syntactic sugar for list(genexp) in py3 is a missed opportunity. Peter From __peter__ at web.de Tue May 25 03:18:15 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 May 2010 09:18:15 +0200 Subject: Question on Python Function References: Message-ID: Kushal Kumaran wrote: > On Tue, May 25, 2010 at 3:38 AM, joy99 wrote: >> >> >> Dear Vlastimir, >> >> As pointed out by Alister, I can print the values of function1 and >> function2 with the help of another function3, but my target is to call >> the "add" value of function1 and "mult" value of function2 in a third >> function or the values and parameters of the third function in fourth >> function. While calling, I am looking not only to print, but to use >> them or manipulate them. >> >> I hope I am bit clear now. >> > > If you need to use the values in another function, you need a way to > let that function get its hands on the values. Your function1 and > function2 should return the values they compute instead of printing > them out. For example: >>> def add(x, y): ... return x + y ... >>> def mul(x, y): ... return x * y ... >>> def sum_of_squares(x, y): ... return add(mul(x, x), mul(y, y)) ... >>> sum_of_squares(3, 4) 25 OP: If that addresses your question I suggest that you work through some introductory text about python. The python wiki has a few suggestions, see http://wiki.python.org/moin/BeginnersGuide Peter From michele.simionato at gmail.com Tue May 25 03:26:18 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 25 May 2010 00:26:18 -0700 (PDT) Subject: Generator expressions vs. comprehensions References: <86661397-d5bd-487c-9132-ae1e620fb0bf@v37g2000vbv.googlegroups.com> Message-ID: <2fbbec16-0070-4284-b78b-f8f11a676dd3@a16g2000vbr.googlegroups.com> On May 25, 9:08?am, Peter Otten <__pete... at web.de> wrote: > But the list comprehension is already non-equivalent to the for loop as the > loop variable isn't leaked anymore. We do have three similar constructs with > subtle differences. > > I think not turning the list-comp into syntactic sugar for list(genexp) in > py3 is a missed opportunity. Actually I do agree with the feeling, and this is not the only missed opportunity in Python 3 :-/ From jeanmichel at sequans.com Tue May 25 04:24:07 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 25 May 2010 10:24:07 +0200 Subject: function that counts... In-Reply-To: <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> Message-ID: <4BFB8927.8050006@sequans.com> superpollo wrote: > Jean-Michel Pichavant ha scritto: >> Jerry Hill wrote: >>> On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: >>> >>>> ... how many positive integers less than n have digits that sum up >>>> to m: >>>> >>> ... >>> >>>> any suggestion for pythonizin' it? >>>> >>> >>> This is how I would do it: >>> >>> def prttn(m, n): >>> """How many positive integers less than n have digits that sum >>> up to m""" >>> total = 0 >>> for testval in range(n): >>> sumofdigits = sum(int(char) for char in str(testval)) >>> if sumofdigits == m: >>> total += 1 >>> return total >>> >>> I added a docstring to the function, saying what it does, and what the >>> arguments are supposed to represent. I also moved the >>> convert-to-string-and-sum-the-digits logic into a single generator >>> expression that's passed to the builtin sum function. Oh, and I tried >>> to use slightly more expressive variable names. >>> >>> >> my favorite solutio nso far. >> >> @ OP >> >> What means prttn ? > > i already answered this downthreads... > >> something ... I don't find the word, something like un-intuitive. >> Sounds like homework. > > it is not. My apologies then, for both statements. I still don't see "how many positive integers less than n have digits that sum up to m" makes it a "partition" though if that what prttn means. Surely because I miss the context. JM From kaklis at gmail.com Tue May 25 04:42:06 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 25 May 2010 01:42:06 -0700 (PDT) Subject: asyncore loop and cmdloop problem Message-ID: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> Hi to all, i'm creating a command line application using asyncore and cmd. At if __name__ == '__main__': import socket args = sys.argv[1:] if not args: print "Usage: %s querystring" % sys.argv[0] sys.exit(0) address = ('localhost', 0) # let the kernel give us a port server = EchoServer(address) ip, port = server.address # find out what port we were given asyncore.loop() CmdClass().cmdloop() what i want is that the above commands asyncore.loop() and CmdClass().cmdloop() running at the same time. Meaning that while the application is in cmd mode with the cmdloop(), it is still able to listen for incoming messages? What should i do? thanks in advance A.K. From farina.ch at gmail.com Tue May 25 04:50:16 2010 From: farina.ch at gmail.com (fari) Date: Tue, 25 May 2010 01:50:16 -0700 (PDT) Subject: how to run brill tagger on urdu corpus? Message-ID: I like to run brill demo function with urdu pos tagged i have urdu corpus reader and a POS tagged file can you help me. 1) how and where i need to define templates for urdu . Is template dat are given with nltk(brill) are compatible to run with urdu. 2) If i want to run brill demo function on urdu tag what should i do ? waiting for reply plzzzzz. From salilgk at gmail.com Tue May 25 04:54:20 2010 From: salilgk at gmail.com (Salil GK) Date: Tue, 25 May 2010 14:24:20 +0530 Subject: Help regarding XML file manipulation Message-ID: Hello I need to make a quick prototype to process some xml file. I found xml.dom.minidom much handy and I can get information from the xml file. But I need to update a filed in the xml file and save the file. I couldn't find a way to do that. Could some one please help me on this. Basically this is what I want to do Hari 102010 201010 Rama 102010 201010 Here I want to read the Engineer information and then change the NextLeave information to a new value and save to the same file. How do we do this - can some one please help me with some sample code for the same. Thanks ~S -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Tue May 25 04:55:30 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 25 May 2010 01:55:30 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> Message-ID: <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> On May 25, 10:42?am, "kak... at gmail.com" wrote: > Hi to all, > i'm creating a command line application using asyncore and cmd. At > > if __name__ == '__main__': > ? ? import socket > > ? ? args = sys.argv[1:] > ? ? if not args: > ? ? ? ? print "Usage: %s querystring" % sys.argv[0] > ? ? ? ? sys.exit(0) > > ? ? address = ('localhost', 0) # let the kernel give us a port > ? ? server = EchoServer(address) > ? ? ip, port = server.address # find out what port we were given > > ? ? asyncore.loop() > ? ? CmdClass().cmdloop() > > what i want is that the above commands asyncore.loop() and > CmdClass().cmdloop() > running at the same time. Meaning that while the application is in cmd > mode > with the cmdloop(), it is still able to listen for incoming messages? > What should i do? > > thanks in advance > A.K. cmd.Cmd is blocking, so the only way it to run the cmdloop in a separated thread. Once for fun I rewrote the cmd module to be non-blocking but if you want to stick with the standard library you need to use a thread. From jimmy.cullen at gmail.com Tue May 25 05:00:30 2010 From: jimmy.cullen at gmail.com (Jimoid) Date: Tue, 25 May 2010 02:00:30 -0700 (PDT) Subject: Reading data from a Microsoft Access 2003 database References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> <4bf3eeeb$0$31263$607ed4bc@cv.net> <3c40f8d8-b29c-484f-b5b3-6dff0f68a032@m21g2000vbr.googlegroups.com> <16c9daac-293a-4cb6-b847-489e696682bd@c11g2000vbe.googlegroups.com> <85rh6gF8ceU1@mid.individual.net> Message-ID: <6d054b62-e79e-40c2-936e-540a61a9a50d@v37g2000vbv.googlegroups.com> This is perfect if the python ODBC driver can read the .mdb without the need for it to be running elsewhere. Thanks all for your help. From shashank.sunny.singh at gmail.com Tue May 25 05:29:12 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Tue, 25 May 2010 14:59:12 +0530 Subject: Help regarding XML file manipulation In-Reply-To: References: Message-ID: On Tue, May 25, 2010 at 2:24 PM, Salil GK wrote: > Hello > > I need to make a quick prototype to process some xml file. I found > xml.dom.minidom much handy and I can get information from the xml file. But > I need to update a filed in the xml file and save the file. I couldn't find > a way to do that. Could some one please help me on this. > > Basically this is what I want to do > > > > > Hari > 102010 > 201010 > > Rama > 102010 > 201010 > > > > > Here I want to read the Engineer information and then change the NextLeave > information to a new value and save to the same file. How do we do this - > can some one please help me with some sample code for the same. > have a look at the xml.dom.minidom module. You can access nodes by getElementsByTagName("Engineer") Access value of the text node by node.nodeValue To modify the xml, you will have to set the node value to the desired value node.nodeValue = newValue Note that to you will have to write the modified dom object back to the file to save the changes, just setting the value of nodes will not automatically do that. HTH -S > > Thanks > ~S > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From kaklis at gmail.com Tue May 25 05:53:12 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 25 May 2010 02:53:12 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> Message-ID: <57fb8b26-d327-4a93-8d14-78f6905e39ac@y21g2000vba.googlegroups.com> On May 25, 4:55?am, Michele Simionato wrote: > On May 25, 10:42?am, "kak... at gmail.com" wrote: > > > > > Hi to all, > > i'm creating a command line application using asyncore and cmd. At > > > if __name__ == '__main__': > > ? ? import socket > > > ? ? args = sys.argv[1:] > > ? ? if not args: > > ? ? ? ? print "Usage: %s querystring" % sys.argv[0] > > ? ? ? ? sys.exit(0) > > > ? ? address = ('localhost', 0) # let the kernel give us a port > > ? ? server = EchoServer(address) > > ? ? ip, port = server.address # find out what port we were given > > > ? ? asyncore.loop() > > ? ? CmdClass().cmdloop() > > > what i want is that the above commands asyncore.loop() and > > CmdClass().cmdloop() > > running at the same time. Meaning that while the application is in cmd > > mode > > with the cmdloop(), it is still able to listen for incoming messages? > > What should i do? > > > thanks in advance > > A.K. > > cmd.Cmd is blocking, so the only way it to run the cmdloop in a > separated thread. Once for fun > I rewrote the cmd module to be non-blocking but if you want to stick > with the standard library you need to use a thread. Thank you so much. Is there a way that i can find that version of cmd? Antonis From g.rodola at gmail.com Tue May 25 06:03:22 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Tue, 25 May 2010 12:03:22 +0200 Subject: asyncore loop and cmdloop problem In-Reply-To: <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> Message-ID: 2010/5/25 Michele Simionato : > On May 25, 10:42?am, "kak... at gmail.com" wrote: >> Hi to all, >> i'm creating a command line application using asyncore and cmd. At >> >> if __name__ == '__main__': >> ? ? import socket >> >> ? ? args = sys.argv[1:] >> ? ? if not args: >> ? ? ? ? print "Usage: %s querystring" % sys.argv[0] >> ? ? ? ? sys.exit(0) >> >> ? ? address = ('localhost', 0) # let the kernel give us a port >> ? ? server = EchoServer(address) >> ? ? ip, port = server.address # find out what port we were given >> >> ? ? asyncore.loop() >> ? ? CmdClass().cmdloop() >> >> what i want is that the above commands asyncore.loop() and >> CmdClass().cmdloop() >> running at the same time. Meaning that while the application is in cmd >> mode >> with the cmdloop(), it is still able to listen for incoming messages? >> What should i do? >> >> thanks in advance >> A.K. > > cmd.Cmd is blocking, so the only way it to run the cmdloop in a > separated thread. Once for fun > I rewrote the cmd module to be non-blocking but if you want to stick > with the standard library you need to use a thread. > -- > http://mail.python.org/mailman/listinfo/python-list > Too bad cmdloop() doesn't provide an argument to return immediately. Why don't you submit this patch on the bug tracker? --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From michele.simionato at gmail.com Tue May 25 06:20:29 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 25 May 2010 03:20:29 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> Message-ID: <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> On May 25, 12:03?pm, Giampaolo Rodol? wrote: > Too bad cmdloop() doesn't provide an argument to return immediately. > Why don't you submit this patch on the bug tracker? > > --- Giampaolohttp://code.google.com/p/pyftpdlibhttp://code.google.com/p/psutil Because it is not a bug, cmd was designed to be blocking. It would be a feature request. I wrote a cmd2 module a few years ago, which was intended as a replacement for cmd with various additional features (including the non blocking behavior). We are using it in production, but I have never published it (I intended to but, you know, a days has only 24 hours ;) I should put together the code in a single file and publish it, but I cannot guarantee if and when I will have the time to do so. From g.rodola at gmail.com Tue May 25 06:48:40 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Tue, 25 May 2010 12:48:40 +0200 Subject: asyncore loop and cmdloop problem In-Reply-To: <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> Message-ID: 2010/5/25 Michele Simionato : > On May 25, 12:03?pm, Giampaolo Rodol? wrote: >> Too bad cmdloop() doesn't provide an argument to return immediately. >> Why don't you submit this patch on the bug tracker? >> >> --- Giampaolohttp://code.google.com/p/pyftpdlibhttp://code.google.com/p/psutil > > Because it is not a bug, cmd was designed to be blocking. It would be > a feature request. Sure, a feature request, but it would be nice to have anyway. =) The OP question shown how this can be desirable in certain circumstances.. --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From tom.browder at gmail.com Tue May 25 07:17:53 2010 From: tom.browder at gmail.com (Tom Browder) Date: Tue, 25 May 2010 06:17:53 -0500 Subject: [wxPython-users] wxPython 2.8.11.0 release In-Reply-To: <4BFB0E05.1090101@alldunn.com> References: <4BFB0E05.1090101@alldunn.com> Message-ID: On Mon, May 24, 2010 at 18:38, Robin Dunn wrote: ... > The 2.8.11.0 release of wxPython is now available for download at > http://wxpython.org/download.php. This release adds Python 2.7 builds, > PySlices, new pubsub implementation, lots of updates to AGW, and lots > of bugs fixed. ?A summary of changes is listed below and also at > http://wxpython.org/recentchanges.php. Has the port to python 3 problem been solved in the development line, or is help still looked for there? See this Nov 19, 2009 msg: http://groups.google.com/group/wxpython-users/browse_thread/thread/86f8b2513941d0f4/6d77c3d4ebd0e919?lnk=gst&q=python+3#6d77c3d4ebd0e919 Thanks, -Tom From utente at esempio.net Tue May 25 07:28:22 2010 From: utente at esempio.net (superpollo) Date: Tue, 25 May 2010 13:28:22 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> Message-ID: <4bfbb456$0$18992$4fafbaef@reader5.news.tin.it> Jean-Michel Pichavant ha scritto: > superpollo wrote: >> Jean-Michel Pichavant ha scritto: >>> Jerry Hill wrote: >>>> On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: >>>> >>>>> ... how many positive integers less than n have digits that sum up >>>>> to m: >>>>> >>>> ... >>>> >>>>> any suggestion for pythonizin' it? >>>>> >>>> >>>> This is how I would do it: >>>> >>>> def prttn(m, n): >>>> """How many positive integers less than n have digits that sum >>>> up to m""" >>>> total = 0 >>>> for testval in range(n): >>>> sumofdigits = sum(int(char) for char in str(testval)) >>>> if sumofdigits == m: >>>> total += 1 >>>> return total >>>> >>>> I added a docstring to the function, saying what it does, and what the >>>> arguments are supposed to represent. I also moved the >>>> convert-to-string-and-sum-the-digits logic into a single generator >>>> expression that's passed to the builtin sum function. Oh, and I tried >>>> to use slightly more expressive variable names. >>>> >>>> >>> my favorite solutio nso far. >>> >>> @ OP >>> >>> What means prttn ? >> >> i already answered this downthreads... >> >>> something ... I don't find the word, something like un-intuitive. >>> Sounds like homework. >> >> it is not. > My apologies then, for both statements. > I still don't see "how many positive integers less than n have digits > that sum up to m" makes it a "partition" though if that what prttn > means. Surely because I miss the context. > > JM ok, this is the mistery. it was inspired by a question on e.c.m.: http://groups.google.it/group/es.ciencia.matematicas/msg/f8f09672bd8a052a the first question is (somewhat) an instance of: http://en.wikipedia.org/wiki/Partition_(number_theory) bye From kaklis at gmail.com Tue May 25 08:56:02 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 25 May 2010 05:56:02 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> Message-ID: <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> On May 25, 6:48?am, Giampaolo Rodol? wrote: > 2010/5/25 Michele Simionato : > > > On May 25, 12:03?pm, Giampaolo Rodol? wrote: > >> Too bad cmdloop() doesn't provide an argument to return immediately. > >> Why don't you submit this patch on the bug tracker? > > >> --- Giampaolohttp://code.google.com/p/pyftpdlibhttp://code.google.com/p/psutil > > > Because it is not a bug, cmd was designed to be blocking. It would be > > a feature request. > > Sure, a feature request, but it would be nice to have anyway. =) > The OP question shown how this can be desirable in certain circumstances.. > > --- Giampaolohttp://code.google.com/p/pyftpdlibhttp://code.google.com/p/psutil Could you please provide me with a simple example how to do this with threads. I don't know where to put the cmdloop(). Please help, i' m so confused! Thank you From victorsubervi at gmail.com Tue May 25 09:30:13 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 25 May 2010 09:30:13 -0400 Subject: A Quick MySQL Question In-Reply-To: References: Message-ID: On Tue, May 25, 2010 at 3:50 AM, Dennis Lee Bieber wrote: > On Mon, 24 May 2010 13:37:58 -0400, Victor Subervi > declaimed the following in > Parameterized queries process the parameters to ensure that they are > safe for use in the SQL statement. > > In the case of the MySQLdb adapter (written to be compatible with > pre-version 5 of MySQL) this means that the parameters are converted to > a string representation (if not already a string), characters in the > parameter that are significant to the MySQL dialect of SQL are safely > escaped, AND the resulting string is WRAPPED in quote marks. > > k. That worked. Thanks! > I suggest you study the SQL standard "like" comparison, and the use > of wildcards with it. Consider a "card catalog" application and how one > would formulate a query in which the author's last name is "Norton", and > the title of the book contains the word "Witch" (the word could be > anywhere within the title). > I understand how to do "like" queries and use wildcards. I didn't understand what you were doing over there, something with %values% or some such. If you care to pick up that thread, fine, otherwise, until the next time. Thanks you as always, Dennis :) beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From cde3 at live.com Tue May 25 09:49:46 2010 From: cde3 at live.com (Sandy Ydnas) Date: Tue, 25 May 2010 18:49:46 +0500 Subject: to prevent reveres engineering for Python In-Reply-To: <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com>, , <87mxvsfzvh.fsf@benfinney.id.au>, <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: Agree, reveres engineering is crucial issuer for programming language but every executable file can be cracked, for example by using disassembler!!! For each weapon there is antiweapon, so is it possible to prevent reveres engineering when customer have access to executable made from Python code??? Regards Sandy > From: pmaupin at gmail.com > Subject: Re: where are the program that are written in python? > Date: Fri, 21 May 2010 23:29:37 -0700 > To: python-list at python.org > > On May 21, 9:12 pm, Ben Finney wrote: > > a... at pythoncraft.com (Aahz) writes: > > > In article , > > > Patrick Maupin wrote: > > > > > >There are a lot of commercial programs written in Python. But any > > > >company which thinks it has a lock on some kind of super secret sauce > > > >isn't going to use Python, because it's very easy to reverse engineer > > > >even compiled Python programs. > > > > > That's not always true. Both my employer (Egnyte) and one of our main > > > competitors (Dropbox) use Python in our clients. We don't care much > > > because using our servers is a requirement of the client. > > > > Doesn't that mean those companies don't fit the above description? That > > is, neither of them ?thinks it has a lock on some kind of super secret > > sauce? in the programs. So they don't seem to be counter-examples. > > Just because someone has competition doesn't mean they don't think > they have secret sauce. I think Aahz's main point was that in his sub- > industry, the secret sauce is guarded by not actually letting the > customer have access to executable code, other than through the > network. > > Regards, > Pat > -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Hotmail: Trusted email with Microsoft?s powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Tue May 25 10:23:58 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 25 May 2010 07:23:58 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> Message-ID: <1fc2db40-42c3-40d7-ab92-b29c6c039345@u7g2000vbq.googlegroups.com> On May 25, 2:56?pm, "kak... at gmail.com" wrote: > Could you please provide me with a simple example how to do this with > threads. > I don't know where to put the cmdloop(). > Please help, i' m so confused! > Thank you What are you trying to do? Do you really need to use the standard library? Likely what you want to accomplish is already implemented in Twisted; I remember there was something like that in their examples directory. From kaklis at gmail.com Tue May 25 10:47:06 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 25 May 2010 07:47:06 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> <1fc2db40-42c3-40d7-ab92-b29c6c039345@u7g2000vbq.googlegroups.com> Message-ID: On May 25, 5:23?pm, Michele Simionato wrote: > On May 25, 2:56?pm, "kak... at gmail.com" wrote: > > > Could you please provide me with a simple example how to do this with > > threads. > > I don't know where to put the cmdloop(). > > Please help, i' m so confused! > > Thank you > > What are you trying to do? Do you really need to use the standard > library? Likely what you want to accomplish is already implemented in > Twisted; I remember there was something like that in their examples > directory. Thank you, and sorry for the mistake i did before with my post. Antonis From awilliam at whitemice.org Tue May 25 11:09:03 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 25 May 2010 11:09:03 -0400 Subject: to prevent reveres engineering for Python In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> , , <87mxvsfzvh.fsf@benfinney.id.au> , <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: <1274800143.9273.31.camel@linux-yu4c.site> On Tue, 2010-05-25 at 18:49 +0500, Sandy Ydnas wrote: > Agree, reveres engineering is crucial issuer for programming > language > but every executable file can be cracked, for example by using > disassembler!!! > For each weapon there is antiweapon, so > is it possible to prevent reveres engineering when customer have > access to executable made from Python code??? No. But you can make it hard. Store a GPG encrypted blob in your program that contains you secret sauce, is decrypted to memory, executed, and then discarded. Setup some kind of license manager like dongle or application to perform the key management. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From kaklis at gmail.com Tue May 25 12:31:03 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 25 May 2010 09:31:03 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> <1fc2db40-42c3-40d7-ab92-b29c6c039345@u7g2000vbq.googlegroups.com> Message-ID: <0123253e-f628-471b-a343-0ad2588b1a20@m33g2000vbi.googlegroups.com> On May 25, 5:47?pm, "kak... at gmail.com" wrote: > On May 25, 5:23?pm, Michele Simionato > wrote: > > > On May 25, 2:56?pm, "kak... at gmail.com" wrote: > > > > Could you please provide me with a simple example how to do this with > > > threads. > > > I don't know where to put the cmdloop(). > > > Please help, i' m so confused! > > > Thank you > > > What are you trying to do? Do you really need to use the standard > > library? Likely what you want to accomplish is already implemented in > > Twisted; I remember there was something like that in their examples > > directory. > > Thank you, > and sorry for the mistake i did before with my post. > > Antonis hi again. i installed twisted, but since i m not familiar with it, do you remember which example you have in mind? What i want to accomplish is something like "asterisk". while you send commands from the asterisk cli, at the same time the underlying protocol sends you notifications to the console. without exiting the application. thanks From tjreedy at udel.edu Tue May 25 13:09:23 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 May 2010 13:09:23 -0400 Subject: Generator expressions vs. comprehensions In-Reply-To: References: <86661397-d5bd-487c-9132-ae1e620fb0bf@v37g2000vbv.googlegroups.com> Message-ID: On 5/25/2010 3:08 AM, Peter Otten wrote: > Michele Simionato wrote: > I think not turning the list-comp into syntactic sugar for list(genexp) in > py3 is a missed opportunity. Implementing it that way was tried but was much slower than the current implementation. If one uses StopIteration as it is intended to be used (and is so documented), then, I believe, they are equivalent. There was a conscious decision to not slow comprehensions for the many to cater to the very few. Terry Jan Reedy From tjreedy at udel.edu Tue May 25 13:16:02 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 May 2010 13:16:02 -0400 Subject: to prevent reveres engineering for Python In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com>, , <87mxvsfzvh.fsf@benfinney.id.au>, <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: On 5/25/2010 9:49 AM, Sandy Ydnas wrote: > is it possible to prevent reveres engineering when customer have access > to executable made from Python code??? If there is, it is a trade secrets that you will not be able to reverse engineer ;-). From tjreedy at udel.edu Tue May 25 13:19:50 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 May 2010 13:19:50 -0400 Subject: Generator expressions vs. comprehensions In-Reply-To: References: <86661397-d5bd-487c-9132-ae1e620fb0bf@v37g2000vbv.googlegroups.com> Message-ID: On 5/25/2010 1:09 PM, Terry Reedy wrote: > On 5/25/2010 3:08 AM, Peter Otten wrote: >> Michele Simionato wrote: > >> I think not turning the list-comp into syntactic sugar for >> list(genexp) in >> py3 is a missed opportunity. > > Implementing it that way was tried but was much slower than the current > implementation. If one uses StopIteration as it is intended to be used > (and is so documented), then, I believe, they are equivalent. There was > a conscious decision to not slow comprehensions for the many to cater to > the very few. And those few can always write list(genexp) instead of [genexp] (or set...) when the minute difference actually matters. > Terry Jan Reedy > From chambon.pascal at wanadoo.fr Tue May 25 13:46:56 2010 From: chambon.pascal at wanadoo.fr (Pascal Chambon) Date: Tue, 25 May 2010 19:46:56 +0200 Subject: Troubles with python internationalization Message-ID: <4BFC0D10.4060002@wanadoo.fr> Hello I'm studying the migration of my website (mixed english and french languages...) to a properly localized architecture. From what I've read so far, using translation "tags" (or quick phrases) in the code, and translating them to every target language (including english) sounds a better approach than using, for example, final english wordings as translation tags. The setup is longer via the first way, but at least if you change english wordings later, you don't break all other translations at the same time. However, I still have problems with some aspects of internationalization: * code safety : it seems default python string formatting technics (% operator, .format() method) are normally used when one needs to substitute placeholders in translated strings. But the thing is : I DONT want my view to raise an exception simply because one of the translations has forgotten a damn "%(myvar)s" placeholder. The only quick fix I can think of, is to always use substitution through defaultdicts instances (and still, exceptions could occur if abnormal "%s" placeholders are found in the translated string). Are there some utilities in python, or frameworks like django, to allow a safe string substitution (which might, for example, simply log an error if a buggy string si found) ? Python's template strings' "safe_substitute()" won't fit, because it swallows errors without any notice... * unknown translatable strings : I have in different data files (eg. yaml), strings which will need translation, but that can't be detected by gettext and co, since they only appear in the code as variable i.e "_(yamlvar)". The easiest, I guess, would be to replace them by specific tags (like "TR_HOMEPAGE_TITLE"), and to have a tool browse the code to extract them and add them to the standard gettext translation chain. Such a tool shouldn't be too hard to code, but I'd rather know : doesn't such a tool already exist somewhere ? I've seen no such mention in gettext or babel tools, only recogniztion via function calls ( _(), tr()... ). * I have seen nowhere mention of how to remove deprecated/unused strings from gettext files - only merging translations seems to interest people. However, having a translation file which slowly fills itself with outdated data doesn't sound cool to me. Does anyone know tools/program flags which would list/extract translations that don't seem used anymore ? Thanks for you help, regards, Pascal From victorsubervi at gmail.com Tue May 25 14:45:16 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 25 May 2010 14:45:16 -0400 Subject: Another Little MySQL Problem Message-ID: Hi; I have this code: clientCursor.execute('select ID from %s' % (personalDataTable)) upds = [itm[0] for itm in clientCursor] print "" % upds The problem is that the values passed are 1L, 2L.... When I retrieve them on the other end and try to convert them to integers, guess what happens? So how do I get rid of that "L"? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From picture017 at gmail.com Tue May 25 15:00:54 2010 From: picture017 at gmail.com (Minhaz Rahman) Date: Tue, 25 May 2010 12:00:54 -0700 (PDT) Subject: Legal Point Dhaka bangladesh Message-ID: <0e1e6d28-fedb-4d43-9f02-7019cb88859b@k31g2000vbu.googlegroups.com> http://www.advocatemizan.com From zasaconsulting at gmail.com Tue May 25 15:05:53 2010 From: zasaconsulting at gmail.com (Alexzive) Date: Tue, 25 May 2010 12:05:53 -0700 (PDT) Subject: speed up a numpy code with huge array Message-ID: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> Hello Pythonguys! is there a way to improve the performance of the attached code ? it takes about 5 h on a dual-core (using only one core) when len(V) ~1MIL. V is an array which is supposed to store all the volumes of tetrahedral elements of a grid whose coord. are stored in NN (accessed trough the list of tetraelements --> EL) Thanks in advance! Alex #### print 'start ' + nameodb #path = '/windows/D/SIM-MM/3D/E_ortho/' + nameodb + '.odb' path = pt + nameodb + '.odb' odb = openOdb(path) N = odb.rootAssembly.instances['PART-1-1'].nodes if loadV==1: pathV=pt+vtet V=numpy.loadtxt(pathV) VTOT = V[0] L3 = V[1] print 'using ' + vtet else: NN=[] B=[0,0,0,0] for i in range(len(N)): B[0] = N[i].label B[1] = N[i].coordinates[0] B[2] = N[i].coordinates[1] B[3] = N[i].coordinates[2] NN = append(NN,B) NN=NN.reshape(-1,4) EL = odb.rootAssembly.instances['PART-1-1'].elements L1 = max(NN[:,1])-min(NN[:,1]) L2 = max(NN[:,2])-min(NN[:,2]) L3 = max(NN[:,3])-min(NN[:,3]) VTOT=L1*L2*L3 print 'VTOT: [mm?]' + str(VTOT) V = array([]) print 'calculating new Vtet ' V = range(len(EL)+2) V[0] = VTOT V[1] = L3 for j in range(0,len(EL)): Va = EL[j].connectivity[0] Vb = EL[j].connectivity[1] Vc = EL[j].connectivity[2] Vd = EL[j].connectivity[3] ix = where(NN[:,0] == Va) Xa = NN[ix,1][0][0] Ya = NN[ix,2][0][0] Za = NN[ix,3][0][0] ix = where(NN[:,0] == Vb) Xb = NN[ix,1][0][0] Yb = NN[ix,2][0][0] Zb = NN[ix,3][0][0] ix = where(NN[:,0] == Vc) Xc = NN[ix,1][0][0] Yc = NN[ix,2][0][0] Zc = NN[ix,3][0][0] ix = where(NN[:,0] == Vd) Xd = NN[ix,1][0][0] Yd = NN[ix,2][0][0] Zd = NN[ix,3][0][0] a = [Xa,Ya,Za] b = [Xb,Yb,Zb] c = [Xc,Yc,Zc] d = [Xd,Yd,Zd] aa = numpy.diff([b,a],axis=0)[0] bb = numpy.diff([c,b],axis=0)[0] cc = numpy.diff([d,c],axis=0)[0] D=array([aa,bb,cc]) det=numpy.linalg.det(D) V[j+2] = abs(det)/6 pathV = pt + vtet savetxt(pathV, V, fmt='%.3e') ### From magnus.moraberg at gmail.com Tue May 25 15:13:55 2010 From: magnus.moraberg at gmail.com (Barry) Date: Tue, 25 May 2010 12:13:55 -0700 (PDT) Subject: UnicodeDecodeError having fetch web page Message-ID: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Hi, The code below is giving me the error: Traceback (most recent call last): File "C:\Users\Administrat??r\Desktop\test.py", line 4, in UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: unexpected code byte What am i doing wrong? Thanks, Barry request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ baby',headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/ 20071127 Firefox/2.0.0.11'} ) response = urllib.request.urlopen(request) html = response.read().decode('utf-8') From vincent at vincentdavis.net Tue May 25 15:25:16 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 25 May 2010 13:25:16 -0600 Subject: speed up a numpy code with huge array In-Reply-To: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> Message-ID: It makes me think you are filling you available memory and using the disk as cache. If this happens things will get real slow. You might take a look at your system resources when this is running. I don't have much else to offer and could be completely wrong. Vincent On Tue, May 25, 2010 at 1:05 PM, Alexzive wrote: > Hello Pythonguys! > > is there a way to improve the performance of the attached code ? it > takes about 5 h on a dual-core (using only one core) when len(V) > ~1MIL. V is an array which is supposed to store all the volumes of > tetrahedral elements of a grid whose coord. are stored in NN (accessed > trough the list of tetraelements --> EL) > > > Thanks in advance! > Alex > > #### > print 'start ' + nameodb > #path = '/windows/D/SIM-MM/3D/E_ortho/' + nameodb + '.odb' > path = pt + nameodb + '.odb' > odb = openOdb(path) > > N = odb.rootAssembly.instances['PART-1-1'].nodes > if loadV==1: > pathV=pt+vtet > V=numpy.loadtxt(pathV) > VTOT = V[0] > L3 = V[1] > print 'using ' + vtet > else: > NN=[] > B=[0,0,0,0] > for i in range(len(N)): > B[0] = N[i].label > B[1] = N[i].coordinates[0] > B[2] = N[i].coordinates[1] > B[3] = N[i].coordinates[2] > NN = append(NN,B) > > NN=NN.reshape(-1,4) > EL = odb.rootAssembly.instances['PART-1-1'].elements > > L1 = max(NN[:,1])-min(NN[:,1]) > L2 = max(NN[:,2])-min(NN[:,2]) > L3 = max(NN[:,3])-min(NN[:,3]) > VTOT=L1*L2*L3 > print 'VTOT: [mm?]' + str(VTOT) > > V = array([]) > > print 'calculating new Vtet ' > V = range(len(EL)+2) > V[0] = VTOT > V[1] = L3 > for j in range(0,len(EL)): > Va = EL[j].connectivity[0] > Vb = EL[j].connectivity[1] > Vc = EL[j].connectivity[2] > Vd = EL[j].connectivity[3] > ix = where(NN[:,0] == Va) > Xa = NN[ix,1][0][0] > Ya = NN[ix,2][0][0] > Za = NN[ix,3][0][0] > ix = where(NN[:,0] == Vb) > Xb = NN[ix,1][0][0] > Yb = NN[ix,2][0][0] > Zb = NN[ix,3][0][0] > ix = where(NN[:,0] == Vc) > Xc = NN[ix,1][0][0] > Yc = NN[ix,2][0][0] > Zc = NN[ix,3][0][0] > ix = where(NN[:,0] == Vd) > Xd = NN[ix,1][0][0] > Yd = NN[ix,2][0][0] > Zd = NN[ix,3][0][0] > a = [Xa,Ya,Za] > b = [Xb,Yb,Zb] > c = [Xc,Yc,Zc] > d = [Xd,Yd,Zd] > aa = numpy.diff([b,a],axis=0)[0] > bb = numpy.diff([c,b],axis=0)[0] > cc = numpy.diff([d,c],axis=0)[0] > D=array([aa,bb,cc]) > det=numpy.linalg.det(D) > V[j+2] = abs(det)/6 > pathV = pt + vtet > savetxt(pathV, V, fmt='%.3e') > ### > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Tue May 25 15:39:03 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 25 May 2010 15:39:03 -0400 Subject: UnicodeDecodeError having fetch web page In-Reply-To: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Message-ID: <23F0D49F-FF28-45B6-8628-CEBCA3FE0E16@semanchuk.com> On May 25, 2010, at 3:13 PM, Barry wrote: > Hi, > > The code below is giving me the error: > > Traceback (most recent call last): > File "C:\Users\Administrat??r\Desktop\test.py", line 4, in > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: > unexpected code byte > > > What am i doing wrong? > > Thanks, > > Barry > > request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ > baby',headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/ > 20071127 Firefox/2.0.0.11'} ) > > response = urllib.request.urlopen(request) > html = response.read().decode('utf-8') Well, for starters you're assuming that the response content is in UTF-8. You need to examine the Content-Type header to see what the encoding is. If it's not UTF-8, there's your problem. HTH P From lie.1296 at gmail.com Tue May 25 15:40:43 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 26 May 2010 05:40:43 +1000 Subject: to prevent reveres engineering for Python In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> , , <87mxvsfzvh.fsf@benfinney.id.au> , <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: <4bfc282a$1@dnews.tpgi.com.au> On 05/26/10 01:09, Adam Tauno Williams wrote: > On Tue, 2010-05-25 at 18:49 +0500, Sandy Ydnas wrote: >> Agree, reveres engineering is crucial issuer for programming >> language >> but every executable file can be cracked, for example by using >> disassembler!!! >> For each weapon there is antiweapon, so >> is it possible to prevent reveres engineering when customer have >> access to executable made from Python code??? > > No. But you can make it hard. > > Store a GPG encrypted blob in your program that contains you secret > sauce, is decrypted to memory, executed, and then discarded. Setup > some kind of license manager like dongle or application to perform the > key management. That merely gives a false sense of security. If the program is decrypted in memory, you can easily make a memory dump to get the unencrypted program. If I am a competitor that can make economic advantage by cracking your secret sauce, it wouldn't be difficult for me to do that. From darcy at druid.net Tue May 25 15:57:12 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 25 May 2010 15:57:12 -0400 Subject: to prevent reveres engineering for Python In-Reply-To: <4bfc282a$1@dnews.tpgi.com.au> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <87mxvsfzvh.fsf@benfinney.id.au> <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> <4bfc282a$1@dnews.tpgi.com.au> Message-ID: <20100525155712.d177b9e9.darcy@druid.net> On Wed, 26 May 2010 05:40:43 +1000 Lie Ryan wrote: > That merely gives a false sense of security. If the program is decrypted > in memory, you can easily make a memory dump to get the unencrypted > program. If I am a competitor that can make economic advantage by > cracking your secret sauce, it wouldn't be difficult for me to do that. Yes, in fact the only people inconvenienced are your paying clients. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From magnus.moraberg at gmail.com Tue May 25 16:00:23 2010 From: magnus.moraberg at gmail.com (Barry) Date: Tue, 25 May 2010 13:00:23 -0700 (PDT) Subject: UnicodeDecodeError having fetch web page References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Message-ID: <089cbe25-2f32-4b9a-90a5-8be952b602f6@l6g2000vbo.googlegroups.com> On 25 Maj, 21:39, Philip Semanchuk wrote: > On May 25, 2010, at 3:13 PM, Barry wrote: > > > > > Hi, > > > The code below is giving me the error: > > > Traceback (most recent call last): > > ?File "C:\Users\Administrat?r\Desktop\test.py", line 4, in > > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: > > unexpected code byte > > > What am i doing wrong? > > > Thanks, > > > Barry > > > request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ > > baby',headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/ > > 20071127 Firefox/2.0.0.11'} ) > > > response = urllib.request.urlopen(request) > > html = response.read().decode('utf-8') > > Well, for starters you're assuming that the response content is in ? > UTF-8. You need to examine the Content-Type header to see what the ? > encoding is. If it's not UTF-8, there's your problem. > > HTH > P The content type is utf-8: Date: Wed, 19 May 2010 19:17:39 GMT Server: Apache Cache-Control: private, s-maxage=0, max-age=0, must-revalidate Content-Language: en Vary: Accept-Encoding,Cookie Last-Modified: Wed, 19 May 2010 10:10:34 GMT Content-Encoding: gzip Content-Length: 25247 Content-Type: text/html; charset=utf-8 X-Cache: HIT from sq61.wikimedia.org X-Cache-Lookup: HIT from sq61.wikimedia.org:3128 Age: 520549 X-Cache: HIT from amssq32.esams.wikimedia.org X-Cache-Lookup: HIT from amssq32.esams.wikimedia.org:3128 X-Cache: MISS from amssq37.esams.wikimedia.org X-Cache-Lookup: MISS from amssq37.esams.wikimedia.org:80 Connection: close Can it be that the page is corrupt? If so, how can I make the best of the situation? Many other pages from this server work without problem. Thanks! Barry From ian.g.kelly at gmail.com Tue May 25 16:01:19 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 25 May 2010 14:01:19 -0600 Subject: Python-list Digest, Vol 80, Issue 223 In-Reply-To: References: Message-ID: On Tue, May 25, 2010 at 1:10 PM, wrote: > ---------- Forwarded message ---------- > From:?Terry Reedy > To:?python-list at python.org > Date:?Tue, 25 May 2010 13:09:23 -0400 > Subject:?Re: Generator expressions vs. comprehensions > On 5/25/2010 3:08 AM, Peter Otten wrote: >> >> Michele Simionato wrote: > >> I think not turning the list-comp into syntactic sugar for list(genexp) in >> py3 is a missed opportunity. > > Implementing it that way was tried but was much slower than the current implementation. If one uses StopIteration as it is intended to be used (and is so documented), then, I believe, they are equivalent. There was a conscious decision to not slow comprehensions for the many to cater to the very few. I thought that I was using it as intended. The full function that I was working with when I ran into the problem was: def tuples(iterable, n=2): """Make an iterator that returns elements from iterable in tuples of n. If the number of elements from the iterable is not a multiple of n, any trailing elements will be truncated. tuples('ABCDEFG', n=2) --> ('A', 'B') ('C', 'D') ('E', 'F') """ iterator = iter(iterable) while True: yield tuple(iterator.next() for i in xrange(n)) The intention being that if iterator.next() raised a StopIteration, it would propagate out and signal no further values for the tuples generator. Instead, the generator expression results in empty tuples once the iterator has run out, and the tuples generator never runs out. This has since been fixed by replacing the generator expression with a for loop, but if you don't mind my asking, how does this violate the documented usage pattern? Is the recommendation to use an explicit try-except around every call of iterator.next()? Off-topic, does anybody know of a better name for this function? Cheers, Ian From invalid at invalid.invalid Tue May 25 16:04:16 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 25 May 2010 20:04:16 +0000 (UTC) Subject: to prevent reveres engineering for Python References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <87mxvsfzvh.fsf@benfinney.id.au> <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> <4bfc282a$1@dnews.tpgi.com.au> Message-ID: On 2010-05-25, D'Arcy J.M. Cain wrote: > On Wed, 26 May 2010 05:40:43 +1000 > Lie Ryan wrote: > >> That merely gives a false sense of security. If the program is >> decrypted in memory, you can easily make a memory dump to get the >> unencrypted program. If I am a competitor that can make economic >> advantage by cracking your secret sauce, it wouldn't be difficult for >> me to do that. > > Yes, in fact the only people inconvenienced are your paying clients. After several bad experiences over the years, I'm now willing go to quite a bit of effort to avoid using products that require dongles, node-locked licenses or license servers. -- Grant Edwards grant.b.edwards Yow! Hold the MAYO & pass at the COSMIC AWARENESS ... gmail.com From __peter__ at web.de Tue May 25 16:10:38 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 May 2010 22:10:38 +0200 Subject: UnicodeDecodeError having fetch web page References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> <089cbe25-2f32-4b9a-90a5-8be952b602f6@l6g2000vbo.googlegroups.com> Message-ID: Barry wrote: > On 25 Maj, 21:39, Philip Semanchuk wrote: >> On May 25, 2010, at 3:13 PM, Barry wrote: >> >> >> >> > Hi, >> >> > The code below is giving me the error: >> >> > Traceback (most recent call last): >> > File "C:\Users\Administrat?r\Desktop\test.py", line 4, in >> > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: >> > unexpected code byte >> >> > What am i doing wrong? >> >> > Thanks, >> >> > Barry >> >> > request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ >> > baby',headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/ >> > 20071127 Firefox/2.0.0.11'} ) >> >> > response = urllib.request.urlopen(request) >> > html = response.read().decode('utf-8') >> >> Well, for starters you're assuming that the response content is in >> UTF-8. You need to examine the Content-Type header to see what the >> encoding is. If it's not UTF-8, there's your problem. >> >> HTH >> P > > The content type is utf-8: > > Date: Wed, 19 May 2010 19:17:39 GMT > Server: Apache > Cache-Control: private, s-maxage=0, max-age=0, must-revalidate > Content-Language: en > Vary: Accept-Encoding,Cookie > Last-Modified: Wed, 19 May 2010 10:10:34 GMT > Content-Encoding: gzip But the data is gzipped. You have to uncompress it before decoding. Peter From rtw at rtw.me.uk Tue May 25 16:12:18 2010 From: rtw at rtw.me.uk (Rob Williscroft) Date: Tue, 25 May 2010 20:12:18 +0000 (UTC) Subject: UnicodeDecodeError having fetch web page References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Message-ID: Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3 @m21g2000vbr.googlegroups.com in gmane.comp.python.general: > Hi, > > The code below is giving me the error: > > Traceback (most recent call last): > File "C:\Users\Administrat??r\Desktop\test.py", line 4, in > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: > unexpected code byte > > > What am i doing wrong? It may not be you, en.wiktionary.org is sending gzip encoded content back, it seems to do this even if you set the Accept header as in: request.add_header( "Accept", "text/html" ) But maybe I'm not doing it correctly. #encoding: utf-8 import urllib import urllib.request request = urllib.request.Request (url='http://en.wiktionary.org/wiki/baby',headers={'User- Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11'} ) response = urllib.request.urlopen(request) info = response.info() enc = info[ 'Content-Encoding' ] print( "Encoding: " + enc ) from io import BytesIO import gzip buf = BytesIO( response.read() ) unziped = gzip.GzipFile( "wahatever", mode = 'rb', fileobj = buf ) html = unziped.read().decode('utf-8') print( html.encode( "ascii", "backslashreplace" ) ) Rob. From clp2 at rebertia.com Tue May 25 16:14:36 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 25 May 2010 13:14:36 -0700 Subject: Python-list Digest, Vol 80, Issue 223 In-Reply-To: References: Message-ID: On Tue, May 25, 2010 at 1:01 PM, Ian Kelly wrote: > On Tue, May 25, 2010 at 1:10 PM, ? wrote: >> ---------- Forwarded message ---------- >> From:?Terry Reedy >> To:?python-list at python.org >> Date:?Tue, 25 May 2010 13:09:23 -0400 >> Subject:?Re: Generator expressions vs. comprehensions >> On 5/25/2010 3:08 AM, Peter Otten wrote: >>> >>> Michele Simionato wrote: >> >>> I think not turning the list-comp into syntactic sugar for list(genexp) in >>> py3 is a missed opportunity. >> >> Implementing it that way was tried but was much slower than the current implementation. If one uses StopIteration as it is intended to be used (and is so documented), then, I believe, they are equivalent. There was a conscious decision to not slow comprehensions for the many to cater to the very few. > > I thought that I was using it as intended. ?The full function that I > was working with when I ran into the problem was: > > def tuples(iterable, n=2): > ? ?"""Make an iterator that returns elements from iterable in tuples of n. ?If > ? ?the number of elements from the iterable is not a multiple of n, any > ? ?trailing elements will be truncated. > > ? ?tuples('ABCDEFG', n=2) --> ('A', 'B') ('C', 'D') ('E', 'F') > ? ?""" > ? ?iterator = iter(iterable) > ? ?while True: > ? ? ? ?yield tuple(iterator.next() for i in xrange(n)) > > The intention being that if iterator.next() raised a StopIteration, it > would propagate out and signal no further values for the tuples > generator. ?Instead, the generator expression results in empty tuples > once the iterator has run out, and the tuples generator never runs > out. ?This has since been fixed by replacing the generator expression > with a for loop, but if you don't mind my asking, how does this > violate the documented usage pattern? ?Is the recommendation to use an > explicit try-except around every call of iterator.next()? > > Off-topic, does anybody know of a better name for this function? truncating_grouper() ? from itertools import izip def truncating_grouper(n, iterable): "truncating_grouper(3, 'ABCDEFG') --> ABC DEF" args = [iter(iterable)] * n return izip(*args) Implementation adapted from itertools's docs's "Recipes" section. Also, avoid replying to digests in the future; it messes up conversation threading. Cheers, Chris -- http://blog.rebertia.com From philip at semanchuk.com Tue May 25 16:23:19 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 25 May 2010 16:23:19 -0400 Subject: UnicodeDecodeError having fetch web page In-Reply-To: <089cbe25-2f32-4b9a-90a5-8be952b602f6@l6g2000vbo.googlegroups.com> References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> <089cbe25-2f32-4b9a-90a5-8be952b602f6@l6g2000vbo.googlegroups.com> Message-ID: On May 25, 2010, at 4:00 PM, Barry wrote: > On 25 Maj, 21:39, Philip Semanchuk wrote: >> On May 25, 2010, at 3:13 PM, Barry wrote: >> >> >> >>> Hi, >> >>> The code below is giving me the error: >> >>> Traceback (most recent call last): >>> File "C:\Users\Administrat?r\Desktop\test.py", line 4, in >>> UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in >>> position 1: >>> unexpected code byte >> >>> What am i doing wrong? >> >>> Thanks, >> >>> Barry >> >>> request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ >>> baby',headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/ >>> 20071127 Firefox/2.0.0.11'} ) >> >>> response = urllib.request.urlopen(request) >>> html = response.read().decode('utf-8') >> >> Well, for starters you're assuming that the response content is in >> UTF-8. You need to examine the Content-Type header to see what the >> encoding is. If it's not UTF-8, there's your problem. >> >> HTH >> P > > The content type is utf-8: > > Date: Wed, 19 May 2010 19:17:39 GMT > Server: Apache > Cache-Control: private, s-maxage=0, max-age=0, must-revalidate > Content-Language: en > Vary: Accept-Encoding,Cookie > Last-Modified: Wed, 19 May 2010 10:10:34 GMT > Content-Encoding: gzip > Content-Length: 25247 > Content-Type: text/html; charset=utf-8 > X-Cache: HIT from sq61.wikimedia.org > X-Cache-Lookup: HIT from sq61.wikimedia.org:3128 > Age: 520549 > X-Cache: HIT from amssq32.esams.wikimedia.org > X-Cache-Lookup: HIT from amssq32.esams.wikimedia.org:3128 > X-Cache: MISS from amssq37.esams.wikimedia.org > X-Cache-Lookup: MISS from amssq37.esams.wikimedia.org:80 > Connection: close Looks like the content is gzipped. Have you unzipped it? Also, from where are you getting those headers? The server might well send different headers to your browser than to a urllib request. Have you examined the raw content in a hex editor on in the debugger? That would probably answer a lot of questions. > Can it be that the page is corrupt? Of course that's always possible, but personally whenever I have to decide whether bits are being flipped at random or my code is buggy, it's almost always the latter. > If so, how can I make the best of the situation? Depends on what you're trying to accomplish. bye Philip From awilliam at whitemice.org Tue May 25 16:43:34 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 25 May 2010 16:43:34 -0400 Subject: to prevent reveres engineering for Python In-Reply-To: <4bfc282a$1@dnews.tpgi.com.au> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> , , <87mxvsfzvh.fsf@benfinney.id.au> , <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> <4bfc282a$1@dnews.tpgi.com.au> Message-ID: <1274820214.21250.4.camel@linux-yu4c.site> On Wed, 2010-05-26 at 05:40 +1000, Lie Ryan wrote: > On 05/26/10 01:09, Adam Tauno Williams wrote: > > On Tue, 2010-05-25 at 18:49 +0500, Sandy Ydnas wrote: > >> Agree, reveres engineering is crucial issuer for programming > >> language > >> but every executable file can be cracked, for example by using > >> disassembler!!! > >> For each weapon there is antiweapon, so > >> is it possible to prevent reveres engineering when customer have > >> access to executable made from Python code??? > > No. But you can make it hard. > > Store a GPG encrypted blob in your program that contains you secret > > sauce, is decrypted to memory, executed, and then discarded. Setup > > some kind of license manager like dongle or application to perform the > > key management. > That merely gives a false sense of security. There is no "true" sense of security. There is only degrees of obfuscation, hence the first sentence: "No. But you can make it hard" > If the program is decrypted > in memory, you can easily make a memory dump Easily? Really? You vastly over estimate the majority of computer users. If someone who knows how to read the memory of a running process wants your secret sauce - they are going to get it. > to get the unencrypted > program. If I am a competitor that can make economic advantage by > cracking your secret sauce, it wouldn't be difficult for me to do that. True. That is pretty much always true. The only effective solution is to have your app call a web service [or some kind of RPC] to a server where you keep the secret sauce hidden away. From fetchinson at googlemail.com Tue May 25 18:07:17 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 26 May 2010 00:07:17 +0200 Subject: to prevent reveres engineering for Python In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <87mxvsfzvh.fsf@benfinney.id.au> <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: >> is it possible to prevent reveres engineering when customer have access >> to executable made from Python code??? The only secure way of protecting your code is if you expose it as a web service or some such. (Yes, people can still crack your web server, but that's nitpicking :)) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From ben+python at benfinney.id.au Tue May 25 18:14:34 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 May 2010 08:14:34 +1000 Subject: to prevent reveres engineering for Python References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <87mxvsfzvh.fsf@benfinney.id.au> <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: <87ocg37ho5.fsf@benfinney.id.au> Terry Reedy writes: > On 5/25/2010 9:49 AM, Sandy Ydnas wrote: > > > is it possible to prevent reveres engineering when customer have > > access to executable made from Python code??? > > If there is, it is a trade secrets that you will not be able to > reverse engineer ;-). +1 QOTW -- \ ?The best way to get information on Usenet is not to ask a | `\ question, but to post the wrong information.? ?Aahz | _o__) | Ben Finney From exarkun at twistedmatrix.com Tue May 25 19:03:55 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Tue, 25 May 2010 23:03:55 -0000 Subject: asyncore loop and cmdloop problem In-Reply-To: <0123253e-f628-471b-a343-0ad2588b1a20@m33g2000vbi.googlegroups.com> References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> <1fc2db40-42c3-40d7-ab92-b29c6c039345@u7g2000vbq.googlegroups.com> <0123253e-f628-471b-a343-0ad2588b1a20@m33g2000vbi.googlegroups.com> Message-ID: <20100525230355.1872.1949927971.divmod.xquotient.1@localhost.localdomain> On 04:31 pm, kaklis at gmail.com wrote: >On May 25, 5:47?pm, "kak... at gmail.com" wrote: >>On May 25, 5:23?pm, Michele Simionato >>wrote: >> >> > On May 25, 2:56?pm, "kak... at gmail.com" wrote: >> >> > > Could you please provide me with a simple example how to do this >>with >> > > threads. >> > > I don't know where to put the cmdloop(). >> > > Please help, i' m so confused! >> > > Thank you >> >> > What are you trying to do? Do you really need to use the standard >> > library? Likely what you want to accomplish is already implemented >>in >> > Twisted; I remember there was something like that in their examples >> > directory. >> >>Thank you, >>and sorry for the mistake i did before with my post. >> >>Antonis > >hi again. i installed twisted, but since i m not familiar with it, do >you remember which example you have in mind? >What i want to accomplish is something like "asterisk". while you send >commands from the asterisk cli, at the same time >the underlying protocol sends you notifications to the console. >without exiting the application. >thanks You can find a couple simple examples here: http://twistedmatrix.com/documents/current/core/examples/ Search for "stdin" and "stdio". Jean-Paul From bryanjugglercryptographer at yahoo.com Tue May 25 19:40:26 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 25 May 2010 16:40:26 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <32c8bb68-75f6-4c80-9c22-36b69e1a5b93@y6g2000pra.googlegroups.com> Raymond Hettinger wrote: > If speed is important, the global lookups can be localized: > > def prttn(m, n, map=itertools.imap, int=int, str=str, range=range): > ? ? return sum(m == sum(map(int, str(x))) for x in range(n)) That's just silly. "If speed is important," we abandon the naive algorithm. -- --Bryan From bryanjugglercryptographer at yahoo.com Tue May 25 21:04:45 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 25 May 2010 18:04:45 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> Message-ID: <498a76fd-4e4b-4d09-86c3-16800a4e3d87@s4g2000prh.googlegroups.com> Jean-Michel Pichavant wrote: > I still don't see "how many positive integers less than n have digits > that sum up to m" makes it a "partition" though if that what prttn > means. Surely because I miss the context. A partition of a positive integer m is an unordered collection of positive integers that sum to m. [1, 1, 2, 5] is a partition of 9. The problem at issue here is not that of counting partitions. My algorithm for our prttn separated out the 'ndsums' sub-problem: Count d-digit ints with digits summing to m. I found a generalization of that problem stated in the /CRC Handbook of Discrete and Combinatorial Mathematics/ (2000 edition, section 2.1) among "counting problems" as: Solutions to x_1 + ... x_n = k 0 <= x_i <= a_i for one or more i Alas, the handbook does not provide a formula or algorithm. It refers to the inclusion/exclusion principle, which I did not see how to turn into an efficient algorithm. My recursive memoizing method for ndsums() was initially a shot in the dark and I was surprised how well it worked. Thinking about it more, I can argue that it is polynomial-time based on the size of the memo- table and the work per entry. My prttn() calls ndsums() once for each digit, so the whole thing is polynomial in the number of digits. -- --Bryan From ptmcg at austin.rr.com Tue May 25 21:45:59 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 25 May 2010 18:45:59 -0700 (PDT) Subject: Need some Python 3 help Message-ID: I was teetering on the brink of releasing Pyparsing 1.5.3 (with some nice new examples and goodies), when I saw that I had recently introduced a bug in the Python 3 compatible version. Here is the stacktrace as reported on SF: Traceback (most recent call last): File "testcase.py", line 11, in result = exp.parseFile("./pyparsing_py3.py") File "/data/projekte/parsing/pyparsing/pyparsing_py3.py", line 1426, in parseFile return self.parseString(file_contents, parseAll) File "/data/projekte/parsing/pyparsing/pyparsing_py3.py", line 1068, in parseString loc, tokens = self._parse( instring, 0 ) File "/data/projekte/parsing/pyparsing/pyparsing_py3.py", line 935, in _parseNoCache preloc = self.preParse( instring, loc ) File "/data/projekte/parsing/pyparsing/pyparsing_py3.py", line 893, in preParse while loc < instrlen and instring[loc] in wt: TypeError: 'in ' requires string as left operand, not int In this section of code, instring is a string, loc is an int, and wt is a string. Any clues why instring[loc] would be evaluating as int? (I am unfortunately dependent on the kindness of strangers when it comes to testing my Python 3 code, as I don't have a Py3 environment installed.) Thanks, -- Paul From bryanjugglercryptographer at yahoo.com Tue May 25 21:56:53 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 25 May 2010 18:56:53 -0700 (PDT) Subject: Need some Python 3 help References: Message-ID: Paul McGuire wrote: [...] > while loc < instrlen and instring[loc] in wt: > TypeError: 'in ' requires string as left operand, not int > > In this section of code, instring is a string, loc is an int, In Python 3, lots of things that used to return str now return bytes, and the elements of a bytes object are ints. Something to check. -- --Bryan From benjamin at python.org Tue May 25 21:58:47 2010 From: benjamin at python.org (Benjamin Peterson) Date: Wed, 26 May 2010 01:58:47 +0000 (UTC) Subject: Need some Python 3 help References: Message-ID: Paul McGuire austin.rr.com> writes: > In this section of code, instring is a string, loc is an int, and wt > is a string. Any clues why instring[loc] would be evaluating as int? > (I am unfortunately dependent on the kindness of strangers when it > comes to testing my Python 3 code, as I don't have a Py3 environment > installed.) Indexing bytes in Python 3 gives an integer. From ptmcg at austin.rr.com Tue May 25 22:04:07 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 25 May 2010 19:04:07 -0700 (PDT) Subject: Need some Python 3 help References: Message-ID: <97dbf3c7-e2f5-4237-8a7b-a04cf3a7f0ee@o15g2000vbb.googlegroups.com> On May 25, 8:58?pm, Benjamin Peterson wrote: > Paul McGuire austin.rr.com> writes: > > > In this section of code, instring is a string, loc is an int, and wt > > is a string. ?Any clues why instring[loc] would be evaluating as int? > > (I am unfortunately dependent on the kindness of strangers when it > > comes to testing my Python 3 code, as I don't have a Py3 environment > > installed.) > > Indexing bytes in Python 3 gives an integer. Hrmm, I had a sneaking hunch this might be the issue. But then I don't know how this code *ever* worked in Python 3, as it is chock full of indexed references into the string being parsed. And yet, I've had other folks test and confirm that pyparsing_py3 *does* work on Python 3. It is a puzzle. -- Paul From bryanjugglercryptographer at yahoo.com Tue May 25 22:46:37 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 25 May 2010 19:46:37 -0700 (PDT) Subject: Need some Python 3 help References: <97dbf3c7-e2f5-4237-8a7b-a04cf3a7f0ee@o15g2000vbb.googlegroups.com> Message-ID: Paul McGuire wrote: > Hrmm, I had a sneaking hunch this might be the issue. ?But then I > don't know how this code *ever* worked in Python 3, as it is chock > full of indexed references into the string being parsed. ?And yet, > I've had other folks test and confirm that pyparsing_py3 *does* work > on Python 3. ?It is a puzzle. I suspect in most cases you use bytes consistently. You got the exception from: instring[loc] in wt If instring and wt are both bytes, that's fine. If they're both str, also fine. If one is bytes and one is str, exception. -- --Bryan From amyoldwatch1800 at gmail.com Tue May 25 23:08:44 2010 From: amyoldwatch1800 at gmail.com (amy) Date: Wed, 26 May 2010 11:08:44 +0800 Subject: Good deal for Cartier Watches online Message-ID: Good deal for Cartier Watches online It is amazing, the Ballon Bleu de Cartier Replica Watches at http://www.swizwatch.com/ are perfect, cheap and high quality. Ballon Bleu de Cartier Watches Collection: http://www.swizwatch.com/ballon-bleu-de-cartier-replica-watches.html Replica Cartier Ballon Bleu de Cartier Two-Tone Ladies Watch W69007Z3 http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Two-Tone-Ladies-Watch-W69007Z3-.html Replica Cartier Ballon Bleu de Cartier 18K Yellow Gold Leather Strap Mens Watch W6900551 http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-18K-Yellow-Gold-Leather-Strap-Mens-Watch-W6900551.html Replica Cartier Ballon Bleu de Cartier Two-Tone Mens Watch W69009Z3 http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Two-Tone-Mens-Watch-W69009Z3.html Replica Cartier Ballon Bleu de Cartier 18K Rose Gold Mens Watch W69006Z2 http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-18K-Rose-Gold-Mens-Watch-W69006Z2.html Replica Cartier Ballon Bleu de Cartier Mens Gold Watch W69013Z2 http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Mens-Gold-Watch-W69013Z2.html Buy more Cartier replica watches at low price by click: http://www.swizwatch.com/cartier-replica-watches.html From godson.g at gmail.com Tue May 25 23:22:48 2010 From: godson.g at gmail.com (Godson Gera) Date: Wed, 26 May 2010 08:52:48 +0530 Subject: [wxPython-users] wxPython 2.8.11.0 release In-Reply-To: <4BFB0E05.1090101@alldunn.com> References: <4BFB0E05.1090101@alldunn.com> Message-ID: On Tue, May 25, 2010 at 5:08 AM, Robin Dunn wrote: > Announcing > ---------- > > The 2.8.11.0 release of wxPython is now available for download at > http://wxpython.org/download.php. This release adds Python 2.7 builds, > PySlices, new pubsub implementation, lots of updates to AGW, and lots > of bugs fixed. A summary of changes is listed below and also at > http://wxpython.org/recentchanges.php. > > Thanks for the great work ! -- Thanks & Regards, Godson Gera IVR India -------------- next part -------------- An HTML attachment was scrubbed... URL: From hnassrat at gmail.com Tue May 25 23:41:08 2010 From: hnassrat at gmail.com (Pykler) Date: Tue, 25 May 2010 20:41:08 -0700 (PDT) Subject: PEP 3119 ABC - And how I learned to love the Abstract Bomb References: Message-ID: <50455a03-4c47-47f3-9d46-8ba2e8629dd4@w3g2000vbd.googlegroups.com> On May 13, 9:30?am, Lawrence D'Oliveiro wrote: > You?re looking at it wrong. If you want to force people to do things in a > certain way, use Java. Python is about enabling things, not forcing them. LoL :-) > Don?t use subclassing. Instead, let the caller pass you a duck-typed object > that implements the methods you need. I totally agree. in my code I do not force the object to be an instance of a subclass of the ABC, they certainly can duck-type as they please. The ABC is simply there to give them an idea of what methods they need to implement. It is kind of self documenting structure if you may. However, I had this problem described earlier which does not let me complete this self documenting structure without adding a thorough doc-string explaining that they still need to implement one or two more methods. From draco.parvus at gmail.com Wed May 26 00:02:03 2010 From: draco.parvus at gmail.com (draco parvus) Date: Tue, 25 May 2010 21:02:03 -0700 (PDT) Subject: speed up a numpy code with huge array References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> Message-ID: <1c498c3f-a635-4799-803f-9c62556bf50b@j36g2000prj.googlegroups.com> On May 26, 7:05?am, Alexzive wrote: > Hello Pythonguys! > > is there a way to improve the performance of the attached code ? it > takes about 5 h on a dual-core (using only one core) when len(V) > ~1MIL. V is an array which is supposed to store all the volumes of > tetrahedral elements of a grid whose coord. are stored in NN (accessed > trough the list of tetraelements --> EL) > > Thanks in advance! > Alex > > #### > print 'start ' + nameodb > #path = '/windows/D/SIM-MM/3D/E_ortho/' + nameodb + '.odb' > path = pt + nameodb + '.odb' > odb = openOdb(path) > > N = odb.rootAssembly.instances['PART-1-1'].nodes > if loadV==1: > ? pathV=pt+vtet > ? V=numpy.loadtxt(pathV) > ? VTOT = V[0] > ? L3 = V[1] > ? print 'using ' + vtet > else: > ? NN=[] > ? B=[0,0,0,0] > ? for i in range(len(N)): > ? ? ? ? B[0] = N[i].label > ? ? ? ? B[1] = N[i].coordinates[0] > ? ? ? ? B[2] = N[i].coordinates[1] > ? ? ? ? B[3] = N[i].coordinates[2] > ? ? ? ? NN = append(NN,B) > > ? NN=NN.reshape(-1,4) > ? EL = odb.rootAssembly.instances['PART-1-1'].elements > > ? L1 = max(NN[:,1])-min(NN[:,1]) > ? L2 = max(NN[:,2])-min(NN[:,2]) > ? L3 = max(NN[:,3])-min(NN[:,3]) > ? VTOT=L1*L2*L3 > ? print 'VTOT: [mm?]' + str(VTOT) > > ? V = array([]) > > ? print 'calculating new Vtet ' > ? V = range(len(EL)+2) > ? V[0] = VTOT > ? V[1] = L3 > ? for j in range(0,len(EL)): > ? ? ? ? Va = EL[j].connectivity[0] > ? ? ? ? Vb = EL[j].connectivity[1] > ? ? ? ? Vc = EL[j].connectivity[2] > ? ? ? ? Vd = EL[j].connectivity[3] > ? ? ? ? ix = where(NN[:,0] == Va) > ? ? ? ? Xa = NN[ix,1][0][0] > ? ? ? ? Ya = NN[ix,2][0][0] > ? ? ? ? Za = NN[ix,3][0][0] > ? ? ? ? ix = where(NN[:,0] == Vb) > ? ? ? ? Xb = NN[ix,1][0][0] > ? ? ? ? Yb = NN[ix,2][0][0] > ? ? ? ? Zb = NN[ix,3][0][0] > ? ? ? ? ix = where(NN[:,0] == Vc) > ? ? ? ? Xc = NN[ix,1][0][0] > ? ? ? ? Yc = NN[ix,2][0][0] > ? ? ? ? Zc = NN[ix,3][0][0] > ? ? ? ? ix = where(NN[:,0] == Vd) > ? ? ? ? Xd = NN[ix,1][0][0] > ? ? ? ? Yd = NN[ix,2][0][0] > ? ? ? ? Zd = NN[ix,3][0][0] > ? ? ? ? a = ?[Xa,Ya,Za] > ? ? ? ? b = ?[Xb,Yb,Zb] > ? ? ? ? c = ?[Xc,Yc,Zc] > ? ? ? ? d = ?[Xd,Yd,Zd] > ? ? ? ? aa = numpy.diff([b,a],axis=0)[0] > ? ? ? ? bb = numpy.diff([c,b],axis=0)[0] > ? ? ? ? cc = numpy.diff([d,c],axis=0)[0] > ? ? ? ? D=array([aa,bb,cc]) > ? ? ? ? det=numpy.linalg.det(D) > ? ? ? ? V[j+2] = abs(det)/6 > ? pathV = pt + vtet > ? savetxt(pathV, V, fmt='%.3e') > ### Main problem you've got is quadratic behaviour. For each vertex of each of your million tets, you go through the entire node list to find its coordinates. You should use a dict instead, such as: allnodes = {} for node in N: allnodes[node.label] = node.coordinates And later, instead of using numpy.where, directly use: Xa, Ya, Za = allnodes[Va] # with Va = EL[j].connectivity[0] ... Should speed things up a bit. But manipulating odb files is never very fast. d. From stefan_ml at behnel.de Wed May 26 02:14:21 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 26 May 2010 08:14:21 +0200 Subject: speed up a numpy code with huge array In-Reply-To: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> Message-ID: Alexzive, 25.05.2010 21:05: > is there a way to improve the performance of the attached code ? it > takes about 5 h on a dual-core (using only one core) when len(V) > ~1MIL. V is an array which is supposed to store all the volumes of > tetrahedral elements of a grid whose coord. are stored in NN (accessed > trough the list of tetraelements --> EL) Consider using Cython for your algorithm. It has direct support for NumPy arrays and translates to fast C code. Stefan From sjmachin at lexicon.net Wed May 26 03:04:23 2010 From: sjmachin at lexicon.net (John Machin) Date: Wed, 26 May 2010 07:04:23 +0000 (UTC) Subject: UnicodeDecodeError having fetch web page References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Message-ID: Rob Williscroft rtw.me.uk> writes: > > Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3 > @m21g2000vbr.googlegroups.com in gmane.comp.python.general: > > > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: > > unexpected code byte > > It may not be you, en.wiktionary.org is sending gzip > encoded content back, It sure is; here's where the offending 0x8b comes from: """ID1 (IDentification 1) ID2 (IDentification 2) These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213), to identify the file as being in gzip format.""" (from http://www.faqs.org/rfcs/rfc1952.html) From bryanjugglercryptographer at yahoo.com Wed May 26 04:03:13 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Wed, 26 May 2010 01:03:13 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> <498a76fd-4e4b-4d09-86c3-16800a4e3d87@s4g2000prh.googlegroups.com> Message-ID: <487ba222-ea1d-4049-b520-1fab5df3c318@n37g2000prc.googlegroups.com> I wrote: > My prttn() calls ndsums() once for each > digit, so the whole thing is polynomial in the number of digits. Correction: my prttn() function calls ndsums() at most 9 times per digit of n. That still provides run time polynomial in the length of the input. -- --Bryan From kaklis at gmail.com Wed May 26 04:29:31 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Wed, 26 May 2010 01:29:31 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> <1fc2db40-42c3-40d7-ab92-b29c6c039345@u7g2000vbq.googlegroups.com> <0123253e-f628-471b-a343-0ad2588b1a20@m33g2000vbi.googlegroups.com> Message-ID: On May 26, 2:03?am, exar... at twistedmatrix.com wrote: > On 04:31 pm, kak... at gmail.com wrote: > > > > >On May 25, 5:47?pm, "kak... at gmail.com" wrote: > >>On May 25, 5:23?pm, Michele Simionato > >>wrote: > > >> > On May 25, 2:56?pm, "kak... at gmail.com" wrote: > > >> > > Could you please provide me with a simple example how to do this > >>with > >> > > threads. > >> > > I don't know where to put the cmdloop(). > >> > > Please help, i' m so confused! > >> > > Thank you > > >> > What are you trying to do? Do you really need to use the standard > >> > library? Likely what you want to accomplish is already implemented > >>in > >> > Twisted; I remember there was something like that in their examples > >> > directory. > > >>Thank you, > >>and sorry for the mistake i did before with my post. > > >>Antonis > > >hi again. i installed twisted, but since i m not familiar with it, do > >you remember which example you have in mind? > >What i want to accomplish is something like "asterisk". while you send > >commands from the asterisk cli, at the same time > >the underlying protocol sends you notifications to the console. > >without exiting the application. > >thanks > > You can find a couple simple examples here: > > ?http://twistedmatrix.com/documents/current/core/examples/ > > Search for "stdin" and "stdio". > > Jean-Paul Thank you so much, i'll check them!!! Antonis From bryanjugglercryptographer at yahoo.com Wed May 26 04:30:22 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Wed, 26 May 2010 01:30:22 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <85l509Fpe7U1@mid.individual.net> <6025dfa5-bc54-412d-98e2-71d2ad4540a6@11g2000prv.googlegroups.com> <041e63e5-8d83-4286-ae2d-7c38f18d8139@s13g2000prc.googlegroups.com> Message-ID: <53122f59-1e37-4ec3-9106-dd129577276f@q39g2000prh.googlegroups.com> I wrote: > > I came up with a recursive memo-izing algorithm that > > handles 100-digit n's. Oops. I missed Richard Thomas's post. He posted the same algorithm a couple days before. -- --Bryan From lex at from.hell Wed May 26 05:21:32 2010 From: lex at from.hell (Lex Lebedeff) Date: Wed, 26 May 2010 09:21:32 +0000 (UTC) Subject: Kohonen neural network Message-ID: Hello! Has anyone tried to build an implementation of subject in Python? Any help is appreciated! --- news://freenews.netfront.net/ - complaints: news at netfront.net --- From durumdara at gmail.com Wed May 26 05:30:41 2010 From: durumdara at gmail.com (Durumdara) Date: Wed, 26 May 2010 11:30:41 +0200 Subject: MySQLDB - server has gone on blob insertion... Message-ID: Hi! I want to test my program that coded into PGSQL, and PySQLite. With these DBs I have problem on many blob deletion (2 hours) and compact/vacuum (1 hours)... So I'm trying to port my program, and before that making a test to check, which time needs to delete 1 GB of blobs. I installed MySQLDb from the exe (Py2.6, from stackoverflow version), set all parameters, etc. import MySQLdb conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "", db = "db") cursor = conn.cursor () cursor.execute ("SELECT VERSION()") cursor.execute('delete from blobs;') s = time.time() for i in range(200): k = str(i) xbuffer = chr(65 + (i % 26)) xbuffer = xbuffer * 1024 * 1024 b = MySQLdb.escape_string(xbuffer) print len(b) cursor.execute('''insert into blobs (blob_id, file_id, size, ext, data) values (%s, %s, %s, %s, %s)''', (i, i, -1, 'org', b)) conn.commit() e = time.time() t = e - s print t sys.exit() When I tried to start this, I got error: _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') I read that server have some parameter, that limit the Query length. Then I decreased the blob size to 1M, and then it is working. But: I can insert 800k-1,9 MB blobs. I tried to set this parameter, but nothing changed. My.ini: # SERVER SECTION # ---------------------------------------------------------------------- # # The following options will be read by the MySQL Server. Make sure that # you have installed the server correctly (see above) so it reads this # file. # [mysqld] max_allowed_packet = 16M # The TCP/IP Port the MySQL Server will listen on port=3306 What is the problem? What I do wrong? Thanks for your help: dd -------------- next part -------------- An HTML attachment was scrubbed... URL: From tom.browder at gmail.com Wed May 26 07:26:01 2010 From: tom.browder at gmail.com (Tom) Date: Wed, 26 May 2010 04:26:01 -0700 (PDT) Subject: Vote to Add Python Package "pubsub" to the Python Standard Library Message-ID: <6b9d2898-4166-40b4-9016-dc55dee77d00@q33g2000vbt.googlegroups.com> I vote for adding the Python package "pubsub" to the Python standard library. It has recently been added to wxpython (replacing the old wx.lib.pubsub package), but it has application to non-gui programs as well. For more information see: . From nilly16 at yahoo.com Wed May 26 07:36:50 2010 From: nilly16 at yahoo.com (Jimbo) Date: Wed, 26 May 2010 04:36:50 -0700 (PDT) Subject: [WxPython] Advice on Temperature Application Method & Structure Message-ID: <1baa040f-0a2c-476a-8b78-26a599452895@k17g2000pro.googlegroups.com> Hello I have made a simple application using WxPython that is a temperature converter. This is my first application made in WxPython, the only other apps I have made were in Win32 c++ so I am new to widgets in general. I am looking for advice & criticism on when you should use classes in GUI widget apps (& where) & other general advice: - Structure of a wxPython script/code - Should every window be in its own class? - whats the best way to refer to a control (by window name or ID) - Should a group of controls that are related be in a class For example should I make a Celsius class that handles the celsius editbox, static & button & the button action function(convert_to_fahrenheit())? - Errors, bad things I have done in my code - When & why use a Validator?? Temperature Converter Application: """ Temperature Application Description: This application uses WxPython to create a simple windows app to convert temperature from celsius to fahrenheit & visa versa. Looking for advice on everything to do with wxPython: For example: - Structure of a wxPython script/code - Should every window be in its own class? - whats the best way to refer to a control (by window name or ID) - Should a ground of controls that are related be in a class For example should I make a Celsius class that handles the celsius editbox, static & button? - Errors, bad things I have done in my code - When & why use a Validator?? """ import wx ## Constants ## ID_FAHREN = 1 ID_CELSIUS = 2 class Controller(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self,parent,id,"Temperature Converter", size=(247,186)) # Create Controls panel = wx.Panel(self) self.create_controls( panel, wx.Validator() ) self.fah_edit.SetValue(str(32)) self.cel_edit.SetValue(str(0)) # Define actions self.Bind_Events() def create_controls(self, panel, val): """ Create all the controls we will need for the temperature conversion """ self.bmp_static = wx.StaticText(panel, -1, "Bitmap pic will be here", (10,5), (150,40)) self.fah_static = wx.StaticText(panel, -1, "Fahrenheit: ", (10,70), (-1,-1)) self.cel_static = wx.StaticText(panel, -1,"Celsius: ", (140,70), (-1,-1)) self.fah_edit = wx.TextCtrl(panel,ID_FAHREN, pos=(70,65), size=(40,25), style=0, validator=val, name='a') self.cel_edit = wx.TextCtrl(panel,ID_CELSIUS, pos=(180,65), size=(40,25), style=0, validator=val, name='b') self.to_fah_button = wx.Button(panel,label="To Fahrenheit", pos=(145,95),size=(80,25)) self.to_cel_button = wx.Button(panel,label="To Celsius", pos=(35,95),size=(80,25)) self.exit_button = wx.Button(panel,label="Exit",pos=(157,123), size=(70,25)) def Bind_Events(self): """ Bind application events to class functions """ self.Bind(wx.EVT_BUTTON,self.close_button, self.exit_button) self.Bind(wx.EVT_CLOSE,self.close_window) self.Bind(wx.EVT_BUTTON,self.convert_to_celsius, self.to_fah_button) self.Bind(wx.EVT_BUTTON,self.convert_to_fahrenheit, self.to_cel_button) def close_button(self, event): self.Close(True) def close_window(self, event): self.Destroy() def error_check(self, string): """ Check for valid input in editboxes. Valid input includes float & integer values only """ if string.isalpha() or len(string) <= 0: return False return True def convert_to_fahrenheit(self, event): """ Convert the value in fahrenheit window to celsius & display in our window/edit box """ # Algorithm # - Get number from fahrenheit editbox # - convert fahrenheit value to celsius # - change value in Celsius Window to # Step 1: fahren_value = self.fah_edit.GetValue() if not self.error_check( fahren_value ): self.fah_edit.SetValue( "NA" ) return # Step 2: value = (float(fahren_value) - 32) * 5/9 # Step 3: self.cel_edit.SetValue( str(value) ) def convert_to_celsius(self, event): """ Convert the value in celcius window/editbox to fahrenheit & display in our window/editbox """ # Algorithm # - Get number from celsius editbox # - convert celsius value to fahrenheit # - change value in fahrenheit Window # Step 1: celsius_value = self.cel_edit.GetValue() if not self.error_check( celsius_value ): self.cel_edit.SetValue( "NA" ) return # Step 2: value = (float( celsius_value ) * 9/5) + 32 # Step 3: self.fah_edit.SetValue( str(value) ) if __name__ == "__main__": app = wx.PySimpleApp() frame = Controller(parent=None,id=-1) frame.Show() app.MainLoop() From zasaconsulting at gmail.com Wed May 26 07:43:24 2010 From: zasaconsulting at gmail.com (Alexzive) Date: Wed, 26 May 2010 04:43:24 -0700 (PDT) Subject: speed up a numpy code with huge array References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> Message-ID: <704eeb6e-4939-43f0-986e-42460c88b738@k31g2000vbu.googlegroups.com> thank you all for the tips. I 'll try them soon. I also notice another bottleneck, when python tries to access some array data stored in the odb files (---> in text below), even before starting the algoritm: ### EPS_nodes = range(len(frames)) for f in frames: ... sum = 0 ---> UN = F[f].fieldOutputs['U'].getSubset(region=TOP).values <--- ... EPS_nodes[f] = UN[10].data[Scomp-1]/L3 ### unfortunately I don't have time to learn cython. Using dictionaries sounds promising. Thanks! Alex On May 26, 8:14?am, Stefan Behnel wrote: > Alexzive, 25.05.2010 21:05: > > > is there a way to improve the performance of the attached code ? it > > takes about 5 h on a dual-core (using only one core) when len(V) > > ~1MIL. V is an array which is supposed to store all the volumes of > > tetrahedral elements of a grid whose coord. are stored in NN (accessed > > trough the list of tetraelements --> ?EL) > > Consider using Cython for your algorithm. It has direct support for NumPy > arrays and translates to fast C code. > > Stefan From zasaconsulting at gmail.com Wed May 26 07:48:00 2010 From: zasaconsulting at gmail.com (Alexzive) Date: Wed, 26 May 2010 04:48:00 -0700 (PDT) Subject: speed up a numpy code with huge array References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> <704eeb6e-4939-43f0-986e-42460c88b738@k31g2000vbu.googlegroups.com> Message-ID: sorry it was just bullshit what I wrote about the second bottleneck, it seemed to hang up but it was just me forgetting to double-enter during debugging after "for cycle". On May 26, 1:43?pm, Alexzive wrote: > thank you all for the tips. > I 'll try them soon. > > I also notice another bottleneck, when python tries to access some > array data stored in the odb files (---> in text below), even before > starting the algoritm: > > ### > EPS_nodes = range(len(frames)) > for f in frames: > ... ? ? sum = 0 > ---> ? ?UN = F[f].fieldOutputs['U'].getSubset(region=TOP).values <--- > ... ? ? EPS_nodes[f] = UN[10].data[Scomp-1]/L3 > > ### > > unfortunately I don't have time to learn cython. Using dictionaries > sounds promising. > Thanks! > Alex > > On May 26, 8:14?am, Stefan Behnel wrote: > > > > > Alexzive, 25.05.2010 21:05: > > > > is there a way to improve the performance of the attached code ? it > > > takes about 5 h on a dual-core (using only one core) when len(V) > > > ~1MIL. V is an array which is supposed to store all the volumes of > > > tetrahedral elements of a grid whose coord. are stored in NN (accessed > > > trough the list of tetraelements --> ?EL) > > > Consider using Cython for your algorithm. It has direct support for NumPy > > arrays and translates to fast C code. > > > Stefan From wuwei23 at gmail.com Wed May 26 08:26:56 2010 From: wuwei23 at gmail.com (alex23) Date: Wed, 26 May 2010 05:26:56 -0700 (PDT) Subject: Kohonen neural network References: Message-ID: <260cd874-fe51-4bdd-b112-f64ff7ef3050@a27g2000prj.googlegroups.com> On May 26, 7:21?pm, Lex Lebedeff wrote: > Has anyone tried to build an implementation of subject in Python? > Any help is appreciated! http://www.dia.fi.upm.es/~jamartin/download.htm Seriously, though, any reason why you couldn't just type "kohonen neural network python" into Google? You would've found it a lot easier to wade through the results before your question & it's many mirrors. It would've been the 2nd entry, immediately after the wikipedia article on Kohonen SOMs. From victorsubervi at gmail.com Wed May 26 08:29:21 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 26 May 2010 08:29:21 -0400 Subject: A Quick MySQL Question In-Reply-To: References: Message-ID: On Wed, May 26, 2010 at 2:42 AM, Dennis Lee Bieber wrote: > I was, for that example, assuming that the user input "values" was > being used in a select query and hence wrapped it with wildcard markers > so that the phrase would match anywhere in the data field. > In said thread you wrote the following: clauses = [] for nm in nameList: clauses.append(nm + " like %s") where = " and ".join(clauses) #could be " or " valueList = ["%%s%" % vl for vl in valueList] SQL = "select * from table where " + where cur.execute(SQL, valueList) Ok, so let's assume we have a name list of: ["name1", "name2", "name3"] and a value list of: ["value1", "value2", "value3"] Therefore: clauses = ["name1 like %s", "name2 like %s", "name3 like %s"] where = "name1 like %s and name2 like %s and name3 like %s" SQL = "select * from table where name1 like %s and name2 like %s and name3 like %s" valueList = ("%value1", "%value2", "%value3") cur.execute("select * from table where name1 like %s and name2 like %s and name3 like %s", ("%value1", "%value2", "%value3")) Why do the values have that extra "%"? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Wed May 26 08:34:06 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 26 May 2010 08:34:06 -0400 Subject: [WxPython] Advice on Temperature Application Method & Structure In-Reply-To: <1baa040f-0a2c-476a-8b78-26a599452895@k17g2000pro.googlegroups.com> References: <1baa040f-0a2c-476a-8b78-26a599452895@k17g2000pro.googlegroups.com> Message-ID: On May 26, 2010, at 7:36 AM, Jimbo wrote: > Hello > > I have made a simple application using WxPython that is a temperature > converter. This is my first application made in WxPython, the only > other apps I have made were in Win32 c++ so I am new to widgets in > general. > > > I am looking for advice & criticism on when you should use classes in > GUI widget apps (& where) & other general advice: Hi Jimbo, The first piece of advice I have is to post on the wxPython mailing list where you'll reach a more focused audience. > - Should every window be in its own class? That works for me. > - whats the best way to refer to a control (by window name or ID) ID. Uniqueness is not enforced among window names. > - Should a group of controls that are related be in a class > For example should I make a Celsius class that handles the > celsius editbox, static & button & the button action > function(convert_to_fahrenheit())? When and where to use a class is not wxPython-specific, and is partly a matter of taste. For instance, I would not put a convert_to_fahrenheit() function inside a class, because it doesn't need any class-related info. Make it a module-level function and it will be easier to re-use. I wouldn't do what you suggested (grouping controls into a class) because it doesn't seem to serve any purpose other than documentation, which can be accomplished just as well with a comment. Ask yourself this -- what problem would grouping them into a class solve? > - When & why use a Validator?? I'm ambivalent about Validators. Before I used them I had all of my init code in one place, and in the on_ok_clicked() event I had all of my teardown code and it was easy to see what control got assigned to which variable. Now that information is scattered through a bunch of classes which are fairly verbose. Also, Validators are great for validating individual controls, but not so great with groups. E.g. when control A can only be blank if B is too. A & B have to know about one another and the Validator starts to get messy. OTOH it's nice to group the code that knows everything that needs to be know about the relationship between a control and the variable to which is assigned. We call the validator when the control loses focus (to let users know if they've entered something invalid) and when OK is clicked. It's nice to be able to simply call the validators in that case. Good luck with your app Philip > Temperature Converter Application: > """ > Temperature Application > > Description: This application uses WxPython to create a simple > windows app to convert temperature from celsius > to fahrenheit & visa versa. > > Looking for advice on everything to do with wxPython: > For example: > - Structure of a wxPython script/code > - Should every window be in its own class? > - whats the best way to refer to a control (by window name or ID) > - Should a ground of controls that are related be in a class > For example should I make a Celsius class that handles the > celsius editbox, static & button? > - Errors, bad things I have done in my code > - When & why use a Validator?? > """ > > > import wx > > > ## Constants ## > ID_FAHREN = 1 > ID_CELSIUS = 2 > > > class Controller(wx.Frame): > > > def __init__(self, parent, id): > > wx.Frame.__init__(self,parent,id,"Temperature Converter", > size=(247,186)) > > # Create Controls > panel = wx.Panel(self) > self.create_controls( panel, wx.Validator() ) > > self.fah_edit.SetValue(str(32)) > self.cel_edit.SetValue(str(0)) > > # Define actions > self.Bind_Events() > > > def create_controls(self, panel, val): > """ Create all the controls we will need for the temperature > conversion """ > > self.bmp_static = wx.StaticText(panel, -1, "Bitmap pic will be here", > (10,5), (150,40)) > > self.fah_static = wx.StaticText(panel, -1, "Fahrenheit: ", > (10,70), (-1,-1)) > > self.cel_static = wx.StaticText(panel, -1,"Celsius: ", > (140,70), (-1,-1)) > > self.fah_edit = wx.TextCtrl(panel,ID_FAHREN, pos=(70,65), > size=(40,25), style=0, validator=val, > name='a') > > self.cel_edit = wx.TextCtrl(panel,ID_CELSIUS, pos=(180,65), > size=(40,25), style=0, validator=val, > name='b') > > self.to_fah_button = wx.Button(panel,label="To Fahrenheit", > pos=(145,95),size=(80,25)) > > self.to_cel_button = wx.Button(panel,label="To Celsius", > pos=(35,95),size=(80,25)) > > self.exit_button = wx.Button(panel,label="Exit",pos=(157,123), > size=(70,25)) > > > > def Bind_Events(self): > """ Bind application events to class functions """ > > self.Bind(wx.EVT_BUTTON,self.close_button, > self.exit_button) > > self.Bind(wx.EVT_CLOSE,self.close_window) > > self.Bind(wx.EVT_BUTTON,self.convert_to_celsius, > self.to_fah_button) > > self.Bind(wx.EVT_BUTTON,self.convert_to_fahrenheit, > self.to_cel_button) > > > def close_button(self, event): > > self.Close(True) > > > def close_window(self, event): > > self.Destroy() > > > def error_check(self, string): > """ Check for valid input in editboxes. Valid input > includes float & integer values only """ > > if string.isalpha() or len(string) <= 0: > > return False > > return True > > > def convert_to_fahrenheit(self, event): > """ Convert the value in fahrenheit window to celsius & > display in our window/edit box """ > > # Algorithm > # - Get number from fahrenheit editbox > # - convert fahrenheit value to celsius > # - change value in Celsius Window to > > # Step 1: > fahren_value = self.fah_edit.GetValue() > > if not self.error_check( fahren_value ): > > self.fah_edit.SetValue( "NA" ) > return > > # Step 2: > value = (float(fahren_value) - 32) * 5/9 > > # Step 3: > self.cel_edit.SetValue( str(value) ) > > > def convert_to_celsius(self, event): > """ Convert the value in celcius window/editbox to > fahrenheit & display in our window/editbox """ > > # Algorithm > # - Get number from celsius editbox > # - convert celsius value to fahrenheit > # - change value in fahrenheit Window > > # Step 1: > celsius_value = self.cel_edit.GetValue() > > if not self.error_check( celsius_value ): > > self.cel_edit.SetValue( "NA" ) > return > > # Step 2: > value = (float( celsius_value ) * 9/5) + 32 > > # Step 3: > self.fah_edit.SetValue( str(value) ) > > > > if __name__ == "__main__": > > app = wx.PySimpleApp() > > frame = Controller(parent=None,id=-1) > frame.Show() > app.MainLoop() > -- > http://mail.python.org/mailman/listinfo/python-list From r3831110n at gmail.com Wed May 26 08:49:37 2010 From: r3831110n at gmail.com (Rebel Lion) Date: Wed, 26 May 2010 05:49:37 -0700 (PDT) Subject: Inheritable Slots Metaclass Message-ID: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> I made a metaclass to inherit __slots__ automatically. I think this feature should be included in builtin object's metaclass. You can now write: class Foo(object): __metaclass__ = SlotMetaclass @slot def foo(): pass class Bar(Foo): @slot def bar(): pass foo = Foo() foo.foo = 1 bar = Bar() bar.bar = 1 bar.foo = 1 try: bar.baz = 1 # this should fall except AttributeError, e: print 'yeah', e Instead of class Foo(object): __slots__ = ['foo'] class Bar(Foo) __slots__ = ['foo', 'bar'] Please discuss the pros & cons for this feature. Here is the metaclass: class slot(object): """Slot Decorator""" def __init__(self, func): pass class SlotMetaclass(type): """Inheritable Slots Metaclass""" def __new__(cls, name, bases, attrs): # make a normal class, and get its attributes to decide which ones are slots tmpcls = type.__new__(cls, name, bases, attrs) slots = [] for k in dir(tmpcls): v = getattr(tmpcls, k) if isinstance(v, slot): slots.append(k) # clean up del tmpcls for x in slots: del attrs[x] # create the real class with __slots__ attrs['__slots__'] = slots return type.__new__(cls, name, bases, attrs) From steveo at syslang.net Wed May 26 08:52:44 2010 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 26 May 2010 08:52:44 -0400 Subject: Looking for matlab to python converter. Message-ID: <4BFD199C.3050103@syslang.net> I found something on sourceforge called mat2py, but there's nothing there. (It seems to be just a placeholder.) I figure that if anyone would know of something useful, this would be the place to try. TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From aahz at pythoncraft.com Wed May 26 08:56:16 2010 From: aahz at pythoncraft.com (Aahz) Date: 26 May 2010 05:56:16 -0700 Subject: LJ.com top article Message-ID: I'm finally getting around to reading my copy of Linux Journal 8/2009 (picked up at OSCON last year), and on page 17, they list the most popular articles from linuxjournal.com. Given that I'm posting here, I'm sure all long-time readers already know what that article is: Eric Raymond's "Why Python?", now ten years old. http://www.linuxjournal.com/article/3882 -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From wuwei23 at gmail.com Wed May 26 09:24:40 2010 From: wuwei23 at gmail.com (alex23) Date: Wed, 26 May 2010 06:24:40 -0700 (PDT) Subject: Looking for matlab to python converter. References: Message-ID: On May 26, 10:52?pm, "Steven W. Orr" wrote: > I found something on sourceforge called mat2py, but there's nothing there. (It > seems to be just a placeholder.) I figure that if anyone would know of something > useful, this would be the place to try. http://sourceforge.net/projects/libermate/ Google is amazing. From rolf.oltmans at gmail.com Wed May 26 09:43:47 2010 From: rolf.oltmans at gmail.com (Oltmans) Date: Wed, 26 May 2010 06:43:47 -0700 (PDT) Subject: Does pickled objects work fine between different OS? Message-ID: If I dump a Python dictionary into a file named "data.pkl" using Pickle module on a Linux operating system, will the data contained in "data.pkl" load fine in a Windows OS? I mean will I be able to load the dictionary data contained in "data.pkl" just fine on Windows XP? I could have tested it but don't have immediate access to a *nix based system so please enlighten me. All help will be appreciated. From aahz at pythoncraft.com Wed May 26 09:50:00 2010 From: aahz at pythoncraft.com (Aahz) Date: 26 May 2010 06:50:00 -0700 Subject: python command line manual References: Message-ID: In article , Chris Rebert wrote: >On Mon, May 24, 2010 at 3:52 PM, Peng Yu wrote: >> >> I mainly check online python manual. But I feel that it would be nice >> if there is command line manual available (just like perl command line >> manual). Could you please let me know if such command line manual >> available? > >98% sure that there isn't. You could instead use a text-based console >web browser such as lynx to view the online docs to much the same >effect though. ...after downloading them locally so that you're not dependent on an Internet connection. At least, that's what I've been doing for about a decade... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From mail at timgolden.me.uk Wed May 26 09:59:35 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 26 May 2010 14:59:35 +0100 Subject: python command line manual In-Reply-To: References: Message-ID: <4BFD2947.6030507@timgolden.me.uk> On 26/05/2010 14:50, Aahz wrote: > In article, > Chris Rebert wrote: >> On Mon, May 24, 2010 at 3:52 PM, Peng Yu wrote: >>> >>> I mainly check online python manual. But I feel that it would be nice >>> if there is command line manual available (just like perl command line >>> manual). Could you please let me know if such command line manual >>> available? >> >> 98% sure that there isn't. You could instead use a text-based console >> web browser such as lynx to view the online docs to much the same >> effect though. > > ...after downloading them locally so that you're not dependent on an > Internet connection. At least, that's what I've been doing for about a > decade... Wow. That's a slow internet connection you've got there... TJG From breamoreboy at yahoo.co.uk Wed May 26 10:12:18 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 26 May 2010 15:12:18 +0100 Subject: Python-URL! archives Message-ID: According to http://www.python.org/community/lists/ these are archived here http://www.equi4.com/wikis/urls/82. As the latter hasn't been updated since 2000-07-20 isn't it time to change the former :) Regards. Mark Lawrence From breamoreboy at yahoo.co.uk Wed May 26 10:15:50 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 26 May 2010 15:15:50 +0100 Subject: python command line manual In-Reply-To: <4BFD2947.6030507@timgolden.me.uk> References: <4BFD2947.6030507@timgolden.me.uk> Message-ID: On 26/05/2010 14:59, Tim Golden wrote: > On 26/05/2010 14:50, Aahz wrote: >> In article, >> Chris Rebert wrote: >>> On Mon, May 24, 2010 at 3:52 PM, Peng Yu wrote: >>>> >>>> I mainly check online python manual. But I feel that it would be nice >>>> if there is command line manual available (just like perl command line >>>> manual). Could you please let me know if such command line manual >>>> available? >>> >>> 98% sure that there isn't. You could instead use a text-based console >>> web browser such as lynx to view the online docs to much the same >>> effect though. >> >> ...after downloading them locally so that you're not dependent on an >> Internet connection. At least, that's what I've been doing for about a >> decade... > > Wow. That's a slow internet connection you've got there... > > TJG +1 LOTW From albert at spenarnc.xs4all.nl Wed May 26 10:32:50 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 26 May 2010 14:32:50 GMT Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: In article <4bf442cd$0$31377$4fafbaef at reader1.news.tin.it>, superpollo wrote: >... how many positive integers less than n have digits that sum up to m: > >In [197]: def prttn(m, n): > tot = 0 > for i in range(n): > s = str(i) > sum = 0 > for j in range(len(s)): > sum += int(s[j]) > if sum == m: > tot += 1 > return tot > .....: > >In [207]: prttn(25, 10000) >Out[207]: 348 > >any suggestion for pythonizin' it? I don't like the excursion to string and back. def x(i) : return x(i/10)+i%10 if i else 0 or if you can't stand recursion: def x(i): s= 0 while i: s += i%10 i /= 10 return s (All untested but you get the idea.) > >bye -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From icanbob at gmail.com Wed May 26 10:52:48 2010 From: icanbob at gmail.com (bobicanprogram) Date: Wed, 26 May 2010 07:52:48 -0700 (PDT) Subject: speed up a numpy code with huge array References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> <704eeb6e-4939-43f0-986e-42460c88b738@k31g2000vbu.googlegroups.com> Message-ID: On May 26, 7:43 am, Alexzive wrote: > thank you all for the tips. > I 'll try them soon. > > I also notice another bottleneck, when python tries to access some > array data stored in the odb files (---> in text below), even before > starting the algoritm: > > ### > EPS_nodes = range(len(frames)) > for f in frames: > ... sum = 0 > ---> UN = F[f].fieldOutputs['U'].getSubset(region=TOP).values <--- > ... EPS_nodes[f] = UN[10].data[Scomp-1]/L3 > > ### > > unfortunately I don't have time to learn cython. Using dictionaries > sounds promising. > Thanks! > Alex > > On May 26, 8:14 am, Stefan Behnel wrote: > > > Alexzive, 25.05.2010 21:05: > > > > is there a way to improve the performance of the attached code ? it > > > takes about 5 h on a dual-core (using only one core) when len(V) > > > ~1MIL. V is an array which is supposed to store all the volumes of > > > tetrahedral elements of a grid whose coord. are stored in NN (accessed > > > trough the list of tetraelements --> EL) > > > Consider using Cython for your algorithm. It has direct support for NumPy > > arrays and translates to fast C code. > > > Stefan The SIMPL toolkit (http://www.icanprogram.com/06py/lesson1/ lesson1.html) might be a simpler way to offload some processing to faster C code. bob From kushal.kumaran at gmail.com Wed May 26 11:25:51 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Wed, 26 May 2010 20:55:51 +0530 Subject: Another Little MySQL Problem In-Reply-To: References: Message-ID: <1274887551.2339.11.camel@nitrogen> On Tue, 2010-05-25 at 14:45 -0400, Victor Subervi wrote: > Hi; > I have this code: > > clientCursor.execute('select ID from %s' % (personalDataTable)) > upds = [itm[0] for itm in clientCursor] > print "" % upds > > The problem is that the values passed are 1L, 2L.... When I retrieve > them on the other end and try to convert them to integers, guess what > happens? So how do I get rid of that "L"? You could build a list of ints instead of a list of longs, like this: upds = [int(itm[0]) for itm in clientCursor] I'm not sure if the result of applying str() on lists is guaranteed not to change, though. -- regards, kushal From fetchinson at googlemail.com Wed May 26 11:40:35 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 26 May 2010 17:40:35 +0200 Subject: Does pickled objects work fine between different OS? In-Reply-To: References: Message-ID: > If I dump a Python dictionary into a file named "data.pkl" using > Pickle module on a Linux operating system, will the data contained in > "data.pkl" load fine in a Windows OS? Yes. > I mean will I be able to load the dictionary data contained in "data.pkl" > just fine on Windows XP? Yes. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From kushal.kumaran at gmail.com Wed May 26 11:59:24 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Wed, 26 May 2010 21:29:24 +0530 Subject: UnicodeDecodeError having fetch web page In-Reply-To: References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Message-ID: <1274889564.2339.16.camel@nitrogen> On Tue, 2010-05-25 at 20:12 +0000, Rob Williscroft wrote: > Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3 > @m21g2000vbr.googlegroups.com in gmane.comp.python.general: > > > Hi, > > > > The code below is giving me the error: > > > > Traceback (most recent call last): > > File "C:\Users\Administrat?r\Desktop\test.py", line 4, in > > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: > > unexpected code byte > > > > > > What am i doing wrong? > > It may not be you, en.wiktionary.org is sending gzip > encoded content back, it seems to do this even if you set > the Accept header as in: > > request.add_header( "Accept", "text/html" ) > > But maybe I'm not doing it correctly. > You need the Accept-Encoding: identity header. http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html -- regards, kushal From rridge at csclub.uwaterloo.ca Wed May 26 12:02:27 2010 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 26 May 2010 12:02:27 -0400 Subject: Does pickled objects work fine between different OS? References: Message-ID: Oltmans wrote: >If I dump a Python dictionary into a file named "data.pkl" using >Pickle module on a Linux operating system, will the data contained in >"data.pkl" load fine in a Windows OS? I mean will I be able to load >the dictionary data contained in "data.pkl" just fine on Windows XP? That will work just fine. The only thing that may be a problem is that if you choose to use the newer pickle format, it won't work with versions of Python before 2.3. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From invalid at invalid.invalid Wed May 26 12:23:48 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 26 May 2010 16:23:48 +0000 (UTC) Subject: Does pickled objects work fine between different OS? References: Message-ID: On 2010-05-26, Oltmans wrote: > If I dump a Python dictionary into a file named "data.pkl" using > Pickle module on a Linux operating system, will the data contained in > "data.pkl" load fine in a Windows OS? That depends on the data and the version of Python. Older versions didn't handle some floating point values (NAN, INF) in a portable manner, and loading the pickled data would fail when such a value was encountered. -- Grant Edwards grant.b.edwards Yow! It's the RINSE CYCLE!! at They've ALL IGNORED the gmail.com RINSE CYCLE!! From ktenney at gmail.com Wed May 26 12:51:22 2010 From: ktenney at gmail.com (Kent Tenney) Date: Wed, 26 May 2010 11:51:22 -0500 Subject: question Message-ID: In a docutils svn checkout. [docutils/trunk/docutils]$ python setup.py install --root /tmp OK [docutils/trunk/docutils]$ python setup.py install_data --root /tmp distutils.errors.DistutilsFileError: could not delete '/usr/local/lib/python2.6/dist-packages/docutils/parsers/rst/include/README.txt': Permission denied Am I missing something? If it works for you, I suppose it's somewhere in my versioning. I have bull in a china shop tendencies when it comes to installing stuff. Thanks, Kent From strombrg at gmail.com Wed May 26 12:55:25 2010 From: strombrg at gmail.com (Dan Stromberg) Date: Wed, 26 May 2010 09:55:25 -0700 (PDT) Subject: Troubles with python internationalization References: Message-ID: <083708a3-b496-4aeb-8f19-bf77eb578888@v37g2000vbv.googlegroups.com> On May 25, 10:46?am, Pascal Chambon wrote: > * code safety : it seems default python string formatting technics (% > operator, .format() method) are normally used when one needs to > substitute placeholders in translated strings. But the thing is : I DONT > want my view to raise an exception simply because one of the > translations has forgotten a damn "%(myvar)s" placeholder. The only > quick fix I can think of, is to always use substitution through > defaultdicts instances (and still, exceptions could occur if abnormal > "%s" placeholders are found in the translated string). > Are there some utilities in python, or frameworks like django, > ? to allow a safe string substitution (which might, > for example, simply log an error if a buggy string si found) ?? Python's > template strings' "safe_substitute()" won't fit, because it swallows > errors without any notice... For this one, you might check into pylint. I've just recently started using it, but I'm loving it. I pretty much don't check things in without first running them through pylint (and some unit tests) first now. From magguri.devi at gmail.com Wed May 26 13:28:21 2010 From: magguri.devi at gmail.com (devi) Date: Wed, 26 May 2010 10:28:21 -0700 (PDT) Subject: uk girls Message-ID: <1e947034-5afb-4361-8ccb-79d0b52e4a7f@a27g2000prj.googlegroups.com> we are write here uk girls body language uk girls clture and that feature what about this last man visit in earth. visit www.ukgirlsbody.blogspot.com From magguri.devi at gmail.com Wed May 26 13:31:47 2010 From: magguri.devi at gmail.com (devi) Date: Wed, 26 May 2010 10:31:47 -0700 (PDT) Subject: uk girls Message-ID: we are write here uk girls body language uk girls clture and that feature what about this last man visit in earth. visit www.onlineairlinesjobs.blogspot.com From xcr4cx at googlemail.com Wed May 26 13:32:42 2010 From: xcr4cx at googlemail.com (christian schulze) Date: Wed, 26 May 2010 10:32:42 -0700 (PDT) Subject: Yet Another Configuration Parser Module Message-ID: <3e5f012a-1ecd-4cd0-91de-0b1d78c5e48a@m4g2000vbl.googlegroups.com> Hey folks, I've written a small configuration parser for a recent project. I think it's pretty usefull and not that "fat" or "complex" as the regular python configuration modules like ConfigParser. The file contains everything you need to know. http://crac.pcriot.com/dl/config.py If you have any suggestions I'd be glad if you'd contact me. From victorsubervi at gmail.com Wed May 26 13:37:29 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 26 May 2010 13:37:29 -0400 Subject: Another Little MySQL Problem In-Reply-To: <1274887551.2339.11.camel@nitrogen> References: <1274887551.2339.11.camel@nitrogen> Message-ID: On Wed, May 26, 2010 at 11:25 AM, Kushal Kumaran wrote: > On Tue, 2010-05-25 at 14:45 -0400, Victor Subervi wrote: > > Hi; > > I have this code: > > > > clientCursor.execute('select ID from %s' % (personalDataTable)) > > upds = [itm[0] for itm in clientCursor] > > print "" % upds > > > > The problem is that the values passed are 1L, 2L.... When I retrieve > > them on the other end and try to convert them to integers, guess what > > happens? So how do I get rid of that "L"? > > You could build a list of ints instead of a list of longs, like this: > > upds = [int(itm[0]) for itm in clientCursor] > Oh, geez. That should have been obvious to me! Thanks! beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From william.miner at enig.com Wed May 26 13:48:42 2010 From: william.miner at enig.com (William Miner) Date: Wed, 26 May 2010 13:48:42 -0400 Subject: Error Message-ID: I?m relative new to python and I puzzled by the following strange (to me) behavior. I was taking pieces from two old scripts to build a new one. When I began to debug it I got the following error message: Traceback (most recent call last): File "/Users/williamminer/ex2gen/ex2gen-3.0.5/src/ScriptDev/run_ex2gen_scan.py", line 38, in if re.search('varm',line): AttributeError: 'function' object has no attribute 'search' This had worked in the previous script but not the new one. I noticed that the new script had an additional line at the beginning (line 3) #!/usr/bin/env python import sys, math, os, shutil, commands, re, mpmath from mpmath import * When I deleted this line, the script ran. Why did the line from mpmath import * Trash the search function fro the regular expression module? I?m running Python 2.6.2 on Mac running OS 10.6.3. Thanks! Buff Miner -- Enig Associates, Inc. Suite 500, Bethesda Crescent Bldg. 4600 East West Hwy Bethesda, Maryland 20814 Tel:(301)680-8600 Fax:(301)680-8100 This message is intended only for the use of the intended recipient(s), and it may be privileged and confidential. If you are not the intended recipient, you are hereby notified that any review, retransmission, conversion to hard copy, copying, circulation or other use of this message is strictly prohibited and may be illegal. If you are not the intended recipient, please notify the sender immediately by return e-mail, and delete this message from your system. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Wed May 26 13:59:06 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 26 May 2010 19:59:06 +0200 Subject: Ugly modification of a class, can it be done better ? In-Reply-To: <4bf5e19e$0$27861$c3e8da3@news.astraweb.com> References: <4BF5D02A.9070600@gmail.com> <4bf5e19e$0$27861$c3e8da3@news.astraweb.com> Message-ID: <4BFD616A.3010009@gmail.com> On 21-05-2010 03:27, Steven D'Aprano wrote: > Sorry for breaking threading, but Stef's original post has not come > through to me. > > >> On Thu, May 20, 2010 at 8:13 PM, Stef Mientki >> wrote: >> > >>> So I want to change the behavior of the class dynamically. I've done it >>> by adding a global variable (Base_Grid_Double_Click) in the module, >>> initial set to None, >>> but can be changed by the main program to some callback function. (see >>> the code below) >>> > How is this supposed to work? If you have *one* global, then *every* > instance will see the same setting. But that's exactly what I need ;-) The problem is a little more complicated, I've several "frame-works", that searches for specific modules (applications) in a specific directory. The frame work should determine what should happen (e.g. on a doubleclick of a grid cell) in these modules (application), but the frame work has no idea what kind of instances are in these modules. The same module can be used in different frame-works (or even stand-alone) and the behavior of e.g. a doubleclick, can differ, depending on the frame work. Describing the situation above, I realize that the concept is already spaghetti in itself ;-) but for a modular system this works like a charm. So for the moment I'll stick to the orginal solution. thank you all for the responses. cheers, Stef Mientki > To change it dynamically, you enter a > nightmare world of having to save the global, modify it, then restore it, > every single time. Trust me, I've been there, this is the *worst* way of > programming. This is why object oriented inheritance was invented, to > escape this nonsense! > > The first thing is to make the callback specific to the class, not > global. Why does your printing code need access to the callback that > handles double-clicking on a grid? It doesn't! So don't give it that > access (at least, not easy access). Put the callback in the class. > > class MyClass: > callback = None > def method(self, *args): > if self.callback is None: > behaviour_with_no_callback() > else: > behaviour_with_callback() > > > Now if you want to apply a callback to some instances, and not others, it > is totally simple: > > > red = MyClass() > blue = MyClass() > red.callback = my_callback_function > > and you're done. > > > If you have lots of instances that use the same callback? Make a subclass. > > class MyDottedClass(MyClass): > pass > > red = MyClass() > blue = MyClass() > red_with_green_dots = MyDottedClass() > blue_with_green_dots = MyDottedClass() > > MyDottedClass.callback = dotted_callback > > And now all the dot instances will use the same callback without > effecting the undotted instances. What to change them all to use a > different behaviour? > > MyDottedClass.callback = something_different > > and now they all change, again without effecting the undotted instances. > > > > > >>> Is this a valid construction ( sorry I'm not a programmer), or are >>> there better ways to accomplish similar dynamic behavior ? >>> > Of course you're a programmer! You're writing programs, aren't you? > > > > > From clp2 at rebertia.com Wed May 26 14:09:58 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 May 2010 11:09:58 -0700 Subject: Error In-Reply-To: References: Message-ID: On Wed, May 26, 2010 at 10:48 AM, William Miner wrote: > I?m relative new to python and I puzzled by the following strange (to me) > behavior. I was taking pieces from two old scripts to build a new one. When > I began to debug it I got the following error message: > > Traceback (most recent call last): > ??File > "/Users/williamminer/ex2gen/ex2gen-3.0.5/src/ScriptDev/run_ex2gen_scan.py", > line 38, in > ????if re.search('varm',line): > AttributeError: 'function' object has no attribute 'search' > > This had worked in the previous script but not the new one. I noticed that > the new script had an additional line at the beginning (line 3) > > #!/usr/bin/env python > import sys, math, os, shutil, commands, re, mpmath > from mpmath import * > > When I deleted this line, the script ran. Why did the line > > from mpmath import * > > Trash the search function fro the regular expression module? mpmath defines a function named re() which returns the real part of a complex number. Because you used "import *", the existing value of the global variable "re", which was the regular expression module, gets clobbered with mpmath's re() function. Thus, you get that error when you try to call the "search" method on what is now a function object. This is precisely why using the `from foo import *` syntax is discouraged. Cheers, Chris -- http://blog.rebertia.com From rtw at rtw.me.uk Wed May 26 14:10:15 2010 From: rtw at rtw.me.uk (Rob Williscroft) Date: Wed, 26 May 2010 18:10:15 +0000 (UTC) Subject: UnicodeDecodeError having fetch web page References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> <1274889564.2339.16.camel@nitrogen> Message-ID: Kushal Kumaran wrote in news:1274889564.2339.16.camel at nitrogen in gmane.comp.python.general: > On Tue, 2010-05-25 at 20:12 +0000, Rob Williscroft wrote: >> Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3 >> @m21g2000vbr.googlegroups.com in gmane.comp.python.general: >> >> > Hi, >> > >> > The code below is giving me the error: >> > >> > Traceback (most recent call last): >> > File "C:\Users\Administrat??r\Desktop\test.py", line 4, in >> > >> > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position >> > 1: unexpected code byte >> > >> > >> > What am i doing wrong? >> >> It may not be you, en.wiktionary.org is sending gzip >> encoded content back, it seems to do this even if you set >> the Accept header as in: >> >> request.add_header( "Accept", "text/html" ) >> >> But maybe I'm not doing it correctly. >> > You need the Accept-Encoding: identity header. > http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html Thanks, following this I did change the line to be: request.add_header( "Accept-Encoding", "identity" ) but it made no difference to en.wiktionary.org it just sent the back a gzip encoded response. Rob. From python at mrabarnett.plus.com Wed May 26 14:13:05 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 May 2010 19:13:05 +0100 Subject: Error In-Reply-To: References: Message-ID: <4BFD64B1.2050205@mrabarnett.plus.com> William Miner wrote: > I?m relative new to python and I puzzled by the following strange (to > me) behavior. I was taking pieces from two old scripts to build a new > one. When I began to debug it I got the following error message: > > Traceback (most recent call last): > File > "/Users/williamminer/ex2gen/ex2gen-3.0.5/src/ScriptDev/run_ex2gen_scan.py", > line 38, in > if re.search('varm',line): > AttributeError: 'function' object has no attribute 'search' > > This had worked in the previous script but not the new one. I noticed > that the new script had an additional line at the beginning (line 3) > > #!/usr/bin/env python > import sys, math, os, shutil, commands, re, mpmath > from mpmath import * > > When I deleted this line, the script ran. Why did the line > > from mpmath import * > > Trash the search function fro the regular expression module? > > I?m running Python 2.6.2 on Mac running OS 10.6.3. > When you write: from mpmath import * you're importing all the 'public' names (by which I mean those not starting with '_') from the mpmath module. The mpmath module happens to contain a function called 're', so 're' will now refer to that function instead of the re module. That's why using "import *" is usually a bad idea. From darcy at druid.net Wed May 26 14:14:52 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 26 May 2010 14:14:52 -0400 Subject: Error In-Reply-To: References: Message-ID: <20100526141452.0f004cba.darcy@druid.net> On Wed, 26 May 2010 13:48:42 -0400 William Miner wrote: > #!/usr/bin/env python > import sys, math, os, shutil, commands, re, mpmath > from mpmath import * > > When I deleted this line, the script ran. Why did the line > > from mpmath import * > > Trash the search function fro the regular expression module? What is mpmath? It isn't in the standard distribution. My guess is that it has an object called "re" that is overwriting the re module. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From tjreedy at udel.edu Wed May 26 14:30:21 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 May 2010 14:30:21 -0400 Subject: TypeError: _new_() takes exactly 3 arguments (2 given) - what does it mean? In-Reply-To: <2061601704.535865.1274727159418.JavaMail.root@vms244.mailsrvcs.net> References: <2061601704.535865.1274727159418.JavaMail.root@vms244.mailsrvcs.net> Message-ID: On 5/24/2010 2:52 PM, Jesse McDonnell wrote: > I'm attempting to install Powerline http://code.google.com/p/powerline/, > a computer reservation software based on CherryPy/Python using a MYSql > database, at my local library and I've run up against an error that I > cannot google my way out of! The google groups for the application is > inactive so I'm posting on here in the hope that I can get some pointers > to get me beyond this issue. Any suggestions/pointers will be greatly > appreciated. Honestly, unless you find a Python+Powerline expert who will help, I suggest that you delete Powerline and look for something else. The most recent release is an alpha release over 2 years old. Except for the Feb 2010 wiki updates, the project appears to be dead. Even if someone helped you past this, there is no evidence that the fix would applied back to the codebase. And what about the next bug or problem? Otherwise, sign in and submit a new issue on the project tracker, with just your command line, empty config response, and traceback (if allowed, I do not know) and see if you get a response. Terry Jan Reedy From gherron at islandtraining.com Wed May 26 14:40:38 2010 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 26 May 2010 11:40:38 -0700 Subject: Error In-Reply-To: References: Message-ID: <4BFD6B26.5070609@islandtraining.com> On 05/26/2010 10:48 AM, William Miner wrote: > I'm relative new to python and I puzzled by the following strange (to > me) behavior. I was taking pieces from two old scripts to build a new > one. When I began to debug it I got the following error message: > > Traceback (most recent call last): > File > "/Users/williamminer/ex2gen/ex2gen-3.0.5/src/ScriptDev/run_ex2gen_scan.py", > line 38, in > if re.search('varm',line): > AttributeError: 'function' object has no attribute 'search' > > This had worked in the previous script but not the new one. I noticed > that the new script had an additional line at the beginning (line 3) > > #!/usr/bin/env python > import sys, math, os, shutil, commands, re, mpmath > from mpmath import * > > When I deleted this line, the script ran. Why did the line > > from mpmath import * Just a guess, (since I don;t have mpmath on hand), but if mpmath has a definition for something named re, it would overwrite any previous definition of re. So general advice says don't use the "from xxx import *" unless you really *know* what is in the module, and need *all* of it imported. Either: from mpmath import x,y,z,whatever or import re import mpmath ... re.search ... ... mpmath.whatever ... Gary Herron > > Trash the search function fro the regular expression module? > > I'm running Python 2.6.2 on Mac running OS 10.6.3. > > Thanks! > > Buff Miner > -- > Enig Associates, Inc. > Suite 500, Bethesda Crescent Bldg. > 4600 East West Hwy > Bethesda, Maryland 20814 > Tel:(301)680-8600 > Fax:(301)680-8100 > > This message is intended only for the use of the intended > recipient(s), and > it may be privileged and confidential. If you are not the intended > recipient, you are hereby notified that any review, retransmission, > conversion to hard copy, copying, circulation or other use of this message > is strictly prohibited and may be illegal. If you are not the intended > recipient, please notify the sender immediately by return e-mail, and > delete > this message from your system. Thank you. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From a_jtim at bellsouth.net Wed May 26 14:47:06 2010 From: a_jtim at bellsouth.net (Tim Arnold) Date: Wed, 26 May 2010 11:47:06 -0700 (PDT) Subject: multiprocessing and accessing server's stdout Message-ID: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Hi, I'm using multiprocessing's BaseManager to create a server on one machine and a client on another. The client fires a request and the server does some work, the result of which ends up on a shared file system that both the client and server can see. However, I need the client machine to see the stdout of the process running on the server. Not sure this is doable--I've been unable to google anything useful on this one. thanks, --Tim Arnold From pavlovevidence at gmail.com Wed May 26 15:04:53 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 May 2010 12:04:53 -0700 (PDT) Subject: TypeError: _new_() takes exactly 3 arguments (2 given) - what does it mean? References: <2061601704.535865.1274727159418.JavaMail.root@vms244.mailsrvcs.net> Message-ID: [Again, can't see the original, sorry] On May 26, 11:30?am, Terry Reedy wrote: > On 5/24/2010 2:52 PM, Jesse McDonnell wrote: > > > I'm attempting to install Powerlinehttp://code.google.com/p/powerline/, > > a computer reservation software based on CherryPy/Python using a MYSql > > database, at my local library and I've run up against an error that I > > cannot google my way out of! The google groups for the application is > > inactive so I'm posting on here in the hope that I can get some pointers > > to get me beyond this issue. Any suggestions/pointers will be greatly > > appreciated. The most common reason for this message is trying to subclass a module. (Very easy mistake when a module has the same name as a class, which is part of why I don't like the practice, though the modern PEP 8 reduces the issue.) IOW, someone did something like this: import foo class bar(foo): pass when they should have done this: from foo import foo class bar(foo): pass Carl Banks From magnus.moraberg at gmail.com Wed May 26 15:12:03 2010 From: magnus.moraberg at gmail.com (Barry) Date: Wed, 26 May 2010 12:12:03 -0700 (PDT) Subject: Fetching a gzipped webpage Message-ID: <3e151334-d5e8-4a1a-9628-d039a2e50dfd@y12g2000vbr.googlegroups.com> Hi, Here's my attempt at petching a webpage which is gzip encoded - import urllib.request import gzip import io request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ baby',headers={'Accept': 'text/html','User-Agent':'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3'} ) response = urllib.request.urlopen(request) data = response.read() compressedstream = io.StringIO(data) gzipper = gzip.GzipFile(fileobj=compressedstream) data = gzipper.read() print(data) However it gives the error: Traceback (most recent call last): File "test.py", line 9, in TypeError: initial_value must be str or None, not bytes How should I be doing this for Python 3? Thanks Barry From __peter__ at web.de Wed May 26 15:41:02 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 May 2010 21:41:02 +0200 Subject: Fetching a gzipped webpage References: <3e151334-d5e8-4a1a-9628-d039a2e50dfd@y12g2000vbr.googlegroups.com> Message-ID: Barry wrote: > Here's my attempt at petching a webpage which is gzip encoded - > > import urllib.request > import gzip > import io > > request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ > baby',headers={'Accept': 'text/html','User-Agent':'Mozilla/5.0 > (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 > (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3'} ) > response = urllib.request.urlopen(request) > data = response.read() > > compressedstream = io.StringIO(data) > > gzipper = gzip.GzipFile(fileobj=compressedstream) > data = gzipper.read() > print(data) > > > However it gives the error: > > Traceback (most recent call last): > File "test.py", line 9, in > TypeError: initial_value must be str or None, not bytes > > How should I be doing this for Python 3? Use io.BytesIO instead of io.StringIO, as Rob Williscroft showed you yesterday. Peter From nagle at animats.com Wed May 26 15:43:29 2010 From: nagle at animats.com (John Nagle) Date: Wed, 26 May 2010 12:43:29 -0700 Subject: Another Little MySQL Problem In-Reply-To: References: Message-ID: <4bfd7436$0$1611$742ec2ed@news.sonic.net> Kushal Kumaran wrote: > On Tue, 2010-05-25 at 14:45 -0400, Victor Subervi wrote: >> Hi; >> I have this code: >> >> clientCursor.execute('select ID from %s' % (personalDataTable)) >> upds = [itm[0] for itm in clientCursor] >> print "" % upds >> >> The problem is that the values passed are 1L, 2L.... When I retrieve >> them on the other end and try to convert them to integers, guess what >> happens? So how do I get rid of that "L"? What's the table definition? John Nagle From shashank.sunny.singh at gmail.com Wed May 26 15:48:46 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Thu, 27 May 2010 01:18:46 +0530 Subject: Fastest way to apply a function to an iterable Message-ID: What is the most efficient way of applying a function to all the elements of an iterable while discarding the result (i.e. operations are done only for side-effects). For example if I want to save all elements in a list of items (and am not interested in what save() returns), the simplest way is: itemlist = [i1, i2, i3....] for item in itemlist: item.save() It might be squeezing too much but is it possible to do it more efficiently by pushing the looping inside the C code and achieve some gains as is done by using map in place of a for loop when the return values need to be saved? Any suggestions will be appreciated. TIA -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Wed May 26 15:53:30 2010 From: nagle at animats.com (John Nagle) Date: Wed, 26 May 2010 12:53:30 -0700 Subject: MySQL, Python, NumPy and formatted read In-Reply-To: References: Message-ID: <4bfd7690$0$1666$742ec2ed@news.sonic.net> Ian Hoffman wrote: > Hello, > > I'm having significant Python difficulties (and I'm new to Python). > I'm trying to read BLOB ASCII (numerical) data from a MySQL database > using MySQLdb in a formatted fashion. The BLOB data is a sequence of > numbers separated by newlines (\n), like this: > 5 > 6 > 10 > 45 > etc. Note that a BLOB is not ASCII. If you're storing ASCII text, use type TEXT in SQL, not type BLOB. Don't lie to the database. It doesn't like that. And if you're going to store numbers, store numbers, not text. SQL has the usual integer and floating point types. When you read a BLOB from MySQLdb, you do not get a string. You get an object of type "bytes". This is not a Python string. Python strings can be ASCII or Unicode in Python 2.x, and in 3.x, are always Unicode. John Nagle From alister.ware at ntlworld.com Wed May 26 16:11:21 2010 From: alister.ware at ntlworld.com (Alister) Date: Wed, 26 May 2010 20:11:21 GMT Subject: Error References: Message-ID: On Wed, 26 May 2010 11:09:58 -0700, Chris Rebert wrote: > On Wed, May 26, 2010 at 10:48 AM, William Miner > wrote: >> I?m relative new to python and I puzzled by the following strange (to >> me) behavior. I was taking pieces from two old scripts to build a new >> one. When I began to debug it I got the following error message: >> >> Traceback (most recent call last): >> ??File >> "/Users/williamminer/ex2gen/ex2gen-3.0.5/src/ScriptDev/ run_ex2gen_scan.py", >> line 38, in >> ????if re.search('varm',line): >> AttributeError: 'function' object has no attribute 'search' >> >> This had worked in the previous script but not the new one. I noticed >> that the new script had an additional line at the beginning (line 3) >> >> #!/usr/bin/env python >> import sys, math, os, shutil, commands, re, mpmath from mpmath import * >> >> When I deleted this line, the script ran. Why did the line >> >> from mpmath import * >> >> Trash the search function fro the regular expression module? > > mpmath defines a function named re() which returns the real part of a > complex number. Because you used "import *", the existing value of the > global variable "re", which was the regular expression module, gets > clobbered with mpmath's re() function. Thus, you get that error when you > try to call the "search" method on what is now a function object. > > This is precisely why using the `from foo import *` syntax is > discouraged. > > Cheers, > Chris I am fairly new to Python but had already decided to opt a style that would always use import XXX rather than the from XXX import * syntax. It is nice to know that at least one of my decisions on best practice is good as an old programmer (8 bit assembler for micro controller applications) picking up the baton again for fun I have to say Python is great (I find C to be so low level I might just as well go back to assembler!). -- "Linux doesn't support any sub-32-bit computers, and despite the occasional deranged people interested in retro-computing (ie Alan Cox) I doubt it seriously will.." - Linus Torvalds From william.miner at enig.com Wed May 26 16:13:27 2010 From: william.miner at enig.com (William Miner) Date: Wed, 26 May 2010 16:13:27 -0400 Subject: Indentation Message-ID: I have a script which I would now put inside a loop. Is there any way to ?automatically? indent the old script so it can be put inside the new loop. Doing it by hand seems so inelegant and time consuming. By the way, thanks for the answer to my previous question. Thanks! Buff Miner -- Enig Associates, Inc. Suite 500, Bethesda Crescent Bldg. 4600 East West Hwy Bethesda, Maryland 20814 Tel:(301)680-8600 Fax:(301)680-8100 This message is intended only for the use of the intended recipient(s), and it may be privileged and confidential. If you are not the intended recipient, you are hereby notified that any review, retransmission, conversion to hard copy, copying, circulation or other use of this message is strictly prohibited and may be illegal. If you are not the intended recipient, please notify the sender immediately by return e-mail, and delete this message from your system. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alister.ware at ntlworld.com Wed May 26 16:17:02 2010 From: alister.ware at ntlworld.com (Alister) Date: Wed, 26 May 2010 20:17:02 GMT Subject: Another Little MySQL Problem References: <4bfd7436$0$1611$742ec2ed@news.sonic.net> Message-ID: <2lfLn.104252$Qg5.19019@newsfe06.ams2> On Wed, 26 May 2010 12:43:29 -0700, John Nagle wrote: > Kushal Kumaran wrote: >> On Tue, 2010-05-25 at 14:45 -0400, Victor Subervi wrote: >>> Hi; >>> I have this code: >>> >>> clientCursor.execute('select ID from %s' % (personalDataTable)) >>> upds = [itm[0] for itm in clientCursor] print ">> type='hidden' name='upds' value='%s' />" % upds >>> >>> The problem is that the values passed are 1L, 2L.... When I retrieve >>> them on the other end and try to convert them to integers, guess what >>> happens? So how do I get rid of that "L"? > > What's the table definition? > > John Nagle I think you should probably also write your execuete diferently: >>> clientCursor.execute('select ID from %s' , (personalDataTable,)) this ensures the parameters are correctly escaped to prevent mysql injection attacks,the "," after personalDataTable is necessary to ensure the parameter is passed as a tupple However I am fairly new so could be mistaken on exactly what your code does. -- If you analyse anything, you destroy it. -- Arthur Miller From awilliam at whitemice.org Wed May 26 16:17:56 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Wed, 26 May 2010 16:17:56 -0400 Subject: Indentation In-Reply-To: References: Message-ID: <1274905076.19105.1.camel@linux-yu4c.site> On Wed, 2010-05-26 at 16:13 -0400, William Miner wrote: > I have a script which I would now put inside a loop. Is there any way > to ?automatically? indent the old script so it can be put inside the > new loop. Doing it by hand seems so inelegant and time consuming. Open script in MonoDevelop Highlight text, right-click, click "Indent Selection" in context menu. Or any decent IDE should provide the same kind of thing. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From no.email at please.post Wed May 26 16:19:47 2010 From: no.email at please.post (kj) Date: Wed, 26 May 2010 20:19:47 +0000 (UTC) Subject: atexit/signal for non-interactive jobs Message-ID: I want to implement clean-up functions for scripts to be run on a Linux cluster (through LSF). The goal is to make sure that a minimal wrap-up sequence (print diagnostic info, flush buffers, etc.) gets executed if the job is terminated for some reason. (The most common reason for premature termination is a SIGUSR2 signal, sent to the process by LSF when the job has taken longer than the time limit for the job's LSF queue.) No matter what I try, I can't get this wrap-up sequence to work when the script runs non-interactively. The latest I have looks something like this: import signal import atexit def set_handlers(handler): atexit.register(handler) for sig in dir(signal): if sig.startswith('SIG') and not '_' in sig: signal(getattr(signal, sig), handler) def wrapup(*args): # etc, etc def main(): # ... set_handlers(wrapup) run() main() If I start the script interactively and after a few seconds (i.e. before it terminates) I hit Ctrl-C (which sends a TERM signal to the process), the wrapup function gets called as desired (although this action appears to be triggered by atexit, and not by the handler for SIGTERM, which apparently never gets called). But if instead I background the script after starting it, and then use kill to explicitly send a TERM signal to its process, the script terminates, but the wrapup code does not execute. It makes no sense to me. If someone cares to explain it, I'd be very grateful. (Is my code doing something wrong?) But more to the point, what must I do to get this to work in the non-interactive case? TIA! ~k From lex at from.hell Wed May 26 16:21:47 2010 From: lex at from.hell (Lex Lebedeff) Date: Wed, 26 May 2010 20:21:47 +0000 (UTC) Subject: Kohonen neural network References: <260cd874-fe51-4bdd-b112-f64ff7ef3050@a27g2000prj.googlegroups.com> Message-ID: On Wed, 26 May 2010 05:26:56 -0700, alex23 wrote: > On May 26, 7:21?pm, Lex Lebedeff wrote: >> Has anyone tried to build an implementation of subject in Python? Any >> help is appreciated! > > http://www.dia.fi.upm.es/~jamartin/download.htm > > Seriously, though, any reason why you couldn't just type "kohonen neural > network python" into Google? You would've found it a lot easier to wade > through the results before your question & it's many mirrors. It > would've been the 2nd entry, immediately after the wikipedia article on > Kohonen SOMs. Thanx, I've already googled this stuff. Rather unreadable and freaky code. --- news://freenews.netfront.net/ - complaints: news at netfront.net --- From python at bdurham.com Wed May 26 16:24:28 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 26 May 2010 16:24:28 -0400 Subject: Using Babel: How to protect translator comments (and old translations) in GNU gettext PO files? Message-ID: <1274905468.22843.1377075711@webmail.messagingengine.com> We're using the Python based Babel gettext utilities. Is there any technique we can use to make sure that translator comments and old ("obsolete") translations (marked with #~) in PO files are preserved across PO file updates? Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Wed May 26 16:26:34 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 26 May 2010 22:26:34 +0200 Subject: Fastest way to apply a function to an iterable In-Reply-To: References: Message-ID: Shashank Singh, 26.05.2010 21:48: > What is the most efficient way of applying a function to all the elements of > an iterable while discarding the > result (i.e. operations are done only for side-effects). > > For example if I want to save all elements in a list of items (and am not > interested in what save() returns), the > simplest way is: > > itemlist = [i1, i2, i3....] > for item in itemlist: item.save() > > It might be squeezing too much but is it possible to do it more efficiently > by pushing the looping inside the C code > and achieve some gains as is done by using map in place of a for loop when > the return values need to be saved? If all items have the exact same type, you can get away with an unbound method: class MyType(object): ... def safe(self): ... itemlist = [ MyType() for i in range(20) ] # this is what you want: from itertools import imap for _ in imap(MyType.save, itemlist): pass But some people may consider this too ugly to actually use in real code. Stefan From pavlovevidence at gmail.com Wed May 26 16:50:37 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 May 2010 13:50:37 -0700 (PDT) Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> Message-ID: <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> On May 26, 5:49?am, Rebel Lion wrote: > I made a metaclass to inherit __slots__ automatically. > > I think this feature should be included in builtin object's metaclass. I'd be ok with a metatype in the standard library that makes slots more transparent, but since slots are intended as an optimization, it doesn't really need (and might be detrimental to have) transparency for ordinary objects. However, Aahz will be by shortly to tell you never to use slots. > You can now write: > > ? ? class Foo(object): > ? ? ? ? __metaclass__ = SlotMetaclass > > ? ? ? ? @slot > ? ? ? ? def foo(): > ? ? ? ? ? ? pass > > ? ? class Bar(Foo): > > ? ? ? ? @slot > ? ? ? ? def bar(): > ? ? ? ? ? ? pass > > ? ? foo = Foo() > ? ? foo.foo = 1 > ? ? bar = Bar() > ? ? bar.bar = 1 > ? ? bar.foo = 1 > ? ? try: > ? ? ? ? bar.baz = 1 # this should fall > ? ? except AttributeError, e: > ? ? ? ? print 'yeah', e > > Instead of > > ? ? class Foo(object): > ? ? ? ? ? __slots__ = ['foo'] > ? ? class Bar(Foo) > ? ? ? ? ? __slots__ = ['foo', 'bar'] > > Please discuss the pros & cons for this feature. It seems like a good approach, but the use of decorators to define slots is hideous. I'd recommend creating slots with simple assignment instead: slot = object() class Foo(): __metaclass__ = SlotsMetaclass foo = slot class Bar(): bar = slot Then replace "isinstance(v,slot)" with "v is slot" in the metaclass. > Here is the metaclass: > > class slot(object): > ? ? """Slot Decorator""" > > ? ? def __init__(self, func): > ? ? ? ? pass > > class SlotMetaclass(type): > ? ? """Inheritable Slots Metaclass""" > > ? ? def __new__(cls, name, bases, attrs): > ? ? ? ? # make a normal class, and get its attributes to decide which > ones are slots > ? ? ? ? tmpcls = type.__new__(cls, name, bases, attrs) > ? ? ? ? slots = [] > ? ? ? ? for k in dir(tmpcls): > ? ? ? ? ? ? v = getattr(tmpcls, k) > ? ? ? ? ? ? if isinstance(v, slot): > ? ? ? ? ? ? ? ? slots.append(k) > ? ? ? ? # clean up > ? ? ? ? del tmpcls > ? ? ? ? for x in slots: > ? ? ? ? ? ? del attrs[x] > ? ? ? ? # create the real class with __slots__ > ? ? ? ? attrs['__slots__'] = slots > ? ? ? ? return type.__new__(cls, name, bases, attrs) You don't need to create a temporary class here; you should loop through the base classes and inspect their slots. Also, you don't need to recreate slots that exist in base classes, so you could just get all the new slots from the class dict. You should consider corner cases if you think it should be standard. For instance, what if a derived class defined the same slot as a a base class--it'll create a new slot in yours but it shouldn't. What if you want to create a subclass that does have a dict? Can't do it in your version. You need to consider stuff like that. Carl Banks From awilliam at whitemice.org Wed May 26 16:52:52 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Wed, 26 May 2010 16:52:52 -0400 Subject: multiprocessing and accessing server's stdout In-Reply-To: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: <1274907172.19105.8.camel@linux-yu4c.site> On Wed, 2010-05-26 at 11:47 -0700, Tim Arnold wrote: > Hi, > I'm using multiprocessing's BaseManager to create a server on one > machine and a client on another. The client fires a request and the > server does some work, the result of which ends up on a shared file > system that both the client and server can see. > However, I need the client machine to see the stdout of the process > running on the server. Not sure this is doable--I've been unable to > google anything useful on this one. Nope, it isn't. Don't use stdout, use an IPC mechanism to communicate between the client and the server if you need feedback. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From python.list at tim.thechases.com Wed May 26 16:54:25 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 26 May 2010 15:54:25 -0500 Subject: Indentation In-Reply-To: References: Message-ID: <4BFD8A81.50006@tim.thechases.com> On 05/26/2010 03:13 PM, William Miner wrote: > I have a script which I would now put inside a loop. Is there > any way to ?automatically? indent the old script so it can be > put inside the new loop. Doing it by hand seems so inelegant > and time consuming. It's usually a function of your editor -- most good editors allow you to indent/exdent a block of code. In vim (my editor of choice), you can use the ">" and "<" operators with a motion or visual block to indent one 'shiftwidth' (which uses spaces or tabs based on your 'expandtab' setting, and can mix-and-match if your 'tabstop' isn't the same as your 'shiftwidth'). Adam already demonstrated how to do it in MonoDevelop, and I think in Visual Studio (a long time since I've had to touch that beast) you can just highlight a block and press or to indent/exdent. Likely an emacs user will chime in on this thread with how to do it there too. If you're stuck with a bogus editor but are on a *nix platform, you can indent with sed: sed 's/^/ /' original.py > out.py (that's 4 spaces after the 2nd slash; adjust accordingly to your tastes) and then just copy the contents of out.py into your script. If you're on Win32 without a good editor, go get a good editor ;-) -tkc From __peter__ at web.de Wed May 26 17:09:39 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 May 2010 23:09:39 +0200 Subject: Fastest way to apply a function to an iterable References: Message-ID: Stefan Behnel wrote: > Shashank Singh, 26.05.2010 21:48: >> What is the most efficient way of applying a function to all the elements >> of an iterable while discarding the >> result (i.e. operations are done only for side-effects). >> >> For example if I want to save all elements in a list of items (and am not >> interested in what save() returns), the >> simplest way is: >> >> itemlist = [i1, i2, i3....] >> for item in itemlist: item.save() >> >> It might be squeezing too much but is it possible to do it more >> efficiently by pushing the looping inside the C code >> and achieve some gains as is done by using map in place of a for loop >> when the return values need to be saved? > > If all items have the exact same type, you can get away with an unbound > method: > > class MyType(object): > ... > def safe(self): > ... > > itemlist = [ MyType() for i in range(20) ] > > # this is what you want: > > from itertools import imap > for _ in imap(MyType.save, itemlist): pass > > > But some people may consider this too ugly to actually use in real code. Which doesn't mean it can't get worse: >>> from sys import maxint >>> from operator import attrgetter >>> from itertools import imap, islice >>> class I: ... def __init__(self, i): ... self.i = i ... def save(self): ... print "saving", self.i ... >>> items = [I(i) for i in range(5)] >>> next(islice(imap(apply, imap(attrgetter("save"), items)), maxint, maxint), None) saving 0 saving 1 saving 2 saving 3 saving 4 See also the following thread: http://mail.python.org/pipermail/python-list/2010-January/1233307.html Most real-world applications should spend significantly more time inside the save() methods than in the enclosing loop, so I'd expect the effect of this kind of optimization on the speed of your program to be negligable. Peter From shashank.sunny.singh at gmail.com Wed May 26 17:16:20 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Thu, 27 May 2010 02:46:20 +0530 Subject: Fastest way to apply a function to an iterable In-Reply-To: References: Message-ID: On Thu, May 27, 2010 at 1:56 AM, Stefan Behnel wrote: > If all items have the exact same type, you can get away with an unbound > method: > > class MyType(object): > ... > def safe(self): > ... > > itemlist = [ MyType() for i in range(20) ] > > # this is what you want: > from itertools import imap > for _ in imap(MyType.save, itemlist): pass > Thanks Stefan, I probably didn't state the problem properly. I was assuming the availability of a static method that could be passed on to map based solution (or imap for that matter). The question was, if one wants to apply a function on each member of list and discard the return value, is it possible to do it more efficiently than having a for loop in python and applying the function of each of the members? Take this run: from itertools import imap from timeit import Timer def save(x): 2 * x from itertools import imap from timeit import Timer def save(x): 2 * x def f1(): map(save, range(1000)) #simple map def f2(): for _ in imap(save, range(1000)): pass #imap def f3(): for x in range(1000):save(x) #simple iteration t1 = Timer("f1()", "from __main__ import f1") print "f1", t1.timeit(number=1000) t2 = Timer("f2()", "from __main__ import f2") print "f2", t2.timeit(number=1000) t3 = Timer("f3()", "from __main__ import f3") print "f3", t3.timeit(number=1000) The output for one run was: f1 0.393015034034 f2 0.476230638252 f3 0.376324923978 => simple for loop performs better than map/imap. Another problem with map/imap is that the memory cost is dependent on the length of the list (because of the intermediate mapped list stored) which is not the case for simple for loop. I hope I have explained it better this time. -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Wed May 26 17:26:05 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 26 May 2010 23:26:05 +0200 Subject: Fastest way to apply a function to an iterable In-Reply-To: References: Message-ID: Shashank Singh, 26.05.2010 23:16: > I probably didn't state the problem properly. I was assuming the > availability of a static method that could be passed on to map based > solution (or imap for that matter). > > The question was, if one wants to apply a function on each member of list > and discard the return value, is it possible to do it more efficiently than > having a for loop in python and applying the function of each of the > members? > > Take this run: > > from itertools import imap > from timeit import Timer > > > def save(x): 2 * x > > from itertools import imap > from timeit import Timer > > > def save(x): 2 * x > > def f1(): map(save, range(1000)) #simple map > > def f2(): > for _ in imap(save, range(1000)): pass #imap > > def f3(): > for x in range(1000):save(x) #simple iteration > > t1 = Timer("f1()", "from __main__ import f1") > print "f1", t1.timeit(number=1000) > > t2 = Timer("f2()", "from __main__ import f2") > print "f2", t2.timeit(number=1000) > > t3 = Timer("f3()", "from __main__ import f3") > print "f3", t3.timeit(number=1000) > > The output for one run was: > > f1 0.393015034034 > f2 0.476230638252 > f3 0.376324923978 > > => simple for loop performs better than map/imap. Interesting. So you've found the fastest solution already. If a simple for loop is both the most readable and the fastest way to do it, it sounds to me like you have solved your problem yourself. > Another problem with > map/imap is that the memory cost is dependent on the length of the list > (because of the intermediate mapped list stored) which is not the case for > simple for loop. ... neither is it the case for the imap() solution - but that still proves to be slower in your timings. BTW, assuming that you are using Python 2, you'd better use xrange() in benchmarks. The list creation of range() can easily spoil your timings. Stefan From debatem1 at gmail.com Wed May 26 17:51:45 2010 From: debatem1 at gmail.com (geremy condra) Date: Wed, 26 May 2010 14:51:45 -0700 Subject: Inheritable Slots Metaclass In-Reply-To: <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: On Wed, May 26, 2010 at 1:50 PM, Carl Banks wrote: > On May 26, 5:49?am, Rebel Lion wrote: >> I made a metaclass to inherit __slots__ automatically. >> >> I think this feature should be included in builtin object's metaclass. > > I'd be ok with a metatype in the standard library that makes slots > more transparent, but since slots are intended as an optimization, it > doesn't really need (and might be detrimental to have) transparency > for ordinary objects. > > However, Aahz will be by shortly to tell you never to use slots. Ok, I'll bite: why? Geremy Condra From lists at cheimes.de Wed May 26 18:24:04 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 27 May 2010 00:24:04 +0200 Subject: Another Little MySQL Problem In-Reply-To: <4bfd9b4e$0$1667$742ec2ed@news.sonic.net> References: <4bfd7436$0$1611$742ec2ed@news.sonic.net> <2lfLn.104252$Qg5.19019@newsfe06.ams2> <4bfd9b4e$0$1667$742ec2ed@news.sonic.net> Message-ID: > Actually, no. The names of tables are not quoted in SQL. > One writes > > SELECT ID FROM mytable; > > not > > SELECT ID FROM "mytable"; nit picking mode: Some RDBMS support case sensitive table names. You have to quote the table name if you using the feature. Yeah I know, it's pretty bad idea but it's possible. Christian From nagle at animats.com Wed May 26 18:30:16 2010 From: nagle at animats.com (John Nagle) Date: Wed, 26 May 2010 15:30:16 -0700 Subject: Another Little MySQL Problem In-Reply-To: <2lfLn.104252$Qg5.19019@newsfe06.ams2> References: <4bfd7436$0$1611$742ec2ed@news.sonic.net> <2lfLn.104252$Qg5.19019@newsfe06.ams2> Message-ID: <4bfd9b4e$0$1667$742ec2ed@news.sonic.net> Alister wrote: > I think you should probably also write your execute differently: > >>>> clientCursor.execute('select ID from %s' , (personalDataTable,)) > > this ensures the parameters are correctly escaped to prevent mysql > injection attacks,the "," after personalDataTable is necessary to ensure > the parameter is passed as a tuple Actually, no. The names of tables are not quoted in SQL. One writes SELECT ID FROM mytable; not SELECT ID FROM "mytable"; so you don't want to run table names through the quoting and escaping function. If the table name is a variable, you need to be very careful about where it comes from. On the other hand, if you're specifying a data value, a field that's normally quoted, as in SELECT ID from mytable WHERE mykey="foo"; you write cursor.execute("SELECT ID FROM mytable WHERE mykey=%s", (mykeyval,)) to get proper escaping. Don't put quote marks around the %s; MySQLdb does that. Also, if you're selecting every entry in a database, without a WHERE or ORDER BY clause, you will get the entries in more or less random order. John Nagle From cs at zip.com.au Wed May 26 18:35:05 2010 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 27 May 2010 08:35:05 +1000 Subject: atexit/signal for non-interactive jobs In-Reply-To: References: Message-ID: <20100526223505.GA2647@cskk.homeip.net> On 26May2010 20:19, kj wrote: | If I start the script interactively and after a few seconds (i.e. | before it terminates) I hit Ctrl-C (which sends a TERM signal to | the process), the wrapup function gets called as desired (although | this action appears to be triggered by atexit, and not by the | handler for SIGTERM, which apparently never gets called). I hate to tell you this, but ^C sends SIGINT, not SIGTERM. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ To have no errors Would be life without meaning No struggle, no joy - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html From pavlovevidence at gmail.com Wed May 26 18:42:43 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 May 2010 15:42:43 -0700 (PDT) Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: <39b6ff82-f3ae-433c-bc13-64215a81e0d5@40g2000vbr.googlegroups.com> On May 26, 2:51?pm, geremy condra wrote: > On Wed, May 26, 2010 at 1:50 PM, Carl Banks wrote: > > On May 26, 5:49?am, Rebel Lion wrote: > >> I made a metaclass to inherit __slots__ automatically. > > >> I think this feature should be included in builtin object's metaclass. > > > I'd be ok with a metatype in the standard library that makes slots > > more transparent, but since slots are intended as an optimization, it > > doesn't really need (and might be detrimental to have) transparency > > for ordinary objects. > > > However, Aahz will be by shortly to tell you never to use slots. > > Ok, I'll bite: why? I was just razzing him a bit. Carl Banks From !nospam!astrochelonian at gmail.com Wed May 26 21:01:06 2010 From: !nospam!astrochelonian at gmail.com (Eduardo Alvarez) Date: Wed, 26 May 2010 21:01:06 -0400 Subject: confusing error with nntplib Message-ID: When trying to use nntplib to connect to the news server nntp.aioe.org, a bizarre sequence of events occurs: 1) I import the module, and create an instance, as follows: s = nntplib.NNTP('nntp.aioe.org') I get no errors, which leads me to believe all went well. The I try fetching info on a newsgroup (in this case, comp.lang.python): s.group('comp.lang.python') I then get the following error: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/nntplib.py", line 345, in group resp = self.shortcmd('GROUP ' + name) File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd return self.getresp() File "/usr/lib/python2.6/nntplib.py", line 214, in getresp resp = self.getline() File "/usr/lib/python2.6/nntplib.py", line 206, in getline if not line: raise EOFError EOFError Running this a *second* time, gives me the following, different error: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/nntplib.py", line 345, in group resp = self.shortcmd('GROUP ' + name) File "/usr/lib/python2.6/nntplib.py", line 258, in shortcmd self.putcmd(line) File "/usr/lib/python2.6/nntplib.py", line 198, in putcmd self.putline(line) File "/usr/lib/python2.6/nntplib.py", line 193, in putline self.sock.sendall(line) File "", line 1, in sendall socket.error: [Errno 32] Broken pipe As this is a broken pipe, I reconnect to the server, the same way as before. When I *then* retrieving the newsgroup's info, I get no errors. I'm pretty baffled by this. It might be an issue with the server itself, but still, any input would be very appreciated. yours, -- Eduardo Alvarez "Stercus, Stercus, Stercus, moriturus sum" -- Rincewind The Wizzard From r3831110n at gmail.com Wed May 26 23:33:41 2010 From: r3831110n at gmail.com (Rebel Lion) Date: Wed, 26 May 2010 20:33:41 -0700 (PDT) Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: > I'd be ok with a metatype in the standard library that makes slots > more transparent, but since slots are intended as an optimization, it > doesn't really need (and might be detrimental to have) transparency > for ordinary objects. > But why there is __slots__ if it's not indeed needed. we should make it more usable instead of a hack, which it now looks like. > However, Aahz will be by shortly to tell you never to use slots. Obviously he didn't work on graphs, at least huge graphs. > It seems like a good approach, but the use of decorators to define > slots is hideous. ?I'd recommend creating slots with simple assignment > instead: > > slot = object() > > class Foo(): > ? ? __metaclass__ = SlotsMetaclass > ? ? foo = slot > > class Bar(): > ? ? bar = slot > > Then replace > > "isinstance(v,slot)" with "v is slot" > > in the metaclass. > This is a style not a problem. My way intents to keep the consistency with @property > You don't need to create a temporary class here; you should loop > through the base classes and inspect their slots. ? As you can see, I'm very lazy. If we got some decision here, we can surely make a better implementation that this hack. > Also, you don't > need to recreate slots that exist in base classes, so you could just > get all the new slots from the class dict. > > You should consider corner cases if you think it should be standard. > For instance, what if a derived class defined the same slot as a a > base class--it'll create a new slot in yours but it shouldn't. ?What > if you want to create a subclass that does have a dict? ?Can't do it > in your version. ?You need to consider stuff like that. > The most arguable point here. I raise this post inorder to make slot inheritable. In most cases, if a class uses slots, it is designed to be heavily used. Ans subclass of it should be heavily used too, but in this case you want to create __slots__, you have to manually lookup __slots__ of bases. But your corner is considerable. We can offer a __no_slots__ to disable slots. In conclusion, my point is: If you don't want to use slots in common days, you can subclass a class which doesn't use slots(in most cases) If you want to use slots, you need inherit parent classes' slots(in a few cases) If you don't want to use slots when you are subclassing a class which uses slots(in few cases): use a __noslots__ magic Regards, From alister.ware at ntlworld.com Thu May 27 00:10:40 2010 From: alister.ware at ntlworld.com (Alister) Date: Thu, 27 May 2010 04:10:40 GMT Subject: Another Little MySQL Problem References: <4bfd7436$0$1611$742ec2ed@news.sonic.net> <2lfLn.104252$Qg5.19019@newsfe06.ams2> <4bfd9b4e$0$1667$742ec2ed@news.sonic.net> Message-ID: <4hmLn.55618$vl7.47083@newsfe07.ams2> On Wed, 26 May 2010 15:30:16 -0700, John Nagle wrote: > Alister wrote: >> I think you should probably also write your execute differently: >> >>>>> clientCursor.execute('select ID from %s' , (personalDataTable,)) >> >> this ensures the parameters are correctly escaped to prevent mysql >> injection attacks,the "," after personalDataTable is necessary to >> ensure the parameter is passed as a tuple > > Actually, no. The names of tables are not quoted in SQL. > One writes > > SELECT ID FROM mytable; > > not > > SELECT ID FROM "mytable"; > > so you don't want to run table names through the quoting and escaping > function. If the table name is a variable, you need to be very careful > about where it comes from. > > On the other hand, if you're specifying a data value, a field that's > normally quoted, as in > > SELECT ID from mytable WHERE mykey="foo"; > > you write > > cursor.execute("SELECT ID FROM mytable WHERE mykey=%s", (mykeyval,)) > > to get proper escaping. Don't put quote marks around the %s; MySQLdb > does that. > > Also, if you're selecting every entry in a database, without a > WHERE or ORDER BY clause, you will get the entries in more or less > random order. > > John Nagle Thanks i hadn't read the search string fully. in this case if personalDataTable is generated by user input it should be carefully checked as it will still be a possible source of attack. The golden rule with user input is trust nothing. -- QOTD: "I won't say he's untruthful, but his wife has to call the dog for dinner." From nagle at animats.com Thu May 27 00:19:46 2010 From: nagle at animats.com (John Nagle) Date: Wed, 26 May 2010 21:19:46 -0700 Subject: Inheritable Slots Metaclass In-Reply-To: References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: <4bfded38$0$1644$742ec2ed@news.sonic.net> Rebel Lion wrote: >> I'd be ok with a metatype in the standard library that makes slots >> more transparent, but since slots are intended as an optimization, it >> doesn't really need (and might be detrimental to have) transparency >> for ordinary objects. >> > > But why there is __slots__ if it's not indeed needed. we should make > it more usable instead of a hack, which it now looks like. > >> However, Aahz will be by shortly to tell you never to use slots. I'd argue that "slotting" of classes should be automatic, unless a class 1) defines "__setattr__" or 2) performs an operation which visibly creates a class attribute, like "self[foo] = ...". This would handle the common use cases. Only classes to which attributes are added from outside the class would be affected. And really, if you're going to do that, you should subclass. John Nagle From pavlovevidence at gmail.com Thu May 27 00:55:54 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 May 2010 21:55:54 -0700 (PDT) Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: <381f0994-3a14-4247-862e-bc24d1d5a6bf@j36g2000prj.googlegroups.com> On May 26, 8:33?pm, Rebel Lion wrote: > > I'd be ok with a metatype in the standard library that makes slots > > more transparent, but since slots are intended as an optimization, it > > doesn't really need (and might be detrimental to have) transparency > > for ordinary objects. > > But why there is __slots__ if it's not indeed needed. we should make > it more usable instead of a hack, which it now looks like. It is needed--for optimization. The thinking is that for most uses it is not a good idea to defeat Python's dynamicsm, therefore making it too easy to add slots would be detrimental to the community because it would encourage people to use slots even when not needed. I more or less agree with this, and would be very -1 on any attempt to mske slots the "default", so to speak; however I don't think it would make slots dangerously accessible to have a user import a module and explicitly set the metaclass, for the benefit of getting rid of their weirdness. > > However, Aahz will be by shortly to tell you never to use slots. > > Obviously he didn't work on graphs, at least huge graphs. There's no need to be presumptuous. You can state your use case with accusing him of anything. > > It seems like a good approach, but the use of decorators to define > > slots is hideous. ?I'd recommend creating slots with simple assignment > > instead: > > > slot = object() > > > class Foo(): > > ? ? __metaclass__ = SlotsMetaclass > > ? ? foo = slot > > > class Bar(): > > ? ? bar = slot > > > Then replace > > > "isinstance(v,slot)" with "v is slot" > > > in the metaclass. > > This is a style not a problem. My way intents to keep the consistency > with @property It's a problem if you think this metaclass ought to be in the standard library. This "style" will never, ever make it to the standard library, ever. I guarantee you. Frankly, you're observing a pattern where there is none. You see decorator syntax and you think "Ah, that's the standard way to define attributes that affect the behavior of a class". It's not. Descriptor syntax is syntax sugar to make it less unwieldy to apply a function to a function or class. That's it, that's all it is. If you don't have a function, there is no reason for a decorator. You're entitled to your own preferred style, of course, but I'm just telling you it'll never fly with most people. > > You don't need to create a temporary class here; you should loop > > through the base classes and inspect their slots. ? > > As you can see, I'm very lazy. If we got some decision here, we can > surely make a better implementation that this hack. No, sorry, it doesn't work that way. Unless you're a known genius and/ or a long time contributor, you better have some pretty worked out code and some persuasive use cases if you want any consideration. Ideas are cheap. (If you want some inspiration, go read PEP 389.) > > Also, you don't > > need to recreate slots that exist in base classes, so you could just > > get all the new slots from the class dict. > > > You should consider corner cases if you think it should be standard. > > For instance, what if a derived class defined the same slot as a a > > base class--it'll create a new slot in yours but it shouldn't. ?What > > if you want to create a subclass that does have a dict? ?Can't do it > > in your version. ?You need to consider stuff like that. > > The most arguable point here. I raise this post inorder to make slot > inheritable. Slots already are inheritable, as I pointed out. It's just weird and complicated how they affect things. class A(object): __slots__ = ['a'] class B(A): __slots__ = ['b'] B().a = 1 # this will work > In most cases, if a class uses slots, it is designed to be heavily > used. > Ans subclass of it should be heavily used too, but in this case you > want to create __slots__, > you have to manually lookup __slots__ of bases. You don't have to, unless you want to work around some of those other corner cases I spoke of. > But your corner is considerable. We can offer a __no_slots__ to > disable slots. > > In conclusion, my point is: > > If you don't want to use slots in common days, you can subclass a > class which doesn't use slots(in most cases) > If you want to use slots, you need inherit parent classes' slots(in a > few cases) > If you don't want to use slots when you are subclassing a class which > uses slots(in few cases): > ? use a __noslots__ magic That seems like a reasonable way to handle it. I don't want to sound to pessimistic about it, I really wouldn't mind a metaclass that makes slots more normal; but you have work to do. Carl Banks From kushal.kumaran+python at gmail.com Thu May 27 01:00:14 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 10:30:14 +0530 Subject: UnicodeDecodeError having fetch web page In-Reply-To: References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> <1274889564.2339.16.camel@nitrogen> Message-ID: On Wed, May 26, 2010 at 11:40 PM, Rob Williscroft wrote: > Kushal Kumaran wrote in news:1274889564.2339.16.camel at nitrogen in > gmane.comp.python.general: > >> On Tue, 2010-05-25 at 20:12 +0000, Rob Williscroft wrote: >>> Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3 >>> @m21g2000vbr.googlegroups.com in gmane.comp.python.general: >>> >>> > Hi, >>> > >>> > The code below is giving me the error: >>> > >>> > Traceback (most recent call last): >>> > ? File "C:\Users\Administrat?r\Desktop\test.py", line 4, in >>> > ? >>> > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position >>> > 1: unexpected code byte >>> > >>> > >>> > What am i doing wrong? >>> >>> It may not be you, en.wiktionary.org is sending gzip >>> encoded content back, it seems to do this even if you set >>> the Accept header as in: >>> >>> request.add_header( "Accept", "text/html" ) >>> >>> But maybe I'm not doing it correctly. >>> >> You need the Accept-Encoding: identity header. >> http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html > > Thanks, following this I did change the line to be: > > request.add_header( "Accept-Encoding", "identity" ) > > but it made no difference to en.wiktionary.org it just sent the > back a gzip encoded response. > A known problem, I guess... https://bugzilla.wikimedia.org/show_bug.cgi?id=7098 You'll just have to handle the gzipped data. -- regards, kushal From pavlovevidence at gmail.com Thu May 27 01:16:16 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 May 2010 22:16:16 -0700 (PDT) Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> <381f0994-3a14-4247-862e-bc24d1d5a6bf@j36g2000prj.googlegroups.com> Message-ID: <21eb799f-f7ff-4d94-966d-d4a69a419583@a39g2000prb.googlegroups.com> On May 26, 9:55?pm, Carl Banks wrote: > I don't want to sound to pessimistic about it, I really wouldn't mind > a metaclass that makes slots more normal; but you have work to do. Just as a minor followup, I'll mention that slots and inheritance have some issues that aren't going to be resolvable to everyone's satisfaction, and that's another reason why I don't think slots should be accessible by default. For instance, some might assume that deriving from a class with slots automatically grants the derived class the same optimization that the base class has. Others will not even consider that the base class has slots and will assume that their derived class has dynamic attributes like most other Python classes. Who's right? I'd go with the former, for the same reason you gave, but the latter is not unreasonable. type does the latter. The best answer might be to always insist on an explicit declaration one way or another, but that makes it prone to other problems like forward compatibility issues. Point is, it's not a simple thing. Carl Banks From wuwei23 at gmail.com Thu May 27 01:16:35 2010 From: wuwei23 at gmail.com (alex23) Date: Wed, 26 May 2010 22:16:35 -0700 (PDT) Subject: Kohonen neural network References: <260cd874-fe51-4bdd-b112-f64ff7ef3050@a27g2000prj.googlegroups.com> Message-ID: <2006f79a-3d52-4dcc-b099-3ef3b3904c3a@a16g2000prg.googlegroups.com> Lex Lebedeff wrote: > Thanx, I've already googled this stuff. Rather unreadable and freaky code. Then please remember to mention what you've already seen & tried when asking in the future, it saves us all from wasting each others time. From kse.listed.co1 at gmail.com Thu May 27 01:37:29 2010 From: kse.listed.co1 at gmail.com (Naeem) Date: Wed, 26 May 2010 22:37:29 -0700 (PDT) Subject: "AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION" Message-ID: "AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION" From mail at timgolden.me.uk Thu May 27 03:39:11 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 May 2010 08:39:11 +0100 Subject: Another Little MySQL Problem In-Reply-To: References: <4bfd7436$0$1611$742ec2ed@news.sonic.net> <2lfLn.104252$Qg5.19019@newsfe06.ams2> <4bfd9b4e$0$1667$742ec2ed@news.sonic.net> Message-ID: <4BFE219F.4020006@timgolden.me.uk> On 26/05/2010 23:24, Christian Heimes wrote: >> Actually, no. The names of tables are not quoted in SQL. >> One writes >> >> SELECT ID FROM mytable; >> >> not >> >> SELECT ID FROM "mytable"; > > nit picking mode: > > Some RDBMS support case sensitive table names. You have to quote the > table name if you using the feature. Yeah I know, it's pretty bad idea > but it's possible. Also -- at least in MSSQL -- if the table name contains spaces (and probably certain other characters which I can't be bothered to research at this moment). TJG From alfps at start.no Thu May 27 06:43:17 2010 From: alfps at start.no (Alf P. Steinbach) Date: Thu, 27 May 2010 12:43:17 +0200 Subject: confusing error with nntplib In-Reply-To: References: Message-ID: * Eduardo Alvarez, on 27.05.2010 03:01: > When trying to use nntplib to connect to the news server nntp.aioe.org, > a bizarre sequence of events occurs: > > 1) I import the module, and create an instance, as follows: > > s = nntplib.NNTP('nntp.aioe.org') > > I get no errors, which leads me to believe all went well. The I try > fetching info on a newsgroup (in this case, comp.lang.python): > > s.group('comp.lang.python') > > I then get the following error: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/nntplib.py", line 345, in group > resp = self.shortcmd('GROUP ' + name) > File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd > return self.getresp() > File "/usr/lib/python2.6/nntplib.py", line 214, in getresp > resp = self.getline() > File "/usr/lib/python2.6/nntplib.py", line 206, in getline > if not line: raise EOFError > EOFError This sounds like a time-out. > Running this a *second* time, gives me the following, different error: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/nntplib.py", line 345, in group > resp = self.shortcmd('GROUP ' + name) > File "/usr/lib/python2.6/nntplib.py", line 258, in shortcmd > self.putcmd(line) > File "/usr/lib/python2.6/nntplib.py", line 198, in putcmd > self.putline(line) > File "/usr/lib/python2.6/nntplib.py", line 193, in putline > self.sock.sendall(line) > File "", line 1, in sendall > socket.error: [Errno 32] Broken pipe When you say "running this", do you mean running a Python program a second time, or issuing the same command in the interpreter a second time? For the latter the result would be more or less expected. After all, you've had an End of File on the connection. > As this is a broken pipe, I reconnect to the server, the same way as > before. When I *then* retrieving the newsgroup's info, I get no errors. > > I'm pretty baffled by this. It might be an issue with the server itself, > but still, any input would be very appreciated. Check if there's any way to specify time-outs. Check if there's any way to trace the actual commands and responses. Cheers & hth., - Alf -- blog at From timoverbeek10 at gmail.com Thu May 27 07:16:11 2010 From: timoverbeek10 at gmail.com (timo verbeek) Date: Thu, 27 May 2010 04:16:11 -0700 (PDT) Subject: type error raise Message-ID: <592e4b41-d00d-4e33-a913-fa0dc42f8b4a@c22g2000vbb.googlegroups.com> what is the problem with this code? _base={"repeat":False,"string":"Progres has failed","works":True} print _base class dictreturn(_base):pass this error Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\Documents and Settings\Owner\Desktop\Python\assistent new \user\dictreturn.py", line 4, in class dictreturn(_base):pass TypeError: Error when calling the metaclass bases From clp2 at rebertia.com Thu May 27 07:22:25 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 May 2010 04:22:25 -0700 Subject: type error raise In-Reply-To: <592e4b41-d00d-4e33-a913-fa0dc42f8b4a@c22g2000vbb.googlegroups.com> References: <592e4b41-d00d-4e33-a913-fa0dc42f8b4a@c22g2000vbb.googlegroups.com> Message-ID: On Thu, May 27, 2010 at 4:16 AM, timo verbeek wrote: > what is the problem with this code? > > _base={"repeat":False,"string":"Progres has failed","works":True} > print _base > class dictreturn(_base):pass You can't subclass a dictionary object, you can only subclass other classes. What on earth are you trying to do? Cheers, Chris -- http://blog.rebertia.com From martin.hellwig at dcuktec.org Thu May 27 07:25:11 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 27 May 2010 12:25:11 +0100 Subject: confusing error with nntplib In-Reply-To: References: Message-ID: On 05/27/10 02:01, Eduardo Alvarez wrote: > When trying to use nntplib to connect to the news server nntp.aioe.org, > a bizarre sequence of events occurs: > > 1) I import the module, and create an instance, as follows: > > s = nntplib.NNTP('nntp.aioe.org') > > I get no errors, which leads me to believe all went well. The I try > fetching info on a newsgroup (in this case, comp.lang.python): > > s.group('comp.lang.python') > > I then get the following error: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/nntplib.py", line 345, in group > resp = self.shortcmd('GROUP ' + name) > File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd > return self.getresp() > File "/usr/lib/python2.6/nntplib.py", line 214, in getresp > resp = self.getline() > File "/usr/lib/python2.6/nntplib.py", line 206, in getline > if not line: raise EOFError > EOFError > > Running this a *second* time, gives me the following, different error: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/nntplib.py", line 345, in group > resp = self.shortcmd('GROUP ' + name) > File "/usr/lib/python2.6/nntplib.py", line 258, in shortcmd > self.putcmd(line) > File "/usr/lib/python2.6/nntplib.py", line 198, in putcmd > self.putline(line) > File "/usr/lib/python2.6/nntplib.py", line 193, in putline > self.sock.sendall(line) > File "", line 1, in sendall > socket.error: [Errno 32] Broken pipe > > As this is a broken pipe, I reconnect to the server, the same way as > before. When I *then* retrieving the newsgroup's info, I get no errors. > > I'm pretty baffled by this. It might be an issue with the server itself, > but still, any input would be very appreciated. > > yours, > Here is how I approached it: # Lets see first if the server is available [martin at aspire8930 /usr/home/martin]$ telnet nntp.aioe.org nntp Trying 94.75.214.90... Connected to nntp.aioe.org. Escape character is '^]'. 200 nntp.aioe.org InterNetNews NNRP server INN 2.5.1 ready (posting ok) ^] telnet> quit Connection closed. # Okidoki seems fine # lets fire up python [martin at aspire8930 /usr/home/martin]$ python Python 2.6.4 (r264:75706, Apr 9 2010, 12:45:45) [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 Type "help", "copyright", "credits" or "license" for more information. >>> import nntplib >>> s = nntplib.NNTP('nntp.aioe.org') >>> s.group('comp.lang.python') Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.6/nntplib.py", line 345, in group resp = self.shortcmd('GROUP ' + name) File "/usr/local/lib/python2.6/nntplib.py", line 259, in shortcmd return self.getresp() File "/usr/local/lib/python2.6/nntplib.py", line 214, in getresp resp = self.getline() File "/usr/local/lib/python2.6/nntplib.py", line 206, in getline if not line: raise EOFError EOFError # Ah yes the same error, good at least the same problem. # Lets see what the docs has to say about it. >>> help(nntplib.NNTP) Help on class NNTP in module nntplib: class NNTP | # The class itself | | Methods defined here: | | __init__(self, host, port=119, user=None, password=None, readermode=None, usenetrc=True) | Initialize an instance. Arguments: | - host: hostname to connect to | - port: port to connect to (default the standard NNTP port) | - user: username to authenticate with | - password: password to use with username | - readermode: if true, send 'mode reader' command after | connecting. | | readermode is sometimes necessary if you are connecting to an | NNTP server on the local machine and intend to call | reader-specific comamnds, such as `group'. If you get | unexpected NNTPPermanentErrors, you might need to set | readermode. | # readermode seems to be worth a shot: >>> s = nntplib.NNTP('nntp.aioe.org', readermode=True) >>> s.group('comp.lang.python') ('211 2444 50405 52862 comp.lang.python', '2444', '50405', '52862', 'comp.lang.python') >>> # okidoki got something, but I have no idea why, perhaps need to have # a look at the source to see what that mode actually does. # But then again I think it would be better if you would do # that and if you are feeling generous might contribute back # to this thread what your findings where. -- mph From __peter__ at web.de Thu May 27 07:27:45 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 May 2010 13:27:45 +0200 Subject: confusing error with nntplib References: Message-ID: Eduardo Alvarez wrote: > When trying to use nntplib to connect to the news server nntp.aioe.org, > a bizarre sequence of events occurs: > > 1) I import the module, and create an instance, as follows: > > s = nntplib.NNTP('nntp.aioe.org') > > I get no errors, which leads me to believe all went well. The I try > fetching info on a newsgroup (in this case, comp.lang.python): > > s.group('comp.lang.python') > > I then get the following error: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/nntplib.py", line 345, in group > resp = self.shortcmd('GROUP ' + name) > File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd > return self.getresp() > File "/usr/lib/python2.6/nntplib.py", line 214, in getresp > resp = self.getline() > File "/usr/lib/python2.6/nntplib.py", line 206, in getline > if not line: raise EOFError > EOFError > I'm pretty baffled by this. It might be an issue with the server itself, > but still, any input would be very appreciated. I tried your example and got the EOFError, too. >>> import nntplib >>> s = nntplib.NNTP("nntp.aioe.org") >>> s.group("comp.lang.python") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/nntplib.py", line 345, in group resp = self.shortcmd('GROUP ' + name) File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd return self.getresp() File "/usr/lib/python2.6/nntplib.py", line 214, in getresp resp = self.getline() File "/usr/lib/python2.6/nntplib.py", line 206, in getline if not line: raise EOFError EOFError >>> s = nntplib.NNTP("nntp.aioe.org", readermode=True) >>> s.group("comp.lang.python") ('211 2445 50405 52863 comp.lang.python', '2445', '50405', '52863', 'comp.lang.python') nntplib.NNTP(host, readermode=True) seems to fix the problem (if it wasn't sheer luck). Peter From henrikho at gmail.com Thu May 27 08:22:55 2010 From: henrikho at gmail.com (HH) Date: Thu, 27 May 2010 05:22:55 -0700 (PDT) Subject: if, continuation and indentation Message-ID: I have a question about best practices when it comes to line wrapping/ continuation and indentation, specifically in the case of an if statement. When I write an if statement with many conditions, I prefer to use a parenthesis around the whole block and get the implicit continuation, rather than ending each line with an escape character. Thus, using the example from the style guide (http://www.python.org/dev/peps/ pep-0008/) I would write: if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") The problem should be obvious -- it's not easy to see where the conditional ends and the statement begins since they have the same indentation. Part of the problem, I suppose, is that Emacs indents 'height' and the other lines in the conditional to 4 spaces (because of the parenthesis). How do people deal with this situation? Thanks, Henrik From victorsubervi at gmail.com Thu May 27 08:34:48 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 08:34:48 -0400 Subject: Yet Another MySQL Problem Message-ID: Hi; I have this code: sql = "insert into %s (%s) values ('%%s');" % (personalDataTable, string.join(cols[1:], ', ')) # cursor.execute(sql, string.join(vals[1:], "', '")) cursor.execute('insert into %s (%s) values ("%s");' % (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '", "'))) Now, if I uncomment the 2nd line and comment the third, the command fails because, apparently, that "');" at the tail end of sql (1st line) gets chopped off. Why?? TIA, beno (Note to self: enterPeople3.py) -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric.brunel.pragmadev at gmail.com Thu May 27 08:37:36 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Thu, 27 May 2010 05:37:36 -0700 (PDT) Subject: Minor annoyances with properties Message-ID: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Hello all, I've been using Python properties quite a lot lately and I've found a few things that are a bit annoying about them in some cases. I wondered if I missed something or if anybody else has this kind of problems too, and if there are better solutions than the ones I'm using ATM. The first annoyance is when I want to specialize a property in a subclass. This happens quite often actually, and it is even sometimes the reason why a plain attribute is turned into a property: a subclass needs to do more things than the superclass when the property is updated for example. So, of course, my first try was: class A(object): def __init__(self): self._p = None def _get_p(self): return self._p def _set_p(self, p): self._p = p p = property(_get_p, _set_p) class B(A): def _set_p(self, p): ## Additional things here? super(B, self)._set_p(p) And of course, it doesn't work: the property has been bound to A._set_p in A, so any new definition of _set_p in any subclass does not replace the set method for the property. So I always have to add a line: p = property(A._get_p, _set_p) in the subclass too. This is a bit awkward to me, since I have to specify the superclass's name (super(?) can't be used, since it should take B as an argument, and B isn't defined yet?). Do I miss something? Is this the way to do it, or is there a better one? The second annoyance is when I have a property that is a list of something. I often have to do something when the contents of the list is modified. So basically, I often end up doing the following: def C(object): def __init__(self): self._l = [] def _get_l(self): return list(self._l) def _set_l(self, l): self._l = list(l) l = property(_get_l, _set_l) But then, I have to do: o = C() l = o.l l.append(42) o.l = l instead of just doing: o.l.append(42) which would seem much more natural IMHO. Is there any not too complicated way to have o.l.append(?) call something in C? And the same for o.l.remove(?), o.l[i] = ?, and everything else updating the list contents? Thanks! - Eric - From contact at xavierho.com Thu May 27 08:48:01 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 May 2010 22:48:01 +1000 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: On 27 May 2010 22:22, HH wrote: > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") > I've gotta say - I've bumped into this problem before, and I'm sure many other have - this is a valid question. It just hasn't bothered me enough to ask... Correct me if I'm wrong, but I think the following is equivalent, and looks better. Although this won't fix all ugly cases in that problem. if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or highlight > 100: raise ValueError("sorry, you lose") Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.hellwig at dcuktec.org Thu May 27 08:54:08 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 27 May 2010 13:54:08 +0100 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: On 05/27/10 13:22, HH wrote: > I have a question about best practices when it comes to line wrapping/ > continuation and indentation, specifically in the case of an if > statement. > > When I write an if statement with many conditions, I prefer to use a > parenthesis around the whole block and get the implicit continuation, > rather than ending each line with an escape character. Thus, using > the example from the style guide (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100): > raise ValueError("sorry, you lose") > > The problem should be obvious -- it's not easy to see where the > conditional ends and the statement begins since they have the same > indentation. Part of the problem, I suppose, is that Emacs indents > 'height' and the other lines in the conditional to 4 spaces (because > of the parenthesis). How do people deal with this situation? > > Thanks, > Henrik Well style guide aside (if pylint is happy with it, so am I) it depends on what I want to emphasize. For example if it is really one long line with every item in it being equally important I do this: if width == 0 and height == 0 and color == 'red' and emphasis == 'strong' \ or highlight > 100: raise ValueError("sorry, you lose") In case it doesn't display correctly, I break up the line to nearest 80th character and align the remaining part on the next line to the right to the 80th character. If I want to emphasize visually a certain part I would do something like this: if width == 0 and height == 0 and color == 'red' \ and emphasis == 'strong' or highlight > 100: raise ValueError("sorry, you lose") But these are my preference, and since it is most likely that I have to read again what I have written I write it in a way that it is most readable to me within the constraints of pylint. -- mph From jeanmichel at sequans.com Thu May 27 08:57:54 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 27 May 2010 14:57:54 +0200 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: <4BFE6C52.1060202@sequans.com> HH wrote: > I have a question about best practices when it comes to line wrapping/ > continuation and indentation, specifically in the case of an if > statement. > > When I write an if statement with many conditions, I prefer to use a > parenthesis around the whole block and get the implicit continuation, > rather than ending each line with an escape character. Thus, using > the example from the style guide (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") > > The problem should be obvious -- it's not easy to see where the > conditional ends and the statement begins since they have the same > indentation. Part of the problem, I suppose, is that Emacs indents > 'height' and the other lines in the conditional to 4 spaces (because > of the parenthesis). How do people deal with this situation? > > Thanks, > Henrik > One possible solution if ( width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100 ): raise ValueError("sorry, you lose") JM From neilc at norwich.edu Thu May 27 09:14:05 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 27 May 2010 13:14:05 GMT Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Message-ID: <8679gtFdj4U1@mid.individual.net> On 2010-05-27, eb303 wrote: > I've been using Python properties quite a lot lately and I've > found a few things that are a bit annoying about them in some > cases. I wondered if I missed something or if anybody else has > this kind of problems too, and if there are better solutions > than the ones I'm using ATM. > The first annoyance is when I want to specialize a property in a > subclass. See: URI:http://infinitesque.net/articles/2005/enhancing%20Python%27s%20property.xhtml -- Neil Cerutti *** You found a dead moose-rat. You sell the hide for $200. *** From contact at xavierho.com Thu May 27 09:14:49 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 May 2010 23:14:49 +1000 Subject: if, continuation and indentation In-Reply-To: <4BFE6C52.1060202@sequans.com> References: <4BFE6C52.1060202@sequans.com> Message-ID: On 27 May 2010 22:57, Jean-Michel Pichavant wrote: > One possible solution > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100 > ): > raise ValueError("sorry, you lose") > > But... but you have a sad face in one line! :( Good trick. -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Thu May 27 09:24:36 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 27 May 2010 15:24:36 +0200 Subject: Minor annoyances with properties In-Reply-To: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Message-ID: > Do I miss something? > Is this the way to do it, or is there a better one? A better way was introduced in Python 2.6. See http://docs.python.org/library/functions.html?highlight=property#property I have a Python only version around if you are still using Python 2.5. Christian From contact at xavierho.com Thu May 27 09:26:54 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 May 2010 23:26:54 +1000 Subject: if, continuation and indentation In-Reply-To: References: <4BFE6C52.1060202@sequans.com> Message-ID: On 27 May 2010 22:57, Jean-Michel Pichavant wrote: > One possible solution >> >> if ( >> width == 0 and >> height == 0 and >> color == 'red' and >> emphasis == 'strong' or >> highlight > 100 >> ): >> raise ValueError("sorry, you lose") >> > Oh, one minor optimisation. You can put the last condition first: if ( highlight > 100 or width == 0 and height == 0 and color == 'red' and emphasis == 'strong' ): raise ValueError("sorry, you lose") -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Thu May 27 09:34:04 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 09:34:04 -0400 Subject: Yet Another MySQL Problem In-Reply-To: References: Message-ID: On Thu, May 27, 2010 at 8:34 AM, Victor Subervi wrote: > Hi; > I have this code: > > sql = "insert into %s (%s) values ('%%s');" % (personalDataTable, > string.join(cols[1:], ', ')) > # cursor.execute(sql, string.join(vals[1:], "', '")) > cursor.execute('insert into %s (%s) values ("%s");' % > (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '", > "'))) > > Now, if I uncomment the 2nd line and comment the third, the command fails > because, apparently, that "');" at the tail end of sql (1st line) gets > chopped off. Why?? > > (Note to self: enterPeople3.py) > ...and here's another one: print 'insert into categories (Store, Category, Parent) values("%s", "%s", Null)'% (store, cat) # cursor.execute('insert into categories (Store, Category, Parent) values("%s", "%s", Null)', (store, cat)) If I print out and manually insert, all goes well. If I uncomment the 2nd line, it inserts store and cat with single quote marks and screws everything up! mysql> select * from categories; +----+------------+------------+--------+ | ID | Store | Category | Parent | +----+------------+------------+--------+ | 1 | 'products' | 'prodCat1' | NULL | | 2 | 'products' | 'prodCat2' | NULL | +----+------------+------------+--------+ as opposed to mysql> select * from categories; +----+------------+------------+--------+ | ID | Store | Category | Parent | +----+------------+------------+--------+ | 1 | products | prodCat1 | NULL | | 2 | products | prodCat2 | NULL | +----+------------+------------+--------+ TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Thu May 27 09:35:13 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 May 2010 23:35:13 +1000 Subject: if, continuation and indentation In-Reply-To: References: <4BFE6C52.1060202@sequans.com> Message-ID: On 27 May 2010 23:26, Xavier Ho wrote: > Oh, one minor optimisation. You can put the last condition first > I take that back. You really can't, without using more parans or ifs. Apologies. -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Thu May 27 10:10:55 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 27 May 2010 09:10:55 -0500 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: <4BFE7D6F.1070203@tim.thechases.com> On 05/27/2010 07:22 AM, HH wrote: > When I write an if statement with many conditions, I prefer to use a > parenthesis around the whole block and get the implicit continuation, > rather than ending each line with an escape character. Thus, using > the example from the style guide (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100): > raise ValueError("sorry, you lose") While it's not PEP material, I tend to use the coding standards I learned working for Computer Sciences Corporation (10 yrs ago, so things may have changed) that mandated 2 levels of indentation for continued lines, turning the above into if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight> 100): # or the closing "):" on this line, # aligned with the previous line raise ValueError("sorry, you lose") which is fairly close to Jean-Michel's proposal. -tkc From kushal.kumaran at gmail.com Thu May 27 10:17:53 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 19:47:53 +0530 Subject: Yet Another MySQL Problem In-Reply-To: References: Message-ID: <1274969873.2411.4.camel@nitrogen> On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote: > Hi; > I have this code: > > sql = "insert into %s (%s) values ('%%s');" % (personalDataTable, > string.join(cols[1:], ', ')) > # cursor.execute(sql, string.join(vals[1:], "', '")) > cursor.execute('insert into %s (%s) values ("%s");' % > (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], > '", "'))) > > Now, if I uncomment the 2nd line and comment the third, the command > fails because, apparently, that "');" at the tail end of sql (1st > line) gets chopped off. Why?? That's not why it is failing. The second argument to cursor.execute must be a tuple of values that will be escaped and interpolated into the query. You are passing in a string instead. Also, you'll need as many %s in the values clause as the number of columns you have. Basically, the query needs to be something like: insert into tablename (col1, col2, col3) values (%s, %s, %s) and the tuple argument to cursor.execute will have to have three values. Also, lose the single quotes around the %s. -- regards, kushal From kushal.kumaran at gmail.com Thu May 27 10:19:35 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 19:49:35 +0530 Subject: Yet Another MySQL Problem In-Reply-To: References: Message-ID: <1274969975.2411.6.camel@nitrogen> On Thu, 2010-05-27 at 09:34 -0400, Victor Subervi wrote: > On Thu, May 27, 2010 at 8:34 AM, Victor Subervi > wrote: > Hi; > I have this code: > > sql = "insert into %s (%s) values ('%%s');" % > (personalDataTable, string.join(cols[1:], ', ')) > # cursor.execute(sql, string.join(vals[1:], "', '")) > cursor.execute('insert into %s (%s) values ("%s");' % > (personalDataTable, string.join(cols[1:], ', '), > string.join(vals[1:], '", "'))) > > Now, if I uncomment the 2nd line and comment the third, the > command fails because, apparently, that "');" at the tail end > of sql (1st line) gets chopped off. Why?? > > (Note to self: enterPeople3.py) > > ...and here's another one: > > print 'insert into categories (Store, Category, Parent) > values("%s", "%s", Null)'% (store, cat) > # cursor.execute('insert into categories (Store, Category, > Parent) values("%s", "%s", Null)', (store, cat)) > Lose the quotes around the %s. I'm pretty sure somebody mentioned this in the previous MySQL problem thread. -- regards, kushal From victorsubervi at gmail.com Thu May 27 10:30:53 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 10:30:53 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <1274969873.2411.4.camel@nitrogen> References: <1274969873.2411.4.camel@nitrogen> Message-ID: On Thu, May 27, 2010 at 10:17 AM, Kushal Kumaran wrote: > On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote: > > Hi; > > I have this code: > > > > sql = "insert into %s (%s) values ('%%s');" % (personalDataTable, > > string.join(cols[1:], ', ')) > > # cursor.execute(sql, string.join(vals[1:], "', '")) > > cursor.execute('insert into %s (%s) values ("%s");' % > > (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], > > '", "'))) > > > > Now, if I uncomment the 2nd line and comment the third, the command > > fails because, apparently, that "');" at the tail end of sql (1st > > line) gets chopped off. Why?? > > That's not why it is failing. > > The second argument to cursor.execute must be a tuple of values that > will be escaped and interpolated into the query. You are passing in a > string instead. > So I tried this: sql = "insert into %s (%s) values (%%s);" % (personalDataTable, string.join(cols[1:], ', ')) cursor.execute(sql, vals[1:]) and got this: A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /var/www/html/angrynates.com/cart/enterPeople3.py 85 print "Enter more personal data?
" % personalDataTable 86 print "Enter products?" 87 print '\n' 88 89 enterPeople3() enterPeople3 = /var/www/html/angrynates.com/cart/enterPeople3.py in enterPeople3() 42 # We will not include the ID column 43 sql = "insert into %s (%s) values (%%s);" % (personalDataTable, string.join(cols[1:], ', ')) 44 cursor.execute(sql, vals[1:]) 45 # cursor.execute(sql, string.join(vals[1:], "', '")) 46 # cursor.execute('insert into %s (%s) values ("%s");' % (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '", "'))) cursor = , cursor.execute = >, sql = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email, PW, State, ShippingState) values (%s);', vals = ['Null', 'prescriptions', 'Beno', 'Candelon', '123', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR'] /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in execute(self=, query='insert into doctorsPersonalData (Store, FirstNam...OB, Email, PW, State, ShippingState) values (%s);', args=['prescriptions', 'Beno', 'Candelon', '123', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR']) 146 query = query.encode(charset) 147 if args is not None: 148 query = query % db.literal(args) 149 try: 150 r = self._query(query) query = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email, PW, State, ShippingState) values (%s);', db = , db.literal = >, args = ['prescriptions', 'Beno', 'Candelon', '123', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR'] TypeError: not all arguments converted during string formatting args = ('not all arguments converted during string formatting',) You sure about not converting to string?? Also, lose the single quotes around the %s. > Well, sure, if not converting to string. Otherwise it's needed. Dennis advised not using quotes, but what he meant was not using double quotes. Single quotes, I have found by experimentation, do work. TIA beno > > -- > regards, > kushal > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu May 27 10:32:53 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 May 2010 15:32:53 +0100 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: <4BFE8295.2090307@mrabarnett.plus.com> HH wrote: > I have a question about best practices when it comes to line wrapping/ > continuation and indentation, specifically in the case of an if > statement. > > When I write an if statement with many conditions, I prefer to use a > parenthesis around the whole block and get the implicit continuation, > rather than ending each line with an escape character. Thus, using > the example from the style guide (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") > > The problem should be obvious -- it's not easy to see where the > conditional ends and the statement begins since they have the same > indentation. Part of the problem, I suppose, is that Emacs indents > 'height' and the other lines in the conditional to 4 spaces (because > of the parenthesis). How do people deal with this situation? > I would probably use half-indentation: if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") Try doing that with tabs! :-) From kushal.kumaran at gmail.com Thu May 27 11:17:04 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 20:47:04 +0530 Subject: Yet Another MySQL Problem In-Reply-To: References: <1274969873.2411.4.camel@nitrogen> Message-ID: <1274973424.2411.13.camel@nitrogen> On Thu, 2010-05-27 at 10:30 -0400, Victor Subervi wrote: > On Thu, May 27, 2010 at 10:17 AM, Kushal Kumaran > wrote: > > On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote: > > Hi; > > I have this code: > > > > sql = "insert into %s (%s) values ('%%s');" % > (personalDataTable, > > string.join(cols[1:], ', ')) > > # cursor.execute(sql, string.join(vals[1:], "', '")) > > cursor.execute('insert into %s (%s) values ("%s");' % > > (personalDataTable, string.join(cols[1:], ', '), > string.join(vals[1:], > > '", "'))) > > > > Now, if I uncomment the 2nd line and comment the third, the > command > > fails because, apparently, that "');" at the tail end of sql > (1st > > line) gets chopped off. Why?? > > > That's not why it is failing. > > The second argument to cursor.execute must be a tuple of > values that > will be escaped and interpolated into the query. You are > passing in a > string instead. > > So I tried this: > > sql = "insert into %s (%s) values (%%s);" % (personalDataTable, > string.join(cols[1:], ', ')) > cursor.execute(sql, vals[1:]) > > and got this: > > > query = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email, > PW, State, ShippingState) values (%s);', db = 0x2b4c17e707e0 to Connection>, db.literal = Connection.literal of <_mysql.connection open to 'localhost' at > e6b08c0>>, args = ['prescriptions', 'Beno', 'Candelon', '123', '456', > '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', > '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR'] > > TypeError: not all arguments converted during string formatting > args = ('not all arguments converted during string > formatting',) > > > You sure about not converting to string?? > Yep, pretty sure. You still need to have as many %s in the query string as the number of values. Since you seem to be passing in 19 values (by a rough count), the query string must be like this: insert into doctorsPersonalData (Store, FirstNam.....) values (%s, %s, %s, ...19 of these) not insert into doctorsPersonalData (Store, FirstNam.....) values (%s) The exception with the "not all arguments converted" message says you have too few %s. > > > Also, lose the single quotes around the %s. > > Well, sure, if not converting to string. Otherwise it's needed. Dennis > advised not using quotes, but what he meant was not using double > quotes. Single quotes, I have found by experimentation, do work. You seem to have a strange definition of "work". -- regards, kushal From harald.luessen at gmx.de Thu May 27 11:34:46 2010 From: harald.luessen at gmx.de (Harald Luessen) Date: Thu, 27 May 2010 17:34:46 +0200 Subject: if, continuation and indentation References: Message-ID: <114tv5pu0ou7auj9kkpakqmhjcsuj38a10@4ax.com> On Thu, 27 May 2010 HH wrote: >I have a question about best practices when it comes to line wrapping/ >continuation and indentation, specifically in the case of an if >statement. > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") My solution would probably look like this: if ( width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100 ): raise ValueError("sorry, you lose") Harald From a_jtim at bellsouth.net Thu May 27 11:36:45 2010 From: a_jtim at bellsouth.net (Tim Arnold) Date: Thu, 27 May 2010 08:36:45 -0700 (PDT) Subject: multiprocessing and accessing server's stdout References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: On May 26, 4:52?pm, Adam Tauno Williams wrote: > On Wed, 2010-05-26 at 11:47 -0700, Tim Arnold wrote: > > Hi, > > I'm using multiprocessing's BaseManager to create a server on one > > machine and a client on another. The client fires a request and the > > server does some work, the result of which ends up on a shared file > > system that both the client and server can see. > > However, I need the client machine to see the stdout of the process > > running on the server. Not sure this is doable--I've been unable to > > google anything useful on this one. > > Nope, it isn't. ?Don't use stdout, use an IPC mechanism to communicate > between the client and the server if you need feedback. > -- > Adam Tauno Williams LPIC-1, Novell CLA > > OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba Thanks for that info, it saves me some time. This is a new area for me though: do you redirect stdout on the server to a socket and have the client listen and somehow pipe the sockets contents to the client stdout? Interestingly, the RPYc package manages it--that is, the client gets the stdout of the server process, so I'll dig into that code to get an idea. In the meantime, are there any recipes or other docs that would be helpful? I've been googling but without much luck. thanks, --Tim From alain at dpt-info.u-strasbg.fr Thu May 27 11:37:30 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 27 May 2010 17:37:30 +0200 Subject: if, continuation and indentation References: Message-ID: <87typtl5j9.fsf@dpt-info.u-strasbg.fr> HH writes: > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") I prefer to see the "and" at the beginning of continuation lines, and usually group related items. I never mix operators without putting explicit parentheses. Something like: if ( width == 0 and height == 0 and color == 'red' and ( emphasis == 'strong' or highlight > 100 ) ): raise ValueError("sorry, you lose") Anyway, choose your style and stick to it. > The problem should be obvious -- it's not easy to see where the > conditional ends and the statement begins since they have the same > indentation. Part of the problem, I suppose, is that Emacs indents > 'height' and the other lines in the conditional to 4 spaces (because > of the parenthesis). Emacs aligns "height" with "width", not with the parenthesis. You can put as many spaces as you want before "(" or between "(" and "width", and the following lines will follow. At least that's what happens with my stock emacs-snapshot on ubuntu, with python.el. If you use a backslashes at the end of line, emacs will double-indent the following lines, but I think you said you prefer paretheses... -- Alain. From jeanmichel at sequans.com Thu May 27 11:46:21 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 27 May 2010 17:46:21 +0200 Subject: if, continuation and indentation In-Reply-To: <4BFE8295.2090307@mrabarnett.plus.com> References: <4BFE8295.2090307@mrabarnett.plus.com> Message-ID: <4BFE93CD.3010408@sequans.com> MRAB wrote: > HH wrote: >> I have a question about best practices when it comes to line wrapping/ >> continuation and indentation, specifically in the case of an if >> statement. >> >> When I write an if statement with many conditions, I prefer to use a >> parenthesis around the whole block and get the implicit continuation, >> rather than ending each line with an escape character. Thus, using >> the example from the style guide (http://www.python.org/dev/peps/ >> pep-0008/) I would write: >> >> if (width == 0 and >> height == 0 and >> color == 'red' and >> emphasis == 'strong' or >> highlight > 100): >> raise ValueError("sorry, you lose") >> >> The problem should be obvious -- it's not easy to see where the >> conditional ends and the statement begins since they have the same >> indentation. Part of the problem, I suppose, is that Emacs indents >> 'height' and the other lines in the conditional to 4 spaces (because >> of the parenthesis). How do people deal with this situation? >> > I would probably use half-indentation: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") > > Try doing that with tabs! :-) if (width ==0 and ' \\ // ' and height == 0 and ' \\// ' and color == 'red' and ' /OO\ ' and emphasis == 'strong' and ' \> 100): raise ValueError("sorry, you lose") Try doing this with spaces !! :p JM From kushal.kumaran at gmail.com Thu May 27 12:11:34 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 21:41:34 +0530 Subject: Yet Another MySQL Problem In-Reply-To: <1274973424.2411.13.camel@nitrogen> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> Message-ID: <1274976694.2411.17.camel@nitrogen> On Thu, 2010-05-27 at 20:47 +0530, Kushal Kumaran wrote: > On Thu, 2010-05-27 at 10:30 -0400, Victor Subervi wrote: > > On Thu, May 27, 2010 at 10:17 AM, Kushal Kumaran > > wrote: > > > > On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote: > > > Hi; > > > I have this code: > > > > > > sql = "insert into %s (%s) values ('%%s');" % > > (personalDataTable, > > > string.join(cols[1:], ', ')) > > > # cursor.execute(sql, string.join(vals[1:], "', '")) > > > cursor.execute('insert into %s (%s) values ("%s");' % > > > (personalDataTable, string.join(cols[1:], ', '), > > string.join(vals[1:], > > > '", "'))) > > > > > > Now, if I uncomment the 2nd line and comment the third, the > > command > > > fails because, apparently, that "');" at the tail end of sql > > (1st > > > line) gets chopped off. Why?? > > > > > > That's not why it is failing. > > > > The second argument to cursor.execute must be a tuple of > > values that > > will be escaped and interpolated into the query. You are > > passing in a > > string instead. > > > > So I tried this: > > > > sql = "insert into %s (%s) values (%%s);" % (personalDataTable, > > string.join(cols[1:], ', ')) > > cursor.execute(sql, vals[1:]) > > > > and got this: > > > > > > > > query = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email, > > PW, State, ShippingState) values (%s);', db = > 0x2b4c17e707e0 to Connection>, db.literal = > Connection.literal of <_mysql.connection open to 'localhost' at > > e6b08c0>>, args = ['prescriptions', 'Beno', 'Candelon', '123', '456', > > '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', > > '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR'] > > > > TypeError: not all arguments converted during string formatting > > args = ('not all arguments converted during string > > formatting',) > > > > > > You sure about not converting to string?? > > > > Yep, pretty sure. You still need to have as many %s in the query string > as the number of values. Since you seem to be passing in 19 values (by > a rough count), the query string must be like this: > > insert into doctorsPersonalData (Store, FirstNam.....) values > (%s, %s, %s, ...19 of these) > > not > > insert into doctorsPersonalData (Store, FirstNam.....) values > (%s) > > The exception with the "not all arguments converted" message says you > have too few %s. > > > > > > > Also, lose the single quotes around the %s. > > > > Well, sure, if not converting to string. Otherwise it's needed. Dennis > > advised not using quotes, but what he meant was not using double > > quotes. Single quotes, I have found by experimentation, do work. > > You seem to have a strange definition of "work". > Since I'm in a good mood today, here's a little present: def insert(cursor, table, columns, values): """Insert a row into a table. columns must be a list of column names. values must be a list of values for the new row. The columns and values must correspond.""" assert len(columns) == len(values) stmt = """ insert into %s (%s) values (%s) """ % (table, ', '.join(columns), ', '.join('%s' * len(values))) logging.debug('stmt: %s, values: %s' % (stmt, values)) cursor.execute(stmt, values) Hope it helps. -- regards, kushal From topherw6 at hotmail.com Thu May 27 12:27:22 2010 From: topherw6 at hotmail.com (speedy66) Date: Thu, 27 May 2010 09:27:22 -0700 (PDT) Subject: matplotlib: show xticks only for discrete times Message-ID: <28696606.post@talk.nabble.com> I am plotting data that depends on time and height using pcolor. The data is collected every 30 minutes, so there will be data at 1PM and again at 1:30PM for instance. My question deals with how to get xticks to show up only for time values that actually exist in the dataset. As an example, ticks will currently appear at a time that corresponds to 1:24PM which is not a time where data exists. These values change as I zoom in also. I'm using matplotlib.pyplot. I've tried searching around for the answer, but have not been successful. Thanks in advance. -- View this message in context: http://old.nabble.com/matplotlib%3A-show-xticks-only-for-discrete-times-tp28696606p28696606.html Sent from the Python - python-list mailing list archive at Nabble.com. From victorsubervi at gmail.com Thu May 27 12:32:54 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 12:32:54 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <1274976694.2411.17.camel@nitrogen> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> Message-ID: On Thu, May 27, 2010 at 12:11 PM, Kushal Kumaran wrote: > Since I'm in a good mood today, here's a little present: > > def insert(cursor, table, columns, values): > """Insert a row into a table. columns must be a list of column > names. values must be a list of values for the new row. The > columns and values must correspond.""" > assert len(columns) == len(values) > > stmt = """ > insert into %s (%s) values (%s) > """ % (table, > ', '.join(columns), > ', '.join('%s' * len(values))) > logging.debug('stmt: %s, values: %s' % (stmt, values)) > > cursor.execute(stmt, values) > > Glad you're in a good mood :) First, I got an error because logging isn't defined. What should I import? I commented out that line. Here's my original code, which is now commented out: ## cursor.execute('insert into %s (%s) values ("%s");' % (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '", "'))) I ran this with your code: insert(cursor, personalDataTable, cols[1:], vals[1:]) and got this error: /var/www/html/angrynates.com/cart/enterPeople3.py 97 print "Enter more personal data?
" % personalDataTable 98 print "Enter products?" 99 print '\n' 100 101 enterPeople3() enterPeople3 = /var/www/html/angrynates.com/cart/enterPeople3.py in enterPeople3() 51 if whatDo == 'insert': 52 # We will not include the ID column 53 insert(cursor, personalDataTable, cols[1:], vals[1:]) 54 # sql = "insert into %s (%s) values (%%s);" % (personalDataTable, string.join(cols[1:], ', ')) 55 # cursor.execute(sql, vals[1:]) global insert = , cursor = , personalDataTable = 'doctorsPersonalData', cols = ['ID', 'Store', 'FirstName', 'LastName', 'Phone', 'Cell', 'Fax', 'Address1', 'Address2', 'City', 'Zip', 'ShippingAddress1', 'ShippingAddress2', 'ShippingCity', 'ShippingZip', 'DOB', 'Email', 'PW', 'State', 'ShippingState'], vals = ['Null', 'prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK'] /var/www/html/angrynates.com/cart/enterPeople3.py in insert(cursor=, table='doctorsPersonalData', columns=['Store', 'FirstName', 'LastName', 'Phone', 'Cell', 'Fax', 'Address1', 'Address2', 'City', 'Zip', 'ShippingAddress1', 'ShippingAddress2', 'ShippingCity', 'ShippingZip', 'DOB', 'Email', 'PW', 'State', 'ShippingState'], values=['prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK']) 19 ', '.join('%s' * len(values))) 20 # logging.debug('stmt: %s, values: %s' % (stmt, values)) 21 cursor.execute(stmt, values) 22 23 def enterPeople3(): cursor = , cursor.execute = >, stmt = '\ninsert into doctorsPersonalData (Store, FirstNa... %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s)\n', values = ['prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK'] /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in execute(self=, query='\ninsert into doctorsPersonalData (Store, FirstNa... %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s)\n', args=['prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK']) 146 query = query.encode(charset) 147 if args is not None: 148 query = query % db.literal(args) 149 try: 150 r = self._query(query) query = '\ninsert into doctorsPersonalData (Store, FirstNa... %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s)\n', db = , db.literal = >, args = ['prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK'] ValueError: unsupported format character ',' (0x2c) at index 221 args = ("unsupported format character ',' (0x2c) at index 221",) It appears to be separating the '%' from the 's' in your assert of '%s', but since I don't know anything about asserts, I'm hoping you can help me here. TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From henrikho at gmail.com Thu May 27 12:45:55 2010 From: henrikho at gmail.com (HH) Date: Thu, 27 May 2010 09:45:55 -0700 (PDT) Subject: if, continuation and indentation References: <87typtl5j9.fsf@dpt-info.u-strasbg.fr> Message-ID: <45063f53-e811-4d5a-97de-c81c9038b801@e21g2000vbl.googlegroups.com> On May 27, 11:37?am, Alain Ketterlin wrote: > HH writes: > > ? ? if (width == 0 and > > ? ? ? ? height == 0 and > > ? ? ? ? color == 'red' and > > ? ? ? ? emphasis == 'strong' or > > ? ? ? ? highlight > 100): > > ? ? ? ? raise ValueError("sorry, you lose") > > I prefer to see the "and" at the beginning of continuation lines, and > usually group related items. I never mix operators without putting > explicit parentheses. Something like: > > ? ? ?if ?( ?width == 0 and height == 0 > ? ? ? ? ? ? and color == 'red' > ? ? ? ? ? ? and ( emphasis == 'strong' or highlight > 100 ) ): > ? ? ? ? ?raise ValueError("sorry, you lose") Thanks for all suggestions! I like this solution a lot. I agree with your statement about mixed operators and explicit parentheses -- expecially since the eye/brain parser often does it wrong, and I believe you demonstrated that above... In [29]: print(False and (False or True)) False In [30]: print(False and False or True) True > If you use a backslashes at the end of line, emacs will double-indent > the following lines, but I think you said you prefer paretheses... Yes, I much prefer the parentheses -- partly because PEP-8 suggests it but mostly because the escapes get lost too easily. HH From python at mrabarnett.plus.com Thu May 27 12:56:41 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 May 2010 17:56:41 +0100 Subject: Yet Another MySQL Problem In-Reply-To: <1274976694.2411.17.camel@nitrogen> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> Message-ID: <4BFEA449.2010105@mrabarnett.plus.com> Kushal Kumaran wrote: [snip] > Since I'm in a good mood today, here's a little present: > > def insert(cursor, table, columns, values): > """Insert a row into a table. columns must be a list of column > names. values must be a list of values for the new row. The > columns and values must correspond.""" > assert len(columns) == len(values) > > stmt = """ > insert into %s (%s) values (%s) > """ % (table, > ', '.join(columns), > ', '.join('%s' * len(values))) That should be: ', '.join(['%s'] * len(values))) > logging.debug('stmt: %s, values: %s' % (stmt, values)) > > cursor.execute(stmt, values) > > Hope it helps. > From jjposner at optimum.net Thu May 27 13:10:46 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 27 May 2010 13:10:46 -0400 Subject: Minor annoyances with properties In-Reply-To: <8679gtFdj4U1@mid.individual.net> References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> <8679gtFdj4U1@mid.individual.net> Message-ID: <4BFEA796.5080902@optimum.net> On 5/27/2010 9:14 AM, Neil Cerutti wrote: > On 2010-05-27, eb303 wrote: >> I've been using Python properties quite a lot lately and I've >> found a few things that are a bit annoying about them in some >> cases. I wondered if I missed something or if anybody else has >> this kind of problems too, and if there are better solutions >> than the ones I'm using ATM. > >> The first annoyance is when I want to specialize a property in a >> subclass. > > See: > > URI:http://infinitesque.net/articles/2005/enhancing%20Python%27s%20property.xhtml > Very nice idea, but I think this solution works too hard and not quite correctly. In Python 2.6.5, checking the name of the OProperty object's "fget" method: if self.fget.__name__ == '' or not self.fget.__name__: ... doesn't distinguish between the original class's get-the-value method and the derived class's. (Did something change between 2005-11-02 and now?) Moreover, you don't *need* to perform this check -- just let *getattr* do the work of finding the right method. These method defs work fine for me: def __get__(self, obj, objtype): if self.fget: return getattr(obj, self.fget.__name__)() else: raise AttributeError, "unreadable attribute" def __set__(self, obj, value): if self.fset: getattr(obj, self.fset.__name__)(value) else: raise AttributeError, "can't set attribute" -John From kushal.kumaran at gmail.com Thu May 27 13:12:56 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 22:42:56 +0530 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEA449.2010105@mrabarnett.plus.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> Message-ID: <1274980376.4183.0.camel@nitrogen> On Thu, 2010-05-27 at 17:56 +0100, MRAB wrote: > Kushal Kumaran wrote: > [snip] > > Since I'm in a good mood today, here's a little present: > > > > def insert(cursor, table, columns, values): > > """Insert a row into a table. columns must be a list of column > > names. values must be a list of values for the new row. The > > columns and values must correspond.""" > > assert len(columns) == len(values) > > > > stmt = """ > > insert into %s (%s) values (%s) > > """ % (table, > > ', '.join(columns), > > ', '.join('%s' * len(values))) > > That should be: > > ', '.join(['%s'] * len(values))) My bad. Tested with sqlite using '?' as the placeholder, then simply replaced with '%s'. -- regards, kushal From sed at thechases.com Thu May 27 13:15:16 2010 From: sed at thechases.com (Tim Chase) Date: Thu, 27 May 2010 12:15:16 -0500 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEA449.2010105@mrabarnett.plus.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> Message-ID: <4BFEA8A4.2040202@thechases.com> On 05/27/2010 11:56 AM, MRAB wrote: > Kushal Kumaran wrote: >> ', '.join('%s' * len(values))) > > That should be: > > ', '.join(['%s'] * len(values))) Or as I've done in the past: ', '.join('%s' for _ in values) -tkc From victorsubervi at gmail.com Thu May 27 13:56:01 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 13:56:01 -0400 Subject: A Quick MySQL Question In-Reply-To: References: Message-ID: On Thu, May 27, 2010 at 1:37 PM, Dennis Lee Bieber wrote: > On Wed, 26 May 2010 08:29:21 -0400, Victor Subervi > declaimed the following in > gmane.comp.python.general: > > > valueList = ("%value1", "%value2", "%value3") > > If I'd coded it correctly, there should have been a % on both sides > (I didn't actually test the statement, was coding from memory -- might > have needed to double up the % to escape them) > > > cur.execute("select * from table where name1 like %s and name2 like %s > and > > name3 like %s", ("%value1", "%value2", "%value3")) > > > > Why do the values have that extra "%"? > > Wild card -- match zero or more characters > > %value1% will match "value1" /anywhere/ in the field name1; useful > if doing keyword searches on text fields. > > To use my card catalog example: > > BOOK(title, author) > "Witch World", "Andre Norton" > "A Mankind Witch", "Dave Freer" > "Three Against the Witch World", "Andre Norton" > "The Jargoon Pard", "Andre Norton" > > names = ["author", "title"] > values = ["Norton", "Witch"] > > The final SQL statement should become > > select * from BOOK > where author like "%Norton%" > and title like "%Witch%" > > and that statement will find the first and third book listed. > Ok. Now I understand. Thank you! beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Thu May 27 14:00:15 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 14:00:15 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEA449.2010105@mrabarnett.plus.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> Message-ID: On Thu, May 27, 2010 at 12:56 PM, MRAB wrote: > Kushal Kumaran wrote: > [snip] > > Since I'm in a good mood today, here's a little present: >> >> def insert(cursor, table, columns, values): >> """Insert a row into a table. columns must be a list of column >> names. values must be a list of values for the new row. The >> columns and values must correspond.""" >> assert len(columns) == len(values) >> >> stmt = """ >> insert into %s (%s) values (%s) >> """ % (table, >> ', '.join(columns), >> ', '.join('%s' * len(values))) >> > > That should be: > > > ', '.join(['%s'] * len(values))) > > logging.debug('stmt: %s, values: %s' % (stmt, values)) >> >> cursor.execute(stmt, values) >> >> Hope it helps. >> >> Yes it did. Thanks. Also figured out the "import logging" :-} beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Thu May 27 14:07:02 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 May 2010 19:07:02 +0100 Subject: matplotlib: show xticks only for discrete times In-Reply-To: <28696606.post@talk.nabble.com> References: <28696606.post@talk.nabble.com> Message-ID: On 27/05/2010 17:27, speedy66 wrote: > > I am plotting data that depends on time and height using pcolor. The data is > collected every 30 minutes, so there will be data at 1PM and again at 1:30PM > for instance. > > My question deals with how to get xticks to show up only for time values > that actually exist in the dataset. As an example, ticks will currently > appear at a time that corresponds to 1:24PM which is not a time where data > exists. These values change as I zoom in also. I'm using > matplotlib.pyplot. > > I've tried searching around for the answer, but have not been successful. > > Thanks in advance. > > See http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks matplotlib also has it's own mailing list. HTH Mark Lawrence From victorsubervi at gmail.com Thu May 27 14:16:10 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 14:16:10 -0400 Subject: Some More MySQL Message-ID: Hi; But what about this? sql = "select pic%d from %s where ID='%%s';" % (pic, store) cursor.execute(sql % id) If I try and rewrite the last line like this: cursor.execute(sql, id) it doesn't work. What do? How about this one: cursor.execute("insert into categories (Store, Category, Parent) values('%s', '%s', Null)", (store, cat)) For some reason it puts single quotes around my variables! This doesn't happen if I change that comma for a percent sign! What do? How about this one: sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + opTable[1:]) # cursor.execute(sql, id) cursor.execute('select * from options%s where ID=%s' % (opTable[0].upper() + opTable[1:], id)) The last one works, but if I comment it out and uncomment the middle line, it doesn't. Same here: sql = "update options%s set PriceDiff='%%s' where Field='%%s' and ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:]) # cursor.execute(sql, (value, opName, id, store)) cursor.execute('update options%s set PriceDiff="%s" where Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:], value, opName, id, store)) Please help. TIA, beno TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From decklar at googlemail.com Thu May 27 14:41:35 2010 From: decklar at googlemail.com (ledpepper) Date: Thu, 27 May 2010 11:41:35 -0700 (PDT) Subject: First script. Need some help Message-ID: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> #Enter in firstname.lastname (bob.smith) #Count the amount of letters(x) and vowels(y) #Then work out if bob is > but not equal to 6 letters #If firstname is less than 6 print firstnamesurnamexy #If firstname is equal to or greater than 6 print firstnamexy #Copy result to clipboard http://codepad.org/Emzpix3H I think you can see what i'm trying to do here. I will definitely elaborate if anyone needs me to. Thanks From python at mrabarnett.plus.com Thu May 27 14:54:43 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 May 2010 19:54:43 +0100 Subject: Some More MySQL In-Reply-To: References: Message-ID: <4BFEBFF3.6040909@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > But what about this? > > sql = "select pic%d from %s where ID='%%s';" % (pic, store) > cursor.execute(sql % id) > > If I try and rewrite the last line like this: > > cursor.execute(sql, id) > > it doesn't work. What do? > > How about this one: > > cursor.execute("insert into categories (Store, Category, Parent) > values('%s', '%s', Null)", (store, cat)) > > For some reason it puts single quotes around my variables! This doesn't > happen if I change that comma for a percent sign! What do? > > How about this one: > > sql = 'select * from options%s where ID=%%s', (opTable[0].upper() > + opTable[1:]) > # cursor.execute(sql, id) > cursor.execute('select * from options%s where ID=%s' % > (opTable[0].upper() + opTable[1:], id)) > > The last one works, but if I comment it out and uncomment the middle > line, it doesn't. Same here: > > sql = "update options%s set PriceDiff='%%s' where Field='%%s' > and ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:]) > # cursor.execute(sql, (value, opName, id, store)) > cursor.execute('update options%s set PriceDiff="%s" where > Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + > opTable[1:], value, opName, id, store)) > As has already been explained, when working with SQL in Python there are 2 forms of placeholder: 1. Python's %s placeholder, replaced by Python's % operator. 2. SQL's %s placeholder, replaced by the .execute method. SQL might not let you use its %s placeholder for table or column names, but they are normally hidden from the user and fixed by the application. For user-supplied values there's the risk of SQL-injection attacks. There are 2 ways of approaching that: 1. The hard way: check the values and add any necessary quoting or escaping before using Python's % operator, then pass the fully-formed SQL statement to result to .execute. 2. The easy way: pass the SQL statement to .execute with a %s for each value and let the method substitute the values itself (it'll add whatever quoting or escaping is necessary). From bieffe62 at gmail.com Thu May 27 14:56:29 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Thu, 27 May 2010 11:56:29 -0700 (PDT) Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Message-ID: On 27 Mag, 14:37, eb303 wrote: > Hello all, > > I've been using Python properties quite a lot lately and I've found a > few things that are a bit annoying about them in some cases. I > wondered if I missed something or if anybody else has this kind of > problems too, and if there are better solutions than the ones I'm > using ATM. > > The first annoyance is when I want to specialize a property in a > subclass. This happens quite often actually, and it is even sometimes > the reason why a plain attribute is turned into a property: a subclass > needs to do more things than the superclass when the property is > updated for example. So, of course, my first try was: > > class A(object): > ? def __init__(self): > ? ? self._p = None > ? def _get_p(self): > ? ? return self._p > ? def _set_p(self, p): > ? ? self._p = p > ? p = property(_get_p, _set_p) > class B(A): > ? def _set_p(self, p): > ? ? ## Additional things here? > ? ? super(B, self)._set_p(p) > > And of course, it doesn't work: the property has been bound to > A._set_p in A, so any new definition of _set_p in any subclass does > not replace the set method for the property. So I always have to add a > line: > p = property(A._get_p, _set_p) > in the subclass too. This is a bit awkward to me, since I have to > specify the superclass's name (super(?) can't be used, since it should > take B as an argument, and B isn't defined yet?). Do I miss something? > Is this the way to do it, or is there a better one? > Don't know if is better, but you could add a level of indirection to solve it class A(object): def __init__(self): self._p = None def _get_p(self): return self._p def _set_p(self, p): self._p = p def _virtual_get_p (self): _get_p(self) def _virtual_set_p (self,v): _set_p(self, v) p = property(_virtual_get_p, _virtual_set_p) At this point, the subclasses of A can reimplement _get_p and _set_p as they like (I think) Ciao ----- FB From victorsubervi at gmail.com Thu May 27 15:36:46 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 15:36:46 -0400 Subject: Some More MySQL In-Reply-To: <4BFEBFF3.6040909@mrabarnett.plus.com> References: <4BFEBFF3.6040909@mrabarnett.plus.com> Message-ID: On Thu, May 27, 2010 at 2:54 PM, MRAB wrote: > Victor Subervi wrote: > >> Hi; >> But what about this? >> >> sql = "select pic%d from %s where ID='%%s';" % (pic, store) >> cursor.execute(sql % id) >> >> If I try and rewrite the last line like this: >> >> cursor.execute(sql, id) >> >> it doesn't work. What do? >> >> How about this one: >> >> cursor.execute("insert into categories (Store, Category, Parent) >> values('%s', '%s', Null)", (store, cat)) >> >> For some reason it puts single quotes around my variables! This doesn't >> happen if I change that comma for a percent sign! What do? >> >> How about this one: >> >> sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + >> opTable[1:]) >> # cursor.execute(sql, id) >> cursor.execute('select * from options%s where ID=%s' % >> (opTable[0].upper() + opTable[1:], id)) >> >> The last one works, but if I comment it out and uncomment the middle line, >> it doesn't. Same here: >> >> sql = "update options%s set PriceDiff='%%s' where Field='%%s' and >> ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:]) >> # cursor.execute(sql, (value, opName, id, store)) >> cursor.execute('update options%s set PriceDiff="%s" where >> Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:], >> value, opName, id, store)) >> >> As has already been explained, when working with SQL in Python there are > 2 forms of placeholder: > > 1. Python's %s placeholder, replaced by Python's % operator. > > 2. SQL's %s placeholder, replaced by the .execute method. > > SQL might not let you use its %s placeholder for table or column names, > but they are normally hidden from the user and fixed by the application. > > For user-supplied values there's the risk of SQL-injection attacks. > There are 2 ways of approaching that: > > 1. The hard way: check the values and add any necessary quoting or > escaping before using Python's % operator, then pass the fully-formed > SQL statement to result to .execute. > > 2. The easy way: pass the SQL statement to .execute with a %s for each > value and let the method substitute the values itself (it'll add > whatever quoting or escaping is necessary). > > > Ok, so you're telling me I'm trying to do it the hard way. That's because I still don't have my head wrapped around the easy way. I was able to follow what Kushal Kumaran supplied; however I must still be lost on how that applies to the above examples. Could you illustrate with the first and let me try and figure out the rest? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu May 27 15:41:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 May 2010 20:41:18 +0100 Subject: First script. Need some help In-Reply-To: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> References: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> Message-ID: <4BFECADE.4040906@mrabarnett.plus.com> ledpepper wrote: > #Enter in firstname.lastname (bob.smith) > #Count the amount of letters(x) and vowels(y) > #Then work out if bob is > but not equal to 6 letters > #If firstname is less than 6 print firstnamesurnamexy > #If firstname is equal to or greater than 6 print firstnamexy > #Copy result to clipboard > > http://codepad.org/Emzpix3H > > I think you can see what i'm trying to do here. I will definitely > elaborate if anyone needs me to. > You need to download and install the Windows-specific extensions: http://sourceforge.net/projects/pywin32/ I'm assuming you're using Python 2.6 on Windows. From breamoreboy at yahoo.co.uk Thu May 27 15:42:51 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 May 2010 20:42:51 +0100 Subject: First script. Need some help In-Reply-To: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> References: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> Message-ID: On 27/05/2010 19:41, ledpepper wrote: > #Enter in firstname.lastname (bob.smith) > #Count the amount of letters(x) and vowels(y) > #Then work out if bob is> but not equal to 6 letters > #If firstname is less than 6 print firstnamesurnamexy > #If firstname is equal to or greater than 6 print firstnamexy > #Copy result to clipboard > > http://codepad.org/Emzpix3H > > I think you can see what i'm trying to do here. I will definitely > elaborate if anyone needs me to. > > Thanks Have you installed the Win32 extensions? From http://www.devx.com/opensource/Article/37233/0/page/3 "Author's Note: the win32clipboard module is not part of the standard Python distribution on Windows. You can get it (along with lots of other comprehensive Python bindings to Win32 APIs) as part of the Win32 extensions project on SourceForge. Alternatively, the module is also bundled with the ActivePython distribution for Windows." HTH. Mark Lawrence From ethan at stoneleaf.us Thu May 27 15:45:58 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 May 2010 12:45:58 -0700 Subject: dbf files and indexes Message-ID: <4BFECBF6.10006@stoneleaf.us> Let's say I have two tables: CatLovers DogLovers ------------------- ------------------- | name | age | | name | age | |-----------------| |-----------------| | Allen | 42 | | Alexis | 7 | | Jerod | 29 | | Michael | 21 | | Samuel | 17 | | Samuel | 17 | | Nickalaus | 55 | | Lawrence | 63 | | Frederick | 34 | | Frederick | 34 | ------------------- ------------------- NumberOfPets --------------------------- | name | cats | dogs | --------------------------- | Allen | 2 | 0 | | Alexis | 0 | 3 | | Michael | 0 | 1 | | Samuel | 1 | 2 | | Jerod | 3 | 0 | | Nickalaus | 5 | 0 | | Lawrence | 0 | 1 | | Frederick | 3 | 2 | --------------------------- (I know, I know -- coming up with examples has never been my strong point. ;) catlovers = dbf.Table('CatLovers') doglovers = dbf.Table('DogLovers') petcount = dbf.Table('NumberOfPets') For the sake of this highly contrived example, let's say I'm printing a report that I would like in alphabetical order of those who love both cats and dogs... def names(record): return record.name c_idx = catlovers.create_index(key=names) d_idx = doglovers.create_index(key=names) p_idx = petcount.create_index(key=names) # method 1 for record in c_idx: if record in d_idx: print record.name, record.age, \ p_idx[record].cats, p_idx[record].dogs *or* # method 2 for record in c_idx: if d_idx.key(record) in d_idx: # or if names(record) in d_idx: print record.name, record.age \ p_idx[record].cats, p_idx[record].dogs Which is better (referring to the _in_ statement)? Part of the issue revolves around the question of is _any_ record in the CatLovers table really in the DogLovers index? Obviously no -- so if you are asking the question in code you are really asking if a record from CatLovers has a matching key value in DogLovers, which means either the __contains__ code can apply the key function to the record (implicit, as in method 1 above) or the calling code can do it (explicit, as in method 2 above). I'm leaning towards method 1, even though the key function is then called behind the scenes, because I think it makes the calling code cleaner. Opinions? ~Ethan~ From wcardoen at gmail.com Thu May 27 15:46:35 2010 From: wcardoen at gmail.com (Wim R. Cardoen) Date: Thu, 27 May 2010 13:46:35 -0600 Subject: On the installation of external Python modules Message-ID: Hello, In the past I installed different versions of python (using gcc) e.g. 2.5.4, 2.6.4 at the following places: /wim/pkg/python/2.5.4 /wim/pkg/python/2.6.4 I installed the numpy, scipy, matplotlib, dadi modules using the command: /wim/pkg/python/2.5.4/bin/python setup.py install --prefix=/wim/pkg/python/2.5.4 As a result the working modules got installed under: /wim/pkg/python/.5.4/lib/python2.5/site-packages/dadi /wim/pkg/python/.5.4/lib/python2.5/site-packages/numpy /wim/pkg/python/.5.4/lib/python2.5/site-packages/scipy /wim/pkg/python/.5.4/lib/python2.5/site-packages/matplotlib Question 1: Is it correct when I state that the above scipy, numpy, modules can only be used by the python2.5.4 executable or can I also use in python2.6.4 if I modify the PYTHONHOME and PYTHONPATH variables? Does one have to recompile all its external libraries for use with an updated python version? (assuming that the glibc is identical) I also tried to install the external libraries (e.g. numpy) in different directories than the main python directories by specifying e.g. --prefix=/wim/pkg/pylib/ (in the case of using python2.6.5)* *I noticed that the suffix was still of the form "lib/pythonx.y/site-packages/numpy" Therefore, I wonder: a. How can one (elegantly) force numpy to be installed under (using python 2.6.2 and python2.6.5): /wim/pkg/pylib/lib/python2.6.4/. /wim/pkg/pylib/lib/python2.6.5 b. How can one (elegantly) install different versions of the same package using the same python binary (2.6.4) as e.g: /wim/pkg/pylib/lib/python2.6/site-packages/numpy0.70 /wim/pkg/pylib/lib/python2.6/site-packages/numpy0.71 or is this the wrong approach? Thanks, Wim -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Thu May 27 16:04:45 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 27 May 2010 16:04:45 -0400 Subject: dbf files and indexes In-Reply-To: <4BFECBF6.10006@stoneleaf.us> References: <4BFECBF6.10006@stoneleaf.us> Message-ID: <20100527160445.30081fd3.darcy@druid.net> On Thu, 27 May 2010 12:45:58 -0700 Ethan Furman wrote: > Let's say I have two tables: > > CatLovers DogLovers > ------------------- ------------------- > | name | age | | name | age | > |-----------------| |-----------------| [...] > > NumberOfPets > --------------------------- > | name | cats | dogs | > --------------------------- [...] First problem is learning to count. :-) Second (first real) problem is that you database is not normalized. If all of the cat lovers and dog lovers are in NumberOfPets then move the age into that. Probably should rename it as well. Finally, are these SQL databases? The best way of getting information is with SQL. SELECT * FROM NumberOfPets WHERE name IN (SELECT name FROM CatLovers) OR name IN (SELECT name FROM DogLovers) ORDER BY name; > catlovers = dbf.Table('CatLovers') > doglovers = dbf.Table('DogLovers') > petcount = dbf.Table('NumberOfPets') I guess you should tell us what dbf is. It doesn't seem to be a standard module and it doesn't look like DB-API. It's hard to answer your question without knowing what these functions do. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From ethan at stoneleaf.us Thu May 27 16:06:18 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 May 2010 13:06:18 -0700 Subject: dbf files and indexes In-Reply-To: <4BFECBF6.10006@stoneleaf.us> References: <4BFECBF6.10006@stoneleaf.us> Message-ID: <4BFED0BA.3000106@stoneleaf.us> Ethan Furman wrote: > Let's say I have two tables: Okay, let's say I have three tables instead. ;p From davea at ieee.org Thu May 27 16:11:24 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 27 May 2010 16:11:24 -0400 Subject: First script. Need some help In-Reply-To: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> References: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> Message-ID: <4BFED1EC.2070609@ieee.org> ledpepper wrote: > #Enter in firstname.lastname (bob.smith) > #Count the amount of letters(x) and vowels(y) > #Then work out if bob is > but not equal to 6 letters > #If firstname is less than 6 print firstnamesurnamexy > #If firstname is equal to or greater than 6 print firstnamexy > #Copy result to clipboard > > http://codepad.org/Emzpix3H > > I think you can see what i'm trying to do here. I will definitely > elaborate if anyone needs me to. > > Thanks > > Why bother using codepad for this? The problem occurs parsing the 3rd line, so you only needed that and the traceback. Have you installed the Win32 extensions? If you think you have, can you find the file ? C:\ProgFiles\Python26\Lib\site-packages\win32\win32clipboard.pyd Naturally, your install directory may be different. But it should be in the site-packages directory, which is where add-ons are installed. DaveA From lists at cheimes.de Thu May 27 16:27:44 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 27 May 2010 22:27:44 +0200 Subject: dbf files and indexes In-Reply-To: <20100527160445.30081fd3.darcy@druid.net> References: <4BFECBF6.10006@stoneleaf.us> <20100527160445.30081fd3.darcy@druid.net> Message-ID: > Finally, are these SQL databases? The best way of getting information > is with SQL. > > SELECT * FROM NumberOfPets > WHERE name IN (SELECT name FROM CatLovers) OR > name IN (SELECT name FROM DogLovers) > ORDER BY name; A good way is to use SQL with JOINs instead of horrible nested selects. Although SQL is declarative, you shouldn't make the work of the query optimizer so hard. Christian From cedric.krier at b2ck.com Thu May 27 16:31:53 2010 From: cedric.krier at b2ck.com (ced) Date: Thu, 27 May 2010 13:31:53 -0700 (PDT) Subject: Tryton 1.6 series is out Message-ID: <68f9d2bc-9f31-4c88-9234-013dca7c4392@m21g2000vbr.googlegroups.com> Tryton is a three-tiers high-level general purpose application platform under the license GPL-3 written in Python and using PostgreSQL as main database engine. It is the core base of a complete business solution providing modularity, scalability and security. This new release comes with the support of MySQL and various improvements and polishing of the framework. As always database migration is ensured from any previous version. This release also marks the end of support for the 1.0 series. The most noteworthy new features are: - The add of MySQL support as DBMS - Some new modules: - Calendar Scheduling - Dashboard - Project Plan - The Russian translation - The security enforcement with fingerprint and CA checks for SSL - The introduction of PYSON[1] for dynamic domain - The add of JSON-RPC protocol - The lazy load of fields in Export/Import windows - The usage of python-dateutil instead of egenix-mx-base - A versioned configuration directory for the client - A bundle of Neso (standalone version of Tryton) for MacOSX - The digits validation on numeric fields[2] - The usage of singleton model[3] for various sequences configuration - Some speed improvements of the report engine A more complete list of the new features on: http://www.tryton.org/news.html#d2010-05-17 :Homepage: http://www.tryton.org/ :Downloads: http://www.tryton.org/downloads.html :Screenshots: http://www.tryton.org/screenshots.html :Demo: http://www.tryton.org/demo.html [1] http://doc.tryton.org/1.6/trytond/doc/topics/pyson.html [2] http://doc.tryton.org/1.6/trytond/doc/ref/models/fields.html#numeric [3] http://doc.tryton.org/1.6/trytond/doc/ref/models/models.html#trytond.model.ModelSingleton] From victorsubervi at gmail.com Thu May 27 16:32:24 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 16:32:24 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEA8A4.2040202@thechases.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> <4BFEA8A4.2040202@thechases.com> Message-ID: On Thu, May 27, 2010 at 1:15 PM, Tim Chase wrote: > On 05/27/2010 11:56 AM, MRAB wrote: > >> Kushal Kumaran wrote: >> >>> ', '.join('%s' * len(values))) >>> >> >> That should be: >> >> ', '.join(['%s'] * len(values))) >> > > Or as I've done in the past: > > ', '.join('%s' for _ in values) > Huh? Can you describe that underscore to me? Fascinating! beno > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Thu May 27 16:33:59 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 May 2010 13:33:59 -0700 Subject: dbf files and indexes In-Reply-To: <20100527160445.30081fd3.darcy@druid.net> References: <4BFECBF6.10006@stoneleaf.us> <20100527160445.30081fd3.darcy@druid.net> Message-ID: <4BFED737.3050906@stoneleaf.us> D'Arcy J.M. Cain wrote: > On Thu, 27 May 2010 12:45:58 -0700 > Ethan Furman wrote: >> Let's say I have two tables: >> >> CatLovers DogLovers >> ------------------- ------------------- >> | name | age | | name | age | >> |-----------------| |-----------------| > [...] >> NumberOfPets >> --------------------------- >> | name | cats | dogs | >> --------------------------- > [...] > > First problem is learning to count. :-) Heh -- like I said, I'm terrible at making examples. Originally it was two tables, then I threw in a third so I could show using an index as a dictionary. > Second (first real) problem is that you database is not normalized. > If all of the cat lovers and dog lovers are in NumberOfPets then move > the age into that. Probably should rename it as well. The actual tables that I would be using are different versions of mailing tables, with one table not having as many records as the other, and wanting to do something with the records that are in common between the two. > Finally, are these SQL databases? The best way of getting information > is with SQL. The format of these tables is either dBase III or Visual FoxPro 6, and dbf is a module I have coded (still working on SQL support for it... getting closer!). A slightly out-of-date version of it is available on PyPI. My question centers around the __contains__ method of the Index object that I am writing, and whether it should call the key function of the index when passed a record, or if I should make the calling code do that. Hope this helps. ~Ethan~ From subhakolkata1234 at gmail.com Thu May 27 16:50:29 2010 From: subhakolkata1234 at gmail.com (joy99) Date: Thu, 27 May 2010 13:50:29 -0700 (PDT) Subject: Question on Python Function References: Message-ID: <14b47fde-d257-41ba-9480-6e8307d3d8a5@z15g2000prh.googlegroups.com> On May 25, 12:18?pm, Peter Otten <__pete... at web.de> wrote: > Kushal Kumaran wrote: > > On Tue, May 25, 2010 at 3:38 AM,joy99 wrote: > >> > > >> Dear Vlastimir, > > >> As pointed out by Alister, I can print the values of function1 and > >> function2 with the help of another function3, but my target is to call > >> the "add" value of function1 and "mult" value of function2 in a third > >> function or the values and parameters of the third function in fourth > >> function. While calling, I am looking not only to print, but to use > >> them or manipulate them. > > >> I hope I am bit clear now. > > > If you need to use the values in another function, you need a way to > > let that function get its hands on the values. ?Your function1 and > > function2 should return the values they compute instead of printing > > them out. > > For example: > > ?>>> def add(x, y): > ... ? ? return x + y > ...>>> def mul(x, y): > > ... ? ? return x * y > ...>>> def sum_of_squares(x, y): > > ... ? ? return add(mul(x, x), mul(y, y)) > ...>>> sum_of_squares(3, 4) > > 25 > > OP: If that addresses your question I suggest that you work through some > introductory text about python. The python wiki has a few suggestions, see > > http://wiki.python.org/moin/BeginnersGuide > > Peter Hi Peter and Other Kind Contributors of the Group, I got lot of insights from the discussion in the group. Though I did not get the exact answer but from Peter's link I could work them out. Thank you, Peter, for kindly referring me the link. I like to thank others of the group also for kindly spending their valuable time. I wanted to define one function and call the value of that function to be used by another function. If I misquoted the problem, I am sorry. Wishing You all a Great Day Ahead, Best Regards, Subhabrata. From nganon at gmail.com Thu May 27 16:58:43 2010 From: nganon at gmail.com (nganon tj) Date: Thu, 27 May 2010 23:58:43 +0300 Subject: PyQt4 QThread - passing arguments to thread methods Message-ID: Hi, I am trying to figure out how to implement a QThread class that will handle GUI event while keeping the GUI responsive. I want to call thread's methods by their names and start() the thread from inside that method. My problem is with passing methods their arguments since start() wont take any argument. So I thought I could keep a global variable self.invoker which holds the name of currently called method and start the thread accordingly as follows: class Counter(QThread): def __init__(self, parent=None): super(Counter, self).__init__(parent) self.reset() def __del__(self): self.exiting = True self.wait() try: self.reset() # is not instantiated except TypeError: return def stop(self): self.__del__() def reset(self): self.exiting = False def countup(self, till): if not self.isRunning(): self.invoker = [self.countup, till] self.start() else: n = 0 while not self.exiting and n < till: n += 1 self.emit(SIGNAL("ticktock(int)", n)) def run(self): self.invoker[0](self.invoker[1], self.invoker[2]) But I cant always know the number of arguments the invoker has, can I? So can you please suggest me a better way of doing this please? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rbrt.somerville at gmail.com Thu May 27 17:31:59 2010 From: rbrt.somerville at gmail.com (robert somerville) Date: Thu, 27 May 2010 14:31:59 -0700 Subject: re ElemenTree producing and reading examples needed : Message-ID: does anybody have some working code that they can point me to so i could see ElemenTtree in action (especially writing XML files) ??? Thanks Robert Somerville -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Thu May 27 17:47:39 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 27 May 2010 16:47:39 -0500 Subject: Yet Another MySQL Problem In-Reply-To: References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> <4BFEA8A4.2040202@thechases.com> Message-ID: <4BFEE87B.1030302@tim.thechases.com> On 05/27/2010 03:32 PM, Victor Subervi wrote: > On Thu, May 27, 2010 at 1:15 PM, Tim Chase wrote: >>> That should be: >>> >>> ', '.join(['%s'] * len(values))) >> >> Or as I've done in the past: >> >> ', '.join('%s' for _ in values) > > Huh? Can you describe that underscore to me? Fascinating! The underscore is a valid variable-name, idiomatically used for "I don't care about this", often seen in places like tuple assignment: a,_,_,d = some_4_element_tuple So in my above case, it could also have been written as ', '.join('%s' for value in values) ', '.join('%s' for dont_care_about_the_value in values) but the "_" idiom means "I'm iterating over 'values' but I'm not actually using the values I get from it" -tkc From python at mrabarnett.plus.com Thu May 27 18:22:24 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 May 2010 23:22:24 +0100 Subject: Some More MySQL In-Reply-To: References: <4BFEBFF3.6040909@mrabarnett.plus.com> Message-ID: <4BFEF0A0.2040800@mrabarnett.plus.com> Victor Subervi wrote: > On Thu, May 27, 2010 at 2:54 PM, MRAB > wrote: > > Victor Subervi wrote: > > Hi; > But what about this? > > sql = "select pic%d from %s where ID='%%s';" % (pic, store) > cursor.execute(sql % id) > > If I try and rewrite the last line like this: > > cursor.execute(sql, id) > > it doesn't work. What do? > > How about this one: > > cursor.execute("insert into categories (Store, Category, > Parent) values('%s', '%s', Null)", (store, cat)) > > For some reason it puts single quotes around my variables! This > doesn't happen if I change that comma for a percent sign! What do? > > How about this one: > > sql = 'select * from options%s where ID=%%s', > (opTable[0].upper() + opTable[1:]) > # cursor.execute(sql, id) > cursor.execute('select * from options%s where ID=%s' % > (opTable[0].upper() + opTable[1:], id)) > > The last one works, but if I comment it out and uncomment the > middle line, it doesn't. Same here: > > sql = "update options%s set PriceDiff='%%s' where > Field='%%s' and ID=%%s and Store='%%s'" % (opTable[0].upper() + > opTable[1:]) > # cursor.execute(sql, (value, opName, id, store)) > cursor.execute('update options%s set PriceDiff="%s" where > Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + > opTable[1:], value, opName, id, store)) > > As has already been explained, when working with SQL in Python there are > 2 forms of placeholder: > > 1. Python's %s placeholder, replaced by Python's % operator. > > 2. SQL's %s placeholder, replaced by the .execute method. > > SQL might not let you use its %s placeholder for table or column names, > but they are normally hidden from the user and fixed by the application. > > For user-supplied values there's the risk of SQL-injection attacks. > There are 2 ways of approaching that: > > 1. The hard way: check the values and add any necessary quoting or > escaping before using Python's % operator, then pass the fully-formed > SQL statement to result to .execute. > > 2. The easy way: pass the SQL statement to .execute with a %s for each > value and let the method substitute the values itself (it'll add > whatever quoting or escaping is necessary). > > > Ok, so you're telling me I'm trying to do it the hard way. That's > because I still don't have my head wrapped around the easy way. I was > able to follow what Kushal Kumaran supplied; however I must still be > lost on how that applies to the above examples. Could you illustrate > with the first and let me try and figure out the rest? > First build the SQL statement with placeholder(s) for the values: sql = "select pic%d from %s where ID=%%s;" % (pic, store) Then execute the SQL statement, passing the value(s) so that .execute performs the substitution itself: cursor.execute(sql, id) Placeholders which are handled by .execute shouldn't be wrapped in quotes, even is the value is a string, because .execute will handle that (and any other details) itself. From rbrt.somerville at gmail.com Thu May 27 19:52:17 2010 From: rbrt.somerville at gmail.com (robert somerville) Date: Thu, 27 May 2010 16:52:17 -0700 Subject: ElementTree write creates large one line XML file .... Message-ID: Hi I am using Ubuntu 9.10 and Python 2.6.4 .. when I create an ElementTree object and the write it out using: xml.etree.ElementTree.write() , I get one single long single line files, instead of something that looks reasonable , what gives ??? (and is it important ??) eg: I get : OneTwo instead of : One Two i found this example at: ( Listing 4 ) http://www.learningpython.com/2008/05/07/elegant-xml-parsing-using-the-elementtree-module/#Listing1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Thu May 27 20:13:02 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 27 May 2010 20:13:02 -0400 Subject: ElementTree write creates large one line XML file .... In-Reply-To: References: Message-ID: On 5/27/10 7:52 PM, robert somerville wrote: > Hi I am using Ubuntu 9.10 and Python 2.6.4 .. > > when I create an ElementTree object and the write it out using: > > xml.etree.ElementTree.write() , I get one single long single line > files, instead of something that looks reasonable , what gives ??? (and > is it important ??) ElementTree writes exactly what you tell it to. In XML, whitespace is significant. If you want newlines and/or indentation to make it pretty-looking, then you need to add those to your elements. Fredrik provides an example function for doing this: http://effbot.org/zone/element-lib.htm#prettyprint -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nagle at animats.com Thu May 27 20:37:44 2010 From: nagle at animats.com (John Nagle) Date: Thu, 27 May 2010 17:37:44 -0700 Subject: MySQLDB - server has gone on blob insertion... In-Reply-To: References: Message-ID: <4bff0aae$0$1592$742ec2ed@news.sonic.net> Dennis Lee Bieber wrote: > On Wed, 26 May 2010 11:30:41 +0200, Durumdara > declaimed the following in gmane.comp.python.general: > >> cursor.execute('delete from blobs;') >> > Since that statement will delete EVERY record from the table > "blobs", I believe it is common practice to replace it with > > drop table blobs > create table blobs (whatever definition it had originally) No, it's not "common practice". Actually, the proper way to clear a table is "TRUNCATE TABLE tablename;" Note that deleting a table referenced by other tables using FOREIGN KEY can be rejected by the database. John Nagle > >> When I tried to start this, I got error: >> >> _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') >> >> I read that server have some parameter, that limit the Query length. >> >> Then I decreased the blob size to 1M, and then it is working. >> > What is the table definition? In MySQL 4 (and likely not changed in > v5 -- I've got the old brown tree book handy, hence the mention of v4) > field type BLOB is limited to a length of 2^16 (64kB), MEDIUMBLOB is > 2^24, and LONGBLOB is 2^32 (if the system is using unsigned integers > internally, that should support 4GB... But do you have enough memory to > pass such an argument? ). From ipatrol6010 at yahoo.com Thu May 27 21:03:52 2010 From: ipatrol6010 at yahoo.com (ipatrol6010 at yahoo.com) Date: Thu, 27 May 2010 18:03:52 -0700 (PDT) Subject: Tkinter error Message-ID: <247190.10596.qm@web45414.mail.sp1.yahoo.com> I run a program (important parts at http://paste.pocoo.org/show/219148/) and all I get is this error: warning: callback failed in WindowList : invalid command name ".45328424.windows" Why? P.S.: Please CC all replies to me, I don't watch the list -------------- next part -------------- An HTML attachment was scrubbed... URL: From jyoung79 at kc.rr.com Thu May 27 22:00:59 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Fri, 28 May 2010 2:00:59 +0000 Subject: pythonMagick question Message-ID: <20100528020059.HINJ0.617899.root@cdptpa-web25-z02> Hello, I'm wanting to try out pythonMagick, but am pretty lost with this whole thing. What I'm wanting to do is view EPS and PDF files with Python and be able to zoom into the images to see smaller detail. I downloaded PythonMagick-0.9.1.tar and have been looking through that folder. The README file says: ------------- Requists for installation is: boost boost-python python 2.5 Magick++ (>= 6.2) and for building: pkg-config libtool make and for generation build scripts is defined in autogen.pl Building: ./configure make make install ------------- What's this 'boost' stuff and Magick++? Do I need to install more things to make this work? I was going to run '.configure', then 'make' and then 'make install' from the command-line, but want to make sure I know what I'm doing before installing something (especially if it won't work). Can anyone give me more info about pythonMagick or send me a link to a site(s) that has more info? Thanks! Jay From sbassi at clubdelarazon.org Thu May 27 22:19:37 2010 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Thu, 27 May 2010 23:19:37 -0300 Subject: ElementTree write creates large one line XML file .... In-Reply-To: References: Message-ID: On Thu, May 27, 2010 at 9:13 PM, Robert Kern wrote: > ElementTree writes exactly what you tell it to. In XML, whitespace is > significant. If you want newlines and/or indentation to make it > pretty-looking, then you need to add those to your elements. This is not always true. Let me quote an XML tutorial (by Oracle): "What is XML Whitespace? XML considers four characters to be whitespace: the carriage return (\r or ch(13)), the linefeed (\n or ch(10)), the tab(\t), and the spacebar (' '). In XML documents, there are two types of whitespace: Significant whitespace is part of the document content and should be preserved. Insignificant whitespace is used when editing XML documents for readability. These whitespaces are typically not intended for inclusion in the delivery of the document. Usually without DTD or XML schema definition, all whitespaces are significant whitespaces and should be preserved. However, with DTD or XML schema definitions, only the whitespaces in the content are significant as follows: ------------------ John Smith Product Manager Example.com -------------------- " From clp2 at rebertia.com Thu May 27 22:24:21 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 May 2010 19:24:21 -0700 Subject: pythonMagick question In-Reply-To: <20100528020059.HINJ0.617899.root@cdptpa-web25-z02> References: <20100528020059.HINJ0.617899.root@cdptpa-web25-z02> Message-ID: On Thu, May 27, 2010 at 7:00 PM, wrote: > Hello, > > I'm wanting to try out pythonMagick, but am pretty lost with this whole thing. > What I'm wanting to do is view EPS and PDF files with Python and be able to > zoom into the images to see smaller detail. > > I downloaded PythonMagick-0.9.1.tar and have been looking through that > folder. ?The README file says: > > ------------- > Requists for installation is: > boost > boost-python > python 2.5 > Magick++ (>= 6.2) > > and for building: > pkg-config > libtool > make > > and for generation build scripts is defined in autogen.pl > > Building: > ./configure > make > make install > ------------- > > What's this 'boost' stuff and Magick++? ?Do I need to install > more things to make this work? Yes: http://www.imagemagick.org/Magick++/ http://www.boost.org/ For what `make` et. al do: http://www.tuxfiles.org/linuxhelp/softinstall.html Cheers, Chris -- http://blog.rebertia.com From sbassi at clubdelarazon.org Thu May 27 22:45:19 2010 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Thu, 27 May 2010 23:45:19 -0300 Subject: Free chapter about Python and databases (MySQL and SQLite) Message-ID: Hello, I want to announce that the publisher of "Python for Bioinformatis" (CRC Press) allowed me to publish a chapter from my book. I decided to publish the chapter about "Python and databases". I think it may be useful for somebody. The official announcement and download link is here: http://py4bio.com/2010/05/28/python_databases_mysql_sqlite/ For more information about the book: www.tinyurl.com/biopython Best, SB. -- Sebasti?n Bassi. Lic. en Biotecnologia. Curso de Python en un d?a: http://bit.ly/cursopython Non standard disclaimer: READ CAREFULLY. By reading this email, you agree, on behalf of your employer, to release me from all obligations and waivers arising from any and all NON-NEGOTIATED agreements, licenses, terms-of-service, shrinkwrap, clickwrap, browsewrap, confidentiality, non-disclosure, non-compete and acceptable use policies ("BOGUS AGREEMENTS") that I have entered into with your employer, its partners, licensors, agents and assigns, in perpetuity, without prejudice to my ongoing rights and privileges. You further represent that you have the authority to release me from any BOGUS AGREEMENTS on behalf of your employer. From john at castleamber.com Thu May 27 23:37:52 2010 From: john at castleamber.com (John Bokma) Date: Thu, 27 May 2010 22:37:52 -0500 Subject: Free chapter about Python and databases (MySQL and SQLite) References: Message-ID: <87vda8ofvz.fsf@castleamber.com> Sebastian Bassi writes: > Hello, I want to announce that the publisher of "Python for > Bioinformatis" (CRC Press) allowed me to publish a chapter from my > book. > I decided to publish the chapter about "Python and databases". I think > it may be useful for somebody. > The official announcement and download link is here: > http://py4bio.com/2010/05/28/python_databases_mysql_sqlite/ > For more information about the book: www.tinyurl.com/biopython I feel more than uncomfortable with example code that uses: user="root" (e.g. p291). I never get why people write a short (IMO) /bad/ intro to databases while there are books out there that do a way better job. To me such chapters are just a way to get more pages :-(. (=make the book more expensive = less money to buy a /good/ book on databases) I would love to see more technical books that start at page 1 with the topic, not with an introduction to the language (170+ pages) and some other stuff that IMO shouldn't be there (MySQL introduction, XML, etc.). What I would expect, based on the title is: p 175-222 p 315-456 p 539-552 This would probably make the book a bit cheaper, so one can buy a good book on MySQL, a good book on XML, and a good book on Python. (Or maybe one already has those, like me). IMO, YMMV -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From sbassi at clubdelarazon.org Fri May 28 00:17:35 2010 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Fri, 28 May 2010 01:17:35 -0300 Subject: Free chapter about Python and databases (MySQL and SQLite) In-Reply-To: <87vda8ofvz.fsf@castleamber.com> References: <87vda8ofvz.fsf@castleamber.com> Message-ID: On Fri, May 28, 2010 at 12:37 AM, John Bokma wrote: > I feel more than uncomfortable with example code that uses: user="root" What's wrong with this? It is just an example of connection string. The reader will use his/her user/pass/dbname according to their own settings. > (e.g. p291). I never get why people write a short (IMO) /bad/ intro to > databases while there are books out there that do a way better The intended audience of this book are biologist who may be not familiarized with relational databases. Most of my colleagues (at least from the bio camp) don't even know that behind most dynamic web pages there are databases and I think that most of them will find the intro section useful. You can always skip what you know and go to the point you want. > job. To me such chapters are just a way to get more pages :-(. (=make > the book more expensive = less money to buy a /good/ book on databases) I am not sure that price in this kind of book are tied to the number of pages. There must be some relation, but this is not the main factor affecting price. > I would love to see more technical books that start at page 1 with the > topic, not with an introduction to the language (170+ pages) and some ... I see where you go, it seems you are not the target audience for this book. Anyway I appreciate your feedback. Best, SB From decklar at googlemail.com Fri May 28 02:17:15 2010 From: decklar at googlemail.com (ledpepper) Date: Thu, 27 May 2010 23:17:15 -0700 (PDT) Subject: First script. Need some help References: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> Message-ID: <7e67baf2-6c00-40dd-80dc-4f12befe70fc@o12g2000vba.googlegroups.com> Thanks Everyone. I followed your instructions and my script is successfully copying the result to the clipboard. Now for the fun. To work out the rest of the script :) I use the IDLE IDE and not codepad.org. I just thought that was the standard for pasting scripts here in this group. Thanks all. From kse.listed.co1 at gmail.com Fri May 28 04:59:01 2010 From: kse.listed.co1 at gmail.com (Naeem) Date: Fri, 28 May 2010 01:59:01 -0700 (PDT) Subject: "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com Message-ID: <81b20491-6ad6-45aa-b4c3-84fc4cc4a8fd@u7g2000vbq.googlegroups.com> "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com From eric.brunel.pragmadev at gmail.com Fri May 28 05:31:49 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Fri, 28 May 2010 02:31:49 -0700 (PDT) Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Message-ID: <4d9e0aff-c013-43ea-81e2-cd674149a05a@z33g2000vbb.googlegroups.com> On May 27, 3:24?pm, Christian Heimes wrote: > > ?Do I miss something? > > Is this the way to do it, or is there a better one? > > A better way was introduced in Python 2.6. Seehttp://docs.python.org/library/functions.html?highlight=property#prop... > I have a Python only version around if you are still using Python 2.5. > > Christian Mmmm, I might still miss something. OK, I can replace my initial property using @property and @p.setter, but it doesn't seem to work in subclasses: class A(object): @property def p(self): return self._p @p.setter def _set_p(self, p): self._p = p class B(A): @p.setter def _set_p(self, p): ? results in: Traceback (most recent call last): File "toto.py", line 8, in class B(A): File "toto.py", line 9, in B @p.setter NameError: name 'p' is not defined From eric.brunel.pragmadev at gmail.com Fri May 28 05:36:39 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Fri, 28 May 2010 02:36:39 -0700 (PDT) Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Message-ID: On May 27, 8:56?pm, Francesco Bochicchio wrote: > On 27 Mag, 14:37, eb303 wrote: > > > > > Hello all, > > > I've been using Python properties quite a lot lately and I've found a > > few things that are a bit annoying about them in some cases. I > > wondered if I missed something or if anybody else has this kind of > > problems too, and if there are better solutions than the ones I'm > > using ATM. > > > The first annoyance is when I want to specialize a property in a > > subclass. This happens quite often actually, and it is even sometimes > > the reason why a plain attribute is turned into a property: a subclass > > needs to do more things than the superclass when the property is > > updated for example. So, of course, my first try was: > > > class A(object): > > ? def __init__(self): > > ? ? self._p = None > > ? def _get_p(self): > > ? ? return self._p > > ? def _set_p(self, p): > > ? ? self._p = p > > ? p = property(_get_p, _set_p) > > class B(A): > > ? def _set_p(self, p): > > ? ? ## Additional things here? > > ? ? super(B, self)._set_p(p) > > > And of course, it doesn't work: the property has been bound to > > A._set_p in A, so any new definition of _set_p in any subclass does > > not replace the set method for the property. So I always have to add a > > line: > > p = property(A._get_p, _set_p) > > in the subclass too. This is a bit awkward to me, since I have to > > specify the superclass's name (super(?) can't be used, since it should > > take B as an argument, and B isn't defined yet?). Do I miss something? > > Is this the way to do it, or is there a better one? > > Don't know if is better, but you could add a level of indirection to > solve it > > ?class A(object): > ? ?def __init__(self): > ? ? ?self._p = None > ? ?def _get_p(self): > ? ? ?return self._p > ? ?def _set_p(self, p): > ? ? ?self._p = p > ? ?def _virtual_get_p (self): _get_p(self) > ? ?def _virtual_set_p (self,v): _set_p(self, v) > ? ?p = property(_virtual_get_p, _virtual_set_p) > > At this point, the subclasses of A can reimplement _get_p and _set_p > as they like (I think) > > Ciao > ----- > FB Well, I've thought about that too and it should work, but that makes 2 function calls instead of one for every property access? I'd really like to avoid that. By the way, I think your 'virtual' methods should be written as: def _virtual_get_p (self): return self._get_p() def _virtual_set_p (self,v): self._set_p(v) Thanks anyway. - Eric - From eric.brunel.pragmadev at gmail.com Fri May 28 05:46:36 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Fri, 28 May 2010 02:46:36 -0700 (PDT) Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> <8679gtFdj4U1@mid.individual.net> Message-ID: <77f68c71-e73f-4721-9ba8-a4524c41ee86@w3g2000vbd.googlegroups.com> On May 27, 3:14?pm, Neil Cerutti wrote: > On 2010-05-27, eb303 wrote: > > > I've been using Python properties quite a lot lately and I've > > found a few things that are a bit annoying about them in some > > cases. I wondered if I missed something or if anybody else has > > this kind of problems too, and if there are better solutions > > than the ones I'm using ATM. > > The first annoyance is when I want to specialize a property in a > > subclass. > > See: > > URI:http://infinitesque.net/articles/2005/enhancing%20Python%27s%20proper... > > -- > Neil Cerutti > *** You found a dead moose-rat. You sell the hide for $200. *** Thanks for the suggestion, but it looks a bit heavy? Performing the name lookup on the specialized object each time the property is accessed seems a bit overkill. I'd really just like a simple way to tell in the subclass: now, the setter methof for property p is this one, only that? Thanks again anyway. - Eric - From lists at cheimes.de Fri May 28 05:50:56 2010 From: lists at cheimes.de (Christian Heimes) Date: Fri, 28 May 2010 11:50:56 +0200 Subject: Minor annoyances with properties In-Reply-To: <4d9e0aff-c013-43ea-81e2-cd674149a05a@z33g2000vbb.googlegroups.com> References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> <4d9e0aff-c013-43ea-81e2-cd674149a05a@z33g2000vbb.googlegroups.com> Message-ID: Am 28.05.2010 11:31, schrieb eb303: > On May 27, 3:24 pm, Christian Heimes wrote: >>> Do I miss something? >>> Is this the way to do it, or is there a better one? >> >> A better way was introduced in Python 2.6. Seehttp://docs.python.org/library/functions.html?highlight=property#prop... >> I have a Python only version around if you are still using Python 2.5. >> >> Christian > > Mmmm, I might still miss something. OK, I can replace my initial > property using @property and @p.setter, but it doesn't seem to work in > subclasses: > > class A(object): > @property > def p(self): > return self._p > @p.setter > def _set_p(self, p): > self._p = p > class B(A): > @p.setter > def _set_p(self, p): > ? > > results in: > > Traceback (most recent call last): > File "toto.py", line 8, in > class B(A): > File "toto.py", line 9, in B > @p.setter > NameError: name 'p' is not defined It doesn't work because "p" is not in the scope of B's body while B is created. You have to write class B(A): # access the "p" property from class A @A.p.setter def p(self, p): pass # once p is in the class body scope, you must not use A.p again @p.deleter def p(self): pass Christian From tartley at tartley.com Fri May 28 05:54:31 2010 From: tartley at tartley.com (Jonathan Hartley) Date: Fri, 28 May 2010 02:54:31 -0700 (PDT) Subject: if, continuation and indentation References: Message-ID: On May 27, 1:57?pm, Jean-Michel Pichavant wrote: > HH wrote: > > I have a question about best practices when it comes to line wrapping/ > > continuation and indentation, specifically in the case of an if > > statement. > > > When I write an if statement with many conditions, I prefer to use a > > parenthesis around the whole block and get the implicit continuation, > > rather than ending each line with an escape character. ?Thus, using > > the example from the style guide (http://www.python.org/dev/peps/ > > pep-0008/) I would write: > > > ? ? if (width == 0 and > > ? ? ? ? height == 0 and > > ? ? ? ? color == 'red' and > > ? ? ? ? emphasis == 'strong' or > > ? ? ? ? highlight > 100): > > ? ? ? ? raise ValueError("sorry, you lose") > > > The problem should be obvious -- it's not easy to see where the > > conditional ends and the statement begins since they have the same > > indentation. ?Part of the problem, I suppose, is that Emacs indents > > 'height' and the other lines in the conditional to 4 spaces (because > > of the parenthesis). ?How do people deal with this situation? > > > Thanks, > > Henrik > > One possible solution > > ? ? if ( > ? ? ? ? ? ? width == 0 and > ? ? ? ? ? ? height == 0 and > ? ? ? ? ? ? color == 'red' and > ? ? ? ? ? ? emphasis == 'strong' or > ? ? ? ? ? ? highlight > 100 > ? ? ? ?): > ? ? ? ? raise ValueError("sorry, you lose") > > JM ? I've always liked this, or even: if ( width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100 ): raise ValueError("sorry, you lose") but my co-workers have uniformly gone bananas whenever I try it. From jeanmichel at sequans.com Fri May 28 06:34:54 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 28 May 2010 12:34:54 +0200 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: <4BFF9C4E.1020208@sequans.com> Jonathan Hartley wrote: > On May 27, 1:57 pm, Jean-Michel Pichavant > wrote: > >> HH wrote: >> >>> I have a question about best practices when it comes to line wrapping/ >>> continuation and indentation, specifically in the case of an if >>> statement. >>> >>> When I write an if statement with many conditions, I prefer to use a >>> parenthesis around the whole block and get the implicit continuation, >>> rather than ending each line with an escape character. Thus, using >>> the example from the style guide (http://www.python.org/dev/peps/ >>> pep-0008/) I would write: >>> >>> if (width == 0 and >>> height == 0 and >>> color == 'red' and >>> emphasis == 'strong' or >>> highlight > 100): >>> raise ValueError("sorry, you lose") >>> >>> The problem should be obvious -- it's not easy to see where the >>> conditional ends and the statement begins since they have the same >>> indentation. Part of the problem, I suppose, is that Emacs indents >>> 'height' and the other lines in the conditional to 4 spaces (because >>> of the parenthesis). How do people deal with this situation? >>> >>> Thanks, >>> Henrik >>> >> One possible solution >> >> if ( >> width == 0 and >> height == 0 and >> color == 'red' and >> emphasis == 'strong' or >> highlight > 100 >> ): >> raise ValueError("sorry, you lose") >> >> JM >> > > I've always liked this, or even: > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100 > ): > raise ValueError("sorry, you lose") > > > but my co-workers have uniformly gone bananas whenever I try it. > I tried to give a layout that fits the OP way of doing, but I would not use what I described above, so I can understand why your co workers go bananas :) when it comes to extended conditions in if statement I prefer to write something like if self.haveLost(): raise ValueError("sorry, you lose") It drastically improves the reading because it splits the notion of what to do in which case, and how do you identify the cases (i.e. what should I do when I've lost, and how do I know that I've lost). If you don't want to pollute your upper namespace you can embed the function that way: def foo(): width = 0 height = 0 color = 'red' emphasis = 'strong' def haveLost(): return not width and not height and color == 'red' and emphasis =='strong' if haveLost(): raise ValueError("sorry you lose") It has the cool side effect to name your condition as well, that helps debugging the condition *a lot*. JM From tartley at tartley.com Fri May 28 06:48:59 2010 From: tartley at tartley.com (Jonathan Hartley) Date: Fri, 28 May 2010 11:48:59 +0100 Subject: if, continuation and indentation In-Reply-To: <4BFF9C4E.1020208@sequans.com> References: <4BFF9C4E.1020208@sequans.com> Message-ID: <4BFF9F9B.40103@tartley.com> On 28/05/2010 11:34, Jean-Michel Pichavant wrote: > Jonathan Hartley wrote: >> On May 27, 1:57 pm, Jean-Michel Pichavant >> wrote: >>> HH wrote: >>>> I have a question about best practices when it comes to line wrapping/ >>>> continuation and indentation, specifically in the case of an if >>>> statement. >>>> When I write an if statement with many conditions, I prefer >>>> to use a >>>> parenthesis around the whole block and get the implicit continuation, >>>> rather than ending each line with an escape character. Thus, using >>>> the example from the style guide (http://www.python.org/dev/peps/ >>>> pep-0008/) I would write: >>>> if (width == 0 and >>>> height == 0 and >>>> color == 'red' and >>>> emphasis == 'strong' or >>>> highlight > 100): >>>> raise ValueError("sorry, you lose") >>>> The problem should be obvious -- it's not easy to see where the >>>> conditional ends and the statement begins since they have the same >>>> indentation. Part of the problem, I suppose, is that Emacs indents >>>> 'height' and the other lines in the conditional to 4 spaces (because >>>> of the parenthesis). How do people deal with this situation? >>>> Thanks, >>>> Henrik >>> One possible solution >>> >>> if ( >>> width == 0 and >>> height == 0 and >>> color == 'red' and >>> emphasis == 'strong' or >>> highlight > 100 >>> ): >>> raise ValueError("sorry, you lose") >>> >>> JM >> >> I've always liked this, or even: >> >> if ( >> width == 0 and >> height == 0 and >> color == 'red' and >> emphasis == 'strong' or >> highlight > 100 >> ): >> raise ValueError("sorry, you lose") >> >> >> but my co-workers have uniformly gone bananas whenever I try it. > I tried to give a layout that fits the OP way of doing, but I would > not use what I described above, so I can understand why your co > workers go bananas :) > > when it comes to extended conditions in if statement I prefer to write > something like > > if self.haveLost(): > raise ValueError("sorry, you lose") > > It drastically improves the reading Good point. +1 for naming the condition, hooray for self-documenting code. Sometime last year at my workplace, we started referring to comments as 'lies', we now always try to use techniques like this instead of comments. -- Jonathan Hartley Made of meat. http://tartley.com tartley at tartley.com +44 7737 062 225 twitter/skype: tartley From kaklis at gmail.com Fri May 28 07:50:21 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 28 May 2010 04:50:21 -0700 (PDT) Subject: Sockets and xml problem Message-ID: <0ee7b377-66af-4b77-aa7f-3e5ef3b2b1ef@q33g2000vbt.googlegroups.com> Hi in the following code class MyClientHandler(SocketServer.BaseRequestHandler): def handle(self): print self.client_address, now( ) time.sleep(5) while True: xmltxt = self.request.recv(1024) <--is this ok - enough? if not xmltxt: break doc = minidom.parseString(data) <--- it also fails for parse(data) rootNode = doc.documentElement level = 0 walk(rootNode, outFile, level) <---just a function to print the xml self.request.send('Echo=>%s at %s' % (data, now( ))) rootNode = doc.documentElement level = 0 walk(rootNode, outFile, level) self.request.send('Echo=>%s at %s' % (data, now( ))) self.request.close( ) # make a threaded server, listen/handle clients forever myaddr = (myHost, myPort) server = SocketServer.ThreadingTCPServer(myaddr, MyClientHandler) server.serve_forever( ) I want to send XML messages from my client. The server sends back the XML it receives but the parser exits with error codes. What am i doing wrong. Thanks in advance From victorsubervi at gmail.com Fri May 28 08:06:10 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 28 May 2010 08:06:10 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEE87B.1030302@tim.thechases.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> <4BFEA8A4.2040202@thechases.com> <4BFEE87B.1030302@tim.thechases.com> Message-ID: On Thu, May 27, 2010 at 5:47 PM, Tim Chase wrote: > On 05/27/2010 03:32 PM, Victor Subervi wrote: > > On Thu, May 27, 2010 at 1:15 PM, Tim Chase wrote: >> >>> That should be: >>>> >>>> ', '.join(['%s'] * len(values))) >>>> >>> >>> Or as I've done in the past: >>> >>> ', '.join('%s' for _ in values) >>> >> >> Huh? Can you describe that underscore to me? Fascinating! >> > > The underscore is a valid variable-name, idiomatically used for "I don't > care about this", often seen in places like tuple assignment: > > a,_,_,d = some_4_element_tuple > > So in my above case, it could also have been written as > > ', '.join('%s' for value in values) > ', '.join('%s' for dont_care_about_the_value in values) > > but the "_" idiom means "I'm iterating over 'values' but I'm not actually > using the values I get from it" > I should have known. Thanks! beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Fri May 28 08:16:09 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 28 May 2010 08:16:09 -0400 Subject: Some More MySQL In-Reply-To: References: <4BFEBFF3.6040909@mrabarnett.plus.com> <4BFEF0A0.2040800@mrabarnett.plus.com> Message-ID: On Fri, May 28, 2010 at 2:17 AM, Dennis Lee Bieber wrote: > On Thu, 27 May 2010 23:22:24 +0100, MRAB > declaimed the following in gmane.comp.python.general: > > > > > Placeholders which are handled by .execute shouldn't be wrapped in > > quotes, even is the value is a string, because .execute will handle that > > (and any other details) itself. > > Even more internal details -- the MySQLdb placeholder is %s because > the adapter, internally, converts ALL parameters to strings, applies > escapes to them, and THEN wraps them with quotes before using Python > string interpolation to make the query that gets submitted to the > server. > > This is why you can not use, say %d as a placeholder for a numeric > parameter... MySQLdb will convert that numeric to a string, and then > Python will choke when it tries to use a %d formatter and is given a > string value. > > > All of your and MRAB's comments were very helpful. However, I don't see how these two problems are addressed: sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + opTable[1:]) # cursor.execute(sql, id) cursor.execute('select * from options%s where ID=%s' % (opTable[0].upper() + opTable[1:], id)) The last one works, but if I comment it out and uncomment the middle line, it doesn't. Same here: sql = "update options%s set PriceDiff='%%s' where Field='%%s' and ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:]) # cursor.execute(sql, (value, opName, id, store)) cursor.execute('update options%s set PriceDiff="%s" where Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:], value, opName, id, store)) TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From awilliam at whitemice.org Fri May 28 08:17:44 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 28 May 2010 08:17:44 -0400 Subject: multiprocessing and accessing server's stdout In-Reply-To: References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: <1275049064.7612.4.camel@linux-yu4c.site> On Thu, 2010-05-27 at 08:36 -0700, Tim Arnold wrote: > On May 26, 4:52 pm, Adam Tauno Williams > wrote: > > On Wed, 2010-05-26 at 11:47 -0700, Tim Arnold wrote: > > > Hi, > > > I'm using multiprocessing's BaseManager to create a server on one > > > machine and a client on another. The client fires a request and the > > > server does some work, the result of which ends up on a shared file > > > system that both the client and server can see. > > > However, I need the client machine to see the stdout of the process > > > running on the server. Not sure this is doable--I've been unable to > > > google anything useful on this one. > > > > Nope, it isn't. Don't use stdout, use an IPC mechanism to communicate > > between the client and the server if you need feedback. > Thanks for that info, it saves me some time. This is a new area for me > though: do you redirect stdout on the server to a socket and have the > client listen and somehow pipe the sockets contents to the client > stdout? No, I close stdin, stderr, and stdout on the server processes and attach them to /dev/null. Just don't use stdout. > Interestingly, the RPYc package manages it--that is, the client gets > the stdout of the server process, so I'll dig into that code to get an > idea. In the meantime, are there any recipes or other docs that would > be helpful? I've been googling but without much luck. Closing stdout and attaching it to any other file descriptor is pretty simple. sys.stdout = open('/dev/null', 'w') You should be able to point it any any file-like object. But, again, why? If you have the data in the process why send it to stdout and redirect it. Why not just send the data to the client directly? -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From stefan_ml at behnel.de Fri May 28 08:23:22 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 28 May 2010 14:23:22 +0200 Subject: Sockets and xml problem In-Reply-To: <0ee7b377-66af-4b77-aa7f-3e5ef3b2b1ef@q33g2000vbt.googlegroups.com> References: <0ee7b377-66af-4b77-aa7f-3e5ef3b2b1ef@q33g2000vbt.googlegroups.com> Message-ID: kaklis at gmail.com, 28.05.2010 13:50: > Hi in the following code > > class MyClientHandler(SocketServer.BaseRequestHandler): > def handle(self): > print self.client_address, now( ) > time.sleep(5) > while True: > xmltxt = self.request.recv(1024)<--is this ok - > enough? Depends. If your messages are never larger than 1K, this is enough. Otherwise, you have to collect the data, instead of parsing each chunk separately. I suggest using the incremental parser in xml.etree.ElementTree, which allows you to push more data into the parser as it comes in. When done, call it's .close() method to retrieve the result. http://docs.python.org/library/xml.etree.elementtree.html#xmltreebuilder-objects > I want to send XML messages from my client. The server sends back the > XML it receives but the parser exits with error codes. You should also rethink your approach one more time. Are you sure that a raw socket is a good protocol for sending your messages? In many cases, a proper higher-level transport protocol like HTTP is much better suited. If you provide more details about what you are trying to do, others may be able to help you further. Stefan From kaklis at gmail.com Fri May 28 08:40:25 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 28 May 2010 05:40:25 -0700 (PDT) Subject: Sockets and xml problem References: <0ee7b377-66af-4b77-aa7f-3e5ef3b2b1ef@q33g2000vbt.googlegroups.com> Message-ID: <650933f4-0db2-4a42-a0a3-0a92d15fd6f0@o4g2000vbo.googlegroups.com> On May 28, 3:23?pm, Stefan Behnel wrote: > kak... at gmail.com, 28.05.2010 13:50: > > > Hi in the following code > > > class MyClientHandler(SocketServer.BaseRequestHandler): > > ? ? ?def handle(self): > > ? ? ? ? ?print self.client_address, now( ) > > ? ? ? ? ?time.sleep(5) > > ? ? ? ? ?while True: > > ? ? ? ? ? ? ?xmltxt = self.request.recv(1024)<--is this ok - > > enough? > > Depends. If your messages are never larger than 1K, this is enough. > Otherwise, you have to collect the data, instead of parsing each chunk > separately. > > I suggest using the incremental parser in xml.etree.ElementTree, which > allows you to push more data into the parser as it comes in. When done, > call it's .close() method to retrieve the result. > > http://docs.python.org/library/xml.etree.elementtree.html#xmltreebuil... > > > I want to send XML messages from my client. The server sends back the > > XML it receives but the parser exits with error codes. > > You should also rethink your approach one more time. Are you sure that a > raw socket is a good protocol for sending your messages? In many cases, a > proper higher-level transport protocol like HTTP is much better suited. If > you provide more details about what you are trying to do, others may be > able to help you further. > > Stefan Stefan first of all thank you for your response. I don't want anything fancy. Just a simple server that accepts xml messages from multple clients in xml, parses the XML and show it in a console. Antonis From tino at wildenhain.de Fri May 28 08:41:54 2010 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 28 May 2010 14:41:54 +0200 Subject: Free chapter about Python and databases (MySQL and SQLite) In-Reply-To: References: Message-ID: <4BFFBA12.6050004@wildenhain.de> Hi, Am 28.05.2010 04:45, schrieb Sebastian Bassi: > Hello, I want to announce that the publisher of "Python for > Bioinformatis" (CRC Press) allowed me to publish a chapter from my > book. > I decided to publish the chapter about "Python and databases". I think > it may be useful for somebody. > The official announcement and download link is here: > http://py4bio.com/2010/05/28/python_databases_mysql_sqlite/ > For more information about the book: www.tinyurl.com/biopython > Best, > SB. This is nice! Congrats! Did you consider adding a part dealing with postgresql too? (Especially interesting in the way you can write stored functions in python there) Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3254 bytes Desc: S/MIME Cryptographic Signature URL: From kushal.kumaran+python at gmail.com Fri May 28 08:58:29 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Fri, 28 May 2010 18:28:29 +0530 Subject: Some More MySQL In-Reply-To: References: <4BFEBFF3.6040909@mrabarnett.plus.com> <4BFEF0A0.2040800@mrabarnett.plus.com> Message-ID: On Fri, May 28, 2010 at 5:46 PM, Victor Subervi wrote: > On Fri, May 28, 2010 at 2:17 AM, Dennis Lee Bieber > wrote: >> >> On Thu, 27 May 2010 23:22:24 +0100, MRAB >> declaimed the following in gmane.comp.python.general: >> >> > >> > Placeholders which are handled by .execute shouldn't be wrapped in >> > quotes, even is the value is a string, because .execute will handle that >> > (and any other details) itself. >> >> ? ? ? ?Even more internal details -- the MySQLdb placeholder is %s because >> the adapter, internally, converts ALL parameters to strings, applies >> escapes to them, and THEN wraps them with quotes before using Python >> string interpolation to make the query that gets submitted to the >> server. >> >> ? ? ? ?This is why you can not use, say %d as a placeholder for a numeric >> parameter... MySQLdb will convert that numeric to a string, and then >> Python will choke when it tries to use a %d formatter and is given a >> string value. >> >> > All of your and MRAB's comments were very helpful. However, I don't see how > these two problems are addressed: > > ????? sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + > opTable[1:]) > #????? cursor.execute(sql, id) > ????? cursor.execute('select * from options%s where ID=%s' % > (opTable[0].upper() + opTable[1:], id)) > The second argument to cursor.execute needs to be a tuple. Change the call to this: cursor.execute(sql, (id,)) > The last one works, but if I comment it out and uncomment the middle line, > it doesn't. Same here: > > ??????? sql = "update options%s set PriceDiff='%%s' where Field='%%s' and > ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:]) > #??????? cursor.execute(sql, (value, opName, id, store)) > ??????? cursor.execute('update options%s set PriceDiff="%s" where Field="%s" > and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:], value, > opName, id, store)) > Lose the quotes around the %s. You are replying to a post that describes why this is important. -- regards, kushal From martin.hellwig at dcuktec.org Fri May 28 10:41:27 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 28 May 2010 15:41:27 +0100 Subject: multiprocessing and accessing server's stdout In-Reply-To: References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: On 05/28/10 13:17, Adam Tauno Williams wrote: > > You should be able to point it any any file-like object. But, again, > why? > > If you have the data in the process why send it to stdout and redirect > it. Why not just send the data to the client directly? Well you might want to multiplex it to more then one client, not saying that this is the case here, just something I imagine possible. -- mph From eric.brunel.pragmadev at gmail.com Fri May 28 11:01:29 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Fri, 28 May 2010 08:01:29 -0700 (PDT) Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> <4d9e0aff-c013-43ea-81e2-cd674149a05a@z33g2000vbb.googlegroups.com> Message-ID: <846debaa-dfb6-4ba4-a421-8c202a1b7756@o15g2000vbb.googlegroups.com> On May 28, 11:50?am, Christian Heimes wrote: > Am 28.05.2010 11:31, schrieb eb303: > > > > > On May 27, 3:24 pm, Christian Heimes wrote: > >>> ?Do I miss something? > >>> Is this the way to do it, or is there a better one? > > >> A better way was introduced in Python 2.6. Seehttp://docs.python.org/library/functions.html?highlight=property#prop... > >> I have a Python only version around if you are still using Python 2.5. > > >> Christian > > > Mmmm, I might still miss something. OK, I can replace my initial > > property using @property and @p.setter, but it doesn't seem to work in > > subclasses: > > > class A(object): > > ? @property > > ? def p(self): > > ? ? return self._p > > ? @p.setter > > ? def _set_p(self, p): > > ? ? self._p = p > > class B(A): > > ? @p.setter > > ? def _set_p(self, p): > > ? ? ? > > > results in: > > > Traceback (most recent call last): > > ? File "toto.py", line 8, in > > ? ? class B(A): > > ? File "toto.py", line 9, in B > > ? ? @p.setter > > NameError: name 'p' is not defined > > It doesn't work because "p" is not in the scope of B's body while B is > created. You have to write > > class B(A): > ? ? # access the "p" property from class A > ? ? @A.p.setter > ? ? def p(self, p): > ? ? ? ? pass > > ? ? # once p is in the class body scope, you must not use A.p again > ? ? @p.deleter > ? ? def p(self): > ? ? ? ? pass > > Christian Well, I still have to explicitely specify the superclass's name then, so IMHO it's not a big improvement over repeating: p = property(A._get_p, _set_p) Thanks anyway? - Eric - From sbassi at clubdelarazon.org Fri May 28 11:12:55 2010 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Fri, 28 May 2010 12:12:55 -0300 Subject: Free chapter about Python and databases (MySQL and SQLite) In-Reply-To: <4BFFBA12.6050004@wildenhain.de> References: <4BFFBA12.6050004@wildenhain.de> Message-ID: On Fri, May 28, 2010 at 9:41 AM, Tino Wildenhain wrote: > Did you consider adding a part dealing with postgresql too? > (Especially interesting in the way you can write stored functions > in python there) That is a good idea for the next version/edition. But meanwhile I could write something in my blog at www.py4bio.com Best, SB From xcr4cx at googlemail.com Fri May 28 11:17:11 2010 From: xcr4cx at googlemail.com (christian schulze) Date: Fri, 28 May 2010 08:17:11 -0700 (PDT) Subject: http post References: <44b9686b-36d6-4aef-b20c-01b909e2ea53@q33g2000vbt.googlegroups.com> Message-ID: <6c0ada45-fa7e-45f6-8d4a-b92fd89e6548@v18g2000vbc.googlegroups.com> On 28 Mai, 16:47, yqyq22 wrote: > Hy, i would like to create a little script to reproduce this one > below: > Do you have suggestion? > > POST /folder/path/upload.exe?/dir HTTP/1.1 > Host: 192.168.100.1:8080 > User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: > 1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/ > *;q=0.8 > Accept-Language: en-us,en;q=0.5 > Accept-Encoding: gzip,deflate > Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 > Keep-Alive: 115 > Proxy-Connection: keep-alive > Referer:http://192.168.1.100:8080/dir1 > Content-Type: multipart/form-data; > boundary=---------------------------7075104567331 > Content-Length: 539 > Connection: close > > -----------------------------7075104567331 > Content-Disposition: form-data; name="F1"; filename="file.txt" > Content-Type: application/octet-stream > > -----------------------------7075104567331 > Content-Disposition: form-data; name="p4" > > -----------------------------7075104567331-- > > THANKS A LOT Just send it via a socket? Or use urllib, afair you can send custom HTTP headers. From yqyq22 at hotmail.com Fri May 28 11:20:53 2010 From: yqyq22 at hotmail.com (yqyq22) Date: Fri, 28 May 2010 08:20:53 -0700 (PDT) Subject: http post References: <44b9686b-36d6-4aef-b20c-01b909e2ea53@q33g2000vbt.googlegroups.com> <6c0ada45-fa7e-45f6-8d4a-b92fd89e6548@v18g2000vbc.googlegroups.com> Message-ID: <43b79db3-1b2d-48f8-8fe3-95a91fbc447c@a16g2000vbr.googlegroups.com> On May 28, 5:17?pm, christian schulze wrote: > On 28 Mai, 16:47, yqyq22 wrote: > > > > > > > Hy, i would like to create a little script to reproduce this one > > below: > > Do you have suggestion? > > > POST /folder/path/upload.exe?/dir HTTP/1.1 > > Host: 192.168.100.1:8080 > > User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: > > 1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) > > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/ > > *;q=0.8 > > Accept-Language: en-us,en;q=0.5 > > Accept-Encoding: gzip,deflate > > Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 > > Keep-Alive: 115 > > Proxy-Connection: keep-alive > > Referer:http://192.168.1.100:8080/dir1 > > Content-Type: multipart/form-data; > > boundary=---------------------------7075104567331 > > Content-Length: 539 > > Connection: close > > > -----------------------------7075104567331 > > Content-Disposition: form-data; name="F1"; filename="file.txt" > > Content-Type: application/octet-stream > > > -----------------------------7075104567331 > > Content-Disposition: form-data; name="p4" > > > -----------------------------7075104567331-- > > > THANKS A LOT > > Just send it via a socket? Or use urllib, afair you can send custom > HTTP headers.- Hide quoted text - > > - Show quoted text - If i understood right i would use only socket.. is it possible? thanks From xcr4cx at googlemail.com Fri May 28 11:23:18 2010 From: xcr4cx at googlemail.com (christian schulze) Date: Fri, 28 May 2010 08:23:18 -0700 (PDT) Subject: Free chapter about Python and databases (MySQL and SQLite) References: <4BFFBA12.6050004@wildenhain.de> Message-ID: <75097175-6f22-4eaa-aa69-c93df86227c5@o4g2000vbo.googlegroups.com> On 28 Mai, 17:12, Sebastian Bassi wrote: > On Fri, May 28, 2010 at 9:41 AM, Tino Wildenhain wrote: > > Did you consider adding a part dealing with postgresql too? > > (Especially interesting in the way you can write stored functions > > in python there) > > That is a good idea for the next version/edition. But meanwhile I > could write something in my blog atwww.py4bio.com > Best, > SB Indeed a style like > user="root" is not that nice. I had no look at the chapter but recommend you to read the PEP 8 - Python style guides (code conventions for python). Imo a book have to be kinda exemplary. And bad style sucks anyway ... PS: > user = 'root' or user = "root" ... would be much more beautyful. From kaklis at gmail.com Fri May 28 11:24:21 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 28 May 2010 08:24:21 -0700 (PDT) Subject: Omit the headers from XML message Message-ID: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Hi i have the following xml message i want to omit the headers, any hints? POST /test/pcp/Listener HTTP/1.1 User-Agent: Jakarta Commons-HttpClient/3.1 Host: 127.0.0.1:50002 Content-Length: 547 scvdcvsdv sdfv Antonis Kaklis away testing the new client jlkdjf android From xcr4cx at googlemail.com Fri May 28 11:24:28 2010 From: xcr4cx at googlemail.com (christian schulze) Date: Fri, 28 May 2010 08:24:28 -0700 (PDT) Subject: http post References: <44b9686b-36d6-4aef-b20c-01b909e2ea53@q33g2000vbt.googlegroups.com> <6c0ada45-fa7e-45f6-8d4a-b92fd89e6548@v18g2000vbc.googlegroups.com> <43b79db3-1b2d-48f8-8fe3-95a91fbc447c@a16g2000vbr.googlegroups.com> Message-ID: <6fce9505-229f-4086-bc51-290369da474b@k31g2000vbu.googlegroups.com> On 28 Mai, 17:20, yqyq22 wrote: > On May 28, 5:17?pm, christian schulze wrote: > > > > > On 28 Mai, 16:47, yqyq22 wrote: > > > > Hy, i would like to create a little script to reproduce this one > > > below: > > > Do you have suggestion? > > > > POST /folder/path/upload.exe?/dir HTTP/1.1 > > > Host: 192.168.100.1:8080 > > > User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: > > > 1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) > > > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/ > > > *;q=0.8 > > > Accept-Language: en-us,en;q=0.5 > > > Accept-Encoding: gzip,deflate > > > Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 > > > Keep-Alive: 115 > > > Proxy-Connection: keep-alive > > > Referer:http://192.168.1.100:8080/dir1 > > > Content-Type: multipart/form-data; > > > boundary=---------------------------7075104567331 > > > Content-Length: 539 > > > Connection: close > > > > -----------------------------7075104567331 > > > Content-Disposition: form-data; name="F1"; filename="file.txt" > > > Content-Type: application/octet-stream > > > > -----------------------------7075104567331 > > > Content-Disposition: form-data; name="p4" > > > > -----------------------------7075104567331-- > > > > THANKS A LOT > > > Just send it via a socket? Or use urllib, afair you can send custom > > HTTP headers.- Hide quoted text - > > > - Show quoted text - > > If i understood right i would use only socket.. is it possible? > thanks Yeah i think so, but i am not quite sure. Just test it :) From yqyq22 at hotmail.com Fri May 28 11:28:45 2010 From: yqyq22 at hotmail.com (yqyq22) Date: Fri, 28 May 2010 08:28:45 -0700 (PDT) Subject: http post References: <44b9686b-36d6-4aef-b20c-01b909e2ea53@q33g2000vbt.googlegroups.com> <6c0ada45-fa7e-45f6-8d4a-b92fd89e6548@v18g2000vbc.googlegroups.com> <43b79db3-1b2d-48f8-8fe3-95a91fbc447c@a16g2000vbr.googlegroups.com> <6fce9505-229f-4086-bc51-290369da474b@k31g2000vbu.googlegroups.com> Message-ID: <323e9d46-09ec-44b4-94d0-e3241579c284@v18g2000vbc.googlegroups.com> On May 28, 5:24?pm, christian schulze wrote: > On 28 Mai, 17:20, yqyq22 wrote: > > > > > > > On May 28, 5:17?pm, christian schulze wrote: > > > > On 28 Mai, 16:47, yqyq22 wrote: > > > > > Hy, i would like to create a little script to reproduce this one > > > > below: > > > > Do you have suggestion? > > > > > POST /folder/path/upload.exe?/dir HTTP/1.1 > > > > Host: 192.168.100.1:8080 > > > > User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: > > > > 1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) > > > > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/ > > > > *;q=0.8 > > > > Accept-Language: en-us,en;q=0.5 > > > > Accept-Encoding: gzip,deflate > > > > Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 > > > > Keep-Alive: 115 > > > > Proxy-Connection: keep-alive > > > > Referer:http://192.168.1.100:8080/dir1 > > > > Content-Type: multipart/form-data; > > > > boundary=---------------------------7075104567331 > > > > Content-Length: 539 > > > > Connection: close > > > > > -----------------------------7075104567331 > > > > Content-Disposition: form-data; name="F1"; filename="file.txt" > > > > Content-Type: application/octet-stream > > > > > -----------------------------7075104567331 > > > > Content-Disposition: form-data; name="p4" > > > > > -----------------------------7075104567331-- > > > > > THANKS A LOT > > > > Just send it via a socket? Or use urllib, afair you can send custom > > > HTTP headers.- Hide quoted text - > > > > - Show quoted text - > > > If i understood right i would use only socket.. is it possible? > > thanks > > Yeah i think so, but i am not quite sure. Just test it :)- Hide quoted text - > > - Show quoted text - Do u have an example/link "closed" to my need? thanks From mgreene at bdurham.com Fri May 28 11:32:45 2010 From: mgreene at bdurham.com (Malcolm Greene) Date: Fri, 28 May 2010 11:32:45 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEE87B.1030302@tim.thechases.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> <4BFEA8A4.2040202@thechases.com> <4BFEE87B.1030302@tim.thechases.com> Message-ID: <1275060765.5732.1377397625@webmail.messagingengine.com> Tim, > The underscore is a valid variable-name, idiomatically used for "I don't care about this", often seen in places like tuple assignment: The underscore is also used as an alias for gettext.gettext or gettext.ugettext so you may want to use another variable-name. Malcolm From victorsubervi at gmail.com Fri May 28 11:39:24 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 28 May 2010 11:39:24 -0400 Subject: Some More MySQL In-Reply-To: References: <4BFEBFF3.6040909@mrabarnett.plus.com> <4BFEF0A0.2040800@mrabarnett.plus.com> Message-ID: I still have this code: sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + opTable[1:]) cursor.execute(sql, (id,)) which throws this error: /var/www/html/angrynates.com/cart/enterOptionsPrices2.py 70 print 'All options prices have been successfully updated.' 71 print '\n' 72 73 enterOptionsPrices2() 74 enterOptionsPrices2 = /var/www/html/angrynates.com/cart/enterOptionsPrices2.py in enterOptionsPrices2() 58 id = form.getfirst('%sID' % option) 59 sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + opTable[1:]) 60 cursor.execute(sql, (id,)) 61 # cursor.execute('select * from options%s where ID=%s' % (opTable[0].upper() + opTable[1:], id)) 62 if cursor.fetchone() is not None: cursor = , cursor.execute = >, sql = ('select * from options%s where ID=%%s', 'Sizes'), id = '0.00' /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in execute(self=, query=('select * from options%s where ID=%%s', 'Sizes'), args=('0.00',)) 144 db = self._get_db() 145 charset = db.character_set_name() 146 query = query.encode(charset) 147 if args is not None: 148 query = query % db.literal(args) query = ('select * from options%s where ID=%%s', 'Sizes'), query.encode undefined, charset = 'latin1' AttributeError: 'tuple' object has no attribute 'encode' args = ("'tuple' object has no attribute 'encode'",) Please advise. TIA beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From joncle at googlemail.com Fri May 28 11:45:41 2010 From: joncle at googlemail.com (Jon Clements) Date: Fri, 28 May 2010 08:45:41 -0700 (PDT) Subject: Omit the headers from XML message References: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Message-ID: On 28 May, 16:24, "kak... at gmail.com" wrote: > Hi i have the following xml message i want to omit the headers, any > hints? > > POST /test/pcp/Listener HTTP/1.1 > User-Agent: Jakarta Commons-HttpClient/3.1 > Host: 127.0.0.1:50002 > Content-Length: 547 > > > ? > ? ? > ? ? ? > ? ? ? ? scvdcvsdv > ? ? ? ? sdfv > ? ? ? ? Antonis Kaklis > ? ? ? ? away > ? ? ? ? testing the new client > ? ? ? ? jlkdjf > ? ? ? ? android > ? ? ? > ? ? > ? > Assuming the header is separated by a blank line, something like: list(islice(dropwhile(bool, s.split('\n')), 1, None)) From __peter__ at web.de Fri May 28 12:09:02 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2010 18:09:02 +0200 Subject: Free chapter about Python and databases (MySQL and SQLite) References: <4BFFBA12.6050004@wildenhain.de> <75097175-6f22-4eaa-aa69-c93df86227c5@o4g2000vbo.googlegroups.com> Message-ID: christian schulze wrote: > On 28 Mai, 17:12, Sebastian Bassi wrote: >> On Fri, May 28, 2010 at 9:41 AM, Tino Wildenhain >> wrote: >> > Did you consider adding a part dealing with postgresql too? >> > (Especially interesting in the way you can write stored functions >> > in python there) >> >> That is a good idea for the next version/edition. But meanwhile I >> could write something in my blog atwww.py4bio.com >> Best, >> SB > > Indeed a style like >> user="root" > is not that nice. > > I had no look at the chapter but recommend you to read the PEP 8 - > Python style guides (code conventions for python). > > Imo a book have to be kinda exemplary. And bad style sucks anyway ... > > PS: >> user = 'root' or user = "root" > ... would be much more beautyful. My crystal ball says that the post you are not quoting is concerned about the security implications of accessing a database as the superuser rather than about spaces surrounding the assignment operator. My crystal ball then starts nitpicking and adds that in the sample chapter user="root" occurs within an argument list where its format is actually required by the PEP: """ - Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value. Yes: def complex(real, imag=0.0): return magic(r=real, i=imag) """ Cheers, Peter From kaklis at gmail.com Fri May 28 12:38:23 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 28 May 2010 09:38:23 -0700 (PDT) Subject: Omit the headers from XML message References: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Message-ID: <5288770c-bfdf-41e3-a2a6-f38587f07802@q13g2000vbm.googlegroups.com> On 28 ?????, 18:45, Jon Clements wrote: > On 28 May, 16:24, "kak... at gmail.com" wrote: > > > > > > > Hi i have the following xml message i want to omit the headers, any > > hints? > > > POST /test/pcp/Listener HTTP/1.1 > > User-Agent: Jakarta Commons-HttpClient/3.1 > > Host: 127.0.0.1:50002 > > Content-Length: 547 > > > > > ? > > ? ? > > ? ? ? > > ? ? ? ? scvdcvsdv > > ? ? ? ? sdfv > > ? ? ? ? Antonis Kaklis > > ? ? ? ? away > > ? ? ? ? testing the new client > > ? ? ? ? jlkdjf > > ? ? ? ? android > > ? ? ? > > ? ? > > ? > > > > Assuming the header is separated by a blank line, something like: > > list(islice(dropwhile(bool, s.split('\n')), 1, None)) Thank you!!! Antonis From python at mrabarnett.plus.com Fri May 28 12:39:32 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 May 2010 17:39:32 +0100 Subject: Some More MySQL In-Reply-To: References: <4BFEBFF3.6040909@mrabarnett.plus.com> <4BFEF0A0.2040800@mrabarnett.plus.com> Message-ID: <4BFFF1C4.3030901@mrabarnett.plus.com> Victor Subervi wrote: > I still have this code: > > sql = 'select * from options%s where ID=%%s', (opTable[0].upper() > + opTable[1:]) > cursor.execute(sql, (id,)) > > which throws this error: > > /var/www/html/angrynates.com/cart/enterOptionsPrices2.py > > 70 print 'All options prices have been successfully updated.' > 71 print '\n' > 72 > 73 enterOptionsPrices2() > 74 > enterOptionsPrices2 = > /var/www/html/angrynates.com/cart/enterOptionsPrices2.py > in enterOptionsPrices2() > 58 id = form.getfirst('%sID' % option) > 59 sql = 'select * from options%s where ID=%%s', > (opTable[0].upper() + opTable[1:]) > 60 cursor.execute(sql, (id,)) > 61 # cursor.execute('select * from options%s where ID=%s' % > (opTable[0].upper() + opTable[1:], id)) > 62 if cursor.fetchone() is not None: > cursor = , cursor.execute = Cursor.execute of >, sql = ('select * > from options%s where ID=%%s', 'Sizes'), id = '0.00' > /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in > execute(self=, query=('select * from > options%s where ID=%%s', 'Sizes'), args=('0.00',)) > 144 db = self._get_db() > 145 charset = db.character_set_name() > 146 query = query.encode(charset) > 147 if args is not None: > 148 query = query % db.literal(args) > query = ('select * from options%s where ID=%%s', 'Sizes'), query.encode > undefined, charset = 'latin1' > > AttributeError: 'tuple' object has no attribute 'encode' > args = ("'tuple' object has no attribute 'encode'",) > > > Please advise. > On line 59 you're making a tuple. From stefan_ml at behnel.de Fri May 28 12:46:54 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 28 May 2010 18:46:54 +0200 Subject: Omit the headers from XML message In-Reply-To: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> References: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Message-ID: kaklis at gmail.com, 28.05.2010 17:24: > Hi i have the following xml message i want to omit the headers, any > hints? > > POST /test/pcp/Listener HTTP/1.1 > User-Agent: Jakarta Commons-HttpClient/3.1 > Host: 127.0.0.1:50002 > Content-Length: 547 > > > > > > scvdcvsdv > sdfv > Antonis Kaklis > away > testing the new client > jlkdjf > android > > > > Use the HTTP server that comes with Python, instead of the plain socket server. Stefan From __peter__ at web.de Fri May 28 12:48:27 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2010 18:48:27 +0200 Subject: Omit the headers from XML message References: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Message-ID: Jon Clements wrote: > On 28 May, 16:24, "kak... at gmail.com" wrote: >> Hi i have the following xml message i want to omit the headers, any >> hints? > Assuming the header is separated by a blank line, something like: > > list(islice(dropwhile(bool, s.split('\n')), 1, None)) Making the same assumptions, but giving a single string instead of a list of lines: s.partition("\n\n")[-1] Peter From rbrt.somerville at gmail.com Fri May 28 12:55:46 2010 From: rbrt.somerville at gmail.com (robert somerville) Date: Fri, 28 May 2010 09:55:46 -0700 Subject: ElementTree write creates large one line XML file .... Message-ID: Thanks Robert Kern : "prettyprint" ; indent() does the trick ;-) >ElementTree writes exactly what you tell it to. In XML, whitespace is >significant. If you want newlines and/or indentation to make it pretty-looking, >then you need to add those to your elements. > >Fredrik provides an example function for doing this: > > http://effbot.org/zone/element-lib.htm#prettyprint -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.rodola at gmail.com Fri May 28 13:08:01 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Fri, 28 May 2010 19:08:01 +0200 Subject: Like __getattr__ but with args and kwargs as well Message-ID: I know, the title doesn't say much, but I had no better ideas. =) I have a class within a serie of redundant methods, which looks like this: class MixedAuthorizer: def __init__(self, *args): # expected a list of class instances self.authorizers = args def get_home(self, user): for auth in self.authorizers: if not auth.has_user(user): continue return auth.get_home(user) return "" def get_password(self, user): for auth in self.authorizers: if not auth.has_user(user): continue return auth.get_password(user) return "" # follows a long list of get_* methods as above ... Considering that I always do the same thing (iterate over a list of objects -> call obj.has_user() -> call obj.get_*()) I would like to know if there's a more compact way to do that. What I basically need is something like __getattr__ but which provides the arguments and eventually the keyword arguments a method has been called with, other than just its name. Actually I'm not even sure whether Python can reach such a level of dynamism but I wanted to give it a try anyway. Is there a way to do such a thing? --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From cjwilliams43 at gmail.com Fri May 28 13:37:14 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Fri, 28 May 2010 13:37:14 -0400 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: On 28-May-10 05:54 AM, Jonathan Hartley wrote: > On May 27, 1:57 pm, Jean-Michel Pichavant > wrote: >> HH wrote: >>> I have a question about best practices when it comes to line wrapping/ >>> continuation and indentation, specifically in the case of an if >>> statement. >> >>> When I write an if statement with many conditions, I prefer to use a >>> parenthesis around the whole block and get the implicit continuation, >>> rather than ending each line with an escape character. Thus, using >>> the example from the style guide (http://www.python.org/dev/peps/ >>> pep-0008/) I would write: >> >>> if (width == 0 and >>> height == 0 and >>> color == 'red' and >>> emphasis == 'strong' or >>> highlight> 100): >>> raise ValueError("sorry, you lose") >> >>> The problem should be obvious -- it's not easy to see where the >>> conditional ends and the statement begins since they have the same >>> indentation. Part of the problem, I suppose, is that Emacs indents >>> 'height' and the other lines in the conditional to 4 spaces (because >>> of the parenthesis). How do people deal with this situation? >> >>> Thanks, >>> Henrik >> >> One possible solution >> >> if ( >> width == 0 and >> height == 0 and >> color == 'red' and >> emphasis == 'strong' or >> highlight> 100 >> ): >> raise ValueError("sorry, you lose") >> >> JM > > I've always liked this, or even: > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100 > ): > raise ValueError("sorry, you lose") > > > but my co-workers have uniformly gone bananas whenever I try it. I liked: On 27-May-10 08:48 AM, Xavier Ho wrote: > On 27 May 2010 22:22, HH > wrote: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") > > > I've gotta say - I've bumped into this problem before, and I'm sure many > other have - this is a valid question. It just hasn't bothered me enough > to ask... > > Correct me if I'm wrong, but I think the following is equivalent, and > looks better. Although this won't fix all ugly cases in that problem.. > > if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or > highlight > 100: > raise ValueError("sorry, you lose") > > Cheers, > Xav but nobody commented. Colin W. From miki.tebeka at gmail.com Fri May 28 13:39:51 2010 From: miki.tebeka at gmail.com (Miki) Date: Fri, 28 May 2010 10:39:51 -0700 (PDT) Subject: Like __getattr__ but with args and kwargs as well References: Message-ID: <1f67b366-9a2a-41b8-9cad-6f4dcc4b2b21@s1g2000prf.googlegroups.com> class MixedAuthorizer: def __init__(self, *args): # expected a list of class instances self.authorizers = args self._set_methods() def _set_methods(self): for attr in ("home", "password"): def fn(user): return self._get_attr(user, attr) setattr(self, "get_%s" % attr, fn) def _get_attr(self, user, attr): auths = [auth for auth in self.authorizers if auth.has_user(user)] if not auths: return "" method_name = "get_%s" % attr method = getattr(auths[0], method_name, None) if not fn: raise ValueError("Unknown attribute - %s" % method_name) return fn(user) HTH, -- Miki http://pythonwise.blogspot.com From miki.tebeka at gmail.com Fri May 28 13:41:31 2010 From: miki.tebeka at gmail.com (Miki) Date: Fri, 28 May 2010 10:41:31 -0700 (PDT) Subject: Like __getattr__ but with args and kwargs as well References: <1f67b366-9a2a-41b8-9cad-6f4dcc4b2b21@s1g2000prf.googlegroups.com> Message-ID: <4ab734a2-c522-4a0e-b2e2-00e8f403ae65@p5g2000pri.googlegroups.com> > ? ? ? ? method = getattr(auths[0], method_name, None) Should be fn = getattr(auths[0], method_name, None) From clp2 at rebertia.com Fri May 28 13:43:33 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 28 May 2010 10:43:33 -0700 Subject: Like __getattr__ but with args and kwargs as well In-Reply-To: References: Message-ID: On Fri, May 28, 2010 at 10:08 AM, Giampaolo Rodol? wrote: > I know, the title doesn't say much, but I had no better ideas. =) > I have a class within a serie of redundant methods, which looks like this: > > class MixedAuthorizer: > > ? ?def __init__(self, *args): > ? ? ? ?# expected a list of class instances > ? ? ? ?self.authorizers = args > > ? ?def get_home(self, user): > ? ? ? ?for auth in self.authorizers: > ? ? ? ? ? ?if not auth.has_user(user): > ? ? ? ? ? ? ? ?continue > ? ? ? ? ? ?return auth.get_home(user) > ? ? ? ?return "" > > ? ?def get_password(self, user): > ? ? ? ?for auth in self.authorizers: > ? ? ? ? ? ?if not auth.has_user(user): > ? ? ? ? ? ? ? ?continue > ? ? ? ? ? ?return auth.get_password(user) > ? ? ? ?return "" > > ? ? # follows a long list of get_* methods as above > ? ? ... > > > Considering that I always do the same thing (iterate over a list of > objects -> call obj.has_user() -> call obj.get_*()) I would like to > know if there's a more compact way to do that. > What I basically need is something like __getattr__ but which provides > the arguments and eventually the keyword arguments a method has been > called with, other than just its name. > Actually I'm not even sure whether Python can reach such a level of > dynamism but I wanted to give it a try anyway. > Is there a way to do such a thing? There's no such "?ber-__getattr__", but with some indirection we can achieve much the same effect: #Note: Completely untested from functools import partial class Whatever(object): def _getter(self, _name, user, *args, **kwds): # I assume your actual code will use the *args and **kwds for auth in self.authorizers: if not auth.has_user(user): continue return getattr(auth, _name)(user) return "" def __getattr__(self, name): if name.startswith("get_"): return partial(self._getter, _name=name) else: raise AttributeError Cheers, Chris -- http://blog.rebertia.com From __peter__ at web.de Fri May 28 13:52:08 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2010 19:52:08 +0200 Subject: Like __getattr__ but with args and kwargs as well References: Message-ID: Giampaolo Rodol? wrote: > I know, the title doesn't say much, but I had no better ideas. =) > I have a class within a serie of redundant methods, which looks like this: > > class MixedAuthorizer: > > def __init__(self, *args): > # expected a list of class instances > self.authorizers = args > > def get_home(self, user): > for auth in self.authorizers: > if not auth.has_user(user): > continue > return auth.get_home(user) > return "" > > def get_password(self, user): > for auth in self.authorizers: > if not auth.has_user(user): > continue > return auth.get_password(user) > return "" > > # follows a long list of get_* methods as above > ... > > > Considering that I always do the same thing (iterate over a list of > objects -> call obj.has_user() -> call obj.get_*()) I would like to > know if there's a more compact way to do that. > What I basically need is something like __getattr__ but which provides > the arguments and eventually the keyword arguments a method has been > called with, other than just its name. > Actually I'm not even sure whether Python can reach such a level of > dynamism but I wanted to give it a try anyway. > Is there a way to do such a thing? Yes, and for the above example it is easier to implement than you think: class MA(object): def __init__(self, authorizers): self.authorizers = authorizers def __getattr__(self, name): def get(self, user): for auth in self.authorizers: if auth.has_user(user): return getattr(auth, name)(user) return get.__get__(self) You can modify it to pass along arbitrary keyword arguments: class MA(object): def __init__(self, authorizers): self.authorizers = authorizers def __getattr__(self, name): def get(self, **kw): for auth in self.authorizers: if auth.has_user(kw["user"]): return getattr(auth, name)(**kw) return get.__get__(self) Peter From g.rodola at gmail.com Fri May 28 14:29:51 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Fri, 28 May 2010 20:29:51 +0200 Subject: Like __getattr__ but with args and kwargs as well In-Reply-To: References: Message-ID: 2010/5/28 Peter Otten <__peter__ at web.de>: > Giampaolo Rodol? wrote: > >> I know, the title doesn't say much, but I had no better ideas. =) >> I have a class within a serie of redundant methods, which looks like this: >> >> class MixedAuthorizer: >> >> ? ? def __init__(self, *args): >> ? ? ? ? # expected a list of class instances >> ? ? ? ? self.authorizers = args >> >> ? ? def get_home(self, user): >> ? ? ? ? for auth in self.authorizers: >> ? ? ? ? ? ? if not auth.has_user(user): >> ? ? ? ? ? ? ? ? continue >> ? ? ? ? ? ? return auth.get_home(user) >> ? ? ? ? return "" >> >> ? ? def get_password(self, user): >> ? ? ? ? for auth in self.authorizers: >> ? ? ? ? ? ? if not auth.has_user(user): >> ? ? ? ? ? ? ? ? continue >> ? ? ? ? ? ? return auth.get_password(user) >> ? ? ? ? return "" >> >> ? ? ?# follows a long list of get_* methods as above >> ? ? ?... >> >> >> Considering that I always do the same thing (iterate over a list of >> objects -> call obj.has_user() -> call obj.get_*()) I would like to >> know if there's a more compact way to do that. >> What I basically need is something like __getattr__ but which provides >> the arguments and eventually the keyword arguments a method has been >> called with, other than just its name. >> Actually I'm not even sure whether Python can reach such a level of >> dynamism but I wanted to give it a try anyway. >> Is there a way to do such a thing? > > Yes, and for the above example it is easier to implement than you think: > > class MA(object): > ? ?def __init__(self, authorizers): > ? ? ? ?self.authorizers = authorizers > ? ?def __getattr__(self, name): > ? ? ? ?def get(self, user): > ? ? ? ? ? ?for auth in self.authorizers: > ? ? ? ? ? ? ? ?if auth.has_user(user): > ? ? ? ? ? ? ? ? ? ?return getattr(auth, name)(user) > ? ? ? ?return get.__get__(self) > > You can modify it to pass along arbitrary keyword arguments: > > class MA(object): > ? ?def __init__(self, authorizers): > ? ? ? ?self.authorizers = authorizers > ? ?def __getattr__(self, name): > ? ? ? ?def get(self, **kw): > ? ? ? ? ? ?for auth in self.authorizers: > ? ? ? ? ? ? ? ?if auth.has_user(kw["user"]): > ? ? ? ? ? ? ? ? ? ?return getattr(auth, name)(**kw) > ? ? ? ?return get.__get__(self) > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks, this has been helpful. I managed to write this monster: =) class MixedAuthorizer(object): def __init__(self, *authorizers): self.authorizers = authorizers def __getattr__(self, name): def get(self, user, *args, **kwargs): for auth in self.authorizers: if auth.has_user(user): method = getattr(auth, name) return method(user, *args, **kwargs) # if we reached this point no user was found if name == "validate_authentication": return False if name.startswith("get"): return "" if name.startswith("has"): return False return get.__get__(self) --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From python at mrabarnett.plus.com Fri May 28 14:42:45 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 May 2010 19:42:45 +0100 Subject: Like __getattr__ but with args and kwargs as well In-Reply-To: References: Message-ID: <4C000EA5.2000200@mrabarnett.plus.com> Giampaolo Rodol? wrote: > I know, the title doesn't say much, but I had no better ideas. =) > I have a class within a serie of redundant methods, which looks like this: > > class MixedAuthorizer: > > def __init__(self, *args): > # expected a list of class instances > self.authorizers = args > > def get_home(self, user): > for auth in self.authorizers: > if not auth.has_user(user): > continue > return auth.get_home(user) > return "" > > def get_password(self, user): > for auth in self.authorizers: > if not auth.has_user(user): > continue > return auth.get_password(user) > return "" > > # follows a long list of get_* methods as above > ... > > > Considering that I always do the same thing (iterate over a list of > objects -> call obj.has_user() -> call obj.get_*()) I would like to > know if there's a more compact way to do that. > What I basically need is something like __getattr__ but which provides > the arguments and eventually the keyword arguments a method has been > called with, other than just its name. > Actually I'm not even sure whether Python can reach such a level of > dynamism but I wanted to give it a try anyway. > Is there a way to do such a thing? > Here's a way (mis)using a decorator (written in Python 3): def locate(func): def lookup(self, user): for auth in self.authorizers: if auth.has_user(user): return getattr(auth, func.__name__)() return "" return lookup class Authorizer: def __init__(self, user): self.user = user def has_user(self, user): return self.user == user def get_home(self): return "{}-HOME".format(self.user) def get_password(self): return "{}-PASSWORD".format(self.user) class MixedAuthorizer: def __init__(self, *authorizers): self.authorizers = authorizers # The following methods are used only as placeholders. @locate def get_home(self): pass @locate def get_password(self): pass a1 = Authorizer("USER1") a2 = Authorizer("USER2") m = MixedAuthorizer(a1, a2) print(m.get_home("USER1")) print(m.get_password("USER2")) From kaklis at gmail.com Fri May 28 14:58:15 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 28 May 2010 11:58:15 -0700 (PDT) Subject: Omit the headers from XML message References: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Message-ID: On May 28, 7:48?pm, Peter Otten <__pete... at web.de> wrote: > Jon Clements wrote: > > On 28 May, 16:24, "kak... at gmail.com" wrote: > >> Hi i have the following xml message i want to omit the headers, any > >> hints? > > Assuming the header is separated by a blank line, something like: > > > list(islice(dropwhile(bool, s.split('\n')), 1, None)) > > Making the same assumptions, but giving a single string instead of a list of > lines: > > s.partition("\n\n")[-1] > > Peter Thank you all for your responses! Antonis From dickinsm at gmail.com Fri May 28 16:44:43 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 28 May 2010 13:44:43 -0700 (PDT) Subject: A Friday Python Programming Pearl: random sampling Message-ID: For a lazy Friday evening, here's a Python algorithm that seemed so cute that I just had to share it with everyone. I'm sure it's well known to many here, but it was new to me. Skip directly to the 'sample2' function to see the algorithm and avoid the commentary... Suppose that you want to select a number of elements, k, say, from a population, without replacement. E.g., selecting 3 elements from range(30) might give you: [13, 3, 27] Order matters, so the above is considered distinct from [3, 13, 27]. And you want to be sure that each possible selection has equal probability of occurring (to within the limits of the underlying PRNG). One solution is to select elements from the population one-by-one, keep track of the indices of already-selected elements in a set, and if you end up selecting something that's already in your set, simply try again. Something like this (code stolen and adapted from Random.sample in Python's standard library 'random' module): from random import randrange def sample1(population, k): n = len(population) result = [None] * k selected = set() for i in range(k): j = randrange(n) # retry until we get something that's not already selected while j in selected: j = randrange(n) selected.add(j) result[i] = population[j] return result N.B. The above is Python 3 code; for Python 2, replace range with xrange. All that's required of 'population' here is that it implements __len__ and __getitem__. The method works well for k significantly smaller than n, but as k approaches n the number of reselections required increases. So for larger k, Random.sample uses a different method: roughly, make a copy of 'population', do a partial in-place shuffle of that copy that randomizes the first k elements, and return those. This second method isn't so great when k is small and n is huge, since it ends up being O(n) from the list copy, but it works out that the two methods complement each other nicely. Looking at the above code, I was idly wondering whether there was a way to alter 'sample1' to avoid the need for resampling, thus giving a single algorithm that works reasonably efficiently regardless of the population size and requested sample size. And it turns out that there is. The code below is similar to 'sample1' above, except that instead of using a set to keep track of indices of already-selected members of the population, it uses a dict; for an index i (corresponding to a member of the population), d[i] gives the position that population[i] will occupy in the resulting sample. from random import randrange def sample2(population, k): n = len(population) d = {} for i in reversed(range(k)): j = randrange(i, n) if j in d: d[i] = d[j] d[j] = i result = [None] * k for j, i in d.items(): result[i] = population[j] return result Note that no resampling is required, and that there's no copying of the population list. The really clever bit is the 'if j in d: ...' block. If you stare at the algorithm for long enough (and it does take some staring), you can convince yourself that after the first 'for' loop, d can be any of the n*(n-1)*...*(n-k+1) mappings-with-no-repeated-elements from some set of k elements of range(n) to range(k), and that each one of these mappings is equally likely to occur. In a sense, this d is the inverse of the desired sample, which would be a map with no repetitions from range(k) to range(n). So inverting d, and replacing d's keys by the corresponding population elements, gives the random sample. N.B. I don't claim any originality for the algorithm; only for the implementation: the algorithm is based on an algorithm attributed to Robert Floyd, and appearing in Jon Bentley's 'Programming Pearls' book (though that algorithm produces a set, so doesn't worry about the ordering of the sample). But I was struck by its beauty and simplicity, and thought it deserved to be better known. Happy Friday! -- Mark From awilliam at whitemice.org Fri May 28 16:44:53 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 28 May 2010 16:44:53 -0400 Subject: multiprocessing and accessing server's stdout In-Reply-To: References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: <1275079493.7612.6.camel@linux-yu4c.site> On Fri, 2010-05-28 at 15:41 +0100, Martin P. Hellwig wrote: > On 05/28/10 13:17, Adam Tauno Williams wrote: > > > You should be able to point it any any file-like object. But, again, > > why? > > If you have the data in the process why send it to stdout and redirect > > it. Why not just send the data to the client directly? > Well you might want to multiplex it to more then one client, not saying > that this is the case here, just something I imagine possible. That still doesn't make sense. Why 'multiplex stdout'? Why not just multiplex the data into proper IPC channels in the first place? -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From jessemcdonnell at verizon.net Fri May 28 17:02:04 2010 From: jessemcdonnell at verizon.net (Jesse McDonnell) Date: Fri, 28 May 2010 17:02:04 -0400 Subject: TypeError: _new_() takes exactly 3 arguments (2 given) - what does it mean? In-Reply-To: References: <2061601704.535865.1274727159418.JavaMail.root@vms244.mailsrvcs.net> Message-ID: <20100528170204.4da8292e.jessemcdonnell@verizon.net> On Wed, 26 May 2010 14:30:21 -0400 Terry Reedy wrote: > On 5/24/2010 2:52 PM, Jesse McDonnell wrote: > > I'm attempting to install Powerline http://code.google.com/p/powerline/, > > a computer reservation software based on CherryPy/Python using a MYSql > > database, at my local library and I've run up against an error that I > > > > Honestly, unless you find a Python+Powerline expert who will help, I > suggest that you delete Powerline and look for something else. The most > recent release is an alpha release over 2 years old. Except for the Feb > 2010 wiki updates, the project appears to be dead. Even if someone > helped you past this, there is no evidence that the fix would applied > back to the codebase. And what about the next bug or problem? > Terry Jan Reedy > and On Wed, 26 May 2010 12:04:53 -0700 (PDT) Carl Banks wrote: > [Again, can't see the original, sorry] > > On May 26, 11:30?am, Terry Reedy wrote: > > On 5/24/2010 2:52 PM, Jesse McDonnell wrote: > > The most common reason for this message is trying to subclass a > module. (Very easy mistake when a module has the same name as a > class, which is part of why I don't like the practice, though the > modern PEP 8 reduces the issue.) > > IOW, someone did something like this: > > import foo > class bar(foo): pass > > when they should have done this: > > from foo import foo > class bar(foo): pass > Terry and Carl, Thanks for your replies. I got a response from the guy who coded Powerline through the google group for the app and upgrading dbwrap resolved this particular error. He also helped me work through some python-genshi issues and I now have a working web interface. Thanks again for your help. Jesse From martin.hellwig at dcuktec.org Fri May 28 19:47:18 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 29 May 2010 00:47:18 +0100 Subject: multiprocessing and accessing server's stdout In-Reply-To: References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: On 05/28/10 21:44, Adam Tauno Williams wrote: > On Fri, 2010-05-28 at 15:41 +0100, Martin P. Hellwig wrote: >> On 05/28/10 13:17, Adam Tauno Williams wrote: >> >>> You should be able to point it any any file-like object. But, again, >>> why? >>> If you have the data in the process why send it to stdout and redirect >>> it. Why not just send the data to the client directly? >> Well you might want to multiplex it to more then one client, not saying >> that this is the case here, just something I imagine possible. > > That still doesn't make sense. Why 'multiplex stdout'? Why not just > multiplex the data into proper IPC channels in the first place? I am going on a stretch here, I mostly agree with you, just trying to illustrate that there could be corner cases where this is sensible. The current situation could be that there is a client/server program (binary only perhaps) which is not multi-user safe. Python can be used as a wrapper around the server to make it multi-client, by emulating the exact behavior towards the client, the client program does not have to be changed. -- mph From lie.1296 at gmail.com Fri May 28 20:23:41 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 29 May 2010 10:23:41 +1000 Subject: function that counts... In-Reply-To: <498a76fd-4e4b-4d09-86c3-16800a4e3d87@s4g2000prh.googlegroups.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> <498a76fd-4e4b-4d09-86c3-16800a4e3d87@s4g2000prh.googlegroups.com> Message-ID: <4c005ef6$1@dnews.tpgi.com.au> On 05/26/10 11:04, Bryan wrote: > Jean-Michel Pichavant wrote: >> I still don't see "how many positive integers less than n have digits >> that sum up to m" makes it a "partition" though if that what prttn >> means. Surely because I miss the context. > > A partition of a positive integer m is an unordered collection of > positive integers that sum to m. [1, 1, 2, 5] is a partition of 9. The > problem at issue here is not that of counting partitions. > > My algorithm for our prttn separated out the 'ndsums' sub-problem: > Count d-digit ints with digits summing to m. I found a generalization > of that problem stated in the /CRC Handbook of Discrete and > Combinatorial Mathematics/ (2000 edition, section 2.1) among "counting > problems" as: > > Solutions to x_1 + ... x_n = k > 0 <= x_i <= a_i for one or more i > > Alas, the handbook does not provide a formula or algorithm. It refers > to the inclusion/exclusion principle, which I did not see how to turn > into an efficient algorithm. superpollo posted this question in comp.programming (http://groups.google.com/group/comp.programming/browse_thread/thread/e3b10346db8ebd0a/579ca67f8b9b5a8c; http://groups.google.com/group/comp.programming/msg/f7323d6e6942e883; http://groups.google.com/group/comp.programming/browse_thread/thread/e3b10346db8ebd0a/dc4cd1e2feb89500 ) I went through the mathematical foundation of using partition/distribution and inclusion-exclusion, and have written some code that solves a subset of the problem, feel free if you or superpollo are interested in continuing my answer (I won't be able to continue it until next week, have been a little bit busy here) copying the code here for convenience: # memoization would be very useful here def fact(n): """ factorial function (i.e. n! = n * (n-1) * ... * 2 * 1) """ return n * fact(n - 1) if n != 0 else 1 def C(n, r): """ regular Combination (nCr) """ return fact(n) / (fact(n - r) * fact(r)) def D(M, N): """ Distribution aka Partitioning """ return C(M + N - 1, M) def partition10(M, i): """ Count how many integer < N sums to M where N = 10**int(i) """ s = 0 sign = 1 for j in range(i + 1): s += sign * D(M, i) * C(i, j) # flip the sign for inclusion-exclusion sign *= -1 # if M = 32, then 32, 22, 12, 2, -8 M -= 10 return s # still need to write: # def partitionN10(...): -- applies a "restriction"/"boundary" to # the most significant digit # then make it recurse. # assuming factorials calculation is constant time (hint: memoization) # the resulting code should work in O(n**2) # an improvement over the naive method which is O(10**n) # where n is the number of digits in N # DISCLAIMER: the big-O is a quick guess, not really calculated From john at castleamber.com Fri May 28 22:05:42 2010 From: john at castleamber.com (John Bokma) Date: Fri, 28 May 2010 21:05:42 -0500 Subject: Free chapter about Python and databases (MySQL and SQLite) References: <87vda8ofvz.fsf@castleamber.com> Message-ID: <87hblrv4w9.fsf@castleamber.com> Sebastian Bassi writes: > On Fri, May 28, 2010 at 12:37 AM, John Bokma wrote: >> I feel more than uncomfortable with example code that uses: user="root" > > What's wrong with this? It is just an example of connection string. > The reader will use his/her user/pass/dbname according to their own > settings. A bit down you're contradicting yourself: your audience is not familiar with databases, yet you assume that they will use their own settings? >> (e.g. p291). I never get why people write a short (IMO) /bad/ intro to >> databases while there are books out there that do a way better > > The intended audience of this book are biologist who may be not > familiarized with relational databases. Most of my colleagues (at > least from the bio camp) don't even know that behind most dynamic web > pages there are databases and I think that most of them will find the > intro section useful. You can always skip what you know and go to the > point you want. My point is that the intro I (speed) read is weak at best. You say you're doing your audience a favor, but I don't agree. > I am not sure that price in this kind of book are tied to the number > of pages. There must be some relation, but this is not the main factor > affecting price. Even if it's just a few bucks, it's still money saved [0]. On top of that I think it's way better to point your audience to good books on the topic and skip the intro instead of doing a (half hearted IMO) attempt at it yourself. >> I would love to see more technical books that start at page 1 with the >> topic, not with an introduction to the language (170+ pages) and some > ... > > I see where you go, it seems you are not the target audience for this > book. Anyway I appreciate your feedback. You're welcome. And to be honest, if the book didn't have those filler chapters (which they are IMO) I would certainly have been interested in it. Note that I am not trying to convince you to rewrite your book, but my bookcase could have 20% more room if technical writers stopped to write books that tried to introduce their audience to everything but the kitchen sink [1]. My favourite books are the ones that /don't/ do the everything but the kitchensink gig, but direct me to other high quality books. [0] I've been a technical editor for a book, and got paid by the page. [1] I mean the books that seem to handle a single specific topic. If I buy "Ubuntu up and running" I expect everything, including the kitchensink. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From drobinow at gmail.com Fri May 28 23:41:31 2010 From: drobinow at gmail.com (Robinow) Date: Fri, 28 May 2010 23:41:31 -0400 Subject: Free chapter about Python and databases (MySQL and SQLite) In-Reply-To: <87hblrv4w9.fsf@castleamber.com> References: <87vda8ofvz.fsf@castleamber.com> <87hblrv4w9.fsf@castleamber.com> Message-ID: <34894370-9E3B-4C21-80DE-A6FF26A7B669@gmail.com> wrote: > Sebastian Bassi writes: > >> On Fri, May 28, 2010 at 12:37 AM, John Bokma >> wrote: > > Even if it's just a few bucks, it's still money saved [0]. On top of > that I think it's way better to point your audience to good books on > the > topic and skip the intro instead of doing a (half hearted IMO) attempt > at it yourself. >> > OK, John. What book do you recommend? From kse.listed.co1 at gmail.com Sat May 29 01:42:03 2010 From: kse.listed.co1 at gmail.com (Naeem) Date: Fri, 28 May 2010 22:42:03 -0700 (PDT) Subject: "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ Message-ID: <4d75ce9d-f29d-4bf9-a515-133bf6783098@l6g2000vbo.googlegroups.com> "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ From contact at xavierho.com Sat May 29 05:33:56 2010 From: contact at xavierho.com (Xavier Ho) Date: Sat, 29 May 2010 19:33:56 +1000 Subject: A Friday Python Programming Pearl: random sampling In-Reply-To: References: Message-ID: On 29 May 2010 06:44, Mark Dickinson wrote: > But I was struck by its beauty and > simplicity, and thought it deserved to be better known. > Wow, that took me at least 2 minutes to see its beauty as well. Nice find, Mark. Thanks for sharing. (Also, it's nice to see another SOer on Python-List as well!) Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From googler.1.webmaster at spamgourmet.com Sat May 29 08:34:56 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Sat, 29 May 2010 05:34:56 -0700 (PDT) Subject: Py_single_input and the side-effects... Message-ID: Hi at all, I have a small problem with Py_single_input, that I dont really know what it actually does. I created my own interactive interpreter loop and when I create objects like p = TestObject() this instance is just deleted on Py_Finalize() even I delete the entire console scope long time before. It seems that Py_single_input stores the references somewhere else. Could anyone explain me a little bit what is actually going on here? Thanks a lot! Cheers, moerchendiser2k3 From pradeepbpin at gmail.com Sat May 29 09:09:35 2010 From: pradeepbpin at gmail.com (Pradeep B) Date: Sat, 29 May 2010 18:39:35 +0530 Subject: Python and Tkinter Programming by John Grayson In-Reply-To: <4B58FCDF.4000402@stoneleaf.us> References: <0738732e-d8df-469d-be4a-3699f4fd5f64@j14g2000yqm.googlegroups.com> <801d251d-ae12-4ce6-95a1-58f594cd2f81@p8g2000yqb.googlegroups.com> <4B4F96D6.2070905@codebykevin.com> <326dc723-3909-4293-9bf6-48a367b9251c@e16g2000yqc.googlegroups.com> <4B58FCDF.4000402@stoneleaf.us> Message-ID: On Fri, Jan 22, 2010 at 6:48 AM, Ethan Furman wrote: > Peter wrote: >> >> On Jan 15, 9:12 am, Kevin Walzer wrote: >>>> >>>> On Jan 15, 6:24 am, Mark Roseman ?wrote: >>>>> >>>>> ?Peter ?wrote: >>>>>> >>>>>> Besides, the book is mainly about using Python with Tkinter - and >>>>>> Tkinter hasn't changed that much since 2000, so I believe it is just >>>>>> as relevant today as it was back then. > >>>>> I'd say that Tkinter has substantially changed - with the introduction >>>>> of the 'ttk' themed widgets. ?I cover these in my tutorial >>>>> athttp://www.tkdocs.com > >>> Another book I've found very helpful for learning Tkinter is Programming >>> Python by Mark Lutz--a lot of coverage there of GUI development. >>> >> >> Another possible consideration when choosing a GUI to learn Python - >> will you want to print from within your GUI application? > > Excellent point. > > Many thanks to all who responded, especially for the reminder of the gui > sections in Programming Python (forgot I had that book!). ?I'll start by > going over that again, and we'll see how confident I feel afterwards. ?;) > > ~Ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > Is printing from GUI still a 'not-happening' thing with Tkinter ? I have just started learning it. -- |_|0|_| |_|_|0| |0|0|0| http://picasaweb.google.com/pradeepbpin From pradeepbpin at gmail.com Sat May 29 09:11:24 2010 From: pradeepbpin at gmail.com (Pradeep B) Date: Sat, 29 May 2010 18:41:24 +0530 Subject: Tkinter library reference Message-ID: Do we have a standard reference library for Tkinter available? -- Pradeep From astley.lejasper at gmail.com Sat May 29 09:24:49 2010 From: astley.lejasper at gmail.com (Astley Le Jasper) Date: Sat, 29 May 2010 06:24:49 -0700 (PDT) Subject: Creating a single list Message-ID: This is probably a really silly question but, given the example code at the bottom, how would I get a single list? What I currently get is: ('id', 20, 'integer') ('companyname', 50, 'text') [('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, 'text'), ('puma', 30, 'text')] ('contact', 50, 'text') ('email', 50, 'text') what I would like is: ('id', 20, 'integer') ('companyname', 50, 'text') ('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, 'text'), ('puma', 30, 'text'), ('contact', 50, 'text') ('email', 50, 'text') SAMPLE CODE>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> def getproducts(): temp_list=[] product_list=['focus','fiesta','mondeo','puma'] #usually this would come from a db for p in product_list: temp_list.append((p,30,'text')) return temp_list def createlist(): column_title_list = ( ("id",20,"integer"), ("companyname",50,"text"), getproducts(), ("contact",50,"text"), ("email",50,"text"), ) return column_title_list for item in createlist(): print item >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> From contact at xavierho.com Sat May 29 09:40:48 2010 From: contact at xavierho.com (Xavier Ho) Date: Sat, 29 May 2010 23:40:48 +1000 Subject: Creating a single list In-Reply-To: References: Message-ID: On 29 May 2010 23:24, Astley Le Jasper wrote: > def createlist(): > column_title_list = ( > ("id",20,"integer"), > ("companyname",50,"text"), > getproducts(), > ("contact",50,"text"), > ("email",50,"text"), > ) > return column_title_list > Note that you're creating a Tuple, not a List. They're not the same thing. Try this: column_title_list = [ ("id",20,"integer"), ("companyname",50,"text"), ("contact",50,"text"), ("email",50,"text"), ] # Insert into the list with slicing syntax. column_title_list[2:3} = getproduct() This will not work with tuples, as they are immutable. Lists are. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Sat May 29 09:41:29 2010 From: contact at xavierho.com (Xavier Ho) Date: Sat, 29 May 2010 23:41:29 +1000 Subject: Creating a single list In-Reply-To: References: Message-ID: > # Insert into the list with slicing syntax. > column_title_list[2:3} = getproduct() > Sorry, that should have been [2:3]. Typing a bit too fast. -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From kw at codebykevin.com Sat May 29 10:03:28 2010 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 29 May 2010 10:03:28 -0400 Subject: Python and Tkinter Programming by John Grayson In-Reply-To: References: <0738732e-d8df-469d-be4a-3699f4fd5f64@j14g2000yqm.googlegroups.com> <801d251d-ae12-4ce6-95a1-58f594cd2f81@p8g2000yqb.googlegroups.com> <4B4F96D6.2070905@codebykevin.com> <326dc723-3909-4293-9bf6-48a367b9251c@e16g2000yqc.googlegroups.com> <4B58FCDF.4000402@stoneleaf.us> Message-ID: <81dfc$4c011eaa$4275d90a$28590@FUSE.NET> > Is printing from GUI still a 'not-happening' thing with Tkinter ? I > have just started learning it. Tkinter doesn't wrap native printing API's. There are a few extensions that do it, but they are platform specific and not complete. The usual ways of printing are like this: 1. If you're outputting data from the text widget, write that to a temporary text file and print via lpr. 2. If you're outputting data from the canvas, write that to a temporary postscript file and print via lpr. This is on Unix/MacOS. Not sure what the equivalent API on Windows is. --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From utente at esempio.net Sat May 29 10:10:41 2010 From: utente at esempio.net (superpollo) Date: Sat, 29 May 2010 16:10:41 +0200 Subject: Creating a single list In-Reply-To: References: Message-ID: <4c012062$0$18987$4fafbaef@reader5.news.tin.it> Astley Le Jasper ha scritto: > This is probably a really silly question but, given the example code > at the bottom, how would I get a single list? > > What I currently get is: > > ('id', 20, 'integer') > ('companyname', 50, 'text') > [('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, > 'text'), ('puma', 30, 'text')] > ('contact', 50, 'text') > ('email', 50, 'text') > > what I would like is: > > ('id', 20, 'integer') > ('companyname', 50, 'text') > ('focus', 30, 'text'), > ('fiesta', 30, 'text'), > ('mondeo', 30, 'text'), > ('puma', 30, 'text'), > ('contact', 50, 'text') > ('email', 50, 'text') > > SAMPLE CODE>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > def getproducts(): > temp_list=[] > product_list=['focus','fiesta','mondeo','puma'] #usually this > would come from a db > for p in product_list: > temp_list.append((p,30,'text')) > return temp_list > > def createlist(): > column_title_list = ( > ("id",20,"integer"), > ("companyname",50,"text"), > getproducts(), > ("contact",50,"text"), > ("email",50,"text"), > ) > return column_title_list > > for item in createlist(): > print item >>> def createlist(): ... column_title_list = [ ... ("id",20,"integer"), ... ("companyname",50,"text")] ... column_title_list += getproducts() ... column_title_list += [ ... ("contact",50,"text"), ... ("email",50,"text")] ... return column_title_list ... >>> for item in createlist(): ... print item ... ('id', 20, 'integer') ('companyname', 50, 'text') ('focus', 30, 'text') ('fiesta', 30, 'text') ('mondeo', 30, 'text') ('puma', 30, 'text') ('contact', 50, 'text') ('email', 50, 'text') >>> bye From bryanjugglercryptographer at yahoo.com Sat May 29 10:43:43 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sat, 29 May 2010 07:43:43 -0700 (PDT) Subject: A Friday Python Programming Pearl: random sampling References: Message-ID: Mark Dickinson wrote: > N.B. ?I don't claim any originality for the algorithm; only for the > implementation: the algorithm is based on an algorithm attributed to > Robert Floyd, and appearing in Jon Bentley's 'Programming Pearls' book Actually it is the sequel, /More Programming Pearls/. > (though that algorithm produces a set, so doesn't worry about the > ordering of the sample). Bentley presents a version of the Floyd algorithm that provides random order, but it requires a set data type with some idea of order, as in "insert j in s after t". As Mark Dickinson's version uses a normal dict(), which Bentley had already introduced under the name "associate array", I'd say Mark's version is an improvement. -- --Bryan From andrew at acooke.org Sat May 29 11:04:51 2010 From: andrew at acooke.org (andrew cooke) Date: Sat, 29 May 2010 08:04:51 -0700 (PDT) Subject: Help with Regexp, \b Message-ID: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> This is a bit embarassing, but I seem to be misunderstanding how \b works in regexps. Please can someone explain why the following fails: from re import compile p = compile(r'\bword\b') m = p.match(' word ') assert m My understanding is that \b matches a space at the start or end of a word, and that "word" is a word - http://docs.python.org/library/re.html What am I missing here? I suspect I am doing something very stupid. Thanks, Andrew From anand.shashwat at gmail.com Sat May 29 11:14:33 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sat, 29 May 2010 20:44:33 +0530 Subject: Help with Regexp, \b In-Reply-To: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> References: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> Message-ID: \b is NOT spaces >>> p = re.compile(r'\sword\s') >>> m = p.match(' word ') >>> assert m >>> m.group(0) ' word ' >>> On Sat, May 29, 2010 at 8:34 PM, andrew cooke wrote: > > This is a bit embarassing, but I seem to be misunderstanding how \b > works in regexps. > > Please can someone explain why the following fails: > > from re import compile > > p = compile(r'\bword\b') > m = p.match(' word ') > assert m > > My understanding is that \b matches a space at the start or end of a > word, and that "word" is a word - http://docs.python.org/library/re.html > > What am I missing here? I suspect I am doing something very stupid. > > Thanks, > Andrew > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Sat May 29 11:24:48 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 May 2010 15:24:48 GMT Subject: Help with Regexp, \b References: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> Message-ID: andrew cooke wrote: > Please can someone explain why the following fails: > > from re import compile > > p = compile(r'\bword\b') > m = p.match(' word ') > assert m > > My understanding is that \b matches a space at the start or end of a > word, and that "word" is a word - http://docs.python.org/library/re.html > > What am I missing here? I suspect I am doing something very stupid. > You misunderstand what \b does: it doesn't match a space, it matches a 0 length string on a boundary between a non-word and a word. Try: p.match(' word ', 1).group(0) and you'll see that you are only match the word, not the surrounding puctuation. From anand.shashwat at gmail.com Sat May 29 11:28:28 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sat, 29 May 2010 20:58:28 +0530 Subject: Help with Regexp, \b In-Reply-To: References: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> Message-ID: Also what you are probably looking for is this I guess, >>> p = re.compile(r'\bword\b') >>> m = p.match('word word') >>> assert m >>> m.group(0) 'word' On Sat, May 29, 2010 at 8:44 PM, Shashwat Anand wrote: > \b is NOT spaces > > >>> p = re.compile(r'\sword\s') > >>> m = p.match(' word ') > >>> assert m > >>> m.group(0) > ' word ' > >>> > > > On Sat, May 29, 2010 at 8:34 PM, andrew cooke wrote: > >> >> This is a bit embarassing, but I seem to be misunderstanding how \b >> works in regexps. >> >> Please can someone explain why the following fails: >> >> from re import compile >> >> p = compile(r'\bword\b') >> m = p.match(' word ') >> assert m >> >> My understanding is that \b matches a space at the start or end of a >> word, and that "word" is a word - http://docs.python.org/library/re.html >> >> What am I missing here? I suspect I am doing something very stupid. >> >> Thanks, >> Andrew >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew at acooke.org Sat May 29 11:30:18 2010 From: andrew at acooke.org (andrew cooke) Date: Sat, 29 May 2010 08:30:18 -0700 (PDT) Subject: Help with Regexp, \b References: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> Message-ID: <4b812698-4779-4502-8cdc-bf5c47dd5a0c@o39g2000vbd.googlegroups.com> On May 29, 11:24?am, Duncan Booth wrote: > andrew cooke wrote: > > Please can someone explain why the following fails: > > > ? ? ? ? from re import compile > > > ? ? ? ? p = compile(r'\bword\b') > > ? ? ? ? m = p.match(' word ') > > ? ? ? ? assert m [...] > You misunderstand what \b does: it doesn't match a space, it matches a 0 > length string on a boundary between a non-word and a word. [...] That's what I thought it did... Then I read the docs and confused "empty string" with "space"(!) and convinced myself otherwise. I think I am going senile. Thanks very much! Andrew From godson.g at gmail.com Sat May 29 11:36:31 2010 From: godson.g at gmail.com (Godson Gera) Date: Sat, 29 May 2010 21:06:31 +0530 Subject: Tkinter library reference In-Reply-To: References: Message-ID: Do you mean Tkinter API reference documentation ? If so, this is what I've used years back http://www.nmt.edu/tcc/help/pubs/tkinter.pdf you can also get some info from http://effbot.org/tkinterbook On Sat, May 29, 2010 at 6:41 PM, Pradeep B wrote: > Do we have a standard reference library for Tkinter available? > > -- > Pradeep > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thanks & Regards, Godson Gera IVR India IVR Vendor India -------------- next part -------------- An HTML attachment was scrubbed... URL: From dickinsm at gmail.com Sat May 29 13:06:19 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 29 May 2010 10:06:19 -0700 (PDT) Subject: A Friday Python Programming Pearl: random sampling References: Message-ID: On May 29, 3:43?pm, Bryan wrote: > Mark Dickinson wrote: > > N.B. ?I don't claim any originality for the algorithm; only for the > > implementation: the algorithm is based on an algorithm attributed to > > Robert Floyd, and appearing in Jon Bentley's 'Programming Pearls' book > > Actually it is the sequel, /More Programming Pearls/. Thanks for the correction. I confess that I've yet to read either book; I'll have to try to track them down. > > (though that algorithm produces a set, so doesn't worry about the > > ordering of the sample). > > Bentley presents a version of the Floyd algorithm that provides random > order, but it requires a set data type with some idea of order, as in > "insert j in s after t". Ah, nice. The dict values, of course, exactly provide the necessary idea of order, so I guess this amounts to pretty much the same thing. -- Mark From nagle at animats.com Sat May 29 14:43:29 2010 From: nagle at animats.com (John Nagle) Date: Sat, 29 May 2010 11:43:29 -0700 Subject: Python vs. Fedora and CentOS Message-ID: <4c015aa9$0$1617$742ec2ed@news.sonic.net> The major Red Hat based Linux distros are still shipping with Python 2.4. As a result, almost all hosting providers are running obsolete versions of Python. The big problem seems to be that "cPanel" and "yum" still use older versions of Python, and those programs are more important to distro builders than Python itself. Is anybody trying to do something about this? John Nagle From breamoreboy at yahoo.co.uk Sat May 29 14:46:28 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 29 May 2010 19:46:28 +0100 Subject: xrange issue 7721 Message-ID: Sorry if this is the wrong ng/ml, but thought I'd better flag this up somewhere. I've had an OverflowError using xrange with Python 2.6.5 on Windows. Googling got me to the subject line. msg97928 gives a code snippet to overcome the limitations of xrange, allowing for negative steps, however it doesn't raise a ValueError for a zero step. msg99624 gives a docs change that has been implemented for V2.6, but this doesn't refer to the msg97928 code snippet, rather it refers to a one liner that only works for positive steps. The docs for V2.7 haven't been changed at all. Assuming that I am correct, can I create myself a login on the bugs tracker and re-open the issue to get this sorted? Kindest regards. Mark Lawrence. From no.email at nospam.invalid Sat May 29 14:58:31 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 29 May 2010 11:58:31 -0700 Subject: Python vs. Fedora and CentOS References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> Message-ID: <7xaaripmaw.fsf@ruckus.brouhaha.com> John Nagle writes: > The major Red Hat based Linux distros are still shipping with Python 2.4. Fedora 12 ships with Python 2.6, I think. From wesbrooks at gmail.com Sat May 29 15:03:54 2010 From: wesbrooks at gmail.com (Wesley Brooks) Date: Sat, 29 May 2010 20:03:54 +0100 Subject: Python vs. Fedora and CentOS In-Reply-To: <7xaaripmaw.fsf@ruckus.brouhaha.com> References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <7xaaripmaw.fsf@ruckus.brouhaha.com> Message-ID: I've got Fedora 10 here with 2.5, and 11 at the office with 2.6. On 29 May 2010 19:58, Paul Rubin wrote: > John Nagle writes: >> ? The major Red Hat based Linux distros are still shipping with Python 2.4. > > Fedora 12 ships with Python 2.6, I think. > -- > http://mail.python.org/mailman/listinfo/python-list > From philip at semanchuk.com Sat May 29 15:09:57 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Sat, 29 May 2010 15:09:57 -0400 Subject: Python vs. Fedora and CentOS In-Reply-To: <7xaaripmaw.fsf@ruckus.brouhaha.com> References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <7xaaripmaw.fsf@ruckus.brouhaha.com> Message-ID: On May 29, 2010, at 2:58 PM, Paul Rubin wrote: > John Nagle writes: >> The major Red Hat based Linux distros are still shipping with >> Python 2.4. > > Fedora 12 ships with Python 2.6, I think. Fedora has been shipping with Python 2.6 since F11 release in June of 2009, and Python > 2.4 since F7 released in May 2007. http://distrowatch.com/table.php?distribution=fedora I think the OP is referring to RHEL (Enterprise Linux). Cheers Philip From mfedyk at mikefedyk.com Sat May 29 15:12:10 2010 From: mfedyk at mikefedyk.com (Mike Fedyk) Date: Sat, 29 May 2010 12:12:10 -0700 Subject: Python vs. Fedora and CentOS In-Reply-To: References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <7xaaripmaw.fsf@ruckus.brouhaha.com> Message-ID: On Sat, May 29, 2010 at 12:03 PM, Wesley Brooks wrote: > On 29 May 2010 19:58, Paul Rubin wrote: >> John Nagle writes: >>> ? The major Red Hat based Linux distros are still shipping with Python 2.4. >> >> Fedora 12 ships with Python 2.6, I think. > > I've got Fedora 10 here with 2.5, and 11 at the office with 2.6. > And Fedora 13 that has 2.6 and 3.1. And whatever slows down the upgrade treadmill is good IMO. People should not have to install the latest python just to use your app. From mmanns at gmx.net Sat May 29 15:12:41 2010 From: mmanns at gmx.net (Martin Manns) Date: Sat, 29 May 2010 21:12:41 +0200 Subject: xrange issue 7721 References: Message-ID: <20100529211241.56dc7bc4@Knock> On Sat, 29 May 2010 19:46:28 +0100 Mark Lawrence wrote: > I've had an OverflowError using xrange with Python 2.6.5 on Windows. > Googling got me to the subject line. > > msg97928 gives a code snippet to overcome the limitations of xrange, > allowing for negative steps, however it doesn't raise a ValueError > for a zero step. msg99624 gives a docs change that has been > implemented for V2.6, but this doesn't refer to the msg97928 code > snippet, rather it refers to a one liner that only works for positive > steps. The docs for V2.7 haven't been changed at all. Mark: Thank you for posting. 2.7 is not affected by issue 7721 because itertools.islice behavior is changed. Therefore, the original snippet should work in 2.7 (I have not tested this). I found the msg97928 code pretty obvious when seeing the snippet. If you disagree you may consider re-opening the issue. Martin From john at castleamber.com Sat May 29 15:12:42 2010 From: john at castleamber.com (John Bokma) Date: Sat, 29 May 2010 14:12:42 -0500 Subject: Free chapter about Python and databases (MySQL and SQLite) References: <87vda8ofvz.fsf@castleamber.com> <87hblrv4w9.fsf@castleamber.com> Message-ID: <878w7234k5.fsf@castleamber.com> Robinow writes: > > On May 28, 2010, at 10:05 PM, John Bokma wrote: > >> Sebastian Bassi writes: >> >>> On Fri, May 28, 2010 at 12:37 AM, John Bokma >>> wrote: >> >> Even if it's just a few bucks, it's still money saved [0]. On top of >> that I think it's way better to point your audience to good books on >> the >> topic and skip the intro instead of doing a (half hearted IMO) attempt >> at it yourself. >>> >> > OK, John. What book do you recommend? Since it's not clear on what topic in the book you want recommendations, I do them all. Note that I only can recommend books I have either in my possession or browsed through that are still on my wish list. I am not new to programming, so the books listed under Python are not books for beginners per se, except the Programming in Python 3, which is on top of that one of the best learning a programming language books I've read (so far). Python: Programming in Python 3 /2nd edition/ If you have some experience with programming: Dive into Python 2 (*) Dive into Python 3 (*) If you already have a book on learning Python and want a good extra reference: Python Essential Reference (4th edition) Subversion: Version Control with Subversion (O'Reilly) (*) Database: The Definitive Guide to SQLite MySQL (4th Edition) by Paul Dubois I also strongly suggest to read 1 or 2 books by Joe Celko before you even start to make your own databases (wish I would had), for example: Data and Databases: Concepts in Practice (**) SQL Programming Style SQL for smarties IMO Joe writes a bit "in your face" and calls a lot of people dumb, but don't let that get in the way ;-). I own also a copy of "MySQL cookbook" but haven't used it much. Still, I recommend to browse this book if you already have book(s) on MySQL and decide for yourself if it's something you want. In my experience most cookbook books by O'Reilly are good or very good. Can't recommend a good book on XML, I don't have one (***). I do have a book on XSLT (XSLT 2.0, O'Reilly) which is IMO very good, and does have, from the top of my head, a good XML introduction. Personally, I think it's good that if you work with XML that at least you have some idea of what XSLT is. Another XSLT book I have is XSLT 2.0 and XPath 2.0, but I haven't used that very often yet. (*) Also available as free download (**) Based on my experience with the other excellent books by Celko (***) A good book on XML would probably be 50 pages or less :-D. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From nagle at animats.com Sat May 29 16:22:49 2010 From: nagle at animats.com (John Nagle) Date: Sat, 29 May 2010 13:22:49 -0700 Subject: Python vs. Fedora and CentOS In-Reply-To: References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <7xaaripmaw.fsf@ruckus.brouhaha.com> Message-ID: <4C017799.6070804@animats.com> Philip Semanchuk wrote: > > On May 29, 2010, at 2:58 PM, Paul Rubin wrote: > >> John Nagle writes: >>> The major Red Hat based Linux distros are still shipping with Python >>> 2.4. >> >> Fedora 12 ships with Python 2.6, I think. > > Fedora has been shipping with Python 2.6 since F11 release in June of > 2009, and Python > 2.4 since F7 released in May 2007. > > http://distrowatch.com/table.php?distribution=fedora The "enterprise ready" versions are much further behind. http://distrowatch.com/table.php?distribution=centos CentOS 5.5 (May 2010) - Python: 2.4.3 http://distrowatch.com/table.php?distribution=redhat RHEL 5.5 (March 2010) - Python 2.4.3 RHEL 6-Beta - Python 2.6.2 However, if 2.6.2 is going into RHEL, the others will follow, and that's probably the production Python on servers for the next few years. John Nagle From bryanjugglercryptographer at yahoo.com Sat May 29 16:45:37 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sat, 29 May 2010 13:45:37 -0700 (PDT) Subject: dbf files and indexes References: <4BFECBF6.10006@stoneleaf.us> <20100527160445.30081fd3.darcy@druid.net> Message-ID: <036564ec-ebb1-422f-904b-2b58d2fcbd12@z13g2000prh.googlegroups.com> Christian Heimes wrote: [D'Arcy J.M. Cain had written:] > > SELECT * FROM NumberOfPets > > WHERE name IN (SELECT name FROM CatLovers) OR > > ? ?name IN (SELECT name FROM DogLovers) > > ORDER BY name; > > A good way is to use SQL with JOINs instead of horrible nested > selects. Do show us your join that makes D'Arcy's nested select horrible by comparison. > Although SQL is declarative, you shouldn't make the work of the query > optimizer so hard. You're not doing the query optimizer any favors. It can normalize the query to the same thing either way, so we might as well write it to be readable by people. I can read D'Arcy's at a glance. -- --Bryan Olson From johan.lans at apspektakel.com Sat May 29 16:51:39 2010 From: johan.lans at apspektakel.com (Johan Lans) Date: Sat, 29 May 2010 13:51:39 -0700 (PDT) Subject: tkinter function outout to text widget Message-ID: Hi I'm totally new on python and I'm doing an assignement where I'm doing a class that manipulates a text. The program is also supposed to have a GUI, for which I have used tkinter. So far I have entry widgets for file names and buttons, its all working like I want it to. What is missing is a way to output the changes to the text. I was thinking that a text-widget would be suitable. Is there a reasonably easy way to do this? I tried inserting a string to the textwidget and letting the class method change this string, but the inserted string isn't updated in the text-widget. Would be very happy for any hints. From texaspeso26 at gmail.com Sat May 29 17:42:27 2010 From: texaspeso26 at gmail.com (KAJAL AGARWAL) Date: Sat, 29 May 2010 14:42:27 -0700 (PDT) Subject: PLAY CAR RACE GAMES Message-ID: PLAY CAR RACE GAMES:- PLAY CAR RACE GAMES ON MY WEB SITE AND ENJOY UR MIND FRESH AND U CAN DOWN LOAD ALSO MY GAMES VISIT http://andhraonlinegames.blogspot,com From alfps at start.no Sat May 29 18:11:09 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 30 May 2010 00:11:09 +0200 Subject: tkinter function outout to text widget In-Reply-To: References: Message-ID: * Johan Lans, on 29.05.2010 22:51: > Hi > I'm totally new on python and I'm doing an assignement where I'm doing > a class that manipulates a text. The program is also supposed to have > a GUI, for which I have used tkinter. > So far I have entry widgets for file names and buttons, its all > working like I want it to. > What is missing is a way to output the changes to the text. I was > thinking that a text-widget would be suitable. Is there a reasonably > easy way to do this? > I tried inserting a string to the textwidget and letting the class > method change this string, but the inserted string isn't updated in > the text-widget. If that is a direct Python string, then you're not changing the string. Python strings are immutable. So, then you're at most changing which string a variable or attribute is referring to. However, if it is some Tkinter thing (I seem to recall that Tkinter offers some automatic update magic via something-something), then I don't know. > Would be very happy for any hints. Just update the widget whenever you change the text. Cheers & hth., - Alf -- blog at From darcy at druid.net Sat May 29 18:55:22 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 29 May 2010 18:55:22 -0400 Subject: Python vs. Fedora and CentOS In-Reply-To: <4c015aa9$0$1617$742ec2ed@news.sonic.net> References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> Message-ID: <20100529185522.0a4bb452.darcy@druid.net> On Sat, 29 May 2010 11:43:29 -0700 John Nagle wrote: > The major Red Hat based Linux distros are still shipping with Python 2.4. > > Is anybody trying to do something about this? Other than not running Linux on our hosting server? My ISP (http://www.Vex.Net) runs FreeBSD. Linux is for the desktop. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From darcy at druid.net Sat May 29 19:00:14 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 29 May 2010 19:00:14 -0400 Subject: dbf files and indexes In-Reply-To: <036564ec-ebb1-422f-904b-2b58d2fcbd12@z13g2000prh.googlegroups.com> References: <4BFECBF6.10006@stoneleaf.us> <20100527160445.30081fd3.darcy@druid.net> <036564ec-ebb1-422f-904b-2b58d2fcbd12@z13g2000prh.googlegroups.com> Message-ID: <20100529190014.969cdb57.darcy@druid.net> On Sat, 29 May 2010 13:45:37 -0700 (PDT) Bryan wrote: > You're not doing the query optimizer any favors. It can normalize the > query to the same thing either way, so we might as well write it to be > readable by people. I can read D'Arcy's at a glance. Assuming that you are running a decent *cough* PostgreSQL *cough* database engine. Readable is good. If you have a problem with your queries chances are that reorganizing your data or adding proper indexes will do more for you than contorted SQL will. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From breamoreboy at yahoo.co.uk Sat May 29 19:49:11 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 30 May 2010 00:49:11 +0100 Subject: xrange issue 7721 In-Reply-To: <20100529211241.56dc7bc4@Knock> References: <20100529211241.56dc7bc4@Knock> Message-ID: Hi Martin, thanks for the response, please see below. On 29/05/2010 20:12, Martin Manns wrote: > On Sat, 29 May 2010 19:46:28 +0100 > Mark Lawrence wrote: > >> I've had an OverflowError using xrange with Python 2.6.5 on Windows. >> Googling got me to the subject line. >> >> msg97928 gives a code snippet to overcome the limitations of xrange, >> allowing for negative steps, however it doesn't raise a ValueError >> for a zero step. msg99624 gives a docs change that has been >> implemented for V2.6, but this doesn't refer to the msg97928 code >> snippet, rather it refers to a one liner that only works for positive >> steps. The docs for V2.7 haven't been changed at all. > > Mark: > > Thank you for posting. > > 2.7 is not affected by issue 7721 because itertools.islice behavior is > changed. Therefore, the original snippet should work in 2.7 (I have not > tested this). From http://docs.python.org/dev/library/itertools.html "Unlike regular slicing, islice() does not support negative values for start, stop, or step." Rule 1 of programming never assume anything, particularly wrt testing. I assume that you are ok with this. :) Dreadful I know :) > > I found the msg97928 code pretty obvious when seeing the snippet. > If you disagree you may consider re-opening the issue. Try running this on Python 2.6.5 in file irange.py from itertools import takewhile, count def irange(start, stop, step): if step < 0: cond = lambda x: x > stop else: cond = lambda x: x < stop return takewhile(cond, (start + i * step for i in count())) if __name__=='__main__': for i in irange(0, 10, 0): print i My output from the command line c:\Users\Mark\python>irange 0 0 etc etc etc I trust that you get my point regarding the failure to raise a ValueError :) Or am I wearing my extremely stupid hat today? > > Martin > Kindest regards. Mark Lawrence. From gnujohn at gmail.com Sat May 29 20:23:23 2010 From: gnujohn at gmail.com (john) Date: Sat, 29 May 2010 17:23:23 -0700 (PDT) Subject: if, continuation and indentation References: Message-ID: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> On May 28, 10:37?am, "Colin J. Williams" wrote: > On 28-May-10 05:54 AM, Jonathan Hartley wrote: > > > On May 27, 1:57 pm, Jean-Michel Pichavant > > wrote: > >> HH wrote: > >>> I have a question about best practices when it comes to line wrapping/ > >>> continuation and indentation, specifically in the case of an if > >>> statement. > > >>> When I write an if statement with many conditions, I prefer to use a > >>> parenthesis around the whole block and get the implicit continuation, > >>> rather than ending each line with an escape character. ?Thus, using > >>> the example from the style guide (http://www.python.org/dev/peps/ > >>> pep-0008/) I would write: > > >>> ? ? ?if (width == 0 and > >>> ? ? ? ? ?height == 0 and > >>> ? ? ? ? ?color == 'red' and > >>> ? ? ? ? ?emphasis == 'strong' or > >>> ? ? ? ? ?highlight> ?100): > >>> ? ? ? ? ?raise ValueError("sorry, you lose") > > >>> The problem should be obvious -- it's not easy to see where the > >>> conditional ends and the statement begins since they have the same > >>> indentation. ?Part of the problem, I suppose, is that Emacs indents > >>> 'height' and the other lines in the conditional to 4 spaces (because > >>> of the parenthesis). ?How do people deal with this situation? > > >>> Thanks, > >>> Henrik > > >> One possible solution > > >> ? ? ?if ( > >> ? ? ? ? ? ? ?width == 0 and > >> ? ? ? ? ? ? ?height == 0 and > >> ? ? ? ? ? ? ?color == 'red' and > >> ? ? ? ? ? ? ?emphasis == 'strong' or > >> ? ? ? ? ? ? ?highlight> ?100 > >> ? ? ? ? ): > >> ? ? ? ? ?raise ValueError("sorry, you lose") > > >> JM > > > I've always liked this, or even: > > > ? ?if ( > > ? ? ? ?width == 0 and > > ? ? ? ?height == 0 and > > ? ? ? ?color == 'red' and > > ? ? ? ?emphasis == 'strong' or > > ? ? ? ?highlight> ?100 > > ? ?): > > ? ? ? ?raise ValueError("sorry, you lose") > > > but my co-workers have uniformly gone bananas whenever I try it. > > I liked: > > On 27-May-10 08:48 AM, Xavier Ho wrote: > ?> On 27 May 2010 22:22, HH > wrote: > > ?> > ?> ? ? ? ? if (width == 0 and > ?> ? ? ? ? ? ? height == 0 and > ?> ? ? ? ? ? ? color == 'red' and > ?> ? ? ? ? ? ? emphasis == 'strong' or > ?> ? ? ? ? ? ? highlight > 100): > ?> ? ? ? ? ? ? raise ValueError("sorry, you lose") > ?> > ?> > ?> I've gotta say - I've bumped into this problem before, and I'm sure many > ?> other have - this is a valid question. It just hasn't bothered me enough > ?> to ask... > ?> > ?> Correct me if I'm wrong, but I think the following is equivalent, and > ?> looks better. Although this won't fix all ugly cases in that problem.. > ?> > ?> if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or > ?> highlight > 100: > ?> ? ? ?raise ValueError("sorry, you lose") > ?> > ?> Cheers, > ?> Xav > > but nobody commented. > > Colin W. Colin: Sure, you can do it that way. IMO, though, the OP was wrong, and so is the PEP. Source code is meant to communicate. So it must transmit the correct information to the computer; it also must inform your coworkers. That means that you have a responsibility to care what they think, though you privately have your opinions. Another reason the PEP is faulty in this circumstance is that a misplaced backslash, or a missing one, is easily found and fixed. A misplaced parentheses, or just one of a pair, will transform your source code into something which may compile and then give faulty results: a disaster. So keep it simple, and make it legible. Yours, John From breamoreboy at yahoo.co.uk Sat May 29 20:59:39 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 30 May 2010 01:59:39 +0100 Subject: if, continuation and indentation In-Reply-To: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> Message-ID: On 30/05/2010 01:23, john wrote: > On May 28, 10:37 am, "Colin J. Williams" > wrote: >> On 28-May-10 05:54 AM, Jonathan Hartley wrote: >> >>> On May 27, 1:57 pm, Jean-Michel Pichavant >>> wrote: >>>> HH wrote: >>>>> I have a question about best practices when it comes to line wrapping/ >>>>> continuation and indentation, specifically in the case of an if >>>>> statement. >> >>>>> When I write an if statement with many conditions, I prefer to use a >>>>> parenthesis around the whole block and get the implicit continuation, >>>>> rather than ending each line with an escape character. Thus, using >>>>> the example from the style guide (http://www.python.org/dev/peps/ >>>>> pep-0008/) I would write: >> >>>>> if (width == 0 and >>>>> height == 0 and >>>>> color == 'red' and >>>>> emphasis == 'strong' or >>>>> highlight> 100): >>>>> raise ValueError("sorry, you lose") >> >>>>> The problem should be obvious -- it's not easy to see where the >>>>> conditional ends and the statement begins since they have the same >>>>> indentation. Part of the problem, I suppose, is that Emacs indents >>>>> 'height' and the other lines in the conditional to 4 spaces (because >>>>> of the parenthesis). How do people deal with this situation? >> >>>>> Thanks, >>>>> Henrik >> >>>> One possible solution >> >>>> if ( >>>> width == 0 and >>>> height == 0 and >>>> color == 'red' and >>>> emphasis == 'strong' or >>>> highlight> 100 >>>> ): >>>> raise ValueError("sorry, you lose") >> >>>> JM >> >>> I've always liked this, or even: >> >>> if ( >>> width == 0 and >>> height == 0 and >>> color == 'red' and >>> emphasis == 'strong' or >>> highlight> 100 >>> ): >>> raise ValueError("sorry, you lose") >> >>> but my co-workers have uniformly gone bananas whenever I try it. >> >> I liked: >> >> On 27-May-10 08:48 AM, Xavier Ho wrote: >> > On 27 May 2010 22:22, HH > wrote: >> >> > >> > if (width == 0 and >> > height == 0 and >> > color == 'red' and >> > emphasis == 'strong' or >> > highlight> 100): >> > raise ValueError("sorry, you lose") >> > >> > >> > I've gotta say - I've bumped into this problem before, and I'm sure many >> > other have - this is a valid question. It just hasn't bothered me enough >> > to ask... >> > >> > Correct me if I'm wrong, but I think the following is equivalent, and >> > looks better. Although this won't fix all ugly cases in that problem.. >> > >> > if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or >> > highlight> 100: >> > raise ValueError("sorry, you lose") >> > >> > Cheers, >> > Xav >> >> but nobody commented. >> >> Colin W. > > Colin: > Sure, you can do it that way. IMO, though, the OP was wrong, and so > is the PEP. Source code is meant to communicate. So it must transmit > the correct information to the computer; it also must inform your > coworkers. That means that you have a responsibility to care what > they think, though you privately have your opinions. Another reason > the PEP is faulty in this circumstance is that a misplaced backslash, > or a missing one, is easily found and fixed. A misplaced parentheses, > or just one of a pair, will transform your source code into something > which may compile and then give faulty results: a disaster. > So keep it simple, and make it legible. > Yours, > John IMHO complete garbage, if your editor doesn't show misplaced or missing parenthesis by highlighting you're using the wrong editor :) Regards. Mark Lawrence. From jyoung79 at kc.rr.com Sat May 29 21:13:22 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Sun, 30 May 2010 1:13:22 +0000 Subject: GUI programs Message-ID: <20100530011322.HBM34.9984.root@cdptpa-web23-z02> Just curious if anyone would be willing to share their thoughts about different Python GUI programming modules. I've been doing a bit of research and am trying to find something that: 1. Is portable. Would like to be able to send the module along with the main python file that would be able to run a GUI window. Would be sending this to multiple machines. Currently I'd like it to work on OS X machines, but it'd be nice if it worked on Windows machines, etc. Probably be using Python 2.5 or 2.6. 2. Can show an image (that is zoomable) as well as add GUI controls like text fields, popup menues, etc. as well as send information back to the program from the text fields, etc. For now, I'm really looking for something that can display EPS (postscript) and PDF images. In my research, here's some GUI modules/programs I've been looking at. I haven't gone real in-depth with these, but did just a little testing: 1. wxPython - This looks very good, although I'm not sure how to set up portability with this. Other machines that would run the Python code probably wouldn't have the Developer Tools or wxPython installed. I think I could use Py2App for OS X to create a Package App but I'm not real familiar with how that would all work. 2. Pyglet - This is a pretty cool program. I was able to display a window with an image? but I don't think it has GUI controls like text fields, drop down menues, etc. 3. ImageMagick - This one looks cool but I can't figure out how to install it correctly on OS X (Snow Leopard). Not sure if it would give me the GUI tools either. 4. PyGui - This one looks very interesting. Just found it last night so haven't looked at it too closely. Looks like it needs PyObjC on the machine for OS X. I'm assuming that comes pre-installed on Snow Leopard machines, but not sure about Leopard or Tiger machines. Anyone have more info about this? 5. NodeBox - This is an incredible application! Don't think I can use it's libraries for what I'm wanting to do, but what a cool program! I will definitely spend some time working with this! 6. TkInter - Does this module come standard on all machines that have Python? Haven't worked with this one much, but if I send Python code to other machines would TkInter work? Would love to hear anyones thoughts about GUI programming and what they use. Would also like to hear pros/cons with the different modules/apps. Thanks for looking at my questions. Jay From fordhaivat at gmail.com Sun May 30 00:05:46 2010 From: fordhaivat at gmail.com (Someone Something) Date: Sun, 30 May 2010 00:05:46 -0400 Subject: Python vs. Fedora and CentOS In-Reply-To: References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <20100529185522.0a4bb452.darcy@druid.net> Message-ID: Redhat as always believed in (sorry if this offends anyone): "Use legacy stuff that works, we don't really give a flying hoot if the rest of the world has moved on" On Sat, May 29, 2010 at 6:55 PM, D'Arcy J.M. Cain wrote: > On Sat, 29 May 2010 11:43:29 -0700 > John Nagle wrote: > > The major Red Hat based Linux distros are still shipping with Python > 2.4. > > > > Is anybody trying to do something about this? > > Other than not running Linux on our hosting server? My ISP > (http://www.Vex.Net) runs FreeBSD. Linux is for the desktop. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Sun May 30 00:15:15 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 29 May 2010 21:15:15 -0700 Subject: Python vs. Fedora and CentOS In-Reply-To: References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <20100529185522.0a4bb452.darcy@druid.net> Message-ID: And since they're "using legacy stuff that works" from 3 years ago (no one upgrades major versions of software in a minor release- hence Win XP SP3 still coming with IE 6), it's no wonder that they're still on 2.4. On Sat, May 29, 2010 at 9:05 PM, Someone Something wrote: > > Redhat as always believed in (sorry if this offends anyone): "Use legacy > stuff that works, we don't really give a flying hoot if the rest of the > world has moved on" > > On Sat, May 29, 2010 at 6:55 PM, D'Arcy J.M. Cain wrote: >> >> On Sat, 29 May 2010 11:43:29 -0700 >> John Nagle wrote: >> > ? ?The major Red Hat based Linux distros are still shipping with Python >> > 2.4. >> > >> > ? ?Is anybody trying to do something about this? >> >> Other than not running Linux on our hosting server? ?My ISP >> (http://www.Vex.Net) runs FreeBSD. ?Linux is for the desktop. >> >> -- >> D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolves >> http://www.druid.net/darcy/ ? ? ? ? ? ? ? ?| ?and a sheep voting on >> +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From nathan.alexander.rice at gmail.com Sun May 30 01:50:02 2010 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Sun, 30 May 2010 01:50:02 -0400 Subject: if, continuation and indentation In-Reply-To: References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> Message-ID: I prefer to just break such things into multiple lines. You're doing that already anyhow, it's not much of a speed hit, and it makes exactly what you're testing explicit. If I break a statement onto multiple lines I only use parenthesis, and that is as a last resort. In my opinion there's almost always some combination of variable assignments and lambda expressions that uses fewer lines and is clearer. is_correct_style = width == 0 and height == 0 and color == 'red' if (is_correct_style and emphasis == 'strong') or highlight > 100: On Sat, May 29, 2010 at 8:59 PM, Mark Lawrence wrote: > On 30/05/2010 01:23, john wrote: > >> On May 28, 10:37 am, "Colin J. Williams" >> wrote: >> >>> On 28-May-10 05:54 AM, Jonathan Hartley wrote: >>> >>> On May 27, 1:57 pm, Jean-Michel Pichavant >>>> wrote: >>>> >>>>> HH wrote: >>>>> >>>>>> I have a question about best practices when it comes to line wrapping/ >>>>>> continuation and indentation, specifically in the case of an if >>>>>> statement. >>>>>> >>>>> >>> When I write an if statement with many conditions, I prefer to use a >>>>>> parenthesis around the whole block and get the implicit continuation, >>>>>> rather than ending each line with an escape character. Thus, using >>>>>> the example from the style guide (http://www.python.org/dev/peps/ >>>>>> pep-0008/) I would write: >>>>>> >>>>> >>> if (width == 0 and >>>>>> height == 0 and >>>>>> color == 'red' and >>>>>> emphasis == 'strong' or >>>>>> highlight> 100): >>>>>> raise ValueError("sorry, you lose") >>>>>> >>>>> >>> The problem should be obvious -- it's not easy to see where the >>>>>> conditional ends and the statement begins since they have the same >>>>>> indentation. Part of the problem, I suppose, is that Emacs indents >>>>>> 'height' and the other lines in the conditional to 4 spaces (because >>>>>> of the parenthesis). How do people deal with this situation? >>>>>> >>>>> >>> Thanks, >>>>>> Henrik >>>>>> >>>>> >>> One possible solution >>>>> >>>> >>> if ( >>>>> width == 0 and >>>>> height == 0 and >>>>> color == 'red' and >>>>> emphasis == 'strong' or >>>>> highlight> 100 >>>>> ): >>>>> raise ValueError("sorry, you lose") >>>>> >>>> >>> JM >>>>> >>>> >>> I've always liked this, or even: >>>> >>> >>> if ( >>>> width == 0 and >>>> height == 0 and >>>> color == 'red' and >>>> emphasis == 'strong' or >>>> highlight> 100 >>>> ): >>>> raise ValueError("sorry, you lose") >>>> >>> >>> but my co-workers have uniformly gone bananas whenever I try it. >>>> >>> >>> I liked: >>> >>> On 27-May-10 08:48 AM, Xavier Ho wrote: >>> > On 27 May 2010 22:22, HH >> henri... at gmail.com>> wrote: >>> >>> > >>> > if (width == 0 and >>> > height == 0 and >>> > color == 'red' and >>> > emphasis == 'strong' or >>> > highlight> 100): >>> > raise ValueError("sorry, you lose") >>> > >>> > >>> > I've gotta say - I've bumped into this problem before, and I'm sure >>> many >>> > other have - this is a valid question. It just hasn't bothered me >>> enough >>> > to ask... >>> > >>> > Correct me if I'm wrong, but I think the following is equivalent, and >>> > looks better. Although this won't fix all ugly cases in that >>> problem.. >>> > >>> > if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or >>> > highlight> 100: >>> > raise ValueError("sorry, you lose") >>> > >>> > Cheers, >>> > Xav >>> >>> but nobody commented. >>> >>> Colin W. >>> >> >> Colin: >> Sure, you can do it that way. IMO, though, the OP was wrong, and so >> is the PEP. Source code is meant to communicate. So it must transmit >> the correct information to the computer; it also must inform your >> coworkers. That means that you have a responsibility to care what >> they think, though you privately have your opinions. Another reason >> the PEP is faulty in this circumstance is that a misplaced backslash, >> or a missing one, is easily found and fixed. A misplaced parentheses, >> or just one of a pair, will transform your source code into something >> which may compile and then give faulty results: a disaster. >> So keep it simple, and make it legible. >> Yours, >> John >> > > IMHO complete garbage, if your editor doesn't show misplaced or missing > parenthesis by highlighting you're using the wrong editor :) > > Regards. > > Mark Lawrence. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Sun May 30 02:06:47 2010 From: nagle at animats.com (John Nagle) Date: Sat, 29 May 2010 23:06:47 -0700 Subject: Where does "make altinstall" put stuff? Message-ID: <4c01facf$0$1600$742ec2ed@news.sonic.net> I know that one is supposed to use "make altinstall" to install versions of Python that won't be the "primary" version. But what directory names does it use for packages and other support files? Is this documented somewhere? I want to make sure that no part of the existing Python installation on Fedora Core is overwritten by an "altinstall" of 2.6. John Nagle From prologic at shortcircuit.net.au Sun May 30 02:21:30 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sun, 30 May 2010 16:21:30 +1000 Subject: Where does "make altinstall" put stuff? In-Reply-To: <4c01facf$0$1600$742ec2ed@news.sonic.net> References: <4c01facf$0$1600$742ec2ed@news.sonic.net> Message-ID: On Sun, May 30, 2010 at 4:06 PM, John Nagle wrote: > I know that one is supposed to use "make altinstall" to install > versions of Python that won't be the "primary" version. ?But what > directory names does it use for packages and other support files? > Is this documented somewhere? > > ?I want to make sure that no part of the existing Python installation > on Fedora Core is overwritten by an "altinstall" of 2.6. Check the generated Makefile (created by ./configure) --James From casevh at gmail.com Sun May 30 02:31:06 2010 From: casevh at gmail.com (casevh) Date: Sat, 29 May 2010 23:31:06 -0700 (PDT) Subject: Where does "make altinstall" put stuff? References: <4c01facf$0$1600$742ec2ed@news.sonic.net> Message-ID: <56b3f785-1135-4a99-b6b9-5646031447d7@6g2000prg.googlegroups.com> On May 29, 11:06?pm, John Nagle wrote: > ? ?I know that one is supposed to use "make altinstall" to install > versions of Python that won't be the "primary" version. ?But what > directory names does it use for packages and other support files? > Is this documented somewhere? > > ? ?I want to make sure that no part of the existing Python installation > on Fedora Core is overwritten by an "altinstall" of 2.6. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle It's placed in the directory specified by --prefix. If --prefix is not specified, /usr/local is used by default. casevh From steve at REMOVE-THIS-cybersource.com.au Sun May 30 02:55:14 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 May 2010 06:55:14 GMT Subject: xrange issue 7721 References: Message-ID: <4c020bd1$0$27827$c3e8da3@news.astraweb.com> On Sat, 29 May 2010 19:46:28 +0100, Mark Lawrence wrote: > I've had an OverflowError using xrange with Python 2.6.5 on Windows. > Googling got me to the subject line. It is considered best practice (or at least sensible practice) to include a relevant URL in your post. This will maximise the number of people who click through to the bug tracker while minimising the number who say "if the poster can't be bothered to copy and paste a URL, he obviously doesn't care that much about the issue, so why should I google for it?". http://bugs.python.org/issue7721 [...] > Assuming that I am correct, can I create myself a login on the bugs > tracker and re-open the issue to get this sorted? You can try, but I don't think that a code snippet is meant as a full- blown replacement for xrange, just as a, well, snippet to get you started. If you need a full replacement, you'll end up with something like this: _xrange = xrange def xrange(a, b=None, step=1): try: return _xrange(a, b, step) except OverflowError: if b is None: start, end = 0, a else: start, end = a, b if step > 0: from operator import lt as cmp elif step < 0: from operator import gt as cmp else: raise ValueError("xrange() arg 3 must not be zero") from itertools import count, takewhile return takewhile( lambda n: cmp(n, end), (start + i*step for i in count())) This should give you a larger range while still avoiding any significant overhead when you don't need it. -- Steven From nagle at animats.com Sun May 30 02:56:39 2010 From: nagle at animats.com (John Nagle) Date: Sat, 29 May 2010 23:56:39 -0700 Subject: MySQLdb install vs. "setuptools" Message-ID: <4c020680$0$1581$742ec2ed@news.sonic.net> MySQLdb won't install as non-root on Python 2.6 because its "setup.py" file requires "setuptools". "setuptools", unlike "distutils", isn't part of the Python 2.6 distribution. IMPORTANT PACKAGES SHOULD NOT USE "setuptools". Use the standard "distutils". "setuptools" and "eggs" create more problems than they solve. "setuptools" has many built-in assumptions about where things are supposed to be, and they're usually wrong. There's an "ez_setup.py" available for MySQLdb. This tries to obtain and install "setuptools". But it wants too many privileges just to do a "build": The following error occurred while trying to add or remove files in the installation directory: [Errno 2] No such file or directory: '/usr/local/lib/python2.6/site-packages/test-easy-install-22015.write-test' That's because "setuptools" has a built-in ego trip of insisting that it should be installed globally. I'm running a freshly-built, but not "installed" version of Python 2.6. I'm trying to install a test version of Python2.6 with some packages without running as root on a live server. It's not just MySQLdb that's broken by "setuptools". See these examples of other installation problems created by "setuptools": http://blog.awarelabs.com/2008/installing-mysqldb-without-python-egg-problems/ http://mail.python.org/pipermail/pythonmac-sig/2009-March/021148.html http://plone.org/documentation/error/permission-denied-python-eggs As soon as "setuptools" becomes involved, unnecessary headaches appear. DO NOT USE SETUPTOOLS. Either use "distutils", or go all the way and provide a RPM for Linux and a .exe for Windows. John Nagle From kobe824ouchao at gmail.com Sun May 30 05:15:04 2010 From: kobe824ouchao at gmail.com (Ou Chao) Date: Sun, 30 May 2010 17:15:04 +0800 Subject: How to use dbstore in google app engine Message-ID: Hi all: I have a question. How GEA save a file as simulates the App Engine datastore in local computer? where is the file? thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From detlev at die-offenbachs.de Sun May 30 05:23:17 2010 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 30 May 2010 11:23:17 +0200 Subject: GUI programs References: Message-ID: I would recommend PyQt. I've done a lot of programming with it (http://eric-ide.python-projects.org) and am amazed about the platform neutrality it offers. Regards, Detlev jyoung79 at kc.rr.com wrote: > Just curious if anyone would be willing to share their thoughts > about different Python GUI programming modules. I've been > doing a bit of research and am trying to find something that: > > 1. Is portable. Would like to be able to send the module along > with the main python file that would be able to run a GUI > window. Would be sending this to multiple machines. > Currently I'd like it to work on OS X machines, but it'd be nice > if it worked on Windows machines, etc. Probably be using > Python 2.5 or 2.6. > > 2. Can show an image (that is zoomable) as well as add GUI > controls like text fields, popup menues, etc. as well as send > information back to the program from the text fields, etc. > For now, I'm really looking for something that can display > EPS (postscript) and PDF images. > > In my research, here's some GUI modules/programs I've been > looking at. I haven't gone real in-depth with these, but did > just a little testing: > > 1. wxPython - This looks very good, although I'm not sure > how to set up portability with this. Other machines that would > run the Python code probably wouldn't have the Developer > Tools or wxPython installed. I think I could use Py2App for > OS X to create a Package App but I'm not real familiar with > how that would all work. > > 2. Pyglet - This is a pretty cool program. I was able to display > a window with an image? but I don't think it has GUI controls > like text fields, drop down menues, etc. > > 3. ImageMagick - This one looks cool but I can't figure out how > to install it correctly on OS X (Snow Leopard). Not sure if it would > give me the GUI tools either. > > 4. PyGui - This one looks very interesting. Just found it last night > so haven't looked at it too closely. Looks like it needs PyObjC on > the machine for OS X. I'm assuming that comes pre-installed on > Snow Leopard machines, but not sure about Leopard or Tiger > machines. Anyone have more info about this? > > 5. NodeBox - This is an incredible application! Don't think I can > use it's libraries for what I'm wanting to do, but what a cool > program! I will definitely spend some time working with this! > > 6. TkInter - Does this module come standard on all machines > that have Python? Haven't worked with this one much, but if I > send Python code to other machines would TkInter work? > > Would love to hear anyones thoughts about GUI programming > and what they use. Would also like to hear pros/cons with the > different modules/apps. > > Thanks for looking at my questions. > > Jay -- Detlev Offenbach detlev at die-offenbachs.de From googler.1.webmaster at spamgourmet.com Sun May 30 06:17:40 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Sun, 30 May 2010 03:17:40 -0700 (PDT) Subject: Py_single_input and the side-effects... References: Message-ID: <71e9afe5-f64e-4c2a-9c25-d814d13c7d46@t14g2000prm.googlegroups.com> Hi, any idea? From peterwfh2000 at gmail.com Sun May 30 06:21:04 2010 From: peterwfh2000 at gmail.com (PETER WONG F H (+971 50 8320722)) Date: Sun, 30 May 2010 03:21:04 -0700 (PDT) Subject: This is the way i make my dream and monthly income Message-ID: Hi, This is the way i make my dream and monthly income Making money online takes "hard work" but... The "$10 Per month" Power Formula Will Make Any Business Grow Without You Doing The Work! For every 5 affiliates you refer, we pay you a US100 cash bonus. There is no limit! Website : http://www.dubaiproperty.ws/ to explore more Best Regards Peter wong Dubai Mob : +971 50 ? 8320722 Malaysia Mob : +6012 ? 2956466 Peterwfh2000 at gmail.com From solipsis at pitrou.net Sun May 30 06:22:28 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 30 May 2010 12:22:28 +0200 Subject: MySQLdb install vs. "setuptools" References: <4c020680$0$1581$742ec2ed@news.sonic.net> Message-ID: <20100530122228.53c8e8a9@pitrou.net> Really, this shouldn't happen if you really are using a non-root version of Python: > [Errno 2] No such file or directory: > '/usr/local/lib/python2.6/site-packages/test-easy-install-22015.write-test' I don't think setuptools is dumb enough to hardcode things like "/usr/local/lib/python2.6/", so the error is probably yours here. Perhaps you should double-check you did everything fine before posting such a rant. Of course, if by "freshly-built version of Python", you mean you didn't run "make install" in any way, then it's your problem. Give "./configure" an appropriate non-root prefix and don't forget to run "make install" at the end. From philip at semanchuk.com Sun May 30 08:22:55 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 30 May 2010 08:22:55 -0400 Subject: GUI programs In-Reply-To: <20100530011322.HBM34.9984.root@cdptpa-web23-z02> References: <20100530011322.HBM34.9984.root@cdptpa-web23-z02> Message-ID: On May 29, 2010, at 9:13 PM, wrote: > Just curious if anyone would be willing to share their thoughts > about different Python GUI programming modules. I've been > doing a bit of research and am trying to find something that: > > 1. Is portable. Would like to be able to send the module along > with the main python file that would be able to run a GUI > window. Would be sending this to multiple machines. > Currently I'd like it to work on OS X machines, but it'd be nice > if it worked on Windows machines, etc. Probably be using > Python 2.5 or 2.6. Hi Jay, wxPython, pyQT and Tkinter are all portable in that they'll run under OS X, Windows, Gnome and KDE. Getting them installed there in some sane fashion is another matter. There are programs like py2exe and py2app that you've found, but Python doesn't lend itself to being bundled this way. It can work, but may be a fair amount of trouble depending on what modules you're trying to use and how diverse your target machines are. > 6. TkInter - Does this module come standard on all machines > that have Python? Haven't worked with this one much, but if I > send Python code to other machines would TkInter work? That's my understanding. I haven't used it. I gather that Tkinter is useful in a pinch, but that it isn't appropriate for applications with much more than a minimalist GUI. > Would love to hear anyones thoughts about GUI programming > and what they use. Would also like to hear pros/cons with the > different modules/apps. There's lots of discussion on this topic in the archives of this mailing list and others. These modules haven't changed dramatically over the past few years, so any recent-ish conversation is relevant. Good luck Philip PS - we use wxPython From 1000lane04 at gmail.com Sun May 30 08:57:37 2010 From: 1000lane04 at gmail.com (yan) Date: Sun, 30 May 2010 05:57:37 -0700 (PDT) Subject: $Wholesale Sports Shoes Clear Air Force One AAA++quality Message-ID: <985d98ba-6ae8-4e5e-9ed0-0876474b692b@p5g2000pri.googlegroups.com> $Wholesale Sports Shoes Clear Air Force One AAA++quality please kindly visite our website: http://www.8000trade.com supply sports shoes. The brand Sports shoes basketball shoes, Boot, walling shoes, Athletic shoes, Jogging shoes, running shoes, leather shoes, football, shoe sports shoe Footwear Sneaker, Shox Max Rift T- shirts, womens t-shirts, Clothing womens clothing, wear hats Caps Jersey jeans Sock Jacks, Watches, wallet, handbags, and Jeans Lady Clothing and so on. Please contact us by email to get more information. our price $33shoes,$15tshirt,15sunglasess, $13cap,$33jean,$35bag please kindly visite our website: http://www.8000trade.com From invalid at invalid.invalid Sun May 30 10:12:20 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 30 May 2010 14:12:20 +0000 (UTC) Subject: GUI programs References: Message-ID: On 2010-05-30, wrote: > 1. wxPython - This looks very good, although I'm not sure > how to set up portability with this. I'm not sure what you mean by "set up portability". If you follow the wxPython API documentation, then wxPython code is fairly portable. > Other machines that would run the Python code probably wouldn't have > the Developer Tools or wxPython installed. I think I could use > Py2App for OS X to create a Package App but I'm not real familiar > with how that would all work. I've used py2exe with success. It's fairly simple to use for simple programs, but can require some configuration tweaking if you use a log of libraries (wxPython numeric Python, scientific Python, etc.). > 6. TkInter - Does this module come standard on all machines > that have Python? Not all, but it's a lot more common than wxPython. > Haven't worked with this one much, but if I send Python code to other > machines would TkInter work? Generally yes, if the machines have TkInter installed. > Would love to hear anyones thoughts about GUI programming and what > they use. Would also like to hear pros/cons with the different > modules/apps. This question comes up about once a week, so Google should be able to find plenty of recent threads. -- Grant From nikunj257 at gmail.com Sun May 30 10:12:55 2010 From: nikunj257 at gmail.com (nikks) Date: Sun, 30 May 2010 07:12:55 -0700 (PDT) Subject: making $$$$ was never so easier..... Message-ID: <9ff37169-9815-464a-9d8b-d90f495a69fd@v12g2000prb.googlegroups.com> Build your own GeoString! and get paid............. http://www.geostring.com/en/?1155577 The longer you make your GeoString... the more free cash we'll put in your pockets! We'll give you $10.00 free money just for starting your own GeoString. Furthermore, we'll pay you every time you add length to your GeoString. It's Fun and it's Free! click below and earn... http://www.geostring.com/en/?1155577 From cournape at gmail.com Sun May 30 10:43:04 2010 From: cournape at gmail.com (David Cournapeau) Date: Sun, 30 May 2010 23:43:04 +0900 Subject: MySQLdb install vs. "setuptools" In-Reply-To: <4c020680$0$1581$742ec2ed@news.sonic.net> References: <4c020680$0$1581$742ec2ed@news.sonic.net> Message-ID: On Sun, May 30, 2010 at 3:56 PM, John Nagle wrote: > ? MySQLdb won't install as non-root on Python 2.6 because > its "setup.py" file requires "setuptools". ?"setuptools", > unlike "distutils", isn't part of the Python 2.6 distribution. > > ? IMPORTANT PACKAGES SHOULD NOT USE "setuptools". ?Use the > standard "distutils". ?"setuptools" and "eggs" create more > problems than they solve. ?"setuptools" has many built-in > assumptions about where things are supposed to be, and they're > usually wrong. Yes, setuptools is often a pain. The magic incantation you want is something like python setup.py install --prefix=someprefix --single-version-externally-managed --record=/dev/null. I myself have a small script which detects whether setup.py uses setuptools or not, and add the necessary options in setuptools case for a sane behavior. David From alfps at start.no Sun May 30 11:21:32 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 30 May 2010 17:21:32 +0200 Subject: GUI programs In-Reply-To: References: Message-ID: * jyoung79 at kc.rr.com, on 30.05.2010 03:13: > Just curious if anyone would be willing to share their thoughts > about different Python GUI programming modules. I've been > doing a bit of research and am trying to find something that: > > 1. Is portable. Would like to be able to send the module along > with the main python file that would be able to run a GUI > window. Would be sending this to multiple machines. > Currently I'd like it to work on OS X machines, but it'd be nice > if it worked on Windows machines, etc. Probably be using > Python 2.5 or 2.6. > > 2. Can show an image (that is zoomable) as well as add GUI > controls like text fields, popup menues, etc. as well as send > information back to the program from the text fields, etc. > For now, I'm really looking for something that can display > EPS (postscript) and PDF images. A GUI library may contain such functionality, but it's more properly the domain of a special purpose library. The question then boils down to which GUI libraries your image/rich text library is compatible with. Perhaps if someone else has handled that combination they'll chime in. Cheers & hth., - Alf PS: Tkinter on its own does not provide image resizing and does not on its own support common image formats like JPEG or PNG (it does support GIF). For Tkinter I think you can do that by adding the PIL library, if I remember the name correctly. But as far as I know PIL doesn't yet support Python 3.x, and doesn't support EPS or PDF, which are not image formats but rich text formats. -- blog at From sitecontactus at gmail.com Sun May 30 12:13:02 2010 From: sitecontactus at gmail.com (pythonista) Date: Sun, 30 May 2010 09:13:02 -0700 (PDT) Subject: strptime dilemma with Python 2.5 Message-ID: Hello, I have a date string looking like the following: "Sun May 30 07:25:17 2010" With Python 2.6, the %f is supported (it parses the microseconds), so that this statement works: dt = datetime.strptime(s, "%a %b %d %H:%M:%f %Y") However, with Python 2.5, (which is supported on the live Webfaction server I'm using), %f is not supported. Is there a straightforward way to simply ignore the :17 microseconds in the original string? Maybe force it to "00" ? - but without having to actually change the original string by removing the ":17" ? If I simply leave out the ":%f" in the strptime call, I get back a " ValueError: time data did not match format: data=Sun May 30 19:33:54 2010 fmt=%a %b %d %H:%M %Y Hoping for a simple solution that someone is familiar with Thanks Steve From nagle at animats.com Sun May 30 12:49:35 2010 From: nagle at animats.com (John Nagle) Date: Sun, 30 May 2010 09:49:35 -0700 Subject: MySQLdb install vs. "setuptools" In-Reply-To: References: <4c020680$0$1581$742ec2ed@news.sonic.net> Message-ID: <4c029178$0$1592$742ec2ed@news.sonic.net> David Cournapeau wrote: > On Sun, May 30, 2010 at 3:56 PM, John Nagle wrote: >> MySQLdb won't install as non-root on Python 2.6 because >> its "setup.py" file requires "setuptools". "setuptools", >> unlike "distutils", isn't part of the Python 2.6 distribution. >> >> IMPORTANT PACKAGES SHOULD NOT USE "setuptools". Use the >> standard "distutils". "setuptools" and "eggs" create more >> problems than they solve. "setuptools" has many built-in >> assumptions about where things are supposed to be, and they're >> usually wrong. > > Yes, setuptools is often a pain. > > The magic incantation you want is something like python setup.py > install --prefix=someprefix --single-version-externally-managed > --record=/dev/null. I myself have a small script which detects whether > setup.py uses setuptools or not, and add the necessary options in > setuptools case for a sane behavior. > > David The "setup.py" file for MySQLdb has, as its first Python line, "from setuptools import ...". No combination of options will get around that. John Nagle From nagle at animats.com Sun May 30 13:10:00 2010 From: nagle at animats.com (John Nagle) Date: Sun, 30 May 2010 10:10:00 -0700 Subject: MySQLdb install vs. "setuptools" In-Reply-To: References: <4c020680$0$1581$742ec2ed@news.sonic.net> Message-ID: <4c029641$0$1619$742ec2ed@news.sonic.net> Antoine Pitrou wrote: > Really, this shouldn't happen if you really are using a > non-root version of Python: > >> [Errno 2] No such file or directory: >> '/usr/local/lib/python2.6/site-packages/test-easy-install-22015.write-test' > > I don't think setuptools is dumb enough to hardcode things like > "/usr/local/lib/python2.6/", so the error is probably yours here. > Perhaps you should double-check you did everything fine before posting > such a rant. > > Of course, if by "freshly-built version of Python", you mean you didn't > run "make install" in any way, then it's your problem. Give > "./configure" an appropriate non-root prefix and don't forget to run > "make install" at the end. Actually, a "built" but "uninstalled" Python works fine. If it didn't, "make test" wouldn't work. "sys.path" correctly points to the library directories created during "build". On the other hand, options to "./configure" apparently don't work right in Python 2.6 through 3.x. "--libdir" and "--bindir" don't actually do anything. See "http://bugs.python.org/issue858809" (an open bug). So custom "configure" is currently broken. The real problem here remains the unnecessary use of "setuptools". It's Debian distro policy not to use "setuptools": http://www.debian.org/doc/packaging-manuals/python-policy/ap-packaging_tools.html Also read "Setuptools is not a decent software package management". http://workaround.org/easy-install-debian The fundamental problem is that "setuptools" is more than an installer but less than a widely-supported system-wide package manager like "yum". Now, how to get the dependency on "setuptools" out of MySQLdb? John Nagle From candide at free.invalid Sun May 30 13:38:23 2010 From: candide at free.invalid (candide) Date: Sun, 30 May 2010 19:38:23 +0200 Subject: Address of an immutable object Message-ID: <4c02a295$0$22392$426a74cc@news.free.fr> Suppose a Python program defines an integer object with value 42. The object has an "address" we can capture with the built-in function id() : >>> a=42 >>> id(a) 152263540 >>> Now I was wondering if any integer object with value 42 will be refered at the same adress with the above id. Some experiments tend to show that it may be the case, for instance : >>> a=42 >>> id(a) 152263540 >>> id(42) 152263540 >>> b=2*21 >>> id(b) 152263540 >>> c=0b101010 >>> id(c) 152263540 >>> d={"foo":42, "bar":"foo"} >>> id(d["foo"]) 152263540 >>> L=["foo",(51,([14,42],5)),"bar"] >>> id(L[1][1][0][1]) 152263540 >>> del a >>> id(L[1][1][0][1]) 152263540 >>> zzz=range(1000) >>> id(zzz[42]) 152263540 >>> Even you can't make a deep copy : >>> from copy import deepcopy >>> a=42 >>> from copy import deepcopy >>> z=deepcopy(a) >>> id(a), id(z) (152263540, 152263540) >>> So is the following true : Two non mutable objects with the same value shall be allocated at a constant and unique address ? From python at mrabarnett.plus.com Sun May 30 13:39:55 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 30 May 2010 18:39:55 +0100 Subject: strptime dilemma with Python 2.5 In-Reply-To: References: Message-ID: <4C02A2EB.6000400@mrabarnett.plus.com> pythonista wrote: > Hello, > I have a date string looking like the following: > > "Sun May 30 07:25:17 2010" > > With Python 2.6, the %f is supported (it parses the microseconds), so > that this statement works: > > dt = datetime.strptime(s, "%a %b %d %H:%M:%f %Y") > > However, with Python 2.5, (which is supported on the live Webfaction > server I'm using), %f is not supported. > > Is there a straightforward way to simply ignore the :17 microseconds > in the original string? > > Maybe force it to "00" ? - but without having to actually change the > original string by removing the ":17" ? > > If I simply leave out the ":%f" in the strptime call, I get back a " > ValueError: time data did not match format: data=Sun May 30 > 19:33:54 2010 fmt=%a %b %d %H:%M %Y > > > Hoping for a simple solution that someone is familiar with The date string looks like it has hours, minutes and seconds, not hours, minutes and microseconds. From alfps at start.no Sun May 30 13:44:09 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 30 May 2010 19:44:09 +0200 Subject: Address of an immutable object In-Reply-To: <4c02a295$0$22392$426a74cc@news.free.fr> References: <4c02a295$0$22392$426a74cc@news.free.fr> Message-ID: * candide, on 30.05.2010 19:38: > Suppose a Python program defines an integer object with value 42. The > object has an "address" we can capture with the built-in function id() : > > >>> a=42 > >>> id(a) > 152263540 > >>> > > Now I was wondering if any integer object with value 42 will be refered > at the same adress with the above id. > > Some experiments tend to show that it may be the case, for instance : > > >>> a=42 > >>> id(a) > 152263540 > >>> id(42) > 152263540 > >>> b=2*21 > >>> id(b) > 152263540 > >>> c=0b101010 > >>> id(c) > 152263540 > >>> d={"foo":42, "bar":"foo"} > >>> id(d["foo"]) > 152263540 > >>> L=["foo",(51,([14,42],5)),"bar"] > >>> id(L[1][1][0][1]) > 152263540 > >>> del a > >>> id(L[1][1][0][1]) > 152263540 > >>> zzz=range(1000) > >>> id(zzz[42]) > 152263540 > >>> > > Even you can't make a deep copy : > > > >>> from copy import deepcopy > >>> a=42 > >>> from copy import deepcopy > >>> z=deepcopy(a) > >>> id(a), id(z) > (152263540, 152263540) > >>> > > So is the following true : > > Two non mutable objects with the same value shall be allocated at a > constant and unique address ? No. First, id() doesn't generally provide an address. It does that in CPython, but more generally it just provides a unique integer identifying the reference. You can think of it as the "reference value" if you want; it's what's copied by an assignment to a variable. Second, the reason that you get the same id for various 42 objects is that CPython uses a cache of "small integer" objects. As I recall the cache ranges from -5 to some 127 or so (or perhaps it was double that). Any value outside that cached range you'll see different id's for the same value. Cheers & hth., - Alf -- blog at From simon at brunningonline.net Sun May 30 14:36:21 2010 From: simon at brunningonline.net (Simon Brunning) Date: Sun, 30 May 2010 19:36:21 +0100 Subject: Address of an immutable object In-Reply-To: <4c02a295$0$22392$426a74cc@news.free.fr> References: <4c02a295$0$22392$426a74cc@news.free.fr> Message-ID: On 30 May 2010 18:38:23 UTC+1, candide wrote: > Two non mutable objects with the same value shall be allocated at a constant and unique address ? Nope. >>> a = 999 >>> b = 999 >>> id(a) == id(b) False Your statement will be the case for small integers, but this in an implementation detail. Indeed, this used to be the case for integers up to 100 (IIRC) or thereabouts, but it's now the case up to 256: >>> a = 256 >>> b = 256 >>> id(a) == id(b) True >>> a = 257 >>> a = 257 >>> id(a) == id(b) False Some identifier-like strings are also interned like this: >>> a = 'foo' >>> b = 'foo' >>> id(a) == id(b) True >>> a = 'two words' >>> b = 'two words' >>> id(a) == id(b) False But again, it's an implementation detail, and shouldn't be relied upon. This same issue also comes up with people noticing that they can compare small integers with the 'is' operator, and getting a surprise when bigger numbers come along: >>> a = 256 >>> b = 256 >>> a is b True >>> a = 257 >>> b = 257 >>> a is b False -- Cheers, Simon B. From nagle at animats.com Sun May 30 14:56:22 2010 From: nagle at animats.com (John Nagle) Date: Sun, 30 May 2010 11:56:22 -0700 Subject: MySQLdb install vs. "setuptools" In-Reply-To: <4c029178$0$1592$742ec2ed@news.sonic.net> References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029178$0$1592$742ec2ed@news.sonic.net> Message-ID: <4c02af2f$0$1597$742ec2ed@news.sonic.net> John Nagle wrote: > David Cournapeau wrote: >> On Sun, May 30, 2010 at 3:56 PM, John Nagle wrote: >>> MySQLdb won't install as non-root on Python 2.6 because >>> its "setup.py" file requires "setuptools". "setuptools", >>> unlike "distutils", isn't part of the Python 2.6 distribution. >>> >>> IMPORTANT PACKAGES SHOULD NOT USE "setuptools". Use the >>> standard "distutils". "setuptools" and "eggs" create more >>> problems than they solve. "setuptools" has many built-in >>> assumptions about where things are supposed to be, and they're >>> usually wrong. I tried this change on MySQLdb's "setup.py": diff setup.py setup-nodistutils.py 5c5 < from setuptools import setup, Extension --- > from distutils.core import setup, Extension The build then runs. The resulting MySQLdb runs under the uninstalled Python and connects to the database properly. There's no need for "setuptools" here at all. It just gets in the way. John Nagle From martin at hvidberg.net Sun May 30 14:58:29 2010 From: martin at hvidberg.net (Martin Hvidberg) Date: Sun, 30 May 2010 20:58:29 +0200 Subject: Returning value from home made unit - how to? Message-ID: Dear A may-bee beginner?s question I have a Python program, which has until now, been running in command line mode only. I wish to add a GUI. I would like to develop (and maintain) the GUI part in a separate module, i.e. in its own .py file, and then ?import? that into the old main program. I jumped into wxPython, as it seems to be the right GUI for me, and downloaded some examples that I took apart and joined. Now the basic GUI is running, though neither beautiful nor complete. The main task for my GUI is to allow the user to point to an input file. It can now obtain a filename from a file selection dialog, but I can?t figure out how to get the filename, i.e. the string variable containing the file name, send back to the main program I attach the two .py files hereunder. My question is: How do I get the information from variable strSequenceFile, back to the main module in file jacxl.py ? Best Regards Martin Hvidberg # ====== File jacxl.py ============= import jacXlgui if __name__ == "__main__": print "Hello World - from Main"; result = jacXlgui.app.MainLoop() print 'Result:',result # ====== End of jacxl.py ============= # ====== File jacXlgui.py ============= #---------------------------------------------------------------------- # A very simple wxPython GUI. # To go with JakXl.py #---------------------------------------------------------------------- import wx, os class JacXlFrame(wx.Frame): """ This is a Frame. It just shows a few controls on a wxPanel, and has a simple menu. """ def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, pos=(150, 150), size=(350, 350)) # Create the menubar menuBar = wx.MenuBar() # and some menus filemenu = wx.Menu() helpmenu = wx.Menu() # add an item to the menu filemenu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Leave without running anything ...") helpmenu.Append(wx.ID_ABOUT, "&About"," Information about this program") # bind the menu event to an event handler self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT) self.Bind(wx.EVT_MENU, self.OnShowAbout, id=wx.ID_ABOUT) # and put the menu on the menubar menuBar.Append(filemenu, "&File") menuBar.Append(helpmenu, "&Help") self.SetMenuBar(menuBar) # Status bar self.CreateStatusBar() # Now create the Panel to put the other controls on. panel = wx.Panel(self) # A text... text = wx.StaticText(panel, -1, "Please select a \"Sequence\" file") text.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)) # , wx.BOLD text.SetSize(text.GetBestSize()) # Where is the Sequence file ? self.txcI = wx.TextCtrl(panel, -1, "", size=(300, -1)) # Some buttons btnFileFind = wx.Button(panel, -1, "Browse for file") btnClose = wx.Button(panel, -1, "Exit") btnRun = wx.Button(panel, -1, "Run") # bind the button events to handlers self.Bind(wx.EVT_BUTTON, self.OnFindFileButton, btnFileFind) self.Bind(wx.EVT_BUTTON, self.OnRunButton, btnRun) self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, btnClose) # Use a sizer to layout the controls, stacked vertically and with # a 10 pixel border around each sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(text, 0, wx.ALL, 10) sizer.Add(self.txcI, 0, wx.ALL, 10) sizer.Add(btnFileFind, 0, wx.ALL, 10) sizer.Add(btnRun, 0, wx.ALL, 10) sizer.Add(btnClose, 0, wx.ALL, 10) panel.SetSizer(sizer) panel.Layout() def OnFindFileButton(self, evt): strReturn = '' wildcard = "Sequence Log (*.LOG)|*.LOG|" \ "All files (*.*)|*.*" dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", wildcard, wx.OPEN) if dialog.ShowModal() == wx.ID_OK: strSequenceFile = dialog.GetPath() self.txcI.ChangeValue(strSequenceFile) # Copying filename to text box dialog.Destroy() print 'Found file:',strSequenceFile return strSequenceFile def OnShowAbout(self, evt): print "About this program ..." def OnRunButton(self, evt): """Event handler for the button click.""" print 'Run :',self.txcI.GetValue() return self.txcI.GetValue() def OnTimeToClose(self, evt): """Event handler for the button click.""" print "See ya later!" self.Close() class JacXlApp(wx.App): def OnInit(self): frame = JacXlFrame(None, "JacXl - converting ... to eXcel") self.SetTopWindow(frame) print "Print statements go to this stdout window by default." frame.Show(True) return True app = JacXlApp(redirect=False) # ====== End of jacXlgui.py ============= From kaklis at gmail.com Sun May 30 15:07:04 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Sun, 30 May 2010 12:07:04 -0700 (PDT) Subject: Threads with Cmd and socket server combination Message-ID: hi, I have implement a command line app using Python's cmd library module and it works fine. I 've also create a simple threaded socket server. How can i merge the two ones, so that the console app, is also a listening server? How can i achieve that with threads? I'm trying for days and i can't make it work! I know it can be done with Twisted but i want to understand how thread works. The console: class BM(CmdBase): """Simple custom command processor""" def do_acmd(self): pass if __name__ == '__main__': BM().cmdloop() and the Server: class MyClientHandler(SocketServer.BaseRequestHandler): def handle(self): pass server = SocketServer.ThreadingTCPServer(myaddr, MyClientHandler) server.serve_forever( ) Thanks in advance Threads can be so difficult A.K. From cjwilliams43 at gmail.com Sun May 30 15:10:23 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Sun, 30 May 2010 15:10:23 -0400 Subject: if, continuation and indentation In-Reply-To: References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> Message-ID: <4C02B81F.20509@gmail.com> On 30-May-10 01:50 AM, Nathan Rice wrote: > I prefer to just break such things into multiple lines. You're doing > that already anyhow, it's not much of a speed hit, and it makes exactly > what you're testing explicit. If I break a statement onto multiple > lines I only use parenthesis, and that is as a last resort. In my > opinion there's almost always some combination of variable assignments > and lambda expressions that uses fewer lines and is clearer. > > is_correct_style = width == 0 and height == 0 and color == 'red' > if (is_correct_style and emphasis == 'strong') or highlight > 100: > > > On Sat, May 29, 2010 at 8:59 PM, Mark Lawrence > wrote: > > On 30/05/2010 01:23, john wrote: > > On May 28, 10:37 am, "Colin J. Williams" > > wrote: > > On 28-May-10 05:54 AM, Jonathan Hartley wrote: > > On May 27, 1:57 pm, Jean-Michel > Pichavant > > wrote: > > HH wrote: > > I have a question about best practices when it > comes to line wrapping/ > continuation and indentation, specifically in > the case of an if > statement. > > > When I write an if statement with many > conditions, I prefer to use a > parenthesis around the whole block and get the > implicit continuation, > rather than ending each line with an escape > character. Thus, using > the example from the style guide > (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100): > raise ValueError("sorry, you lose") > > > The problem should be obvious -- it's not easy > to see where the > conditional ends and the statement begins since > they have the same > indentation. Part of the problem, I suppose, is > that Emacs indents > 'height' and the other lines in the conditional > to 4 spaces (because > of the parenthesis). How do people deal with > this situation? > > > Thanks, > Henrik > > > One possible solution > > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100 > ): > raise ValueError("sorry, you lose") > > > JM > > > I've always liked this, or even: > > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100 > ): > raise ValueError("sorry, you lose") > > > but my co-workers have uniformly gone bananas whenever I > try it. > > > I liked: > > On 27-May-10 08:48 AM, Xavier Ho wrote: > > On 27 May 2010 22:22, HH > >> wrote: > > > > > if (width == 0 and > > height == 0 and > > color == 'red' and > > emphasis == 'strong' or > > highlight> 100): > > raise ValueError("sorry, you lose") > > > > > > I've gotta say - I've bumped into this problem before, > and I'm sure many > > other have - this is a valid question. It just hasn't > bothered me enough > > to ask... > > > > Correct me if I'm wrong, but I think the following is > equivalent, and > > looks better. Although this won't fix all ugly cases in > that problem.. > > > > if (width, height, color, emphasis) == (0, 0, 'red', > 'strong') or > > highlight> 100: > > raise ValueError("sorry, you lose") > > > > Cheers, > > Xav > > but nobody commented. > > Colin W. > > > Colin: > Sure, you can do it that way. IMO, though, the OP was wrong, > and so > is the PEP. Source code is meant to communicate. So it must > transmit > the correct information to the computer; it also must inform your > coworkers. That means that you have a responsibility to care what > they think, though you privately have your opinions. Another reason > the PEP is faulty in this circumstance is that a misplaced > backslash, > or a missing one, is easily found and fixed. A misplaced > parentheses, > or just one of a pair, will transform your source code into > something > which may compile and then give faulty results: a disaster. > So keep it simple, and make it legible. > Yours, > John > > > IMHO complete garbage, if your editor doesn't show misplaced or > missing parenthesis by highlighting you're using the wrong editor :) > > Regards. > > Mark Lawrence. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Perhaps the arrangement below shows the matching a little better than the Xav suggestion. The main point is that, to me, the tuple shows the item by item matching better than a series of and clauses: # tif.py (width, height, color, emphasis)= 0, 0, 'red', 'strong' highlight= 99 if (width, height, color, emphasis) == \ ( 0, 0, 'red', 'strong') or highlight> 100: raise ValueError("sorry, you lose") Colin W. From cjwilliams43 at gmail.com Sun May 30 15:10:23 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Sun, 30 May 2010 15:10:23 -0400 Subject: if, continuation and indentation In-Reply-To: References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> Message-ID: <4C02B81F.20509@gmail.com> On 30-May-10 01:50 AM, Nathan Rice wrote: > I prefer to just break such things into multiple lines. You're doing > that already anyhow, it's not much of a speed hit, and it makes exactly > what you're testing explicit. If I break a statement onto multiple > lines I only use parenthesis, and that is as a last resort. In my > opinion there's almost always some combination of variable assignments > and lambda expressions that uses fewer lines and is clearer. > > is_correct_style = width == 0 and height == 0 and color == 'red' > if (is_correct_style and emphasis == 'strong') or highlight > 100: > > > On Sat, May 29, 2010 at 8:59 PM, Mark Lawrence > wrote: > > On 30/05/2010 01:23, john wrote: > > On May 28, 10:37 am, "Colin J. Williams" > > wrote: > > On 28-May-10 05:54 AM, Jonathan Hartley wrote: > > On May 27, 1:57 pm, Jean-Michel > Pichavant > > wrote: > > HH wrote: > > I have a question about best practices when it > comes to line wrapping/ > continuation and indentation, specifically in > the case of an if > statement. > > > When I write an if statement with many > conditions, I prefer to use a > parenthesis around the whole block and get the > implicit continuation, > rather than ending each line with an escape > character. Thus, using > the example from the style guide > (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100): > raise ValueError("sorry, you lose") > > > The problem should be obvious -- it's not easy > to see where the > conditional ends and the statement begins since > they have the same > indentation. Part of the problem, I suppose, is > that Emacs indents > 'height' and the other lines in the conditional > to 4 spaces (because > of the parenthesis). How do people deal with > this situation? > > > Thanks, > Henrik > > > One possible solution > > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100 > ): > raise ValueError("sorry, you lose") > > > JM > > > I've always liked this, or even: > > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100 > ): > raise ValueError("sorry, you lose") > > > but my co-workers have uniformly gone bananas whenever I > try it. > > > I liked: > > On 27-May-10 08:48 AM, Xavier Ho wrote: > > On 27 May 2010 22:22, HH > >> wrote: > > > > > if (width == 0 and > > height == 0 and > > color == 'red' and > > emphasis == 'strong' or > > highlight> 100): > > raise ValueError("sorry, you lose") > > > > > > I've gotta say - I've bumped into this problem before, > and I'm sure many > > other have - this is a valid question. It just hasn't > bothered me enough > > to ask... > > > > Correct me if I'm wrong, but I think the following is > equivalent, and > > looks better. Although this won't fix all ugly cases in > that problem.. > > > > if (width, height, color, emphasis) == (0, 0, 'red', > 'strong') or > > highlight> 100: > > raise ValueError("sorry, you lose") > > > > Cheers, > > Xav > > but nobody commented. > > Colin W. > > > Colin: > Sure, you can do it that way. IMO, though, the OP was wrong, > and so > is the PEP. Source code is meant to communicate. So it must > transmit > the correct information to the computer; it also must inform your > coworkers. That means that you have a responsibility to care what > they think, though you privately have your opinions. Another reason > the PEP is faulty in this circumstance is that a misplaced > backslash, > or a missing one, is easily found and fixed. A misplaced > parentheses, > or just one of a pair, will transform your source code into > something > which may compile and then give faulty results: a disaster. > So keep it simple, and make it legible. > Yours, > John > > > IMHO complete garbage, if your editor doesn't show misplaced or > missing parenthesis by highlighting you're using the wrong editor :) > > Regards. > > Mark Lawrence. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Perhaps the arrangement below shows the matching a little better than the Xav suggestion. The main point is that, to me, the tuple shows the item by item matching better than a series of and clauses: # tif.py (width, height, color, emphasis)= 0, 0, 'red', 'strong' highlight= 99 if (width, height, color, emphasis) == \ ( 0, 0, 'red', 'strong') or highlight> 100: raise ValueError("sorry, you lose") Colin W. From cjwilliams43 at gmail.com Sun May 30 15:20:43 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Sun, 30 May 2010 15:20:43 -0400 Subject: GUI programs In-Reply-To: References: <20100530011322.HBM34.9984.root@cdptpa-web23-z02> Message-ID: On 30-May-10 08:22 AM, Philip Semanchuk wrote: > > On May 29, 2010, at 9:13 PM, > wrote: > >> Just curious if anyone would be willing to share their thoughts >> about different Python GUI programming modules. I've been >> doing a bit of research and am trying to find something that: >> >> 1. Is portable. Would like to be able to send the module along >> with the main python file that would be able to run a GUI >> window. Would be sending this to multiple machines. >> Currently I'd like it to work on OS X machines, but it'd be nice >> if it worked on Windows machines, etc. Probably be using >> Python 2.5 or 2.6. > > Hi Jay, > wxPython, pyQT and Tkinter are all portable in that they'll run under OS > X, Windows, Gnome and KDE. Getting them installed there in some sane > fashion is another matter. There are programs like py2exe and py2app > that you've found, but Python doesn't lend itself to being bundled this > way. It can work, but may be a fair amount of trouble depending on what > modules you're trying to use and how diverse your target machines are. > >> 6. TkInter - Does this module come standard on all machines >> that have Python? Haven't worked with this one much, but if I >> send Python code to other machines would TkInter work? > > That's my understanding. I haven't used it. I gather that Tkinter is > useful in a pinch, but that it isn't appropriate for applications with > much more than a minimalist GUI. > >> Would love to hear anyones thoughts about GUI programming >> and what they use. Would also like to hear pros/cons with the >> different modules/apps. > > There's lots of discussion on this topic in the archives of this mailing > list and others. These modules haven't changed dramatically over the > past few years, so any recent-ish conversation is relevant. > > > Good luck > Philip > > PS - we use wxPython I am just starting with PyQt4. It has an IDE, Eric4, which seems flexible and is about to be fully geared up for Windows. There is also a Screen Designer, that I haven't used yet. Colin W. From sitecontactus at gmail.com Sun May 30 15:43:10 2010 From: sitecontactus at gmail.com (pythonista) Date: Sun, 30 May 2010 12:43:10 -0700 (PDT) Subject: strptime dilemma with Python 2.5 References: Message-ID: <48661a90-25ec-40e7-b1a6-d22f61476b90@p5g2000pri.googlegroups.com> You know why it looks like it has seconds and not microseconds? Because it does, and I'm on something. Thank you > > The date string looks like it has hours, minutes and seconds, not hours, > minutes and microseconds. From solipsis at pitrou.net Sun May 30 15:55:25 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 30 May 2010 21:55:25 +0200 Subject: MySQLdb install vs. "setuptools" References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029641$0$1619$742ec2ed@news.sonic.net> Message-ID: <20100530215525.6bb1b5ef@pitrou.net> On Sun, 30 May 2010 10:10:00 -0700 John Nagle wrote: > > Actually, a "built" but "uninstalled" Python works fine. > If it > didn't, "make test" wouldn't work. That's a completely unrelated thing. The main reason "make test" works with an uninstalled Python is simply so that the core developers' life is easier. It doesn't mean all Python functionalities work in that context. > On the other hand, options to "./configure" apparently don't work > right in Python 2.6 through 3.x. "--libdir" and "--bindir" don't actually > do anything. You can use "--prefix" instead, it works. > The real problem here remains the unnecessary use of "setuptools". No, again, the real problem is just that you are trying to install modules for an uninstalled Python. You may hate setuptools with a passion, but it's unconstructive and useless to put the blame on it without any solid argument. Do yourself a favour: pass the proper options to "./configure", and install Python. Regards Antoine. From candide at free.invalid Sun May 30 16:07:15 2010 From: candide at free.invalid (candide) Date: Sun, 30 May 2010 22:07:15 +0200 Subject: Address of an immutable object In-Reply-To: <4c02a295$0$22392$426a74cc@news.free.fr> References: <4c02a295$0$22392$426a74cc@news.free.fr> Message-ID: <4c02c57a$0$12648$426a74cc@news.free.fr> Thanks for your responses, I should do more experiments ! From candide at free.invalid Sun May 30 16:08:49 2010 From: candide at free.invalid (candide) Date: Sun, 30 May 2010 22:08:49 +0200 Subject: Address of an immutable object In-Reply-To: References: <4c02a295$0$22392$426a74cc@news.free.fr> Message-ID: <4c02c5d7$0$12648$426a74cc@news.free.fr> Alf P. Steinbach a ?crit : > * candide, on 30.05.2010 19:38: >> Suppose a Python program defines an integer object with value 42. The >> object has an "address" we can capture with the built-in function id() : > First, id() doesn't generally provide an address. I talked about a quote unquote "address" ;) but according to "The Python Language Reference" it's not very far from the truth : -------------------- 3.1 Objects, values and types (...) An object?s identity never changes once it has been created; you may think of it as the object?s _address_ in memory. The ?is? operator compares the identity of two objects; the id() function returns an integer representing its identity (currently implemented as its _address_). -------------------- (emphasizing is mine) From mmanns at gmx.net Sun May 30 17:11:56 2010 From: mmanns at gmx.net (Martin Manns) Date: Sun, 30 May 2010 23:11:56 +0200 Subject: xrange issue 7721 References: <20100529211241.56dc7bc4@Knock> Message-ID: <20100530231156.313d748c@Knock> On Sun, 30 May 2010 00:49:11 +0100 Mark Lawrence wrote: > From http://docs.python.org/dev/library/itertools.html > "Unlike regular slicing, islice() does not support negative values > for start, stop, or step." > > Rule 1 of programming never assume anything, particularly wrt > testing. I assume that you are ok with this. :) Dreadful I know :) Right, never post before reading the fine manual :) > > I found the msg97928 code pretty obvious when seeing the snippet. > > If you disagree you may consider re-opening the issue. > I trust that you get my point regarding the failure to raise a > ValueError :) Or am I wearing my extremely stupid hat today? Since you seem to find this issue important, are you going to re-open the issue? Cheers Martin From scalesjordan at gmail.com Sun May 30 17:45:44 2010 From: scalesjordan at gmail.com (prezjordan) Date: Sun, 30 May 2010 14:45:44 -0700 (PDT) Subject: GUI programs References: <20100530011322.HBM34.9984.root@cdptpa-web23-z02> Message-ID: <1eabbe7c-78d8-4cda-90f7-2e60b45a22e8@w3g2000vbd.googlegroups.com> How does GTK compare to Qt? From electronixtar at gmail.com Sun May 30 17:49:19 2010 From: electronixtar at gmail.com (est) Date: Sun, 30 May 2010 14:49:19 -0700 (PDT) Subject: What's the largest python/django powered website in the world? Message-ID: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> Hi list, just curious, what's the largest python powered website in the world? and what's the largest django powered website in the world? Is it disqus.com? From fetchinson at googlemail.com Sun May 30 18:09:00 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 31 May 2010 00:09:00 +0200 Subject: What's the largest python/django powered website in the world? In-Reply-To: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> References: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> Message-ID: > just curious, what's the largest python powered website in the world? I'm afraid you'll need to define what you mean by "python powered". If the server side of a web application is written in 3 or more languages and one of them is python, does that count? If yes, then probably google and youtube are the "largest python powered websites". Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From solipsis at pitrou.net Sun May 30 18:11:45 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Mon, 31 May 2010 00:11:45 +0200 Subject: MySQLdb install vs. "setuptools" References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029641$0$1619$742ec2ed@news.sonic.net> <4c02de23$0$1603$742ec2ed@news.sonic.net> Message-ID: <20100531001145.73e16360@pitrou.net> On Sun, 30 May 2010 15:16:42 -0700 John Nagle wrote: > > It's nice that some of the options work. Note that someone who > used "--bindir", expecting it to work, might end up overwriting their > existing Python installation unintentionally, which would break system > administration tools like cPanel and "yum". Well, usually you don't type "sudo" unintentionally... > The ongoing low quality of Python distribution mechanisms, and the > denial of that fact, is a major part of why Python, after 20 years, is far > less available than Perl. "Far less available"? How so? > The latest production versions of Red Hat > Enterprise Linux and CentOS, the major server distributions, still ship > with Python 2.4.3, a five year old version of Python. And of course nothing in this is Python's or setuptools' fault, since it's just Redhat's policy, so I wonder what you're trying to tell us. (not to mention that it doesn't have anything to do with the original topic anymore, either) From nagle at animats.com Sun May 30 18:16:42 2010 From: nagle at animats.com (John Nagle) Date: Sun, 30 May 2010 15:16:42 -0700 Subject: MySQLdb install vs. "setuptools" In-Reply-To: References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029641$0$1619$742ec2ed@news.sonic.net> Message-ID: <4c02de23$0$1603$742ec2ed@news.sonic.net> Antoine Pitrou wrote: > On Sun, 30 May 2010 10:10:00 -0700 > John Nagle wrote: >> Actually, a "built" but "uninstalled" Python works fine. >> If it >> didn't, "make test" wouldn't work. > > That's a completely unrelated thing. The main reason "make test" works > with an uninstalled Python is simply so that the core developers' life > is easier. It doesn't mean all Python functionalities work in that > context. > >> On the other hand, options to "./configure" apparently don't work >> right in Python 2.6 through 3.x. "--libdir" and "--bindir" don't actually >> do anything. > > You can use "--prefix" instead, it works. It's nice that some of the options work. Note that someone who used "--bindir", expecting it to work, might end up overwriting their existing Python installation unintentionally, which would break system administration tools like cPanel and "yum". cPanel support recommends against installing a new Python other than through "yum". http://forums.cpanel.net/f5/mailman-breaks-stable-upcp-due-python-upgrade-126453.html http://forums.cpanel.net/f5/upgrade-python-whm-113593.html They don't trust other install mechanisms. With good cause. >> The real problem here remains the unnecessary use of "setuptools". > > No, again, the real problem is just that you are trying to install > modules for an uninstalled Python. > You may hate setuptools with a passion, but it's unconstructive and > useless to put the blame on it without any solid argument. > Do yourself a favour: pass the proper options to "./configure", and > install Python. > > Regardssetu > > Antoine. Having demonstrated in a previous post that 1) the use of "setuptools" was completely unnecessary, and 2) it's quite possible to load and use MySQLdb in an "uninstalled" Python, we can dismiss the above argument. The ongoing low quality of Python distribution mechanisms, and the denial of that fact, is a major part of why Python, after 20 years, is far less available than Perl. The latest production versions of Red Hat Enterprise Linux and CentOS, the major server distributions, still ship with Python 2.4.3, a five year old version of Python. John Nagle From mwilson at the-wire.com Sun May 30 18:22:04 2010 From: mwilson at the-wire.com (Mel) Date: Sun, 30 May 2010 18:22:04 -0400 Subject: Returning value from home made unit - how to? References: Message-ID: Martin Hvidberg wrote: > I have a Python program, which has until now, been running in command line > mode only. I wish to add a GUI. > > I would like to develop (and maintain) the GUI part in a separate module, > i.e. in its own .py file, and then ?import? that into the old main > program. > > I jumped into wxPython, as it seems to be the right GUI for me, and > downloaded some examples that I took apart and joined. Now the basic GUI > is running, though neither beautiful nor complete. > > The main task for my GUI is to allow the user to point to an input file. > It can now obtain a filename from a file selection dialog, but I can?t > figure out how to get the filename, i.e. the string variable containing > the file name, send back to the main program > > I attach the two .py files hereunder. > > My question is: > How do I get the information from variable strSequenceFile, back to the > main module in file jacxl.py ? AFAIK, typically, you don't -- the way it is here. Returning a value from a Button handler, or any event handler generally, won't have any effect. The event handlers are called from deep in wx code by routines that don't deal with anything specific to the data-processing side of the program. What I think you might do is to make strSequenceFile an attribute of your Frame, so that OnFindFile button does ``self.strSequenceFile = dialog.GetPath()'' rather than returning that value. Then your main level can do ``jacXlgui.app.GetTopWindow().strSequenceFile'' . There are probably refinements to be added to this, but I think it's a good beginning strategy. The first new place I would take the whole program would be to remove the command-line controls from the command line program, so you're left with a sort of "business model" that contains only the data processing. Then you can write a new GUI program based on jacXlgui that imports the data processing module and calls computations and reports results from the model. Mel. From cournape at gmail.com Sun May 30 18:49:40 2010 From: cournape at gmail.com (David Cournapeau) Date: Mon, 31 May 2010 07:49:40 +0900 Subject: MySQLdb install vs. "setuptools" In-Reply-To: <4c02de23$0$1603$742ec2ed@news.sonic.net> References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029641$0$1619$742ec2ed@news.sonic.net> <4c02de23$0$1603$742ec2ed@news.sonic.net> Message-ID: On Mon, May 31, 2010 at 7:16 AM, John Nagle wrote: > ? ?It's nice that some of the options work. ?Note that someone who > used "--bindir", expecting it to work, might end up overwriting their > existing Python installation unintentionally, which would break system > administration tools like cPanel and "yum". > > ? ?cPanel support recommends against installing a new Python other > than through "yum". > > http://forums.cpanel.net/f5/mailman-breaks-stable-upcp-due-python-upgrade-126453.html > http://forums.cpanel.net/f5/upgrade-python-whm-113593.html > > ? ?They don't trust other install mechanisms. ?With good cause. This has absolutely nothing to do with how python is installed. It is common sense that you should upgrade an installed package through the package manager mechanism (here yum), and is true for any software, python or not. >?The latest production versions of Red Hat > Enterprise Linux and CentOS, the major server distributions, still ship > with Python 2.4.3, a five year old version of Python. Yes, by definition RHEL ships softwares that does not change for a long time. By your argument, the linux kernel and gcc are broken because they are 4 years old on RHEL 5 (linux 2.6.18. gcc 4.0.*). That does not make any sense. cheers, David From martin at v.loewis.de Sun May 30 18:54:16 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 31 May 2010 00:54:16 +0200 Subject: xrange issue 7721 In-Reply-To: References: Message-ID: <4C02EC98.9020507@v.loewis.de> > Assuming that I am correct, can I create myself a login on the bugs > tracker and re-open the issue to get this sorted? Definitely not. The issue you are looking at has been fixed; whatever your issue is (you didn't state it clearly), it must be a different one. So if you are going to report anything, please submit a new bug report instead. For the record, the issue you were looking at was a complaint that the documentation is incorrect. This had been fixed by correcting the documentation. Please structure bug reports as follows: 1. this is what you did 2. this is what happened 3. this is what you had expected/wanted to happen instead Regards, Martin From benjamin.kaplan at case.edu Sun May 30 18:57:17 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 30 May 2010 15:57:17 -0700 Subject: MySQLdb install vs. "setuptools" In-Reply-To: <4c02de23$0$1603$742ec2ed@news.sonic.net> References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029641$0$1619$742ec2ed@news.sonic.net> <4c02de23$0$1603$742ec2ed@news.sonic.net> Message-ID: On Sun, May 30, 2010 at 3:16 PM, John Nagle wrote: > Antoine Pitrou wrote: > >> On Sun, 30 May 2010 10:10:00 -0700 >> John Nagle wrote: >> >>> Actually, a "built" but "uninstalled" Python works fine. >>> If it >>> didn't, "make test" wouldn't work. >>> >> >> That's a completely unrelated thing. The main reason "make test" works >> with an uninstalled Python is simply so that the core developers' life >> is easier. It doesn't mean all Python functionalities work in that >> context. >> > > > >> On the other hand, options to "./configure" apparently don't work >>> right in Python 2.6 through 3.x. "--libdir" and "--bindir" don't >>> actually >>> do anything. >>> >> >> You can use "--prefix" instead, it works. >> > > It's nice that some of the options work. Note that someone who > used "--bindir", expecting it to work, might end up overwriting their > existing Python installation unintentionally, which would break system > administration tools like cPanel and "yum". > > cPanel support recommends against installing a new Python other > than through "yum". > > > http://forums.cpanel.net/f5/mailman-breaks-stable-upcp-due-python-upgrade-126453.html > http://forums.cpanel.net/f5/upgrade-python-whm-113593.html > > They don't trust other install mechanisms. With good cause. > > The real problem here remains the unnecessary use of "setuptools". >>> >> >> No, again, the real problem is just that you are trying to install >> modules for an uninstalled Python. >> You may hate setuptools with a passion, but it's unconstructive and >> useless to put the blame on it without any solid argument. >> Do yourself a favour: pass the proper options to "./configure", and >> install Python. >> >> Regardssetu >> >> Antoine. >> > > Having demonstrated in a previous post that 1) the use of "setuptools" > was completely unnecessary, and 2) it's quite possible to load and use > MySQLdb in an "uninstalled" Python, we can dismiss the above argument. > > The ongoing low quality of Python distribution mechanisms, and the > denial of that fact, is a major part of why Python, after 20 years, is far > less available than Perl. The latest production versions of Red Hat > Enterprise Linux and CentOS, the major server distributions, still ship > with Python 2.4.3, a five year old version of Python. > > John Nagle > > Based on a quick search, CentOS 5.5 ships with Perl 5.8.8. I would assume that it uses the same version as RHEL. Based on another quick search, Perl 5.8.8 shipped in February 2006, one month before Python 2.4.3. What does this have to do with distribution mechanisms again? And last time I checked, Python is now preinstalled on every OS worth speaking of except for Windows. Last time I checked, Perl was preinstalled on every OS worth speaking of except for Windows. With IronPython putting Python on the .NET Framework, one could argue that, if anything, Python is more available than Perl. Particularly if Microsoft ever gets around to giving IronPython and IronRuby first class status in Visual Studio. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun May 30 19:19:13 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 May 2010 23:19:13 GMT Subject: Address of an immutable object References: <4c02a295$0$22392$426a74cc@news.free.fr> <4c02c5d7$0$12648$426a74cc@news.free.fr> Message-ID: <4c02f271$0$14140$c3e8da3@news.astraweb.com> On Sun, 30 May 2010 22:08:49 +0200, candide wrote: > Alf P. Steinbach a ?crit : >> * candide, on 30.05.2010 19:38: >>> Suppose a Python program defines an integer object with value 42. The >>> object has an "address" we can capture with the built-in function id() >>> : > >> First, id() doesn't generally provide an address. > > I talked about a quote unquote "address" ;) but according to "The Python > Language Reference" it's not very far from the truth : > > -------------------- > 3.1 Objects, values and types > (...) > An object?s identity never changes > once it has been created; you may think of it as the object?s _address_ > in memory. The ?is? operator compares the identity of two objects; the > id() function returns an integer representing its identity (currently > implemented as its _address_). > -------------------- > > (emphasizing is mine) Which is a weakness of the documentation, since in Jython object ids are 1, 2, 3, 4, ... rather than addresses in memory. Of course, if you want to think of 1, 2, 3, 4, ... as addresses, who's going to stop you? :-) -- Steven From electronixtar at gmail.com Sun May 30 19:27:27 2010 From: electronixtar at gmail.com (est) Date: Sun, 30 May 2010 16:27:27 -0700 (PDT) Subject: What's the largest python/django powered website in the world? References: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> Message-ID: > I'm afraid you'll need to define what you mean by "python powered". Except database, presentation layer, major business logic is done by python. Except Google/youtube, what's next? From steve at REMOVE-THIS-cybersource.com.au Sun May 30 19:34:19 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 May 2010 23:34:19 GMT Subject: xrange issue 7721 References: <4C02EC98.9020507@v.loewis.de> Message-ID: <4c02f5fa$0$14140$c3e8da3@news.astraweb.com> On Mon, 31 May 2010 00:54:16 +0200, Martin v. Loewis wrote: >> Assuming that I am correct, can I create myself a login on the bugs >> tracker and re-open the issue to get this sorted? > > Definitely not. The issue you are looking at has been fixed; whatever > your issue is (you didn't state it clearly), it must be a different one. > So if you are going to report anything, please submit a new bug report > instead. > > For the record, the issue you were looking at was a complaint that the > documentation is incorrect. This had been fixed by correcting the > documentation. I think Mark's point is that the code snippet given isn't a full replacement for xrange, since it doesn't support negative step sizes, nor does it raise an exception on step=0. I can see why somebody might argue that the documentation is wrong. The given snippet *isn't* a replacement for xrange, but merely an example of how you might get xrange-like behaviour over a restricted domain. Since the docs are read by people with vastly different levels of experience, skill and nous, I think it's a reasonable complaint to make. I am sure that there will be plenty of people who will take the docs literally and be surprised when their code fails because the xrange replacement fails. I'd suggest fixing the docs to make it clear that the snippet is a simplified example rather than a replacement, rather than trying to complicate the snippet to cover all cases xrange deals with. In my opinion, all it takes is the addition of two words: If a larger range is needed, an alternate version can be crafted using the itertools module, for example: takewhile(lambda x: x References: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> Message-ID: On Mon, May 31, 2010 at 9:27 AM, est wrote: > Except Google/youtube, what's next? bitbucket (1) is mostly implemented in Python cheers James 1. http://bitbucket.org/ -- -- "Problems are solved by method" From benjamin.kaplan at case.edu Sun May 30 20:14:23 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 30 May 2010 17:14:23 -0700 Subject: What's the largest python/django powered website in the world? In-Reply-To: References: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> Message-ID: On Sun, May 30, 2010 at 4:27 PM, est wrote: > > > I'm afraid you'll need to define what you mean by "python powered". > > Except database, presentation layer, major business logic is done by > python. > > Except Google/youtube, what's next? > -- > http://mail.python.org/mailman/listinfo/python-list http://www.reddit.com http://github.com/reddit/reddit I believe they recently said that they're at 7.5 million users and 270 million page views per month. And the repo is 71% Python with most of the rest as Javascript. From pavlovevidence at gmail.com Sun May 30 21:31:11 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 30 May 2010 18:31:11 -0700 (PDT) Subject: Py_single_input and the side-effects... References: <71e9afe5-f64e-4c2a-9c25-d814d13c7d46@t14g2000prm.googlegroups.com> Message-ID: <0d5415fc-d59b-42a2-99da-d1fd49c7a401@11g2000prv.googlegroups.com> On May 30, 3:17?am, moerchendiser2k3 wrote: > Hi, any idea? Python doesn't guarantee that objects will be deleted at a specific time. There are different reasons why an object might not be deleted. In command line mode Python keeps a reference to the most recent result. I don't know if it happens in general for any Py_single_input, but you could try to execute a few dummy commands with Py_single_input to see if it helps. But if you're relying on that behavior you really need to consider rethinking your problem. The only foolproof way to ensure that an object has been finalized is to do it manually (i.e., provide a finalize method to releases resources). Carl Banks From jyoung79 at kc.rr.com Sun May 30 23:29:55 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Mon, 31 May 2010 3:29:55 +0000 Subject: GUI programs Message-ID: <20100531032955.CIMZB.277363.root@cdptpa-web08-z02> Just want to say thank you to all those who responded with their thoughts so far. Really appreciate you taking the time to share. This list has always been incredibly helpful and insightful! I do have another quick question. Has anyone had any luck getting PyGUI working on Snow Leopard? I can't seem to get the blobedit example to work. -- >> 1. wxPython - This looks very good, although I'm not sure >> how to set up portability with this. > I'm not sure what you mean by "set up portability". If you follow the > wxPython API documentation, then wxPython code is fairly portable. By portable, I mean I want to send code out to other machines (right now just OS X machines) that don't already have wxPython. It'd be nice to be able to package the appropriate module/library with my Python script. For example, I include the xlrd module and Python file inside of an AppleScript droplet which works perfect as a stand-alone droplet on numerous machines. -- >> Would love to hear anyones thoughts about GUI programming and what >> they use. Would also like to hear pros/cons with the different >> modules/apps. > This question comes up about once a week, so Google should be able > to find plenty of recent threads. I've been googling this subject for quite some time. Have found a lot of good results but would like to find more detail - especially more specific to displaying zoomable images like EPS, etc. From xcr4cx at googlemail.com Mon May 31 04:22:10 2010 From: xcr4cx at googlemail.com (christian schulze) Date: Mon, 31 May 2010 01:22:10 -0700 (PDT) Subject: Free chapter about Python and databases (MySQL and SQLite) References: <4BFFBA12.6050004@wildenhain.de> <75097175-6f22-4eaa-aa69-c93df86227c5@o4g2000vbo.googlegroups.com> Message-ID: <41f36471-cfeb-4fc9-9353-f0dd32c72687@j9g2000vbp.googlegroups.com> On 28 Mai, 18:09, Peter Otten <__pete... at web.de> wrote: > christian schulze wrote: > > On 28 Mai, 17:12, Sebastian Bassi wrote: > >> On Fri, May 28, 2010 at 9:41 AM, Tino Wildenhain > >> wrote: > >> > Did you consider adding a part dealing with postgresql too? > >> > (Especially interesting in the way you can write stored functions > >> > in python there) > > >> That is a good idea for the next version/edition. But meanwhile I > >> could write something in my blog atwww.py4bio.com > >> Best, > >> SB > > > Indeed a style like > >> user="root" > > is not that nice. > > > I had no look at the chapter but recommend you to read the PEP 8 - > > Python style guides (code conventions for python). > > > Imo a book have to be kinda exemplary. And bad style sucks anyway ... > > > PS: > >> user = 'root' or user = "root" > > ... would be much more beautyful. > > My crystal ball says that the post you are not quoting is concerned about > the security implications of accessing a database as the superuser rather > than about spaces surrounding the assignment operator. > > My crystal ball then starts nitpicking and adds that in the sample chapter > user="root" occurs within an argument list where its format is actually > required by the PEP: > > """ > - Don't use spaces around the '=' sign when used to indicate a > ? ? ? keyword argument or a default parameter value. > > ? ? ? Yes: > > ? ? ? ? ? def complex(real, imag=0.0): > ? ? ? ? ? ? ? return magic(r=real, i=imag) > """ > > Cheers, > Peter Oh, I'm sorry. As I said, i didn't even had a look on the chapter. I assumed it was a regular variable declaration. So just ignore what I said :P best regards From martin at v.loewis.de Mon May 31 04:22:35 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 31 May 2010 10:22:35 +0200 Subject: xrange issue 7721 In-Reply-To: <4c02f5fa$0$14140$c3e8da3@news.astraweb.com> References: <4C02EC98.9020507@v.loewis.de> <4c02f5fa$0$14140$c3e8da3@news.astraweb.com> Message-ID: <4C0371CB.401@v.loewis.de> >> For the record, the issue you were looking at was a complaint that the >> documentation is incorrect. This had been fixed by correcting the >> documentation. > > I think Mark's point is that the code snippet given isn't a full > replacement for xrange, since it doesn't support negative step sizes, nor > does it raise an exception on step=0. Still, that issue is different from 7721. 7721 was about a completely-nonworking example in the documentation. This error has been fully corrected. So this issue *is* fixed, reopining it would be inappropriate. There may be another issue with this example, which should be reported separately. > Since the docs are read by people with vastly different levels of > experience, skill and nous, I think it's a reasonable complaint to make. That may well be. The proposed approach (reopen the issue) is what I consider unreasonable. Regards, Martin From eric.brunel.pragmadev at gmail.com Mon May 31 04:55:17 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Mon, 31 May 2010 01:55:17 -0700 (PDT) Subject: GUI programs References: Message-ID: <871b2e6c-f716-4627-8bfb-888503cf1b1a@r9g2000vbk.googlegroups.com> On May 30, 5:21?pm, "Alf P. Steinbach" wrote: > PS: Tkinter on its own does not provide image resizing and does not on its own > support common image formats like JPEG or PNG (it does support GIF). "Native" PNG support in tcl/tk and hence Tkinter is planned for the next release (8.6), which is in beta stage, so should be official soon. From eric.brunel.pragmadev at gmail.com Mon May 31 05:07:09 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Mon, 31 May 2010 02:07:09 -0700 (PDT) Subject: tkinter function outout to text widget References: Message-ID: On May 29, 10:51?pm, Johan Lans wrote: > Hi > I'm totally new on python and I'm doing an assignement where I'm doing > a class that manipulates a text. The program is also supposed to have > a GUI, for which I have used tkinter. > So far I have entry widgets for file names and buttons, its all > working like I want it to. > What is missing is a way to output the changes to the text. I was > thinking that a text-widget would be suitable. Is there a reasonably > easy way to do this? > I tried inserting a string to the textwidget and letting the class > method change this string, but the inserted string isn't updated in > the text-widget. > Would be very happy for any hints. You won't be able to do exactly what you want with the text widget. There is a possibility to have to auto-updating in the GUI indeed, but it can only be made via other widgets than the text. Here is an example of what you can do: -------- from Tkinter import * root = Tk() var = StringVar() var.set('aaa') lbl = Label(root, textvariable=var) lbl.pack(side=LEFT) def next(): var.set(''.join(chr(ord(c) + 1) for c in var.get())) Button(root, text='Next', command=next).pack() root.mainloop() -------- As you can see, I'm using a Label here. This should be enough if the text you want to display is read-only. The Label will also adapt its size if there are several lines in your text. The biggest limitation is probably that you can't make it scrollable (not easily, at least?). HTH - Eric - From eric.brunel.pragmadev at gmail.com Mon May 31 05:16:14 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Mon, 31 May 2010 02:16:14 -0700 (PDT) Subject: Tkinter library reference References: Message-ID: <83599fd6-e654-47ec-87fd-33d8bb87eef8@k31g2000vbu.googlegroups.com> On May 29, 3:11?pm, Pradeep B wrote: > Do we have a standard reference library for Tkinter available? > > -- > Pradeep Short answer: no, at least not a complete one for Tkinter itself. However, there is a complete reference for tcl/tk here: http://www.tcl.tk/man/tcl8.5/ Once you're used to converting tcl/tk's commands and options into Tkinter classes and methods, it is the best one around. If you really need Python/Tkinter syntax, there are some good documents here: http://www.tkdocs.com/widgets/index.html http://effbot.org/tkinterbook/ But these are not complete or rather old. However, you can use them as a starting point before diving into the tcl/tk reference above. HTH - Eric - From astley.lejasper at gmail.com Mon May 31 05:24:43 2010 From: astley.lejasper at gmail.com (Astley Le Jasper) Date: Mon, 31 May 2010 02:24:43 -0700 (PDT) Subject: Creating a single list References: <4c012062$0$18987$4fafbaef@reader5.news.tin.it> Message-ID: On May 29, 4:10?pm, superpollo wrote: > Astley Le Jasper ha scritto: > > > > > This is probably a really silly question but, given the example code > > at the bottom, how would I get a single list? > > > What I currently get is: > > > ('id', 20, 'integer') > > ('companyname', 50, 'text') > > [('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, > > 'text'), ('puma', 30, 'text')] > > ('contact', 50, 'text') > > ('email', 50, 'text') > > > what I would like is: > > > ('id', 20, 'integer') > > ('companyname', 50, 'text') > > ('focus', 30, 'text'), > > ('fiesta', 30, 'text'), > > ('mondeo', 30, 'text'), > > ('puma', 30, 'text'), > > ('contact', 50, 'text') > > ('email', 50, 'text') > > > SAMPLE CODE>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > > def getproducts(): > > ? ? temp_list=[] > > ? ? product_list=['focus','fiesta','mondeo','puma'] #usually this > > would come from a db > > ? ? for p in product_list: > > ? ? ? ? temp_list.append((p,30,'text')) > > ? ? return temp_list > > > def createlist(): > > ? ? column_title_list = ( > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("id",20,"integer"), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("companyname",50,"text"), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? getproducts(), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("contact",50,"text"), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("email",50,"text"), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ) > > ? ? return column_title_list > > > for item in createlist(): > > ? ? print item > > ?>>> def createlist(): > ... ? ? column_title_list = [ > ... ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("id",20,"integer"), > ... ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("companyname",50,"text")] > ... ? ? column_title_list += getproducts() > ... ? ? column_title_list += [ > ... ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("contact",50,"text"), > ... ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("email",50,"text")] > ... ? ? return column_title_list > ... > ?>>> for item in createlist(): > ... ? ? print item > ... > ('id', 20, 'integer') > ('companyname', 50, 'text') > ('focus', 30, 'text') > ('fiesta', 30, 'text') > ('mondeo', 30, 'text') > ('puma', 30, 'text') > ('contact', 50, 'text') > ('email', 50, 'text') > ?>>> > > bye Cheers for that. I was thinking there might be something clever, but as usual, simple is better. From googler.1.webmaster at spamgourmet.com Mon May 31 06:10:52 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Mon, 31 May 2010 03:10:52 -0700 (PDT) Subject: Py_single_input and the side-effects... References: <71e9afe5-f64e-4c2a-9c25-d814d13c7d46@t14g2000prm.googlegroups.com> <0d5415fc-d59b-42a2-99da-d1fd49c7a401@11g2000prv.googlegroups.com> Message-ID: Hi Carl, thanks for your help!! > The only foolproof way to ensure that an object has been finalized is > to do it manually (i.e., provide a finalize method to releases > resources). Yes, you are right, thats what I thought, too. So I wanted to manually delete the reference, but browsing the sources, seems that I cant really free it, because its wrapped somewhere in Py_Finalize() and PyGC_Collect and Py_FreeModules. Any ideas? Thanks a lot! Cheers, moerchendiser2k3 From payal-python at scriptkitchen.com Mon May 31 06:19:46 2010 From: payal-python at scriptkitchen.com (Payal) Date: Mon, 31 May 2010 03:19:46 -0700 Subject: reading help() - newbie question Message-ID: <20100531101946.GA13241@scriptkitchen.com> Hi, I am trying to learn Python (again) and have some basic doubts which I hope someone in the list can address. (English is not my first language and I have no CS background except I can write decent shell scripts) When I type help(something) e.g. help(list), I see many methods like, __methodname__(). Are these something special? How do I use them and why put "__" around them? One more simple query. Many times I see something like this, | D.iteritems() -> an iterator over the (key, value) items of D What is this iterator they are talking about and how do I use these methods because simly saying D.iteritems() does not work? Thanks a lot in advance. With warm regards, -Payal -- From contact at xavierho.com Mon May 31 06:41:54 2010 From: contact at xavierho.com (Xavier Ho) Date: Mon, 31 May 2010 20:41:54 +1000 Subject: reading help() - newbie question In-Reply-To: <20100531101946.GA13241@scriptkitchen.com> References: <20100531101946.GA13241@scriptkitchen.com> Message-ID: On 31 May 2010 20:19, Payal wrote: > Hi, > I am trying to learn Python (again) and have some basic doubts which I > hope someone in the list can address. (English is not my first language and > I > have no CS background except I can write decent shell scripts) > > Welcome (back) to the Python-List! > When I type help(something) e.g. help(list), I see many methods like, > __methodname__(). Are these something special? They're very special. You can think of them as "Python internal functions", and are called internally by other functions. > How do I use them and why > put "__" around them? > You call them as if they were any other function. 99% of the time though, you don't need to call them, as there are better, cleaner ways. > > One more simple query. Many times I see something like this, > | D.iteritems() -> an iterator over the (key, value) items of D > What is this iterator they are talking about <...> > See http://docs.python.org/library/stdtypes.html#iterator-types . Just a peek, nothing big. > and how do I use these > You can use iterators by ... iterating through the items! Like this: >>> for i in [1, 3, 6, 10, 15]: ... print i ... 1 3 6 10 15 and, in your specific example: >>> x = {1: 2, 3: 4} >>> for key, value in x.iteritems(): ... print key, "->", value ... 1 -> 2 3 -> 4 > methods because simly saying D.iteritems() does not work? It does work - it returns you an iterator you can use later: >>> x_items = x.iteritems() >>> for k, v in x_items: ... print k + v ... 3 7 Have fun with Python! Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon May 31 06:47:38 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 31 May 2010 03:47:38 -0700 Subject: reading help() - newbie question In-Reply-To: References: <20100531101946.GA13241@scriptkitchen.com> Message-ID: On Mon, May 31, 2010 at 3:41 AM, Xavier Ho wrote: > On 31 May 2010 20:19, Payal wrote: >> When I type help(something) e.g. help(list), I see many methods like, >> __methodname__(). Are these something special? > > They're very special. You can think of them as "Python internal functions", > and are called internally by other functions. > >> >> How do I use them and why >> put "__" around them? > > You call them as if they were any other function. 99% of the time though, > you don't need to call them, as there are better, cleaner ways. To be a bit more specific, double-underscore methods are called internally by Python to implement various operators. For example, `a + b` is usually equivalent to `a.__add__(b)`, and `len(a)` calls `a.__len__()` internally. For more info, see http://docs.python.org/reference/datamodel.html#special-method-names Cheers, Chris -- http://blog.rebertia.com From cjwilliams43 at gmail.com Mon May 31 06:48:16 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Mon, 31 May 2010 06:48:16 -0400 Subject: reading help() - newbie question In-Reply-To: <20100531101946.GA13241@scriptkitchen.com> References: <20100531101946.GA13241@scriptkitchen.com> Message-ID: On 31-May-10 06:19 AM, Payal wrote: > Hi, > I am trying to learn Python (again) and have some basic doubts which I > hope someone in the list can address. (English is not my first language and I > have no CS background except I can write decent shell scripts) > > When I type help(something) e.g. help(list), I see many methods like, > __methodname__(). Are these something special? How do I use them and why > put "__" around them? > > One more simple query. Many times I see something like this, > | D.iteritems() -> an iterator over the (key, value) items of D > What is this iterator they are talking about and how do I use these > methods because simly saying D.iteritems() does not work? > > Thanks a lot in advance. > With warm regards, > -Payal Here is an extract from the docs for Python 2.6.5. I hope that this clarifies things. Colin W. 2.3.2. Reserved classes of identifiers Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters: _* Not imported by from module import *. The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the __builtin__ module. When not in interactive mode, _ has no special meaning and is not defined. See section The import statement. Note The name _ is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention. __*__ System-defined names. These names are defined by the interpreter and its implementation (including the standard library); applications should not expect to define additional names using this convention. The set of names of this class defined by Python may be extended in future versions. See section Special method names. __* Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between ?private? attributes of base and derived classes. See section Identifiers (Names). From googler.1.webmaster at spamgourmet.com Mon May 31 07:11:25 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Mon, 31 May 2010 04:11:25 -0700 (PDT) Subject: Py_single_input and the side-effects... References: <71e9afe5-f64e-4c2a-9c25-d814d13c7d46@t14g2000prm.googlegroups.com> <0d5415fc-d59b-42a2-99da-d1fd49c7a401@11g2000prv.googlegroups.com> Message-ID: Hi Carl, you are right, Python still holds the last reference. I just set a dummy and thats it :) Can you tell me where did you get the information from? Thanks! From e49eb54c193c5 at poster.grepler.com Mon May 31 07:13:03 2010 From: e49eb54c193c5 at poster.grepler.com (Jason D) Date: 31 May 2010 11:13:03 GMT Subject: Python vs. Fedora and CentOS In-Reply-To: <4c015aa9$0$1617$742ec2ed@news.sonic.net> References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> Message-ID: <3RMMn.125235$y07.3938@news.usenetserver.com> > The major Red Hat based Linux distros are still shipping with >Python 2.4. >As a result, almost all hosting providers are running obsolete >versions of >Python. > > The big problem seems to be that &quot;cPanel&quot; and >&quot;yum&quot; still use older versions >of Python, and those programs are more important to distro builders >than Python >itself. > > Is anybody trying to do something about this? > > John Nagle I am not sure of Fedora, CentOs 5.x ships with Python 2.5 . The version of python depends a lot on everything else that is packed into the system and uses python. e.g. GUI based tools, system scripts etc. There is however never been an issue to locate different version of python in your system as you deem fit without problems. So I dont understand why your concern. regards Jason ---------------------------- posted via Grepler.com -- poster is authenticated. From holmes86 at gmail.com Mon May 31 07:37:58 2010 From: holmes86 at gmail.com (holmes86) Date: Mon, 31 May 2010 04:37:58 -0700 (PDT) Subject: how to generate a csr in python? Message-ID: hi,everyone I want generate a Certificate signing request in python,but I don't how to realize this function.I don't find any method after read the python-openssl manual.Any help will appreciate. From pradeepbpin at gmail.com Mon May 31 08:59:55 2010 From: pradeepbpin at gmail.com (Pradeep B) Date: Mon, 31 May 2010 18:29:55 +0530 Subject: Tkinter library reference In-Reply-To: <83599fd6-e654-47ec-87fd-33d8bb87eef8@k31g2000vbu.googlegroups.com> References: <83599fd6-e654-47ec-87fd-33d8bb87eef8@k31g2000vbu.googlegroups.com> Message-ID: On Mon, May 31, 2010 at 2:46 PM, eb303 wrote: > On May 29, 3:11?pm, Pradeep B wrote: >> Do we have a standard reference library for Tkinter available? >> >> -- >> Pradeep > > Short answer: no, at least not a complete one for Tkinter itself. > > However, there is a complete reference for tcl/tk here: http://www.tcl.tk/man/tcl8.5/ > Once you're used to converting tcl/tk's commands and options into > Tkinter classes and methods, it is the best one around. > > If you really need Python/Tkinter syntax, there are some good > documents here: > http://www.tkdocs.com/widgets/index.html > http://effbot.org/tkinterbook/ > But these are not complete or rather old. However, you can use them as > a starting point before diving into the tcl/tk reference above. > > HTH > ?- Eric - > -- > http://mail.python.org/mailman/listinfo/python-list > I think, generating it using the 'pydoc' seems to be much better. -pradeep -- |_|0|_| |_|_|0| |0|0|0| http://picasaweb.google.com/pradeepbpin From pradeepbpin at gmail.com Mon May 31 09:01:48 2010 From: pradeepbpin at gmail.com (Pradeep B) Date: Mon, 31 May 2010 18:31:48 +0530 Subject: Python and Tkinter Programming by John Grayson In-Reply-To: <81dfc$4c011eaa$4275d90a$28590@FUSE.NET> References: <0738732e-d8df-469d-be4a-3699f4fd5f64@j14g2000yqm.googlegroups.com> <801d251d-ae12-4ce6-95a1-58f594cd2f81@p8g2000yqb.googlegroups.com> <4B4F96D6.2070905@codebykevin.com> <326dc723-3909-4293-9bf6-48a367b9251c@e16g2000yqc.googlegroups.com> <4B58FCDF.4000402@stoneleaf.us> <81dfc$4c011eaa$4275d90a$28590@FUSE.NET> Message-ID: On Sat, May 29, 2010 at 7:33 PM, Kevin Walzer wrote: > Tkinter doesn't wrap native printing API's. There are a few extensions that > do it, but they are platform specific and not complete. > > The usual ways of printing are like this: > > 1. If you're outputting data from the text widget, write that to a temporary > text file and print via lpr. > > 2. If you're outputting data from the canvas, write that to a temporary > postscript file and print via lpr. > > This is on Unix/MacOS. Not sure what the equivalent API on Windows is. > > --Kevin > > -- > Kevin Walzer > Code by Kevin > http://www.codebykevin.com > -- > http://mail.python.org/mailman/listinfo/python-list > Thanx Kevin. Anybody can throw light on how to do the same in Windows ? -pradeep -- |_|0|_| |_|_|0| |0|0|0| http://picasaweb.google.com/pradeepbpin From magawake at gmail.com Mon May 31 09:42:04 2010 From: magawake at gmail.com (Mag Gam) Date: Mon, 31 May 2010 09:42:04 -0400 Subject: parsing question Message-ID: I have a file with bunch of nfsstat -c (on AIX) which has all the hostnames, for example ========r1svr========== Client rpc: Connection oriented calls badcalls badxids timeouts newcreds badverfs timers 0 0 0 0 0 0 0 nomem cantconn interrupts 0 0 0 Connectionless calls badcalls retrans badxids timeouts newcreds badverfs 6553 0 0 0 0 0 0 timers nomem cantsend 0 0 0 Client nfs: calls badcalls clgets cltoomany 6541 0 0 0 Version 2: (6541 calls) null getattr setattr root lookup readlink read 0 0% 590 9% 414 6% 0 0% 2308 35% 0 0% 0 0% wrcache write create remove rename link symlink 0 0% 2482 37% 276 4% 277 4% 147 2% 0 0% 0 0% mkdir rmdir readdir statfs 6 0% 6 0% 30 0% 5 0% Version 3: (0 calls) null getattr setattr lookup access readlink read 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% write create mkdir symlink mknod remove rmdir 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% rename link readdir readdir+ fsstat fsinfo pathconf 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% commit 0 0% ========r2svr========== Client rpc: Connection oriented calls badcalls badxids timeouts newcreds badverfs timers 0 0 0 0 0 0 0 nomem cantconn interrupts 0 0 0 Connectionless calls badcalls retrans badxids timeouts newcreds badverfs 6553 0 0 0 0 0 0 timers nomem cantsend 0 0 0 Client nfs: calls badcalls clgets cltoomany 6541 0 0 0 Version 2: (6541 calls) null getattr setattr root lookup readlink read 0 0% 590 9% 414 6% 0 0% 2308 35% 0 0% 0 0% wrcache write create remove rename link symlink 0 0% 2482 37% 276 4% 277 4% 147 2% 0 0% 0 0% mkdir rmdir readdir statfs 6 0% 6 0% 30 0% 5 0% Version 3: (0 calls) null getattr setattr lookup access readlink read 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% write create mkdir symlink mknod remove rmdir 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% rename link readdir readdir+ fsstat fsinfo pathconf 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% commit 0 0% and so on... (http://publib.boulder.ibm.com/infocenter/aix/v6r1/index.jsp?topic=/com.ibm.aix.prftungd/doc/prftungd/nfsstat_c_command.htm) Is there a an easy way to parse this file according to each host? So, r1svr.Connectionless.calls=6553 r1svr.Connectionless.badcalls=0 and so on... I am currently using awk which I am able to get what I need, but curious if in python how people handle block data. From philip at semanchuk.com Mon May 31 09:53:09 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 31 May 2010 09:53:09 -0400 Subject: Python vs. Fedora and CentOS In-Reply-To: <3RMMn.125235$y07.3938@news.usenetserver.com> References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <3RMMn.125235$y07.3938@news.usenetserver.com> Message-ID: On May 31, 2010, at 7:13 AM, Jason D wrote: >> The major Red Hat based Linux distros are still shipping with >> Python 2.4. >> As a result, almost all hosting providers are running obsolete >> versions of >> Python. >> >> The big problem seems to be that &quot;cPanel&quot; and >> &quot;yum&quot; still use older versions >> of Python, and those programs are more important to distro builders >> than Python >> itself. >> >> Is anybody trying to do something about this? >> >> John Nagle > > I am not sure of Fedora, CentOs 5.x ships with Python 2.5 . The > version of python depends a lot on everything else that is packed > into the system and uses python. e.g. GUI based tools, system > scripts etc. Hi Jason, CentOS is based on RHEL SRPMs. How could it ship a more advanced version of Python than RHEL? I have CentOS 5.4 installed, and it only offers Python 2.4.3. And distrowatch.org backs this up -- the latest Python available for Centos 5.x is 2.4: http://distrowatch.com/table.php?distribution=centos Did you perhaps install Python 2.5 on your own by compiling the source tarball? bye Philip From vincent at vincentdavis.net Mon May 31 10:04:53 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 31 May 2010 08:04:53 -0600 Subject: Question about permutations (itertools) Message-ID: As a note I am doing this in py3. I am looking for the most efficient (speed) way to produce an an iterator to of permutations. One of the problem I am having it that neither combinations nor permutations does not exactly what I want directly. For example If I want all possible ordered lists of 0,1 of length 3 (0,0,0) (0,0,1) (0,1,1) (1,1,1) (1,0,1) (1,1,0) (1,0,0) I don't see a way to get this directly from the itertools. But maybe I am missing something. I see ways to get a bigger list and then remove duplicates. >>> list(permutations([0,1], 3)) [] >>> list(combinations_with_replacement('01',3)) ('0', '0', '0') ('0', '0', '1') ('0', '1', '1') ('1', '1', '1') Is it possible to get combinations_with_replacement to return numbers rather than strings? (see above) Thanks Vincent From contact at xavierho.com Mon May 31 10:17:49 2010 From: contact at xavierho.com (Xavier Ho) Date: Tue, 1 Jun 2010 00:17:49 +1000 Subject: Question about permutations (itertools) In-Reply-To: References: Message-ID: > >>> list(combinations_with_replacement('01',3)) > ('0', '0', '0') > ('0', '0', '1') > ('0', '1', '1') > ('1', '1', '1') > > Is it possible to get combinations_with_replacement to return numbers > rather than strings? (see above) > >>> list(combinations_with_replacement(range(0,2), 3)) [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] Hopefully that'll give you some ideas. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon May 31 10:25:26 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 May 2010 16:25:26 +0200 Subject: Question about permutations (itertools) References: Message-ID: Vincent Davis wrote: > As a note I am doing this in py3. > > I am looking for the most efficient (speed) way to produce an an > iterator to of permutations. > One of the problem I am having it that neither combinations nor > permutations does not exactly what I want directly. > For example If I want all possible ordered lists of 0,1 of length 3 > (0,0,0) > (0,0,1) > (0,1,1) > (1,1,1) > (1,0,1) > (1,1,0) > (1,0,0) > I don't see a way to get this directly from the itertools. But maybe I > am missing something. >>> for t in itertools.product([0, 1], repeat=3): ... print(t) ... (0, 0, 0) (0, 0, 1) (0, 1, 0) # Seems you missed one (0, 1, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1) > I see ways to get a bigger list and then remove > duplicates. > >>>> list(permutations([0,1], 3)) > [] > >>>> list(combinations_with_replacement('01',3)) > ('0', '0', '0') > ('0', '0', '1') > ('0', '1', '1') > ('1', '1', '1') > > Is it possible to get combinations_with_replacement to return numbers > rather than strings? (see above) >>> for t in itertools.combinations_with_replacement([0, 1], 3): ... print(t) ... (0, 0, 0) (0, 0, 1) (0, 1, 1) (1, 1, 1) Peter From vincent at vincentdavis.net Mon May 31 10:31:38 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 31 May 2010 08:31:38 -0600 Subject: Question about permutations (itertools) In-Reply-To: References: Message-ID: On Mon, May 31, 2010 at 8:17 AM, Xavier Ho wrote: > >> >>> list(combinations_with_replacement('01',3)) >> ('0', '0', '0') >> ('0', '0', '1') >> ('0', '1', '1') >> ('1', '1', '1') >> >> Is it possible to get combinations_with_replacement to return numbers >> rather than strings? (see above) > >>>> list(combinations_with_replacement(range(0,2), 3)) > [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] Thanks, for some reason I didn't combinations_with_replacement took a list as an argument. > Hopefully that'll give you some ideas. > > Cheers, > Xav From dickinsm at gmail.com Mon May 31 11:03:43 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 31 May 2010 08:03:43 -0700 (PDT) Subject: Question about permutations (itertools) References: Message-ID: <46baf97c-a31d-4e5b-888d-682e8da76153@f13g2000vbm.googlegroups.com> On May 31, 3:04?pm, Vincent Davis wrote: > For example If I want all possible ordered lists of 0,1 of length 3 > (0,0,0) > (0,0,1) > (0,1,1) > (1,1,1) > (1,0,1) > (1,1,0) > (1,0,0) > I don't see a way to get this directly from the itertools. But maybe I > am missing something. In this case, you're missing itertools.product: >>> list(itertools.product([0, 1], repeat=3)) [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] -- Mark From eckhardt at satorlaser.com Mon May 31 11:05:23 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 31 May 2010 17:05:23 +0200 Subject: Question about permutations (itertools) References: Message-ID: Vincent Davis wrote: > I am looking for the most efficient (speed) way to produce an an > iterator to of permutations. > One of the problem I am having it that neither combinations nor > permutations does not exactly what I want directly. > For example If I want all possible ordered lists of 0,1 of length 3 > (0,0,0) > (0,0,1) > (0,1,1) > (1,1,1) > (1,0,1) > (1,1,0) > (1,0,0) > I don't see a way to get this directly from the itertools. But maybe I > am missing something. I see ways to get a bigger list and then remove > duplicates. You have three digits where each digit can have two values (binary digits, a.k.a. bits), so the number of combinations is 2*2*2 = 8. Even if the possible values where unevenly distributed, you could calculate the number of combinations by multiplying. Then, there are two different approaches: 1. count with an integer and then dissect into digits # Note: Using // for integer division in Python3! digit0 = n % base0 digit1 = (n // base0) % base1 digit2 = (n // base0 // base1) % base2 2. simulate digits and detect overflow Here you simply count up the "ones" and if they overflow, you reset them to zero and count up the "tens". What I don't really understand is what you mean with "ordered lists". Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From python.list at tim.thechases.com Mon May 31 11:07:02 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 May 2010 10:07:02 -0500 Subject: parsing question In-Reply-To: References: Message-ID: <4C03D096.5040204@tim.thechases.com> On 05/31/2010 08:42 AM, Mag Gam wrote: > I have a file with bunch of nfsstat -c (on AIX) which has all the > hostnames, for example ... > Is there a an easy way to parse this file according to each host? > > So, > r1svr.Connectionless.calls=6553 > r1svr.Connectionless.badcalls=0 > > and so on... > > > I am currently using awk which I am able to get what I need, but > curious if in python how people handle block data. Since you already profess to having an awk solution, I felt it was okay to at least take a stab at my implementation (rather than doing your job for you :). Without a complete spec for the output, it's a bit of guesswork, but I got something fairly close to what you want. It uses nested dictionaries which mean the keys and values have to be referenced like servers["r1svr"]["connectionless"]["calls"] and the values are strings (I'm not sure what you want in the case of the data that has both a value and percentage) not ints/floats/percentages/etc. That said, this should get you fairly close to what you describe: ########################################### import re header_finding_re = re.compile(r'\b\w{2,}') version_re = re.compile(r'^Version (\d+):\s*\(.*\)$', re.I) CLIENT_HEADER = 'Client ' CONNECTION_HEADER = 'Connection' servers = {} server = client = orig_client = subtype = None source = file('data.txt') for line in source: line = line.rstrip('\r\n') if not line.strip(): continue if line.startswith('='*5) and line.endswith('='*5): server = line.strip('=') client = orig_client = subtype = None elif line.startswith(CLIENT_HEADER): orig_client = client = line[len(CLIENT_HEADER):-1] subtype = 'all' elif line.startswith(CONNECTION_HEADER): subtype = line.replace(' ', '').lower() else: # it's a version or header row m = version_re.match(line) if m: subtype = "v" + m.group(1) else: if None in (server, client, subtype): print "Missing data", repr((server, client, subtype)) continue dest = servers.setdefault(server, {} ).setdefault(client, {} ).setdefault(subtype, {}) data = source.next() row = header_finding_re.finditer(line) prev = row.next() for header in row: key = prev.group(0) value = data[prev.start():header.start()].strip() prev = header dest[key] = value key = prev.group(0) value = data[prev.start():].strip() dest[key] = value for server, clients in servers.items(): for client, subtypes in clients.items(): for subtype, kv in subtypes.items(): for key, value in kv.items(): print ".".join([server, client, subtype, key]), print '=', value ########################################### Have fun, -tkc From razieh.eskandari at gmail.com Mon May 31 11:56:23 2010 From: razieh.eskandari at gmail.com (eskandari) Date: Mon, 31 May 2010 08:56:23 -0700 (PDT) Subject: writing numbers in binary file Message-ID: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Hi, I am a newbie in python. I have an data.pickle file which is serialized form of an "array of strings", I want to write their offsets in another binary file, so an C++ program can read and analyse them. But when I try to write offset (number) in binary file, it raise exception below in line "offsetfile.write(offset)" "TypeError: argument 1 must be string or read-only buffer, not int" I search the internet, find that all suggest converting number to string ---with str()---and then write string to file. But I shouldn't do this. because the above mentioned C++ function, read file with this assumption that there are numbers in file. So I want to know, Is there any way to produce an binary file containing numbers same as the way C++ does? Can anybody help me? Thanks a lot. From cde3 at live.com Mon May 31 11:58:16 2010 From: cde3 at live.com (Sandy Ydnas) Date: Mon, 31 May 2010 20:58:16 +0500 Subject: where are the program that are written in python? In-Reply-To: <1c5ea366-a909-4da7-ab7a-fe30542ebfab@a27g2000prj.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com>, <85rfa9Fv65U1@mid.individual.net>, <1c5ea366-a909-4da7-ab7a-fe30542ebfab@a27g2000prj.googlegroups.com> Message-ID: http://en.wikipedia.org/wiki/List_of_Python_software List of Python software >From Wikipedia, the free encyclopedia Jump to:navigation, search This article needs additional citations for verification. Please help improve this article by adding reliable references. Unsourced material may be challenged and removed. (March 2008) The Python programming language is actively used by many people, both in industry and academia for a wide variety of purposes. Contents[hide] 1 Integrated development environments 2 Applications 3 Web Applications 4 Video games 5 Web frameworks 6 Graphics frameworks 7 GUI frameworks 8 Scientific packages 9 Mathematical libraries 10 Additional development packages 11 Embedded as a scripting language 12 Commercial uses 13 Python implementations 14 References 15 External links [edit] Integrated development environments Boa Constructor, a cross-platform IDE for Python development EasyEclipse, an open source IDE for Python and other languages Eric, an IDE for Python and Ruby PIDA, open source IDE written in Python capable of embedding other text editors, such as Vim Stani's Python Editor (SPE), a cross-platform IDE for Python development Webware for Python, a suite of programming tools for constructing web-based applications in Python Wing IDE, an IDE for Python NetBeans, is written in Java and runs everywhere where a JVM is installed. [edit] Applications Anki, a spaced repetition flashcard program Bazaar, a free distributed revision control system BitTorrent, original client, along with several derivatives BuildBot, a continuous integration system Calibre, an open source e-book management tool Chandler, a personal information manager including calendar, email, tasks and notes support that is currently under development Decibel Audio Player, an open source audio player Deluge, a BitTorrent client for GNOME emesene, a MSN/WLM substitute Exaile, an open source audio player Gajim, an instant messaging client for the XMPP protocol GRAMPS, an open source genealogy software Gwibber, a microblogging client Impressive (ex. KeyJnote), a presentation software Juice, a popular podcast downloader Mercurial a cross-platform, distributed source management tool Miro, a cross-platform internet television application Morpheus, file-sharing client/server software operated by the company StreamCast MusicBrainz Picard, a cross-platform MusicBrainz tag editor Nicotine, a PyGTK Soulseek client OpenLP, lyrics projection software OpenShot Video Editor PiTiVi, a non-linear video editor Portage, the heart of Gentoo Linux, an advanced package management system based on the BSD-style ports system Quake Army Knife, an environment for developing 3D maps for games based on the Quake engine Resolver One, a spreadsheet Sage (sagemath) combines more than 20 main opensource math packages and provides easy to use web interface with the help of Python SCons, a tool for building software Ubuntu Software Center, a graphical package manager, installed by default in Ubuntu 9.10 and higher Wammu, a mobile phone management utility Wicd, a network manager for Linux YUM, a package management utility for RPM-compatible Linux operating systems [edit] Web Applications ERP5, a powerful open source ERP / CRM used in Aerospace, Apparel, Banking and for e-government GNU Mailman, one of the more popular packages for running email mailing lists MoinMoin, a popular wiki engine Planet, a feed aggregator Plone, a user-friendly and powerful open source content management system Projectplace, Europe?s Leading Online Service for Project Collaboration Roundup, a bug tracking system ViewVC, a web-based interface for browsing CVS and SVN repositories Trac, web-based bug/issue tracking database, wiki, and version control front-end MediaCore Video CMS is an open source media focused content management system. [edit] Video games Civilization IV uses Python for most of its tasks Battlefield 2 uses Python for all of its addons and a lot of its functionality Eve Online uses Stackless Python Freedom Force Frets on Fire uses Python and Pygame The Temple of Elemental Evil, a computer role-playing game based on the classic Greyhawk Dungeons & Dragons campaign setting Vampire: The Masquerade ? Bloodlines, a computer role-playing game based on the World of Darkness campaign setting Vega Strike, an open source space simulator [edit] Web frameworks CherryPy, an object-oriented web application server and framework Django, an MVC (model, view, controller) web framework Pylons, a lightweight web framework emphasizing flexibility and rapid development Quixote, a framework for developing Web applications in Python Topsite Templating System, another Python-powered web framework TurboGears, a web framework combining CherryPy, SQLObject, and Kid web2py, a full-stack enterprise web application framework, following the MVC design Zope, an application server, commonly used to build content management systems [edit] Graphics frameworks Pygame, Python bindings for SDL Pyglet, a cross-platform windowing and multimedia library for Python Python Imaging Library, a module for working with images Python-Ogre, a Python Language binding for the OGRE 3D engine Soya3D, a high-level 3D game engine for Python [edit] GUI frameworks PyGTK, a popular cross-platform GUI library based on GTK+; furthermore, other GNOME libraries also have bindings for Python PyQt, another cross-platform GUI library based on Qt; as above, KDE libraries have bindings too wxPython, a port of wxWidgets and a cross-platform GUI library for Python [edit] Scientific packages Biopython, a Python molecular biology suite SciPy, a library of scientific and numerical routines SimPy, a discrete-event simulation package stsci python, a library library of Python routines and C extensions that has been developed to provide a general astronomical data analysis infrastructure, developed by STScI [edit] Mathematical libraries matplotlib, an extension providing MATLAB-like plotting and mathematical functions NumPy, a language extension that adds support for large and fast, multi-dimensional arrays and matrices PyIMSL Studio is a Python distribution which includes the IMSL math and statistics Libraries from Visual Numerics (a Rogue Wave Software company) Sage Math is a large mathematical software application which integrates the work of nearly 100 free software projects and supports linear algebra, combinatorics, numerical mathematics, calculus, and more. SymPy, a computer algebra system [edit] Additional development packages Cheetah, a Python-powered template engine and code-generation tool IPython, a powerful development shell both written in and designed for Python Jinja, a Python-powered template engine, inspired by Django's template engine mod python, an Apache module allowing direct integration of Python scripts with the Apache web server PYthon Remote Objects, a Distributed Object Technology PyObjC, a Python-Objective C bridge that allows one to write Mac OS X software in Python Twisted, a networking framework for Python [edit] Embedded as a scripting language Python is, or can be used as the scripting language in these software products. Amarok AMESim ArcGIS, a prominent GIS platform, allows extensive modelling using Python Autodesk Softimage (formerly Softimage|XSI) Blender Boxee, a cross-platform home theater PC software Corel Paint Shop Pro DSHub Epiphany EventScripts, plugin for Valve's Source engine gedit GIMP GNAT The GNAT programming chain tool (Ada language implementation in GNU gcc), as a GNATcoll reusable components for the applications (with or without PyGTK) and as a scripting language for the commands in the GPS programming environment Inkscape Autodesk Maya (version 8.5 and newer only) Modo Nuke (compositing for visual effects) Poser, a 3D rendering and animation software program, that uses for scripting a special dialect of Python, called PoserPython PyMOL, a popular molecular viewer that embeds Python for scripting and integration QGIS uses Python for scripting and plugin-development Rhythmbox Scribus SPSS statistical software SPSS Programmability Extension allows users to extend the SPSS command syntax language with Python Totem, a media player for the GNOME desktop environment Vim VisIt WeeChat, a console IRC client [edit] Commercial uses CCP hf uses Stackless Python in both its server and client side applications for its MMO Eve Online[1] Google uses Python for many tasks including the backends of web apps such as Google Groups, Gmail, and Google Maps, as well as for some of its search-engine internals Autodesk Maya, professional 3D modeler allows Python scripting as an alternative to MEL as of version 8.5 NASA is using Python to implement a CAD/CAE/PDM repository and model management, integration, and transformation system which will be the core infrastructure for its next-generation collaborative engineering environment[citation needed] reddit was originally written in Common Lisp, but was rewritten in Python in 2005[2] Yahoo! Groups uses Python "to maintain its discussion groups" YouTube uses Python "to produce maintainable features in record times, with a minimum of developers"[3] [edit] Python implementations CPython - the reference implementation IronPython - Python for .NET and Mono platforms Jython - Python coded in Java Parrot - virtual machine being developed mainly as the runtime for Perl 6, but with the intent to also support dynamic languages like Python, Ruby, Tcl, etc. Psyco - not an implementation, but JIT compiler for CPython PyPy - Python coded in Python Stackless Python - Python with coroutines Unladen Swallow - the Python implementation from the Google team [edit] References ^ http://www.eve-online.com/faq/faq_07.asp ^ http://blog.reddit.com/2005/12/on-lisp.html ^ http://www.python.org/about/quotes > From: wuwei23 at gmail.com > Subject: Re: where are the program that are written in python? > Date: Sun, 23 May 2010 22:29:12 -0700 > To: python-list at python.org > > Gregory Ewing wrote: > > I came across a game on Big Fish Games recently (it was > > "The Moonstone" IIRC) that appeared to have been built using > > Python and py2app. > > Python tends to be used more for scripting internal game logic than > for every aspect of a game (which is, IMO, the right way to go about > it). It's not a huge list of commercial games that does this[1], but > it's a fairly classy one :) > > 1: http://en.wikipedia.org/wiki/Category:Python-scripted_video_games > -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Hotmail: Trusted email with Microsoft?s powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Mon May 31 12:30:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 31 May 2010 17:30:25 +0100 Subject: writing numbers in binary file In-Reply-To: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> References: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Message-ID: <4C03E421.3020407@mrabarnett.plus.com> eskandari wrote: > Hi, > I am a newbie in python. I have an data.pickle file which is > serialized form of an "array of strings", I want to write their > offsets in another binary file, so an C++ program can read and analyse > them. > But when I try to write offset (number) in binary file, it raise > exception below in line "offsetfile.write(offset)" > "TypeError: argument 1 must be string or read-only buffer, not int" > > I search the internet, find that all suggest converting number to > string ---with str()---and then write string to file. > But I shouldn't do this. because the above mentioned C++ function, > read file with this assumption that there are numbers in file. > So I want to know, Is there any way to produce an binary file > containing numbers same as the way C++ does? > Can anybody help me? > You can't write ints to a file, but you can write bytestrings ('str' in Python 2, 'bytes' in Python 3). Use the 'struct' module to convert the int to a bytestring, and remember to open the file as a binary file. From nagle at animats.com Mon May 31 12:40:18 2010 From: nagle at animats.com (John Nagle) Date: Mon, 31 May 2010 09:40:18 -0700 Subject: Python vs. Fedora and CentOS In-Reply-To: References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <3RMMn.125235$y07.3938@news.usenetserver.com> Message-ID: <4c03e090$0$1584$742ec2ed@news.sonic.net> Philip Semanchuk wrote: > Hi Jason, > CentOS is based on RHEL SRPMs. How could it ship a more advanced version > of Python than RHEL? > > I have CentOS 5.4 installed, and it only offers Python 2.4.3. > > And distrowatch.org backs this up -- the latest Python available for > Centos 5.x is 2.4: > http://distrowatch.com/table.php?distribution=centos Shared hosting services mostly run CentOS or RHEL; there's a trend away from running Fedora Core. So if you want to do anything in Python that is intended to run on shared hosting, you have to target Python 2.4. I have a dedicated server for a big site; there I can build and install later Python versions. That's not the problem. It's the little sites, ones not big enough to need their own dedicated server or virtual machine, where it's difficult to run Python. The current RHEL beta has Python 2.6, and that should be out this year. Hosting providers should start cutting over to it in 2011. RHEL and CentOS have a 7-year life cycle. So we can expect mainstream availability of Python 2.6 from 2011 to 2018. John Nagle From python.list at tim.thechases.com Mon May 31 12:42:18 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 May 2010 11:42:18 -0500 Subject: writing numbers in binary file In-Reply-To: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> References: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Message-ID: <4C03E6EA.80602@tim.thechases.com> On 05/31/2010 10:56 AM, eskandari wrote: > But when I try to write offset (number) in binary file, it raise > exception below in line "offsetfile.write(offset)" > "TypeError: argument 1 must be string or read-only buffer, not int" > > I search the internet, find that all suggest converting number to > string ---with str()---and then write string to file. > But I shouldn't do this. because the above mentioned C++ function, > read file with this assumption that there are numbers in file. > So I want to know, Is there any way to produce an binary file > containing numbers same as the way C++ does? Well, you have at least two options: 1) use the pack/unpack functions in the "struct" module to convert a number to a byte representation that you can then write to a file 2) write the number to the file as a string and then use C++ libraries to parse a number from a string. In both cases, you have to consider what happens when the number is outside the bounds of your C++ data-type (you don't mention what you're using...an int, a long, or "long long"; signed vs. unsigned). Additionally in the first case, you have to make sure that your memory-architecture (big-endian vs. little-endian) matches on both sides; or that you marshal the data through a pre-defined format (in libraries, commonly called "network" format). For such reasons, I'd stick with method #2 unless you have a strong reason not to. -tkc From razieh.eskandari at gmail.com Mon May 31 12:43:02 2010 From: razieh.eskandari at gmail.com (eskandari) Date: Mon, 31 May 2010 09:43:02 -0700 (PDT) Subject: writing numbers in binary file References: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Message-ID: On May 31, 12:30?pm, MRAB wrote: > eskandari wrote: > > Hi, > > I am a newbie in python. I have an data.pickle file which is > > serialized form of an "array of strings", I want to write their > > offsets in another binary file, so an C++ program can read and analyse > > them. > > But when I try to write offset (number) in binary file, it raise > > exception below in line ?"offsetfile.write(offset)" > > "TypeError: argument 1 must be string or read-only buffer, not int" > > > I search the internet, find that all suggest converting number to > > string ---with str()---and then write string to file. > > But I shouldn't do this. because the above mentioned C++ function, > > read file with this assumption that there are numbers in file. > > So I want to know, Is there any way to produce an binary file > > containing numbers same as the way C++ does? > > Can anybody help me? > > You can't write ints to a file, but you can write bytestrings ('str' in > Python 2, 'bytes' in Python 3). > > Use the 'struct' module to convert the int to a bytestring, and remember > to open the file as a binary file. Thanks alot, I have an question, if I do so, Will the second program (C++ program) which process this file, encounter any problem while parsing the file? It find number of integers by filelen/4 and ..... (It assumes that file was created as the same way which C++ does) Thanks in advance From ronyekr at gmail.com Mon May 31 13:00:27 2010 From: ronyekr at gmail.com (ekr3d) Date: Mon, 31 May 2010 10:00:27 -0700 (PDT) Subject: Do you want the safety of the computer ? Message-ID: Do you want the safety of the computer? Take this gift Advanced SystemCare Free 3.3.1 http://free-ekramy.blogspot.com From arndt.roger at addcom.de Mon May 31 13:04:42 2010 From: arndt.roger at addcom.de (Arndt Roger Schneider) Date: Mon, 31 May 2010 19:04:42 +0200 Subject: Python and Tkinter Programming by John Grayson References: <0738732e-d8df-469d-be4a-3699f4fd5f64@j14g2000yqm.googlegroups.com> <801d251d-ae12-4ce6-95a1-58f594cd2f81@p8g2000yqb.googlegroups.com> <4B4F96D6.2070905@codebykevin.com> <326dc723-3909-4293-9bf6-48a367b9251c@e16g2000yqc.googlegroups.com> <4B58FCDF.4000402@stoneleaf.us> <81dfc$4c011eaa$4275d90a$28590@FUSE.NET> Message-ID: Pradeep B schrieb: >On Sat, May 29, 2010 at 7:33 PM, Kevin Walzer wrote: > > > >>Tkinter doesn't wrap native printing API's. There are a few extensions that >>do it, but they are platform specific and not complete. >> >>The usual ways of printing are like this: >> >>1. If you're outputting data from the text widget, write that to a temporary >>text file and print via lpr. >> >>2. If you're outputting data from the canvas, write that to a temporary >>postscript file and print via lpr. >> >>This is on Unix/MacOS. Not sure what the equivalent API on Windows is. >> >>--Kevin >> >>-- >>Kevin Walzer >>Code by Kevin >>http://www.codebykevin.com >>-- >>http://mail.python.org/mailman/listinfo/python-list >> >> >> > > >Thanx Kevin. > >Anybody can throw light on how to do the same in Windows ? > >-pradeep > > > > The conventional --crude-- way is to take the bitmap of a window and to stretchDIBBitBlt it onto the printer device in windows and osx. Native printer dialogs do exist for both platforms ... When you do not need a printer dialog: Convert the Tk-GUI to SVG, then wrap it into a fo-xml wrapper --fo accepts inline SVG-- and use fop for printing. This approach works cross-platform, albeit you need a Java intallation (fop is a Java application). You can use http://jeszra.sourceforge.net to generate SVG for a complete Tk-GUI. In addition. there is a python/tkinter SVG export project for the Tk canvas --search the tkinter wiki. -roger From mlsngac at gmail.com Mon May 31 13:16:22 2010 From: mlsngac at gmail.com (M L) Date: Mon, 31 May 2010 10:16:22 -0700 (PDT) Subject: passing external data to web forms Message-ID: <9afd92f6-0780-4773-994c-8db303f64f52@a20g2000vbc.googlegroups.com> (Note: If you just skim this and can tell me how to pass data from an external program to a web form, that's all I need, and the rest is just what I'd like to have.) This is probably extremely simple when you know what you're doing. I figured I'd see if I could find a kind soul who could give me some code samples. Here's what I need to do: 1. Receive email via IMAP-IDLE 2. Parse the email to see if it contains certain text 3. Open a browser window with the following variables based on what that text is a. URL b. username c. password Specifically, I'm needing to login to a particular website, and which username I use varies based on it being specified in the email. I tried to do this with a combination of message filters in Thunderbird and command line arguments in Firefox, but it can't quite do everything I need. My real problem is how to get the username and password passed to the browser. Also, you should know that the server to which I'm connecting is a site to which I subscribe, not my own, so I can't run anything sever-side. Also, if possible, having this just fill whatever the first html form field it comes to with the username and the second with the password would be great, though not necessary if that's significantly more complicated than it filling them based on a specific name. I don't anticipate the site changing the names of those fields, but I'd like to not have to redo the code if it does. Finally, and again just a preference not a requirement, I feel that it would be easier to have an external file that stores the usernames and passwords that could be referenced to load them based on the email contents rather than having the usernames and passwords hardcoded. However, I'm only needing about half a dozen, so if it's significantly simpler, I'll go with that. Thanks for any help! -ML From tjreedy at udel.edu Mon May 31 13:23:15 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 May 2010 13:23:15 -0400 Subject: writing numbers in binary file In-Reply-To: References: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Message-ID: On 5/31/2010 12:43 PM, eskandari wrote: > On May 31, 12:30 pm, MRAB wrote: >> eskandari wrote: >> Use the 'struct' module to convert the int to a bytestring, and remember >> to open the file as a binary file. > > Thanks alot, > I have an question, if I do so, Will the second program (C++ program) > which process this file, encounter any problem while parsing the file? > It find number of integers by filelen/4 and ..... (It assumes that > file was created as the same way which C++ does) Tim Chase pretty well answered this. If you are not familiar with the problem of 'endianess', see http://en.wikipedia.org/wiki/Endianess From pavel.mba.du at gmail.com Mon May 31 13:26:15 2010 From: pavel.mba.du at gmail.com (Pavel Haque) Date: Mon, 31 May 2010 10:26:15 -0700 (PDT) Subject: Windows and Linux Tips Message-ID: Hi Friends, For Windows and Linux Tips, Please Visit: www.windowsandlinuxtips.blogspot.com From gabriele.lanaro at gmail.com Mon May 31 14:47:59 2010 From: gabriele.lanaro at gmail.com (Gabriele Lanaro) Date: Mon, 31 May 2010 20:47:59 +0200 Subject: Problems with relative imports and pep 366 Message-ID: <1275331679.3204.1.camel@eulero-desktop> I've yet asked this question on SO, I'll copy the contents: I have a "canonical file structure" like that (I'm giving sensible names to ease the reading): mainpack/ __main__.py __init__.py - helpers/ __init__.py path.py - network/ __init__.py clientlib.py server.py - gui/ __init__.py mainwindow.py controllers.py In this structure, for example modules contained in each package may want to access the helpers utilities through relative imports in something like: # network/clientlib.py from ..helpers.path import create_dir The program is runned "as a script" using the __main__.py file in this way: python mainpack/ Trying to follow the PEP 366 I've put in __main__.py these lines: ___package___ = "mainpack" from .network.clientlib import helloclient But when running: $ python mainpack Traceback (most recent call last): File "/usr/lib/python2.6/runpy.py", line 122, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.6/runpy.py", line 34, in _run_code exec code in run_globals File "path/mainpack/__main__.py", line 2, in from .network.clientlib import helloclient SystemError: Parent module 'mainpack' not loaded, cannot perform relative import What's wrong? What is the correct way to handle and effectively use relative imports? I've tried also to add the current directory to the PYTHONPATH, nothing changes. link: http://stackoverflow.com/questions/2943847/nightmare-with-relative-imports-how-does-pep-366-work From aahz at pythoncraft.com Mon May 31 14:55:09 2010 From: aahz at pythoncraft.com (Aahz) Date: 31 May 2010 11:55:09 -0700 Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: In article <5a3a5737-f1b7-4419-9bb3-088c244a4760 at c13g2000vbr.googlegroups.com>, Carl Banks wrote: > >However, Aahz will be by shortly to tell you never to use slots. Please note that there is an important distinction between "don't use slots" and "never use slots" -- if you can locate any instances where I wrote the latter, I will be surprised and issue a retraction. Obviously, slots are an important element of Python, but they should be used only when other approaches have proven impractical. To quote Guido: __slots__ is a terrible hack with nasty, hard-to-fathom side effects that should only be used by programmers at grandmaster and wizard levels. Unfortunately it has gained an enormous undeserved popularity amongst the novices and apprentices, who should know better than to use this magic incantation casually. See also http://www.dalkescientific.com/writings/diary/archive/2006/03/19/class_instantiation_performance.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From naresh.ftp at gmail.com Mon May 31 15:19:08 2010 From: naresh.ftp at gmail.com (Naresh Kumar) Date: Mon, 31 May 2010 12:19:08 -0700 (PDT) Subject: DOWNLOAD FREE PALTALK LIVE VIDEO AND VOICE CHAT SOFTWARE Message-ID: <0a579e7a-042d-49d2-b7f2-3cea619e2107@40g2000pry.googlegroups.com> Download free here - http://bit.ly/auQHjB 4000+ VIDEO CHAT ROOMS 4 Million+ FRIENDLY USERS WORLDWIDE HOST YOUR OWN CAM SHOWS CONNECT WITH YOUR YAHOO/ICQ/AOL BUDDIES Download free here - http://bit.ly/auQHjB Thanks and Regards tony :) From lweberk at gmail.com Mon May 31 16:56:00 2010 From: lweberk at gmail.com (Leonhard Weber) Date: Mon, 31 May 2010 22:56:00 +0200 Subject: Spawning console and piping the stdout into it Message-ID: Hi, I'm stuck at a puzzle for quite some time. Situation: (Linux environment) I have a script that is invoked from an application (running my script as part of embedded python). I have no power over that application, only supply the script it executes. Now for development reasons I want that script to spawn a console and show me the output through there. Though there is the ugly way of writing to file and tailing it, it would be great if someone could come up with a cleaner version. The approach I've been taking is trying to start a child with the subprocess module and pipe the sys.stdoout into the stdin of the child... hummmm. No success so far. Thanks, ~lwk -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Mon May 31 17:15:05 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 01 Jun 2010 07:15:05 +1000 Subject: if, continuation and indentation In-Reply-To: References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> Message-ID: <4c042759$1@dnews.tpgi.com.au> On 05/31/10 05:10, Colin J. Williams wrote: > On 30-May-10 01:50 AM, Nathan Rice wrote: >> On 27-May-10 08:48 AM, Xavier Ho wrote: >> > On 27 May 2010 22:22, HH> > > >> wrote: >> >> > >> > if (width == 0 and >> > height == 0 and >> > color == 'red' and >> > emphasis == 'strong' or >> > highlight> 100): >> > raise ValueError("sorry, you lose") >> > >> > >> > I've gotta say - I've bumped into this problem before, >> and I'm sure many >> > other have - this is a valid question. It just hasn't >> bothered me enough >> > to ask... >> > >> > Correct me if I'm wrong, but I think the following is >> equivalent, and >> > looks better. Although this won't fix all ugly cases in >> that problem.. >> > >> > if (width, height, color, emphasis) == (0, 0, 'red', >> 'strong') or >> > highlight> 100: >> > raise ValueError("sorry, you lose") >> > >> > Cheers, >> > Xav >> >> but nobody commented. >> >> Colin W. >> >> >> Colin: >> Sure, you can do it that way. IMO, though, the OP was wrong, >> and so >> is the PEP. Source code is meant to communicate. So it must >> transmit >> the correct information to the computer; it also must inform your >> coworkers. That means that you have a responsibility to care >> what >> they think, though you privately have your opinions. Another >> reason >> the PEP is faulty in this circumstance is that a misplaced >> backslash, >> or a missing one, is easily found and fixed. A misplaced >> parentheses, >> or just one of a pair, will transform your source code into >> something >> which may compile and then give faulty results: a disaster. >> So keep it simple, and make it legible. >> Yours, >> John >> >> >> IMHO complete garbage, if your editor doesn't show misplaced or >> missing parenthesis by highlighting you're using the wrong editor :) >> >> > > Perhaps the arrangement below shows the matching a little better than > the Xav suggestion. The main point is that, to me, the tuple shows the > item by item matching better than a series of and clauses: > > # tif.py > > (width, height, color, emphasis)= 0, 0, 'red', 'strong' > highlight= 99 > if (width, height, color, emphasis) == \ > ( 0, 0, 'red', 'strong') or highlight> 100: > raise ValueError("sorry, you lose") How about: all(a == b for a,b in ((width, 0), (height, 0), (color, 'red'), (emphasis, 'strong')))) From python.list at tim.thechases.com Mon May 31 17:21:29 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 May 2010 16:21:29 -0500 Subject: passing external data to web forms In-Reply-To: <9afd92f6-0780-4773-994c-8db303f64f52@a20g2000vbc.googlegroups.com> References: <9afd92f6-0780-4773-994c-8db303f64f52@a20g2000vbc.googlegroups.com> Message-ID: <4C042859.5090805@tim.thechases.com> On 05/31/2010 12:16 PM, M L wrote: > Specifically, I'm needing to login to a particular website, > and which username I use varies based on it being specified > in the email. Are you in control of this email generation (that is, can you generate an email with an HTML form within, or is this email coming from a 3rd-party)? Creating an HTML-email with a form to submit the username/password isn't a flawless solution because many folks (self included) configure their mail-reader to only display plain-text and ignore HTML components. > My real problem is how to get the username and password > passed to the browser. If you can't create an HTML form in the source email, then it depends on what the web-server is expecting -- a GET (bad for users, good for you) or a POST (good web practice, but a pain for you). If the web login form is maldesigned and uses a GET submission, you can just parse the email body for the fields and generate a link of the form http://example.com/login?user=jsmith&pass=SeKrEt However, if the website creates expects a POST to login (good design so credentials don't get saved in history, or get bookmarked accidentally), then you have to either 1) do some dark browser-specific hackery, perhaps with a bit of urllib magic to kludge the session into an active browser. Not a particularly inviting solution to implement. 2) generate a temporary HTML file with the prepopulated form in it, point the browser at that page and either (2a) have the user click on the [submit] button, and/or (2b) have a little JavaScript that clicks the [submit] button (or calls form.submit() more likely) after the temp-page is loaded. I'd do both in the event the user has JS turned off in their browser (again, that'd be me, thanks to NoScript). This temporary HTML file could be scraped (via urllib) from the login url itself, or hard-coded if you expect it to be of the same format for each website. My crack at it looks something like ########################## from sys import exit, stderr from tempfile import NamedTemporaryFile import email import imaplib import os import re import time import urllib import webbrowser url_re = re.compile(r'\burl:\s*(http://.*)') user_re = re.compile(r'\buser(?:name)?:\s*(.*)') pass_re = re.compile(r'\bpass(?:word)?:\s*(.*)') class MissingField(Exception): pass IMAP = imaplib.IMAP4_SSL def get_email(host, username, password): # ... for message in messages_I_care_about: yield message def fields(msg): url_m = url_re.search(msg) if not url_m: raise MissingField("No URL") user_m = user_re.search(msg) if not user_m: raise MissingField("No username") pass_m = pass_re.search(msg) if not pass_m: raise MissingField("No password") return [m.group(1).strip() for m in (url_m, user_m, pass_m)] def create_temp_html(url, username, password): f = NamedTemporaryFile(mode='w', suffix='.html') # HTML hard-coded here, but could be # scraped from the site, parsed with BeautifulSoup # searched for the form/uname/pwd values # and more programatically generated # but this is the lazy version you get for free ;-) f.write(""" Some Title Hang on...time to log in...

""" % ( url, urllib.quote_plus(username), urllib.quote_plus(password), ) ) f.flush() return f if __name__ == "__main__": HOST = 'mail.example.com' USER = 'email_username at example.com' PASS = 'SecretEmailPassword' EXPECTED_SENDER = 'somebody at example.net' for message in get_email(HOST, USER, PASS): msg = email.message_from_string(message) # if you don't want to limit the sender # delete/comment the next 3 lines if EXPECTED_SENDER not in msg['from'].lower(): print "Unexpected sender...ignoring %r" % msg['subject'] continue for part in msg.walk(): # you may not want to skip HTML portions or other # MIME-types like attachments, but whatever if part.get_content_type() != 'text/plain': continue try: url, username, password = fields(msg.get_payload()) print url, username, password except MissingField, e: print e continue f = create_temp_html(url, username, password) stderr.write( "Opening %r in %s\n" % (f.name, webbrowser.get().basename.title())) webbrowser.open(f.name) time.sleep(30) # wait for the browser to load the file # otherwise this .close() will delete it # before the web-browser could open it f.close() ########################## Adjust regexps to find your URL/uname/pwd as desired, create the get_email() iterator that finds all the messages in your inbox that match your criteria (such as "not already seen, has XYZ in the subject, etc") I'm not 100% sure of my JavaScript in the form.onload but you can also tweak that if your JS is enabled and you want to tinker with it for auto-login. -tkc From aahz at pythoncraft.com Mon May 31 17:37:53 2010 From: aahz at pythoncraft.com (Aahz) Date: 31 May 2010 14:37:53 -0700 Subject: Vote to Add Python Package "pubsub" to the Python Standard Library References: <6b9d2898-4166-40b4-9016-dc55dee77d00@q33g2000vbt.googlegroups.com> Message-ID: In article <6b9d2898-4166-40b4-9016-dc55dee77d00 at q33g2000vbt.googlegroups.com>, Tom wrote: > >I vote for adding the Python package "pubsub" to the Python standard >library. It has recently been added to wxpython (replacing the old >wx.lib.pubsub package), but it has application to non-gui programs as >well. You should create a ticket on bugs.python.org -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From breamoreboy at yahoo.co.uk Mon May 31 17:38:42 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 31 May 2010 22:38:42 +0100 Subject: xrange issue 7721 In-Reply-To: <4C0371CB.401@v.loewis.de> References: <4C02EC98.9020507@v.loewis.de> <4c02f5fa$0$14140$c3e8da3@news.astraweb.com> <4C0371CB.401@v.loewis.de> Message-ID: On 31/05/2010 09:22, Martin v. Loewis wrote: >>> For the record, the issue you were looking at was a complaint that the >>> documentation is incorrect. This had been fixed by correcting the >>> documentation. >> >> I think Mark's point is that the code snippet given isn't a full >> replacement for xrange, since it doesn't support negative step sizes, nor >> does it raise an exception on step=0. > > Still, that issue is different from 7721. 7721 was about a > completely-nonworking example in the documentation. This error has been > fully > corrected. So this issue *is* fixed, reopining it would be > inappropriate. > > There may be another issue with this example, which should be reported > separately. > >> Since the docs are read by people with vastly different levels of >> experience, skill and nous, I think it's a reasonable complaint to make. > > That may well be. The proposed approach (reopen the issue) is what I > consider unreasonable. > > Regards, > Martin Just forget it, if anyone falls foul of the garbage that has been put into the documentation, you can accept responsibility. Disgusted and offended. Mark Lawrence. From davea at ieee.org Mon May 31 18:39:52 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 31 May 2010 18:39:52 -0400 Subject: writing numbers in binary file In-Reply-To: References: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Message-ID: <4C043AB8.3040500@ieee.org> eskandari wrote: > On May 31, 12:30 pm, MRAB wrote: > >> eskandari wrote: >> >>> Hi, >>> I am a newbie in python. I have an data.pickle file which is >>> serialized form of an "array of strings", I want to write their >>> offsets in another binary file, so an C++ program can read and analyse >>> them. >>> But when I try to write offset (number) in binary file, it raise >>> exception below in line "offsetfile.write(offset)" >>> "TypeError: argument 1 must be string or read-only buffer, not int" >>> >>> I search the internet, find that all suggest converting number to >>> string ---with str()---and then write string to file. >>> But I shouldn't do this. because the above mentioned C++ function, >>> read file with this assumption that there are numbers in file. >>> So I want to know, Is there any way to produce an binary file >>> containing numbers same as the way C++ does? >>> Can anybody help me? >>> >> You can't write ints to a file, but you can write bytestrings ('str' in >> Python 2, 'bytes' in Python 3). >> >> Use the 'struct' module to convert the int to a bytestring, and remember >> to open the file as a binary file. >> > > Thanks alot, > I have an question, if I do so, Will the second program (C++ program) > which process this file, encounter any problem while parsing the file? > It find number of integers by filelen/4 and ..... (It assumes that > file was created as the same way which C++ does) > Thanks in advance > > You talk as if C++ has a single way to write a file, or read a file. It has dozens of possibilities, as does Python. In another message, you refer to four bytes per number, so it's possible you're talking about reading directly from the file into an int variable. If you know that the C++ program is reading a file in mode 'b' directly to an unsigned int, and is compiled in 32 bits, and has the same endian-ness as the Python program, chances are the struct will work correctly, if you're running Python under the same conditions. DaveA From cjwilliams43 at gmail.com Mon May 31 19:34:55 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Mon, 31 May 2010 19:34:55 -0400 Subject: if, continuation and indentation In-Reply-To: <4c042759$1@dnews.tpgi.com.au> References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> <4c042759$1@dnews.tpgi.com.au> Message-ID: On 31-May-10 17:15 PM, Lie Ryan wrote: > On 05/31/10 05:10, Colin J. Williams wrote: >> On 30-May-10 01:50 AM, Nathan Rice wrote: >>> On 27-May-10 08:48 AM, Xavier Ho wrote: >>> > On 27 May 2010 22:22, HH>> > >> >> wrote: >>> >>> > >>> > if (width == 0 and >>> > height == 0 and >>> > color == 'red' and >>> > emphasis == 'strong' or >>> > highlight> 100): >>> > raise ValueError("sorry, you lose") >>> > >>> > >>> > I've gotta say - I've bumped into this problem before, >>> and I'm sure many >>> > other have - this is a valid question. It just hasn't >>> bothered me enough >>> > to ask... >>> > >>> > Correct me if I'm wrong, but I think the following is >>> equivalent, and >>> > looks better. Although this won't fix all ugly cases in >>> that problem.. >>> > >>> > if (width, height, color, emphasis) == (0, 0, 'red', >>> 'strong') or >>> > highlight> 100: >>> > raise ValueError("sorry, you lose") >>> > >>> > Cheers, >>> > Xav >>> >>> but nobody commented. >>> >>> Colin W. >>> >>> >>> Colin: >>> Sure, you can do it that way. IMO, though, the OP was wrong, >>> and so >>> is the PEP. Source code is meant to communicate. So it must >>> transmit >>> the correct information to the computer; it also must inform your >>> coworkers. That means that you have a responsibility to care >>> what >>> they think, though you privately have your opinions. Another >>> reason >>> the PEP is faulty in this circumstance is that a misplaced >>> backslash, >>> or a missing one, is easily found and fixed. A misplaced >>> parentheses, >>> or just one of a pair, will transform your source code into >>> something >>> which may compile and then give faulty results: a disaster. >>> So keep it simple, and make it legible. >>> Yours, >>> John >>> >>> >>> IMHO complete garbage, if your editor doesn't show misplaced or >>> missing parenthesis by highlighting you're using the wrong editor :) >>> >>> >> >> Perhaps the arrangement below shows the matching a little better than >> the Xav suggestion. The main point is that, to me, the tuple shows the >> item by item matching better than a series of and clauses: >> >> # tif.py >> >> (width, height, color, emphasis)= 0, 0, 'red', 'strong' >> highlight= 99 >> if (width, height, color, emphasis) == \ >> ( 0, 0, 'red', 'strong') or highlight> 100: >> raise ValueError("sorry, you lose") > > How about: > > all(a == b for a,b in ((width, 0), (height, 0), (color, 'red'), > (emphasis, 'strong')))) You need to add "or highlight > 100" From sjmachin at lexicon.net Mon May 31 20:12:09 2010 From: sjmachin at lexicon.net (John Machin) Date: Mon, 31 May 2010 17:12:09 -0700 (PDT) Subject: Help with Regexp, \b References: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> <4b812698-4779-4502-8cdc-bf5c47dd5a0c@o39g2000vbd.googlegroups.com> Message-ID: <06964c58-d63a-4065-83fb-9b9e32047b3b@y6g2000pra.googlegroups.com> On May 30, 1:30?am, andrew cooke wrote: > > That's what I thought it did... ?Then I read the docs and confused > "empty string" with "space"(!) and convinced myself otherwise. ?I > think I am going senile. Not necessarily. Conflating concepts like "string containing whitespace", "string containing space(s)", "empty aka 0-length string", None, (ASCII) NUL, and (SQL) NULL appears to be an age- independent problem :-) From greg.ewing at canterbury.ac.nz Mon May 31 20:46:01 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 01 Jun 2010 12:46:01 +1200 Subject: GUI programs In-Reply-To: References: Message-ID: <86j303Fih6U1@mid.individual.net> jyoung79 at kc.rr.com wrote: > Has anyone had any luck getting > PyGUI working on Snow Leopard? I can't seem to get the blobedit > example to work. I've received reports that it seems to be problematic on Snow Leopard. Unfortunately I don't have access to a Snow Leopard system at the moment to troubleshoot it. -- Greg From steveo at syslang.net Mon May 31 20:51:02 2010 From: steveo at syslang.net (Steven W. Orr) Date: Mon, 31 May 2010 20:51:02 -0400 Subject: problem with Descriptors Message-ID: <4C045976.9010901@syslang.net> I just discovered descriptors but what I want to do isn't working right. I hope this isn't too long. :-( Here's what I have that works: class C(object): def g(self): print "dir(g):",dir(self.g) def f(self, ss): print "ss = ", ss cc = C() cc.ff = f.__get__(C,cc) cc.ff('Round 3') And when I run it, it prints out: ss = Round 3 That's the part that works. I'm trying to use the above construct to implement a new kind of dict(). The idea is that I want to create a dict that knows about certain values that can have dependencies on other values. If you change a value that is a dependency of another value within the dict, then the target value will automatically recompute itself. In the example below, the value of the key "range" is dependent on the value of the key "stop". When I run the code, the function recalc_range seems to be successfully saved as a bound method. (The save happens in AddDep) But then when I try to invoke the saved bound method, it yells at me that the arg to __getitem__ is of the wrong type. Does anyone see what I did wrong? class BalancedDict(dict): def __init__( self, initval={}, depDesc=None ): dict.__init__(self) self.target = [] self.deplist = [] self.recalc_f = [] self.addDep( depDesc ) if isinstance(initval, dict): dict.update(self, initval) def __setitem__(self, key, value): # setting a keyword dict.__setitem__(self, key, value) for ii, deps in enumerate(self.deplist): if key in deps: print '__setitem__:recalc_f[%d]'%ii,self.recalc_f[ii] print '__setitem__:targ:',self.target[ii] print '__setitem__:deplist:',self.deplist[ii] self.recalc_f[ii](self.target[ii],self.deplist[ii]) def addDep(self, depDesc=None): if not depDesc: return for jj in depDesc: self.target.append(jj[0]) self.deplist.append(jj[1]) self.recalc_f.append(None) idx = len(self.recalc_f) - 1 self.recalc_f[idx] = jj[2].__get__(BalancedDict, self) print 'addDep:self.recalc_f[%d]:'%idx, self.recalc_f[idx] if __name__ == "__main__": import pprint def recalc_range(self, target, deplist): print 'recalc_range:type(self):', type(self), "self:",self print 'recalc_range:target:', target print 'recalc_range:deplist:', deplist stop = None for ii in deplist: if ii == 'stop': print "ii:",ii print "self:", self, type(self) stop = self.__getitem__(ii) if ( isinstance( stop, int ) ): self.__setitem__( self[target], range( stop ) ) pp = pprint.PrettyPrinter() dd = BalancedDict() print 'dd: Init' pp.pprint(dd) dd.addDep([['range', ['stop'], recalc_range]]) dd['stop'] = 40 print 'dd: After start stop and step' pp.pprint(dd) C:\Users\Steve\Documents\PythonSamples>python -i vfunc3.py dd: Init {} addDep:self.recalc_f[0]: > __setitem__:recalc_f[0] > __setitem__:targ: range __setitem__:deplist: ['stop'] recalc_range:type(self): self: recalc_range:target: range recalc_range:deplist: ['stop'] ii: stop self: Traceback (most recent call last): File "vfunc3.py", line 55, in dd['stop'] = 40 File "vfunc3.py", line 20, in __setitem__ self.recalc_f[ii](self.target[ii],self.deplist[ii]) File "vfunc3.py", line 46, in recalc_range stop = self.__getitem__(ii) TypeError: descriptor '__getitem__' requires a 'dict' object but received a 'str' >>> -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From huangqiang.zhou at gmail.com Mon May 31 21:47:59 2010 From: huangqiang.zhou at gmail.com (huangqiang.zhou) Date: Tue, 1 Jun 2010 09:47:59 +0800 Subject: Error building on cygwin Message-ID: <201006010947536718608@gmail.com> Hi All: When i install wxPython on cygwin in windows xp, i get this error and can't continue... my enviroment: $ cygcheck -c cygwin Cygwin Package Information Package Version Status cygwin 1.7.5-1 Incomplete wxPython-src-2.8.11.0 Following the build instructions on www.wxpython.org, before the installing of wxPython i have installed additional packages as : autoconf automake gcc-core gcc-g++ gcc-mingw gcc-mingw-core gcc-mingw-g++ make mingw-runtime mingw-zlib patch w32api // i can't find this package when i am installing cygwin, so it was not be installed Then: i put the sourcecode to /usr/sr/wxPython-src-2.8.11.0 $cd /usr/sr/wxPython-src-2.8.11.0 $CC="gcc -mno-cygwin -mwindows" \ CXX="g++ -mno-cygwin -mwindows" \ LDFLAGS="-mno-cygwin -mwindows" \ ./configure \ --with-msw \ --build=i686-pc-mingw32 \ --prefix=/opt/wx/2.8 \ --enable-unicode \ --enable-debug \ --enable-debug_gdb \ --enable-geometry \ --enable-display \ --enable-shared \ --enable-optimise \ --with-expat=builtin \ --with-regex=builtin \ --with-zlib=builtin $make $* \ && make -C contrib/src/gizmos $* \ && make -C contrib/src/stc $* and then : ./src/msw/utils.cpp: In function ?const wxChar* wxGetHomeDir(wxString*)?: ./src/msw/utils.cpp:392: error: cannot convert ?const char*? to ?const wxChar *? for argument ?1? to ?wxChar* wxGetenv(const wxChar*)? ./src/msw/utils.cpp:408: warning: ?int cygwin_conv_to_full_win32_path(const cha r*, char*)? is deprecated (declared at /usr/include/sys/cygwin.h:52) ./src/msw/utils.cpp:408: error: cannot convert ?wxString? to ?const char*? f or argument ?1? to ?int cygwin_conv_to_full_win32_path(const char*, char*)? ./src/msw/utils.cpp: In function ?wxChar* wxGetUserHome(const wxString&)?: ./src/msw/utils.cpp:472: error: new declaration ?wxChar* wxGetUserHome(const wx String&)? ./include/wx/utils.h:528: error: ambiguates old declaration ?const wxWCharBuffe r wxGetUserHome(const wxString&)? make: *** [basedll_msw_utils.o] Error 1 please help! regards. 2010-06-01 huangqiang.zhou -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Sat May 1 00:29:05 2010 From: timr at probo.com (Tim Roberts) Date: Fri, 30 Apr 2010 21:29:05 -0700 Subject: winreg - access mask References: Message-ID: Richard Lamboj wrote: > >if i want to read, write a key and set a value, does i only need to set >KEY_WRITE, or does i need to set KEY_READ, KEY_WRITE and KEY_SET_VALUE? > >This questions is related to the OpenKey Function. You need KEY_READ|KEY_WRITE|KEY_SET_VALUE. Those constants are straight from the Windows API. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From pmaupin at gmail.com Sat May 1 01:08:14 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 30 Apr 2010 22:08:14 -0700 (PDT) Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: On Apr 30, 11:04?am, Jabapyth wrote: > At least a few times a day I wish python had the following shortcut > syntax: > > vbl.=func(args) > > this would be equivalent to > > vbl = vbl.func(args) > > example: > > foo = "Hello world" > foo.=split(" ") > print foo > # ['Hello', 'world'] > > and I guess you could generalize this to > > vbl.=[some text] > # > vbl = vbl.[some text] > > e.g. > > temp.=children[0] > # temp = temp.children[0] > > thoughts? First thought: good luck getting something like this through. Probably not going to happen, although I do find the idea very intriguing. Second thought: I don't like the proposed syntax at all. +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- place operator methods, actually) *modify* the lhs object. Your proposed .= syntax conceptually *replaces* the lhs object (actually, rebinds the lhs symbol to the new object). If this were to be deemed worthy of the language, I would think a better syntax would be something like: mystring = .upper() mystring = .replace('a', 'b') etc. The '=' shows clearly that mystring is being rebound to a new object. As Steven has shown, '.' functions as an operator, so if this change were accepted, in reality you would probably be able to write: mystring = . upper() mystring=.upper() or whatever. But the canonical form would probably be with a space before the period but not after. Regards, Pat From simonluijk at googlemail.com Sat May 1 02:03:30 2010 From: simonluijk at googlemail.com (Simon) Date: Sat, 1 May 2010 08:03:30 +0200 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: Hay I got a better idea. If you put two dots (..) on a line by itself it means execute the previous line again! On 1 May 2010 07:08, Patrick Maupin wrote: > On Apr 30, 11:04 am, Jabapyth wrote: > > At least a few times a day I wish python had the following shortcut > > syntax: > > > > vbl.=func(args) > > > > this would be equivalent to > > > > vbl = vbl.func(args) > > > > example: > > > > foo = "Hello world" > > foo.=split(" ") > > print foo > > # ['Hello', 'world'] > > > > and I guess you could generalize this to > > > > vbl.=[some text] > > # > > vbl = vbl.[some text] > > > > e.g. > > > > temp.=children[0] > > # temp = temp.children[0] > > > > thoughts? > > First thought: good luck getting something like this through. > Probably not going to happen, although I do find the idea very > intriguing. > > Second thought: I don't like the proposed syntax at all. > > +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- > place operator methods, actually) *modify* the lhs object. > > Your proposed .= syntax conceptually *replaces* the lhs object > (actually, rebinds the lhs symbol to the new object). > > If this were to be deemed worthy of the language, I would think a > better syntax would be something like: > > mystring = .upper() > mystring = .replace('a', 'b') > > etc. > > The '=' shows clearly that mystring is being rebound to a new object. > > As Steven has shown, '.' functions as an operator, so if this change > were accepted, in reality you would probably be able to write: > > mystring = . upper() > mystring=.upper() > > or whatever. But the canonical form would probably be with a space > before the period but not after. > > Regards, > Pat > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Sat May 1 02:27:46 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 01 May 2010 08:27:46 +0200 Subject: Ignoring XML Namespaces with cElementTree In-Reply-To: References: <9527079b-92bf-4c59-af2b-ab2c84029f55@h37g2000pra.googlegroups.com> Message-ID: dmtr, 30.04.2010 23:59: >> I think that's your main mistake: don't remove them. Instead, use the fully >> qualified names when comparing. > > Yes. That's what I'm forced to do. Pre-calculating tags like tagChild > = "{%s}child" % uri and using them instead of "child". Exactly. Keeps you from introducing typos in your code. And keeps you from having to deal with namespace-prefix mappings. Big features. > As a result the > code looks ugly and there is extra overhead concatenating/comparing > these repeating and redundant prefixes. The overhead is really small, though. In many cases, a pointer comparison will do. > I don't understand why > cElementTree forces users to do that. So far I couldn't find any way > around that without rebuilding cElementTree from source. Then don't do it. > Apparently somebody hard-coded the namespace_separator parameter in > the cElementTree.c (what a dumb thing to do!!!, it should have been a > parameter in the cElementTree.XMLParser() arguments): > =========== > self->parser = EXPAT(ParserCreate_MM)(encoding,&memory_handler, "}"); > =========== > > Simply replacing "}" with NULL gives me desired tags without stinking > URIs. You should try to calm down and embrace this feature. Stefan From shashank.sunny.singh at gmail.com Sat May 1 02:31:56 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Sat, 1 May 2010 12:01:56 +0530 Subject: No subject In-Reply-To: <20100501033354.30222.qmail@f4mail-234-119.rediffmail.com> References: <20100501033354.30222.qmail@f4mail-234-119.rediffmail.com> Message-ID: Here is my quick take on it using re import re strings = ["1 ALA Helix Sheet Helix Coil", "2 ALA Coil Coil Coil Sheet", "3 ALA Helix Sheet Coil Turn", "4 ALA Helix Sheet Helix Sheet"] regex = re.compile(r" (.+?\b)(?=.*\1)") for s in strings: moreThanOnce = list(set(regex.findall(s))) count = len(moreThanOnce) if count == 1: print moreThanOnce[0] elif count == 2: print "doubtful" else: print "error" Although this is short, its probably not the most efficient. A more verbose and efficient version would be for s in strings: l = s.split()[2:] counts = {} for ss in l: if counts.has_key(ss): counts[ss] += 1 else: counts[ss] = 1 filtered = [ss for ss in counts if counts[ss] >= 2] filteredCount = len(filtered) if filteredCount == 1: print filtered[0] elif filteredCount > 1: print "doubtful" else: print "error" HTH On Sat, May 1, 2010 at 9:03 AM, mannu jha wrote: > Dear all, > > I am trying my problem in this way: > > import re > expr = re.compile("Helix Helix| Sheet Sheet| Turn Turn| Coil Coil") > f = open("CalcSecondary4.txt") > for line in f: > if expr.search(line): > print line > > but with this it is printing only those line in which helix, sheet, turn > and coil are coming twice. Kindly suggest how should I modify it so that > whatever secondary structure is coming more than or equal to two times it > should write that as final secondary structure and if two seconday structure > are coming two-two times in one line itself like: > > 4 ALA Helix Sheet Helix Sheet > > then it should write that as doubtful and rest it should write as error. > > Thanks, > > > Dear all, > > I have a file like: > > 1 ALA Helix Sheet Helix Coil > 2 ALA Coil Coil Coil Sheet > 3 ALA Helix Sheet Coil Turn > > now what I want is that write a python program in which I will put the > condition that in each line whatever secondary structure is coming more than > or equal to two times it should write that as final secondary structure and > if two seconday structure are coming two-two times in one line itself like: > > 4 ALA Helix Sheet Helix Sheet > > then it should write that as doubtful and rest it should write as error. > > Thanks, > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From bestomegawatch at yahoo.com Sat May 1 03:18:33 2010 From: bestomegawatch at yahoo.com (Jack) Date: Sat, 1 May 2010 15:18:33 +0800 Subject: External Hashing [was Re: matching strings in a large set of strings] References: <840jkoFaibU1@mid.dfncis.de> Message-ID: http://www.swizwatch.com/ All Cartier replica watches sold at Hotwristwatch.com are brand-new and high quality. Each Cartier Replica Watch produced is examined carefully by our quality test department and each watch is inspected again before being sent to our customer. It is our desire that you do experience the joy of shopping when buying one of our Cartier Replica Watches at our site. Some Cartier Watches may need to be special ordered, please call for availability on Cartier watches. Best service you will receive from us. "Helmut Jarausch" ??????:840jkoFaibU1 at mid.dfncis.de... >I think one could apply an external hashing technique which would require >only > very few disk accesses per lookup. > Unfortunately, I'm now aware of an implementation in Python. > Does anybody know about a Python implementation of external hashing? > > Thanks, > Helmut. > > -- > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany From onlinejobsatfreetime at gmail.com Sat May 1 04:10:27 2010 From: onlinejobsatfreetime at gmail.com (online jobs) Date: Sat, 1 May 2010 01:10:27 -0700 (PDT) Subject: Online survey jobs & data entry jobs Message-ID: <8ff9c401-815f-4abb-b573-3ddae2f858de@n37g2000prc.googlegroups.com> http://teluguscope.com/job.html http://teluguscope.com/links/onlinedataentryjobs.html http://teluguscope.com/links/Copy%20Past%20jobs.html http://teluguscope.com/links/Work%20from%20Home.html http://teluguscope.com/links/Formfilling%20jobs.html http://teluguscope.com/links/Survey%20Jobs.html From mkmax2 at gmail.com Sat May 1 04:33:04 2010 From: mkmax2 at gmail.com (Andrew) Date: Sat, 1 May 2010 01:33:04 -0700 (PDT) Subject: Cheap Software Offers! Message-ID: We have best software prices, visit us at http://cheaphsoft4u.com/?rid=107 From pavlovevidence at gmail.com Sat May 1 06:17:32 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 1 May 2010 03:17:32 -0700 (PDT) Subject: Ignoring XML Namespaces with cElementTree References: <9527079b-92bf-4c59-af2b-ab2c84029f55@h37g2000pra.googlegroups.com> Message-ID: <7305286c-cc77-48cb-bd9b-22b2eb35ae5d@y18g2000prn.googlegroups.com> On Apr 27, 6:42?pm, dmtr wrote: > Is there any way to configure cElementTree to ignore the XML root > namespace? ?Default cElementTree (Python 2.6.4) appears to add the XML > root namespace URI to _every_ single tag. ?I know that I can strip > URIs manually, from every tag, but it is a rather idiotic thing to do > (performance wise). Perhaps upgrade to lxml. Not sure if gives you control over namespace expansion but if it doesn't it should at least be faster. For this and some other reasons, I find ElementTree not quite as handy when processing files from another source as when I'm saving and retrieving my own data. Carl Banks From pavlovevidence at gmail.com Sat May 1 06:33:57 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 1 May 2010 03:33:57 -0700 (PDT) Subject: Ignoring XML Namespaces with cElementTree References: <9527079b-92bf-4c59-af2b-ab2c84029f55@h37g2000pra.googlegroups.com> Message-ID: <7a4f1818-e77a-4238-b021-3e2c6da836ae@a18g2000prd.googlegroups.com> On Apr 29, 10:12?pm, Stefan Behnel wrote: > dmtr, 30.04.2010 04:57: > > > > > I'm referring to xmlns/URI prefixes. Here's a code example: > > ? from xml.etree.cElementTree import iterparse > > ? from cStringIO import StringIO > > ? xml = """ > root>""" > > ? for event, elem in iterparse(StringIO(xml)): print event, elem > > > The output is: > > ? end > > ? end > > > I don't want these "{http://www.very_long_url.com}" in front of my > > tags. > > > They create performance disaster on large files > > I seriously doubt that they do. I don't know what kind of XML files you deal with, but for me a large XML file is gigabyte-sized (obviously I don't use Element Tree for those). Even for files tens-of-megabyte files string ops to expand tags with namespaces is going to be a pretty decent penalty--remember ElementTree does nothing lazily. > > (first cElementTree > > adds them, then I have to remove them in python). > > I think that's your main mistake: don't remove them. Instead, use the fully > qualified names when comparing. Unless you have multiple namespaces or are working with defined schema or something, it's useless boilerplate. It'd be a nice feature if ElementTree could let users optionally ignore a namespace, unfortunately it doesn't have it. Carl Banks From dodo_do_not_wake_up at yahoo.Fr Sat May 1 06:52:01 2010 From: dodo_do_not_wake_up at yahoo.Fr (Dodo) Date: Sat, 01 May 2010 12:52:01 +0200 Subject: CGI python 3 write RAW BINARY In-Reply-To: References: <4bd8ae7e$0$27615$ba4acef3@reader.news.orange.fr> <4bd96540$0$27597$ba4acef3@reader.news.orange.fr> <4bd9b4c2$0$27606$ba4acef3@reader.news.orange.fr> <4bd9fc1a$0$2980$ba4acef3@reader.news.orange.fr> Message-ID: <4bdc07d4$0$2980$ba4acef3@reader.news.orange.fr> Le 30/04/2010 17:52, Antoine Pitrou a ?crit : > Le Thu, 29 Apr 2010 23:37:32 +0200, Dodo a ?crit : >> ....I don't get a thing. >> Now with the fix : >> All browsers shows a different thing, but not the image! >> http://ddclermont.homeip.net/misc/python/ >> >> If I save it to computer : >> * Windows image viewer won't read it >> * Irfanview can read it without problems > > Did you set the content-type and content-length in the HTTP headers? > Can you post your code? > > I didn't know about content-lenght Here's the new code (I used a fixed image patch to make sure this is not the source of the problem) #!/usr/bin/python3 import cgi, sys, cgitb cgitb.enable() f = open("/home/dodo/54.jpg", "rb") data = f.read() l = len(data) f.close() print("Content-type:image/jpg\nContent-length:%d\n\n" % l) sys.stdout.flush() sys.stdout.buffer.write( data ) Dorian From ben+python at benfinney.id.au Sat May 1 06:55:24 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 May 2010 20:55:24 +1000 Subject: Python daemonisation with python-daemon References: <7ed4c441-78b2-4452-a814-ba2306152236@k29g2000yqh.googlegroups.com> Message-ID: <87ljc3howz.fsf@benfinney.id.au> Thomas Courbon writes: > I would like to turn my server script into a Linux/Unix daemon > (launched at boot time by init, dunno if that matter) using the nice > python-daemon package by Ben Finley et al I resemble that name :-) > This package comes with a class DaemonRunner that seems to fit almost > exactly my need but I still have some interrogation. Yes, that class is unlikely to grow much beyond a simple example of how to use ?DaemonContext?. You should feel free to take ?DaemonRunner? under the granted license and adapt it to be closer to what you want. > The DaemonRunner class expects my class to have stdin_path, > stdout_path, stderr_path attributes and after reading the code it > seems they have to be valid paths. Is that ok for a Daemon to redirect > those stream to /dev/null for example ? I would prefer to alter the > DaemonRunner class to accept None as value since DaemonContext, the > underlying class, seems to accept None for those parameters. This is a godd idea, allowing a more minimal use of ?DaemonRunner?. I'll take this as a feature request for a future revision of the class. > Also, the DaemonRunner use os.kill(pid, signal.SIGTERM) to stop the > daemon. I wonder if with my signal handling I'll be able to terminate > correctly the daemon (joining children, flushing buffers, closing > connections...). If that's relevant, the connection I use is a > Listener/Client connection from the standard multiprocessing module. I'll be interested to know too :-) > I'm quite neophyte in Unix daemon programming so please forgive me if > my question are obvious. Thank you for your feedback, and I hope the ?python-daemon? library continues to meet your needs. -- \ ?In the long run, the utility of all non-Free software | `\ approaches zero. All non-Free software is a dead end.? ?Mark | _o__) Pilgrim, 2006 | Ben Finney From jason.heeris at gmail.com Sat May 1 07:04:09 2010 From: jason.heeris at gmail.com (Jason) Date: Sat, 1 May 2010 04:04:09 -0700 (PDT) Subject: PyObject_SetAttrString - doesn't set instance attribute Message-ID: <82ae0f7b-e5f4-4b85-a9fb-aef16de10af2@a39g2000prb.googlegroups.com> I'm having a bit of trouble with C/Python bindings. Particularly, trying to set an instance variable from C when the object is initialised using PyObject_SetAttrString, but nothing seems to happen. The C initialisation code is: static void nautilus_python_object_instance_init (NautilusPythonObject *object) { fprintf(stderr, "nautilus_python_object_instance_init called\n"); NautilusPythonObjectClass *class; debug_enter(); class = (NautilusPythonObjectClass*)(((GTypeInstance*)object)- >g_class); object->instance = PyObject_CallObject(class->type, NULL); PyObject* test_int = PyInt_FromLong(42); if (object->instance == NULL) { PyErr_Print(); } else { fprintf(stderr, "Setting magic parameter\n"); fprintf(stderr, "From C: "); PyObject_Print(object->instance, stderr, 0); fprintf(stderr, "\n"); int retval = PyObject_SetAttrString(object->instance, "super_happy_magic", test_int); fprintf(stderr, "Result: %i\n", retval); } Py_DECREF(test_int); } ...and the Python module contains: class MenuProviderTest(nautilus.MenuProvider): def __init__(self): print "From Python: %s" % self try: print getattr(self, "super_happy_magic") except AttributeError: print "Didn't work!" When the MenuProviderTest is created, the output is: nautilus_python_object_instance_init called Setting magic parameter >From C: Result: 0 >From Python: Didn't work! (I've tried getattr and self.super_happy_magic, with the same effect.) Where am I going wrong? ? Jason From news1234 at free.fr Sat May 1 07:48:02 2010 From: news1234 at free.fr (News123) Date: Sat, 01 May 2010 13:48:02 +0200 Subject: matching strings in a large set of strings In-Reply-To: References: Message-ID: <4BDC14F2.2050603@free.fr> Dennis Lee Bieber wrote: > On Thu, 29 Apr 2010 11:38:28 +0200, "Karin Lagesen" > declaimed the following in comp.lang.python: > >> Hello. >> >> I have approx 83 million strings, all 14 characters long. I need to be >> able to take another string and find out whether this one is present >> within the 83 million strings. >> >> > So don't load them into memory... First use a file-based (not memory > > > That lets you do a binary search on the file. Much faster than a > linear search (linear search will average out to 41.5M read operations; > binary should be around 10000 reads) Don't you meant 27 reads instead of 41.5 M reads? >>> from math import log >>> log(83e6)/log(2) 26.306608000671101 >>> N From walter.overby at gmail.com Sat May 1 07:59:17 2010 From: walter.overby at gmail.com (Walter Overby) Date: Sat, 1 May 2010 04:59:17 -0700 (PDT) Subject: Use Regular Expressions to extract URL's References: <0760f79c-aa63-43c7-a845-339c6abcc702@g39g2000pri.googlegroups.com> <4bda9ce2$0$8757$c3e8da3@news.astraweb.com> Message-ID: A John Gruber post from November seems relevant. I have not tried his regex in any language. http://daringfireball.net/2009/11/liberal_regex_for_matching_urls Regards, Walter. From tim at thechases.com Sat May 1 08:13:42 2010 From: tim at thechases.com (Tim Chase) Date: Sat, 01 May 2010 07:13:42 -0500 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: <4BDC1AF6.3070505@thechases.com> On 05/01/2010 12:08 AM, Patrick Maupin wrote: > +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- > place operator methods, actually) *modify* the lhs object. > > Your proposed .= syntax conceptually *replaces* the lhs object > (actually, rebinds the lhs symbol to the new object). The += family of operators really do rebind the symbol, not modify the object. >>> from decimal import Decimal >>> d = Decimal(42) >>> e = Decimal(18) >>> orig = d >>> d += e >>> d Decimal("60") >>> e Decimal("18") >>> orig Decimal("42") >>> d is orig False If your suggestion that += *modifies* the object, then orig would now unintuitively contain 60 and "d is orig" would return True. This doesn't preclude you from implementing a self-mutating += style __add__ method and returning "self", but it's usually a bad idea unless it's dire for performance (and even then, think it over a couple times). -tkc From martin at v.loewis.de Sat May 1 08:16:29 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 01 May 2010 14:16:29 +0200 Subject: http://pypi.python.org/pypi In-Reply-To: <5587c2ea-567d-4a20-9e60-70c4ee18b24b@e39g2000yqf.googlegroups.com> References: <5587c2ea-567d-4a20-9e60-70c4ee18b24b@e39g2000yqf.googlegroups.com> Message-ID: <4BDC1B9D.70505@v.loewis.de> > I have only access to the webpage form too upload my one file. > pkginfo is ok, just want to at a single .py file instead of a complete > site-package tar directory, because it is not a site-package, its more > like a single exe file. Uploading individual .py files is not supported. If it's not a Python package, it shouldn't be in the Python Package Index. Regards, Martin From stefan_ml at behnel.de Sat May 1 08:34:39 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 01 May 2010 14:34:39 +0200 Subject: Ignoring XML Namespaces with cElementTree In-Reply-To: <7a4f1818-e77a-4238-b021-3e2c6da836ae@a18g2000prd.googlegroups.com> References: <9527079b-92bf-4c59-af2b-ab2c84029f55@h37g2000pra.googlegroups.com> <7a4f1818-e77a-4238-b021-3e2c6da836ae@a18g2000prd.googlegroups.com> Message-ID: Carl Banks, 01.05.2010 12:33: > On Apr 29, 10:12 pm, Stefan Behnel wrote: >> dmtr, 30.04.2010 04:57: >>> I don't want these "{http://www.very_long_url.com}" in front of my >>> tags. They create performance disaster on large files >> >> I seriously doubt that they do. > > I don't know what kind of XML files you deal with, but for me a large > XML file is gigabyte-sized (obviously I don't use Element Tree for > those). Why not? I used cElementTree for files of that size (1-1.5GB unpacked) a couple of times, and it was never a problem. > Even for files tens-of-megabyte files string ops to expand tags with > namespaces is going to be a pretty decent penalty--remember > ElementTree does nothing lazily. So? Did you run a profiler on it to know that there is a penalty due to the string concatenation? cElementTree's parser (expat) and its tree builder are blazingly fast, especially the iterparse() implementation. http://codespeak.net/lxml/performance.html#parsing-and-serialising http://codespeak.net/lxml/performance.html#a-longer-example http://effbot.org/zone/celementtree.htm#benchmarks >>> (first cElementTree adds them, then I have to remove them in python). >> >> I think that's your main mistake: don't remove them. Instead, use the fully >> qualified names when comparing. > > Unless you have multiple namespaces or are working with defined schema > or something, it's useless boilerplate. > > It'd be a nice feature if ElementTree could let users optionally > ignore a namespace, unfortunately it doesn't have it. I agree that that would make for a nice parser option, e.g. when dealing with HTML and XHTML in the same code. Stefan From stefan_ml at behnel.de Sat May 1 09:05:05 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 01 May 2010 15:05:05 +0200 Subject: matching strings in a large set of strings In-Reply-To: References: <877hnpjtdw.fsf@rudin.co.uk> Message-ID: Duncan Booth, 30.04.2010 10:20: > So more than 3GB just for the strings (and that's for Python 2.x on > Python 3.x you'll need nearly 5GB). > > Running on a 64 bit version of Python should be fine, but for a 32 bit > system a naive approach just isn't going to work. > > Option 1: use a trie. That should reduce storage, maybe it will reduce > it enough, maybe not. It depends on the data. Depending on the implementation and the data, a trie can also use a lot /more/ space than the set of strings that it contains. The 83 million 14 character strings can well include a relatively large subset of the possible permutations (imagine purely numeric, hex-numeric or lower-case alpha-numeric strings, for example), so the trie will likely need to branch very often with very low intermediate run length. If you use pointers for trie branches, that's at least 8 bytes per branch on a 64bit system, versus 1 byte per character in a byte string list. Depending on the ratio of branches to characters, one or the other may win. So a "naive approach" likely won't work for tries either. Stefan From stefan_ml at behnel.de Sat May 1 09:17:25 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 01 May 2010 15:17:25 +0200 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4BDC1AF6.3070505@thechases.com> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4BDC1AF6.3070505@thechases.com> Message-ID: Tim Chase, 01.05.2010 14:13: > On 05/01/2010 12:08 AM, Patrick Maupin wrote: >> +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- >> place operator methods, actually) *modify* the lhs object. >> >> Your proposed .= syntax conceptually *replaces* the lhs object >> (actually, rebinds the lhs symbol to the new object). > > The += family of operators really do rebind the symbol, not modify the > object. > > >>> from decimal import Decimal > >>> d = Decimal(42) > >>> e = Decimal(18) > >>> orig = d > >>> d += e > >>> d > Decimal("60") > >>> e > Decimal("18") > >>> orig > Decimal("42") > >>> d is orig > False > > If your suggestion that += *modifies* the object, then orig would now > unintuitively contain 60 and "d is orig" would return True. > > This doesn't preclude you from implementing a self-mutating += style > __add__ method and returning "self", but it's usually a bad idea unless > it's dire for performance (and even then, think it over a couple times). It's not like this was unprecedented in Python, though: Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> l = [1,2,3] >>> a = l >>> l += [4,5,6] >>> l [1, 2, 3, 4, 5, 6] >>> a [1, 2, 3, 4, 5, 6] And I'm pretty sure this wasn't just done for performance reasons. Mutable data types behave that way. Stefan From python.list at tim.thechases.com Sat May 1 09:19:00 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 01 May 2010 08:19:00 -0500 Subject: Fast Efficient way to transfer an object to another list In-Reply-To: <4bdba195$0$8757$c3e8da3@news.astraweb.com> References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> Message-ID: <4BDC2A44.5080301@tim.thechases.com> On 04/30/2010 10:35 PM, Steven D'Aprano wrote: > If you know there is one, and only one, item with that stock code: > > def transfer_stock(stock_code, old_list, new_list): > """ Transfer a stock from one list to another """ > i = old_list.index(stock_code) # search > new_list.append(old_list[i]) # copy > del old_list[i] # delete > return new_list This could be written as def move(code, source, dest): dest.append(source.pop(source.index(code))) return dest depending on how one thinks. I tend to prefer lst.pop(idx) over tmp = lst[idx] del lst[idx] only using the latter if "idx" is a range/slice. Though since the function mutates the arguments, I'd be tempted to return None like list.sort() does for the same rationale. If more than one item is in the source, it will move/remove the first leaving the remainder; if no matching item is in the source it will appropriately raise a ValueError. -tkc From kaleem.adil at gmail.com Sat May 1 09:28:33 2010 From: kaleem.adil at gmail.com (Adil Kaleem) Date: Sat, 1 May 2010 06:28:33 -0700 (PDT) Subject: Help needed in downloading Brown corpus Message-ID: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> Hi all I'm a masters student in NLP. I needed to download the Brown corpus. I'm unable to download from nltk.org with the python CLI. My network connection is behind a proxy server so it's creating a problem. Since I don't know a bit of python, so unable to figure a way out. Can someone help me in this regard either how to solve my downloading problem or how to get Brown Corpus from some other link. Thanks in advance. From shashank.sunny.singh at gmail.com Sat May 1 09:37:28 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Sat, 1 May 2010 19:07:28 +0530 Subject: Help needed in downloading Brown corpus In-Reply-To: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> References: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> Message-ID: try this: run this in your terminal before you hit nltk.download(). Don't forget to set username, password and proxy info for your own system.(in PROXY_INFO) import urllib2 PROXY_INFO = { 'user' : username, 'pass' : password, 'host' : proxy_server, 'port' : proxy_port } proxy_support = urllib2.ProxyHandler({"http" : \ "http://%(user)s:%(pass)s@%(host)s:%(port)d" % PROXY_INFO}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) urllib2.install_opener(opener) HTH On Sat, May 1, 2010 at 6:58 PM, Adil Kaleem wrote: > Hi all > I'm a masters student in NLP. I needed to download the Brown corpus. > I'm unable to download from nltk.org with the python CLI. My network > connection is behind a proxy server so it's creating a problem. Since > I don't know a bit of python, so unable to figure a way out. Can > someone help me in this regard either how to solve my downloading > problem or how to get Brown Corpus from some other link. > Thanks in advance. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From news1234 at free.fr Sat May 1 10:44:48 2010 From: news1234 at free.fr (News123) Date: Sat, 01 May 2010 16:44:48 +0200 Subject: Windows7 run python script / sub process with elevated privileges Message-ID: <4bdc3e60$0$12096$426a74cc@news.free.fr> Hi, I have a small python script, which has been started as normal non privileged user. At a later point in time it would like to start another python script with elevated privileges. How can I write my code such, that I will get the privilege elevation prompt and I can start a sub process / python function with elevated privileges. thanks for any hints. Under Linux Ubuntu I would use sudo/gksu Under Windows 7 I'm a little lost. A Python only solution is of course prefered, but any .bat .c .C# .cmd wrapper would be fine. N From alfps at start.no Sat May 1 10:45:51 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 01 May 2010 16:45:51 +0200 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: On 01.05.2010 14:13, * Tim Chase: > On 05/01/2010 12:08 AM, Patrick Maupin wrote: >> +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- >> place operator methods, actually) *modify* the lhs object. >> >> Your proposed .= syntax conceptually *replaces* the lhs object >> (actually, rebinds the lhs symbol to the new object). > > The += family of operators really do rebind the symbol, not modify the > object. > > >>> from decimal import Decimal > >>> d = Decimal(42) > >>> e = Decimal(18) > >>> orig = d > >>> d += e > >>> d > Decimal("60") > >>> e > Decimal("18") > >>> orig > Decimal("42") > >>> d is orig > False > > If your suggestion that += *modifies* the object, then orig would now > unintuitively contain 60 and "d is orig" would return True. In some cases += modifies the object. For CPython this is an optimization for the 'str' type, reducing to O(n) time the common newbie O(n^2) loops. The criterion for doing it is that there is exactly 1 reference (as is the case after a first append, subsequent appends can just modify). > This doesn't preclude you from implementing a self-mutating += style > __add__ method and returning "self", but it's usually a bad idea unless > it's dire for performance (and even then, think it over a couple times). Agreed, at the Python level one doesn't in general have the necessary information to do it safely. Nothwithstanding the current CPython and Jython documentation error of sys.getrefcount (or whatever the name was) that indicates that it's available in any implementation. Cheers, - Alf From python at mrabarnett.plus.com Sat May 1 11:08:22 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 01 May 2010 16:08:22 +0100 Subject: Fast Efficient way to transfer an object to another list In-Reply-To: <4BDC2A44.5080301@tim.thechases.com> References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> <4BDC2A44.5080301@tim.thechases.com> Message-ID: <4BDC43E6.1090508@mrabarnett.plus.com> Tim Chase wrote: > On 04/30/2010 10:35 PM, Steven D'Aprano wrote: >> If you know there is one, and only one, item with that stock code: >> >> def transfer_stock(stock_code, old_list, new_list): >> """ Transfer a stock from one list to another """ >> i = old_list.index(stock_code) # search >> new_list.append(old_list[i]) # copy >> del old_list[i] # delete >> return new_list > > This could be written as > > def move(code, source, dest): > dest.append(source.pop(source.index(code))) > return dest > > depending on how one thinks. I tend to prefer > > lst.pop(idx) > > over > > tmp = lst[idx] > del lst[idx] > > only using the latter if "idx" is a range/slice. > > Though since the function mutates the arguments, I'd be tempted to > return None like list.sort() does for the same rationale. > > If more than one item is in the source, it will move/remove the first > leaving the remainder; if no matching item is in the source it will > appropriately raise a ValueError. > It would be more efficient if instead of deleting or popping the item you moved the last one into its place: if idx == len(source) - 1: item = source.pop() else: item = source[idx] source[idx] = source.pop() assuming that the order of the items in the list doesn't matter. From bieffe62 at gmail.com Sat May 1 11:11:45 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sat, 1 May 2010 08:11:45 -0700 (PDT) Subject: Fast Efficient way to transfer an object to another list References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> Message-ID: <06366a6d-e3db-4963-bcc0-0bc03d035a94@e2g2000yqn.googlegroups.com> On 1 Mag, 05:35, Steven D'Aprano wrote: > > def transfer_stock(stock_code, old_list, new_list): > ? ? """ Transfer a stock from one list to another """ > ? ? while True: ?# loop forever > ? ? ? ? try: > ? ? ? ? ? ? i = old_list.index(stock_code) > ? ? ? ? except ValueError: > ? ? ? ? ? ? # not found, so we're done > ? ? ? ? ? ? break > ? ? ? ? new_list.append(old_list[i]) > ? ? ? ? del old_list[i] > ? ? return new_list > > -- > Steven I think this could be slower than doing like the OP, since 'index' rescan the whole list every time while doing an explicit loop you only scan the list once. Anyway i think that list.extract( old_list, predicate ) -> new_list would be a nice addition to the standard library (possibly a C faster version of what one could implement in python) ... and since the library is not under moratorium maybe we will have it ... the semantic could be like th OP asked: --- code begins class ListE(list): def extract(self, predicate): res = [] for idx, el in enumerate(self): if predicate(el): res.append( self.pop(idx) ) return res class Stock(object): def __init__(self, code): self.code = code def __repr__(self): return "Stock: code=%d" % self.code l = ListE( Stock(n) for n in range(19) ) subl = l.extract( lambda x: x.code in (1,4, 9) ) print " l = ", l print "subl = ", subl --- code ends --- results l = [Stock: code=0, Stock: code=2, Stock: code=3, Stock: code=5, Stock: code=6, Stock: code=7, Stock: code=8, Stock: code=10, Stock: code=11, Stock: code=12, Stock: code=13, Stock: code=14, Stock: code=15, Stock: code=16, Stock: code=17, Stock: code=18] subl = [Stock: code=1, Stock: code=4, Stock: code=9] Ciao --- FB From news1234 at free.fr Sat May 1 11:57:56 2010 From: news1234 at free.fr (News123) Date: Sat, 01 May 2010 17:57:56 +0200 Subject: Windows7 run python script / sub process with elevated privileges In-Reply-To: <4bdc3e60$0$12096$426a74cc@news.free.fr> References: <4bdc3e60$0$12096$426a74cc@news.free.fr> Message-ID: <4bdc4f84$0$18399$426a74cc@news.free.fr> I Found a first solution, though not very satisfying: News123 wrote: > Hi, > > I have a small python script, which has been started as normal non > privileged user. > > At a later point in time it would like to start another python script > with elevated privileges. > > How can I write my code such, that I will get the privilege elevation > prompt and I can start a sub process / python function with elevated > privileges. > > thanks for any hints. > > Under Linux Ubuntu I would use sudo/gksu > > Under Windows 7 I'm a little lost. > > A Python only solution is of course prefered, but any .bat .c .C# .cmd > wrapper would be fine. > I could call following command: PowerShell -Command (New-Object -com 'Shell.Application').ShellExecute('Cmd.exe', '/c c:\abs_path_to_my_app\pyscript.pyw', ' ', 'runas') So I might do something like: # ########### script starts import subprocess cmd_wrap = "PowerShell -Command (New-Object -com "\ "'Shell.Application').ShellExecute('Cmd.exe', "\ "'/c %s', '', 'runas')" args = r"c:\abspathtommyapp\myapp.pyw" cmd = cmd_wrap % args # create KW args to hide console kwargs = { } su = subprocess.STARTUPINFO() su.dwFlags |= subprocess.STARTF_USESHOWWINDOW su.wShowWindow = subprocess.SW_HIDE kwargs['startupinfo'] = su p = subprocess.Popen( cmd.split() , **kwargs ) # script ends here However my issue is, that I have one annoying console window popping up when PowerShell starts cmd.exe Is there anything better? From daniel at stutzbachenterprises.com Sat May 1 11:57:56 2010 From: daniel at stutzbachenterprises.com (Daniel Stutzbach) Date: Sat, 1 May 2010 10:57:56 -0500 Subject: Fast Efficient way to transfer an object to another list In-Reply-To: References: Message-ID: On Fri, Apr 30, 2010 at 9:16 PM, Jimbo wrote: > Hello I have a relatively simple thing to do; move an object from one > to list into another. But I think my solution maybe inefficient & > slow. > Removing an item from a list is O(n) on average, so it's going to be a bit slow any way you slice it (unless you only remove from the end of the list which is O(1)). Can you tell us more about why you're using a list? If the order of the items doesn't matter, you may be able to use a set(). If the order matters, how is the list ordered? If we know how the list is ordered, we may be able to help you come up with a clever way to remove an item cheaply. -- Daniel Stutzbach, Ph.D. President, Stutzbach Enterprises, LLC -------------- next part -------------- An HTML attachment was scrubbed... URL: From WolfgangMeiners01 at web.de Sat May 1 12:04:43 2010 From: WolfgangMeiners01 at web.de (Wolfgang Meiners) Date: Sat, 01 May 2010 18:04:43 +0200 Subject: recommended way to insert data into a one to many relationship using python Message-ID: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Hi, one to many relationships are fairly common, i think. So there should be a recommended way to insert data into such a relation using python. Given the following programm, what is the recommended way to insert the list of NewEmployees to the database? ======================================================================== # !python # -*- coding: utf-8 -*- import sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() cur.execute("""create table employees( eid integer primary key autoincrement, name text not null, rid integer references rooms(rid))""") cur.execute("""create table rooms( rid integer primary key autoincrement, number integer, fid integer references floors(fid))""") cur.execute("""create table floors( fid integer primary key autoincrement, floor text not null)""") cur.execute("""insert into floors(floor) values ('first floor')""") cur.execute("""insert into floors(floor) values ('second floor')""") cur.execute("""insert into rooms(number,fid) values (21, 1)""") cur.execute("""insert into rooms(number,fid) values (22, 2)""") cur.execute("""insert into employees(name,rid) values ('Joe', 1)""") cur.execute("""insert into employees(name,rid) values ('Nancy', 2)""") cur.execute("""create view emplist as select name, number, floor from employees natural inner join rooms natural inner join floors""") print cur.execute("""select * from emplist order by name""").fetchall() NewEmployees =[] NewEmployees.append({'name': 'George', 'room': 89, 'floor': 'third floor'}) NewEmployees.append({'name': 'Ellen', 'room': 21, 'floor': 'first floor'}) print NewEmployees con.close() =========================================================================== Thank you for any hint Wolfgang From ppearson at nowhere.invalid Sat May 1 13:54:40 2010 From: ppearson at nowhere.invalid (Peter Pearson) Date: 1 May 2010 17:54:40 GMT Subject: Help needed in downloading Brown corpus References: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> Message-ID: <843870Fj4oU1@mid.individual.net> On Sat, 1 May 2010 06:28:33 -0700 (PDT), Adil Kaleem wrote: > Hi all > I'm a masters student in NLP. I needed to download the Brown corpus. > I'm unable to download from nltk.org with the python CLI. My network > connection is behind a proxy server so it's creating a problem. Since > I don't know a bit of python, so unable to figure a way out. Can > someone help me in this regard either how to solve my downloading > problem or how to get Brown Corpus from some other link. > Thanks in advance. As I understand it (from Wikipedia), the Brown Corpus is a collection of samples of modern American English text, and nltk.org provides a Python toolkit for exploring said Corpus. I'm trying to figure out whether you're trying to get the Corpus or the toolkit. Neither interpretation looks plausible: if you're after the Corpus itself and you don't know a bit of Python, why are you struggling with Python? On the other hand, if you're after the toolkit, what's the problem? People download Python modules all the time. And besides, why would you be after the toolkit if you don't know a bit of Python? If your goal is to learn enough Python to use the toolkit, you'll find this newsgroup full of smart and helpful people. But you'll have to be a little more explicit about what you're trying to do and more specific about what obstacles you encounter. As you might see by looking at other threads on this newsgroup, the queries that get the most prompt and useful responses usually include blocks of quoted text of the form "I type this [cut-and-pasted block] and get this response [another cut-and-pasted block]." -- To email me, substitute nowhere->spamcop, invalid->net. From lie.1296 at gmail.com Sat May 1 15:08:53 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 02 May 2010 05:08:53 +1000 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> Message-ID: <4bdc7ca3$1@dnews.tpgi.com.au> On 05/01/10 11:16, Steven D'Aprano wrote: > On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote: > > In practice though, I think that's a difference that makes no difference. > It walks like an operator, it swims like an operator, and it quacks like > an operator. > Nope it's not. A full-time operator in python have a reflected version (e.g. __radd__), which dot does not have. And Python's object system makes it that the argument to __getattr__ is always a string even though there might be a valid variable that corresponds to it: a = MyClass() b = MyClass() print a . b I've often wanted to figure out a way to (ab)use python's dot operator for function composition (i.e. f.g(x) ==> f(g(x)) ). There's no way to do it, not without being way too hackish. OTOH, doing so is quite trivial with regular operators. In short, unless there's __rgetattr__ and unless you can refer to the right-hand operand as an object[1], dot doesn't quack like an operator. [1] well, technically string is an object, but you get what I mean From __peter__ at web.de Sat May 1 15:20:33 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 May 2010 21:20:33 +0200 Subject: recommended way to insert data into a one to many relationship using python References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Wolfgang Meiners wrote: > Hi, > > one to many relationships are fairly common, i think. So there should be > a recommended way to insert data into such a relation using python. > > > Given the following programm, what is the recommended way to insert the > list of NewEmployees to the database? > > ======================================================================== > # !python > # -*- coding: utf-8 -*- > > import sqlite3 > > con = sqlite3.connect(":memory:") > cur = con.cursor() > > cur.execute("""create table employees( > eid integer primary key autoincrement, > name text not null, > rid integer references rooms(rid))""") > > cur.execute("""create table rooms( > rid integer primary key autoincrement, > number integer, > fid integer references floors(fid))""") > > cur.execute("""create table floors( > fid integer primary key autoincrement, > floor text not null)""") > > cur.execute("""insert into floors(floor) values ('first floor')""") > cur.execute("""insert into floors(floor) values ('second floor')""") > > cur.execute("""insert into rooms(number,fid) values (21, 1)""") > cur.execute("""insert into rooms(number,fid) values (22, 2)""") > > cur.execute("""insert into employees(name,rid) values ('Joe', 1)""") > cur.execute("""insert into employees(name,rid) values ('Nancy', 2)""") > > cur.execute("""create view emplist as select name, number, floor > from employees natural inner join rooms natural inner join > floors""") > > print cur.execute("""select * from emplist order by name""").fetchall() > > NewEmployees =[] > NewEmployees.append({'name': 'George', 'room': 89, 'floor': 'third > floor'}) NewEmployees.append({'name': 'Ellen', 'room': 21, 'floor': 'first > floor'}) > > print NewEmployees > con.close() > =========================================================================== > > Thank you for any hint > Wolfgang There are probably some opportunities for generalization lurking in the following mess, but it would take me more time than I'm willing to invest. cur.execute("create table new_employees (name, room, floor, fid);") cur.executemany("""insert into new_employees (name, room, floor) values (:name, :room, :floor)""", NewEmployees) c2 = con.cursor() missing = c2.execute(""" select distinct n.floor from new_employees n left outer join floors f on n.floor = f.floor where f.floor is null """) cur.executemany("insert into floors (floor) values (?)", missing) cur.execute(""" update new_employees set fid = (select fid from floors where floors.floor = new_employees.floor)""") missing = c2.execute(""" select distinct n.fid, n.room from new_employees n left outer join rooms r on n.fid = r.fid and n.room = r.number where r.fid is null""") cur.executemany("insert into rooms (fid, number) values (?, ?)", missing) new = c2.execute(""" select n.name, r.rid from new_employees n, rooms r where n.room = r.number and n.fid == r.fid """) cur.executemany("insert into employees (name, rid) values (?, ?)", new) If your data is small enough you may try to do the heavy lifting in Python instead of SQL; if not, maybe you'd better ask in a SQL forum. Peter Afterthought: Can SQLAlchemy do these kind of things cleanly? From pmaupin at gmail.com Sat May 1 15:22:06 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 1 May 2010 12:22:06 -0700 (PDT) Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: <54dfd378-f519-4a43-96ba-df8de28c45c6@k29g2000yqh.googlegroups.com> On May 1, 7:13?am, Tim Chase wrote: > On 05/01/2010 12:08 AM, Patrick Maupin wrote: > > > +=, -=, /=, *=, etc. ?conceptually (and, if lhs object supports in- > > place operator methods, actually) *modify* the lhs object. > > > Your proposed .= syntax conceptually *replaces* the lhs object > > (actually, rebinds the lhs symbol to the new object). > > The += family of operators really do rebind the symbol, not > modify the object. > > ? ?>>> from decimal import Decimal > ? ?>>> d = Decimal(42) > ? ?>>> e = Decimal(18) > ? ?>>> orig = d > ? ?>>> d += e > ? ?>>> d > ? ?Decimal("60") > ? ?>>> e > ? ?Decimal("18") > ? ?>>> orig > ? ?Decimal("42") > ? ?>>> d is orig > ? ?False > > If your suggestion that += *modifies* the object, then orig would > now unintuitively contain 60 and "d is orig" would return True. Well, I wrote "conceptually" (which I believe is true; it's certainly true for me) and "sometimes actually" (which I know is true): >>> x = [1,2,3,4,5] >>> y = x >>> x += [6] >>> y [1, 2, 3, 4, 5, 6] >>> >>> x = set() >>> y = x >>> x |= set([1]) >>> y set([1]) SO, if you find those results "unintuitive", perhaps you should upgrade your understanding of python. Personally, I don't find any of the results I gave, or the results you gave, surprising, so I'm not saying my "conceptually and sometimes actually modifies the result" is right for *you* but it works great for me. :-) > This doesn't preclude you from implementing a self-mutating += > style __add__ method and returning "self", but it's usually a bad > idea unless it's dire for performance (and even then, think it > over a couple times). Well, you should submit a bug report to fix the operation of lists and sets for a starter. But first, you might want to read PEP 203 -- augmented assignments. I particularly like the section which says: "The idea behind augmented assignment in Python is that it isn't just an easier way to write the common practice of storing the result of a binary operation in its left-hand operand, but also a way for the left- hand operand in question to know that it should operate `on itself', rather than creating a modified copy of itself." There are a lot of sections which have a similar flavor. If (which I doubt), the "augmented dot" is accepted, it won't necessarily have the same meaning. x = x.foo could replace x with any other kind of object, and I view it as a replacement, while I view x += foo as a modification. Regards, Pat From darcy at druid.net Sat May 1 15:24:46 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 1 May 2010 15:24:46 -0400 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4bdc7ca3$1@dnews.tpgi.com.au> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> Message-ID: <20100501152446.2fd017bd.darcy@druid.net> On Sun, 02 May 2010 05:08:53 +1000 Lie Ryan wrote: > On 05/01/10 11:16, Steven D'Aprano wrote: > > On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote: > > > > In practice though, I think that's a difference that makes no difference. > > It walks like an operator, it swims like an operator, and it quacks like > > an operator. > > > > Nope it's not. A full-time operator in python have a reflected version Hi. Please watch the attributions. I didn't write that. I was the one who said that '.' was not an operator. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From paul.paj at gmail.com Sat May 1 16:16:04 2010 From: paul.paj at gmail.com (Paul Johnston) Date: Sat, 1 May 2010 13:16:04 -0700 (PDT) Subject: jpeg package Message-ID: Hi, I've used the jpeg library on PyPI in the past and it's been great: http://pypi.python.org/pypi/jpeg/0.1.4 However, the library home page is now unaccessible. I can't even find the library on archive.org. Any idea how I can get it? http://www.emilas.com/jpeg/ Thanks, Paul From Jack.Jansen at cwi.nl Sat May 1 17:40:13 2010 From: Jack.Jansen at cwi.nl (Jack Jansen) Date: Sat, 1 May 2010 23:40:13 +0200 Subject: [capi-sig] SWIG + expy In-Reply-To: <272522.69975.qm@web54204.mail.re2.yahoo.com> References: <272522.69975.qm@web54204.mail.re2.yahoo.com> Message-ID: <652256E5-5D3A-41DE-A7C5-6BED41F5944E@cwi.nl> On 27-Apr-2010, at 08:30 , Yingjie Lan wrote: > Hi, > > Is it possible to use SWIG to parse C/C++, and provide an interface for me to generate some code? I thought it might be good to have SWIG help generate expy (see http://expy.sourceforge.net) files, then generate the python extension via expy. I would be very interested in a universal intermediate format for all the interface generators. I'm still using a version of Guido's old bgen, now grudgingly extended to handle C++ and do bidirectional bridging between Python and C++, and while I love and cherish the code generator the C++ parser is, uhm... challenging. Parsing C++ with per-line regular expressions is no fun:-) I looked at gccxml at some point, as well as at some of the competing Python interface generators, but it went nowhere. gccxml output is far too detailed, and the output is too much of a simple parse tree to be of any use. The intermediate formats of the other interface generators I looked at were all too inaccessible. Maybe we can come up with something decent in this group? If there is enough interest: I can start by describing bgen's intermediate format, and if other people do the same for theirs we may be able to get to common ground... -- Jack Jansen, , http://www.cwi.nl/~jack If I can't dance I don't want to be part of your revolution -- Emma Goldman From news1234 at free.fr Sat May 1 17:46:33 2010 From: news1234 at free.fr (News123) Date: Sat, 01 May 2010 23:46:33 +0200 Subject: matching strings in a large set of strings In-Reply-To: References: <4BDC14F2.2050603@free.fr> Message-ID: <4BDCA139.2010303@free.fr> Dennis Lee Bieber wrote: > On Sat, 01 May 2010 13:48:02 +0200, News123 declaimed > the following in gmane.comp.python.general: > >> Dennis Lee Bieber wrote: >>> That lets you do a binary search on the file. Much faster than a >>> linear search (linear search will average out to 41.5M read operations; >>> binary should be around 10000 reads) >> Don't you meant 27 reads instead of 41.5 M reads? >> > Don't you mean my 10000 reads? The 41.5M is the average for the > linear search. > Indeed, this is what I meant. or phrased differently: "about 27 reads with a binary search instead of 41.5M reads average with a linear search." >>>>> from math import log >>>>> log(83e6)/log(2) >> 26.306608000671101 > Probably -- it was late at night and I was working things out in my > head... I know about late nights. I just wondered whether I overlooked something. From news1234 at free.fr Sat May 1 17:46:33 2010 From: news1234 at free.fr (News123) Date: Sat, 01 May 2010 23:46:33 +0200 Subject: matching strings in a large set of strings In-Reply-To: References: <4BDC14F2.2050603@free.fr> Message-ID: <4BDCA139.2010303@free.fr> Dennis Lee Bieber wrote: > On Sat, 01 May 2010 13:48:02 +0200, News123 declaimed > the following in gmane.comp.python.general: > >> Dennis Lee Bieber wrote: >>> That lets you do a binary search on the file. Much faster than a >>> linear search (linear search will average out to 41.5M read operations; >>> binary should be around 10000 reads) >> Don't you meant 27 reads instead of 41.5 M reads? >> > Don't you mean my 10000 reads? The 41.5M is the average for the > linear search. > Indeed, this is what I meant. or phrased differently: "about 27 reads with a binary search instead of 41.5M reads average with a linear search." >>>>> from math import log >>>>> log(83e6)/log(2) >> 26.306608000671101 > Probably -- it was late at night and I was working things out in my > head... I know about late nights. I just wondered whether I overlooked something. From vincent at vincentdavis.net Sat May 1 18:22:57 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Sat, 1 May 2010 16:22:57 -0600 Subject: jpeg package In-Reply-To: References: Message-ID: This gets you the cached page link I also fond some of the source pages in googles cache *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn On Sat, May 1, 2010 at 2:16 PM, Paul Johnston wrote: > Hi, > > I've used the jpeg library on PyPI in the past and it's been great: > http://pypi.python.org/pypi/jpeg/0.1.4 > > However, the library home page is now unaccessible. I can't even find > the library on archive.org. Any idea how I can get it? > http://www.emilas.com/jpeg/ > > Thanks, > > Paul > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregory.j.baker at gmail.com Sat May 1 18:57:06 2010 From: gregory.j.baker at gmail.com (Novocastrian_Nomad) Date: Sat, 1 May 2010 15:57:06 -0700 (PDT) Subject: Need direction on mass find/replacement in HTML files References: Message-ID: One single line regex solution would be: re.sub(r'http\://www.mysite.org/\?page=([^"]+)',r'pages/\1.htm',html) From evil.hackerz.999 at gmail.com Sat May 1 19:54:21 2010 From: evil.hackerz.999 at gmail.com (EVIL-HaCkErZ) Date: Sat, 1 May 2010 16:54:21 -0700 (PDT) Subject: TEAM EVILHACKERZ Message-ID: TEAM EVILHACKERZ http://handyzon.com/ [Amazon social network & discount center] http://fullversionddl.com [cracked software & etc] http://realhacks.com [learn hacking/tutorials] http://desktopmp3.com [mucic album & wallpaper] http://dvdripdownload.com [latest movies download ] From steve at REMOVE-THIS-cybersource.com.au Sat May 1 20:58:10 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 00:58:10 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> Message-ID: <4bdcce21$0$27782$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 05:08:53 +1000, Lie Ryan wrote: > On 05/01/10 11:16, Steven D'Aprano wrote: >> On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote: >> >> In practice though, I think that's a difference that makes no >> difference. It walks like an operator, it swims like an operator, and >> it quacks like an operator. >> >> > Nope it's not. A full-time operator in python have a reflected version > (e.g. __radd__), which dot does not have. What are the reflected versions of __eq__ and __ne__ (binary == and != operators)? And __neg__, __pos__ and __inv__ (for the unary - + and ~ operators)? And the three-argument form of __pow__ for power(1, 2, x)? > And Python's object system > makes it that the argument to __getattr__ is always a string even though > there might be a valid variable that corresponds to it: That is nothing to do with the object system, it is related to the semantics of Python syntax. a.b doesn't mean "apply the binary dot operator to arguments a and b". It is syntactic sugar for "look for an attribute named 'b' on object a". As such, the operands that __getattr__ receives are the object a and the *name* b (implemented as a string). Also, the implementation of attribute lookup is quite complex, with all sorts of special cases and optimizations. > a = MyClass() > b = MyClass() > print a . b > > I've often wanted to figure out a way to (ab)use python's dot operator > for function composition (i.e. f.g(x) ==> f(g(x)) ). There's no way to > do it, not without being way too hackish. That's a good example of where the difference does make a difference. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 1 20:59:36 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 00:59:36 GMT Subject: Fast Efficient way to transfer an object to another list References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> <06366a6d-e3db-4963-bcc0-0bc03d035a94@e2g2000yqn.googlegroups.com> Message-ID: <4bdcce77$0$27782$c3e8da3@news.astraweb.com> On Sat, 01 May 2010 08:11:45 -0700, Francesco Bochicchio wrote: > On 1 Mag, 05:35, Steven D'Aprano > wrote: > > >> def transfer_stock(stock_code, old_list, new_list): >> ? ? """ Transfer a stock from one list to another """ while True: ?# >> ? ? loop forever >> ? ? ? ? try: >> ? ? ? ? ? ? i = old_list.index(stock_code) >> ? ? ? ? except ValueError: >> ? ? ? ? ? ? # not found, so we're done >> ? ? ? ? ? ? break >> ? ? ? ? new_list.append(old_list[i]) >> ? ? ? ? del old_list[i] >> ? ? return new_list >> >> -- >> Steven > > I think this could be slower than doing like the OP, since 'index' > rescan the whole list every time > while doing an explicit loop you only scan the list once. If the list is sufficiently big enough, yes, you are correct. But since list.index is fast C code, and a while loop is slow Python code, it would need to be fairly big, and probably much bigger than you think! The simplest way to speed the above code up is not to start from the beginning each time. That requires two very small changes. And since deletions from the front of the list are slow, MRAB's suggestion is also a good idea. This requires another very small change. Putting them together: # Untested. def transfer_stock(stock_code, old_list, new_list): ? ? """ Transfer a stock from one list to another """ i = 0 while True: ?# loop forever ? ? ? ?try: ? ? ? ? ? i = old_list.index(stock_code, i) ? ? ? except ValueError: ? ? ? ? ? ? # not found, so we're done ? ? ? ? ? ? break ? ? ? ? new_list.append(old_list[i]) ? ? ? ? old_list[i] = old_list[-1] del old_list[-1] ? ? return new_list This should be very much faster, for hardly any extra complexity. > Anyway i think that list.extract( old_list, predicate ) -> new_list > would be a nice addition to the standard library (possibly a C faster > version of what one could implement in python) ... and since the library > is not under moratorium maybe we will have it ... But since it is a method on a built-in (list), and not a library function, it does fall under the moratorium. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 1 21:30:26 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 01:30:26 GMT Subject: Help needed in downloading Brown corpus References: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> Message-ID: <4bdcd5b2$0$27782$c3e8da3@news.astraweb.com> On Sat, 01 May 2010 06:28:33 -0700, Adil Kaleem wrote: > Hi all > I'm a masters student in NLP. I needed to download the Brown corpus. I'm > unable to download from nltk.org with the python CLI. My network > connection is behind a proxy server so it's creating a problem. Since I > don't know a bit of python, so unable to figure a way out. This has nothing to do with Python, it is a network issue. Talk to your network administrator and get him to fix the proxy, or give you a way to bypass it. Or if you have an internet connection at home, download it from there. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 1 21:32:34 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 01:32:34 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: <4bdcd631$0$27782$c3e8da3@news.astraweb.com> On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: > On 05/01/2010 12:08 AM, Patrick Maupin wrote: >> +=, -=, /=, *=, etc. conceptually (and, if lhs object supports in- >> place operator methods, actually) *modify* the lhs object. >> >> Your proposed .= syntax conceptually *replaces* the lhs object >> (actually, rebinds the lhs symbol to the new object). > > The += family of operators really do rebind the symbol, not modify the > object. They potentially do both, depending on the object, even for built-ins. > >>> from decimal import Decimal [...] I'm not sure why you took the trouble to import Decimal for this example, when you could have shown the same thing with built-ins int or float. All three types are immutable. A counter example with a mutable type: >>> a = [] >>> b = a >>> a += [2] >>> a [2] >>> b [2] thus demonstrating that __iadd__ modifies in place as well as rebinds for at least one mutable type. > This doesn't preclude you from implementing a self-mutating += style > __add__ method and returning "self", but it's usually a bad idea Obviously the Python dev team don't agree with that :) Just to prove that += for lists is not an accident: >>> a = set() >>> b = a >>> a |= set([1]) >>> a set([1]) >>> b set([1]) -- Steven From clp2 at rebertia.com Sat May 1 22:03:04 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 1 May 2010 19:03:04 -0700 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4bdcd631$0$27782$c3e8da3@news.astraweb.com> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On Sat, May 1, 2010 at 6:32 PM, Steven D'Aprano wrote: > On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: >> This doesn't preclude you from implementing a self-mutating += style >> __add__ method and returning "self", but it's usually a bad idea > > Obviously the Python dev team don't agree with that :) > > Just to prove that += for lists is not an accident: > >>>> a = set() >>>> b = a >>>> a |= set([1]) >>>> a > set([1]) >>>> b > set([1]) In both cases, __iOP__ operator methods are being used, not vanilla __OP__ methods, so neither of your examples are relevant to Mr. Chase's point. Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sat May 1 22:24:16 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 02:24:16 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: <4bdce250$0$27782$c3e8da3@news.astraweb.com> On Sat, 01 May 2010 19:03:04 -0700, Chris Rebert wrote: > On Sat, May 1, 2010 at 6:32 PM, Steven D'Aprano > wrote: >> On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: >>> This doesn't preclude you from implementing a self-mutating += style >>> __add__ method and returning "self", but it's usually a bad idea >> >> Obviously the Python dev team don't agree with that :) >> >> Just to prove that += for lists is not an accident: [...] > In both cases, __iOP__ operator methods are being used, not vanilla > __OP__ methods, so neither of your examples are relevant to Mr. Chase's > point. I'm sorry, I read Tim's reference to __add__ (instead of __iadd__) as a typo. Having __add__ mutate self would be a strange thing to do. -- Steven From pmaupin at gmail.com Sat May 1 23:03:14 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 1 May 2010 20:03:14 -0700 (PDT) Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: <3c3d61cc-c714-4bea-91bc-b423a5dbdf99@g21g2000yqk.googlegroups.com> On May 1, 9:03?pm, Chris Rebert wrote: > In both cases, __iOP__ operator methods are being used, not vanilla > __OP__ methods, so neither of your examples are relevant to Mr. > Chase's point. Well, Tim's main assertion was: "The += family of operators really do rebind the symbol, not modify the object." So, using __iadd__ to disprove this blanket assertion is certainly relevant. Regards, Pat From dchichkov at gmail.com Sat May 1 23:06:24 2010 From: dchichkov at gmail.com (dmtr) Date: Sat, 1 May 2010 20:06:24 -0700 (PDT) Subject: Ignoring XML Namespaces with cElementTree References: <9527079b-92bf-4c59-af2b-ab2c84029f55@h37g2000pra.googlegroups.com> <7a4f1818-e77a-4238-b021-3e2c6da836ae@a18g2000prd.googlegroups.com> Message-ID: <74e6f0f1-1665-4902-9d1a-ccf9cfc2e2f7@u3g2000prl.googlegroups.com> > Unless you have multiple namespaces or are working with defined schema > or something, it's useless boilerplate. > > It'd be a nice feature if ElementTree could let users optionally > ignore a namespace, unfortunately it doesn't have it. Yep. Exactly my point. Here's a link to the patch addressing this: http://bugs.python.org/issue8583 From aahz at pythoncraft.com Sun May 2 00:06:48 2010 From: aahz at pythoncraft.com (Aahz) Date: 1 May 2010 21:06:48 -0700 Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: In article <4bdcd631$0$27782$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: >> >> The += family of operators really do rebind the symbol, not modify the >> object. > >They potentially do both, depending on the object, even for built-ins. No, they always rebind; sometimes they modify the object and sometimes they rebind the original target to the same object. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From stefan_ml at behnel.de Sun May 2 00:44:11 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 02 May 2010 06:44:11 +0200 Subject: [capi-sig] SWIG + expy In-Reply-To: <652256E5-5D3A-41DE-A7C5-6BED41F5944E@cwi.nl> References: <272522.69975.qm@web54204.mail.re2.yahoo.com> <652256E5-5D3A-41DE-A7C5-6BED41F5944E@cwi.nl> Message-ID: Jack Jansen, 01.05.2010 23:40: > I would be very interested in a universal intermediate format for all > the interface generators. I'm still using a version of Guido's old bgen, > now grudgingly extended to handle C++ and do bidirectional bridging > between Python and C++, and while I love and cherish the code generator > the C++ parser is, uhm... challenging. Parsing C++ with per-line regular > expressions is no fun:-) > > I looked at gccxml at some point, as well as at some of the competing > Python interface generators, but it went nowhere. gccxml output is far > too detailed, and the output is too much of a simple parse tree to be of > any use. The intermediate formats of the other interface generators I > looked at were all too inaccessible. > > Maybe we can come up with something decent in this group? This sounds like a good topic for the CAPI-sig group, rather than for c.l.py. I suggest keeping subsequent discussion there. Stefan From alfps at start.no Sun May 2 01:05:26 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 02 May 2010 07:05:26 +0200 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On 02.05.2010 06:06, * Aahz: > In article<4bdcd631$0$27782$c3e8da3 at news.astraweb.com>, > Steven D'Aprano wrote: >> On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: >>> >>> The += family of operators really do rebind the symbol, not modify the >>> object. >> >> They potentially do both, depending on the object, even for built-ins. > > No, they always rebind; sometimes they modify the object If they always rebind and sometimes modify object then they "potentially do both", and so the "No" at the start of the sentence contradicts this later part. > and sometimes > they rebind the original target to the same object. At the Python level that seems to be an undetectable null-operation. Granted one could see something going on in a machine code or byte code debugger. But making that distinction (doing nothing versus self-assignment) at the Python level seems, to me, to be meaningless. Cheers, - Alf From clp2 at rebertia.com Sun May 2 01:19:23 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 1 May 2010 22:19:23 -0700 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On Sat, May 1, 2010 at 10:05 PM, Alf P. Steinbach wrote: > On 02.05.2010 06:06, * Aahz: >> In article<4bdcd631$0$27782$c3e8da3 at news.astraweb.com>, >> Steven D'Aprano ?wrote: >>> >>> On Sat, 01 May 2010 07:13:42 -0500, Tim Chase wrote: >>>> >>>> The += family of operators really do rebind the symbol, not modify the >>>> object. >>> >>> They potentially do both, depending on the object, even for built-ins. >> >> No, they always rebind; sometimes they modify the object > > If they always rebind and sometimes modify object then they "potentially do > both", and so the "No" at the start of the sentence contradicts this later > part. > > >> and sometimes >> they rebind the original target to the same object. > > At the Python level that seems to be an undetectable null-operation. Granted > one could see something going on in a machine code or byte code debugger. > But making that distinction (doing nothing versus self-assignment) at the > Python level seems, to me, to be meaningless. There are some circumstances where the subtle distinction matters. Consider x.y += z where x is an instance of a class that overrides __setattr__ and __getattribute__ and x.y results in a mutable object. Not doing the assignment can result in a noticeable difference in behavior since __setattr__ won't get called. Yes, this is a slightly obscure case, but it does come up. Cheers, Chris -- http://blog.rebertia.com From porterj at alum.rit.edu Sun May 2 02:03:19 2010 From: porterj at alum.rit.edu (James Porter) Date: Sun, 02 May 2010 01:03:19 -0500 Subject: sometype.__new__ and C subclasses Message-ID: I've been trying to write a Python C extension module that uses NumPy and has a subtype of numpy.ndarray written in C. However, I've run into a snag: calling numpy.ndarray.__new__(mysubtype, ...) triggers an exception in the bowels of Python (this is necessary for a handful of NumPy features). I'm posting to this list to try to figure out why this exception exists in the first place, and what (if anything) I can do to work around it. The exception in question happens in Objects/typeobject.c in tp_new_wrapper. Here's the comment for the block: /* Check that the use doesn't do something silly and unsafe like object.__new__(dict). To do this, we check that the most derived base that's not a heap type is this type. */ The code has the end effect that basetype.__new__(subtype, ...) fails whenever subtype is a statically-defined type (i.e. a normal C extension type object). Why is this necessary in general? I can see why it might be bad for a limited number of core Python types, but it seems unnecessarily limiting for Python C extensions. On a more practical note, is there a way (short of rewriting the subtype in Python) to work around this? It seems that I could call the type metaclass to create a heap type in C, but I'm not sure of all the implications of that. Thanks in advance, Jim From kaleem.adil at gmail.com Sun May 2 02:03:22 2010 From: kaleem.adil at gmail.com (Adil Kaleem) Date: Sat, 1 May 2010 23:03:22 -0700 (PDT) Subject: Help needed in downloading Brown corpus References: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> <843870Fj4oU1@mid.individual.net> Message-ID: <3a537cd0-4716-420a-b271-0e9904566133@u20g2000pru.googlegroups.com> On May 1, 10:54?pm, Peter Pearson wrote: > > As I understand it (from Wikipedia), the Brown Corpus is a > collection of samples of modern American English text, and > nltk.org provides a Python toolkit for exploring said Corpus. > > I'm trying to figure out whether you're trying to get the > Corpus or the toolkit. ?Neither interpretation looks > plausible: if you're after the Corpus itself and you don't > know a bit of Python, why are you struggling with Python? > On the other hand, if you're after the toolkit, what's the > problem? People download Python modules all the time. ?And > besides, why would you be after the toolkit if you don't > know a bit of Python? > > If your goal is to learn enough Python to use the toolkit, > you'll find this newsgroup full of smart and helpful people. > > But you'll have to be a little more explicit about what > you're trying to do and more specific about what obstacles > you encounter. ?As you might see by looking at other threads > on this newsgroup, the queries that get the most prompt and > useful responses usually include blocks of quoted text of > the form "I type this [cut-and-pasted block] and get > this response [another cut-and-pasted block]." > > -- > To email me, substitute nowhere->spamcop, invalid->net. Hi Peter, Thanks for replying. Appreciate your pain in writing. I'm sorry I wasn't proper in my question. I downloaded the toolkit and from it I wanted to download the corpora. But since my system is behind the proxy (no direct connection), I couldn't download the corpora as was the process told for downloading using Python IDLE. The exact steps/ codes to write were given on the website for downloading but was only for a direct connection. I didn't knew the process of configuring IDLE for a proxy network for the download. And lastly since I'm unaware of Python programming, I faced the problem. This was my total essence of the problem and in this regard, I sought to take help from the very best of this language knowers i.e, you all. But nonetheless, I got my problem solved. One amongst you, Shashank Singh, in this group helped me in solving the problem. I thank him again for taking all the pain in making the system work for me. Thanks Shashank, I owe you man. Thank you Peter for giving your precious time in reading and replying to my problem. From kaleem.adil at gmail.com Sun May 2 02:09:24 2010 From: kaleem.adil at gmail.com (Adil Kaleem) Date: Sat, 1 May 2010 23:09:24 -0700 (PDT) Subject: Help needed in downloading Brown corpus References: <1cc3f7fa-b78c-4318-8eda-c345769d1eca@t26g2000prt.googlegroups.com> <4bdcd5b2$0$27782$c3e8da3@news.astraweb.com> Message-ID: <867f8d34-64c0-4ce1-90e0-de8c9c30bf9a@n37g2000prc.googlegroups.com> On May 2, 6:30?am, Steven D'Aprano wrote: > On Sat, 01 May 2010 06:28:33 -0700, Adil Kaleem wrote: > > Hi all > > I'm a masters student in NLP. I needed to download the Brown corpus. I'm > > unable to download from nltk.org with the python CLI. My network > > connection is behind a proxy server so it's creating a problem. Since I > > don't know a bit of python, so unable to figure a way out. > > This has nothing to do with Python, it is a network issue. Talk to your > network administrator and get him to fix the proxy, or give you a way to > bypass it. Or if you have an internet connection at home, download it > from there. > > -- > Steven Hi Steven, It all had to do with configuring the network from Python IDLE, aliter: It all had to do with Python. I could have done it, the bypasssing. But I couldn't have learned anything if I hadn't fought with the problem, of course it was Shashank Singh from this group who helped me through. Bypassing is always not good, atleast for me and therefore I came to seek the help of you all. Thanks Steven in reading and replying to my problem. -- Adil From lie.1296 at gmail.com Sun May 2 02:28:28 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 02 May 2010 16:28:28 +1000 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4bdcce21$0$27782$c3e8da3@news.astraweb.com> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> <4bdcce21$0$27782$c3e8da3@news.astraweb.com> Message-ID: <4bdd1bea$1@dnews.tpgi.com.au> On 05/02/10 10:58, Steven D'Aprano wrote: >> > And Python's object system >> > makes it that the argument to __getattr__ is always a string even though >> > there might be a valid variable that corresponds to it: > That is nothing to do with the object system, it is related to the > semantics of Python syntax. a.b doesn't mean "apply the binary dot > operator to arguments a and b". It is syntactic sugar for "look for an > attribute named 'b' on object a". As such, the operands that __getattr__ > receives are the object a and the *name* b (implemented as a string). You just described *exactly* the reason why dot is not, and cannot be an operator. From lie.1296 at gmail.com Sun May 2 03:09:36 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 02 May 2010 17:09:36 +1000 Subject: Python dot-equals (syntax proposal) In-Reply-To: <4bdcce21$0$27782$c3e8da3@news.astraweb.com> References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> <4bdcce21$0$27782$c3e8da3@news.astraweb.com> Message-ID: <4bdd258e$1@dnews.tpgi.com.au> On 05/02/10 10:58, Steven D'Aprano wrote: > On Sun, 02 May 2010 05:08:53 +1000, Lie Ryan wrote: > >> > On 05/01/10 11:16, Steven D'Aprano wrote: >>> >> On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote: >>> >> >>> >> In practice though, I think that's a difference that makes no >>> >> difference. It walks like an operator, it swims like an operator, and >>> >> it quacks like an operator. >>> >> >>> >> >> > Nope it's not. A full-time operator in python have a reflected version >> > (e.g. __radd__), which dot does not have. > What are the reflected versions of __eq__ and __ne__ (binary == and != > operators)? Python do not have them now, but it does make sense if python have them[1]. OTOH, given current python's language semantic, __rgetattr__ doesn't make any sense; adding __rgetattr__ would require a quite fundamental change to the language's semantic, primarily how attribute resolution works. [1] though they'd probably be dismissed as bad idea since equality and inequality are supposed to be a symmetric relation; reflected (in)equality makes it way too easy to break that premise > And __neg__, __pos__ and __inv__ (for the unary - + and ~ operators)? > > And the three-argument form of __pow__ for power(1, 2, x)? I know you're a famed nitpicker, but don't be silly, reflected operator, by definition, only makes sense for binary operator. From news3 at mystrobl.de Sun May 2 03:16:10 2010 From: news3 at mystrobl.de (Wolfgang Strobl) Date: Sun, 02 May 2010 09:16:10 +0200 Subject: pyjamas 0.7 released References: <5cf8017c-d2e1-4ee4-b5d4-48e0cda19396@i37g2000yqn.googlegroups.com> <823f6745-c63a-45c5-a11e-860b7f344262@o11g2000yqj.googlegroups.com> <518it5t6hpvv4pdlue6cljmb09mse7ctov@4ax.com> <80d02ac5-b6ed-43fa-9508-67996cbedfde@b18g2000yqb.googlegroups.com> Message-ID: lkcl : > at least _some_ input would be good! the knowledge doesn't have to >be there: just the bugreports saying "there's a problem and here's >exactly how you reproduce it" would be a start! >> So please make it simpler for more people to help. > ... how?? there's a bugtracker, wiki, svn repository, over 30 >examples and a developer list. the code really _is_ very very small >(the UI widget set, with around 75 widgets, minus the license header >text is only around 4,000 lines _total_, making it very very simple >and very very easy for people to get used to). suggestions welcome! Well, the bunch of programming languages and APIs I collected over the years is large enough already. These days I prefer to stay with python and c, spiced with an occasional domain specific language. That's why I was attracted by pyjamas, to begin with!. If I'd like to program using Eclipse and Java or fool around with JavaScript, I'd do just that. But I don't. IMHO, that ist a general problem of translation tools - they attract the wrong people, from the point of view a developer who looks for people sharing some of the workload. :-) So, Luke, I can only answer your question from the point of view of somebody who is mostly a potentional consumer of your work, and most problably not another developer. If you want to delegate some work you'd like not to do yourself (for example because you prefer designing and coding to testing and reorganizing and polishing the docs), than you have at least to _define_ those pieces and to monitor progress. > >> Other people have >> other projects, where they invest some of their own time and money in. > > yes. been there. didn't receive any return on investment. did some >projects. received about 25% of required money to pay bills. need >?15k pa; receiving approximately ?7-8k. > >> >> ?I didn't look at >> >> every example again, but AFAIK, this didn't change with 0.7. (Tried with >> >> Python 2.6.4/5 on WinXP/7 with Firefox and Chrome, if that matters). >> >> > then please issue bugreports for as many as you feel comfortable >> >with / have time for. ? Well, ok. I put my notes in a Google chart, see http://spreadsheets.google.com/pub?key=0Au5LhqNQyrfCdGpDbTVjZFJwSERzVUFXVlg5bWl2enc I had to write a short patch against compile.py (see issue 397) in order to make it compile the showcase examples on Windows. In addition, I've tried to create Selenium tests for automating the time consuming job of checking all those examples, using Selenium IDE in Firefox. I was my first experience using this against Ajax apps. The results are somewhat mixed. Playing a round of "lightout" was a breeze, but so far I hadn't much luck in driving the showcase example(s). I didn't try very hard, though, because I ran out of time, as I do now. -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From tjreedy at udel.edu Sun May 2 04:04:11 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 May 2010 04:04:11 -0400 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On 5/2/2010 1:05 AM, Alf P. Steinbach wrote: > On 02.05.2010 06:06, * Aahz: >> and sometimes >> they rebind the original target to the same object. > > At the Python level that seems to be an undetectable null-operation. If you try t=(1,2,3); t[1]+=3, if very much matters that a rebind occurs. > Granted one could see something going on in a machine code or byte code > debugger. But making that distinction (doing nothing versus > self-assignment) at the Python level seems, to me, to be meaningless. Please do not confuse things. Augmented *assignment* must be understood as assignment. Failure to do so leads (and has lead) newbies into confusion, and puzzled posts on this list. Terry Jan Reedy From steve at REMOVE-THIS-cybersource.com.au Sun May 2 05:21:16 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 09:21:16 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> <4bdcce21$0$27782$c3e8da3@news.astraweb.com> <4bdd1bea$1@dnews.tpgi.com.au> Message-ID: <4bdd440b$0$27782$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 16:28:28 +1000, Lie Ryan wrote: > On 05/02/10 10:58, Steven D'Aprano wrote: >>> > And Python's object system >>> > makes it that the argument to __getattr__ is always a string even >>> > though there might be a valid variable that corresponds to it: >> That is nothing to do with the object system, it is related to the >> semantics of Python syntax. a.b doesn't mean "apply the binary dot >> operator to arguments a and b". It is syntactic sugar for "look for an >> attribute named 'b' on object a". As such, the operands that >> __getattr__ receives are the object a and the *name* b (implemented as >> a string). > > You just described *exactly* the reason why dot is not, and cannot be an > operator. This would be relevant if I said it was an operator. I did not. I said it was a de facto operator that behaves similarly enough to operators as to make it reasonable to talk about "dot operator". I still stand by that. That doesn't imply that Python's implementation of a.b has to be identical in every last detail to Python's implementation of a+b, because it clearly isn't. But there are sufficient similarities to justify saying that it duck-types as an operator. This isn't meant to be a vigorous statement of fact in the same manner than "CPython implements lists as arrays of pointers" is a statement of fact. It's meant to be a hand-wavy "dot act kinda-sorta like an operator" manner. I'm sorry if I failed to make that clear enough. I thought that explicitly stating that it wasn't a real operator would be sufficient. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun May 2 05:24:23 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 09:24:23 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdb80e4$0$8757$c3e8da3@news.astraweb.com> <4bdc7ca3$1@dnews.tpgi.com.au> <4bdcce21$0$27782$c3e8da3@news.astraweb.com> <4bdd258e$1@dnews.tpgi.com.au> Message-ID: <4bdd44c7$0$27782$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 17:09:36 +1000, Lie Ryan wrote: > On 05/02/10 10:58, Steven D'Aprano wrote: >> On Sun, 02 May 2010 05:08:53 +1000, Lie Ryan wrote: >> >>> > On 05/01/10 11:16, Steven D'Aprano wrote: >>>> >> On Fri, 30 Apr 2010 12:34:34 -0400, D'Arcy J.M. Cain wrote: >>>> >> >>>> >> In practice though, I think that's a difference that makes no >>>> >> difference. It walks like an operator, it swims like an operator, >>>> >> and it quacks like an operator. >>>> >> >>>> >> >>> > Nope it's not. A full-time operator in python have a reflected >>> > version (e.g. __radd__), which dot does not have. >> What are the reflected versions of __eq__ and __ne__ (binary == and != >> operators)? > > Python do not have them now, but it does make sense if python have > them[1]. OTOH, given current python's language semantic, __rgetattr__ > doesn't make any sense; adding __rgetattr__ would require a quite > fundamental change to the language's semantic, primarily how attribute > resolution works. > > [1] though they'd probably be dismissed as bad idea since equality and > inequality are supposed to be a symmetric relation; reflected > (in)equality makes it way too easy to break that premise > >> And __neg__, __pos__ and __inv__ (for the unary - + and ~ operators)? >> >> And the three-argument form of __pow__ for power(1, 2, x)? > > I know you're a famed nitpicker, but don't be silly, reflected operator, > by definition, only makes sense for binary operator. Binary operators aren't the only kind of operator, and you claimed that: "A full-time operator in python have a reflected version". But there are full-time operators that don't have reflected versions, so your claim is just *wrong*. It would still be wrong even if you had limited yourself to binary operators. I have agreed with you that there are useful things people might want to do (e.g. function composition) that you can't do because the "dot operator" isn't a *real* operator with exactly the same semantics as "plus operator", "multiply operator" and friends. I think we're in violent agreement, and merely disagreeing over semantics. There's no need to continue arguing against a position I haven't actually taken :) -- Steven From pavlovevidence at gmail.com Sun May 2 05:34:54 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 02:34:54 -0700 (PDT) Subject: sometype.__new__ and C subclasses References: Message-ID: On May 1, 11:03?pm, James Porter wrote: > I've been trying to write a Python C extension module that uses NumPy > and has a subtype of numpy.ndarray written in C. However, I've run into > a snag: calling numpy.ndarray.__new__(mysubtype, ...) triggers an > exception in the bowels of Python (this is necessary for a handful of > NumPy features). I'm posting to this list to try to figure out why this > exception exists in the first place, and what (if anything) I can do to > work around it. > > The exception in question happens in Objects/typeobject.c in > tp_new_wrapper. Here's the comment for the block: > > ? ? ? ? /* Check that the use doesn't do something silly and unsafe like > ? ? ? ? ? ?object.__new__(dict). ?To do this, we check that the > ? ? ? ? ? ?most derived base that's not a heap type is this type. */ > > The code has the end effect that basetype.__new__(subtype, ...) fails > whenever subtype is a statically-defined type (i.e. a normal C extension > type object). Why is this necessary in general? I can see why it might > be bad for a limited number of core Python types, but it seems > unnecessarily limiting for Python C extensions. Why don't you use mysubtype.__new__(mysubtype,...)? If you wrote mysubtype in C, and defined a different tp_new than ndarray, then this exception will trigger. And it ought to; you don't want to use ndarray's tp_new to create an object of your subclass, if you've defined a different tp_new. > On a more practical note, is there a way (short of rewriting the subtype > in Python) to work around this? It seems that I could call the type > metaclass to create a heap type in C, but I'm not sure of all the > implications of that. It should work if you use mysubtype.__new__(mysubtype,...). If it doesn't do what you want, then there's probably something wrong with the way you subclassed ndarray. Carl Banks From pavlovevidence at gmail.com Sun May 2 05:52:13 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 02:52:13 -0700 (PDT) Subject: PyObject_SetAttrString - doesn't set instance attribute References: <82ae0f7b-e5f4-4b85-a9fb-aef16de10af2@a39g2000prb.googlegroups.com> Message-ID: <1579c863-c7e2-47ba-ae45-b3ba74eff40c@a39g2000prb.googlegroups.com> On May 1, 4:04?am, Jason wrote: > I'm having a bit of trouble with C/Python bindings. Particularly, > trying to set an instance variable from C when the object is > initialised using PyObject_SetAttrString, but nothing seems to happen. > The C initialisation code is: > > static void > nautilus_python_object_instance_init (NautilusPythonObject *object) > { > > ? ? ? ? fprintf(stderr, "nautilus_python_object_instance_init called\n"); > > ? ? ? ? NautilusPythonObjectClass *class; > ? ? ? ? debug_enter(); > > ? ? ? ? class = (NautilusPythonObjectClass*)(((GTypeInstance*)object)- > > >g_class); > > ? ? ? ? object->instance = PyObject_CallObject(class->type, NULL); > > ? ? ? ? PyObject* test_int = PyInt_FromLong(42); > > ? ? ? ? if (object->instance == NULL) > ? ? ? ? { > ? ? ? ? ? ? ? ? PyErr_Print(); > ? ? ? ? } > ? ? ? ? else > ? ? ? ? { > ? ? ? ? ? ? ? ? fprintf(stderr, "Setting magic parameter\n"); > ? ? ? ? ? ? ? ? fprintf(stderr, "From C: "); > ? ? ? ? ? ? ? ? PyObject_Print(object->instance, stderr, 0); > ? ? ? ? ? ? ? ? fprintf(stderr, "\n"); > ? ? ? ? ? ? ? ? int retval = PyObject_SetAttrString(object->instance, > "super_happy_magic", test_int); > ? ? ? ? ? ? ? ? fprintf(stderr, "Result: %i\n", retval); > ? ? ? ? } > > ? ? ? ? Py_DECREF(test_int); > > } Not sure what you're doing here. It looks like you are being passed an object of a given type, then you get the type object, call it to create another object of that type, and assign it to object->instance. > ...and the Python module contains: > > class MenuProviderTest(nautilus.MenuProvider): > > ? ? def __init__(self): > ? ? ? ? print "From Python: %s" % self > > ? ? ? ? try: > ? ? ? ? ? ? print getattr(self, "super_happy_magic") > ? ? ? ? except AttributeError: > ? ? ? ? ? ? print "Didn't work!" > > When the MenuProviderTest is created, the output is: > > nautilus_python_object_instance_init called > Setting magic parameter > From C: > Result: 0 > From Python: > Didn't work! > > (I've tried getattr and self.super_happy_magic, with the same effect.) > > Where am I going wrong? You are assigning the attirbute the the object that the C code refers to as "object->instance", but it seems that in the Python snippet you are calling getattr on the object that the C code refers to as "object". Carl Banks From michelparker at live.com Sun May 2 06:00:14 2010 From: michelparker at live.com (michel parker) Date: Sun, 2 May 2010 11:00:14 +0100 Subject: help error : Failed to build these modules: _dbm Message-ID: Hi, When i make python 3.1 on my ubuntu 9.10 i get following error : Failed to build these modules: _dbm Please help me. I have done : apt-get build-dep python2.5 but to no avail. Cheers _________________________________________________________________ Hotmail: Free, trusted and rich email service. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun May 2 06:08:55 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 10:08:55 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: <4bdd4f37$0$27782$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 04:04:11 -0400, Terry Reedy wrote: > On 5/2/2010 1:05 AM, Alf P. Steinbach wrote: >> On 02.05.2010 06:06, * Aahz: > >>> and sometimes >>> they rebind the original target to the same object. >> >> At the Python level that seems to be an undetectable null-operation. > > If you try t=(1,2,3); t[1]+=3, if very much matters that a rebind > occurs. > >> Granted one could see something going on in a machine code or byte code >> debugger. But making that distinction (doing nothing versus >> self-assignment) at the Python level seems, to me, to be meaningless. > > Please do not confuse things. Augmented *assignment* must be understood > as assignment. Failure to do so leads (and has lead) newbies into > confusion, and puzzled posts on this list. I think that if you think *only* about Python's standard namespaces, self- assignment is more or less a no-op. I can't think of any way that x = x could do anything other than use CPU cycles, *if* you limit yourself to the standard global or function local namespaces. But if you think about custom namespace types, and item assignment (e.g. the example you gave with a tuple), the situation becomes different. Here's a nice example, using Python 3.1: >>> class B(A): # class A defined elsewhere -- see below. ... x = 1 ... x = x ... Traceback (most recent call last): File "", line 1, in File "", line 3, in B File "", line 4, in __setitem__ TypeError: can't rebind constants Thus proving that self-assignment is not necessarily a no-op. How did I make that work? It takes a custom dict and a bit of metaclass magic: class ConstantNamespace(dict): def __setitem__(self, key, value): if key in self: raise TypeError("can't rebind constants") super(ConstantNamespace, self).__setitem__(key, value) class WriteOnceClass(type): @classmethod def __prepare__(metacls, name, bases): return ConstantNamespace() def __new__(cls, name, bases, classdict): return type.__new__(cls, name, bases, classdict) class A(metaclass=WriteOnceClass): pass -- Steven From jason.heeris at gmail.com Sun May 2 06:26:46 2010 From: jason.heeris at gmail.com (Jason) Date: Sun, 2 May 2010 03:26:46 -0700 (PDT) Subject: PyObject_SetAttrString - doesn't set instance attribute References: <82ae0f7b-e5f4-4b85-a9fb-aef16de10af2@a39g2000prb.googlegroups.com> <1579c863-c7e2-47ba-ae45-b3ba74eff40c@a39g2000prb.googlegroups.com> Message-ID: <751257bd-5d92-4ec9-bec9-41369b5d31e5@y18g2000prn.googlegroups.com> On May 2, 5:52?pm, Carl Banks wrote: > Not sure what you're doing here. ?It looks like you are being passed > an object of a given type, then you get the type object, call it to > create another object of that type, and assign it to object->instance. Sorry, I should have noted that the "NautilusPythonObject" type in the code is a struct defined as: struct _NautilusPythonObject { GObject parent_slot; PyObject *instance; }; > You are assigning the attirbute the the object that the C code refers > to as "object->instance", but it seems that in the Python snippet you > are calling getattr on the object that the C code refers to as > "object". object->instance is the PyObject, and I gathered that it was the correct thing to assign to from the fact that the address is identical as seen from C and Python. ? Jason From kushal.kumaran+python at gmail.com Sun May 2 07:08:28 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sun, 2 May 2010 16:38:28 +0530 Subject: help error : Failed to build these modules: _dbm In-Reply-To: References: Message-ID: On Sun, May 2, 2010 at 3:30 PM, michel parker wrote: > Hi, > When i make python 3.1 on my ubuntu 9.10 i get following error : > > Failed to build these modules: > _dbm > Please help me. > I have done : > > apt-get build-dep python2.5 > > but to no avail. > Cheers > > Probably the packages libdb4.7-dev (if you want berkeley db) or libgdbm-dev (if you want gnu dbm). ISTR there was a thread about this just a couple of days ago. -- regards, kushal From michelparker at live.com Sun May 2 07:56:57 2010 From: michelparker at live.com (michel parker) Date: Sun, 2 May 2010 12:56:57 +0100 Subject: help error : Failed to build these modules: _dbm In-Reply-To: References: , Message-ID: hi, yup problem solved module was missing libgdbm-dev > From: kushal.kumaran+python at gmail.com > Date: Sun, 2 May 2010 16:38:28 +0530 > Subject: Re: help error : Failed to build these modules: _dbm > To: michelparker at live.com > CC: python-list at python.org > > On Sun, May 2, 2010 at 3:30 PM, michel parker wrote: > > Hi, > > When i make python 3.1 on my ubuntu 9.10 i get following error : > > > > Failed to build these modules: > > _dbm > > Please help me. > > I have done : > > > > apt-get build-dep python2.5 > > > > but to no avail. > > Cheers > > > > > > Probably the packages libdb4.7-dev (if you want berkeley db) or > libgdbm-dev (if you want gnu dbm). > > ISTR there was a thread about this just a couple of days ago. > > -- > regards, > kushal _________________________________________________________________ Hotmail: Trusted email with powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From michelparker at live.com Sun May 2 07:59:35 2010 From: michelparker at live.com (michel parker) Date: Sun, 2 May 2010 12:59:35 +0100 Subject: help req setting python executable Message-ID: hi, i have just installed python3.1 with opt=g option. but when i set python executable in wingide to usr/local/bin/python3.1 it says : Some values are invalid: - Python executable 'usr/local/bin/python3.1' is not in path Please correct the values and try again. Please help. What is going to be correct pythonpath for me. i have installed python using standard sudo make install method. Cheers _________________________________________________________________ Hotmail: Powerful Free email with security by Microsoft. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmitrey.kroshko at scipy.org Sun May 2 08:11:40 2010 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 2 May 2010 05:11:40 -0700 (PDT) Subject: Bug in Python set Message-ID: <0bd314a8-db65-43f1-a999-521e2ed71cad@n15g2000yqf.googlegroups.com> Python 2.6.5 r265:79063 >>>set().update(set()) is None True while I expect result of update to be set. Also, result of set().add(None) is None while I expect it to be set with element None (or, maybe, it should be empty set?) Regards, D. From albert at spenarnc.xs4all.nl Sun May 2 08:12:23 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 02 May 2010 12:12:23 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> Message-ID: In article , Jean-Michel Pichavant wrote: >Jabapyth wrote: >> At least a few times a day I wish python had the following shortcut >> syntax: >> >> vbl.=func(args) >> >> this would be equivalent to >> >> vbl = vbl.func(args) >> >> example: >> >> foo = "Hello world" >> foo.=split(" ") >> print foo >> # ['Hello', 'world'] >> >> and I guess you could generalize this to >> >> vbl.=[some text] >> # >> vbl = vbl.[some text] >> >> e.g. >> >> temp.=children[0] >> # temp = temp.children[0] >> >> thoughts? >> >Useless if you use meaningful names for your variables & attributes. > >It may happen that one object attribute refer to an object of the same >type, but it is quite rare that both can share the same name anyway. > >Possible use cases: > >1/ >car = Car() >car = car.wheel # ??? > >2/ >wheel = Car() # ??? >wheel = wheel.wheel # ??? > >3/ >currentCar = Car() >currentCar = currentCar.nextCar > >The syntax you prose will be applicable on very little assignements (use >case 3). I'm not sure it's worth it. Note how related it is to the requirement to have a _radd_ operator. It amounts to the argument that a op= b requires that a and b have somewhat "similar" "type", or that the "type" of a doesn't really change as a result from the operation. This is IMHO an argument against the .= pseudo-operator. > >JM Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From __peter__ at web.de Sun May 2 08:13:02 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2010 14:13:02 +0200 Subject: recommended way to insert data into a one to many relationship using python References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Peter Otten wrote: If you create indices for floors (and rooms) cur.execute("""create unique index room_index on rooms (fid, number);""") cur.execute("""create unique index floor_index on floors (floor);""") the addition of missing rows can be simplified to missing = c2.execute("""select distinct floor from new_employees;""") cur.executemany("insert or ignore into floors (floor) values (?)", missing) etc. Peter From aahz at pythoncraft.com Sun May 2 08:23:23 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 May 2010 05:23:23 -0700 Subject: Bug in Python set References: <0bd314a8-db65-43f1-a999-521e2ed71cad@n15g2000yqf.googlegroups.com> Message-ID: In article <0bd314a8-db65-43f1-a999-521e2ed71cad at n15g2000yqf.googlegroups.com>, dmitrey wrote: > >Python 2.6.5 r265:79063 >>>>set().update(set()) is None >True >while I expect result of update to be set. >Also, result of >set().add(None) >is None while I expect it to be set with element None (or, maybe, it >should be empty set?) Why are you assuming that your expectations are correct? Generally speaking, Python methods that mutate do *not* return the original object, precisely to make sure you don't make stupid mistakes. You should probably read this: http://www.catb.org/~esr/faqs/smart-questions.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From albert at spenarnc.xs4all.nl Sun May 2 08:23:45 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 02 May 2010 12:23:45 GMT Subject: matching strings in a large set of strings References: <877hnpjtdw.fsf@rudin.co.uk> Message-ID: In article <877hnpjtdw.fsf at rudin.co.uk>, Paul Rudin wrote: >"Karin Lagesen" writes: > >> Hello. >> >> I have approx 83 million strings, all 14 characters long. I need to be >> able to take another string and find out whether this one is present >> within the 83 million strings. >> >> Now, I have tried storing these strings as a list, a set and a dictionary. >> I know that finding things in a set and a dictionary is very much faster >> than working with a list, so I tried those first. However, I run out of >> memory building both the set and the dictionary, so what I seem to be left >> with is the list, and using the in method. >> >> I imagine that there should be a faster/better way than this? >> > >Shouldn't a set with 83 million 14 character strings be fine in memory >on a stock PC these days? I suppose if it's low on ram you might start >swapping which will kill performance. Perhaps the method you're using to >build the data structures creates lots of garbage? How much ram do you >have and how much memory does the python process use as it builds your >data structures? And if this is practical there should be no swapping problems, as the working set will be a small fraction of the data used. > >There are other algorithms you can use that have better theoretical >performance than using bisect for this particular problem, but you get >into trade offs between executing things in python as opposed to C if >you start to hand code things in python. There are a lot of possibility, but they depend a great deal on secondary conditions, like how often the 83 M dataset changes. Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From steve at REMOVE-THIS-cybersource.com.au Sun May 2 09:12:10 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 13:12:10 GMT Subject: Bug in Python set References: <0bd314a8-db65-43f1-a999-521e2ed71cad@n15g2000yqf.googlegroups.com> Message-ID: <4bdd7a2a$0$27857$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 05:11:40 -0700, dmitrey wrote: > Python 2.6.5 r265:79063 >>>>set().update(set()) is None > True > while I expect result of update to be set. Change your expectations. Generally, methods which modify the object rather than creating a new one return None. >>> s = set([1,2,3]) >>> s.update(set([3, 4, 5])) >>> s {1, 2, 3, 4, 5} > Also, result of set().add(None) is None while I expect it to be set > with element None (or, maybe, it should be empty set?) >>> s = set() >>> s.add(None) >>> s {None} Python sets have been used by tens of thousands of programmers for many years now. Which do you think is more likely? (1) Not one person before you noticed that something as fundamental as adding an item to a set is buggy; or (2) You have misunderstood what is happening? -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun May 2 10:57:30 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 14:57:30 GMT Subject: List size versus list allocation Message-ID: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> Python lists are over-allocated: whenever they need to be resized, they are made a little bit larger than necessary so that appends will be fast. See: http://code.python.org/hg/trunk/file/e9d930f8b8ff/Objects/listobject.c I'm interested in gathering some statistics on this, and to do so I need a way of measuring the list's logical size versus its actual size. The first is easy: it's just len(list). Is there some way of getting the allocated size of the list? -- Steven From hansmu at xs4all.nl Sun May 2 11:07:29 2010 From: hansmu at xs4all.nl (Hans Mulder) Date: Sun, 02 May 2010 17:07:29 +0200 Subject: Fast Efficient way to transfer an object to another list In-Reply-To: <06366a6d-e3db-4963-bcc0-0bc03d035a94@e2g2000yqn.googlegroups.com> References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> <06366a6d-e3db-4963-bcc0-0bc03d035a94@e2g2000yqn.googlegroups.com> Message-ID: <4bdd953c$0$22933$e4fe514c@news.xs4all.nl> Francesco Bochicchio wrote: > Anyway i think that list.extract( old_list, predicate ) -> new_list > would be a nice addition to the standard library You could use filter( predicate, old_list ) -> new_list -- HansM From darcy at druid.net Sun May 2 11:10:10 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 2 May 2010 11:10:10 -0400 Subject: help req setting python executable In-Reply-To: References: Message-ID: <20100502111010.5ef5748d.darcy@druid.net> On Sun, 2 May 2010 12:59:35 +0100 michel parker wrote: > > hi, > i have just installed python3.1 with opt=g option. > but when i set python executable in wingide to usr/local/bin/python3.1 it says : I don't know anything about wingide but I think your problem is simply a missing slash. /usr/local/bin/python3.1 -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From __peter__ at web.de Sun May 2 11:52:05 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2010 17:52:05 +0200 Subject: List size versus list allocation References: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Python lists are over-allocated: whenever they need to be resized, they > are made a little bit larger than necessary so that appends will be fast. > > See: > > http://code.python.org/hg/trunk/file/e9d930f8b8ff/Objects/listobject.c > > I'm interested in gathering some statistics on this, and to do so I need > a way of measuring the list's logical size versus its actual size. The > first is easy: it's just len(list). Is there some way of getting the > allocated size of the list? With some brute force guesswork... >>> a = [None] * 42 >>> for i in range(10): ... print i, ctypes.c_ulong.from_address(id(a)+i*8) ... 0 c_ulong(1L) 1 c_ulong(8488896L) 2 c_ulong(42L) 3 c_ulong(37432768L) 4 c_ulong(42L) 5 c_ulong(1L) 6 c_ulong(8510496L) 7 c_ulong(32L) 8 c_ulong(18446744073709551615L) 9 c_ulong(8935143189711421440L) >>> a = [] >>> for i in range(42): a.append(None) ... >>> for i in range(10): ... print i, ctypes.c_ulong.from_address(id(a)+i*8) ... 0 c_ulong(1L) 1 c_ulong(8488896L) 2 c_ulong(42L) 3 c_ulong(40136160L) 4 c_ulong(46L) 5 c_ulong(0L) 6 c_ulong(0L) 7 c_ulong(0L) 8 c_ulong(0L) 9 c_ulong(0L) ... you can see that the size sits at offset 4*sizeof(long) on my 64-bit Python. With that information we can take a look at a list's overallocation strategy: >>> a = [] >>> for i in range(20): ... print i, ctypes.c_ulong.from_address(id(a)+4*8) ... a.append(None) ... 0 c_ulong(0L) 1 c_ulong(4L) 2 c_ulong(4L) 3 c_ulong(4L) 4 c_ulong(4L) 5 c_ulong(8L) 6 c_ulong(8L) 7 c_ulong(8L) 8 c_ulong(8L) 9 c_ulong(16L) 10 c_ulong(16L) 11 c_ulong(16L) 12 c_ulong(16L) 13 c_ulong(16L) 14 c_ulong(16L) 15 c_ulong(16L) 16 c_ulong(16L) 17 c_ulong(25L) 18 c_ulong(25L) 19 c_ulong(25L) Peter From lists at cheimes.de Sun May 2 12:07:31 2010 From: lists at cheimes.de (Christian Heimes) Date: Sun, 02 May 2010 18:07:31 +0200 Subject: List size versus list allocation In-Reply-To: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> References: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> Message-ID: > I'm interested in gathering some statistics on this, and to do so I need > a way of measuring the list's logical size versus its actual size. The > first is easy: it's just len(list). Is there some way of getting the > allocated size of the list? With Python 2.6 and newer you can use sys.getsizeof() to get the actual size of the list object: >>> import sys, struct >>> sys.getsizeof([]) 72 >>> a = [1,2,3] >>> b = [] >>> b.append(1) >>> b.append(2) >>> b.append(3) >>> sys.getsizeof(a) 96 >>> sys.getsizeof(b) 104 >>> def slots(lst): ... return (sys.getsizeof(lst) - sys.getsizeof([])) / struct.calcsize("P") ... >>> slots(b) 4 >>> slots(a) 3 Christian From __peter__ at web.de Sun May 2 12:24:37 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2010 18:24:37 +0200 Subject: List size versus list allocation References: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> Message-ID: Christian Heimes wrote: >>>> def slots(lst): > ... return (sys.getsizeof(lst) - sys.getsizeof([])) / D'oh! Peter From ptmcg at austin.rr.com Sun May 2 13:14:44 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 2 May 2010 10:14:44 -0700 (PDT) Subject: condition and True or False Message-ID: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> While sifting through some code looking for old "x and y or z" code that might better be coded using "y if x else z", I came across this puzzler: x = and True or False What is "and True or False" adding to this picture? The boolean expression part is already evaluating to a boolean, so I don't understand why a code author would feel compelled to beat this one over the head with the additional "and True or False". I did a little code Googling and found a few other Python instances of this, but also many Lua instances. I'm not that familiar with Lua, is this a practice that one who uses Lua frequently might carry over to Python, not realizing that the added "and True or False" is redundant? Other theories? -- Paul From porterj at alum.rit.edu Sun May 2 13:48:01 2010 From: porterj at alum.rit.edu (James Porter) Date: Sun, 02 May 2010 12:48:01 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 5/2/2010 4:34 AM, Carl Banks wrote: > Why don't you use mysubtype.__new__(mysubtype,...)? > > If you wrote mysubtype in C, and defined a different tp_new than > ndarray, then this exception will trigger. And it ought to; you don't > want to use ndarray's tp_new to create an object of your subclass, if > you've defined a different tp_new. Unfortunately, I can't do that, since that call is in NumPy itself and it's part of their "standard" way of making instances of subclasses of ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, ...) to create new arrays based on the shape of other arrays. The Python version of the subclass is shown here: , and I'm trying to write something pretty similar in C. I'm trying to stay in C since everything else is in C, so it's easier to stay in C then to jump back and forth all the time. Maybe the real answer to this question is "NumPy is doing it wrong" and I should be on their list; still, it seems strange that the behavior is different between Python and C. - Jim From mount.sarah at gmail.com Sun May 2 14:06:52 2010 From: mount.sarah at gmail.com (Sarah Mount) Date: Sun, 2 May 2010 19:06:52 +0100 Subject: Python debuggers with sys.settrace() Message-ID: This is a bit of an odd question, but is there any way for a Python debugger to suppress I/O generated by the program which is being debugged? I guess an "obvious" thing to do would be to replace core parts of the standard library and change any relevant imports in the locals and globals dicts to fake ones which don't generate I/O, but this seems brittle as the standard library will change over time. Is it possible to modify the byte-compiled code in each stack frame? Or is there a simpler way to do this? Many thanks, Sarah -- Sarah Mount, Senior Lecturer, University of Wolverhampton website: http://www.snim2.org/ twitter: @snim2 From __peter__ at web.de Sun May 2 14:13:42 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2010 20:13:42 +0200 Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > x = and True or False > > What is "and True or False" adding to this picture? The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one > over the head with the additional "and True or False". > > I did a little code Googling and found a few other Python instances of > this, but also many Lua instances. I'm not that familiar with Lua, is > this a practice that one who uses Lua frequently might carry over to > Python, not realizing that the added "and True or False" is redundant? > > Other theories? If it were e. g. def f(): big_beast = list(range(10**100)) return big_beast and True or False x = f() it would prevent that a big_beast reference becomes visible outside the function and allow for immediate release of its memory. Peter From nulla.epistola at web.de Sun May 2 14:28:54 2010 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 02 May 2010 20:28:54 +0200 Subject: assigning multi-line strings to variables In-Reply-To: <34ec4b50-7a05-46af-aeed-a123e62a9267@z30g2000yqz.googlegroups.com> References: <7d91e94e-88fe-43e3-817e-b9a8f5cdb16a@u34g2000yqu.googlegroups.com> <4e25733e-eafa-477b-a84d-a64d139f7134@u34g2000yqu.googlegroups.com> <4bd868bd$1@dnews.tpgi.com.au> <4bd89846$1@dnews.tpgi.com.au> <83t5esFbnhU1@mid.individual.net> <34ec4b50-7a05-46af-aeed-a123e62a9267@z30g2000yqz.googlegroups.com> Message-ID: goldtech schrieb: > Thank you to posters for help to my question. Seems I had trouble with > triple quotes strings in the PythonWin shell. But using the Idle shell > things work as expected. But this is probably another issue...any way, > w/Idle's shell I got the "action" regarding multiline strings I > expected. What PythonWin version? I remember having had such trouble years ago, probably Python 1.something. Greetings Sibylle From zak.mc.kraken at libero.it Sun May 2 14:35:29 2010 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Sun, 02 May 2010 20:35:29 +0200 Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: Peter Otten wrote: > def f(): > big_beast = list(range(10**100)) > return big_beast and True or False > x = f() > > it would prevent that a big_beast reference becomes visible outside the > function and allow for immediate release of its memory. what's wrong in bool(big_beast)? -- By ZeD From robert.kern at gmail.com Sun May 2 14:43:08 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 02 May 2010 13:43:08 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 2010-05-02 12:48 , James Porter wrote: > On 5/2/2010 4:34 AM, Carl Banks wrote: >> Why don't you use mysubtype.__new__(mysubtype,...)? >> >> If you wrote mysubtype in C, and defined a different tp_new than >> ndarray, then this exception will trigger. And it ought to; you don't >> want to use ndarray's tp_new to create an object of your subclass, if >> you've defined a different tp_new. > > Unfortunately, I can't do that, since that call is in NumPy itself and > it's part of their "standard" way of making instances of subclasses of > ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, > ...) to create new arrays based on the shape of other arrays. > > The Python version of the subclass is shown here: > , > and I'm trying to write something pretty similar in C. I'm trying to > stay in C since everything else is in C, so it's easier to stay in C > then to jump back and forth all the time. > > Maybe the real answer to this question is "NumPy is doing it wrong" and > I should be on their list; still, it seems strange that the behavior is > different between Python and C. Perhaps things would be clearer if you could post the C code that you've written that fails. So far, you've only alluded at what you are doing using Python-syntax examples. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bryanjugglercryptographer at yahoo.com Sun May 2 15:05:32 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sun, 2 May 2010 12:05:32 -0700 (PDT) Subject: recommended way to insert data into a one to many relationship using python References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <16f716de-8a0c-455c-8eb5-dbed332a81fe@h20g2000prn.googlegroups.com> Wolfgang Meiners wrote: > one to many relationships are fairly common, i think. So there should be > a recommended way to insert data into such a relation using python. > > Given the following programm, what is the recommended way to insert the > list of NewEmployees to the database? > > ======================================================================== > # !python > # -*- coding: utf-8 -*- > > import sqlite3 > > con = sqlite3.connect(":memory:") > cur = con.cursor() > > cur.execute("""create table employees( > ? ? eid integer primary key autoincrement, > ? ? name text not null, > ? ? rid integer references rooms(rid))""") > > cur.execute("""create table rooms( > ? ? rid integer primary key autoincrement, > ? ? number integer, > ? ? fid integer references floors(fid))""") > > cur.execute("""create table floors( > ? ? fid integer primary key autoincrement, > ? ? floor text not null)""") > [...] > > NewEmployees ?=[] > NewEmployees.append({'name': 'George', 'room': 89, 'floor': 'third floor'}) > NewEmployees.append({'name': 'Ellen', 'room': 21, 'floor': 'first floor'}) > For that kind of insert to be well-defined, the pair (floor, room_number) must uniquely identify a room. When natural keys like that are availabe, they're the obvious choice for primary keys in the database schema. I suggested getting rid of fid and rid, as in: schema = """ CREATE TABLE floors ( floor TEXT PRIMARY KEY ); CREATE TABLE rooms ( floor TEXT REFERENCES floors, number INTEGER, PRIMARY KEY (floor, number) ); CREATE TABLE employees ( eid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, floor TEXT, room_number INTEGER, FOREIGN KEY (floor, room_number) REFERENCES rooms ) """ con = sqlite3.connect(":memory:") for cmd in schema.split(';'): con.execute(cmd) con.close() -- --Bryan From tjreedy at udel.edu Sun May 2 15:23:05 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 May 2010 15:23:05 -0400 Subject: Bug in Python set In-Reply-To: <0bd314a8-db65-43f1-a999-521e2ed71cad@n15g2000yqf.googlegroups.com> References: <0bd314a8-db65-43f1-a999-521e2ed71cad@n15g2000yqf.googlegroups.com> Message-ID: On 5/2/2010 8:11 AM, dmitrey wrote: > Python 2.6.5 r265:79063 >>>> set().update(set()) is None > True > while I expect result of update to be set. > Also, result of > set().add(None) > is None while I expect it to be set with element None (or, maybe, it > should be empty set?) 'Expect' has two different meanings in this context. 1. The empirical behavior surprised me (because I did not bother to read the manual, which clearly says what the returns are). 2. The documented behavior, which I read, surprises me, because I would have designed things differently, perhaps because I have used other languages designed differently. I am not sure which you meant. From andreas.loescher at s2005.tu-chemnitz.de Sun May 2 15:54:03 2010 From: andreas.loescher at s2005.tu-chemnitz.de (Andreas =?ISO-8859-1?Q?L=F6scher?=) Date: Sun, 02 May 2010 21:54:03 +0200 Subject: Parser Message-ID: <1272830042.14469.1.camel@laptop> Hi, I am looking for an easy to use parser. I am want to get an overview over parsing and want to try to get some information out of a C-Header file. Which parser would you recommend? Best, Andreas From porterj at alum.rit.edu Sun May 2 16:03:45 2010 From: porterj at alum.rit.edu (James Porter) Date: Sun, 02 May 2010 15:03:45 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 5/2/2010 1:43 PM, Robert Kern wrote: > Perhaps things would be clearer if you could post the C code that you've > written that fails. So far, you've only alluded at what you are doing > using Python-syntax examples. I'm not sure how much this will help, but here you go. The actual C code probably doesn't matter except for where I set tp_flags, tp_new, and register the type, but I included it for completeness. The full C source is available here if you need it, but be warned that other strangeness abounds in the code: . Obviously, this is kind of a bizarre case, so I'm not entirely sure what the best route is here. Thanks, Jim static PyObject* iMeshArrObj_new(PyTypeObject *cls,PyObject *args,PyObject *kw) { static char *kwlist[] = {"object","instance",0}; PyObject *obj; iMesh_Object *instance = NULL; PyObject *arr = NULL; iMeshArr_Object *self; if(!PyArg_ParseTupleAndKeywords(args,kw,"O|O!",kwlist,&obj, &iMesh_Type,&instance)) return NULL; arr = PyArray_FROM_O(obj); if(arr == NULL) return NULL; self = (iMeshArr_Object*)PyObject_CallMethod(arr,"view","O",cls); Py_DECREF(arr); if(self == NULL) return NULL; /* some boring stuff to set |instance| */ return self; } static void iMeshArrObj_dealloc(iMeshArr_Object *self) { Py_XDECREF(self->instance); self->array.ob_type->tp_free((PyObject*)self); } static PyObject* iMeshArrObj_finalize(iMeshArr_Object *self,PyObject *args) { iMeshArr_Object *context; if(PyArg_ParseTuple(args,"O!",&iMeshArr_Type,&context)) { self->instance = context->instance; Py_XINCREF(self->instance); } PyErr_Clear(); Py_RETURN_NONE; } static PyMethodDef iMeshArrObj_methods[] = { { "__array_finalize__", (PyCFunction)iMeshArrObj_finalize, METH_VARARGS, "" }, {0} }; static PyMemberDef iMeshArrObj_members[] = { {"instance", T_OBJECT_EX, offsetof(iMeshArr_Object, instance), READONLY, "base iMesh instance"}, {0} }; static PyTypeObject iMeshArr_Type = { PyObject_HEAD_INIT(NULL) /* ... */ (destructor)iMeshArrObj_dealloc, /* tp_dealloc */ /* ... */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "iMesh array objects", /* tp_doc */ /* ... */ iMeshArrObj_methods, /* tp_methods */ iMeshArrObj_members, /* tp_members */ /* ... */ iMeshArrObj_new, /* tp_new */ }; PyMODINITFUNC initiMesh(void) { PyObject *m; m = Py_InitModule("iMesh",module_methods); import_array(); iMeshArr_Type.tp_base = &PyArray_Type; if(PyType_Ready(&iMeshArr_Type) < 0) return; Py_INCREF(&iMeshArr_Type); PyModule_AddObject(m,"Array",(PyObject *)&iMeshArr_Type); } /***** End C code *****/ And then in Python: A = iMesh.Array(numpy.array([1,2,3,4,5]), instance=mesh) numpy.zeros_like(A) # fails here Inside NumPy, zeros_like looks like this (there's a bit more than this, but it's irrelevant to this problem): def zeros_like(a): if isinstance(a, ndarray): res = ndarray.__new__(type(a), a.shape, a.dtype, order=a.flags.fnc) res.fill(0) return res From drobinow at gmail.com Sun May 2 16:16:21 2010 From: drobinow at gmail.com (David Robinow) Date: Sun, 2 May 2010 16:16:21 -0400 Subject: condition and True or False In-Reply-To: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: On Sun, May 2, 2010 at 1:14 PM, Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > ? ?x = and True or False > > What is "and True or False" adding to this picture? ?The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one > over the head with the additional "and True or False". > > I did a little code Googling and found a few other Python instances of > this, but also many Lua instances. ?I'm not that familiar with Lua, is > this a practice that one who uses Lua frequently might carry over to > Python, not realizing that the added "and True or False" is redundant? > > Other theories? > > -- Paul > -- > http://mail.python.org/mailman/listinfo/python-list > True and False were added in Python 2.2.1 (PEP 285) Perhaps this was a silly way to ensure that the user wouldn't try to run it in earlier versions. From jason.scheirer at gmail.com Sun May 2 16:28:03 2010 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Sun, 2 May 2010 13:28:03 -0700 (PDT) Subject: Parser References: <1272830042.14469.1.camel@laptop> Message-ID: On May 2, 12:54?pm, Andreas L?scher wrote: > Hi, > I am looking for an easy to use parser. I am want to get an overview > over parsing and want to try to get some information out of a C-Header > file. Which parser would you recommend? > > Best, > Andreas Pyparsing: http://pyparsing.wikispaces.com/ I've abused the lexers built in to Pygments ( http://pygments.org/ ) a few times to decent effect too. From pavlovevidence at gmail.com Sun May 2 16:28:05 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 13:28:05 -0700 (PDT) Subject: sometype.__new__ and C subclasses References: Message-ID: On May 2, 10:48?am, James Porter wrote: > On 5/2/2010 4:34 AM, Carl Banks wrote: > > > Why don't you use mysubtype.__new__(mysubtype,...)? > > > If you wrote mysubtype in C, and defined a different tp_new than > > ndarray, then this exception will trigger. ?And it ought to; you don't > > want to use ndarray's tp_new to create an object of your subclass, if > > you've defined a different tp_new. > > Unfortunately, I can't do that, since that call is in NumPy itself and > it's part of their "standard" way of making instances of subclasses of > ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, > ...) to create new arrays based on the shape of other arrays. > > The Python version of the subclass is shown here: > , > and I'm trying to write something pretty similar in C. I'm trying to > stay in C since everything else is in C, so it's easier to stay in C > then to jump back and forth all the time. > > Maybe the real answer to this question is "NumPy is doing it wrong" and > I should be on their list; still, it seems strange that the behavior is > different between Python and C. I would say numpy is wrong here, so I suggest filing a bug report. In fact I can't think of any benefit to EVER calling X.__new__(Y) where X is not Y. Maybe old-style classes? Someone who wants to ensure they're getting an instance of a certain type can check issubclass(Y,X) then call Y.__new__(Y). Unfortunately, you just can't get rid of the test in tp_new_wrapper. Carl Banks From robert.kern at gmail.com Sun May 2 16:51:19 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 02 May 2010 15:51:19 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 2010-05-02 15:28 , Carl Banks wrote: > On May 2, 10:48 am, James Porter wrote: >> On 5/2/2010 4:34 AM, Carl Banks wrote: >> >>> Why don't you use mysubtype.__new__(mysubtype,...)? >> >>> If you wrote mysubtype in C, and defined a different tp_new than >>> ndarray, then this exception will trigger. And it ought to; you don't >>> want to use ndarray's tp_new to create an object of your subclass, if >>> you've defined a different tp_new. >> >> Unfortunately, I can't do that, since that call is in NumPy itself and >> it's part of their "standard" way of making instances of subclasses of >> ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, >> ...) to create new arrays based on the shape of other arrays. >> >> The Python version of the subclass is shown here: >> , >> and I'm trying to write something pretty similar in C. I'm trying to >> stay in C since everything else is in C, so it's easier to stay in C >> then to jump back and forth all the time. >> >> Maybe the real answer to this question is "NumPy is doing it wrong" and >> I should be on their list; still, it seems strange that the behavior is >> different between Python and C. > > I would say numpy is wrong here, so I suggest filing a bug report. > > In fact I can't think of any benefit to EVER calling X.__new__(Y) > where X is not Y. Maybe old-style classes? Someone who wants to > ensure they're getting an instance of a certain type can check > issubclass(Y,X) then call Y.__new__(Y). Well, the Y.__new__(Y) may call X.__new__(Y) (and we certainly do this successfully in other Python subclasses of ndarray; this also appears in the Python regression tests). I'm not sure why this would be permitted there and not in a regular function (numpy.zeros_like() seems to be the function that does this and fails for the OP). The reason we do it there instead of calling the subclass's constructor is because the subclass's constructor may have different arguments. I'm happy to concede that this might be a bug in numpy, but I don't understand why this is allowed for Python subclasses but not C subtypes. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Sun May 2 16:58:27 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 02 May 2010 15:58:27 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 2010-05-02 15:03 , James Porter wrote: > And then in Python: > > A = iMesh.Array(numpy.array([1,2,3,4,5]), instance=mesh) > numpy.zeros_like(A) # fails here > > Inside NumPy, zeros_like looks like this (there's a bit more than this, > but it's irrelevant to this problem): > > def zeros_like(a): > if isinstance(a, ndarray): > res = ndarray.__new__(type(a), a.shape, a.dtype, > order=a.flags.fnc) > res.fill(0) > return res Well, I think we can change zeros_like() and the rest to work around this issue. Can you bring it up on the numpy mailing list? def zeros_like(a): if isinstance(a, ndarray): res = numpy.empty(a.shape, a.dtype, order=a.flags.fnc) res.fill(0) res = res.view(type(a)) return res ... -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From pavlovevidence at gmail.com Sun May 2 17:19:08 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 14:19:08 -0700 (PDT) Subject: PyObject_SetAttrString - doesn't set instance attribute References: <82ae0f7b-e5f4-4b85-a9fb-aef16de10af2@a39g2000prb.googlegroups.com> <1579c863-c7e2-47ba-ae45-b3ba74eff40c@a39g2000prb.googlegroups.com> <751257bd-5d92-4ec9-bec9-41369b5d31e5@y18g2000prn.googlegroups.com> Message-ID: <0c809eb9-6e97-4b23-93bd-79b875daf09d@n37g2000prc.googlegroups.com> On May 2, 3:26?am, Jason wrote: > On May 2, 5:52?pm, Carl Banks wrote: > > > Not sure what you're doing here. ?It looks like you are being passed > > an object of a given type, then you get the type object, call it to > > create another object of that type, and assign it to object->instance. > > Sorry, I should have noted that the "NautilusPythonObject" type in the > code is a struct defined as: > > struct _NautilusPythonObject { > ? GObject parent_slot; > ? PyObject *instance; > > }; > > You are assigning the attirbute the the object that the C code refers > > to as "object->instance", but it seems that in the Python snippet you > > are calling getattr on the object that the C code refers to as > > "object". > > object->instance is the PyObject, and I gathered that it was the > correct thing to assign to from the fact that the address is identical > as seen from C and Python. We'd have to see more code, I'd think. What you posted needs more context. For instance, what type, exactly, is class->type? This would help us understand better. I don't understand how object->instance and self could be the same object. If they have the same address it's possible (and, I'm inclined to think, likely) that you're creating an object, it's getting destroyed, then you are creating another one. Here's what's really odd. You are calling getattr(self, "super_happy_magic") inside __init__, which is the class's initializer. How could you have had occasion to call PyObject_SetAttrString on that same object at that point? The only possible way it could have happened is if nautilus_python_object_instance_init is invoked by MenuProviderTest.__new__ somehow, but that doesn't make sense either. You run PyObject_CallObject(class->type,NULL) to create object- >instance, but calling a type also calls the type's __init__ method. So how is it that later the __init__ method is being called again on the same object? Unless you're doing something very weird, it could only mean it's a different object. I doubt it'll fix all your problems, but one thing to try is to replace "PyObject_CallObject(class->type, NULL);" with "class->type- >tp_new(class->type);". But you probably have to go back to the drawing board and rethink the whole thing. What you've posted is quite unusual. You should choose more descriptive variable names, too. Carl Banks From pavlovevidence at gmail.com Sun May 2 17:39:27 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 14:39:27 -0700 (PDT) Subject: sometype.__new__ and C subclasses References: Message-ID: <6fb5fa23-f484-4fba-9b73-5e0517dc374d@34g2000prs.googlegroups.com> On May 2, 1:51?pm, Robert Kern wrote: > On 2010-05-02 15:28 , Carl Banks wrote: > > > > > On May 2, 10:48 am, James Porter ?wrote: > >> On 5/2/2010 4:34 AM, Carl Banks wrote: > > >>> Why don't you use mysubtype.__new__(mysubtype,...)? > > >>> If you wrote mysubtype in C, and defined a different tp_new than > >>> ndarray, then this exception will trigger. ?And it ought to; you don't > >>> want to use ndarray's tp_new to create an object of your subclass, if > >>> you've defined a different tp_new. > > >> Unfortunately, I can't do that, since that call is in NumPy itself and > >> it's part of their "standard" way of making instances of subclasses of > >> ndarray. Functions like numpy.zeros_like use ndarray.__new__(subtype, > >> ...) to create new arrays based on the shape of other arrays. > > >> The Python version of the subclass is shown here: > >> , > >> and I'm trying to write something pretty similar in C. I'm trying to > >> stay in C since everything else is in C, so it's easier to stay in C > >> then to jump back and forth all the time. > > >> Maybe the real answer to this question is "NumPy is doing it wrong" and > >> I should be on their list; still, it seems strange that the behavior is > >> different between Python and C. > > > I would say numpy is wrong here, so I suggest filing a bug report. > > > In fact I can't think of any benefit to EVER calling X.__new__(Y) > > where X is not Y. ?Maybe old-style classes? ?Someone who wants to > > ensure they're getting an instance of a certain type can check > > issubclass(Y,X) then call Y.__new__(Y). > > Well, the Y.__new__(Y) may call X.__new__(Y) (and we certainly do this > successfully in other Python subclasses of ndarray; this also appears in the > Python regression tests). I'm not sure why this would be permitted there and not > in a regular function (numpy.zeros_like() seems to be the function that does > this and fails for the OP). The reason we do it there instead of calling the > subclass's constructor is because the subclass's constructor may have different > arguments. > > I'm happy to concede that this might be a bug in numpy, but I don't understand > why this is allowed for Python subclasses but not C subtypes. Because Python subclasses (i.e., "heap types") all invoke tp_new_wrapper, which is guaranteed to call the tp_new of the most derived base. C subtypes can, and often have to, replace tp_new with their own version. Calling a base type's tp_new when you've defined your own tp_new at the C level is dangerous. As for the issue with a subclass's arguments being different, I'm shocked that anyone at numpy could possibly think bypassing the subtype's constructor is good idea. Carl Banks From pavlovevidence at gmail.com Sun May 2 17:49:16 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 May 2010 14:49:16 -0700 (PDT) Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: <5ac89a1b-1646-4196-8805-e50a19230490@j36g2000prj.googlegroups.com> On May 2, 10:14?am, Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > ? ? x = and True or False > > What is "and True or False" adding to this picture? ?The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one > over the head with the additional "and True or False". > > I did a little code Googling and found a few other Python instances of > this, but also many Lua instances. ?I'm not that familiar with Lua, is > this a practice that one who uses Lua frequently might carry over to > Python, not realizing that the added "and True or False" is redundant? > > Other theories? The person who wrote it was a programmer who fancied himself to be more clever than he really was. Convenient though they may be, people always abuse (and often misuse) these boolean shortcuts, a big reason why I don't like them. You never see crap like this in Java. Carl Banks From martin at v.loewis.de Sun May 2 18:02:07 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 03 May 2010 00:02:07 +0200 Subject: Parser In-Reply-To: <1272830042.14469.1.camel@laptop> References: <1272830042.14469.1.camel@laptop> Message-ID: <4BDDF65F.7080302@v.loewis.de> Andreas L?scher wrote: > Hi, > I am looking for an easy to use parser. I am want to get an overview > over parsing and want to try to get some information out of a C-Header > file. To get information from a header file, try Tools/scripts/h2py.py Regards, Martin From porterj at alum.rit.edu Sun May 2 18:06:34 2010 From: porterj at alum.rit.edu (James Porter) Date: Sun, 02 May 2010 17:06:34 -0500 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: On 5/2/2010 3:58 PM, Robert Kern wrote: > Well, I think we can change zeros_like() and the rest to work around > this issue. Can you bring it up on the numpy mailing list? > > def zeros_like(a): > if isinstance(a, ndarray): > res = numpy.empty(a.shape, a.dtype, order=a.flags.fnc) > res.fill(0) > res = res.view(type(a)) > return res > ... I'm having difficulty posting to the NumPy list (both via gmane and email) so I'm just going to put this here so it doesn't get lost. zeros_like probably needs to call __array_finalize__ for this to work properly (it'll cause a segfault for me otherwise): def zeros_like(a): if isinstance(a, ndarray): res = numpy.zeros(a.shape, a.dtype, order=a.flags.fnc) res = res.view(type(a)) res.__array_finalize__(a) return res ... - Jim From steve at REMOVE-THIS-cybersource.com.au Sun May 2 19:14:22 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 23:14:22 GMT Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: <4bde074e$0$27857$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 10:14:44 -0700, Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code that > might better be coded using "y if x else z", I came across this puzzler: > > x = and True or False > > What is "and True or False" adding to this picture? The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one over > the head with the additional "and True or False". If is already an actual bool, then I can only imagine that the author is simply struggling with the concept, in the same way that some people write: if == True: ... If it is any arbitrary object, then "x and True or False" is just an obfuscated way of writing "bool(x)". Perhaps their code predates the introduction of bools, and they have defined global constants True and False but not bool. Then they removed the True and False bindings as no longer necessary, but neglected to replace the obfuscated conversion. -- Steven From lanyjie at yahoo.com Sun May 2 19:24:11 2010 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sun, 2 May 2010 16:24:11 -0700 (PDT) Subject: ANN: expy 0.6.6 released! Message-ID: <196302.50328.qm@web54202.mail.re2.yahoo.com> EXPY is an express way to extend Python! EXPY provides a way to extend python in an elegant way. For more information and a tutorial, see: http://expy.sourceforge.net/ What's new: 1. Special methods can now take @throws decorators. 2. Added convenience macros _NEW and _CheckExact for extension types. 3. Give warnings of missing Py_INCREF on all methods/functions returning an object. 4. And the responsibility of Py_INCREF is left for the developer. 5. Documentation update. Cheers, Yingjie From steve at REMOVE-THIS-cybersource.com.au Sun May 2 19:26:46 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 May 2010 23:26:46 GMT Subject: List size versus list allocation References: <4bdd92da$0$27857$c3e8da3@news.astraweb.com> Message-ID: <4bde0a36$0$27857$c3e8da3@news.astraweb.com> On Sun, 02 May 2010 18:07:31 +0200, Christian Heimes wrote: >> I'm interested in gathering some statistics on this, and to do so I >> need a way of measuring the list's logical size versus its actual size. >> The first is easy: it's just len(list). Is there some way of getting >> the allocated size of the list? > > With Python 2.6 and newer you can use sys.getsizeof() to get the actual > size of the list object: Thanks Christian and Peter for your answers. That's very helpful. -- Steven From pmaupin at gmail.com Sun May 2 19:37:43 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 2 May 2010 16:37:43 -0700 (PDT) Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: <5e5a0005-1c44-4d47-bd3e-8ebbd66eea1e@k19g2000yqm.googlegroups.com> On May 2, 12:14?pm, Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > ? ? x = and True or False > > What is "and True or False" adding to this picture? ?The boolean > expression part is already evaluating to a boolean, so I don't > understand why a code author would feel compelled to beat this one > over the head with the additional "and True or False". > > I did a little code Googling and found a few other Python instances of > this, but also many Lua instances. ?I'm not that familiar with Lua, is > this a practice that one who uses Lua frequently might carry over to > Python, not realizing that the added "and True or False" is redundant? > > Other theories? > > -- Paul I think it's idiomatic -- that it was written by someone who was deep in thought about actually getting something accomplished, and not thinking at the level of the details. As you're actively *looking* for "x and y or z" I'm sure you'll agree that we've probably all written lots of stuff like: x = and 'some_prefix' or '' x = and 42 or 0 x = and ['Hi, mom!'] or [] When you're in this mode of expression, the only thing that would really trip you up and make it "wrong" is if 'some_prefix' or 42 or ['Hi, mom!'] evaluated to False, and then you get the '', 0, or [] you didn't really want. So I know that, to the extent I was thinking deeply about the low level of what I was writing, my mental energy would be going towards making sure that the second sub-expression evaluated to true. So, if you're mentally operating in this mode, and you want True or False, and you forget, don't think about, or are not cognizant of the fact that bool() is available, it's pretty obvious what the result is going to be. I've probably done it myself a few times, although I would probably have to be *really* lost in thought in order to do it when the underlying sub-expression was boolean to start with. Regards, Pat From greg.ewing at canterbury.ac.nz Sun May 2 20:41:29 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 May 2010 12:41:29 +1200 Subject: sometype.__new__ and C subclasses In-Reply-To: References: Message-ID: <846jr7Fl1cU1@mid.individual.net> James Porter wrote: > Functions like numpy.zeros_like use ndarray.__new__(subtype, > ...) to create new arrays based on the shape of other arrays. > > Maybe the real answer to this question is "NumPy is doing it wrong" Yes, I think NumPy is doing it wrong, even for subclasses written in Python. If the subtype has overridden ndarray's __new__ method, the way NumPy is doing it will skip the subclass's version of the method. -- Greg From sjmachin at lexicon.net Sun May 2 20:42:27 2010 From: sjmachin at lexicon.net (John Machin) Date: Sun, 2 May 2010 17:42:27 -0700 (PDT) Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> <4bde074e$0$27857$c3e8da3@news.astraweb.com> Message-ID: On May 3, 9:14?am, Steven D'Aprano wrote: > If it is any arbitrary object, then "x and True or False" is just an > obfuscated way of writing "bool(x)". Perhaps their code predates the > introduction of bools, and they have defined global constants True and > False but not bool. Then they removed the True and False bindings as no > longer necessary, but neglected to replace the obfuscated conversion. Or perhaps they are maintaining code that must run on any 2.X. True and False would be set up conditional on Python version. Writing "expression and True or False" avoids a function call. From lanyjie at yahoo.com Sun May 2 21:40:30 2010 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sun, 2 May 2010 18:40:30 -0700 (PDT) Subject: ANN: expy 0.6.6 released! In-Reply-To: <196302.50328.qm@web54202.mail.re2.yahoo.com> Message-ID: <74508.23739.qm@web54204.mail.re2.yahoo.com> > Subject: ANN: expy 0.6.6 released! > To: "python list" > Cc: "CAPI Python" > Date: Monday, May 3, 2010, 3:24 AM > EXPY is an express way to extend Python! > > EXPY provides a way to extend python in an elegant way. For > more information and a tutorial, see: http://expy.sourceforge.net/ > I'm using expy in a serious project to wrap an old project written in C and deliver it up via www with django. That is why expy is getting improved quickly these days. So far, both the project and expy are making good progress hand in hand. Cheers, Yingjie From bryanjugglercryptographer at yahoo.com Sun May 2 21:52:06 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sun, 2 May 2010 18:52:06 -0700 (PDT) Subject: Fast Efficient way to transfer an object to another list References: <4bdba195$0$8757$c3e8da3@news.astraweb.com> <06366a6d-e3db-4963-bcc0-0bc03d035a94@e2g2000yqn.googlegroups.com> <4bdcce77$0$27782$c3e8da3@news.astraweb.com> Message-ID: <01862ff6-f0a9-436c-b836-a73fbfdd1439@a39g2000prb.googlegroups.com> Steven D'Aprano wrote: > The simplest way to speed the above code up is not to start from the > beginning each time. That requires two very small changes. And since > deletions from the front of the list are slow, MRAB's suggestion is also > a good idea. Those two speed-ups provide worst-case linear run-time, but as MRAB astutely noted, his optimization assumes that order is unimportant. That's a bad assumption for a general extract-from-list function. Where order does not matter, I'd suspect 'list' was a poor choice of data type. Here's a general, order-preserving, linear-time version: def extract(lst, predicate): """ Return items of lst satisfying predicate, deleting them from lst. """ result = [] j = 0 for i in range(len(lst)): if predicate(lst[i]): result.append(lst[i]) else: lst[j] = lst[i] j += 1 del lst[j:] return result # some testing: for nitems in range(10): for pred in [lambda x: True, lambda x: False, lambda x: x % 2 == 0, lambda x: x % 2 == 1, lambda x: x < nitems // 2, lambda x: x >= nitems // 2]: original = list(range(nitems)) source = original[:] extracted = extract(source, pred) assert len(source) + len(extracted) == nitems assert sorted(source) == source for n in source: assert not pred(n) assert n in original assert sorted(extracted) == extracted for n in extracted: assert pred(n) assert n in original -- --Bryan From alfps at start.no Mon May 3 00:37:49 2010 From: alfps at start.no (Alf P. Steinbach) Date: Mon, 03 May 2010 06:37:49 +0200 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: * Terry Reedy: > * Alf P. Steinbach: >> * Aahz: > >>> and sometimes >>> they rebind the original target to the same object. >> >> At the Python level that seems to be an undetectable null-operation. > > If you try t=(1,2,3); t[1]+=3, if very much matters that a rebind occurs. Testing: >>> t = ([], [], []) >>> t ([], [], []) >>> t[0] += ["blah"] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> t (['blah'], [], []) >>> _ Yep, it matters. Is this change-but-raise-exception a bug? I seem to have a knack for running into bugs. :-) >> Granted one could see something going on in a machine code or byte code >> debugger. But making that distinction (doing nothing versus >> self-assignment) at the Python level seems, to me, to be meaningless. > > Please do not confuse things. Augmented *assignment* must be understood > as assignment. Failure to do so leads (and has lead) newbies into > confusion, and puzzled posts on this list. OK. But I think it would be less confusing, less breaking of expectations, if, for the example above, += reduced to the functionality of extend(), with no x. Cheers, & thanks, - Alf From dchichkov at gmail.com Mon May 3 01:10:00 2010 From: dchichkov at gmail.com (dmtr) Date: Sun, 2 May 2010 22:10:00 -0700 (PDT) Subject: Parser References: <1272830042.14469.1.camel@laptop> Message-ID: <2121ba34-89e2-430f-bc99-5b6a2388f3dd@g1g2000pro.googlegroups.com> On May 2, 12:54?pm, Andreas L?scher wrote: > Hi, > I am looking for an easy to use parser. I am want to get an overview > over parsing and want to try to get some information out of a C-Header > file. Which parser would you recommend? ANTLR From clp2 at rebertia.com Mon May 3 01:18:39 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 May 2010 22:18:39 -0700 Subject: Parser In-Reply-To: <2121ba34-89e2-430f-bc99-5b6a2388f3dd@g1g2000pro.googlegroups.com> References: <1272830042.14469.1.camel@laptop> <2121ba34-89e2-430f-bc99-5b6a2388f3dd@g1g2000pro.googlegroups.com> Message-ID: On Sun, May 2, 2010 at 10:10 PM, dmtr wrote: > On May 2, 12:54?pm, Andreas L?scher chemnitz.de> wrote: >> Hi, >> I am looking for an easy to use parser. I am want to get an overview >> over parsing and want to try to get some information out of a C-Header >> file. Which parser would you recommend? > > ANTLR I don't know if it's that easy to get started with though. The companion for-pay book is *most excellent*, but it seems to have been written to the detriment of the normal online docs. Cheers, Chris -- http://blog.rebertia.com From dchichkov at gmail.com Mon May 3 01:39:43 2010 From: dchichkov at gmail.com (dmtr) Date: Sun, 2 May 2010 22:39:43 -0700 (PDT) Subject: Parser References: <1272830042.14469.1.camel@laptop> <2121ba34-89e2-430f-bc99-5b6a2388f3dd@g1g2000pro.googlegroups.com> Message-ID: <6d42a22e-ed67-4e8e-bcdb-ceed85f6c6d2@r21g2000prr.googlegroups.com> > > > ANTLR > > I don't know if it's that easy to get started with though. The > companion for-pay book is *most excellent*, but it seems to have been > written to the detriment of the normal online docs. > > Cheers, > Chris > --http://blog.rebertia.com IMO ANTLR is much easier to use compared to any other tool simply because it has excellent GUI (the quality of which is amazing). From stefan_ml at behnel.de Mon May 3 01:56:50 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 03 May 2010 07:56:50 +0200 Subject: Parser In-Reply-To: <6d42a22e-ed67-4e8e-bcdb-ceed85f6c6d2@r21g2000prr.googlegroups.com> References: <1272830042.14469.1.camel@laptop> <2121ba34-89e2-430f-bc99-5b6a2388f3dd@g1g2000pro.googlegroups.com> <6d42a22e-ed67-4e8e-bcdb-ceed85f6c6d2@r21g2000prr.googlegroups.com> Message-ID: dmtr, 03.05.2010 07:39: >>> ANTLR >> >> I don't know if it's that easy to get started with though. The >> companion for-pay book is *most excellent*, but it seems to have been >> written to the detriment of the normal online docs. > > IMO ANTLR is much easier to use compared to any other tool simply > because it has excellent GUI (the quality of which is amazing). See? Explanations help more than bold statements. Stefan From parul.pandey85 at gmail.com Mon May 3 02:24:51 2010 From: parul.pandey85 at gmail.com (pp) Date: Sun, 2 May 2010 23:24:51 -0700 (PDT) Subject: Problems with 'scipy.sparse.linalg.dsolve.umfpack' Message-ID: <2bed17f4-0fa1-4561-b7ec-32002e38b690@32g2000prq.googlegroups.com> Hello all, I have this equation to solve where variable LHS is a sparse matrix and RHS is an array . c = linsolve.spsolve(LHS, RHS) i get this error warn( 'scipy.sparse.linalg.dsolve.umfpack will be removed,'\ ' install scikits.umfpack instead' what is the reason for this and do I do next Please help I am very new to scipy. Thanks a lot From clp2 at rebertia.com Mon May 3 02:48:03 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 May 2010 23:48:03 -0700 Subject: Problems with 'scipy.sparse.linalg.dsolve.umfpack' In-Reply-To: <2bed17f4-0fa1-4561-b7ec-32002e38b690@32g2000prq.googlegroups.com> References: <2bed17f4-0fa1-4561-b7ec-32002e38b690@32g2000prq.googlegroups.com> Message-ID: On Sun, May 2, 2010 at 11:24 PM, pp wrote: > Hello all, > > I have this equation to solve where variable > LHS is a sparse matrix and RHS is an array . > c = linsolve.spsolve(LHS, RHS) > > > i get this error > warn( 'scipy.sparse.linalg.dsolve.umfpack will be removed,'\ > ? ? ? ? ? ? ? ? ?' install scikits.umfpack instead' > what is the reason for this and do I do next > > Please help > I am very new to scipy. This is the general Python mailinglist. You'd be more likely to get an answer on the SciPy mailinglist: http://mail.scipy.org/mailman/listinfo/scipy-user Cheers, Chris -- http://blog.rebertia.com From WolfgangMeiners01 at web.de Mon May 3 02:51:13 2010 From: WolfgangMeiners01 at web.de (Wolfgang Meiners) Date: Mon, 03 May 2010 08:51:13 +0200 Subject: recommended way to insert data into a one to many relationship using python In-Reply-To: References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4bde7262$0$6776$9b4e6d93@newsspool3.arcor-online.net> Peter Otten schrieb: > Peter Otten wrote: > > If you create indices for floors (and rooms) > > cur.execute("""create unique index room_index on rooms (fid, number);""") > cur.execute("""create unique index floor_index on floors (floor);""") > > the addition of missing rows can be simplified to > > missing = c2.execute("""select distinct floor from new_employees;""") > cur.executemany("insert or ignore into floors (floor) values (?)", missing) > > etc. > > Peter Hi Peter, thank you for your response. What i have got from it, is to have a (temporary) table to do the work inside sql and not from python. I thought of a second method to do it inside sql by an trigger sql = """create trigger insert_new_employee instead of insert on emplist begin # insert floor if not exists floor # insert (room, floor) if not exists (room, floor) # insert (person, rid) end""" but i would have to learn how to write triggers. Your idea gives me a more direct solution. Wolfgang From WolfgangMeiners01 at web.de Mon May 3 03:03:57 2010 From: WolfgangMeiners01 at web.de (Wolfgang Meiners) Date: Mon, 03 May 2010 09:03:57 +0200 Subject: recommended way to insert data into a one to many relationship using python In-Reply-To: <16f716de-8a0c-455c-8eb5-dbed332a81fe@h20g2000prn.googlegroups.com> References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> <16f716de-8a0c-455c-8eb5-dbed332a81fe@h20g2000prn.googlegroups.com> Message-ID: <4bde755d$0$6762$9b4e6d93@newsspool3.arcor-online.net> Bryan schrieb: > Wolfgang Meiners wrote: >> one to many relationships are fairly common, i think. So there should be >> a recommended way to insert data into such a relation using python. >> >> Given the following programm, what is the recommended way to insert the >> list of NewEmployees to the database? >> >> ======================================================================== >> # !python >> # -*- coding: utf-8 -*- >> >> import sqlite3 >> >> con = sqlite3.connect(":memory:") >> cur = con.cursor() >> >> cur.execute("""create table employees( >> eid integer primary key autoincrement, >> name text not null, >> rid integer references rooms(rid))""") >> >> cur.execute("""create table rooms( >> rid integer primary key autoincrement, >> number integer, >> fid integer references floors(fid))""") >> >> cur.execute("""create table floors( >> fid integer primary key autoincrement, >> floor text not null)""") >> > [...] >> NewEmployees =[] >> NewEmployees.append({'name': 'George', 'room': 89, 'floor': 'third floor'}) >> NewEmployees.append({'name': 'Ellen', 'room': 21, 'floor': 'first floor'}) >> > > For that kind of insert to be well-defined, the pair (floor, > room_number) must uniquely identify a room. When natural keys like > that are availabe, they're the obvious choice for primary keys in the > database schema. I suggested getting rid of fid and rid, as in: > > > schema = """ > CREATE TABLE floors ( > floor TEXT PRIMARY KEY > ); > > CREATE TABLE rooms ( > floor TEXT REFERENCES floors, > number INTEGER, > PRIMARY KEY (floor, number) > ); > > CREATE TABLE employees ( > eid INTEGER PRIMARY KEY AUTOINCREMENT, > name TEXT, > floor TEXT, > room_number INTEGER, > FOREIGN KEY (floor, room_number) REFERENCES rooms > ) > """ > > con = sqlite3.connect(":memory:") > for cmd in schema.split(';'): > con.execute(cmd) > con.close() > > > > -- > --Bryan This looks interesting to me. I would have all necessary information in table employees. But i think the additional tables for rooms and floors are necessary too, to have a normalized database. I thougth of a function like try_insert_and_return_key(x,y) for the tables but i had difficulties to write such a function. In this function x should be the key and y the depended data that can be compound. Nevertheless, with a given y there might be more then one x and i think, this is exactly what you stated above. Thank you for this hint Wolfgang From steven at REMOVE.THIS.cybersource.com.au Mon May 3 03:29:05 2010 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 03 May 2010 07:29:05 GMT Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On Mon, 03 May 2010 06:37:49 +0200, Alf P. Steinbach wrote: > * Terry Reedy: >> * Alf P. Steinbach: >>> * Aahz: >> >>>> and sometimes >>>> they rebind the original target to the same object. >>> >>> At the Python level that seems to be an undetectable null-operation. >> >> If you try t=(1,2,3); t[1]+=3, if very much matters that a rebind >> occurs. > > Testing: > > > >>> t = ([], [], []) > >>> t > ([], [], []) > >>> t[0] += ["blah"] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > >>> t > (['blah'], [], []) > >>> _ > > > Yep, it matters. > > Is this change-but-raise-exception a bug? > > I seem to have a knack for running into bugs. :-) No, I don't believe so -- I believe that it is behaving exactly as advertised. But it is absolutely a gotcha. Consider: >>> class K(object): ... def __init__(self, value=0): ... self.value = value ... def __add__(self, other): ... self.value = self.value + other ... return self ... def __str__(self): ... return "%s" % self.value ... __repr__ = __str__ ... >>> x = K(42) >>> x + 5 47 >>> t = (None, x) >>> t (None, 47) >>> >>> t[1] + 3 50 >>> t (None, 50) >>> t[1] += 1 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> t (None, 51) Unintuitive, yes. Possibly a bad design, maybe. Surprising, absolutely. But not a bug, as it's working exactly as promised. += is conceptually two steps: perform an addition, and perform an assignment afterward. That addition is sometimes performed in-place, but regardless of whether it is or not, the assignment is always attempted. -- Steven From nospam at nospam.com Mon May 3 03:46:05 2010 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 03 May 2010 09:46:05 +0200 Subject: HTTP server + SQLite? Message-ID: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Hello I'd like to build a prototype that will combine a web server as front-end (it must support GZIPping data to the remote client when there are a lot of data to return), and SQLite as back-end, call the server from a VB.Net application, and see how well this works. I want to see if performance is significantly lower than using a server that uses a binary protocol. I'm no Python expert, so would appreciate any information on how to combine a web server and SQLite into a single Python application. This is just for a proof-of-concept, so it doesn't need to be shipping-quality. Thank you for any hint. From wuwei23 at gmail.com Mon May 3 04:32:07 2010 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 May 2010 01:32:07 -0700 (PDT) Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Message-ID: <77d7a0ba-4141-4c05-aef1-96f64ee38ed8@s4g2000prh.googlegroups.com> Gilles Ganault wrote: > I'm no Python expert, so would appreciate any information on how to > combine a web server and SQLite into a single Python application. Hey Gilles, I'm a fan of the http framework, CherryPy[1]. Very quick and easy to get something up and running. The site also has some ideas on interoperating with a database[2], although this might be a better starting point[3]. SQLite is included in the Python standard library past 2.5, but if you're stuck with either 2.3 or 2.4, the 3rd party library pysqlite[4] provides support for them. For a higher level web framework, I find Turbogears 2.x[5] really straightforward. It's based around SQLAlchemy, which supports SQLite, but sounds like it's probably overkill for your situation. 1: http://www.cherrypy.org/ 2: http://tools.cherrypy.org/wiki/Databases 3: http://code.activestate.com/recipes/496799/ 4: http://code.google.com/p/pysqlite 5: http://turbogears.org/2.0/ From clp2 at rebertia.com Mon May 3 04:48:38 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 01:48:38 -0700 Subject: HTTP server + SQLite? In-Reply-To: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Message-ID: On Mon, May 3, 2010 at 12:46 AM, Gilles Ganault wrote: > I'd like to build a prototype that will combine a web server as > front-end (it must support GZIPping data to the remote client when > there are a lot of data to return), and SQLite as back-end, call the > server from a VB.Net application, and see how well this works. I want > to see if performance is significantly lower than using a server that > uses a binary protocol. > > I'm no Python expert, so would appreciate any information on how to > combine a web server and SQLite into a single Python application. This > is just for a proof-of-concept, so it doesn't need to be > shipping-quality. If your want to write a basic/low-level HTTP server: http://docs.python.org/library/basehttpserver.html Looks like you'd use HTTPServer and a custom subclass of BaseHTTPRequestHandler. If you want to write at the slightly higher WSGI (http://www.python.org/dev/peps/pep-0333/) level of abstraction, you can have your WSGI application run by a simple Python HTTP server such as: http://pythonpaste.org/modules/httpserver.html As Alex said, SQLite is in the std lib: http://docs.python.org/library/sqlite3 Cheers, Chris -- http://blog.rebertia.com From __peter__ at web.de Mon May 3 05:34:19 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2010 11:34:19 +0200 Subject: Python dot-equals (syntax proposal) References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: Alf P. Steinbach wrote: > > >>> t = ([], [], []) > >>> t > ([], [], []) > >>> t[0] += ["blah"] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > >>> t > (['blah'], [], []) > >>> _ > > > Yep, it matters. > > Is this change-but-raise-exception a bug? No. a[0] += b translates to a.__setitem__(0, a.__getitem__(0).__iadd__(b)) assuming a[0] has an __iadd__() method. It should be obvious that only the the last operation, the outer a.__setitem__(...), will fail here. A possible fix might be a changed order of evaluation: _internal_set = a.__setitem__ _internal_set(0, a.__getitem__(0).__iadd__(b)) I don't know if there are arguments against this other than increased compiler complexity. Or one could argue that a += b should have been implemented as a = a + b or a = a.__add__(b) which is currently used as the fallback when there is no __iadd__() method and which gives a more intuitive behaviour at the cost of a greater overhead. But it's a little late for that discussion, for that language. Peter From jarausch at igpm.rwth-aachen.de Mon May 3 05:51:41 2010 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 03 May 2010 11:51:41 +0200 Subject: HTTP server + SQLite? In-Reply-To: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Message-ID: <847klaFrjnU1@mid.dfncis.de> On 05/03/10 09:46, Gilles Ganault wrote: > Hello > > I'd like to build a prototype that will combine a web server as > front-end (it must support GZIPping data to the remote client when > there are a lot of data to return), and SQLite as back-end, call the > server from a VB.Net application, and see how well this works. I want > to see if performance is significantly lower than using a server that > uses a binary protocol. > > I'm no Python expert, so would appreciate any information on how to > combine a web server and SQLite into a single Python application. This > is just for a proof-of-concept, so it doesn't need to be > shipping-quality. > You might have a look at http://www.karrigell.fr/doc/ Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From natalie5348 at gmail.com Mon May 3 06:23:44 2010 From: natalie5348 at gmail.com (Nat) Date: Mon, 3 May 2010 03:23:44 -0700 (PDT) Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> <847klaFrjnU1@mid.dfncis.de> Message-ID: <4d6a5330-0dec-4b4a-b56a-2d512c123afc@11g2000prv.googlegroups.com> interesting natalie5348 at hotmail.co.jp natalie5348s at yahoo.co.jp natalie5348 at gmail.com wlipgftth at jupiter.ocn.ne.jp natalie5348 at mbr.nifty.com natalie5348 at xqg.biglobe.ne.jp natalie5348 at zpost.plala.or.jp From nospam at nospam.com Mon May 3 06:57:49 2010 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 03 May 2010 12:57:49 +0200 Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> <847klaFrjnU1@mid.dfncis.de> Message-ID: On Mon, 03 May 2010 11:51:41 +0200, Helmut Jarausch wrote: >http://www.karrigell.fr/doc/ Thanks for the tip. From richard.lamboj at bilcom.at Mon May 3 07:02:31 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Mon, 3 May 2010 13:02:31 +0200 Subject: win32 - catch events(wmi?) Message-ID: <201005031302.31772.richard.lamboj@bilcom.at> Hello, i want catch the following events: - registry has chanced - file has chanced - outgoing network connection - programm start and i want to be able to allow, or deny this "requests". Kind Regards Richi From space.ship.traveller at gmail.com Mon May 3 08:05:26 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 4 May 2010 00:05:26 +1200 Subject: Teaching Programming Message-ID: Dear Friends, I'm looking for some help from the Python community. I hope this is the right place to ask for information. I'm putting together a website aimed at high school students and teachers, and would like to make sure the following page is as good as possible: http://programming.dojo.net.nz/languages/python/index In particular, "Why would I learn this language?" section needs to have a few paragraphs. I don't use Python predominantly so I hoped that you could provide the main reasons why Python is a language someone would want to learn about. Any other suggestions or ideas for the Python page would be fantastic, and any suggestions to other pages in general is also very helpful. http://programming.dojo.net.nz/ Kind regards, Samuel -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew at acooke.org Mon May 3 08:21:43 2010 From: andrew at acooke.org (andrew cooke) Date: Mon, 3 May 2010 05:21:43 -0700 (PDT) Subject: Parser References: <1272830042.14469.1.camel@laptop> Message-ID: <71942dbb-a772-4fcb-9746-282cc216eb70@q32g2000yqb.googlegroups.com> On May 2, 3:54?pm, Andreas L?scher wrote: > Hi, > I am looking for an easy to use parser. I am want to get an overview > over parsing and want to try to get some information out of a C-Header > file. Which parser would you recommend? > > Best, > Andreas I develop Lepl - http://www.acooke.org/lepl/ I think it's easy to use, and other people have said the documentation is fairly good. It doesn't have a GUI like Antlr, but it is recursive descent rather and completely implemented in Python, which (I think) makes it easier to understand and extend. Cheers, Andrew From clp2 at rebertia.com Mon May 3 08:29:57 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 05:29:57 -0700 Subject: Teaching Programming In-Reply-To: References: Message-ID: On Mon, May 3, 2010 at 5:05 AM, Samuel Williams wrote: > Dear Friends, > > I'm looking for some help from the Python community. I hope this is the > right place to ask for information. > > I'm putting together a website aimed at high school students and teachers, > and would like to make sure the following page is as good as possible: > http://programming.dojo.net.nz/languages/python/index > In particular, "Why would I learn this language?" section needs to have a > few paragraphs. I don't use Python predominantly so I hoped that you could > provide the main reasons why Python is a language someone would want to > learn about. - Significant use in certain applications areas: * Web programming (common frameworks include Django & TurboGears) * Scientific and numerical computing (see SciPy and Numeric) - Large "batteries-included" standard library, with a large number of third-party libraries also available - Used by Industrial Light and Magic, Google/YouTube, and other big names (http://www.python.org/about/success/) - A very clean syntax and elegant design, compared to other languages Cheers, Chris -- http://blog.rebertia.com From bazwal at ftml.net Mon May 3 08:42:13 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 13:42:13 +0100 Subject: strange interaction between open and cwd Message-ID: <4BDEC4A5.5070801@ftml.net> Python 2.6.4 (r264:75706, Mar 7 2010, 02:18:40) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.mkdir('/home/baz/tmp/xxx') >>> f = open('/home/baz/tmp/abc.txt', 'w') >>> f.write('abc') >>> f.close() >>> os.chdir('/home/baz/tmp/xxx') >>> os.getcwd() '/home/baz/tmp/xxx' >>> os.rmdir(os.getcwd()) >>> os.getcwd() Traceback (most recent call last): File "", line 1, in OSError: [Errno 2] No such file or directory >>> open('../abc.txt').read() 'abc' >>> can anybody explain how python is able to read the file at the end of this session? i'm guessing it's a platform specific thing as i'm pretty sure the above sequence of commands wouldn't work on windows (i.e. attempting to remove the cwd would produce an error). but how can python determine the parent directory of a directory that no longer exists? this actually caused a bug for me. i was trying to ensure that my program always resolved any file-names given on the command line by using os.path.realpath(). i had assumed that if realpath failed, then open would also fail - but not so! From lanyjie at yahoo.com Mon May 3 08:43:55 2010 From: lanyjie at yahoo.com (Yingjie Lan) Date: Mon, 3 May 2010 05:43:55 -0700 (PDT) Subject: ANN: expy 0.6.7 released! In-Reply-To: <74508.23739.qm@web54204.mail.re2.yahoo.com> Message-ID: <741400.49245.qm@web54202.mail.re2.yahoo.com> EXPY is an express way to extend Python! EXPY provides a way to extend python in an elegant way. For more information and a tutorial, see: http://expy.sourceforge.net/ I'm glad to announce a new release again today. ^_^ What's new: Version 0.6.7 1. Now functions can have 'value on failure' via rawtype. 2. Now property getters/setters can have @throws 3. Bug fix: if __init__ wrapper fails, it must return -1. Cheers, Yingjie From clp2 at rebertia.com Mon May 3 09:06:09 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 06:06:09 -0700 Subject: Teaching Programming In-Reply-To: References: Message-ID: On Mon, May 3, 2010 at 5:29 AM, Chris Rebert wrote: > On Mon, May 3, 2010 at 5:05 AM, Samuel Williams > wrote: >> Dear Friends, >> >> I'm looking for some help from the Python community. I hope this is the >> right place to ask for information. >> >> I'm putting together a website aimed at high school students and teachers, >> and would like to make sure the following page is as good as possible: >> http://programming.dojo.net.nz/languages/python/index >> In particular, "Why would I learn this language?" section needs to have a >> few paragraphs. I don't use Python predominantly so I hoped that you could >> provide the main reasons why Python is a language someone would want to >> learn about. > - A very clean syntax and elegant design, compared to other languages Also, I take issue with your classifying Python as orange with regard to "Is the general syntax simple and concise?" on http://programming.dojo.net.nz/resources/programming-language-comparison/index Python's syntax is at least as simple, if not simpler, than Ruby's, which you rate as green. Ruby may be /slightly/ more concise than Python in certain cases due to its Perl influences, but those instances of specialized syntax also make it more complex. To wit, I refer you to http://webcache.googleusercontent.com/search?q=cache:dyugd_KlqvcJ:blog.nicksieger.com/articles/2006/10/27/visualization-of-rubys-grammar+ruby+grammar+visualization&cd=1&hl=en&ct=clnk&gl=us Note the complexity of the graph for Ruby's grammar. By comparison, here is the same graph for Python (generated from a file linked to in the post's comment thread): http://rebertia.com/images/python_grammar_graph.png (Disclaimer: Neither of the graphs are current.) Additionally, you rate Python orange but Perl green for "Does the language provide a useful and consistent set of object oriented constructs?". Could you explain your reasoning for this? While neither Python nor Perl have the level of object-oriented purity of Ruby or Smalltalk, my understanding is that short of using CPAN libraries for Perl or dealing in Perl 6, Perl and Python have a substantially similar object model, so I don't how Python could rate below Perl in this area. Cheers, Chris -- http://blog.rebertia.com From andrew at acooke.org Mon May 3 09:06:59 2010 From: andrew at acooke.org (andrew cooke) Date: Mon, 3 May 2010 06:06:59 -0700 (PDT) Subject: Ann: Validating Emails and HTTP URLs in Python Message-ID: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> Hi, The latest Lepl release includes an implementation of RFC 3696 - the RFC that describes how best to validate email addresses and HTTP URLs. For more information please see http://www.acooke.org/lepl/rfc3696.html Lepl's main page is http://www.acooke.org/lepl Because Lepl compiles to regular expressions wherever possible, the library is quite fast - in testing I was seeing about 1ms needed to validate a URL. Please bear in mind that this is the very first release of this module, so it may have some bugs... If you find any problems contact me and I'll fix them ASAP. Thanks, Andrew From clp2 at rebertia.com Mon May 3 09:18:55 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 06:18:55 -0700 Subject: strange interaction between open and cwd In-Reply-To: <4BDEC4A5.5070801@ftml.net> References: <4BDEC4A5.5070801@ftml.net> Message-ID: On Mon, May 3, 2010 at 5:42 AM, Baz Walter wrote: > Python 2.6.4 (r264:75706, Mar ?7 2010, 02:18:40) > [GCC 4.4.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os >>>> os.mkdir('/home/baz/tmp/xxx') >>>> f = open('/home/baz/tmp/abc.txt', 'w') >>>> f.write('abc') >>>> f.close() >>>> os.chdir('/home/baz/tmp/xxx') >>>> os.getcwd() > '/home/baz/tmp/xxx' >>>> os.rmdir(os.getcwd()) >>>> os.getcwd() > Traceback (most recent call last): > ?File "", line 1, in > OSError: [Errno 2] No such file or directory >>>> open('../abc.txt').read() > 'abc' >>>> > > can anybody explain how python is able to read the file at the end of this > session? > but how can python determine the > parent directory of a directory that no longer exists? Whether or not /home/baz/tmp/xxx/ exists, we know from the very structure and properties of directory paths that its parent directory is, *by definition*, /home/baz/tmp/ (just chop off everything after the second-to-last slash). I would assume this is what happens internally. How exactly this interacts with, say, moving the directory to a new location rather than deleting it, I don't know; again, it would quite likely be platform-specific. Cheers, Chris -- http://blog.rebertia.com From philip at semanchuk.com Mon May 3 09:24:49 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 3 May 2010 09:24:49 -0400 Subject: Ann: Validating Emails and HTTP URLs in Python In-Reply-To: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> References: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> Message-ID: On May 3, 2010, at 9:06 AM, andrew cooke wrote: > > Hi, > > The latest Lepl release includes an implementation of RFC 3696 - the > RFC that describes how best to validate email addresses and HTTP > URLs. For more information please see http://www.acooke.org/lepl/rfc3696.html > > Lepl's main page is http://www.acooke.org/lepl > > Because Lepl compiles to regular expressions wherever possible, the > library is quite fast - in testing I was seeing about 1ms needed to > validate a URL. > > Please bear in mind that this is the very first release of this > module, so it may have some bugs... If you find any problems contact > me and I'll fix them ASAP. Thanks, Andrew, for contributing that to the open source community. FYI, Fourthought's PyXML has a module called uri.py that contains regexes for URL validation. I've over a million URLs (harvested from the Internet) through their code. I can't say I checked each and every result, but I never saw anything that would lead me to believe it was misbehaving. It might be interesting to compare the results of running a large list of URLs through your code and theirs. Good luck Philip From vithya.69 at gmail.com Mon May 3 09:33:49 2010 From: vithya.69 at gmail.com (vithya subramani) Date: Mon, 3 May 2010 19:03:49 +0530 Subject: Python code for outlook automation. Message-ID: hi, i need python source code for - Adding Contacts into Outlook. - Adding Blocked list,Safe sender list to junk Email folder in outlook - Counting total no of contacts in Blocked list,Safe sender list please provide help on these... Thanks, Vidu.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From space.ship.traveller at gmail.com Mon May 3 09:38:53 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 4 May 2010 01:38:53 +1200 Subject: Teaching Programming In-Reply-To: References: Message-ID: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> Dear Chris, Thanks for reading further into the site. Yes, it is complicated to provide a good comparison. It isn't always accurate and I welcome feedback. Please be aware that orange does not mean problem - it simply means take note that there may be potential issues that you need to consider. It is highly subjective, so I appreciate your feedback. The red dot is when there is definitely an issue that needs to be taken into consideration. It isn't "Okay, Warning, Error" because it isn't possible to make this kind of judgement without being omnipotent. There are several reason why I decided to rate the syntax as not being simple. 1) Indentation model is not appreciated by everyone - I think its a good model, but feedback from some other people has been that they don't like it. Also, I've had perfectly good Python code fall to bits after editing in a different editor. I'm not saying that this was the fault of Python, but in an educational context it might be a problem, since people are fairly limited and don't understand these issues. 2) I don't think that the list comprehension integrates well with the rest of the language. It is an additional syntactic construct which seems to be separate from the rest of the language. It would be nice if list comprehension was implemented in a way that was more general, using a general closure syntax for example. This is just my opinion, and it might not be valid (I don't research this point very heavily). I appreciate that in general the Python syntax is good and concise. It is hard. Some teacher might want to consider these issues more carefully. Do you think I should change that spot to green? I don't have a problem with doing that, as long as it makes sense. Thanks for providing the syntax images, they are very interesting. With regards to Perl, yes, this is probably something I need to investigate further. It is not always easy to do a comparison of this nature. From my experience, Perl generally seems to have a robust object model that is consistently implemented (even if the syntax is pretty wonky at times). However, in a sense, it is no better or worse than Python implementation... so why is it green dot? Do you think I should change Perl to orange or Python to green. The main criteria is whether it is going to be an issue in an educational context - this means, for new programmers, or those who might make error easily (syntax, semantic), etc. Also, I wonder if Visual Basic needs to be reevaluated on this criteria too. I guess what is important is the relative importance. I will bring this issue up on the Perl mailing list in order to get advice. Would you recommend changing Perl to orange? Thanks for your well thought out response, it is very helpful. Kind regards, Samuel On 4/05/2010, at 1:06 AM, Chris Rebert wrote: > On Mon, May 3, 2010 at 5:29 AM, Chris Rebert wrote: >> On Mon, May 3, 2010 at 5:05 AM, Samuel Williams >> wrote: >>> Dear Friends, >>> >>> I'm looking for some help from the Python community. I hope this is the >>> right place to ask for information. >>> >>> I'm putting together a website aimed at high school students and teachers, >>> and would like to make sure the following page is as good as possible: >>> http://programming.dojo.net.nz/languages/python/index >>> In particular, "Why would I learn this language?" section needs to have a >>> few paragraphs. I don't use Python predominantly so I hoped that you could >>> provide the main reasons why Python is a language someone would want to >>> learn about. > >> - A very clean syntax and elegant design, compared to other languages > > Also, I take issue with your classifying Python as orange with regard > to "Is the general syntax simple and concise?" on > http://programming.dojo.net.nz/resources/programming-language-comparison/index > Python's syntax is at least as simple, if not simpler, than Ruby's, > which you rate as green. Ruby may be /slightly/ more concise than > Python in certain cases due to its Perl influences, but those > instances of specialized syntax also make it more complex. > To wit, I refer you to > http://webcache.googleusercontent.com/search?q=cache:dyugd_KlqvcJ:blog.nicksieger.com/articles/2006/10/27/visualization-of-rubys-grammar+ruby+grammar+visualization&cd=1&hl=en&ct=clnk&gl=us > Note the complexity of the graph for Ruby's grammar. By comparison, > here is the same graph for Python (generated from a file linked to in > the post's comment thread): > http://rebertia.com/images/python_grammar_graph.png > (Disclaimer: Neither of the graphs are current.) > > Additionally, you rate Python orange but Perl green for "Does the > language provide a useful and consistent set of object oriented > constructs?". Could you explain your reasoning for this? While neither > Python nor Perl have the level of object-oriented purity of Ruby or > Smalltalk, my understanding is that short of using CPAN libraries for > Perl or dealing in Perl 6, Perl and Python have a substantially > similar object model, so I don't how Python could rate below Perl in > this area. > > Cheers, > Chris > -- > http://blog.rebertia.com From __peter__ at web.de Mon May 3 09:46:35 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2010 15:46:35 +0200 Subject: strange interaction between open and cwd References: Message-ID: Baz Walter wrote: > attempting to remove the cwd would produce an error). but how can python > determine the parent directory of a directory that no longer exists? My tentative explanation would be that the directory, namely the inode, still exists -- only the entry for it in its parent directory is gone. So "one level up from here" is still a valid operation, but there is no longer a path in the file system associated with "here". Peter From bazwal at ftml.net Mon May 3 09:49:46 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 14:49:46 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> Message-ID: <4BDED47A.7050106@ftml.net> On 03/05/10 14:18, Chris Rebert wrote: > Whether or not /home/baz/tmp/xxx/ exists, we know from the very > structure and properties of directory paths that its parent directory > is, *by definition*, /home/baz/tmp/ (just chop off everything after > the second-to-last slash). I would assume this is what happens > internally. > How exactly this interacts with, say, moving the directory to a new > location rather than deleting it, I don't know; again, it would quite > likely be platform-specific. but how does '..' get resolved in the relative path '../abc.txt'? i'm assuming python must initially use getcwd() internally to do this, and then if that fails it falls back on something else. but what is that something else? is it something that is reproducible in pure python? From clp2 at rebertia.com Mon May 3 09:56:42 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 06:56:42 -0700 Subject: strange interaction between open and cwd In-Reply-To: <4BDED47A.7050106@ftml.net> References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: On Mon, May 3, 2010 at 6:49 AM, Baz Walter wrote: > On 03/05/10 14:18, Chris Rebert wrote: >> Whether or not /home/baz/tmp/xxx/ exists, we know from the very >> structure and properties of directory paths that its parent directory >> is, *by definition*, /home/baz/tmp/ (just chop off everything after >> the second-to-last slash). I would assume this is what happens >> internally. >> How exactly this interacts with, say, moving the directory to a new >> location rather than deleting it, I don't know; again, it would quite >> likely be platform-specific. > > but how does '..' get resolved in the relative path '../abc.txt'? i'm > assuming python must initially use getcwd() internally to do this, and then > if that fails it falls back on something else. but what is that something > else? is it something that is reproducible in pure python? I would think that the OS system call, not Python itself, does the relative->absolute conversion. Cheers, Chris -- Fsck MMW. From clp2 at rebertia.com Mon May 3 09:58:39 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 06:58:39 -0700 Subject: Teaching Programming In-Reply-To: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> References: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> Message-ID: > On 4/05/2010, at 1:06 AM, Chris Rebert wrote: >> On Mon, May 3, 2010 at 5:29 AM, Chris Rebert wrote: >>> On Mon, May 3, 2010 at 5:05 AM, Samuel Williams >>> wrote: >>>> In particular, "Why would I learn this language?" section needs to have a >>>> few paragraphs. I don't use Python predominantly so I hoped that you could >>>> provide the main reasons why Python is a language someone would want to >>>> learn about. >> >>> - A very clean syntax and elegant design, compared to other languages >> >> Also, I take issue with your classifying Python as orange with regard >> to "Is the general syntax simple and concise?" on >> http://programming.dojo.net.nz/resources/programming-language-comparison/index >> Python's syntax is at least as simple, if not simpler, than Ruby's, >> which you rate as green. Ruby may be /slightly/ more concise than >> Python in certain cases due to its Perl influences, but those >> instances of specialized syntax also make it more complex. >> To wit, I refer you to >> http://webcache.googleusercontent.com/search?q=cache:dyugd_KlqvcJ:blog.nicksieger.com/articles/2006/10/27/visualization-of-rubys-grammar+ruby+grammar+visualization&cd=1&hl=en&ct=clnk&gl=us >> Note the complexity of the graph for Ruby's grammar. By comparison, >> here is the same graph for Python (generated from a file linked to in >> the post's comment thread): >> http://rebertia.com/images/python_grammar_graph.png >> (Disclaimer: Neither of the graphs are current.) >> >> Additionally, you rate Python orange but Perl green for "Does the >> language provide a useful and consistent set of object oriented >> constructs?". Could you explain your reasoning for this? While neither >> Python nor Perl have the level of object-oriented purity of Ruby or >> Smalltalk, my understanding is that short of using CPAN libraries for >> Perl or dealing in Perl 6, Perl and Python have a substantially >> similar object model, so I don't how Python could rate below Perl in >> this area. On Mon, May 3, 2010 at 6:38 AM, Samuel Williams wrote: > Dear Chris, > > Thanks for reading further into the site. > > Yes, it is complicated to provide a good comparison. It isn't always accurate and I welcome feedback. > > Please be aware that orange does not mean problem - it simply means take note that there may be potential issues that you need to consider. It is highly subjective, so I appreciate your feedback. The red dot is when there is definitely an issue that needs to be taken into consideration. It isn't "Okay, Warning, Error" because it isn't possible to make this kind of judgement without being omnipotent. > > There are several reason why I decided to rate the syntax as not being simple. > 1) Indentation model is not appreciated by everyone - I think its a good model, but feedback from some other people has been that they don't like it. Also, I've had perfectly good Python code fall to bits after editing in a different editor. I'm not saying that this was the fault of Python, but in an educational context it might be a problem, since people are fairly limited and don't understand these issues. > 2) I don't think that the list comprehension integrates well with the rest of the language. It is an additional syntactic construct which seems to be separate from the rest of the language. It would be nice if list comprehension was implemented in a way that was more general, using a general closure syntax for example. This is just my opinion, and it might not be valid (I don't research this point very heavily). > > I appreciate that in general the Python syntax is good and concise. It is hard. Some teacher might want to consider these issues more carefully. Do you think I should change that spot to green? I don't have a problem with doing that, as long as it makes sense. Yes, I do think it ought to be green, though I admit I'm not unbiased on this. I will point out that (1) does not seem related to "simplicity and conciseness", which is what that row in the comparison claims to be about. > With regards to Perl, yes, this is probably something I need to investigate further. It is not always easy to do a comparison of this nature. From my experience, Perl generally seems to have a robust object model that is consistently implemented (even if the syntax is pretty wonky at times). However, in a sense, it is no better or worse than Python implementation... so why is it green dot? Do you think I should change Perl to orange or Python to green. I'm unsure, but in either case, at least based on my limited knowledge of Perl 5, it again seems rather strange for Python & Perl to not be rated approximately the same in this area (if anything, I'd think Perl might be slightly worse off due to its syntax; but again, I'm not unbiased and my Perl knowledge is limited). Cheers, Chris -- Avoid "top-posting" (google it) http://blog.rebertia.com From space.ship.traveller at gmail.com Mon May 3 10:05:04 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 4 May 2010 02:05:04 +1200 Subject: Teaching Programming In-Reply-To: References: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> Message-ID: <678305F9-CE2F-4467-9E1D-FBF8235A4A7D@gmail.com> Dear Chris, I will take your feedback into consideration and let you know the outcome when I have time to think about it. Again, I appreciate your thoughts. Thanks for taking the time to think about the comparison chart. Kind regards, Samuel On 4/05/2010, at 1:58 AM, Chris Rebert wrote: >> I appreciate that in general the Python syntax is good and concise. It is hard. Some teacher might want to consider these issues more carefully. Do you think I should change that spot to green? I don't have a problem with doing that, as long as it makes sense. > > Yes, I do think it ought to be green, though I admit I'm not unbiased > on this. I will point out that (1) does not seem related to > "simplicity and conciseness", which is what that row in the comparison > claims to be about. > >> With regards to Perl, yes, this is probably something I need to investigate further. It is not always easy to do a comparison of this nature. From my experience, Perl generally seems to have a robust object model that is consistently implemented (even if the syntax is pretty wonky at times). However, in a sense, it is no better or worse than Python implementation... so why is it green dot? Do you think I should change Perl to orange or Python to green. > > I'm unsure, but in either case, at least based on my limited knowledge > of Perl 5, it again seems rather strange for Python & Perl to not be > rated approximately the same in this area (if anything, I'd think Perl > might be slightly worse off due to its syntax; but again, I'm not > unbiased and my Perl knowledge is limited). From bazwal at ftml.net Mon May 3 10:10:21 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 15:10:21 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BDED94D.20209@ftml.net> On 03/05/10 14:56, Chris Rebert wrote: >> but how does '..' get resolved in the relative path '../abc.txt'? i'm >> assuming python must initially use getcwd() internally to do this, and then >> if that fails it falls back on something else. but what is that something >> else? is it something that is reproducible in pure python? > > I would think that the OS system call, not Python itself, does the > relative->absolute conversion. so there is a discrepancy between some of the std library path functions (like realpath, getcwd, abspath) and the built-in open function. there are files which can be opened for which it is impossible to resolve their full paths (on some platforms). From andrew at acooke.org Mon May 3 10:13:58 2010 From: andrew at acooke.org (andrew cooke) Date: Mon, 3 May 2010 07:13:58 -0700 (PDT) Subject: Ann: Validating Emails and HTTP URLs in Python References: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> Message-ID: > FYI, Fourthought's PyXML has a module called uri.py that contains ? > regexes for URL validation. I've over a million URLs (harvested from ? > the Internet) through their code. I can't say I checked each and every ? > result, but I never saw anything that would lead me to believe it was ? > misbehaving. > > It might be interesting to compare the results of running a large list ? > of URLs through your code and theirs. > > Good luck > Philip It's getting a set of URLs that's the main problem. I've tested it with URL examples in RFC 3696, and with a few extra ones that test particular issues, but when I looked around I couldn't find any public, obvious list of URLs for general testing. Could I use your list? Also, same for emails... Cheers, Andrew Cheers, Andrew From invalid at invalid.invalid Mon May 3 10:22:26 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 14:22:26 +0000 (UTC) Subject: strange interaction between open and cwd References: Message-ID: On 2010-05-03, Peter Otten <__peter__ at web.de> wrote: > Baz Walter wrote: > >> attempting to remove the cwd would produce an error). but how can >> python determine the parent directory of a directory that no longer >> exists? Python doesn't determine the parent directory. The Unix system call and filesystem code do. The same thing happens in bash. IOW, you can do this: $ rm -rf $PWD; cd .. > My tentative explanation would be that the directory, namely the > inode, still exists -- only the entry for it in its parent directory > is gone. That sounds right. > So "one level up from here" is still a valid operation, but there is > no longer a path in the file system associated with "here". I believe that is the case. -- Grant Edwards grant.b.edwards Yow! -- I have seen the at FUN -- gmail.com From bazwal at ftml.net Mon May 3 10:23:47 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 15:23:47 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: Message-ID: <4BDEDC73.1020301@ftml.net> On 03/05/10 14:46, Peter Otten wrote: > Baz Walter wrote: > >> attempting to remove the cwd would produce an error). but how can python >> determine the parent directory of a directory that no longer exists? > > My tentative explanation would be that the directory, namely the inode, > still exists -- only the entry for it in its parent directory is gone. > > So "one level up from here" is still a valid operation, but there is no > longer a path in the file system associated with "here". so "here" must always be available somehow, even if getcwd() fails (something like the environment variable $PWD). shame that os.getenv('PWD') isn't reliable, as it would solve my issue :( From invalid at invalid.invalid Mon May 3 10:24:20 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 14:24:20 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: > On 03/05/10 14:18, Chris Rebert wrote: >> Whether or not /home/baz/tmp/xxx/ exists, we know from the very >> structure and properties of directory paths that its parent directory >> is, *by definition*, /home/baz/tmp/ (just chop off everything after >> the second-to-last slash). I would assume this is what happens >> internally. >> How exactly this interacts with, say, moving the directory to a new >> location rather than deleting it, I don't know; again, it would quite >> likely be platform-specific. > > but how does '..' get resolved in the relative path '../abc.txt'? The current directory has an entry named '..' that points to the parent directory. > i'm assuming python must initially use getcwd() internally to do > this, Nope. Python just passes the string '../abc.txt' to libc's open() function, and that in turn passes it on to the Unix/Linux open() syscall, when follows the link in the current working directory named '..'. > and then if that fails it falls back on something else. but what is > that something else? is it something that is reproducible in pure > python? None of this has anything at all to do with Python. -- Grant Edwards grant.b.edwards Yow! I didn't order any at WOO-WOO ... Maybe a YUBBA gmail.com ... But no WOO-WOO! From philip at semanchuk.com Mon May 3 10:28:54 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 3 May 2010 10:28:54 -0400 Subject: Ann: Validating Emails and HTTP URLs in Python In-Reply-To: References: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> Message-ID: <25608F6F-DF17-4E32-A693-4B96B3DBD624@semanchuk.com> On May 3, 2010, at 10:13 AM, andrew cooke wrote: >> FYI, Fourthought's PyXML has a module called uri.py that contains >> regexes for URL validation. I've over a million URLs (harvested from >> the Internet) through their code. I can't say I checked each and >> every >> result, but I never saw anything that would lead me to believe it was >> misbehaving. >> >> It might be interesting to compare the results of running a large >> list >> of URLs through your code and theirs. >> >> Good luck >> Philip > > It's getting a set of URLs that's the main problem. I've tested it > with URL examples in RFC 3696, and with a few extra ones that test > particular issues, but when I looked around I couldn't find any > public, obvious list of URLs for general testing. Could I use your > list? > > Also, same for emails... If I still had a list of URLs you'd be welcome to it. The list was generated as part of a spidering project that's long gone. If all you want to do is generate a list of URLs and email addresses, you could cobble a robots.txt-respectful spider without too much trouble. As with so many things, it's just an SMOP [1]. =) [1] - http://en.wikipedia.org/wiki/Small_matter_of_programming bye Philip From davea at ieee.org Mon May 3 10:49:16 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 03 May 2010 10:49:16 -0400 Subject: strange interaction between open and cwd In-Reply-To: <4BDED47A.7050106@ftml.net> References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BDEE26C.1050608@ieee.org> Baz Walter wrote: > On 03/05/10 14:18, Chris Rebert wrote: >> Whether or not /home/baz/tmp/xxx/ exists, we know from the very >> structure and properties of directory paths that its parent directory >> is, *by definition*, /home/baz/tmp/ (just chop off everything after >> the second-to-last slash). I would assume this is what happens >> internally. >> How exactly this interacts with, say, moving the directory to a new >> location rather than deleting it, I don't know; again, it would quite >> likely be platform-specific. > > but how does '..' get resolved in the relative path '../abc.txt'? i'm > assuming python must initially use getcwd() internally to do this, and > then if that fails it falls back on something else. but what is that > something else? is it something that is reproducible in pure python? > > os.path.dirname() doesn't care about whether a path actually represents a location on disk. It just parses the string. If I were processing the .., that's what I'd use to normalize it. DaveA From invalid at invalid.invalid Mon May 3 10:55:16 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 14:55:16 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: > On 03/05/10 14:56, Chris Rebert wrote: >>> but how does '..' get resolved in the relative path '../abc.txt'? i'm >>> assuming python must initially use getcwd() internally to do this, and then >>> if that fails it falls back on something else. but what is that something >>> else? is it something that is reproducible in pure python? >> >> I would think that the OS system call, not Python itself, does the >> relative->absolute conversion. > > so there is a discrepancy between some of the std library path functions > (like realpath, getcwd, abspath) and the built-in open function. Not really. There is a discrepancy between your perception and expectations and the way the Unix filesystem works. > there are files which can be opened for which it is impossible to > resolve their full paths (on some platforms). Sort of. The file in question _has_ a full path, you just can't tell what it is based on the path you used to open it. -- Grant Edwards grant.b.edwards Yow! I smell a RANCID at CORN DOG! gmail.com From invalid at invalid.invalid Mon May 3 10:56:42 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 14:56:42 +0000 (UTC) Subject: strange interaction between open and cwd References: Message-ID: On 2010-05-03, Baz Walter wrote: > On 03/05/10 14:46, Peter Otten wrote: >> Baz Walter wrote: >> >>> attempting to remove the cwd would produce an error). but how can python >>> determine the parent directory of a directory that no longer exists? >> >> My tentative explanation would be that the directory, namely the inode, >> still exists -- only the entry for it in its parent directory is gone. >> >> So "one level up from here" is still a valid operation, but there is no >> longer a path in the file system associated with "here". > > so "here" must always be available somehow, Yes. > even if getcwd() fails If the current working directory doesn't _have_ a path within a filesystem, what do you expect it to do? > (something like the environment variable $PWD). shame that > os.getenv('PWD') isn't reliable, as it would solve my issue :( I don't understand what you mean by that. -- Grant Edwards grant.b.edwards Yow! I'm wet! I'm wild! at gmail.com From see at sig.for.address Mon May 3 11:17:47 2010 From: see at sig.for.address (Victor Eijkhout) Date: Mon, 3 May 2010 10:17:47 -0500 Subject: long int computations Message-ID: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> I have two long ints, both too long to convert to float, but their ratio is something reasonable. How can I compute that? The obvious "(1.*x)/y" does not work. Victor. -- Victor Eijkhout -- eijkhout at tacc utexas edu From lists at nanl.de Mon May 3 11:22:58 2010 From: lists at nanl.de (Mirko Vogt) Date: Mon, 03 May 2010 17:22:58 +0200 Subject: using python2.6 on windows without installation In-Reply-To: References: <1272554759.3626.52.camel@mia> Message-ID: <1272900178.3769.3.camel@mia> Thanks a lot for all your solutions! Tried installing it "just for the current user" as suggested by Christian and it works like a charme, so there seems to be no need for another python distribution in this case. Thanks a lot once again! mirko On Fri, 2010-04-30 at 01:34 +0200, Christian Heimes wrote: > Mirko Vogt wrote: > > Hey, > > > > is there a way to use python2.6 without having used the installation > > routine? > > > > When I install python2.6 and copy over the python-directory (C:\programs > > \python2.6) to another windows host and trying to execute python.exe > > there, I get an error that python26.dll could not be found. > > > > On the host where I used the installation routine, python26.dll is > > stored in C:\windows\system32 which (obviously) isn't on the host where > > I just copied the python directory to. > > > > Is it possible to include python26.dll in the application folder or tell > > python not to look in C:\windows\system32 for its library? > > You need to include more than just python26.dll. The correct MSVCRT > version must be shipped with your package or it has to be installed by > your users. > > Fear not, my friend! The solution for your quest is easy to come by. > Install Python 2.6 again but this time chose "install only for me" > instead of "for all users". With this option all necessary files land > into one directory. As long as you have no need for fancy stuff like COM > and Windows services you have to worry about python26.dll in Windows' > system32 directory. > > At work we run our entire application stack including Python2.6, tons of > Python packages with extensions, a complete Java runtime environment and > a pile of DLLs from svn. Works like a charm. > > Christian > -- This email address is used for mailinglist purposes only. Non-mailinglist emails will be dropped automatically. If you want to get in contact with me personally, please mail to: mirko.vogt nanl de From jarausch at igpm.rwth-aachen.de Mon May 3 11:25:07 2010 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 03 May 2010 17:25:07 +0200 Subject: Teaching Programming In-Reply-To: References: Message-ID: <84886fFomtU1@mid.dfncis.de> On 05/03/10 14:29, Chris Rebert wrote: > On Mon, May 3, 2010 at 5:05 AM, Samuel Williams > wrote: >> Dear Friends, >> >> I'm looking for some help from the Python community. I hope this is the >> right place to ask for information. >> >> I'm putting together a website aimed at high school students and teachers, >> and would like to make sure the following page is as good as possible: >> http://programming.dojo.net.nz/languages/python/index >> In particular, "Why would I learn this language?" section needs to have a >> few paragraphs. I don't use Python predominantly so I hoped that you could >> provide the main reasons why Python is a language someone would want to >> learn about. > > - Significant use in certain applications areas: > * Web programming (common frameworks include Django & TurboGears) > * Scientific and numerical computing (see SciPy and Numeric) > - Large "batteries-included" standard library, with a large number of > third-party libraries also available > - Used by Industrial Light and Magic, Google/YouTube, and other big > names (http://www.python.org/about/success/) > - A very clean syntax and elegant design, compared to other languages > I've used Perl for quite some years before I switched to Python. I've been burnt by Perl. There so many hidden variables and states which influence the outcome of nearly each statement in Perl, that it is hard to understand and debug unless you're using it several hours a day (each day). What convinced me is clearly written in http://www.linuxjournal.com/article/3882 Please have a look at it, Helmut. (I'm teaching programming for more than 15 years) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From __peter__ at web.de Mon May 3 11:30:03 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2010 17:30:03 +0200 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: Victor Eijkhout wrote: > I have two long ints, both too long to convert to float, but their ratio > is something reasonable. How can I compute that? The obvious "(1.*x)/y" > does not work. >>> import fractions >>> x = 12345 * 10**1000 >>> y = 765 * 10**1000 >>> float(x) Traceback (most recent call last): File "", line 1, in OverflowError: long int too large to convert to float >>> fractions.Fraction(x, y) Fraction(823, 51) >>> float(_) 16.137254901960784 Peter From malaclypse2 at gmail.com Mon May 3 11:41:31 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 3 May 2010 11:41:31 -0400 Subject: long int computations In-Reply-To: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: On Mon, May 3, 2010 at 11:17 AM, Victor Eijkhout wrote: > I have two long ints, both too long to convert to float, but their ratio > is something reasonable. How can I compute that? The obvious "(1.*x)/y" > does not work. You didn't say what version of python you were using, but this seems to work for me in 2.6.4: >>> long1 = 10**1000 >>> long2 = long1 * 2 >>> float(long1) Traceback (most recent call last): File "", line 1, in float(long1) OverflowError: long int too large to convert to float >>> long1/long2 0L >>> from __future__ import division >>> long1/long2 0.5 The "from __future__ import division" line gets python to return a float as the result of dividing two integers (or longs), instead of returning an integer. If I recall correctly, this has been available for quite a few python versions (since 2.2 maybe?), and has become the default in python 3. If you need to do integer division, you would use the // operator: >>> long1 // long2 0L Hope that helps. -- Jerry From varnikat22 at gmail.com Mon May 3 11:44:48 2010 From: varnikat22 at gmail.com (varnikat t) Date: Mon, 3 May 2010 21:14:48 +0530 Subject: How to check when OCRing is finished Message-ID: Hi, How to check if OCR engine like cuneiform,ocropus,ocrad OCRing an image has completed the job if running it from a python program? I am using a progress bar on the front end to show the OCRing progress happening in background but how to stop progress bar automatically when OCRing is done. As of now, I am just running the timer for a few seconds (considering the maximum time taken by ocropus and for high resolution image) but then the OCRing time varies for different engines and different images.Some take less and some take more. Any solutions? Regards Varnika Tewari (UMIT,SNDT University) -------------- next part -------------- An HTML attachment was scrubbed... URL: From bryanjugglercryptographer at yahoo.com Mon May 3 11:53:18 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Mon, 3 May 2010 08:53:18 -0700 (PDT) Subject: matching strings in a large set of strings References: Message-ID: Karin Lagesen wrote: > I have approx 83 million strings, all 14 characters long. I need to be > able to take another string and find out whether this one is present > within the 83 million strings. [...] > I run out of memory building both the set and the dictionary, so > what I seem to be left with is the list I agree with the recommendations to try modules that maintain the set on disk (sqlite, dbm, shelve), but here's an in-memory solution: Hash to about 8 million buckets, and use a compact representation for the several strings in each bucket. That gives you most of the speed and avoids most of the memory overhead. Python makes it easy: class ConstLenStrSet: """ Keep a set of strings all of the same length. Support set.add() and Python's 'in' test. """ def __init__(self, strlen=14, nbuckets=8000000): assert strlen > 0 and nbuckets > 0 self.strlen = strlen self.nbuckets = nbuckets | 1 self.table = [''] * self.nbuckets def _hashstr(self, s): return hash(s) % self.nbuckets def add(self, s): assert len(s) == self.strlen if s not in self: self.table[self._hashstr(s)] += s def __contains__(self, s): data = self.table[self._hashstr(s)] for i in range(0, len(data), self.strlen): if data[i : i + self.strlen] == s: return True return False # Rudimentary demo-test: from random import choice from string import letters def rnd_str(slen=14): return ''.join(choice(letters) for _ in range(slen)) # Test against Python's built-in set sref = set() for i in range(830000): sref.add(rnd_str()) print('Strings generated.') sset = sset = ConstLenStrSet(14, 80000) for s in sref: sset.add(s) print 'ConstLenStrSet loaded.' for s in sref: assert s in sset for i in range(1000): s = rnd_str() if s in sref: print 'That was unlucky.' else: assert s not in sset If building the set is too slow, and you know you don't have a lot of duplicate strings, you can use a faster insert method that doesn't check whether the string is already in the set: def add_quick(self, s): assert len(s) == self.strlen self.table[self._hashstr(s)] += s -- --Bryan From davea at ieee.org Mon May 3 12:10:36 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 03 May 2010 12:10:36 -0400 Subject: long int computations In-Reply-To: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: <4BDEF57C.1070409@ieee.org> Victor Eijkhout wrote: > I have two long ints, both too long to convert to float, but their ratio > is something reasonable. How can I compute that? The obvious "(1.*x)/y" > does not work. > > Victor. > > You don't make clear what you mean by "too long to convert to float." Do you mean can't convert exactly, or that they're more than 400 digits or whatever the exponent limit of float is (I'm too lazy to look it up right now) ? Assuming the latter, you could divide each by the same constant, then use your formula above to make a float version of the ratio. How to pick the constant? How about the smaller of your numbers, divided by 1e18 ? You'd have to build that number using longs as well. Alternatively, you could build your own floating point library, using longs as the mantissa. DaveA From ppearson at nowhere.invalid Mon May 3 12:16:24 2010 From: ppearson at nowhere.invalid (Peter Pearson) Date: 3 May 2010 16:16:24 GMT Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: <848b6oFvnkU1@mid.individual.net> On Mon, 03 May 2010 17:30:03 +0200, Peter Otten <__peter__ at web.de> wrote: > Victor Eijkhout wrote: > >> I have two long ints, both too long to convert to float, but their ratio >> is something reasonable. How can I compute that? The obvious "(1.*x)/y" >> does not work. > >>>> import fractions >>>> x = 12345 * 10**1000 >>>> y = 765 * 10**1000 >>>> float(x) > Traceback (most recent call last): > File "", line 1, in > OverflowError: long int too large to convert to float >>>> fractions.Fraction(x, y) > Fraction(823, 51) >>>> float(_) > 16.137254901960784 Does this still work if y = 765 * 10**1000 + 1 ? It looks as if it might rely on x and y having a large common divisor. (I blush to confess that my Python has no fractions module, and it's too early in the morning to risk trying to update anything.) -- To email me, substitute nowhere->spamcop, invalid->net. From jpiitula at ling.helsinki.fi Mon May 3 12:23:40 2010 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 03 May 2010 19:23:40 +0300 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: Peter Otten writes: > Victor Eijkhout wrote: > > > I have two long ints, both too long to convert to float, but their > > ratio is something reasonable. How can I compute that? The obvious > > "(1.*x)/y" does not work. > > >>> import fractions > >>> x = 12345 * 10**1000 > >>> y = 765 * 10**1000 > >>> float(x) > Traceback (most recent call last): > File "", line 1, in > OverflowError: long int too large to convert to float > >>> fractions.Fraction(x, y) > Fraction(823, 51) > >>> float(_) > 16.137254901960784 Logarithms agree to 13 decimal digits or so: >>> math.exp(math.log(x) - math.log(y)) 16.13725490196353 From bazwal at ftml.net Mon May 3 12:27:05 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 17:27:05 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: Message-ID: <4BDEF959.7070104@ftml.net> On 03/05/10 15:56, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: >> On 03/05/10 14:46, Peter Otten wrote: >>> Baz Walter wrote: >>> >>>> attempting to remove the cwd would produce an error). but how can python >>>> determine the parent directory of a directory that no longer exists? >>> >>> My tentative explanation would be that the directory, namely the inode, >>> still exists -- only the entry for it in its parent directory is gone. >>> >>> So "one level up from here" is still a valid operation, but there is no >>> longer a path in the file system associated with "here". >> >> so "here" must always be available somehow, > > Yes. > >> even if getcwd() fails > > If the current working directory doesn't _have_ a path within a > filesystem, what do you expect it to do? well, i expect it to fail, like i said :) >> (something like the environment variable $PWD). shame that >> os.getenv('PWD') isn't reliable, as it would solve my issue :( > > I don't understand what you mean by that. i'm trying to understand how the path of the cwd can be known if there is no entry for it in the filesytem - but this is starting to get a little OT, so i won't pursue it here any longer. From invalid at invalid.invalid Mon May 3 12:34:12 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 16:34:12 +0000 (UTC) Subject: strange interaction between open and cwd References: Message-ID: On 2010-05-03, Baz Walter wrote: >>> (something like the environment variable $PWD). shame that >>> os.getenv('PWD') isn't reliable, as it would solve my issue :( >> >> I don't understand what you mean by that. > > i'm trying to understand how the path of the cwd can be known if there > is no entry for it in the filesytem It can't. That's why cwd() failed. > - but this is starting to get a little OT, so i won't pursue it here > any longer. OK. -- Grant Edwards grant.b.edwards Yow! Should I do my BOBBIE at VINTON medley? gmail.com From __peter__ at web.de Mon May 3 12:39:33 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2010 18:39:33 +0200 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> <848b6oFvnkU1@mid.individual.net> Message-ID: Peter Pearson wrote: > On Mon, 03 May 2010 17:30:03 +0200, Peter Otten <__peter__ at web.de> wrote: >> Victor Eijkhout wrote: >> >>> I have two long ints, both too long to convert to float, but their ratio >>> is something reasonable. How can I compute that? The obvious "(1.*x)/y" >>> does not work. >> >>>>> import fractions >>>>> x = 12345 * 10**1000 >>>>> y = 765 * 10**1000 >>>>> float(x) >> Traceback (most recent call last): >> File "", line 1, in >> OverflowError: long int too large to convert to float >>>>> fractions.Fraction(x, y) >> Fraction(823, 51) >>>>> float(_) >> 16.137254901960784 > > Does this still work if y = 765 * 10**1000 + 1 ? It looks > as if it might rely on x and y having a large common divisor. You mean something like this? >>> import fractions >>> x = 765 * 10**1000 >>> fractions.gcd(x, x+1) 1L >>> float(fractions.Fraction(x, x+1)) 1.0 But my D'oh!* moment really was seeing Jerry Hill doing it with >>> from __future__ import division >>> x/(x+1) 1.0 Peter (*) I'm having a lot of these lately. Looks like I need a new brain. From lbolla at gmail.com Mon May 3 12:51:26 2010 From: lbolla at gmail.com (lbolla) Date: Mon, 3 May 2010 09:51:26 -0700 (PDT) Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Message-ID: <3d78b115-9fa2-4b2b-bd0d-ff21f1c9509d@e2g2000yqn.googlegroups.com> On May 3, 8:46?am, Gilles Ganault wrote: > Hello > > I'd like to build a prototype that will combine a web server as > front-end (it must support GZIPping data to the remote client when > there are a lot of data to return), and SQLite as back-end, call the > server from a VB.Net application, and see how well this works. I want > to see if performance is significantly lower than using a server that > uses a binary protocol. > > I'm no Python expert, so would appreciate any information on how to > combine a web server and SQLite into a single Python application. This > is just for a proof-of-concept, so it doesn't need to be > shipping-quality. > > Thank you for any hint. I quite like web.py: http://webpy.org/ L. From bazwal at ftml.net Mon May 3 12:59:25 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 17:59:25 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BDF00ED.8090604@ftml.net> On 03/05/10 15:55, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: >> On 03/05/10 14:56, Chris Rebert wrote: >>>> but how does '..' get resolved in the relative path '../abc.txt'? i'm >>>> assuming python must initially use getcwd() internally to do this, and then >>>> if that fails it falls back on something else. but what is that something >>>> else? is it something that is reproducible in pure python? >>> >>> I would think that the OS system call, not Python itself, does the >>> relative->absolute conversion. >> >> so there is a discrepancy between some of the std library path functions >> (like realpath, getcwd, abspath) and the built-in open function. > > Not really. There is a discrepancy between your perception and > expectations and the way the Unix filesystem works. it's a fact that realpath/abspath/normpath etc can fail for paths that don't when used with os.stat or the builtin open function. i think it's reasonable to expect that a path that can be used to successfully open a file wont then produce "No such file or directory" errors when used with an os.path function like realpath. it shouldn't be necessary to have detailed knowledge of the underlying filesytem to be able to use os.path - it's supposed to be generic. >> there are files which can be opened for which it is impossible to >> resolve their full paths (on some platforms). > > Sort of. The file in question _has_ a full path, you just can't tell > what it is based on the path you used to open it. yes, that's exactly what i was trying to demonstrate in my OP. i can use python to open a file; but under certain circumstances, there seems to be no guarantee that i can then use python to locate that file in the filesystem. From invalid at invalid.invalid Mon May 3 13:12:09 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 17:12:09 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: > it's a fact that realpath/abspath/normpath etc can fail for paths > that don't when used with os.stat or the builtin open function. True. > i think it's reasonable to expect that a path that can be used to > successfully open a file wont then produce "No such file or > directory" errors when used with an os.path function like realpath. Yes, I understand that's what you think. That's not, however, a reasonable expectation in some cases. > it shouldn't be necessary to have detailed knowledge of the > underlying filesytem to be able to use os.path - it's supposed to be > generic. If you ask for the path of a file that has no path (or for which the path can't be determined from the provided information), what do you propose should happen? >>> there are files which can be opened for which it is impossible to >>> resolve their full paths (on some platforms). >> >> Sort of. The file in question _has_ a full path, you just can't tell >> what it is based on the path you used to open it. > > yes, that's exactly what i was trying to demonstrate in my OP. i can > use python to open a file; but under certain circumstances, there > seems to be no guarantee that i can then use python to locate that > file in the filesystem. Exactly. In your example, it's simply not possible to determine the file's absolute path within the filesystem given the relative path you provided. You requested something that wasn't possible. It failed. What do you think should have happened? -- Grant Edwards grant.b.edwards Yow! There's enough money at here to buy 5000 cans of gmail.com Noodle-Roni! From tjreedy at udel.edu Mon May 3 13:15:31 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 May 2010 13:15:31 -0400 Subject: Python dot-equals (syntax proposal) In-Reply-To: References: <2b5baa96-f10f-4461-a991-0db353236583@37g2000yqm.googlegroups.com> <4bdcd631$0$27782$c3e8da3@news.astraweb.com> Message-ID: On 5/3/2010 12:37 AM, Alf P. Steinbach wrote: > * Terry Reedy: >> * Alf P. Steinbach: >>> * Aahz: >> >>>> and sometimes >>>> they rebind the original target to the same object. >>> >>> At the Python level that seems to be an undetectable null-operation. >> >> If you try t=(1,2,3); t[1]+=3, if very much matters that a rebind occurs. > > Testing: > > > >>> t = ([], [], []) > >>> t > ([], [], []) > >>> t[0] += ["blah"] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > >>> t > (['blah'], [], []) > >>> _ > > > Yep, it matters. So one should instead write t[0].extend('blah') to the same effect, but without the exception raising assignment attempt, when that is what one really means ;-). Terry Jan Reedy From tjreedy at udel.edu Mon May 3 13:32:14 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 May 2010 13:32:14 -0400 Subject: Teaching Programming In-Reply-To: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> References: <70C32392-56C2-4F05-AE46-F19A9D98B25E@gmail.com> Message-ID: On 5/3/2010 9:38 AM, Samuel Williams wrote: > Dear Chris, > > Thanks for reading further into the site. > > Yes, it is complicated to provide a good comparison. It isn't always > accurate and I welcome feedback. > > Please be aware that orange does not mean problem - it simply means > take note that there may be potential issues that you need to > consider. It is highly subjective, so I appreciate your feedback. The > red dot is when there is definitely an issue that needs to be taken > into consideration. It isn't "Okay, Warning, Error" because it isn't > possible to make this kind of judgement without being omnipotent. > > There are several reason why I decided to rate the syntax as not > being simple. 1) Indentation model is not appreciated by everyone - I Appreciation is orthogonal to simplicity. > think its a good model, but feedback from some other people has been > that they don't like it. Also, I've had perfectly good Python code > fall to bits after editing in a different editor. I'm not saying that I view this is a consequence of simplicity. Python does not have the complexity of usually redundant (but possibly contradictory) backup indication of structure. So to me, you are rating Python as not simple because it is too simple for some people for some purposes ;-). > this was the fault of Python, but in an educational context it might > be a problem, since people are fairly limited and don't understand > these issues. 2) I don't think that the list comprehension integrates > well with the rest of the language. It is an additional syntactic > construct which seems to be separate from the rest of the language. > It would be nice if list comprehension was implemented in a way that > was more general, using a general closure syntax for example. This is List comprehensions have been generalized in Python 3 to generator expressions and list/set/dict comprehensions. I do not know whether you rate Py2 or Py3 at your site, but for 'should I learn this language' comparision, Py3 would be fairest. > just my opinion, and it might not be valid (I don't research this > point very heavily). > > I appreciate that in general the Python syntax is good and concise. > It is hard. Some teacher might want to consider these issues more > carefully. Do you think I should change that spot to green? I don't > have a problem with doing that, as long as it makes sense. > > Thanks for providing the syntax images, they are very interesting. I chose Python over Perl (over a decade ago) partly because it seemed to me them to have a simpler, more consistent object model and system. Since then, the user class system has been integrated with the builtin type system, and the older separate class system eliminated in Python3, which, again, simplifies things. It is perhaps worth noting that Python's object model, and consequent function calling protocol, dates back at least to Barbara Liskov's CLU language. Terry Jan Reedy From bazwal at ftml.net Mon May 3 13:37:09 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 18:37:09 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> Message-ID: <4BDF09C5.7050107@ftml.net> On 03/05/10 15:24, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: >> On 03/05/10 14:18, Chris Rebert wrote: >>> Whether or not /home/baz/tmp/xxx/ exists, we know from the very >>> structure and properties of directory paths that its parent directory >>> is, *by definition*, /home/baz/tmp/ (just chop off everything after >>> the second-to-last slash). I would assume this is what happens >>> internally. >>> How exactly this interacts with, say, moving the directory to a new >>> location rather than deleting it, I don't know; again, it would quite >>> likely be platform-specific. >> >> but how does '..' get resolved in the relative path '../abc.txt'? > > The current directory has an entry named '..' that points to the > parent directory. > >> i'm assuming python must initially use getcwd() internally to do >> this, > > Nope. Python just passes the string '../abc.txt' to libc's open() > function, and that in turn passes it on to the Unix/Linux open() > syscall, when follows the link in the current working directory named > '..'. > >> and then if that fails it falls back on something else. but what is >> that something else? is it something that is reproducible in pure >> python? > > None of this has anything at all to do with Python. i think what i'm asking for is a python function that, given, say, a valid file descriptor, can return the file's full path. would such a thing even be possible? From invalid at invalid.invalid Mon May 3 13:41:42 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 17:41:42 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: > i think what i'm asking for is a python function that, given, say, a > valid file descriptor, can return the file's full path. Firstly, a file may have any number of paths (including 0). > would such a thing even be possible? Yes. You have to search the filesystem and compare the descirptor's inode number to that of every file in the filesystem. It will match 0 or more of them. However, that will probably take a long time (many minutes) for a typical "single partition" Unix filesystem. If you have a dedicated filesystem with a small number of files, it may be feasible. -- Grant Edwards grant.b.edwards Yow! !! I am having fun!!! at gmail.com From bazwal at ftml.net Mon May 3 13:45:31 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 18:45:31 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BDF0BBB.1080009@ftml.net> On 03/05/10 18:12, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: >>> Sort of. The file in question _has_ a full path, you just can't tell >>> what it is based on the path you used to open it. >> >> yes, that's exactly what i was trying to demonstrate in my OP. i can >> use python to open a file; but under certain circumstances, there >> seems to be no guarantee that i can then use python to locate that >> file in the filesystem. > > Exactly. > > In your example, it's simply not possible to determine the file's > absolute path within the filesystem given the relative path you > provided. > > You requested something that wasn't possible. It failed. What do you > think should have happened? path = '../abc.txt' os.path.realpath(path) -> "OSError: [Errno 2] No such file or directory" therefore: open(path) -> "IOError: [Errno 2] No such file or directory" i think that if the first of these seemingly "impossible" requests fails, it is reasonable to expect that the second one also fails. but the second one (sometimes) doesn't. i think they should always either both succeed, or both fail. From WolfgangMeiners01 at web.de Mon May 3 13:46:19 2010 From: WolfgangMeiners01 at web.de (Wolfgang Meiners) Date: Mon, 03 May 2010 19:46:19 +0200 Subject: recommended way to insert data into a one to many relationship using python In-Reply-To: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> References: <4bdc511b$0$6883$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4bdf0bec$0$6770$9b4e6d93@newsspool3.arcor-online.net> Wolfgang Meiners schrieb: [... example of a simple sql-database and relating questions ...] so after reading the hints of Peter Otten and Bryan i played around a bit and got the following solution. Of course it would be much simpler following Bryans idea of natural keys but i think, i will go step by step. Any useful comments appreacheated. Wolfgang ================================================================================ # !python # -*- coding: utf-8 -*- import sqlite3 schema = """ create table floors ( fid integer primary key autoincrement, floor text not null); create table rooms ( rid integer primary key autoincrement, number integer, fid integer references floors(fid)); create table employees ( eid integer primary key autoincrement, name text not null, rid integer references rooms(rid)); create view emplist as select name, number, floor from employees natural inner join rooms natural inner join floors; """ #con = sqlite3.connect("test.db") con = sqlite3.connect(":memory:") cur = con.cursor() for cmd in schema.split(';'): cur.execute(cmd) def insert_new_value(d): sql = """insert or ignore into floors(floor) select :floor where not exists (select * from floors where floor = :floor)""" cur.execute(sql,d) sql = """insert or ignore into rooms (number, fid) select :number, fid from floors where floor = :floor and not exists (select * from rooms natural inner join floors where number = :number and floor = :floor)""" cur.execute(sql,d) sql = """insert or ignore into employees(name,rid) select :name, rid from rooms natural inner join floors where number = :number and floor = :floor and not exists (select * from employees natural inner join rooms natural inner join floors where name = :name and number = :number and floor = :floor) """ cur.execute(sql,d) NewEmployees =[] NewEmployees.append({'name': 'Joe', 'number': 21, 'floor': 'first floor'}) NewEmployees.append({'name': 'Nancy', 'number': 22, 'floor': 'second floor'}) NewEmployees.append({'name': 'George', 'number': 89, 'floor': 'third floor'}) NewEmployees.append({'name': 'Ellen', 'number': 21, 'floor': 'first floor'}) NewEmployees.append({'name': 'Joe', 'number': 21, 'floor': 'first floor'}) print "Old Values:" print cur.execute("""select * from emplist order by name """).fetchall() for d in NewEmployees: insert_new_value(d) print "New Values:" print cur.execute("""select * from emplist order by name """).fetchall() con.close() ================================================================================ From crebert at ucsd.edu Mon May 3 13:53:31 2010 From: crebert at ucsd.edu (Chris Rebert) Date: Mon, 3 May 2010 10:53:31 -0700 Subject: How to check when OCRing is finished In-Reply-To: References: Message-ID: On Mon, May 3, 2010 at 8:44 AM, varnikat t wrote: > Hi, > How to check if OCR engine? like cuneiform,ocropus,ocrad OCRing an image has > completed the job if running it from a? python program? > > I am using a progress bar on the front end to show the OCRing progress > happening in background but how to stop progress bar automatically when > OCRing is done. > > As of now, I am just running the timer for a few seconds (considering the > maximum time taken by ocropus and for high resolution image) but then the > OCRing time varies for different engines and different images.Some take less > and some take more. > > Any solutions? I believe one generally uses an "indeterminate progress bar", throbber (http://en.wikipedia.org/wiki/Throbber), or other similar widget rather than a normal progress bar when the time an operation will take is indeterminate or can't be accurately estimated (in this case, due to invoking an external program which apparently does not report its intermediate progress). I presume such widgets have a way to be easily notified, and thus in turn indicate to the user, when an operation has indeed been completed. Cheers, Chris -- http://blog.rebertia.com From bazwal at ftml.net Mon May 3 13:56:59 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 18:56:59 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> Message-ID: <4BDF0E6B.2010600@ftml.net> On 03/05/10 18:41, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: > >> i think what i'm asking for is a python function that, given, say, a >> valid file descriptor, can return the file's full path. > > Firstly, a file may have any number of paths (including 0). yes, of course. i forgot about hard links - that pretty much kills that idea. oh well. From clp2 at rebertia.com Mon May 3 14:05:00 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 May 2010 11:05:00 -0700 Subject: strange interaction between open and cwd In-Reply-To: <4BDF0BBB.1080009@ftml.net> References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> Message-ID: On Mon, May 3, 2010 at 10:45 AM, Baz Walter wrote: > On 03/05/10 18:12, Grant Edwards wrote: >> On 2010-05-03, Baz Walter ?wrote: >>>> Sort of. ?The file in question _has_ a full path, you just can't tell >>>> what it is based on the path you used to open it. >>> >>> yes, that's exactly what i was trying to demonstrate in my OP. i can >>> use python to open a file; but under certain circumstances, there >>> seems to be no guarantee that i can then use python to locate that >>> file in the filesystem. >> >> Exactly. >> >> In your example, it's simply not possible to determine the file's >> absolute path within the filesystem given the relative path you >> provided. >> >> You requested something that wasn't possible. ?It failed. ?What do you >> think should have happened? > > path = '../abc.txt' > > os.path.realpath(path) -> "OSError: [Errno 2] No such file or directory" > > therefore: > > open(path) -> "IOError: [Errno 2] No such file or directory" > > i think that if the first of these seemingly "impossible" requests fails, it > is reasonable to expect that the second one also fails. but the second one > (sometimes) doesn't. > > i think they should always either both succeed, or both fail. Well, that's Unix and Worse-is-Better[1] for ya. Inelegant theoretically, but probably makes some bit of the OS's job slightly easier and is usually good enough in practice. Pragmatism is a bitch sometimes. :-) Cheers, Chris -- [1]: http://en.wikipedia.org/wiki/Worse_is_better http://blog.rebertia.com From bazwal at ftml.net Mon May 3 14:10:53 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 19:10:53 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> Message-ID: <4BDF11AD.2060009@ftml.net> On 03/05/10 19:05, Chris Rebert wrote: > On Mon, May 3, 2010 at 10:45 AM, Baz Walter wrote: >> On 03/05/10 18:12, Grant Edwards wrote: >>> On 2010-05-03, Baz Walter wrote: >>>>> Sort of. The file in question _has_ a full path, you just can't tell >>>>> what it is based on the path you used to open it. >>>> >>>> yes, that's exactly what i was trying to demonstrate in my OP. i can >>>> use python to open a file; but under certain circumstances, there >>>> seems to be no guarantee that i can then use python to locate that >>>> file in the filesystem. >>> >>> Exactly. >>> >>> In your example, it's simply not possible to determine the file's >>> absolute path within the filesystem given the relative path you >>> provided. >>> >>> You requested something that wasn't possible. It failed. What do you >>> think should have happened? >> >> path = '../abc.txt' >> >> os.path.realpath(path) -> "OSError: [Errno 2] No such file or directory" >> >> therefore: >> >> open(path) -> "IOError: [Errno 2] No such file or directory" >> >> i think that if the first of these seemingly "impossible" requests fails, it >> is reasonable to expect that the second one also fails. but the second one >> (sometimes) doesn't. >> >> i think they should always either both succeed, or both fail. > > Well, that's Unix and Worse-is-Better[1] for ya. Inelegant > theoretically, but probably makes some bit of the OS's job slightly > easier and is usually good enough in practice. Pragmatism is a bitch > sometimes. :-) yeah, i probably should have added "in an ideal world" or something :) From invalid at invalid.invalid Mon May 3 14:12:10 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 18:12:10 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: >> You requested something that wasn't possible. It failed. What do >> you think should have happened? > > path = '../abc.txt' > > os.path.realpath(path) -> "OSError: [Errno 2] No such file or directory" > > therefore: > > open(path) -> "IOError: [Errno 2] No such file or directory" > > i think that if the first of these seemingly "impossible" requests > fails, it is reasonable to expect that the second one also fails. but > the second one (sometimes) doesn't. Because the second one isn't impossible in the case you posted. > i think they should always either both succeed, or both fail. That's not how Unix filesystems work. Are you saying that Python should add code to it's open() builtin which calls realpath() and then refuses to open files for which realpath() fails? Even though the user provided a legal and openable path? -- Grant Edwards grant.b.edwards Yow! Did I say I was at a sardine? Or a bus??? gmail.com From invalid at invalid.invalid Mon May 3 14:14:47 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 3 May 2010 18:14:47 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> Message-ID: On 2010-05-03, Chris Rebert wrote: >> open(path) -> "IOError: [Errno 2] No such file or directory" >> >> i think that if the first of these seemingly "impossible" requests fails, it >> is reasonable to expect that the second one also fails. but the second one >> (sometimes) doesn't. >> >> i think they should always either both succeed, or both fail. > > Well, that's Unix and Worse-is-Better[1] for ya. Inelegant > theoretically, I don't see how it's inelegant at all. Perhaps it's counter-intuitive if you don't understand how a Unix filesystem works, but the underlying filesystem model is very simple, regular, and elegant. > but probably makes some bit of the OS's job slightly easier and is > usually good enough in practice. Pragmatism is a bitch sometimes. :-) -- Grant Edwards grant.b.edwards Yow! ... I'm IMAGINING a at sensuous GIRAFFE, CAVORTING gmail.com in the BACK ROOM of a KOSHER DELI -- From andre.roberge at gmail.com Mon May 3 14:23:00 2010 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 3 May 2010 11:23:00 -0700 (PDT) Subject: Teaching Programming References: Message-ID: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> To Samuel Williams: (and other interested ;-) If you want to consider Python in education, I would encourage you have a look at http://www.python.org/community/sigs/current/edu-sig/ I think you will find that there are quite a few resources available - perhaps more than you are aware of. And, I don't think that because "some people do not like the indentation strategy" is a valid reason not to consider that Python's syntax is concise and simple. Actually, I would almost argue for the contrary. Indentation indicate programming structure/logic very clearly, without the need for arbitrary keywords and other punctuation symbols. There are very few keywords in the language. You indicate that Python programs are readable. They are also known to be short (much shorter than some other languages). Andr? From a_jtim at bellsouth.net Mon May 3 15:09:28 2010 From: a_jtim at bellsouth.net (Tim Arnold) Date: Mon, 3 May 2010 12:09:28 -0700 (PDT) Subject: design question Message-ID: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> This is a question about system design I guess. I have a django website that allows users to change/view configuration details for documentation builds. The database is very small. The reason I'm using a database in the first place is to make it easy for users to change the configuration of their builds. Django makes that easy and I can go on to other problems, like actually building the documentation. During a build, I query the configuration database at different times to get the configuration I need, which results in several calls to the database at different points of the build process. It doesn't feel right that I'm making these calls at different times. I *could* make a single big call at the beginning of the build, basically serializing all the config data I could need into a dictionary or maybe a json structure. And just pass that structure around as needed during the build, with no more database calls needed. These builds take from a few minutes to an hour or so, with the time spent making db calls almost insignificant. So if time isn't a problem, am I wringing my hands over something that really doesn't matter much? I guess it just doesn't feel like the right thing to me. thanks, --Tim From tomf.sessile at gmail.com Mon May 3 15:24:33 2010 From: tomf.sessile at gmail.com (TomF) Date: Mon, 3 May 2010 12:24:33 -0700 Subject: Django as exemplary design Message-ID: <2010050312243328275-tomfsessile@gmailcom> I'm interested in improving my python design by studying a large, well-designed codebase. Someone (not a python programmer) suggested Django. I realize that Django is popular, but can someone comment on whether its code is well-designed and worth studying? Thanks, -Tom From gandalf at shopzeus.com Mon May 3 15:28:39 2010 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 03 May 2010 21:28:39 +0200 Subject: duplicate temporary file? Message-ID: <4BDF23E7.8090505@shopzeus.com> I try to write an iterator class: class FileIterator(object): def __init__(self,file_object): self.fin = file_object # other initialization code here ... def __iter__(self): return self def next(self): # special code that reads from the file and converts to Pythonic data... This iterator I want to use with regular binary file objects. My requirement is to be able to create many iterators for the same file object, and use them from many threads - which is not straightforward. Of course I do not want to save file positions in the iterators, use locking on the file, and call seek() every time I need to read from the file. Instead of that, I try to re-open the file for each iteator. The trivial way to do it is: class FileIterator(object): def __init__(self,file_object): self.fin = open(file_object.name,"rb") self.fin.seek(file_object.tell()) ... However, it won't work for temporary files. Temporary files are just file-like objects, and their name is ''. I guess I could open a temporary file with os.open, and then use os.dup, but that is low level stuff. Then I have to use os.* methods, and the file object won't be iterable. tempfile.NamedTempFile is not better, because it cannot be reopened under Windows. So the question is, how do I create my iterator so that: * under Windows and Unix * many iterators can be used for the same underlying file, from many threads * with a normal binary file * and also with temporary files A workaround would be to create a temporary directory, and then create real files inside the temporary directory. If there is no better way to do it, I'll do that. Thanks Laszlo -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Mon May 3 15:43:00 2010 From: lists at cheimes.de (Christian Heimes) Date: Mon, 03 May 2010 21:43:00 +0200 Subject: duplicate temporary file? In-Reply-To: <4BDF23E7.8090505@shopzeus.com> References: <4BDF23E7.8090505@shopzeus.com> Message-ID: Laszlo Nagy wrote: > However, it won't work for temporary files. Temporary files are just > file-like objects, and their name is ''. I guess I could open a > temporary file with os.open, and then use os.dup, but that is low level > stuff. Then I have to use os.* methods, and the file object won't be > iterable. tempfile.NamedTempFile is not better, because it cannot be > reopened under Windows. On POSIX OSes like Linux a temporary file *is* a real file. It just doesn't have a name on the file system anymore. The concept is called an anonymous file. Python creates the file in the tmp directory and unlinks the name. The file still needs resources on the file system but you can "see" it. The /proc/PID/fd/ directory will show the temporary files. In order to copy the file handler you have to os.dup() the file descriptor (file_object.fileno()) and os.fdopen() it to get a file object. The Python documentation and the man pages dup(2), fileno(3) and fopen(3) will give you more information. Christian From mail at timgolden.me.uk Mon May 3 16:02:36 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 03 May 2010 21:02:36 +0100 Subject: win32 - catch events(wmi?) In-Reply-To: <201005031302.31772.richard.lamboj@bilcom.at> References: <201005031302.31772.richard.lamboj@bilcom.at> Message-ID: <4BDF2BDC.7020805@timgolden.me.uk> On 03/05/2010 12:02 PM, Richard Lamboj wrote: > i want catch the following events: > - registry has chanced > - file has chanced > - outgoing network connection > - programm start > > and i want to be able to allow, or deny this "requests". Wow. That's quite a list. To do what you want in general terms, you're into driver-level code which you're really not going to be able to do with Python. Windows does provide certain hooks and events but they're relatively limited. And the final requirement of being able to allow or deny requests is basically what the OS does via security, so to do it yourself would be quite a large task, methinks. In principle, you can use WMI events to track some of the things you've listed. The only one I'd really recommend is "program[m] start" for which you can see an related example here: http://timgolden.me.uk/python/wmi/cookbook.html#run-notepad-wait-until-it-s-closed-and-then-show-its-text Even there, WMI is polling on your behalf and if programs are spawning fast enough you'll miss one or more events. File monitoring *can* be done with the same sort of technique from within WMI, but don't: it will bring your disk to its knees. Instead, use the file monitoring APIs, such as: http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges I'm not aware of any technique for monitoring registry use, altho' a scan of sysinternals (or its ms-owned replacement) might yield something. And I'm not sure exactly what you mean by "outgoing network connection": that's really what the Windows firewall is there for. The firewall does have a WMI interface, although at this moment I can't remember where it is, which would enable you to set some things up, but I don't believe it provides an event/callback mechanism. Might be worth Googling to see if I'm wrong. And in all these cases, I'm really only talking about monitoring usage: you can terminate a process once it's open; you can delete a file once it's created; you can (possibly) nobble a socket connection once it's been made, but anything else and you're doing the Operating System's job for it. TJG From pavlovevidence at gmail.com Mon May 3 16:13:42 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 May 2010 13:13:42 -0700 (PDT) Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <5e748866-3ff5-43f7-bdca-08de1a0a534f@e35g2000yqm.googlegroups.com> On May 3, 12:24?pm, TomF wrote: > I'm interested in improving my python design by studying a large, > well-designed codebase. ?Someone (not a python programmer) suggested > Django. ?I realize that Django is popular, but can someone comment on > whether its code is well-designed and worth studying? I once delved into django because I wanted to use a couple of the administrative tools for non-web tasks, and found it to be disappointingly ad hoc. It it makes some assumptions about file locations and module names (unnecessarily, IMO). It works well as long as someone sticks to the rigid conventions, but can't cope well with deviances. Therefore I'd call its codebase less than exemplary. As a tool it's quite good (as long as you can stick to the prescribed layout) but that's a different question. Carl Banks From rouslank at msn.com Mon May 3 16:44:02 2010 From: rouslank at msn.com (Rouslan Korneychuk) Date: Mon, 03 May 2010 16:44:02 -0400 Subject: new extension generator for C++ Message-ID: Hi, I'm new here. I'm working on a program that exposes C++ declarations to Python and I was wondering if there is any interest in it. It's a hobby project. I was originally using Boost.Python on another project but found a couple of things I didn't like. Eg: you can't really have private constructors. If you want a Python object created, you either have to expose the constructor in Python, or create an instance of the object somewhere else in memory, and have it either copied to the PyObject or have the PyObject hold a reference to it. I was working on a rudimentary 3D game engine that was a Python extension. It was important to avoid copying potentially huge amounts of data, but to have almost every PyObject just be a pointer to another object (and the object already is just a few or even one pointer) seemed like an pointless compromise, considering that I was writing code that was specifically designed to be a Python extension (There was also another issue I came across but don't remember now). So I looked for other solutions and noticed that Py++ (which simply generates Boost.Python code for you) was based on a seperate program called GCCXML. I figured I could use GCCXML and generate code however I wanted. So I did. My program generates human-readable code (it even uses proper indentation). The program still has a lot of work to be done on it, but it can already generate working Python extensions. It takes an input file like this: module doc string class doc string You can probably figure out what the resulting code does. The goal is to generate code that is as close to hand-written code as possible. It even forgoes using PyArg_ParseTupleAndKeywords and has the argument checks hard-wired. It also generates a header file that contains a PyObject implementation of MyClass called obj_AClass, with every constructor fowarded and with the new and delete operators overloaded to play nice with Python's memory handler: ... extern PyTypeObject obj_AClassType; struct obj_AClass { PyObject_HEAD MyClass base; bool initialized; void *operator new(size_t s) { void *ptr = PyMem_Malloc(s); if(!ptr) throw std::bad_alloc(); return ptr; } void operator delete(void *ptr) { PyMem_Free(ptr); } obj_AClass(MyClass const & _0) : base(_0) { PyObject_Init(reinterpret_cast(this),&obj_AClassType); initialized = true; } obj_AClass(unsigned int _0) : base(_0) { PyObject_Init(reinterpret_cast(this),&obj_AClassType); initialized = true; } }; ... If you want to expose one overload of a constructor or function but not the others, you can add overload="list,of,args" to or . Default values for arguments are handled automatically. When handling overloaded functions, it checks the types of the arguments to pick the best overload, taking into consideration polymorphism and the fact that basic types like ints can be converted from one-another. It will automatically detect if two overloads match to the same set of Python arguments (eg: void func(float) vs void func(double)). The only issue is it will not use keyword arguments for overloaded functions (I don't know if that can even be done reliably *and* efficiently. I would need to give it more thought). If there is enough interest I can put this project up on SourceForge or Google Code. From see at sig.for.address Mon May 3 16:49:02 2010 From: see at sig.for.address (Victor Eijkhout) Date: Mon, 3 May 2010 15:49:02 -0500 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: <1jhxakp.1xj5u9nd6k7x7N%see@sig.for.address> Jerry Hill wrote: > >>> from __future__ import division > >>> long1/long2 > 0.5 Beautiful. Thanks so much guys. Victor. -- Victor Eijkhout -- eijkhout at tacc utexas edu From realvrz at aol.com Mon May 3 16:49:14 2010 From: realvrz at aol.com (Country Boy) Date: Mon, 3 May 2010 13:49:14 -0700 (PDT) Subject: PyQt Ram Usage Message-ID: <023dd1f9-7a9c-4f46-a6a6-9821bc7e6de0@b7g2000yqk.googlegroups.com> Hi, I am new to Python (and programming so pardon my ignorance) I have a small PyQt program that lives in windows system tray. I am using Suds & ElemetTree to do webservices call and parse XML. I have a QTimer that runs every 30 seconds and fetches the updated data from the server. Finally, the python script is "frozen" into exe using CX_FREEZE. When I run the exe, it starts with 18MB (which i think i high for an app that just fetches info from webserver and creates a menu full of web url shortcuts, but thats besides the point). After every 30 seconds (as my QTimer timeout()), my RAM usage goes up by 400KB. So after an hour or two of running the application almost uses ~60MB or more, which is ridiculous. I think my application has some memory leaks and I think every time I create an instance of the WebService class (its a QThread that fetches information using WSDL) the RAM goes up but doesn't get released once Class's work is done. Can somebody pls direct me into the things that I should be looking into to troubleshooting this issue... I am running my application on Windows Embedded thin clients so its really important that my application's memory footprint is low. Update: I tried del and it decreased the amount of RAM overall, but the application still starts with 20MB and then goes unto 40MB. From david at boddie.org.uk Mon May 3 17:53:08 2010 From: david at boddie.org.uk (David Boddie) Date: Mon, 03 May 2010 23:53:08 +0200 Subject: PyQt Ram Usage References: <023dd1f9-7a9c-4f46-a6a6-9821bc7e6de0@b7g2000yqk.googlegroups.com> Message-ID: On Monday 03 May 2010 22:49, Country Boy wrote: > I am new to Python (and programming so pardon my ignorance) > I have a small PyQt program that lives in windows system tray. I am > using Suds & ElemetTree to do webservices call and parse XML. > I have a QTimer that runs every 30 seconds and fetches the updated > data from the server. > Finally, the python script is "frozen" into exe using CX_FREEZE. > When I run the exe, it starts with 18MB (which i think i high for an > app that just fetches info from webserver and creates a menu full of > web url shortcuts, but thats besides the point). It's the price you pay for features. There are ways to cut out features you don't want if you're prepared to use a specialised version of Qt. > After every 30 seconds (as my QTimer timeout()), my RAM usage goes up > by 400KB. So after an hour or two of running the application almost > uses ~60MB or more, which is ridiculous. > I think my application has some memory leaks and I think every time I > create an instance of the WebService class (its a QThread that fetches > information using WSDL) the RAM goes up but doesn't get released once > Class's work is done. Can somebody pls direct me into the things that > I should be looking into to troubleshooting this issue... Qt has its own way of managing memory that usually plays well with Python's own memory management, but there are ways to accidentally create objects that will stay alive until the application exits. In particular, beware of creating objects with a parent QObject if you really want to manage them from Python because Qt will keep the underlying C++ object around, even if you delete the object in Python. This might not be the reason for the memory usage you see, but it's one thing to look at. You might also need to show us some code if the problem turns out to be more complicated than this. David From bazwal at ftml.net Mon May 3 17:57:41 2010 From: bazwal at ftml.net (Baz Walter) Date: Mon, 03 May 2010 22:57:41 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BDF46D5.1040501@ftml.net> On 03/05/10 19:12, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: > >>> You requested something that wasn't possible. It failed. What do >>> you think should have happened? >> >> path = '../abc.txt' >> >> os.path.realpath(path) -> "OSError: [Errno 2] No such file or directory" >> >> therefore: >> >> open(path) -> "IOError: [Errno 2] No such file or directory" >> >> i think that if the first of these seemingly "impossible" requests >> fails, it is reasonable to expect that the second one also fails. but >> the second one (sometimes) doesn't. > > Because the second one isn't impossible in the case you posted. > >> i think they should always either both succeed, or both fail. > > That's not how Unix filesystems work. > > Are you saying that Python should add code to it's open() builtin > which calls realpath() and then refuses to open files for which > realpath() fails? my original question was really about *how* python does the "seemingly impossible". i had hoped there might be a way to augment realpath so that it would always work for any path which is openable. but apparently that is not possible for unix filesystems. > Even though the user provided a legal and openable path? that sounds like an operational definition to me: what's the difference between "legal" and "openable"? From g.rodola at gmail.com Mon May 3 18:53:59 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Tue, 4 May 2010 00:53:59 +0200 Subject: win32 - catch events(wmi?) In-Reply-To: <4BDF2BDC.7020805@timgolden.me.uk> References: <201005031302.31772.richard.lamboj@bilcom.at> <4BDF2BDC.7020805@timgolden.me.uk> Message-ID: Just out of curiosity, is WMI able to list the TCP and UDP connections opened by a process or by the OS? We'll have to do this for psutil (http://code.google.com/p/psutil) and we guess it's not gonna be easy. --- Giampaolo http://code.google.com/p/psutil http://code.google.com/p/pyftpdlib 2010/5/3 Tim Golden : > On 03/05/2010 12:02 PM, Richard Lamboj wrote: >> >> i want catch the following events: >> ?- registry has chanced >> ?- file has chanced >> ?- outgoing network connection >> ?- programm start >> >> and i want to be able to allow, or deny this "requests". > > Wow. That's quite a list. To do what you want in general > terms, you're into driver-level code which you're really > not going to be able to do with Python. Windows does > provide certain hooks and events but they're relatively > limited. And the final requirement of being able to allow > or deny requests is basically what the OS does via security, > so to do it yourself would be quite a large task, methinks. > > In principle, you can use WMI events to track some of > the things you've listed. The only one I'd really recommend > is "program[m] start" for which you can see an related example > here: > > ?http://timgolden.me.uk/python/wmi/cookbook.html#run-notepad-wait-until-it-s-closed-and-then-show-its-text > > Even there, WMI is polling on your behalf and if programs are > spawning fast enough you'll miss one or more events. > > File monitoring *can* be done with the same sort of technique > from within WMI, but don't: it will bring your disk to its > knees. Instead, use the file monitoring APIs, such as: > > ?http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges > > I'm not aware of any technique for monitoring registry use, > altho' a scan of sysinternals (or its ms-owned replacement) > might yield something. And I'm not sure exactly what you > mean by "outgoing network connection": that's really what the > Windows firewall is there for. The firewall does have a WMI > interface, although at this moment I can't remember where it > is, which would enable you to set some things up, but I don't > believe it provides an event/callback mechanism. Might be worth > Googling to see if I'm wrong. > > And in all these cases, I'm really only talking about monitoring > usage: you can terminate a process once it's open; you can delete > a file once it's created; you can (possibly) nobble a socket > connection once it's been made, but anything else and you're > doing the Operating System's job for it. > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > From kevin.p.dwyer at gmail.com Mon May 3 19:29:18 2010 From: kevin.p.dwyer at gmail.com (Kev) Date: Mon, 3 May 2010 23:29:18 +0000 (UTC) Subject: design question References: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> Message-ID: Tim Arnold wrote: > This is a question about system design I guess. I have a django > website that allows users to change/view configuration details for > documentation builds. The database is very small. The reason I'm using > a database in the first place is to make it easy for users to change > the configuration of their builds. Django makes that easy and I can go > on to other problems, like actually building the documentation. > > During a build, I query the configuration database at different times > to get the configuration I need, which results in several calls to the > database at different points of the build process. > > It doesn't feel right that I'm making these calls at different times. > I *could* make a single big call at the beginning of the build, > basically serializing all the config data I could need into a > dictionary or maybe a json structure. And just pass that structure > around as needed during the build, with no more database calls needed. > > These builds take from a few minutes to an hour or so, with the time > spent making db calls almost insignificant. So if time isn't a > problem, am I wringing my hands over something that really doesn't > matter much? I guess it just doesn't feel like the right thing to me. > > thanks, > --Tim Hello Tim, Given the times that you've quoted for the documentation builds, a few microseconds here and there for database queries doesn't really matter. The Django docs, as it happens, look favourably on doing one query up front, (http://docs.djangoproject.com/en/1.1/topics/db/optimization/#topics-db-optimization), but they also recommend profiling first, which would presumably highlight the insignificance of your queries compared with the duration of the builds. So I think the upshot is don't worry about it, or if you must, accept that you're worrying more about aesthetics than anything else (not that aesthetics aren't important). Cheers, Kev From lie.1296 at gmail.com Mon May 3 19:39:20 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 04 May 2010 09:39:20 +1000 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4bdf5f09$1@dnews.tpgi.com.au> On 05/04/10 07:57, Baz Walter wrote: > On 03/05/10 19:12, Grant Edwards wrote: >> On 2010-05-03, Baz Walter wrote: >> >>>> You requested something that wasn't possible. It failed. What do >>>> you think should have happened? >>> >>> path = '../abc.txt' >>> >>> os.path.realpath(path) -> "OSError: [Errno 2] No such file or >>> directory" >>> >>> therefore: >>> >>> open(path) -> "IOError: [Errno 2] No such file or directory" >>> >>> i think that if the first of these seemingly "impossible" requests >>> fails, it is reasonable to expect that the second one also fails. but >>> the second one (sometimes) doesn't. >> >> Because the second one isn't impossible in the case you posted. >> >>> i think they should always either both succeed, or both fail. >> >> That's not how Unix filesystems work. >> >> Are you saying that Python should add code to it's open() builtin >> which calls realpath() and then refuses to open files for which >> realpath() fails? > > my original question was really about *how* python does the "seemingly > impossible". i had hoped there might be a way to augment realpath so > that it would always work for any path which is openable. but apparently > that is not possible for unix filesystems. It's the OS that does the "seemingly impossible" things. Python only makes the relevant system call with the string you've given, and leaves the rest of the magic of resolving the real file to open, opening the filename, moving the harddrive head, etc to OS kernel. If OS kernel dictates that you can open a file that have no actual path; then Python will do so. >> Even though the user provided a legal and openable path? > > that sounds like an operational definition to me: what's the difference > between "legal" and "openable"? From cjw at ncf.ca Mon May 3 19:46:19 2010 From: cjw at ncf.ca (cjw) Date: Mon, 03 May 2010 19:46:19 -0400 Subject: Teaching Programming In-Reply-To: References: Message-ID: On 03-May-10 09:38 AM, Samuel Williams wrote: > Dear Chris, > > Thanks for reading further into the site. > > Yes, it is complicated to provide a good comparison. It isn't always accurate and I welcome feedback. > > Please be aware that orange does not mean problem - it simply means take note that there may be potential issues that you need to consider. It is highly subjective, so I appreciate your feedback. The red dot is when there is definitely an issue that needs to be taken into consideration. It isn't "Okay, Warning, Error" because it isn't possible to make this kind of judgement without being omnipotent. > > There are several reason why I decided to rate the syntax as not being simple. > 1) Indentation model is not appreciated by everyone - I think its a good model, but feedback from some other people has been that they don't like it. Also, I've had perfectly good Python code fall to bits after editing in a different editor. I'm not saying that this was the fault of Python, but in an educational context it might be a problem, since people are fairly limited and don't understand these issues. Nobody likes indentation at first, it is different. There is no begin/end and not {}. That feeling might last for an hour. People welcome the absence of clutter. Indentation makes it easier to read and understand the code. Coding errors are easily found with a good IDE, such as PyScripter Colin W. > 2) I don't think that the list comprehension integrates well with the rest of the language. It is an additional syntactic construct which seems to be separate from the rest of the language. It would be nice if list comprehension was implemented in a way that was more general, using a general closure syntax for example. This is just my opinion, and it might not be valid (I don't research this point very heavily). > > I appreciate that in general the Python syntax is good and concise. It is hard. Some teacher might want to consider these issues more carefully. Do you think I should change that spot to green? I don't have a problem with doing that, as long as it makes sense. > > Thanks for providing the syntax images, they are very interesting. > > With regards to Perl, yes, this is probably something I need to investigate further. It is not always easy to do a comparison of this nature. From my experience, Perl generally seems to have a robust object model that is consistently implemented (even if the syntax is pretty wonky at times). However, in a sense, it is no better or worse than Python implementation... so why is it green dot? Do you think I should change Perl to orange or Python to green. > > The main criteria is whether it is going to be an issue in an educational context - this means, for new programmers, or those who might make error easily (syntax, semantic), etc. > > Also, I wonder if Visual Basic needs to be reevaluated on this criteria too. I guess what is important is the relative importance. > > I will bring this issue up on the Perl mailing list in order to get advice. > > Would you recommend changing Perl to orange? > > Thanks for your well thought out response, it is very helpful. > > Kind regards, > Samuel > > On 4/05/2010, at 1:06 AM, Chris Rebert wrote: > >> On Mon, May 3, 2010 at 5:29 AM, Chris Rebert wrote: >>> On Mon, May 3, 2010 at 5:05 AM, Samuel Williams >>> wrote: >>>> Dear Friends, >>>> >>>> I'm looking for some help from the Python community. I hope this is the >>>> right place to ask for information. >>>> >>>> I'm putting together a website aimed at high school students and teachers, >>>> and would like to make sure the following page is as good as possible: >>>> http://programming.dojo.net.nz/languages/python/index >>>> In particular, "Why would I learn this language?" section needs to have a >>>> few paragraphs. I don't use Python predominantly so I hoped that you could >>>> provide the main reasons why Python is a language someone would want to >>>> learn about. >> >>> - A very clean syntax and elegant design, compared to other languages >> >> Also, I take issue with your classifying Python as orange with regard >> to "Is the general syntax simple and concise?" on >> http://programming.dojo.net.nz/resources/programming-language-comparison/index >> Python's syntax is at least as simple, if not simpler, than Ruby's, >> which you rate as green. Ruby may be /slightly/ more concise than >> Python in certain cases due to its Perl influences, but those >> instances of specialized syntax also make it more complex. >> To wit, I refer you to >> http://webcache.googleusercontent.com/search?q=cache:dyugd_KlqvcJ:blog.nicksieger.com/articles/2006/10/27/visualization-of-rubys-grammar+ruby+grammar+visualization&cd=1&hl=en&ct=clnk&gl=us >> Note the complexity of the graph for Ruby's grammar. By comparison, >> here is the same graph for Python (generated from a file linked to in >> the post's comment thread): >> http://rebertia.com/images/python_grammar_graph.png >> (Disclaimer: Neither of the graphs are current.) >> >> Additionally, you rate Python orange but Perl green for "Does the >> language provide a useful and consistent set of object oriented >> constructs?". Could you explain your reasoning for this? While neither >> Python nor Perl have the level of object-oriented purity of Ruby or >> Smalltalk, my understanding is that short of using CPAN libraries for >> Perl or dealing in Perl 6, Perl and Python have a substantially >> similar object model, so I don't how Python could rate below Perl in >> this area. >> >> Cheers, >> Chris >> -- >> http://blog.rebertia.com > From kalin at el.net Mon May 3 19:53:11 2010 From: kalin at el.net (kalin m) Date: Mon, 03 May 2010 19:53:11 -0400 Subject: msg_footer Message-ID: <4BDF61E7.2030808@el.net> is there a variable for the member's email address in the msg_footer? the one the message is being sent to? thanks.... From C.Sanders at DeleteThis.Bom.GOV.AU Mon May 3 20:16:39 2010 From: C.Sanders at DeleteThis.Bom.GOV.AU (Charles) Date: Tue, 4 May 2010 10:16:39 +1000 Subject: [OT] strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> Message-ID: <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> "Grant Edwards" wrote in message news:hrn3qn$nh0$2 at reader1.panix.com... > On 2010-05-03, Chris Rebert wrote: > >>> open(path) -> "IOError: [Errno 2] No such file or directory" >>> >>> i think that if the first of these seemingly "impossible" requests >>> fails, it >>> is reasonable to expect that the second one also fails. but the second >>> one >>> (sometimes) doesn't. >>> >>> i think they should always either both succeed, or both fail. >> >> Well, that's Unix and Worse-is-Better[1] for ya. Inelegant >> theoretically, > > I don't see how it's inelegant at all. Perhaps it's counter-intuitive > if you don't understand how a Unix filesystem works, but the > underlying filesystem model is very simple, regular, and elegant. > >> but probably makes some bit of the OS's job slightly easier and is >> usually good enough in practice. Pragmatism is a bitch sometimes. :-) > I agree that the Unix file system is quite elegant, but can be counter-intuitive for people who are used to the "one file, one name" paradigm. Simplifying, if I recall correctly from Unix courses in the early 1980's, Unix knows a file by the triple (device major number, device minor number, inode number). Ignoring mount points, directories are simply files that contain a map from names (components of a path) to inode numbers, assumed to be on the same device as the directory. There can be many references to the same inode ("hard" links). The OS keeps track of how many references there are to a file and deletes files when they no longer have any references. Opening a file, or using a directory as the current working directory, count as references. Removing a file or directory removes the reference in the file system, but leaves the in memory references for open files or current directories. Thus, removing a file (or directory) while one or more processes have an open file descriptor referring to it (or have it as their current directory) does not result in it being deleted. The in-memory references keep it alive, but it is no longer accessible to other processes as it no longer has a name in the file system. It is (or used to be) a common unix idiom to create and open a temporary file (or create a temporary directory and cd to it), and then delete it. This ensured that no other processes could then access the file/directory (it no longer had a name in the file system), and that the file (directory) will usually be deleted by the OS when the process exits, as the only reference to the file/directory is the open file descriptor/current directory in the process, which disappears when the process exits. This applies even if the normal end of process cleanup does not happen because of a (Unix) kill -9 or other major problem, and usually applies even in case of a system crash. In the OP's case, references to the directory have been removed from the file system, but his process still has the current working directory reference to it, so it has not actually been deleted. When he opens "../abc.txt", the OS searches the current directory for ".." and finds the inode for /home/baz/tmp, then searches that directory (/home/baz/tmp) for abc.txt and finds it. Note that, on unix, hard links and possible duplicate NFS mounts make it impossible to guarantee a unique "name" for a file. Even on windows, multiple CIFS mounts can result in in being impossible to guarantee a unique name. Charles From alfps at start.no Mon May 3 20:21:36 2010 From: alfps at start.no (Alf P. Steinbach) Date: Tue, 04 May 2010 02:21:36 +0200 Subject: design question In-Reply-To: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> References: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> Message-ID: * Tim Arnold: > This is a question about system design I guess. I have a django > website that allows users to change/view configuration details for > documentation builds. The database is very small. The reason I'm using > a database in the first place is to make it easy for users to change > the configuration of their builds. Django makes that easy and I can go > on to other problems, like actually building the documentation. > > During a build, I query the configuration database at different times > to get the configuration I need, which results in several calls to the > database at different points of the build process. > > It doesn't feel right that I'm making these calls at different times. > I *could* make a single big call at the beginning of the build, > basically serializing all the config data I could need into a > dictionary or maybe a json structure. And just pass that structure > around as needed during the build, with no more database calls needed. > > These builds take from a few minutes to an hour or so, with the time > spent making db calls almost insignificant. So if time isn't a > problem, am I wringing my hands over something that really doesn't > matter much? I guess it just doesn't feel like the right thing to me. Re efficiency it seems to be a complete non-issue, but correctness is much more important: is there any way that the config details can be (inadvertently) changed while the build is going on? If so then it might be a good idea to read all relevant info up front (holding a lock for hours seems ungood to me). Cheers & hth., - Alf From ben+python at benfinney.id.au Mon May 3 21:12:49 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 04 May 2010 11:12:49 +1000 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> Message-ID: <87d3xch3la.fsf@benfinney.id.au> Baz Walter writes: > On 03/05/10 18:41, Grant Edwards wrote: > > Firstly, a file may have any number of paths (including 0). > > yes, of course. i forgot about hard links Rather, you forgot that *every* entry that references a file is a hard link. To ask for a filesystem entry referencing the file contents *is* to ask for a hard link; and there can be zero or more of those. The case where there is exactly one of those for a given file is the special case, and should not be assumed. -- \ ?[Freedom of speech] isn't something somebody else gives you. | `\ That's something you give to yourself.? ?_Hocus Pocus_, Kurt | _o__) Vonnegut | Ben Finney From kalin at el.net Mon May 3 21:16:48 2010 From: kalin at el.net (kalin m) Date: Mon, 03 May 2010 21:16:48 -0400 Subject: msg_footer In-Reply-To: <4BDF61E7.2030808@el.net> References: <4BDF61E7.2030808@el.net> Message-ID: <4BDF7580.5060009@el.net> nevermind... i found it... kalin m wrote: > > is there a variable for the member's email address in the msg_footer? > the one the message is being sent to? > > thanks.... From cs at zip.com.au Mon May 3 21:36:58 2010 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 4 May 2010 11:36:58 +1000 Subject: strange interaction between open and cwd In-Reply-To: <4BDEDC73.1020301@ftml.net> References: <4BDEDC73.1020301@ftml.net> Message-ID: <20100504013658.GA25409@cskk.homeip.net> On 03May2010 15:23, Baz Walter wrote: | On 03/05/10 14:46, Peter Otten wrote: | >Baz Walter wrote: | > | >>attempting to remove the cwd would produce an error). but how can python | >>determine the parent directory of a directory that no longer exists? | > | >My tentative explanation would be that the directory, namely the inode, | >still exists -- only the entry for it in its parent directory is gone. | > | >So "one level up from here" is still a valid operation, but there is no | >longer a path in the file system associated with "here". | | so "here" must always be available somehow, even if getcwd() fails Well, yeah. Just like an open file handle on a file you have subsequently removed still exists. Remember that the directory tree is a digraph, and (historically at least, and probably for real in many filesystems) '.' and '..' are just pointers to "here" and "up". Your rmdir has detached the current directory from the one that was "up", but the "up" pointer still references the old parent. There's just no filesystem path that refers to your current directory any more (except '.'). Just like a detached object in python really. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Everything that can be invented has been invented. - Charles H. Duell, Commissioner, U.S. Office of Patents, 1899. From invalid at invalid.invalid Mon May 3 22:19:04 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 4 May 2010 02:19:04 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: On 2010-05-03, Baz Walter wrote: > On 03/05/10 19:12, Grant Edwards wrote: >>> i think they should always either both succeed, or both fail. >> >> That's not how Unix filesystems work. >> >> Are you saying that Python should add code to it's open() builtin >> which calls realpath() and then refuses to open files for which >> realpath() fails? > > my original question was really about *how* python does the > "seemingly impossible". i had hoped there might be a way to augment > realpath so that it would always work for any path which is openable. > but apparently that is not possible for unix filesystems. Exactly >> Even though the user provided a legal and openable path? > > that sounds like an operational definition to me: what's the > difference between "legal" and "openable"? Legal as in meets the syntactic requirements for a path (not sure if there really are any requirements other than it being a null-terminated string). Openable meaning that it denotes a path file that exists and for which the caller has read permissions on the file and execute premissions on the directories within the path. -- Grant From invalid at invalid.invalid Mon May 3 22:25:54 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 4 May 2010 02:25:54 +0000 (UTC) Subject: [OT] strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> Message-ID: On 2010-05-04, Charles wrote: >> I don't see how it's inelegant at all. Perhaps it's >> counter-intuitive if you don't understand how a Unix filesystem >> works, but the underlying filesystem model is very simple, regular, >> and elegant. >> >>> but probably makes some bit of the OS's job slightly easier and is >>> usually good enough in practice. Pragmatism is a bitch sometimes. :-) >> > > I agree that the Unix file system is quite elegant, but can be > counter-intuitive for people who are used to the "one file, one name" > paradigm. I guess I've been using Unix for too long (almost 30 years). I don't think I was consciously aware of a "one file, one name" paradigm. Is that a characteristic of Dos, Windows or Mac filesystems? > [...] > In the OP's case, references to the directory have been removed from > the file system, but his process still has the current working > directory reference to it, so it has not actually been deleted. When > he opens "../abc.txt", the OS searches the current directory for ".." > and finds the inode for /home/baz/tmp, then searches that directory > (/home/baz/tmp) for abc.txt and finds it. Exactly. I probably should have taken the time to explain that as well as you did. One forgets that there are a log of new Unix users who've never been taught how the filesystem works. -- Grant From invalid at invalid.invalid Mon May 3 22:36:47 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 4 May 2010 02:36:47 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEDC73.1020301@ftml.net> Message-ID: On 2010-05-04, Cameron Simpson wrote: > On 03May2010 15:23, Baz Walter wrote: >| so "here" must always be available somehow, even if getcwd() fails > > Well, yeah. Just like an open file handle on a file you have > subsequently removed still exists. Remember that the directory tree > is a digraph, and (historically at least, and probably for real in > many filesystems) '.' and '..' are just pointers to "here" and "up". > > Your rmdir has detached the current directory from the one that was > "up", but the "up" pointer still references the old parent. > > There's just no filesystem path that refers to your current directory > any more (except '.'). Just like a detached object in python really. Indeed. In fact, CPython uses a pointer/link and reference counting scheme that's pretty much identical to that used by Unix filesystems except that Python objects can form a generalized graph, and Unix filesystems are constrained to be a tree. Though once upon a time SunOS allowed you to create arbitrary graphs within a filesystem by allowing you to create hard links to directories. You had to be root, and you had to use some sort of override option on the command line (probably -f). If you knew enough to gracefully extract yourself from the situation, you probably wouldn't have done it in the first place. IOW, it wasn't something one did a second time. Still, at the time, it _seemed_ like a good way to share a directory of source code amongst multiple projects. I don't remember why symlinks wouldn't accomplish the task -- something to do with RCS... -- Grant From mwilson at the-wire.com Mon May 3 23:34:21 2010 From: mwilson at the-wire.com (Mel) Date: Mon, 03 May 2010 23:34:21 -0400 Subject: [OT] strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> Message-ID: Grant Edwards wrote: > I guess I've been using Unix for too long (almost 30 years). I don't > think I was consciously aware of a "one file, one name" paradigm. Is > that a characteristic of Dos, Windows or Mac filesystems? Older and simpler filesystems used to combine the naming with the space allocation. CP/M, and (IIRC) the GE/Honeywell mainframe systems I used to work with. MS-DOS FAT filesystems might have supported multi-names but refused to administer them before long filenames were implemented as special cases. I first ran into multi-names on Multics, where the Volume Table of Contents controlled disk space allocation and directories provided name- keyed access to the VTOC entries. Pretty much as Linux does now with directories and inodes. Mel. From cmpython at gmail.com Tue May 4 00:03:32 2010 From: cmpython at gmail.com (CM) Date: Mon, 3 May 2010 21:03:32 -0700 (PDT) Subject: Teaching Programming References: Message-ID: > Nobody likes indentation at first, it is different. ? For what it's worth, I didn't have a programming background, and I liked Python's indentation right from the start. I was used to thinking in terms of indentation from writing and word processing documents with subordinate sections, so I found it very natural (and already had a well-developed tab finger). On the other hand, curly braces always have struck me as visual "clutter". From nagle at animats.com Tue May 4 00:12:19 2010 From: nagle at animats.com (John Nagle) Date: Mon, 03 May 2010 21:12:19 -0700 Subject: HTTP server + SQLite? In-Reply-To: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> Message-ID: <4bdf993e$0$1669$742ec2ed@news.sonic.net> Gilles Ganault wrote: > Hello > > I'd like to build a prototype that will combine a web server as > front-end (it must support GZIPping data to the remote client when > there are a lot of data to return), and SQLite as back-end, call the > server from a VB.Net application, and see how well this works. I want > to see if performance is significantly lower than using a server that > uses a binary protocol. > > I'm no Python expert, so would appreciate any information on how to > combine a web server and SQLite into a single Python application. This > is just for a proof-of-concept, so it doesn't need to be > shipping-quality. > > Thank you for any hint. There's no reason you can't do that. Whether you want to is another issue. There are, after all, plenty of web servers out there. Also, SQLite really is a "lite" database. Although there's good read concurrency, multiple updates from multiple processes tend to result in sizable delays, since the locking is via file locks and wait/retry logic. John Nagle From robin1 at cnsp.com Tue May 4 01:00:08 2010 From: robin1 at cnsp.com (Robin) Date: Mon, 3 May 2010 22:00:08 -0700 (PDT) Subject: repeat tkinter Message-ID: <8739b635-18c6-40e6-82ac-7b0ca673774b@o11g2000yqj.googlegroups.com> How can I make a command within a tkinter application repeat itself over and over in intervals of a certain time. Thanks, -Robin From fred at bsdhost.net Tue May 4 01:01:49 2010 From: fred at bsdhost.net (Fred C) Date: Mon, 3 May 2010 22:01:49 -0700 Subject: print executed query In-Reply-To: <8E05B556-DB67-4B4C-B4B4-C34E12BE6E35@semanchuk.com> References: <9b2a7e6f-003d-474a-968f-0cdcede9ce5c@k41g2000yqb.googlegroups.com> <8E05B556-DB67-4B4C-B4B4-C34E12BE6E35@semanchuk.com> Message-ID: On Apr 29, 2010, at 9:49 AM, Philip Semanchuk wrote: > > On Apr 29, 2010, at 12:01 PM, someone wrote: > >> Hello! >> >> Is there a way to print a query for logging purpose as it was or will >> be sent to database, if I don't escape values of query by myself? >> >> cursor.execute(query, [id, somestring]) >> >> I could print query and values separate, but it would be great, if I >> could see how query is constructed and can the also copy it and >> execute in console. >> >> Im using psycopg2, btw > > > If you can fiddle with the Postgres server settings, the server has options for logging lots of things, including the queries it executes. > > > Hope this helps > Philip > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3676 bytes Desc: not available URL: From rickhg12hs at gmail.com Tue May 4 01:02:45 2010 From: rickhg12hs at gmail.com (rickhg12hs) Date: Mon, 3 May 2010 22:02:45 -0700 (PDT) Subject: Recursive functions not returning lists as expected Message-ID: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Would a kind soul explain something basic to a python noob? Why doesn't this function always return a list? def recur_trace(x,y): print x,y if not x: return y recur_trace(x[1:], y + [x[0]]) Here are a couple sample runs. >>> print(recur_trace([],[1,2,3])) [] [1,2,3] [1,2,3] So that worked okay and returned the list [1,2,3]. >>> print(recur_trace([9,8],[1,2,3])) [9,8] [1,2,3] [8] [1,2,3,9] [] [1,2,3,9,8] None No list is returned here. Why? [Using Python 2.6.2] From fred at bsdhost.net Tue May 4 01:02:47 2010 From: fred at bsdhost.net (Fred C) Date: Mon, 3 May 2010 22:02:47 -0700 Subject: print executed query In-Reply-To: <8E05B556-DB67-4B4C-B4B4-C34E12BE6E35@semanchuk.com> References: <9b2a7e6f-003d-474a-968f-0cdcede9ce5c@k41g2000yqb.googlegroups.com> <8E05B556-DB67-4B4C-B4B4-C34E12BE6E35@semanchuk.com> Message-ID: <5B1BDBA5-CB8B-4238-ADB4-506914DEB706@bsdhost.net> On Apr 29, 2010, at 9:49 AM, Philip Semanchuk wrote: > > On Apr 29, 2010, at 12:01 PM, someone wrote: > >> Hello! >> >> Is there a way to print a query for logging purpose as it was or will >> be sent to database, if I don't escape values of query by myself? >> >> cursor.execute(query, [id, somestring]) >> >> I could print query and values separate, but it would be great, if I >> could see how query is constructed and can the also copy it and >> execute in console. >> >> Im using psycopg2, btw > > > If you can fiddle with the Postgres server settings, the server has options for logging lots of things, including the queries it executes. > Yes you can fiddle like that: >>> cur.mogrify("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar')) "INSERT INTO test (num, data) VALUES (42, E'bar')" -fred- -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3676 bytes Desc: not available URL: From ideamonk at gmail.com Tue May 4 01:30:34 2010 From: ideamonk at gmail.com (Abhishek Mishra) Date: Tue, 4 May 2010 11:00:34 +0530 Subject: Recursive functions not returning lists as expected In-Reply-To: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: Perhaps you forgot a return, thats fundamental to recursion right - funciton returning itself to itself :) Here's a bit modification needed - def recur_trace(x,y): print x,y if not x: return y return recur_trace(x[1:], y + x[:1]) print ( recur_trace([],[1,2,3]) ) print print ( recur_trace([9,8],[1,2,3]) ) print print ( recur_trace([0],[1,2,3]) ) $ python poo.py [] [1, 2, 3] [1, 2, 3] [9, 8] [1, 2, 3] [8] [1, 2, 3, 9] [] [1, 2, 3, 9, 8] [1, 2, 3, 9, 8] [0] [1, 2, 3] [] [1, 2, 3, 0] [1, 2, 3, 0] On Tue, May 4, 2010 at 10:32 AM, rickhg12hs wrote: > Would a kind soul explain something basic to a python noob? > > Why doesn't this function always return a list? > > def recur_trace(x,y): > print x,y > if not x: > return y > recur_trace(x[1:], y + [x[0]]) > > Here are a couple sample runs. > > >>> print(recur_trace([],[1,2,3])) > [] [1,2,3] > [1,2,3] > > So that worked okay and returned the list [1,2,3]. > > >>> print(recur_trace([9,8],[1,2,3])) > [9,8] [1,2,3] > [8] [1,2,3,9] > [] [1,2,3,9,8] > None > > No list is returned here. Why? > [Using Python 2.6.2] > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From C.Sanders at DeleteThis.Bom.GOV.AU Tue May 4 01:32:18 2010 From: C.Sanders at DeleteThis.Bom.GOV.AU (Charles) Date: Tue, 4 May 2010 15:32:18 +1000 Subject: Recursive functions not returning lists as expected References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: <4bdfb164$0$45290$c30e37c6@exi-reader.telstra.net> "rickhg12hs" wrote in message news:2ff16113-4f79-4dcf-8310-35d2b91e89dc at o11g2000yqj.googlegroups.com... > Would a kind soul explain something basic to a python noob? > > Why doesn't this function always return a list? > > def recur_trace(x,y): > print x,y > if not x: > return y > recur_trace(x[1:], y + [x[0]]) > shouldn't it be return recur_trace(x[1:], y + [x[0]]) otherwise the recursive call returns nothing Charles From cs at zip.com.au Tue May 4 01:34:12 2010 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 4 May 2010 15:34:12 +1000 Subject: Recursive functions not returning lists as expected In-Reply-To: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: <20100504053412.GA27108@cskk.homeip.net> On 03May2010 22:02, rickhg12hs wrote: | Would a kind soul explain something basic to a python noob? | | Why doesn't this function always return a list? | | def recur_trace(x,y): | print x,y | if not x: | return y | recur_trace(x[1:], y + [x[0]]) You need: return recur_trace(x[1:], y + [x[0]]) Otherwise the function returns None. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ [...] every time you touch something, if your security systems rely on biometric ID, then you're essentially leaving your pin number on a post-it note. - Ben Goldacre, http://www.badscience.net//?p=585 From rickhg12hs at gmail.com Tue May 4 01:45:16 2010 From: rickhg12hs at gmail.com (rickhg12hs) Date: Mon, 3 May 2010 22:45:16 -0700 (PDT) Subject: Recursive functions not returning lists as expected References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: On May 4, 1:34?am, Cameron Simpson wrote: > On 03May2010 22:02, rickhg12hs wrote: > | Would a kind soul explain something basic to a python noob? > | > | Why doesn't this function always return a list? > | > | def recur_trace(x,y): > | ? print x,y > | ? if not x: > | ? ? return y > | ? recur_trace(x[1:], y + [x[0]]) > > You need: > ? ? return recur_trace(x[1:], y + [x[0]]) > > Otherwise the function returns None. Ah, an explicit "return" is required. Thanks! [To bad there's no tail recursion optimization.] 8-( From stefan_ml at behnel.de Tue May 4 01:51:07 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 07:51:07 +0200 Subject: new extension generator for C++ In-Reply-To: References: Message-ID: Rouslan Korneychuk, 03.05.2010 22:44: > So I looked for other solutions and noticed that Py++ (which simply > generates Boost.Python code for you) was based on a seperate program > called GCCXML. I figured I could use GCCXML and generate code however I > wanted. So I did. > > My program generates human-readable code (it even uses proper > indentation). The program still has a lot of work to be done on it, but > it can already generate working Python extensions. Last I heard, that was basically what PyBindGen does (and probably some other existing binding generators). You should take a look at them before investing too much time into a duplicated effort. Also, if you're interested in performance, you should take a look at Cython, which is an optimising compiler for (basically) Python code that can talk to C, C++ and Fortran code. It's been used a lot for writing performance critical library wrappers. Stefan From michele.simionato at gmail.com Tue May 4 01:57:07 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 3 May 2010 22:57:07 -0700 (PDT) Subject: Sphinx hosting Message-ID: Say you have a project with a lot of documentation in the form of Sphinx pages (for instance a book project). What is the the easiest way to publish it on the Web? I see that GitHub Pages allows you to publish static pages, but I would need to check in both the .rst sources and the .html output: it is not that annoying, but perhaps there is already some services out there publishing Sphinx pages directly. Do you know of any? Currently I am hosting my stuff on Google Code but I do not see an easy way to publish the documentation there. Any hint is appreciated. Michele Simionato From kse.listed.co1 at gmail.com Tue May 4 02:02:42 2010 From: kse.listed.co1 at gmail.com (Naeem) Date: Mon, 3 May 2010 23:02:42 -0700 (PDT) Subject: "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ Message-ID: <2b150fa6-3a2b-4693-b54f-80429166a25e@o14g2000yqb.googlegroups.com> "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "bollywood actress" bollywood actress blue film" "bollywood actress katrina kaif" "bollywood actress wallpapers" "bollywood actress kareena kapoor" "bollywood actress sexiest videos" "mallika sherawat" hhttp://e-bollywoodhungama.blogspot.com/ "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments "Sheena shahabadi" "KAREENA KAPOOR WITH VISIBLE BELLY DRESS HOW MUCH SHE IS PRETTY COMMENTS" "MANDIRA IN FASHION SHOW" "DIYA MIRZA" "PREETI BHUTANI" " NAMITHA THE FATTY CUTE INDIAN BOLLYWOOD STAR" "Shradha Sharma" "Shraddha sharma hot pictures wallpapers hot legs" "Shriya Saran" "Shriya Saran" "Sushmita Sen" "Vidya Balan" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "PRETTY INDIAN PAKISTANI GIRLS" "Navneet Kaur" "RANI" "RANI MUKHARJEE" "BOLLYWOOD ACTRESS" "BOLLYWOOD HUNGAMA" "bollywood actress" "bollywood masala" "bollywood sexiest movie clips" "bollywood movies" "bollywood songs" "bollywood wallpapers" bollywood news" Posted by Muhammad Ijaz at 6:51 AM 0 comments From paul.nospam at rudin.co.uk Tue May 4 02:04:24 2010 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Tue, 04 May 2010 07:04:24 +0100 Subject: Recursive functions not returning lists as expected References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: <874oio19uf.fsf@rudin.co.uk> rickhg12hs writes: > Would a kind soul explain something basic to a python noob? > > Why doesn't this function always return a list? > > def recur_trace(x,y): > print x,y > if not x: > return y > recur_trace(x[1:], y + [x[0]]) > > Here are a couple sample runs. > >>>> print(recur_trace([],[1,2,3])) > [] [1,2,3] > [1,2,3] > > So that worked okay and returned the list [1,2,3]. > >>>> print(recur_trace([9,8],[1,2,3])) > [9,8] [1,2,3] > [8] [1,2,3,9] > [] [1,2,3,9,8] > None > > No list is returned here. Why? > [Using Python 2.6.2] Without trying it out I'd guess you want a "return" in your last line. (If python falls out of a function without hitting an explicit return then None is returned by default.) From bryanjugglercryptographer at yahoo.com Tue May 4 02:07:08 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Mon, 3 May 2010 23:07:08 -0700 (PDT) Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> <4bdf993e$0$1669$742ec2ed@news.sonic.net> Message-ID: <11247616-b5da-4494-bf83-1d7416c8dbef@g5g2000pre.googlegroups.com> John Nagle wrote: > [...] SQLite really > is a "lite" database. ?Although there's good read concurrency, multiple > updates from multiple processes tend to result in sizable delays, since > the locking is via file locks and wait/retry logic. True, and I have other gripes about SQLite, but I've fallen in love with it. SQLite rocks. SQLite rocks like Python rocks. Hard as Python had rocked before, Python started rockin' a whole bunch harder when 2.5 included SQLite3 in the standard library. I love SQLite because it solves problems I actually have. For the vast majority of code I write, "lite" is a good thing, and lite as it is, SQLite can handle several transactions per second. I give SQLite a file path and in a split second I have a relational, transactional database. Great. I did not want to configure a server and I sure did not want to inflict complexity upon my users. If you are smart and/or lucky enough to write a web app so popular that it outgrows SQLite, you can switch over to a big-time SQL server DBMS. At worst, you'll have to tweak some of the code. Imagine how much harder the scaling problem would be if the persistent data were stored via pickle. The SQLite developers state the situation brilliantly at http://www.sqlite.org/whentouse.html: "SQLite is not designed to replace Oracle. It is designed to replace fopen()." -- --Bryan From martin at v.loewis.de Tue May 4 02:07:48 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 04 May 2010 08:07:48 +0200 Subject: Sphinx hosting In-Reply-To: References: Message-ID: <4BDFB9B4.1040400@v.loewis.de> Michele Simionato wrote: > Say you have a project with a lot of documentation in the form of > Sphinx pages (for instance a book project). What is the the easiest > way to publish it on the Web? I see that GitHub Pages allows you to > publish static pages, but I would need to check in both the .rst > sources and the .html output: it is not that annoying, but perhaps > there is already some services out there publishing Sphinx pages > directly. Do you know of any? Currently I am hosting my stuff on > Google Code but I do not see an easy way to publish the documentation > there. Any hint is appreciated. If it's a Python package that this documentation is about, you can host it on PyPI. Regards, Martin From michele.simionato at gmail.com Tue May 4 02:19:12 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 3 May 2010 23:19:12 -0700 (PDT) Subject: Sphinx hosting References: <4BDFB9B4.1040400@v.loewis.de> Message-ID: <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> On May 4, 8:07?am, "Martin v. Loewis" wrote: > If it's a Python package that this documentation is about, you can host > it on PyPI. It must not be Python, but let's consider this case first. How does it work? When I published my decorator module (http://pypi.python.org/pypi/decorator) the support was not very good. At the end I decided to put the generated .html inside the long_description field instead of the .rst source to get the look and feel I wanted. Moreover the long_description hack works for a single page documentation, but I am talking here of a book-sized document with many pages and hyperlinks. Do you know of recent improvements on the PyPI side about docs hosting? The CheeseShopTutorial http://wiki.python.org/moin/CheeseShopTutorial seems to give the same info of the last time I checked. From rony.masc at gmail.com Tue May 4 02:21:23 2010 From: rony.masc at gmail.com (Rony Mascreen) Date: Mon, 3 May 2010 23:21:23 -0700 (PDT) Subject: Rockin phone u r rit Message-ID: I wasnt intend to buy any of the samsung phones. but i was fascinated of its new corby series and buy this phone. really amazing phone with lots social networking programs. i have written more on http://hubpages.com/hub/Samsung-Corby-TxT-B3210 This phone is worth to buy. From rony.masc at gmail.com Tue May 4 02:21:45 2010 From: rony.masc at gmail.com (Rony Mascreen) Date: Mon, 3 May 2010 23:21:45 -0700 (PDT) Subject: Buy Samsung Corby TXT B3210 Mobile References: <6606ee63-9e0d-4a5d-97eb-4b88133345c7@30g2000yqi.googlegroups.com> Message-ID: <0647c288-17b2-45c6-a566-3af18dc16e9b@z13g2000prh.googlegroups.com> On Apr 12, 3:05?pm, "mohanti.si... at yahoo.in" wrote: > Samsung Corby TXT is a GSM phone. Samsung Corby TXT, a SmartPhone > mobile comes with a great list of features. > > ?Samsung Corby TXT B3210 is a mobile with a user memory of 38 MB and > MicroSD support up to 8 GB of external memory. This simple statement > of specifications is sufficient for mobile buffs to gauge the power of > Samsung Corby TXT B3210. > > The Samsung Corby TxT is approximately priced at Rs 7,000 in India. > > Samsung Corby Txt Specification > ? Network: GSM, Band 850/900/1800/1900 > ? Dimension: 59?110x12.9 > ? Display: TFT LCD 2.2 inch > ? Battery: 800mAh > ? Talk Time: up to 10 hrs > ? Standby: up to 316H > ? Camera: 2MP, 2x digital zoom > ? Video player > ? Video recording > ? Video messaging > ? Video streaming > ? Music Player > ? MP3 Ringtones > ? 3D sound technology ? Music Recognition > ? FM Radio > ? Bluetooth > ? WAP > ? USB > ? PC Sync Application > ? User Memory: 38 MB > ? SMS Memory: 500 > ? Phone Book Entries upto 1000 > ? External Memory: Upto MicroSD(Upto 8GB) > ? Speakerphone > For more information:http://www.khojle.in/classifieds/mobile/ I wasnt intend to buy any of the samsung phones. but i was fascinated of its new corby series and buy this phone. really amazing phone with lots social networking programs. i have written more on http://hubpages.com/hub/Samsung-Corby-TxT-B3210 This phone is worth to buy. From martin at v.loewis.de Tue May 4 02:37:32 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 04 May 2010 08:37:32 +0200 Subject: Sphinx hosting In-Reply-To: <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> Message-ID: <4BDFC0AC.40609@v.loewis.de> > Do you know of recent improvements on the PyPI side about docs > hosting? Yes; go to your package's pkg_edit page, i.e. http://pypi.python.org/pypi?%3Aaction=pkg_edit&name=decorator and provide a zip file at Upload Documentation. Regards, Martin From __peter__ at web.de Tue May 4 02:45:57 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 May 2010 08:45:57 +0200 Subject: repeat tkinter References: <8739b635-18c6-40e6-82ac-7b0ca673774b@o11g2000yqj.googlegroups.com> Message-ID: Robin wrote: > How can I make a command within a tkinter application repeat itself > over and over in intervals of a certain time. >>> import Tkinter as tk >>> root = tk.Tk() >>> color = "blue" >>> def switch_color(): ... global color ... if color == "blue": ... color = "red" ... else: ... color = "blue" ... root["background"] = color ... root.after(500, switch_color) ... >>> switch_color() From Ron.Barak at lsi.com Tue May 4 03:01:35 2010 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 4 May 2010 08:01:35 +0100 Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> Hi, I'm parsing XML files using ElementTree from xml.etree (see code below (and attached xml_parse_example.py)). However, I'm coming across input XML files (attached an example: tmp.xml) which include invalid characters, that produce the following traceback: $ python xml_parse_example.py Traceback (most recent call last): File "xml_parse_example.py", line 63, in tree = xml2dict.open_and_parse_xml_file() File "xml_parse_example.py", line 14, in open_and_parse_xml_file tree = ElementTree.parse(f) File "c:\Python26\lib\xml\etree\ElementTree.py", line 862, in parse tree.parse(source, parser) File "c:\Python26\lib\xml\etree\ElementTree.py", line 586, in parse parser.feed(data) File "c:\Python26\lib\xml\etree\ElementTree.py", line 1245, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 6, column 34 I read the documentation for xml.etree.ElementTree and see that it may take an optional parser parameter, but I don't know what this parser should be - to ignore the invalid characters. Could you suggest a way to call ElementTree, so it won't bomb on these invalid characters ? Thanks, Ron. ________________________________ #!/usr/bin/env python from xml.etree import ElementTree import pprint compute_tail = False class XmlFileToDict(): def __init__(self, xml_file_path): self.xml_file_path = xml_file_path def open_and_parse_xml_file(self): with open(self.xml_file_path, 'rt') as f: tree = ElementTree.parse(f) return tree def dict_list(self, node): res = {} res[node.tag] = [] self.xml_to_dict(node,res[node.tag]) reply = {} if compute_tail: reply[node.tag] = {'value':res[node.tag],'attribs':node.attrib,'tail':node.tail} else: reply[node.tag] = {'value':res[node.tag],'attribs':node.attrib} return reply def xml_to_dict(self, node, res): rep = {} if len(node): #n = 0 for n in list(node): rep[node.tag] = [] value = self.xml_to_dict(n,rep[node.tag]) if len(n): if compute_tail: value = {'value':rep[node.tag],'attributes':n.attrib,'tail':n.tail} else: value = {'value':rep[node.tag],'attributes':n.attrib} res.append({n.tag:value}) else : res.append(rep[node.tag][0]) else: value = {} if compute_tail: value = {'value':node.text,'attributes':node.attrib,'tail':node.tail} else: value = {'value':node.text,'attributes':node.attrib} res.append({node.tag:value}) return if __name__ == '__main__' : xml_file_path ='tmp.xml' xml2dict = XmlFileToDict(xml_file_path) tree = xml2dict.open_and_parse_xml_file() xml_dict = xml2dict.dict_list(tree.getroot()) pprint.pprint(xml_dict) ________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: tmp.xml Type: application/xml Size: 637 bytes Desc: tmp.xml URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: xml_parse_example.py Type: application/octet-stream Size: 2294 bytes Desc: xml_parse_example.py URL: From stefan_ml at behnel.de Tue May 4 03:01:40 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 09:01:40 +0200 Subject: new extension generator for C++ In-Reply-To: References: Message-ID: Rouslan Korneychuk, 03.05.2010 22:44: > The only issue is > it will not use keyword arguments for overloaded functions (I don't know > if that can even be done reliably *and* efficiently. I would need to > give it more thought). You should look at the argument unpacking code that Cython generates. It has been subject to serious benchmarking and optimisations. Stefan From space.ship.traveller at gmail.com Tue May 4 03:06:17 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 4 May 2010 19:06:17 +1200 Subject: new extension generator for C++ In-Reply-To: References: Message-ID: <9F9978CE-B1DD-4BBF-AEAF-25B8515E4932@gmail.com> Dear Rouslan, It looks interesting. I say go for it. You will learn something and might make some improvements on existing ideas. I recommend putting the code on www.github.com Kind regards, Samuel On 4/05/2010, at 8:44 AM, Rouslan Korneychuk wrote: > Hi, I'm new here. I'm working on a program that exposes C++ declarations to Python and I was wondering if there is any interest in it. > > It's a hobby project. I was originally using Boost.Python on another project but found a couple of things I didn't like. Eg: you can't really have private constructors. If you want a Python object created, you either have to expose the constructor in Python, or create an instance of the object somewhere else in memory, and have it either copied to the PyObject or have the PyObject hold a reference to it. I was working on a rudimentary 3D game engine that was a Python extension. It was important to avoid copying potentially huge amounts of data, but to have almost every PyObject just be a pointer to another object (and the object already is just a few or even one pointer) seemed like an pointless compromise, considering that I was writing code that was specifically designed to be a Python extension (There was also another issue I came across but don't remember now). > > So I looked for other solutions and noticed that Py++ (which simply generates Boost.Python code for you) was based on a seperate program called GCCXML. I figured I could use GCCXML and generate code however I wanted. So I did. > > My program generates human-readable code (it even uses proper indentation). The program still has a lot of work to be done on it, but it can already generate working Python extensions. > > It takes an input file like this: > > > module doc string > > > class doc string > > > > > > > > You can probably figure out what the resulting code does. The goal is to generate code that is as close to hand-written code as possible. It even forgoes using PyArg_ParseTupleAndKeywords and has the argument checks hard-wired. It also generates a header file that contains a PyObject implementation of MyClass called obj_AClass, with every constructor fowarded and with the new and delete operators overloaded to play nice with Python's memory handler: > ... > extern PyTypeObject obj_AClassType; > > struct obj_AClass { > PyObject_HEAD > MyClass base; > bool initialized; > > void *operator new(size_t s) { > void *ptr = PyMem_Malloc(s); > if(!ptr) throw std::bad_alloc(); > return ptr; > } > > void operator delete(void *ptr) { > PyMem_Free(ptr); > } > > obj_AClass(MyClass const & _0) : base(_0) { > PyObject_Init(reinterpret_cast(this),&obj_AClassType); > initialized = true; > } > > obj_AClass(unsigned int _0) : base(_0) { > PyObject_Init(reinterpret_cast(this),&obj_AClassType); > initialized = true; > } > > }; > ... > > If you want to expose one overload of a constructor or function but not the others, you can add overload="list,of,args" to or . Default values for arguments are handled automatically. When handling overloaded functions, it checks the types of the arguments to pick the best overload, taking into consideration polymorphism and the fact that basic types like ints can be converted from one-another. It will automatically detect if two overloads match to the same set of Python arguments (eg: void func(float) vs void func(double)). The only issue is it will not use keyword arguments for overloaded functions (I don't know if that can even be done reliably *and* efficiently. I would need to give it more thought). > > If there is enough interest I can put this project up on SourceForge or Google Code. > -- > http://mail.python.org/mailman/listinfo/python-list From r1chardj0n3s at gmail.com Tue May 4 03:07:21 2010 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Tue, 4 May 2010 17:07:21 +1000 Subject: Next Melbourne PUG meeting 6:30pm Monday 10th of May @ Horse Bazaar Message-ID: Meeting details, location and talks list are at: http://wiki.python.org/moin/MelbournePUG It looks like we've got a few cool talks lined up: 15 minute talks - None yet... suggest one! 5 minute talks - Load-balancing xmlrpclib/jsonrpclib for robust distributed applications (Andreux Fort) ... please feel free to suggest a topic - anything cool you've discovered lately. And I'm sure there'll be some talk about PyCon Australia as well! Richard From stefan_ml at behnel.de Tue May 4 03:23:56 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 09:23:56 +0200 Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> Message-ID: Barak, Ron, 04.05.2010 09:01: > I'm parsing XML files using ElementTree from xml.etree (see code below > (and attached xml_parse_example.py)). > > However, I'm coming across input XML files (attached an example: > tmp.xml) which include invalid characters, that produce the following > traceback: > > $ python xml_parse_example.py > Traceback (most recent call last): > xml.parsers.expat.ExpatError: not well-formed (invalid token): line 6, column 34 I hope you are aware that this means that the input you are parsing is not XML. It's best to reject the file and tell the producers that they are writing broken output files. You should always fix the source, instead of trying to make sense out of broken input in fragile ways. > I read the documentation for xml.etree.ElementTree and see that it may > take an optional parser parameter, but I don't know what this parser > should be - to ignore the invalid characters. > > Could you suggest a way to call ElementTree, so it won't bomb on these > invalid characters ? No. The parser in lxml.etree has a 'recover' option that lets it try to recover from input errors, but in general, XML parsers are required to reject non well-formed input. Stefan From michele.simionato at gmail.com Tue May 4 03:27:30 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 4 May 2010 00:27:30 -0700 (PDT) Subject: Sphinx hosting References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> Message-ID: <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> On May 4, 8:37?am, "Martin v. Loewis" wrote: > > Do you know of recent improvements on the PyPI side about docs > > hosting? > > Yes; go to your package's pkg_edit page, i.e. > > http://pypi.python.org/pypi?%3Aaction=pkg_edit&name=decorator > > and provide a zip file at Upload Documentation. > > Regards, > Martin Cool, that's good to know. I am still accepting recommendations for non-Python projects ;) From bruno.42.desthuilliers at websiteburo.invalid Tue May 4 03:37:03 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 04 May 2010 09:37:03 +0200 Subject: Django as exemplary design In-Reply-To: <2010050312243328275-tomfsessile@gmailcom> References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <4bdfce42$0$9110$426a34cc@news.free.fr> TomF a ?crit : > I'm interested in improving my python design by studying a large, > well-designed codebase. Someone (not a python programmer) suggested > Django. I realize that Django is popular, but can someone comment on > whether its code is well-designed and worth studying? > Carl makes some valid points in his answer, and there are indeed a couple dark corners in this area - bit it's just a part of the whole framework. There are still things worth studying in Django IHMO, specially if you're interested in seeing metaclasses and descriptors at work. From bruno.42.desthuilliers at websiteburo.invalid Tue May 4 03:39:03 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 04 May 2010 09:39:03 +0200 Subject: design question In-Reply-To: References: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> Message-ID: <4bdfceba$0$9110$426a34cc@news.free.fr> Alf P. Steinbach a ?crit : (snip) > Re efficiency it seems to be a complete non-issue, but correctness is > much more important: is there any way that the config details can be > (inadvertently) changed while the build is going on? +1 From prologic at shortcircuit.net.au Tue May 4 03:48:22 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 4 May 2010 17:48:22 +1000 Subject: Sphinx hosting In-Reply-To: <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> Message-ID: On Tue, May 4, 2010 at 5:27 PM, Michele Simionato wrote: > Cool, that's good to know. I am still accepting recommendations for > non-Python projects ;) bitbucket (1) also provide static file hosting through the wiki. From what I understand (tested) you simply clone the wiki repository (which is it's own repository) and commit a bunch of .html files. cheers James 1. http://bitbucket.org/ From greg.ewing at canterbury.ac.nz Tue May 4 03:56:13 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 May 2010 19:56:13 +1200 Subject: [OT] strange interaction between open and cwd In-Reply-To: <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> Message-ID: <84a1mcFfnpU1@mid.individual.net> Charles wrote: > In the OP's case, references to the directory have been removed from the > file > system, but his process still has the current working directory reference to > it, > so it has not actually been deleted. When he opens "../abc.txt", the OS > searches > the current directory for ".." and finds the inode for /home/baz/tmp, This doesn't seem to be quite correct. An experiment I just did reveals that the link count on the parent directory goes down by one when the current directory is deleted, suggesting that the .. link has actually been removed... yet it still works! I think what must be happening is that the kernel is maintaining an in-memory reference to the parent directory, and treating ".." as a special case when looking up a name. (This probably shouldn't be too surprising, because ".." is special in another way as well -- at the root of a mounted file system, it leads to the parent of the mount point, even though the actual ".." link on disk just points back to the same directory. Probably it simplifies the name lookup logic to always treat it specially.) -- Greg From greg.ewing at canterbury.ac.nz Tue May 4 04:08:36 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 May 2010 20:08:36 +1200 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEDC73.1020301@ftml.net> Message-ID: <84a2djFjqrU1@mid.individual.net> Grant Edwards wrote: > except that Python objects can form a generalized graph, and Unix > filesystems are constrained to be a tree. Actually I believe that root is allowed to create arbitrary hard links to directories in Unix, so it's possible to turn the file system in to a general graph. It's highly unrecommended, though, because it confuses the heck out of programs that recursively traverse directories (which is why only root is allowed to do it). -- Greg From ldo at geek-central.gen.new_zealand Tue May 4 04:15:43 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 04 May 2010 20:15:43 +1200 Subject: [PATCH] add functional matrix-returning methods to Pycairo Message-ID: I find the matrix methods in Pycairo to be an annoying hodge-podge of ones that overwrite the Matrix object in-place (init_rotate, invert) versus ones that concatenate additional transformations (rotate, scale, translate) versus ones that return new matrices without modifying the originals (multiply). Myself, I prefer methods that always return new matrices. This allows for a more functional style of programming, e.g. given m = cairo.Matrix() then m2 = m.translation(-10, -10) * m.rotation(math.pi / 4) * m.translation(10, 10) concisely expresses rotation by 90? about the centre (10, 10). Herewith a patch to add such methods to the cairo.Matrix class. Note that the names (inverse, rotation, scaling, translation) are nouns, to reflect the fact that they don't perform the actions, but they return Matrix objects that do. --- src/matrix.c | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 75 insertions(+), 0 deletions(-) diff --git a/src/matrix.c b/src/matrix.c index eefeab9..d1709b9 100644 --- a/src/matrix.c +++ b/src/matrix.c @@ -206,6 +206,76 @@ matrix_translate (PycairoMatrix *o, PyObject *args) { } static PyObject * +matrix_translation(PycairoMatrix *unused, PyObject *args) + { + PyObject * result = NULL; + double tx, ty; + cairo_matrix_t result_matrix; + do /*once*/ + { + if (!PyArg_ParseTuple(args, "dd:Matrix.translation", &tx, &ty)) + break; + cairo_matrix_init_identity(&result_matrix); + cairo_matrix_translate(&result_matrix, tx, ty); + result = PycairoMatrix_FromMatrix(&result_matrix); + } + while (0); + return result; + } /*matrix_translation*/ + +static PyObject * +matrix_scaling(PycairoMatrix *unused, PyObject *args) + { + PyObject * result = NULL; + double sx, sy; + cairo_matrix_t result_matrix; + do /*once*/ + { + if (!PyArg_ParseTuple(args, "dd:Matrix.scaling", &sx, &sy)) + break; + cairo_matrix_init_identity(&result_matrix); + cairo_matrix_scale(&result_matrix, sx, sy); + result = PycairoMatrix_FromMatrix(&result_matrix); + } + while (0); + return result; + } /*matrix_scaling*/ + +static PyObject * +matrix_rotation(PycairoMatrix *unused, PyObject *args) + { + PyObject * result = NULL; + double radians; + cairo_matrix_t result_matrix; + do /*once*/ + { + if (!PyArg_ParseTuple(args, "d:Matrix.rotation", &radians)) + break; + cairo_matrix_init_identity(&result_matrix); + cairo_matrix_rotate(&result_matrix, radians); + result = PycairoMatrix_FromMatrix(&result_matrix); + } + while (0); + return result; + } /*matrix_rotation*/ + +static PyObject * +matrix_inverse(PycairoMatrix *self, PyObject *args_unused) + { + PyObject * result = NULL; + cairo_matrix_t result_matrix; + do /*once*/ + { + result_matrix = self->matrix; + if (Pycairo_Check_Status(cairo_matrix_invert(&result_matrix))) + break; + result = PycairoMatrix_FromMatrix(&result_matrix); + } + while (0); + return result; + } /*matrix_inverse*/ + +static PyObject * matrix_item (PycairoMatrix *o, Py_ssize_t i) { switch (i) { case 0: @@ -297,6 +367,11 @@ static PyMethodDef matrix_methods[] = { {"transform_distance",(PyCFunction)matrix_transform_distance, METH_VARARGS }, {"transform_point", (PyCFunction)matrix_transform_point, METH_VARARGS }, {"translate", (PyCFunction)matrix_translate, METH_VARARGS }, + /* functional methods: */ + {"translation", (PyCFunction)matrix_translation, METH_VARARGS | METH_STATIC }, + {"scaling", (PyCFunction)matrix_scaling, METH_VARARGS | METH_STATIC }, + {"rotation", (PyCFunction)matrix_rotation, METH_VARARGS | METH_STATIC }, + {"inverse", (PyCFunction)matrix_inverse, METH_VARARGS }, {NULL, NULL, 0, NULL}, }; -- 1.7.0 From greg.ewing at canterbury.ac.nz Tue May 4 04:23:50 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 May 2010 20:23:50 +1200 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <84a3a5Fp5nU1@mid.individual.net> Grant Edwards wrote: > In your example, it's simply not possible to determine the file's > absolute path within the filesystem given the relative path you > provided. Actually, I think it *is* theoretically possible to find an absolute path for the file in this case. I suspect that what realpath() is doing for a relative path is something like: 1. Use getcwd() to find an absolute path for the current directory. 2. Chop off a trailing pathname component for each ".." on the front of the original path. 3. Tack the filename on the end of what's left. Step 1 fails because the current directory no longer has an absolute pathname -- specifically, it has no name in what used to be its parent directory. What realpath() is failing to realise is that it doesn't actually need to know the full path of the current directory, only of its parent directory, which is still reachable via ".." (if it weren't, the file wouldn't be reachable either, and we wouldn't be having this discussion). A smarter version of realpath() wouldn't try to find the path of the *current* directory, but would follow the ".." links until it got to a directory that it did need to know an absolute path for, and start with that. Unfortunately, there is no C stdlib routine that does the equivalent of getcwd() for an arbitrary directory, so this would require realpath() to duplicate much of getcwd()'s functionality, which is probably why it's done the way it is. -- Greg From mail at timgolden.me.uk Tue May 4 05:19:31 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 04 May 2010 10:19:31 +0100 Subject: win32 - catch events(wmi?) In-Reply-To: References: <201005031302.31772.richard.lamboj@bilcom.at> <4BDF2BDC.7020805@timgolden.me.uk> Message-ID: <4BDFE6A3.5010002@timgolden.me.uk> On 03/05/2010 23:53, Giampaolo Rodol? wrote: > Just out of curiosity, is WMI able to list the TCP and UDP connections > opened by a process or by the OS? > We'll have to do this for psutil (http://code.google.com/p/psutil) and > we guess it's not gonna be easy. Not as far as I know. WMI doesn't tend to deal with things at a process level. (Altho' I'm always being surprised at just what *is* out there in WMI-land). TJG From jeanmichel at sequans.com Tue May 4 05:22:09 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 04 May 2010 11:22:09 +0200 Subject: Teaching Programming In-Reply-To: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> Message-ID: <4BDFE741.40305@sequans.com> Andr? wrote: > To Samuel Williams: (and other interested ;-) > > If you want to consider Python in education, I would encourage you > have a look at http://www.python.org/community/sigs/current/edu-sig/ > > I think you will find that there are quite a few resources available - > perhaps more than you are aware of. > > And, I don't think that because "some people do not like the > indentation strategy" is a valid reason not to consider that Python's > syntax is concise and simple. Actually, I would almost argue for the > contrary. Indentation indicate programming structure/logic very > clearly, without the need for arbitrary keywords and other punctuation > symbols. There are very few keywords in the language. > > You indicate that Python programs are readable. They are also known > to be short (much shorter than some other languages). > Andr? > Python indentation has been already discussed many times around, I remember someone saying something like "How is it possible not to like indentation while any decent programmer will use it no matter the language, including all those which feature statements/keywords for blocks". JM From space.ship.traveller at gmail.com Tue May 4 05:33:32 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 4 May 2010 21:33:32 +1200 Subject: Teaching Programming In-Reply-To: <4BDFE741.40305@sequans.com> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> Message-ID: I personally like indentation. I just wonder whether it is an issue that some people will dislike. But anyway, I updated the language comparison to remove this critique. Kind regards, Samuel On 4/05/2010, at 9:22 PM, Jean-Michel Pichavant wrote: > Andr? wrote: >> To Samuel Williams: (and other interested ;-) >> >> If you want to consider Python in education, I would encourage you >> have a look at http://www.python.org/community/sigs/current/edu-sig/ >> >> I think you will find that there are quite a few resources available - >> perhaps more than you are aware of. >> >> And, I don't think that because "some people do not like the >> indentation strategy" is a valid reason not to consider that Python's >> syntax is concise and simple. Actually, I would almost argue for the >> contrary. Indentation indicate programming structure/logic very >> clearly, without the need for arbitrary keywords and other punctuation >> symbols. There are very few keywords in the language. >> >> You indicate that Python programs are readable. They are also known >> to be short (much shorter than some other languages). >> Andr? >> > Python indentation has been already discussed many times around, I remember someone saying something like "How is it possible not to like indentation while any decent programmer will use it no matter the language, including all those which feature statements/keywords for blocks". > > JM > -- > http://mail.python.org/mailman/listinfo/python-list From nico.schloemer at gmail.com Tue May 4 06:10:36 2010 From: nico.schloemer at gmail.com (=?ISO-8859-1?Q?Nico_Schl=F6mer?=) Date: Tue, 4 May 2010 12:10:36 +0200 Subject: itertools: problem with nested groupby, list() Message-ID: Hi, I ran into a bit of an unexpected issue here with itertools, and I need to say that I discovered itertools only recently, so maybe my way of approaching the problem is "not what I want to do". Anyway, the problem is the following: I have a list of dictionaries, something like [ { "a": 1, "b": 1, "c": 3 }, { "a": 1, "b": 1, "c": 4 }, ... ] and I'd like to iterate through all items with, e.g., "a":1. What I do is sort and then groupby, my_list.sort( key=operator.itemgetter('a') ) my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) and then just very simply iterate over my_list_grouped, for my_item in my_list_grouped: # do something with my_item[0], my_item[1] Now, inside this loop I'd like to again iterate over all items with the same 'b'-value -- no problem, just do the above inside the loop: for my_item in my_list_grouped: # group by keyword "b" my_list2 = list( my_item[1] ) my_list2.sort( key=operator.itemgetter('b') ) my_list_grouped = itertools.groupby( my_list2, operator.itemgetter('b') ) for e in my_list_grouped: # do something with e[0], e[1] That seems to work all right. Now, the problem occurs when this all is wrapped into an outer loop, such as for k in [ 'first pass', 'second pass' ]: for my_item in my_list_grouped: # bla, the above To be able to iterate more than once through my_list_grouped, I have to convert it into a list first, so outside all loops, I go like my_list.sort( key=operator.itemgetter('a') ) my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) my_list_grouped = list( my_list_grouped ) This, however, makes it impossible to do the inner sort and groupby-operation; you just get the very first element, and that's it. An example file is attached. Hints, anyone? Cheers, Nico -------------- next part -------------- A non-text attachment was scrubbed... Name: iterator-test.py Type: text/x-python Size: 1146 bytes Desc: not available URL: From petshmidt at googlemail.com Tue May 4 06:17:10 2010 From: petshmidt at googlemail.com (someone) Date: Tue, 4 May 2010 03:17:10 -0700 (PDT) Subject: print executed query References: <9b2a7e6f-003d-474a-968f-0cdcede9ce5c@k41g2000yqb.googlegroups.com> <8E05B556-DB67-4B4C-B4B4-C34E12BE6E35@semanchuk.com> Message-ID: On 4 Mai, 07:01, Fred C wrote: > On Apr 29, 2010, at 9:49 AM, Philip Semanchuk wrote: > > > > > > > On Apr 29, 2010, at 12:01 PM, someone wrote: > > >> Hello! > > >> Is there a way to print a query for logging purpose as it was or will > >> be sent to database, if I don't escape values of query by myself? > > >> cursor.execute(query, [id, somestring]) > > >> I could print query and values separate, but it would be great, if I > >> could see how query is constructed and can the also copy it and > >> execute in console. > > >> Im using psycopg2, btw > > > If you can fiddle with the Postgres server settings, the server has options for logging lots of things, including the queries it executes. > > > Hope this helps > > Philip > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ?smime.p7s > 4KAnzeigenHerunterladen Hello! Thanks for help! I've found much more simpler solution ;) http://initd.org/psycopg/docs/cursor.html query Read-only attribute containing the body of the last query sent to the backend (including bound arguments). None if no query has been executed yet: >>> cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar')) >>> cur.query "INSERT INTO test (num, data) VALUES (42, E'bar')" DB API extension The query attribute is a Psycopg extension to the DB API 2.0. From utente at esempio.net Tue May 4 06:28:51 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 12:28:51 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> Message-ID: <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> Samuel Williams ha scritto: > I personally like indentation. > > I just wonder whether it is an issue that some people will dislike. i think there is an issue if you -- say -- produce python code, from within another programming environment, to be executed on the fly, at least in some instances. there might be problems if for example you generate code from a one-line template. i use a special template system for my job, which goes like this: ... %%SCHEMA: ... $A, $B, $C being "loop" control variables reserved to the template system. upon parsing, the system generates the corresponding code (say "print 12*2**3") and stores the output for further use. due to design restrictions, i cannot write a code-template which spans multiple template-lines, and that is a problem with python, because for instance i cannot use conditionals or for loops. if it was C or java there wuold be no problem since the source is free-form, so an entire program can "live" on a single source line. bye From eckhardt at satorlaser.com Tue May 4 06:46:20 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 04 May 2010 12:46:20 +0200 Subject: itertools: problem with nested groupby, list() References: Message-ID: Nico Schl?mer wrote: > I ran into a bit of an unexpected issue here with itertools, and I > need to say that I discovered itertools only recently, so maybe my way > of approaching the problem is "not what I want to do". > > Anyway, the problem is the following: > I have a list of dictionaries, something like > > [ { "a": 1, "b": 1, "c": 3 }, > { "a": 1, "b": 1, "c": 4 }, > ... > ] > > and I'd like to iterate through all items with, e.g., "a":1. What I do > is sort and then groupby, > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > > and then just very simply iterate over my_list_grouped, > > for my_item in my_list_grouped: > # do something with my_item[0], my_item[1] I'd try to avoid copying the list and instead just iterate over it: def iterate_by_key(l, key): for d in l: try: yield l[key] except: continue Note that you could also ask the dictionary first if it has the key, but I'm told this way is even faster since it only requires a single lookup attempt. > Now, inside this loop I'd like to again iterate over all items with > the same 'b'-value -- no problem, just do the above inside the loop: > > for my_item in my_list_grouped: > # group by keyword "b" > my_list2 = list( my_item[1] ) > my_list2.sort( key=operator.itemgetter('b') ) > my_list_grouped = itertools.groupby( my_list2, > operator.itemgetter('b') ) > for e in my_list_grouped: > # do something with e[0], e[1] > > That seems to work all right. Since your operation not only iterates over a list but first sorts it, it requires a modification which must not happen while iterating. You work around this by copying the list first. > Now, the problem occurs when this all is wrapped into an outer loop, such > as > > for k in [ 'first pass', 'second pass' ]: > for my_item in my_list_grouped: > # bla, the above > > To be able to iterate more than once through my_list_grouped, I have > to convert it into a list first, so outside all loops, I go like > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > my_list_grouped = list( my_list_grouped ) > > This, however, makes it impossible to do the inner sort and > groupby-operation; you just get the very first element, and that's it. I believe that you are doing a modifying operation inside the the iteration, which is a no-no. Create a custom iterator function (IIRC they are called "generators") and you should be fine. Note that this should also perform better since copying and sorting are not exactly for free, though you may not notice that with small numbers of objects. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From stefan_ml at behnel.de Tue May 4 06:50:46 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 12:50:46 +0200 Subject: Teaching Programming In-Reply-To: <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> Message-ID: superpollo, 04.05.2010 12:28: > i think there is an issue if you -- say -- produce python code, from > within another programming environment, to be executed on the fly, at > least in some instances. there might be problems if for example you > generate code from a one-line template. There are a couple of code generation tools available that you can find on PyPI. However, the main reason why this problem doesn't hurt much in Python is that Python is a dynamic language that can get you extremely far without generating code. It's simply not necessary in most cases, so people don't run into problems with it. Stefan From joncle at googlemail.com Tue May 4 07:08:14 2010 From: joncle at googlemail.com (Jon Clements) Date: Tue, 4 May 2010 04:08:14 -0700 (PDT) Subject: itertools: problem with nested groupby, list() References: Message-ID: <76fc5fab-9c3b-4aeb-b38d-8ae913822d3a@q32g2000yqb.googlegroups.com> On 4 May, 11:10, Nico Schl?mer wrote: > Hi, > > I ran into a bit of an unexpected issue here with itertools, and I > need to say that I discovered itertools only recently, so maybe my way > of approaching the problem is "not what I want to do". > > Anyway, the problem is the following: > I have a list of dictionaries, something like > > [ { "a": 1, "b": 1, "c": 3 }, > ? { "a": 1, "b": 1, "c": 4 }, > ? ... > ] > > and I'd like to iterate through all items with, e.g., "a":1. What I do > is sort and then groupby, > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > > and then just very simply iterate over my_list_grouped, > > for my_item in my_list_grouped: > ? ? # do something with my_item[0], my_item[1] > > Now, inside this loop I'd like to again iterate over all items with > the same 'b'-value -- no problem, just do the above inside the loop: > > for my_item in my_list_grouped: > ? ? ? ? # group by keyword "b" > ? ? ? ? my_list2 = list( my_item[1] ) > ? ? ? ? my_list2.sort( key=operator.itemgetter('b') ) > ? ? ? ? my_list_grouped = itertools.groupby( my_list2, > operator.itemgetter('b') ) > ? ? ? ? for e in my_list_grouped: > ? ? ? ? ? ? # do something with e[0], e[1] > > That seems to work all right. > > Now, the problem occurs when this all is wrapped into an outer loop, such as > > for k in [ 'first pass', 'second pass' ]: > ? ? for my_item in my_list_grouped: > ? ? # bla, the above > > To be able to iterate more than once through my_list_grouped, I have > to convert it into a list first, so outside all loops, I go like > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > my_list_grouped = list( my_list_grouped ) > > This, however, makes it impossible to do the inner sort and > groupby-operation; you just get the very first element, and that's it. > > An example file is attached. > > Hints, anyone? > > Cheers, > Nico Does this example help at all? my_list.sort( key=itemgetter('a','b','c') ) for a, a_iter in groupby(my_list, itemgetter('a')): print 'New A', a for b, b_iter in groupby(a_iter, itemgetter('b')): print '\t', 'New B', b for c, c_iter in groupby(b_iter, itemgetter('c')): print '\t'*2, 'New C', c for c_data in c_iter: print '\t'*3, a, b, c, c_data print '\t'*2, 'End C', c print '\t', 'End B', b print 'End A', a Jon. From chris at simplistix.co.uk Tue May 4 07:22:02 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 04 May 2010 12:22:02 +0100 Subject: modifying open office spreadsheet (with OO installed) In-Reply-To: <4BD9FB33.90208@comcast.net> References: <4bd8aa92$0$2118$426a34cc@news.free.fr> <4bd9ec94$0$24904$426a74cc@news.free.fr> <4BD9FB33.90208@comcast.net> Message-ID: <4BE0035A.4080001@simplistix.co.uk> Jim Byrnes wrote: > News123 wrote: >> Mumbling to myself, perhaps somebody else is interested. > > Yes I am. > >> News123 wrote: >>> Hi, >>> >>> >>> I wanted to know who can recommend a good module/library, that allows to >>> modify an Open Office spreadsheet. >>> >>> One can assume, that Open Office is installed on the host. >>> >>> >> Following url gives a small introduction about using the PyUno-bridge to >> open-read-modify-save a spread sheet >> http://stuvel.eu/ooo-python If .xls files are an option for you, xlutils.copy is your friend: https://secure.simplistix.co.uk/svn/xlutils/trunk/xlutils/docs/copy.txt cheers, Chris From chris at simplistix.co.uk Tue May 4 07:23:26 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 04 May 2010 12:23:26 +0100 Subject: ooolib, reading writing a spread sheet and keep formatting In-Reply-To: <4BD94090.8060005@free.fr> References: <4bd8cfc3$0$667$426a74cc@news.free.fr> <4BD94090.8060005@free.fr> Message-ID: <4BE003AE.4080406@simplistix.co.uk> News123 wrote: > > from xlrd import open_workbook > from xlutils.copy import copy > > rb = open_workbook('doc1.xls') open_workbook('doc1.xls',formatting_info=True) > print "WB with %d sheets" % rb.nsheets > wb = copy(rb) > wb.save("doc2.xls") # file is created, but ALL formattng is lost and > formulas are now diplayed as text cheers, Chris From utente at esempio.net Tue May 4 07:23:56 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 13:23:56 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> Message-ID: <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> Stefan Behnel ha scritto: > superpollo, 04.05.2010 12:28: >> i think there is an issue if you -- say -- produce python code, from >> within another programming environment, to be executed on the fly, at >> least in some instances. there might be problems if for example you >> generate code from a one-line template. > > There are a couple of code generation tools available that you can find > on PyPI. > > However, the main reason why this problem doesn't hurt much in Python is > that Python is a dynamic language that can get you extremely far without > generating code. It's simply not necessary in most cases, so people > don't run into problems with it. > > Stefan > Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> A,B=2,3 >>> if A>B: ... print A+B ... else: ... print A**B-B**2 ... -1 >>> A,B=3,2 >>> if A>B: ... print A+B ... else: ... print A**B-B**2 ... 5 >>> tell me please: how can generate the same output (depending on A and B) without control structure? i mean in a natural "pythonic" way... bye From martin.hellwig at dcuktec.org Tue May 4 07:25:57 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 04 May 2010 12:25:57 +0100 Subject: Teaching Programming In-Reply-To: <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> Message-ID: On 05/04/10 11:28, superpollo wrote: > Samuel Williams ha scritto: >> I personally like indentation. >> >> I just wonder whether it is an issue that some people will dislike. > there might be problems if for example you > generate code from a one-line template. Well a one-line template code generator are great and such, but if the output should be human readable it is necessary to have at least some form of mark-up control on it. Like newlines and indentations. On the other hand if it is only meant to generate executable code, generating an interpreted code might not be the best solution for the actual problem. For the corner cases (I can think of a couple) it is good to know you can use ';' most of the time. -- mph From oxfordenergyservices at googlemail.com Tue May 4 07:26:53 2010 From: oxfordenergyservices at googlemail.com (a) Date: Tue, 4 May 2010 04:26:53 -0700 (PDT) Subject: python gui Message-ID: <2f187732-ae4d-4cfc-8c43-3e4a5cd0166f@b18g2000yqb.googlegroups.com> where's the best online resource for teaching about GUI building? Thanks Paul C From nico.schloemer at gmail.com Tue May 4 07:36:06 2010 From: nico.schloemer at gmail.com (=?ISO-8859-1?Q?Nico_Schl=F6mer?=) Date: Tue, 4 May 2010 13:36:06 +0200 Subject: itertools: problem with nested groupby, list() In-Reply-To: <76fc5fab-9c3b-4aeb-b38d-8ae913822d3a@q32g2000yqb.googlegroups.com> References: <76fc5fab-9c3b-4aeb-b38d-8ae913822d3a@q32g2000yqb.googlegroups.com> Message-ID: > Does this example help at all? Thanks, that clarified things a lot! To make it easier, let's just look at 'a' and 'b': > my_list.sort( key=itemgetter('a','b','c') ) > for a, a_iter in groupby(my_list, itemgetter('a')): > print 'New A', a > for b, b_iter in groupby(a_iter, itemgetter('b')): > print '\t', 'New B', b > for b_data in b_iter: > print '\t'*3, a, b, b_data > print '\t', 'End B', b > print 'End A', a That works well, and I can wrap the outer loop in another loop without problems. What's *not* working, though, is having more than one pass on the inner loop, as in =============================== *snip* =============================== my_list.sort( key=itemgetter('a','b','c') ) for a, a_iter in groupby(my_list, itemgetter('a')): print 'New A', a for pass in ['first pass', 'second pass']: for b, b_iter in groupby(a_iter, itemgetter('b')): print '\t', 'New B', b for b_data in b_iter: print '\t'*3, a, b, b_data print '\t', 'End B', b print 'End A', a =============================== *snap* =============================== I tried working around this by =============================== *snip* =============================== my_list.sort( key=itemgetter('a','b','c') ) for a, a_iter in groupby(my_list, itemgetter('a')): print 'New A', a inner_list = list( groupby(a_iter, itemgetter('b')) ) for pass in ['first pass', 'second pass']: for b, b_iter in inner_list: print '\t', 'New B', b for b_data in b_iter: print '\t'*3, a, b, b_data print '\t', 'End B', b print 'End A', a =============================== *snap* =============================== which don't work either, and I don't understand why. -- I'll look at Uli's comments. Cheers, Nico On Tue, May 4, 2010 at 1:08 PM, Jon Clements wrote: > On 4 May, 11:10, Nico Schl?mer wrote: >> Hi, >> >> I ran into a bit of an unexpected issue here with itertools, and I >> need to say that I discovered itertools only recently, so maybe my way >> of approaching the problem is "not what I want to do". >> >> Anyway, the problem is the following: >> I have a list of dictionaries, something like >> >> [ { "a": 1, "b": 1, "c": 3 }, >> ? { "a": 1, "b": 1, "c": 4 }, >> ? ... >> ] >> >> and I'd like to iterate through all items with, e.g., "a":1. What I do >> is sort and then groupby, >> >> my_list.sort( key=operator.itemgetter('a') ) >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> >> and then just very simply iterate over my_list_grouped, >> >> for my_item in my_list_grouped: >> ? ? # do something with my_item[0], my_item[1] >> >> Now, inside this loop I'd like to again iterate over all items with >> the same 'b'-value -- no problem, just do the above inside the loop: >> >> for my_item in my_list_grouped: >> ? ? ? ? # group by keyword "b" >> ? ? ? ? my_list2 = list( my_item[1] ) >> ? ? ? ? my_list2.sort( key=operator.itemgetter('b') ) >> ? ? ? ? my_list_grouped = itertools.groupby( my_list2, >> operator.itemgetter('b') ) >> ? ? ? ? for e in my_list_grouped: >> ? ? ? ? ? ? # do something with e[0], e[1] >> >> That seems to work all right. >> >> Now, the problem occurs when this all is wrapped into an outer loop, such as >> >> for k in [ 'first pass', 'second pass' ]: >> ? ? for my_item in my_list_grouped: >> ? ? # bla, the above >> >> To be able to iterate more than once through my_list_grouped, I have >> to convert it into a list first, so outside all loops, I go like >> >> my_list.sort( key=operator.itemgetter('a') ) >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> my_list_grouped = list( my_list_grouped ) >> >> This, however, makes it impossible to do the inner sort and >> groupby-operation; you just get the very first element, and that's it. >> >> An example file is attached. >> >> Hints, anyone? >> >> Cheers, >> Nico > > Does this example help at all? > > my_list.sort( key=itemgetter('a','b','c') ) > for a, a_iter in groupby(my_list, itemgetter('a')): > ? ?print 'New A', a > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): > ? ? ? ?print '\t', 'New B', b > ? ? ? ?for c, c_iter in groupby(b_iter, itemgetter('c')): > ? ? ? ? ? ?print '\t'*2, 'New C', c > ? ? ? ? ? ?for c_data in c_iter: > ? ? ? ? ? ? ? ?print '\t'*3, a, b, c, c_data > ? ? ? ? ? ?print '\t'*2, 'End C', c > ? ? ? ?print '\t', 'End B', b > ? ?print 'End A', a > > Jon. > -- > http://mail.python.org/mailman/listinfo/python-list > From nico.schloemer at gmail.com Tue May 4 07:43:18 2010 From: nico.schloemer at gmail.com (=?ISO-8859-1?Q?Nico_Schl=F6mer?=) Date: Tue, 4 May 2010 13:43:18 +0200 Subject: itertools: problem with nested groupby, list() In-Reply-To: References: Message-ID: > I'd try to avoid copying the list and instead just iterate over it: > > > def iterate_by_key(l, key): > for d in l: > try: > yield l[key] > except: > continue Hm, that won't work for me b/c I don't know all the keys beforehand. I could certainly do a unique(list.keys()) or something like that beforehand, but I guess this does away with the speed advantage. > Since your operation not only iterates over a list but first sorts it, it > requires a modification which must not happen while iterating. You work > around this by copying the list first. So when I go like for item in list: item[1].sort() I actually modify *list*? I didn't realize that; I thought it'd just be a copy of it. Anyway, I could just try for item in list: newitem = sorted( item[1] ) in that case. > which is a no-no. Create a custom iterator function (IIRC they are > called "generators") and you should be fine. I'll look into this, thanks for the hint. Cheers, Nico On Tue, May 4, 2010 at 12:46 PM, Ulrich Eckhardt wrote: > Nico Schl?mer wrote: >> I ran into a bit of an unexpected issue here with itertools, and I >> need to say that I discovered itertools only recently, so maybe my way >> of approaching the problem is "not what I want to do". >> >> Anyway, the problem is the following: >> I have a list of dictionaries, something like >> >> [ { "a": 1, "b": 1, "c": 3 }, >> ? { "a": 1, "b": 1, "c": 4 }, >> ? ... >> ] >> >> and I'd like to iterate through all items with, e.g., "a":1. What I do >> is sort and then groupby, >> >> my_list.sort( key=operator.itemgetter('a') ) >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> >> and then just very simply iterate over my_list_grouped, >> >> for my_item in my_list_grouped: >> ? ? # do something with my_item[0], my_item[1] > > I'd try to avoid copying the list and instead just iterate over it: > > > ? ?def iterate_by_key(l, key): > ? ? ? ?for d in l: > ? ? ? ? ? ?try: > ? ? ? ? ? ? ? ?yield l[key] > ? ? ? ? ? ?except: > ? ? ? ? ? ? ? ?continue > > Note that you could also ask the dictionary first if it has the key, but I'm > told this way is even faster since it only requires a single lookup > attempt. > > >> Now, inside this loop I'd like to again iterate over all items with >> the same 'b'-value -- no problem, just do the above inside the loop: >> >> for my_item in my_list_grouped: >> ? ? ? ? # group by keyword "b" >> ? ? ? ? my_list2 = list( my_item[1] ) >> ? ? ? ? my_list2.sort( key=operator.itemgetter('b') ) >> ? ? ? ? my_list_grouped = itertools.groupby( my_list2, >> operator.itemgetter('b') ) >> ? ? ? ? for e in my_list_grouped: >> ? ? ? ? ? ? # do something with e[0], e[1] >> >> That seems to work all right. > > Since your operation not only iterates over a list but first sorts it, it > requires a modification which must not happen while iterating. You work > around this by copying the list first. > >> Now, the problem occurs when this all is wrapped into an outer loop, such >> as >> >> for k in [ 'first pass', 'second pass' ]: >> ? ? for my_item in my_list_grouped: >> ? ? # bla, the above >> >> To be able to iterate more than once through my_list_grouped, I have >> to convert it into a list first, so outside all loops, I go like >> >> my_list.sort( key=operator.itemgetter('a') ) >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> my_list_grouped = list( my_list_grouped ) >> >> This, however, makes it impossible to do the inner sort and >> groupby-operation; you just get the very first element, and that's it. > > I believe that you are doing a modifying operation inside the the iteration, > which is a no-no. Create a custom iterator function (IIRC they are > called "generators") and you should be fine. Note that this should also > perform better since copying and sorting are not exactly for free, though > you may not notice that with small numbers of objects. > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 > > -- > http://mail.python.org/mailman/listinfo/python-list > From stefan_ml at behnel.de Tue May 4 07:43:43 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 13:43:43 +0200 Subject: Teaching Programming In-Reply-To: <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> Message-ID: superpollo, 04.05.2010 13:23: > Stefan Behnel ha scritto: >> the main reason why this problem doesn't hurt much in Python >> is that Python is a dynamic language that can get you extremely far >> without generating code. It's simply not necessary in most cases, so >> people don't run into problems with it. > > Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> A,B=2,3 > >>> if A>B: > ... print A+B > ... else: > ... print A**B-B**2 > ... > -1 > >>> A,B=3,2 > >>> if A>B: > ... print A+B > ... else: > ... print A**B-B**2 > ... > 5 > > tell me please: how can generate the same output (depending on A and B) > without control structure? i mean in a natural "pythonic" way... The question is: why do you have to generate the above code in the first place? Isn't a function enough that does the above? Stefan From joncle at googlemail.com Tue May 4 07:52:34 2010 From: joncle at googlemail.com (Jon Clements) Date: Tue, 4 May 2010 04:52:34 -0700 (PDT) Subject: itertools: problem with nested groupby, list() References: <76fc5fab-9c3b-4aeb-b38d-8ae913822d3a@q32g2000yqb.googlegroups.com> Message-ID: <22a806f2-03a0-4cfa-a73f-b4d4ff582937@g21g2000yqk.googlegroups.com> On 4 May, 12:36, Nico Schl?mer wrote: > > Does this example help at all? > > Thanks, that clarified things a lot! > > To make it easier, let's just look at 'a' and 'b': > > > my_list.sort( key=itemgetter('a','b','c') ) > > for a, a_iter in groupby(my_list, itemgetter('a')): > > ? ?print 'New A', a > > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): > > ? ? ? ?print '\t', 'New B', b > > ? ? ? ?for b_data in b_iter: > > ? ? ? ? ? ?print '\t'*3, a, b, b_data > > ? ? ? ?print '\t', 'End B', b > > ? ?print 'End A', a > > That works well, and I can wrap the outer loop in another loop without > problems. What's *not* working, though, is having more than one pass > on the inner loop, as in > > =============================== *snip* =============================== > my_list.sort( key=itemgetter('a','b','c') ) > for a, a_iter in groupby(my_list, itemgetter('a')): > ? ?print 'New A', a > ? ?for pass in ['first pass', 'second pass']: > ? ? ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): > ? ? ? ? ? ?print '\t', 'New B', b > ? ? ? ? ? ?for b_data in b_iter: > ? ? ? ? ? ? ? ?print '\t'*3, a, b, b_data > ? ? ? ? ? ?print '\t', 'End B', b > ? ? ? ?print 'End A', a > =============================== *snap* =============================== > > I tried working around this by > > =============================== *snip* =============================== > my_list.sort( key=itemgetter('a','b','c') ) > for a, a_iter in groupby(my_list, itemgetter('a')): > ? ?print 'New A', a > ? ?inner_list = ?list( groupby(a_iter, itemgetter('b')) ) > ? ?for pass in ['first pass', 'second pass']: > ? ? ? ?for b, b_iter in inner_list: > ? ? ? ? ? ?print '\t', 'New B', b > ? ? ? ? ? ?for b_data in b_iter: > ? ? ? ? ? ? ? ?print '\t'*3, a, b, b_data > ? ? ? ? ? ?print '\t', 'End B', b > ? ? ? ?print 'End A', a > =============================== *snap* =============================== > > which don't work either, and I don't understand why. -- I'll look at > Uli's comments. > > Cheers, > Nico > > On Tue, May 4, 2010 at 1:08 PM, Jon Clements wrote: > > On 4 May, 11:10, Nico Schl?mer wrote: > >> Hi, > > >> I ran into a bit of an unexpected issue here with itertools, and I > >> need to say that I discovered itertools only recently, so maybe my way > >> of approaching the problem is "not what I want to do". > > >> Anyway, the problem is the following: > >> I have a list of dictionaries, something like > > >> [ { "a": 1, "b": 1, "c": 3 }, > >> ? { "a": 1, "b": 1, "c": 4 }, > >> ? ... > >> ] > > >> and I'd like to iterate through all items with, e.g., "a":1. What I do > >> is sort and then groupby, > > >> my_list.sort( key=operator.itemgetter('a') ) > >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > > >> and then just very simply iterate over my_list_grouped, > > >> for my_item in my_list_grouped: > >> ? ? # do something with my_item[0], my_item[1] > > >> Now, inside this loop I'd like to again iterate over all items with > >> the same 'b'-value -- no problem, just do the above inside the loop: > > >> for my_item in my_list_grouped: > >> ? ? ? ? # group by keyword "b" > >> ? ? ? ? my_list2 = list( my_item[1] ) > >> ? ? ? ? my_list2.sort( key=operator.itemgetter('b') ) > >> ? ? ? ? my_list_grouped = itertools.groupby( my_list2, > >> operator.itemgetter('b') ) > >> ? ? ? ? for e in my_list_grouped: > >> ? ? ? ? ? ? # do something with e[0], e[1] > > >> That seems to work all right. > > >> Now, the problem occurs when this all is wrapped into an outer loop, such as > > >> for k in [ 'first pass', 'second pass' ]: > >> ? ? for my_item in my_list_grouped: > >> ? ? # bla, the above > > >> To be able to iterate more than once through my_list_grouped, I have > >> to convert it into a list first, so outside all loops, I go like > > >> my_list.sort( key=operator.itemgetter('a') ) > >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > >> my_list_grouped = list( my_list_grouped ) > > >> This, however, makes it impossible to do the inner sort and > >> groupby-operation; you just get the very first element, and that's it. > > >> An example file is attached. > > >> Hints, anyone? > > >> Cheers, > >> Nico > > > Does this example help at all? > > > my_list.sort( key=itemgetter('a','b','c') ) > > for a, a_iter in groupby(my_list, itemgetter('a')): > > ? ?print 'New A', a > > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): > > ? ? ? ?print '\t', 'New B', b > > ? ? ? ?for c, c_iter in groupby(b_iter, itemgetter('c')): > > ? ? ? ? ? ?print '\t'*2, 'New C', c > > ? ? ? ? ? ?for c_data in c_iter: > > ? ? ? ? ? ? ? ?print '\t'*3, a, b, c, c_data > > ? ? ? ? ? ?print '\t'*2, 'End C', c > > ? ? ? ?print '\t', 'End B', b > > ? ?print 'End A', a > > > Jon. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Are you basically after this, then? for a, a_iter in groupby(my_list, itemgetter('a')): print 'New A', a for b, b_iter in groupby(a_iter, itemgetter('b')): b_list = list(b_iter) for p in ['first', 'second']: for b_data in b_list: #whatever... Cos that looks like it could be simplified to (untested) for (a, b), data_iter in groupby(my_list, itemgetter('a','b')): data = list(data) # take copy for pass_ in ['first', 'second']: # do something with data But from my POV, it's almost looking like a 2-tuple key in a defaultdict jobby. Jon. From utente at esempio.net Tue May 4 07:56:43 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 13:56:43 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> Message-ID: <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Stefan Behnel ha scritto: > superpollo, 04.05.2010 13:23: >> Stefan Behnel ha scritto: >>> the main reason why this problem doesn't hurt much in Python >>> is that Python is a dynamic language that can get you extremely far >>> without generating code. It's simply not necessary in most cases, so >>> people don't run into problems with it. >> >> Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) >> [GCC 4.3.3] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> A,B=2,3 >> >>> if A>B: >> ... print A+B >> ... else: >> ... print A**B-B**2 >> ... >> -1 >> >>> A,B=3,2 >> >>> if A>B: >> ... print A+B >> ... else: >> ... print A**B-B**2 >> ... >> 5 >> >> tell me please: how can generate the same output (depending on A and B) >> without control structure? i mean in a natural "pythonic" way... > > The question is: why do you have to generate the above code in the first > place? Isn't a function enough that does the above? of course! *but* if i must generate on-the-fly python code that defines a function i am back again to the problem: def fun(): .... ecc... how can i put *that* on a oneliner? From utente at esempio.net Tue May 4 07:59:46 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 13:59:46 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> Message-ID: <4be00c33$0$1134$4fafbaef@reader3.news.tin.it> Martin P. Hellwig ha scritto: > On 05/04/10 11:28, superpollo wrote: >> Samuel Williams ha scritto: >>> I personally like indentation. >>> >>> I just wonder whether it is an issue that some people will dislike. > >> there might be problems if for example you >> generate code from a one-line template. > > Well a one-line template code generator are great and such, but if the > output should be human readable it is necessary to have at least some > form of mark-up control on it. Like newlines and indentations. or latex markup, in my case... > On the other hand if it is only meant to generate executable code, > generating an interpreted code might not be the best solution for the > actual problem. yes, maybe generating code for a *compiler* might be faster but you must consider overhead due to compilation time, especially if code snippets are sprinkled by the dozen all over the template file. > For the corner cases (I can think of a couple) it is good to know you > can use ';' most of the time. > most but not always as i noted (think about loops or function definition) bye From livibetter at gmail.com Tue May 4 08:02:51 2010 From: livibetter at gmail.com (livibetter) Date: Tue, 4 May 2010 05:02:51 -0700 (PDT) Subject: Ann: Validating Emails and HTTP URLs in Python References: <980e7f0d-d92a-49ae-8f9e-6a3a3a95756b@t21g2000yqg.googlegroups.com> Message-ID: First, it's good to see a library has URL and email validator. But I found there might be a problem in your validator, the problems I found are these URLs: http://example.com/path http://example.com/path) http://example.com/path] http://example.com/path} By my understanding from RFCs, only first two are valid. >>> from lepl.apps.rfc3696 import * >>> v = HttpUrl() >>> v('http://example.com/') True >>> v('http://example.com/path') True >>> v('http://example.com/path)') True >>> v('http://example.com/path]') True >>> v('http://example.com/path}') True You use RFC 3969 [1] to write your code (I read your source code, lepl.apps.rfc3696._HttpUrl()), I think your code should only return True for first case, but all return True. Maybe I use it incorrectly? And I think that has a slight issue because RFC 3969 was written based on RFC 2396 [2], which is obsoleted by RFC 3986 [3]. I never really read RFC 3969, I am not sure if there is problem. But in RFC 3969, it writes The following characters are reserved in many URIs -- they must be used for either their URI-intended purpose or must be encoded. Some particular schemes may either broaden or relax these restrictions (see the following sections for URLs applicable to "web pages" and electronic mail), or apply them only to particular URI component parts. ; / ? : @ & = + $ , ? However in RFC 2396 (the obsoleted RFC), "3.3. Path Component," The path component contains data, specific to the authority (or the scheme if there is no authority component), identifying the resource within the scope of that scheme and authority. path = [ abs_path | opaque_part ] path_segments = segment *( "/" segment ) segment = *pchar *( ";" param ) param = *pchar pchar = unreserved | escaped | ":" | "@" | "&" | "=" | "+" | "$" | "," Here is unreserved of pchar: unreserved = alphanum | mark mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" In RFC 3986, they are a bit different, but my point here is "(" and ")". The Uri from 4Suite return the results I expect: >>> import Ft.Lib.Uri as U >>> U.MatchesUriSyntax('http://example.com/path') True >>> U.MatchesUriSyntax('http://example.com/path)') True >>> U.MatchesUriSyntax('http://example.com/path}') False >>> U.MatchesUriSyntax('http://example.com/path]') False I think you should use (read) RFC 3986 not RFC 3696 for URL validation. One more thing, HttpUrl()'s docstring should s/email/url/. [1]: http://tools.ietf.org/html/rfc3696 [2]: http://tools.ietf.org/html/rfc2396 [3]: http://tools.ietf.org/html/rfc3986 From prologic at shortcircuit.net.au Tue May 4 08:04:19 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 4 May 2010 22:04:19 +1000 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> Message-ID: On Tue, May 4, 2010 at 9:43 PM, Stefan Behnel wrote: >> Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) >> [GCC 4.3.3] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> ?>>> A,B=2,3 >> ?>>> if A>B: >> ... print A+B >> ... else: >> ... print A**B-B**2 >> ... >> -1 >> ?>>> A,B=3,2 >> ?>>> if A>B: >> ... print A+B >> ... else: >> ... print A**B-B**2 >> ... >> 5 >> >> tell me please: how can generate the same output (depending on A and B) >> without control structure? i mean in a natural "pythonic" way... >>> def quadratic(a, b): ... return a + b if a > b else a**b - b**2 ... >>> a, b = 2, 3 >>> print quadratic(a, b) -1 >>> a, b = 3, 2 >>> print quadratic(a, b) 5 >>> --james From prologic at shortcircuit.net.au Tue May 4 08:06:38 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 4 May 2010 22:06:38 +1000 Subject: Teaching Programming In-Reply-To: <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: > of course! *but* if i must generate on-the-fly python code that defines a > function i am back again to the problem: One-liner: $ python Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) [GCC 4.4.1 (CRUX)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a, b = 2, 3 >>> print a + b if a > b else a**b - b**2 -1 >>> a, b = 3, 2 >>> print a + b if a > b else a**b - b**2 5 >>> --James From eckhardt at satorlaser.com Tue May 4 08:09:41 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 04 May 2010 14:09:41 +0200 Subject: itertools: problem with nested groupby, list() References: Message-ID: <5df5b7-g8u.ln1@satorlaser.homedns.org> Nico Schl?mer wrote: > So when I go like > > for item in list: > item[1].sort() > > I actually modify *list*? I didn't realize that; I thought it'd just > be a copy of it. No, I misunderstood your code there. Modifying the objects inside the list is fine, but I don't thing you do that, provided the items in the list don't contain references to the list itself. Good luck! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From e_d_k at yahoo.com Tue May 4 08:15:31 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 05:15:31 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <163888.67952.qm@web58706.mail.re1.yahoo.com> --- On Tue, 5/4/10, Stefan Behnel wrote: > From: Stefan Behnel > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 7:43 AM > superpollo, 04.05.2010 13:23: > > Stefan Behnel ha scritto: > >> the main reason why this problem doesn't hurt much > in Python > >> is that Python is a dynamic language that can get > you extremely far > >> without generating code. It's simply not necessary > in most cases, so > >> people don't run into problems with it. > > > > Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) > > [GCC 4.3.3] on linux2 > > Type "help", "copyright", "credits" or "license" for > more information. > >? >>> A,B=2,3 > >? >>> if A>B: > > ... print A+B > > ... else: > > ... print A**B-B**2 > > ... > > -1 > >? >>> A,B=3,2 > >? >>> if A>B: > > ... print A+B > > ... else: > > ... print A**B-B**2 > > ... > > 5 > > > > tell me please: how can generate the same output > (depending on A and B) > > without control structure? i mean in a natural > "pythonic" way... > > The question is: why do you have to generate the above code > in the first > place? Isn't a function enough that does the above? > > Stefan > > -- > http://mail.python.org/mailman/listinfo/python-list > Just thought I'd add my $0.02 here. I wrote AsciiLitProg (http://asciilitprog.berlios.de/) in Python. It is a literate programming tool. It generates code from a document. It can generate code in any language the author wants. It would have been a LOT easier to write if it did not generate Python code. Python is a great language to write in (although I do wish it did a better job with closures). But it is a PITA to generate code for! -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From benjamin.kaplan at case.edu Tue May 4 08:17:33 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 4 May 2010 08:17:33 -0400 Subject: Teaching Programming In-Reply-To: <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> Message-ID: On Tue, May 4, 2010 at 7:23 AM, superpollo wrote: > Stefan Behnel ha scritto: >> >> superpollo, 04.05.2010 12:28: >>> >>> i think there is an issue if you -- say -- produce python code, from >>> within another programming environment, to be executed on the fly, at >>> least in some instances. there might be problems if for example you >>> generate code from a one-line template. >> >> There are a couple of code generation tools available that you can find on >> PyPI. >> >> However, the main reason why this problem doesn't hurt much in Python is >> that Python is a dynamic language that can get you extremely far without >> generating code. It's simply not necessary in most cases, so people don't >> run into problems with it. >> >> Stefan >> > > Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> A,B=2,3 >>>> if A>B: > ... ? ? print A+B > ... else: > ... ? ? print A**B-B**2 > ... > -1 >>>> A,B=3,2 >>>> if A>B: > ... ? ? print A+B > ... else: > ... ? ? print A**B-B**2 > ... > 5 >>>> > > tell me please: how can generate the same output (depending on A and B) > without control structure? i mean in a natural "pythonic" way... > > bye Well, it requires 2.6 or 3 Python 2.6.5 (r265:79063, Mar 21 2010, 22:38:52) [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import print_function >>> A,B=2,3;print(A+B if A > B else A**B - B**2) -1 >>> A,B=3,2;print(A+B if A > B else A**B - B**2) 5 > > -- > http://mail.python.org/mailman/listinfo/python-list > From utente at esempio.net Tue May 4 08:23:00 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 14:23:00 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4be011a4$0$1121$4fafbaef@reader3.news.tin.it> James Mills ha scritto: > On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: >> of course! *but* if i must generate on-the-fly python code that defines a >> function i am back again to the problem: > > One-liner: > > $ python > Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) > [GCC 4.4.1 (CRUX)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a, b = 2, 3 >>>> print a + b if a > b else a**b - b**2 > -1 >>>> a, b = 3, 2 >>>> print a + b if a > b else a**b - b**2 > 5 > > --James much obliged. From prologic at shortcircuit.net.au Tue May 4 08:24:16 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 4 May 2010 22:24:16 +1000 Subject: python gui In-Reply-To: <2f187732-ae4d-4cfc-8c43-3e4a5cd0166f@b18g2000yqb.googlegroups.com> References: <2f187732-ae4d-4cfc-8c43-3e4a5cd0166f@b18g2000yqb.googlegroups.com> Message-ID: On Tue, May 4, 2010 at 9:26 PM, a wrote: > where's the best online resource for teaching about GUI building? There are many many resources available on the topic. If you simply Google (tm) some of the keywords in your post you'll be presented with a whole smorgasbord of useful resources. --james From stefan_ml at behnel.de Tue May 4 08:33:58 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 14:33:58 +0200 Subject: Teaching Programming In-Reply-To: <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: superpollo, 04.05.2010 13:56: > Stefan Behnel ha scritto: >> The question is: why do you have to generate the above code in the >> first place? Isn't a function enough that does the above? > > of course! *but* if i must generate on-the-fly python code that defines > a function [...] Well, could you provide a use case where you have to generate Python code, and where normally written code with some kind of parametrisation won't work? The only thing that currently comes to my mind is a template compiler that translates a user provided template into an executable Python program. But that should be pretty trivial to do as well. I just remembered this little thing on Fredrik's effbot site, which should help here: http://effbot.org/zone/python-code-generator.htm Stefan From nico.schloemer at gmail.com Tue May 4 08:37:17 2010 From: nico.schloemer at gmail.com (=?ISO-8859-1?Q?Nico_Schl=F6mer?=) Date: Tue, 4 May 2010 14:37:17 +0200 Subject: itertools: problem with nested groupby, list() In-Reply-To: <22a806f2-03a0-4cfa-a73f-b4d4ff582937@g21g2000yqk.googlegroups.com> References: <76fc5fab-9c3b-4aeb-b38d-8ae913822d3a@q32g2000yqb.googlegroups.com> <22a806f2-03a0-4cfa-a73f-b4d4ff582937@g21g2000yqk.googlegroups.com> Message-ID: > Are you basically after this, then? > > for a, a_iter in groupby(my_list, itemgetter('a')): > print 'New A', a > for b, b_iter in groupby(a_iter, itemgetter('b')): > b_list = list(b_iter) > for p in ['first', 'second']: > for b_data in b_list: > #whatever... Yes. Moving the 'first', 'second' operation to the innermost loop works all right, and I guess that's what I'll do. > Cos that looks like it could be simplified to (untested) > for (a, b), data_iter in groupby(my_list, itemgetter('a','b')): > data = list(data) # take copy > for pass_ in ['first', 'second']: > # do something with data Potentially yes, but for now I actually need to do something at "print 'New A', a", so I can't just skip this. Anyway, the above suggestion works well for now. Thanks! --Nico On Tue, May 4, 2010 at 1:52 PM, Jon Clements wrote: > On 4 May, 12:36, Nico Schl?mer wrote: >> > Does this example help at all? >> >> Thanks, that clarified things a lot! >> >> To make it easier, let's just look at 'a' and 'b': >> >> > my_list.sort( key=itemgetter('a','b','c') ) >> > for a, a_iter in groupby(my_list, itemgetter('a')): >> > ? ?print 'New A', a >> > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): >> > ? ? ? ?print '\t', 'New B', b >> > ? ? ? ?for b_data in b_iter: >> > ? ? ? ? ? ?print '\t'*3, a, b, b_data >> > ? ? ? ?print '\t', 'End B', b >> > ? ?print 'End A', a >> >> That works well, and I can wrap the outer loop in another loop without >> problems. What's *not* working, though, is having more than one pass >> on the inner loop, as in >> >> =============================== *snip* =============================== >> my_list.sort( key=itemgetter('a','b','c') ) >> for a, a_iter in groupby(my_list, itemgetter('a')): >> ? ?print 'New A', a >> ? ?for pass in ['first pass', 'second pass']: >> ? ? ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): >> ? ? ? ? ? ?print '\t', 'New B', b >> ? ? ? ? ? ?for b_data in b_iter: >> ? ? ? ? ? ? ? ?print '\t'*3, a, b, b_data >> ? ? ? ? ? ?print '\t', 'End B', b >> ? ? ? ?print 'End A', a >> =============================== *snap* =============================== >> >> I tried working around this by >> >> =============================== *snip* =============================== >> my_list.sort( key=itemgetter('a','b','c') ) >> for a, a_iter in groupby(my_list, itemgetter('a')): >> ? ?print 'New A', a >> ? ?inner_list = ?list( groupby(a_iter, itemgetter('b')) ) >> ? ?for pass in ['first pass', 'second pass']: >> ? ? ? ?for b, b_iter in inner_list: >> ? ? ? ? ? ?print '\t', 'New B', b >> ? ? ? ? ? ?for b_data in b_iter: >> ? ? ? ? ? ? ? ?print '\t'*3, a, b, b_data >> ? ? ? ? ? ?print '\t', 'End B', b >> ? ? ? ?print 'End A', a >> =============================== *snap* =============================== >> >> which don't work either, and I don't understand why. -- I'll look at >> Uli's comments. >> >> Cheers, >> Nico >> >> On Tue, May 4, 2010 at 1:08 PM, Jon Clements wrote: >> > On 4 May, 11:10, Nico Schl?mer wrote: >> >> Hi, >> >> >> I ran into a bit of an unexpected issue here with itertools, and I >> >> need to say that I discovered itertools only recently, so maybe my way >> >> of approaching the problem is "not what I want to do". >> >> >> Anyway, the problem is the following: >> >> I have a list of dictionaries, something like >> >> >> [ { "a": 1, "b": 1, "c": 3 }, >> >> ? { "a": 1, "b": 1, "c": 4 }, >> >> ? ... >> >> ] >> >> >> and I'd like to iterate through all items with, e.g., "a":1. What I do >> >> is sort and then groupby, >> >> >> my_list.sort( key=operator.itemgetter('a') ) >> >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> >> >> and then just very simply iterate over my_list_grouped, >> >> >> for my_item in my_list_grouped: >> >> ? ? # do something with my_item[0], my_item[1] >> >> >> Now, inside this loop I'd like to again iterate over all items with >> >> the same 'b'-value -- no problem, just do the above inside the loop: >> >> >> for my_item in my_list_grouped: >> >> ? ? ? ? # group by keyword "b" >> >> ? ? ? ? my_list2 = list( my_item[1] ) >> >> ? ? ? ? my_list2.sort( key=operator.itemgetter('b') ) >> >> ? ? ? ? my_list_grouped = itertools.groupby( my_list2, >> >> operator.itemgetter('b') ) >> >> ? ? ? ? for e in my_list_grouped: >> >> ? ? ? ? ? ? # do something with e[0], e[1] >> >> >> That seems to work all right. >> >> >> Now, the problem occurs when this all is wrapped into an outer loop, such as >> >> >> for k in [ 'first pass', 'second pass' ]: >> >> ? ? for my_item in my_list_grouped: >> >> ? ? # bla, the above >> >> >> To be able to iterate more than once through my_list_grouped, I have >> >> to convert it into a list first, so outside all loops, I go like >> >> >> my_list.sort( key=operator.itemgetter('a') ) >> >> my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) >> >> my_list_grouped = list( my_list_grouped ) >> >> >> This, however, makes it impossible to do the inner sort and >> >> groupby-operation; you just get the very first element, and that's it. >> >> >> An example file is attached. >> >> >> Hints, anyone? >> >> >> Cheers, >> >> Nico >> >> > Does this example help at all? >> >> > my_list.sort( key=itemgetter('a','b','c') ) >> > for a, a_iter in groupby(my_list, itemgetter('a')): >> > ? ?print 'New A', a >> > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): >> > ? ? ? ?print '\t', 'New B', b >> > ? ? ? ?for c, c_iter in groupby(b_iter, itemgetter('c')): >> > ? ? ? ? ? ?print '\t'*2, 'New C', c >> > ? ? ? ? ? ?for c_data in c_iter: >> > ? ? ? ? ? ? ? ?print '\t'*3, a, b, c, c_data >> > ? ? ? ? ? ?print '\t'*2, 'End C', c >> > ? ? ? ?print '\t', 'End B', b >> > ? ?print 'End A', a >> >> > Jon. >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> > > Are you basically after this, then? > > for a, a_iter in groupby(my_list, itemgetter('a')): > ? ?print 'New A', a > ? ?for b, b_iter in groupby(a_iter, itemgetter('b')): > ? ? ? ?b_list = list(b_iter) > ? ? ? ?for p in ['first', 'second']: > ? ? ? ? ? ?for b_data in b_list: > ? ? ? ? ? ? ? ?#whatever... > > Cos that looks like it could be simplified to (untested) > > for (a, b), data_iter in groupby(my_list, itemgetter('a','b')): > ? data = list(data) # take copy > ? for pass_ in ['first', 'second']: > ? ? ?# do something with data > > But from my POV, it's almost looking like a 2-tuple key in a > defaultdict jobby. > > Jon. > -- > http://mail.python.org/mailman/listinfo/python-list > From stefan_ml at behnel.de Tue May 4 08:40:07 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 14:40:07 +0200 Subject: Teaching Programming In-Reply-To: <163888.67952.qm@web58706.mail.re1.yahoo.com> References: <163888.67952.qm@web58706.mail.re1.yahoo.com> Message-ID: Ed Keith, 04.05.2010 14:15: > I wrote AsciiLitProg (http://asciilitprog.berlios.de/) in Python. It is > a literate programming tool. It generates code from a document. It can > generate code in any language the author wants. It would have been a LOT > easier to write if it did not generate Python code. > > Python is a great language to write in (although I do wish it did a > better job with closures). But it is a PITA to generate code for! Interesting. Could you elaborate a bit? Could you give a short example of what kind of document text you translate into what kind of Python code, and what the problems were that you faced in doing so? Stefan From utente at esempio.net Tue May 4 08:46:52 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 14:46:52 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> Stefan Behnel ha scritto: > superpollo, 04.05.2010 13:56: >> Stefan Behnel ha scritto: >>> The question is: why do you have to generate the above code in the >>> first place? Isn't a function enough that does the above? >> >> of course! *but* if i must generate on-the-fly python code that defines >> a function [...] > > Well, could you provide a use case where you have to generate Python > code, and where normally written code with some kind of parametrisation > won't work? i see your point, and mr mills gave me hints as to how to attack some of my problems in such a fashion. > The only thing that currently comes to my mind is a template compiler > that translates a user provided template into an executable Python > program. But that should be pretty trivial to do as well. I just > remembered this little thing on Fredrik's effbot site, which should help > here: > > http://effbot.org/zone/python-code-generator.htm very good. i will most certainly give it a try. but i do not think i can use it myself, since my template system wants the input to generate the code to stay on a single line ( don't ask :-( ) bye From bazwal at ftml.net Tue May 4 08:53:40 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 04 May 2010 13:53:40 +0100 Subject: strange interaction between open and cwd In-Reply-To: <87d3xch3la.fsf@benfinney.id.au> References: <4BDEC4A5.5070801@ftml.net> <87d3xch3la.fsf@benfinney.id.au> Message-ID: <4BE018D4.8060808@ftml.net> On 04/05/10 02:12, Ben Finney wrote: > Baz Walter writes: > >> On 03/05/10 18:41, Grant Edwards wrote: >>> Firstly, a file may have any number of paths (including 0). >> >> yes, of course. i forgot about hard links > > Rather, you forgot that *every* entry that references a file is a hard > link. i'm not a frequent poster on this list, but i'm aware of it's reputation for pointless pedantry ;-) but what the heck, when in rome... note that i said hard links (plural) - i think a more generous reader would assume i was referring to additional hard links. From C.Sanders at DeleteThis.Bom.GOV.AU Tue May 4 09:02:29 2010 From: C.Sanders at DeleteThis.Bom.GOV.AU (Charles) Date: Tue, 4 May 2010 23:02:29 +1000 Subject: [OT] strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> <84a1mcFfnpU1@mid.individual.net> Message-ID: <4be01ae8$0$45294$c30e37c6@exi-reader.telstra.net> "Gregory Ewing" wrote in message news:84a1mcFfnpU1 at mid.individual.net... > Charles wrote: > >> In the OP's case, references to the directory have been removed >> from the file system, but his process still has the current working >> directory reference to it, so it has not actually been deleted. >> When he opens "../abc.txt", the OS searches the current directory >> for ".." and finds the inode for /home/baz/tmp, > > This doesn't seem to be quite correct. An experiment I just did > reveals that the link count on the parent directory goes down by > one when the current directory is deleted, suggesting that the .. > link has actually been removed... yet it still works! > > I think what must be happening is that the kernel is maintaining > an in-memory reference to the parent directory, and treating ".." > as a special case when looking up a name. > > (This probably shouldn't be too surprising, because ".." is special > in another way as well -- at the root of a mounted file system, it > leads to the parent of the mount point, even though the actual ".." > link on disk just points back to the same directory. Probably it > simplifies the name lookup logic to always treat it specially.) I am by no means an expert in this area, but what I think happens (and I may well be wrong) is that the directory is deleted on the file system. The link from the parent is removed, and the parent's link count is decremented, as you observed, but the directory itself is still intact with it's original contents, including the "." and ".." names and associated inode numbers. Unix does not normally zero out files on deletion - the file's blocks usually retain their contents, and I would not expect directories to be a special case. The blocks from the directory will be re-cycled when the memory reference (the process's current working directory) disappears, but until then the directory and its contents are still accessible via the process's current directory. This is all supposition, and based on distant memories form the mid 1980s, I could very well be wrong. Charles From bazwal at ftml.net Tue May 4 09:03:55 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 04 May 2010 14:03:55 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> Message-ID: <4BE01B3B.7010901@ftml.net> On 04/05/10 03:19, Grant Edwards wrote: > On 2010-05-03, Baz Walter wrote: >> On 03/05/10 19:12, Grant Edwards wrote: >>> Even though the user provided a legal and openable path? >> >> that sounds like an operational definition to me: what's the >> difference between "legal" and "openable"? > > Legal as in meets the syntactic requirements for a path (not sure if > there really are any requirements other than it being a > null-terminated string). Openable meaning that it denotes a path file > that exists and for which the caller has read permissions on the file > and execute premissions on the directories within the path. openable is not the same as accessible. a file can still openable, even though a user may not have permission to access it. a better definition of "legal path" might be whether any useful information can be gained from a stat() call on it. From stefan_ml at behnel.de Tue May 4 09:09:29 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 15:09:29 +0200 Subject: Teaching Programming In-Reply-To: <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> Message-ID: superpollo, 04.05.2010 14:46: > my template system wants > the input to generate the code to stay on a single line ( don't ask :-( ) I hope you don't mind if I still ask. What are you generating and for what templating system? Stefan From utente at esempio.net Tue May 4 09:15:31 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 15:15:31 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> Message-ID: <4be01df4$0$1134$4fafbaef@reader3.news.tin.it> Stefan Behnel ha scritto: > superpollo, 04.05.2010 14:46: >> my template system wants >> the input to generate the code to stay on a single line ( don't ask :-( ) > > I hope you don't mind if I still ask. What are you generating and for > what templating system? ok, since you asked for it, prepare yourself for a bit of a horror story ;-) i will answer in my next post bye From e_d_k at yahoo.com Tue May 4 09:19:38 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 06:19:38 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <121607.77893.qm@web58702.mail.re1.yahoo.com> --- On Tue, 5/4/10, Stefan Behnel wrote: > From: Stefan Behnel > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 8:40 AM > Ed Keith, 04.05.2010 14:15: > > I wrote AsciiLitProg (http://asciilitprog.berlios.de/) in Python. It is > > a literate programming tool. It generates code from a > document. It can > > generate code in any language the author wants. It > would have been a LOT > > easier to write if it did not generate Python code. > > > > Python is a great language to write in (although I do > wish it did a > > better job with closures). But it is a PITA to > generate code for! > > Interesting. Could you elaborate a bit? Could you give a > short example of what kind of document text you translate > into what kind of Python code, and what the problems were > that you faced in doing so? > > Stefan > > -- http://mail.python.org/mailman/listinfo/python-list > The program is written using itself. If you click on the link above you will see an HTML file that fully describes the program. That HTML is generated from an AcsiiDoc (http://www.methods.co.nz/asciidoc/) document. The same document is used to generate the python code that it describes. The source document, and the generated HTML and Python code are all avalable at BerliOS (http://developer.berlios.de/projects/asciilitprog/). For more information on Literate Programming in general see the following links. http://www.literateprogramming.com/ http://en.wikipedia.org/wiki/Literate_programming http://en.literateprograms.org/LiteratePrograms:Welcome -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From ben+python at benfinney.id.au Tue May 4 09:23:16 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 04 May 2010 23:23:16 +1000 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <87d3xch3la.fsf@benfinney.id.au> Message-ID: <87vdb3g5rv.fsf@benfinney.id.au> Baz Walter writes: > On 04/05/10 02:12, Ben Finney wrote: > > Baz Walter writes: > >> yes, of course. i forgot about hard links > > > > Rather, you forgot that *every* entry that references a file is a > > hard link. > > i'm not a frequent poster on this list, but i'm aware of it's > reputation for pointless pedantry ;-) Only pointless if you view this as a conversation entirely for the benefit of you and I. I, on the other hand, am trying to make this useful to whoever may read it now and in the future. > note that i said hard links (plural) - i think a more generous reader > would assume i was referring to additional hard links. The point, though, was that this is normal operation, rather than exceptional. Files have zero or more hard links, and ?this file has exactly one hard link? is merely a common case among that spectrum. I'm glad you already knew this, and hope you can appreciate that it's better explicit than implicit. -- \ ?The difference between religions and cults is determined by | `\ how much real estate is owned.? ?Frank Zappa | _o__) | Ben Finney From nobody at nowhere.com Tue May 4 09:29:20 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 04 May 2010 14:29:20 +0100 Subject: [OT] strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> <84a1mcFfnpU1@mid.individual.net> <4be01ae8$0$45294$c30e37c6@exi-reader.telstra.net> Message-ID: On Tue, 04 May 2010 23:02:29 +1000, Charles wrote: > I am by no means an expert in this area, but what I think happens (and I > may well be wrong) is that the directory is deleted on the file system. > The link from the parent is removed, and the parent's link count is > decremented, as you observed, but the directory itself is still intact > with it's original contents, including the "." and ".." names and > associated inode numbers. Unix does not normally zero out files on > deletion - the file's blocks usually retain their contents, and I would > not expect directories to be a special case. You are correct. System calls don't "delete" inodes (files, directories, etc), they "unlink" them. Deletion occurs when the inode's link count reaches zero and no process holds a reference to the inode (a reference could be a descriptor, or the process' cwd, chroot directory, or an mmap()d file, etc). IOW, reference-counted garbage collection. From bazwal at ftml.net Tue May 4 09:36:06 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 04 May 2010 14:36:06 +0100 Subject: strange interaction between open and cwd In-Reply-To: <84a3a5Fp5nU1@mid.individual.net> References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: <4BE022C6.8070600@ftml.net> On 04/05/10 09:23, Gregory Ewing wrote: > Grant Edwards wrote: > >> In your example, it's simply not possible to determine the file's >> absolute path within the filesystem given the relative path you >> provided. > > Actually, I think it *is* theoretically possible to find an > absolute path for the file in this case. > > I suspect that what realpath() is doing for a relative path is > something like: > > 1. Use getcwd() to find an absolute path for the current > directory. > 2. Chop off a trailing pathname component for each ".." > on the front of the original path. > 3. Tack the filename on the end of what's left. > > Step 1 fails because the current directory no longer has > an absolute pathname -- specifically, it has no name in > what used to be its parent directory. > > What realpath() is failing to realise is that it doesn't > actually need to know the full path of the current directory, > only of its parent directory, which is still reachable via > ".." (if it weren't, the file wouldn't be reachable either, > and we wouldn't be having this discussion). > > A smarter version of realpath() wouldn't try to find the > path of the *current* directory, but would follow the > ".." links until it got to a directory that it did need to > know an absolute path for, and start with that. > > Unfortunately, there is no C stdlib routine that does the > equivalent of getcwd() for an arbitrary directory, so > this would require realpath() to duplicate much of > getcwd()'s functionality, which is probably why it's > done the way it is. actually, this part of the problem can be achieved using pure python. given the basename of a file, all you have to do is use os.stat and os.listdir to recursively climb up the tree and build a dirpath for it. start by doing os.stat(basename) to make sure you have a legal file in the current directory; then use os.stat('..') to get the parent directory inode, and stat each of the items in os.listdir('../..') to find a name matching that inode etc. (note that the possibility of hard-linked directories doesn't really spoil this - for relative paths, we don't care exactly which absolute path is found). this will work so long as the file is in a part of the filesystem that can be traversed from the current directory to the root. what i'm not sure about is whether it's possible to cross filesystem boundaries using this kind of technique. From nobody at nowhere.com Tue May 4 09:39:04 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 04 May 2010 14:39:04 +0100 Subject: strange interaction between open and cwd References: <4BDEDC73.1020301@ftml.net> <84a2djFjqrU1@mid.individual.net> Message-ID: On Tue, 04 May 2010 20:08:36 +1200, Gregory Ewing wrote: >> except that Python objects can form a generalized graph, and Unix >> filesystems are constrained to be a tree. > > Actually I believe that root is allowed to create arbitrary hard links to > directories in Unix, so it's possible to turn the file system in to a > general graph. It's highly unrecommended, though, because it confuses the > heck out of programs that recursively traverse directories (which is why > only root is allowed to do it). The 1980s are over already ;) I don't know of any modern Unix which allows creating additional hard links to directories (even for root). It creates too many problems, and isn't necessary if you have symlinks. If you want to turn the filesystem into a cyclic graph, you typically need to bypass the kernel's filesystem interface and modify the block device directly (e.g. with debugfs). If fsck finds out, it's likely to fix it. From a_jtim at bellsouth.net Tue May 4 09:43:32 2010 From: a_jtim at bellsouth.net (Tim Arnold) Date: Tue, 4 May 2010 06:43:32 -0700 (PDT) Subject: design question References: <4de9fbb8-c1b9-44eb-b8d5-2c57ea372d9b@n15g2000yqf.googlegroups.com> <4bdfceba$0$9110$426a34cc@news.free.fr> Message-ID: <259ba42e-471c-4801-9f1d-28f869c60dee@r6g2000vbh.googlegroups.com> On May 4, 3:39?am, Bruno Desthuilliers wrote: > Alf P. Steinbach a ?crit : > (snip) > > > Re efficiency it seems to be a complete non-issue, but correctness is > > much more important: is there any way that the config details can be > > (inadvertently) changed while the build is going on? > > +1 Thanks everyone, I'm new at this type of development so it helps to get input from folks who know what they're talking about. I'm just been coding and doing what is right in my own eyes... There is almost no way for the configuration to change during a build, so it looks like I was just worrying about something that doesn't need worry. Now on to the things that do! thanks again, --Tim From bazwal at ftml.net Tue May 4 09:48:28 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 04 May 2010 14:48:28 +0100 Subject: strange interaction between open and cwd In-Reply-To: <84a2djFjqrU1@mid.individual.net> References: <4BDEDC73.1020301@ftml.net> <84a2djFjqrU1@mid.individual.net> Message-ID: <4BE025AC.7070309@ftml.net> On 04/05/10 09:08, Gregory Ewing wrote: > Grant Edwards wrote: > >> except that Python objects can form a generalized graph, and Unix >> filesystems are constrained to be a tree. > > Actually I believe that root is allowed to create arbitrary > hard links to directories in Unix, so it's possible to turn > the file system in to a general graph. It's highly > unrecommended, though, because it confuses the heck out of > programs that recursively traverse directories (which is > why only root is allowed to do it). i think there are versions of mac osx that use hard-linked directories in their backup systems. From nobody at nowhere.com Tue May 4 09:48:34 2010 From: nobody at nowhere.com (Nobody) Date: Tue, 04 May 2010 14:48:34 +0100 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> Message-ID: On Mon, 03 May 2010 06:18:55 -0700, Chris Rebert wrote: >> but how can python determine the >> parent directory of a directory that no longer exists? > > Whether or not /home/baz/tmp/xxx/ exists, we know from the very structure > and properties of directory paths that its parent directory is, *by > definition*, /home/baz/tmp/ (just chop off everything after the > second-to-last slash). Not necessarily. There are two common interpretations for the concept of a "parent directory". One is the directory referenced by removing the last component from the (normalised) path, the other is the directory referenced by appending ".." to the path. The two don't necessarily refer to the same directory if the last component is a symlink (or an additional hard link, on platforms which allow creating additional hard links to directories). For the current directory[1], or a directory referenced by a descriptor rather than a path, the latter definition has to be used, as there is no path to manipulate. [1] And also for e.g. "./../..". From wuwei23 at gmail.com Tue May 4 10:06:08 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 May 2010 07:06:08 -0700 (PDT) Subject: Teaching Programming References: Message-ID: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> Ed Keith wrote: > For more information on Literate Programming in general see the following links. None of which address the question of what you found problematic about generating Python code. Was it issues with indentation? From __peter__ at web.de Tue May 4 10:10:55 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 May 2010 16:10:55 +0200 Subject: itertools: problem with nested groupby, list() References: Message-ID: Nico Schl?mer wrote: > Hi, > > I ran into a bit of an unexpected issue here with itertools, and I > need to say that I discovered itertools only recently, so maybe my way > of approaching the problem is "not what I want to do". > > Anyway, the problem is the following: > I have a list of dictionaries, something like > > [ { "a": 1, "b": 1, "c": 3 }, > { "a": 1, "b": 1, "c": 4 }, > ... > ] > > and I'd like to iterate through all items with, e.g., "a":1. What I do > is sort and then groupby, > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > > and then just very simply iterate over my_list_grouped, > > for my_item in my_list_grouped: > # do something with my_item[0], my_item[1] > > Now, inside this loop I'd like to again iterate over all items with > the same 'b'-value -- no problem, just do the above inside the loop: > > for my_item in my_list_grouped: > # group by keyword "b" > my_list2 = list( my_item[1] ) > my_list2.sort( key=operator.itemgetter('b') ) > my_list_grouped = itertools.groupby( my_list2, > operator.itemgetter('b') ) > for e in my_list_grouped: > # do something with e[0], e[1] > > That seems to work all right. > > Now, the problem occurs when this all is wrapped into an outer loop, such > as > > for k in [ 'first pass', 'second pass' ]: > for my_item in my_list_grouped: > # bla, the above > > To be able to iterate more than once through my_list_grouped, I have > to convert it into a list first, so outside all loops, I go like > > my_list.sort( key=operator.itemgetter('a') ) > my_list_grouped = itertools.groupby( my_list, operator.itemgetter('a') ) > my_list_grouped = list( my_list_grouped ) > > This, however, makes it impossible to do the inner sort and > groupby-operation; you just get the very first element, and that's it. > > An example file is attached. > > Hints, anyone? If you want a reusable copy of a groupby(...) it is not enough to convert it to a list as a whole: >>> from itertools import groupby >>> from operator import itemgetter >>> items = [(1,1), (1,2), (1,3), (2,1), (2,2)] >>> grouped_items = list(groupby(items, key=itemgetter(0))) # WRONG >>> for run in 1, 2: ... print "run", run ... for k, g in grouped_items: ... print k, list(g) ... run 1 1 [] 2 [(2, 2)] run 2 1 [] 2 [] Instead, you have to process the groups, too: >>> grouped_items = [(k, list(g)) for k, g in groupby(items, key=itemgetter(0))] >>> for run in 1, 2: ... print "run", run ... for k, g in grouped_items: ... print k, list(g) ... run 1 1 [(1, 1), (1, 2), (1, 3)] 2 [(2, 1), (2, 2)] run 2 1 [(1, 1), (1, 2), (1, 3)] 2 [(2, 1), (2, 2)] But usually you don't bother and just run groupby() twice: >>> for run in 1, 2: ... print "run", run ... for k, g in groupby(items, key=itemgetter(0)): ... print k, list(g) ... run 1 1 [(1, 1), (1, 2), (1, 3)] 2 [(2, 1), (2, 2)] run 2 1 [(1, 1), (1, 2), (1, 3)] 2 [(2, 1), (2, 2)] The only caveat then is that list(items) == list(items) must hold. Peter From wuwei23 at gmail.com Tue May 4 10:11:08 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 May 2010 07:11:08 -0700 (PDT) Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: TomF wrote: > I'm interested in improving my python design by studying a large, > well-designed codebase. ?Someone (not a python programmer) suggested > Django. ?I realize that Django is popular, but can someone comment on > whether its code is well-designed and worth studying? Here's a viewpoint that says no: http://mockit.blogspot.com/2010/04/mess-djangos-in.html There's a lot of good counterpoint in the comments too. (I also think there's value to be gained in studying _bad_ code, too...) From Ron.Barak at lsi.com Tue May 4 10:11:17 2010 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 4 May 2010 15:11:17 +0100 Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? In-Reply-To: References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6A3B87357@enbmail01.lsi.com> > -----Original Message----- > From: Stefan Behnel [mailto:stefan_ml at behnel.de] > Sent: Tuesday, May 04, 2010 10:24 AM > To: python-list at python.org > Subject: Re: How to get xml.etree.ElementTree not bomb on > invalid characters in XML file ? > > Barak, Ron, 04.05.2010 09:01: > > I'm parsing XML files using ElementTree from xml.etree (see code > > below (and attached xml_parse_example.py)). > > > > However, I'm coming across input XML files (attached an example: > > tmp.xml) which include invalid characters, that produce the > following > > traceback: > > > > $ python xml_parse_example.py > > Traceback (most recent call last): > > xml.parsers.expat.ExpatError: not well-formed (invalid > token): line 6, > > column 34 > > I hope you are aware that this means that the input you are > parsing is not XML. It's best to reject the file and tell the > producers that they are writing broken output files. You > should always fix the source, instead of trying to make sense > out of broken input in fragile ways. > > > > I read the documentation for xml.etree.ElementTree and see > that it may > > take an optional parser parameter, but I don't know what > this parser > > should be - to ignore the invalid characters. > > > > Could you suggest a way to call ElementTree, so it won't > bomb on these > > invalid characters ? > > No. The parser in lxml.etree has a 'recover' option that lets > it try to recover from input errors, but in general, XML > parsers are required to reject non well-formed input. > > Stefan > > > Hi Stefan, The XML file seems to be valid XML (all XML viewers I tried were able to read it). You can verify this by trying to read the XML example I attached to the original message (attached again here). Actually, when trying to view the file with an XML viewer, these offensive characters are not shown. It's just that some of the fields include characters that the parser used by ElementTree seems to chock on. Bye, Ron. -------------- next part -------------- A non-text attachment was scrubbed... Name: tmp_small.xml Type: application/xml Size: 637 bytes Desc: tmp_small.xml URL: From mkiever at Pirx.sirius.org Tue May 4 10:17:06 2010 From: mkiever at Pirx.sirius.org (Matthias Kievernagel) Date: Tue, 4 May 2010 14:17:06 +0000 (UTC) Subject: py3 tkinter acceps bytes. why? Message-ID: From: Matthias Kievernagel Subject: py3 tkinter acceps bytes. why? Newsgroups: comp.lang.python Summary: Keywords: In a recent thread named "py3 tkinter Text accepts what bytes?" (google groups link: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b75ed69f4e81b202/e2aff9ddd62d210c?lnk=raot) I asked what kinds of bytes are accepted as tkinter parameters. I still wonder why they are accepted at all. Does anyone know a reason for this or has a link to some relevant discussion? Thanks for any hint, Matthias Kievernagel From e_d_k at yahoo.com Tue May 4 10:21:29 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 07:21:29 -0700 (PDT) Subject: Teaching Programming In-Reply-To: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> Message-ID: <952067.92151.qm@web58703.mail.re1.yahoo.com> --- On Tue, 5/4/10, alex23 wrote: > From: alex23 > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 10:06 AM > Ed Keith > wrote: > > For more information on Literate Programming in > general see the following links. > > None of which address the question of what you found > problematic about > generating Python code. Was it issues with indentation? > > > -- > http://mail.python.org/mailman/listinfo/python-list > Yes, the problem was indentation. To deal with indentation I had to 1) keep track of indentation of all chunks of code embedded in the document and indent inserted chunks to the sum of all the indentation of the enclosing chunks. and 2) expand all tabls to spaces and allow the user to set the tab expansion size from the command line. Fortunately Python provides good support for this. Neither of these problems exist in languages that are not indention sensitive. Tabs are always a problem when writing Python. I get around this problem by setting my text editor to expand all tabs with spaces when editing Python, but I have had problems when coworkers have not done this. Don't get me wrong, I love working in Python. It is one of my favorite languages, but it, like all other languages, is not perfect. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From Michael.Coll-Barth at VerizonWireless.com Tue May 4 10:23:53 2010 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Tue, 4 May 2010 10:23:53 -0400 Subject: Django as exemplary design In-Reply-To: References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <20100504143508.07C19C70A@mail.python.org> > From: alex23 > (I also think there's value to be gained in studying _bad_ code, > too...) Oh, very true. And not just true for python. But, only if an 'expoert' points out why it is bad and provides an alternative. And saying things like, "it isn't pyhonic" or that such and such is a more "pythonic way" is NOT helpful. From prologic at shortcircuit.net.au Tue May 4 10:35:18 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 5 May 2010 00:35:18 +1000 Subject: Teaching Programming In-Reply-To: <952067.92151.qm@web58703.mail.re1.yahoo.com> References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> Message-ID: On Wed, May 5, 2010 at 12:21 AM, Ed Keith wrote: > To deal with indentation I had to > > ? 1) keep track of indentation of all chunks of code embedded in the > ? ? ?document and indent inserted chunks to the sum of all the > ? ? ?indentation of the enclosing chunks. In my experience of non-indentation sensitive languages such as C-class (curly braces) it's just as hard to keep track of opening and closing braces. --James From bazwal at ftml.net Tue May 4 10:38:23 2010 From: bazwal at ftml.net (Baz Walter) Date: Tue, 04 May 2010 15:38:23 +0100 Subject: [OT] strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <4BDF0BBB.1080009@ftml.net> <4bdf676b$0$45279$c30e37c6@exi-reader.telstra.net> Message-ID: <4BE0315F.6090607@ftml.net> On 04/05/10 03:25, Grant Edwards wrote: > On 2010-05-04, Charles wrote: > >>> I don't see how it's inelegant at all. Perhaps it's >>> counter-intuitive if you don't understand how a Unix filesystem >>> works, but the underlying filesystem model is very simple, regular, >>> and elegant. >>> >>>> but probably makes some bit of the OS's job slightly easier and is >>>> usually good enough in practice. Pragmatism is a bitch sometimes. :-) >>> >> >> I agree that the Unix file system is quite elegant, but can be >> counter-intuitive for people who are used to the "one file, one name" >> paradigm. > > I guess I've been using Unix for too long (almost 30 years). I don't > think I was consciously aware of a "one file, one name" paradigm. Is > that a characteristic of Dos, Windows or Mac filesystems? > >> [...] > >> In the OP's case, references to the directory have been removed from >> the file system, but his process still has the current working >> directory reference to it, so it has not actually been deleted. When >> he opens "../abc.txt", the OS searches the current directory for ".." >> and finds the inode for /home/baz/tmp, then searches that directory >> (/home/baz/tmp) for abc.txt and finds it. > > Exactly. I probably should have taken the time to explain that as > well as you did. One forgets that there are a log of new Unix users > who've never been taught how the filesystem works. actually, what i failed to grok is that whatever '..' refers to is all that is needed to find the file 'abc.txt' *even if the current directory has been deleted*. an absolute path just isn't needed. this has really got nothing to do with how unix filesystems work per se or "one file, one name", but more to do with simple reference counting. when i mentioned in my original post how windows handles attempts to delete the cwd differently, i should have put two and two together and figured this all out for myself. but i don't think it's immediately obvious what the consequences of (re)moving the cwd are, even if you've been using unix filesystems for a while. in know for a fact that i have used several linux programs in the past that didn't handle this possiblity gracefully, so it's not just new users that can be caught out by this. From invalid at invalid.invalid Tue May 4 10:55:52 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 4 May 2010 14:55:52 +0000 (UTC) Subject: strange interaction between open and cwd References: <4BDEDC73.1020301@ftml.net> <84a2djFjqrU1@mid.individual.net> Message-ID: On 2010-05-04, Gregory Ewing wrote: > Grant Edwards wrote: > >> except that Python objects can form a generalized graph, and Unix >> filesystems are constrained to be a tree. > > Actually I believe that root is allowed to create arbitrary > hard links to directories in Unix, I know that used to be the case in SunOS (as I found out the hard way), but I've been told by Solaris experts that it is no longer allowed. I was also under the impression that it wasn't allowed in Linux, but I've never tried it. According the the Linux ln (1) man page: -d, -F, --directory allow the superuser to attempt to hard link directories (note: will probably fail due to system restrictions, even for the superuser) > so it's possible to turn the file system in to a general graph. It's > highly unrecommended, though, because it confuses the heck out of > programs that recursively traverse directories (which is why only > root is allowed to do it). It sure caused trouble when I did it on a SunOS system back in the day (1990 or thereabouts). -- Grant Edwards grant.b.edwards Yow! I feel like I'm at in a Toilet Bowl with a gmail.com thumbtack in my forehead!! From andreengels at gmail.com Tue May 4 11:00:11 2010 From: andreengels at gmail.com (Andre Engels) Date: Tue, 4 May 2010 17:00:11 +0200 Subject: Teaching Programming In-Reply-To: References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> Message-ID: On Tue, May 4, 2010 at 4:35 PM, James Mills wrote: > On Wed, May 5, 2010 at 12:21 AM, Ed Keith wrote: >> To deal with indentation I had to >> >> ? 1) keep track of indentation of all chunks of code embedded in the >> ? ? ?document and indent inserted chunks to the sum of all the >> ? ? ?indentation of the enclosing chunks. > > In my experience of non-indentation sensitive languages > such as C-class (curly braces) it's just as hard to keep track > of opening and closing braces. Although I have little or no experience with this, I still dare to say that I don't agree. The difference is that in C you do not _need_ to know where in the braces-defined hierarchy you are. You just embed or change a piece of code at the right location. In Python however you _do_ need to know how far your code is to be indented. -- Andr? Engels, andreengels at gmail.com From e_d_k at yahoo.com Tue May 4 11:11:20 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 08:11:20 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <915747.23422.qm@web58705.mail.re1.yahoo.com> --- On Tue, 5/4/10, James Mills wrote: > From: James Mills > Subject: Re: Teaching Programming > To: "python list" > Date: Tuesday, May 4, 2010, 10:35 AM > On Wed, May 5, 2010 at 12:21 AM, Ed > Keith > wrote: > > To deal with indentation I had to > > > > ? 1) keep track of indentation of all chunks of code > embedded in the > > ? ? ?document and indent inserted chunks to the sum > of all the > > ? ? ?indentation of the enclosing chunks. > > In my experience of non-indentation sensitive languages > such as C-class (curly braces) it's just as hard to keep > track > of opening and closing braces. > > --James > -- > http://mail.python.org/mailman/listinfo/python-list > Not in this case, because the user is required to include all text of the program in the chunks, the tools does not generate any text, It only needs to generate white space if the language is white space sensitive. I can see how it could be a problem in other cases. In the interest of completeness, I should mention that I had to take care not to introduce extraneous line breaks for languages that are sensitive to them. It is much easier to generate code for languages that are completely white space agnostic. I actually find the fact that I need to think about where I can, and where I can not, break a line to be a bigger problem when write code, than keeping track of indentation level. And Python is not the only language that has this problem. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From e_d_k at yahoo.com Tue May 4 11:14:57 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 08:14:57 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <472414.98152.qm@web58708.mail.re1.yahoo.com> --- On Tue, 5/4/10, Andre Engels wrote: > From: Andre Engels > Subject: Re: Teaching Programming > To: "James Mills" > Cc: "python list" > Date: Tuesday, May 4, 2010, 11:00 AM > On Tue, May 4, 2010 at 4:35 PM, James > Mills > > wrote: > > On Wed, May 5, 2010 at 12:21 AM, Ed Keith > wrote: > >> To deal with indentation I had to > >> > >> ? 1) keep track of indentation of all chunks of > code embedded in the > >> ? ? ?document and indent inserted chunks to the > sum of all the > >> ? ? ?indentation of the enclosing chunks. > > > > In my experience of non-indentation sensitive > languages > > such as C-class (curly braces) it's just as hard to > keep track > > of opening and closing braces. > > Although I have little or no experience with this, I still > dare to say > that I don't agree. The difference is that in C you do not > _need_ to > know where in the braces-defined hierarchy you are. You > just embed or > change a piece of code at the right location. In Python > however you > _do_ need to know how far your code is to be indented. > > For a programmer, it is harder to keep track of braced. For a code generator, it is harder to keep track of indentation. It is a matter of which you are more interested in catering to. Python is easier to write, C is easier to generate. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From ethan at stoneleaf.us Tue May 4 11:28:08 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 04 May 2010 08:28:08 -0700 Subject: Teaching Programming In-Reply-To: References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> Message-ID: <4BE03D08.1080108@stoneleaf.us> Andre Engels wrote: > On Tue, May 4, 2010 at 4:35 PM, James Mills > wrote: >> On Wed, May 5, 2010 at 12:21 AM, Ed Keith wrote: >>> To deal with indentation I had to >>> >>> 1) keep track of indentation of all chunks of code embedded in the >>> document and indent inserted chunks to the sum of all the >>> indentation of the enclosing chunks. >> In my experience of non-indentation sensitive languages >> such as C-class (curly braces) it's just as hard to keep track >> of opening and closing braces. > > Although I have little or no experience with this, I still dare to say > that I don't agree. The difference is that in C you do not _need_ to > know where in the braces-defined hierarchy you are. You just embed or > change a piece of code at the right location. In Python however you > _do_ need to know how far your code is to be indented. And how do you know where the right location is? You have to figure it out from the different (nested) braces at the 'right' location. For me, at least, it's much easier to get that information from the already indented Python code, as opposed to indenting (and double-checking the indents) on the braces language. ~Ethan~ From nospam at nospam.com Tue May 4 11:28:26 2010 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 04 May 2010 17:28:26 +0200 Subject: HTTP server + SQLite? References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> <4bdf993e$0$1669$742ec2ed@news.sonic.net> <11247616-b5da-4494-bf83-1d7416c8dbef@g5g2000pre.googlegroups.com> Message-ID: On Mon, 3 May 2010 23:07:08 -0700 (PDT), Bryan wrote: >I love SQLite because it solves problems I actually have. For the vast >majority of code I write, "lite" is a good thing, and lite as it is, >SQLite can handle several transactions per second. I give SQLite a >file path and in a split second I have a relational, transactional >database. Great. I did not want to configure a server and I sure did >not want to inflict complexity upon my users. Exactly. I need a safe way to share an SQLite database among a few years, but sharing a drive isn't safe but I also don't need a full-fledged DBMS like MySQL. At this point, as an alternative to a Python-based solution, it seems like Mongoose + Lua + SQLite could do the trick. From stefan_ml at behnel.de Tue May 4 11:33:33 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 17:33:33 +0200 Subject: Teaching Programming In-Reply-To: <121607.77893.qm@web58702.mail.re1.yahoo.com> References: <121607.77893.qm@web58702.mail.re1.yahoo.com> Message-ID: Ed Keith, 04.05.2010 15:19: > --- On Tue, 5/4/10, Stefan Behnel wrote: >> Ed Keith, 04.05.2010 14:15: >>> Python is a great language to write in (although I do >>> wish it did a better job with closures). But it is a PITA to >>> generate code for! >> >> Interesting. Could you elaborate a bit? Could you give a >> short example of what kind of document text you translate >> into what kind of Python code, and what the problems were >> that you faced in doing so? > > The program is written using itself. If you click on the link above you > will see an HTML file that fully describes the program. I did. I find it a bit hard to read due to the block splitting (basically like 'include' based spaghetti programming), but so far, the actual code that does the code merging looks pretty simple and I can't figure out where the "PITA" bit is on that page. That's why I asked. Stefan From stefan_ml at behnel.de Tue May 4 11:37:50 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 17:37:50 +0200 Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6A3B87357@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> <7F0503CD69378F49BE0DC30661C6CCF6A3B87357@enbmail01.lsi.com> Message-ID: Barak, Ron, 04.05.2010 16:11: >>> I'm parsing XML files using ElementTree from xml.etree (see code >>> below (and attached xml_parse_example.py)). >>> >>> However, I'm coming across input XML files (attached an example: >>> tmp.xml) which include invalid characters, that produce the >>> following traceback: >>> >>> $ python xml_parse_example.py >>> Traceback (most recent call last): >>> xml.parsers.expat.ExpatError: not well-formed (invalid >>> token): line 6, column 34 >> >> I hope you are aware that this means that the input you are >> parsing is not XML. It's best to reject the file and tell the >> producers that they are writing broken output files. You >> should always fix the source, instead of trying to make sense >> out of broken input in fragile ways. >> > The XML file seems to be valid XML (all XML viewers I tried were able to read it). This is what xmllint gives me: ----------------------- $ xmllint /home/sbehnel/tmp.xml tmp.xml:6: parser error : Char 0x0 out of allowed range "MainStorage_snap ^ tmp.xml:6: parser error : Premature end of data in tag m_sanApiName1 line 6 "MainStorage_snap ^ tmp.xml:6: parser error : Premature end of data in tag DbHbaGroup line 5 "MainStorage_snap ^ tmp.xml:6: parser error : Premature end of data in tag database line 4 "MainStorage_snap ^ ----------------------- The file contains 0-bytes - clearly not XML. Stefan From e_d_k at yahoo.com Tue May 4 11:43:22 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 08:43:22 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <304036.63124.qm@web58706.mail.re1.yahoo.com> --- On Tue, 5/4/10, Stefan Behnel wrote: > From: Stefan Behnel > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 11:33 AM > Ed Keith, 04.05.2010 15:19: > > --- On Tue, 5/4/10, Stefan Behnel wrote: > >> Ed Keith, 04.05.2010 14:15: > >>> Python is a great language to write in > (although I do > >>> wish it did a better job with closures). But > it is a PITA to > >>> generate code for! > >> > >> Interesting. Could you elaborate a bit? Could you > give a > >> short example of what kind of document text you > translate > >> into what kind of Python code, and what the > problems were > >> that you faced in doing so? > > > > The program is written using itself. If you click on > the link above you > > will see an HTML file that fully describes the > program. > > I did. I find it a bit hard to read due to the block > splitting (basically like 'include' based spaghetti > programming), but so far, the actual code that does the code > merging looks pretty simple and I can't figure out where the > "PITA" bit is on that page. That's why I asked. > > Stefan > > -- http://mail.python.org/mailman/listinfo/python-list > The PITA is having to keep track of the indentation of each embedded chunk and summing it for each level of indentation. This requires a fair amount of bookkeeping that would not otherwise be necessary. The original prototype simply replaced each embedded chunk with the text from the chunk definition, all indenting information was lost. It worked for most languages, but not Python. In testing the program I used two languages, Python and J. I figured if I could make both of them work I would not have any problem with anything else. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From wuwei23 at gmail.com Tue May 4 11:45:32 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 May 2010 08:45:32 -0700 (PDT) Subject: Teaching Programming References: Message-ID: <5512eb07-b589-4f18-9ccf-634efc7c6f70@u3g2000prl.googlegroups.com> Ed Keith wrote: > Tabs are always a problem when writing Python. I get > around this problem by setting my text editor to expand > all tabs with spaces when editing Python, but I have had > problems when coworkers have not done this. It's best not to trust others to do the right thing. I do trust Tools/ scripts/reindent.py more though :) > Don't get me wrong, I love working in Python. It is one > of my favorite languages, but it, like all other languages, > is not perfect. I was genuinely interested in the problems you hit as I have some hazy projects in mind that I was planning on trying to handle via code generation. Context managers seem the best place to first try dealing with it. If you're interested I can keep you posted when I finally have some working code. Cheers for the clarification. From darcy at druid.net Tue May 4 11:49:25 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 May 2010 11:49:25 -0400 Subject: Teaching Programming In-Reply-To: References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> Message-ID: <20100504114925.af9e3224.darcy@druid.net> On Wed, 5 May 2010 00:35:18 +1000 James Mills wrote: > In my experience of non-indentation sensitive languages > such as C-class (curly braces) it's just as hard to keep track > of opening and closing braces. Harder. That was the big "Aha!" for me with Python. My first programming language was Fortran in 1969 so when I saw indentation as syntax I also recoiled in horror for about 0.5 seconds. However, I immediately realized that from now on I could be sure that if it looked right then it was right. for (x = 0; x++; x < 10); printf("Current number is %d\n", x); Or... for (x = 0; x++; x < 10); { printf("Current number is %d\n", x); } Oops. Looks right but isn't. Try to make that mistake in Python. Note untested - I wasn't about to fire up an editor, create a C program, add the includes, compile and run the a.out just to test this. Another way that Python excels. However, I am pretty sure that the above would compile. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From stefan_ml at behnel.de Tue May 4 11:52:30 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 17:52:30 +0200 Subject: Teaching Programming In-Reply-To: <304036.63124.qm@web58706.mail.re1.yahoo.com> References: <304036.63124.qm@web58706.mail.re1.yahoo.com> Message-ID: Ed Keith, 04.05.2010 17:43: > The PITA is having to keep track of the indentation of each embedded > chunk and summing it for each level of indentation. This requires a fair > amount of bookkeeping that would not otherwise be necessary. > > The original prototype simply replaced each embedded chunk with the text > from the chunk definition, all indenting information was lost. It worked > for most languages, but not Python. > > In testing the program I used two languages, Python and J. Well, then both of the language generators have benefited from your effort because the generated complete code is properly indented and therefore much more readable during debugging. I'd say it was worth it. Stefan From utente at esempio.net Tue May 4 11:55:20 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 17:55:20 +0200 Subject: Teaching Programming In-Reply-To: <4be01df4$0$1134$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> <4be01df4$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4be0436a$0$1125$4fafbaef@reader3.news.tin.it> superpollo ha scritto: > Stefan Behnel ha scritto: >> superpollo, 04.05.2010 14:46: >>> my template system wants >>> the input to generate the code to stay on a single line ( don't ask >>> :-( ) >> >> I hope you don't mind if I still ask. What are you generating and for >> what templating system? > > ok, since you asked for it, prepare yourself for a bit of a horror story > ;-) > > i will answer in my next post ok here it is. i am not a programmer or it-guy in the first place; my job is as a high school teacher in a field only remotely connected with computers (math and physics). since i have some kind of computer literacy (as opposed to most of my colleagues), some years ago i was kindly asked to try and solve a "simple" particular problem, that is to write a program that generates math exercises (q+a) from an example taken from the textbook. for instance, this: %%TITLE:Sample worksheet %% %%SCHEMA:\lim_{x \to } %%SCHEMA:\frac %%SCHEMA:{x^3-x^2-x} %%SCHEMA:{x^3-x^2+x-}\\ %% %%ANS:FRAC %%ANSNUM: %%ANSDEN: %% %%AMIN:1 %%AINC:1 %%AMAX:2 %%BMIN:3 %%BINC:1 %%BMAX:4 %%CMIN:2 %%CINC:1 %%CMAX:3 should generate this latex source document: \documentclass[a4paper,10pt,twocolumn,fleqn]{article} \title{Sample worksheet} \pagestyle{empty} \usepackage[italian]{babel} \usepackage{amsmath} \usepackage{amssymb} \usepackage{cancel} \usepackage{mathrsfs} \usepackage[dvips]{graphicx} \usepackage{eurosym} \usepackage{pstricks} \usepackage{pst-eucl} \usepackage{pst-poly} \usepackage{pst-plot} \frenchspacing \begin{document} \section*{\center{\framebox{Sample worksheet}}} \noindent \begin{enumerate} \item \begin{multline*} \lim_{x \to 1} \frac {x^3+3x^2-4x} {x^3-x^2+2x-2}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 2} \frac {x^3+x^2-6x} {x^3-2x^2+2x-4}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 2} \frac {x^3+2x^2-8x} {x^3-2x^2+2x-4}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 1} \frac {x^3+2x^2-3x} {x^3-x^2+2x-2}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 1} \frac {x^3+2x^2-3x} {x^3-x^2+3x-3}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 1} \frac {x^3+3x^2-4x} {x^3-x^2+3x-3}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 2} \frac {x^3+x^2-6x} {x^3-2x^2+3x-6}\\ \end{multline*} \item \begin{multline*} \lim_{x \to 2} \frac {x^3+2x^2-8x} {x^3-2x^2+3x-6}\\ \end{multline*} \end{enumerate} \subsection*{\center{Answers}} \begin{enumerate} \item \begin{displaymath} \frac{5}{3} \end{displaymath} \item \begin{displaymath} \frac{5}{3} \end{displaymath} \item \begin{displaymath} 2 \end{displaymath} \item \begin{displaymath} \frac{4}{3} \end{displaymath} \item \begin{displaymath} 1 \end{displaymath} \item \begin{displaymath} \frac{5}{4} \end{displaymath} \item \begin{displaymath} \frac{10}{7} \end{displaymath} \item \begin{displaymath} \frac{12}{7} \end{displaymath} \end{enumerate} \end{document} which in turn can be used to generate the following pdf file: http://www.datafilehost.com/download-cc88a19e.html fine huh? now, for the horror part. when i began putting down some code i thought that maybe it would take a couple of evenings to put up a working prototype, and i was w-r-o-n-g: 1) as i said i am not a professional 2) i decided to use bash shell as a core language for the parser/generator ( *sigh* ) 3) feautiritis soon crept in if some of you knows a bit about math and especially algebra, you will understand that some of the biggest problems in generating standard math notation in to cope with the various layers of traditions and innuendos: for example i could generate the string "2x" which is fine; but what about "1x" or "-1x" or "0x"? and what about plus signs at the start of an expression (normally omitted)? when does a subexpression start? etc ... there are plenty of icompatible rules and as much as exceptions ... as you can see i had many problems to solve and i am not trained to cope with such issues from a programmatic standpoint. another thing is that for some features i intended to include i found convenient to use python (since it's the language i feel i am more at ease with), so i had to cope with template lines like this: %%SCHEMA: or even worse: %%ANSFRCEMBPYC:\\ to make a long story short: the whole program is now 4775 lines of bash code, written by an unqualified amateur under time pressure; sometimes i have to hand-modify it to get certain outputs as i expect them to be; this in turn breaks other subsystems. i am ashamed to post the code, and it is a true design nightmare. also it is offtopic (being bash). *but* it was and it is a wonderful experience to learn to program, to acknowledge weaknesses end strongnesses of various approaches, to better understand the structure of math notation, problem solving end teaching techniques. it is still work in progress though, and i hope i will never see the day i have to refurbish it. i hope -- instead -- that the next time i try to attack the task i will have a better knowledge thanks to errors committed, to avoid many of the pitfalls i stumbled upon. for now, it works. *whew* i hope i was not boring, and i sincerely hope that some of you could see the depth of the problem i tried to solve (perhaps usuccesfully), end give me some professional advice as what to do for the next incarnation of my awful program. any concrete suggestion will be *very* appreciated. thank to all bye From tjreedy at udel.edu Tue May 4 12:06:10 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 12:06:10 -0400 Subject: Teaching Programming In-Reply-To: References: Message-ID: On 5/3/2010 7:46 PM, cjw wrote: > Nobody likes indentation at first, Speak for yourself, please. For two decades before I met Python, I indented code nicely whenever it was allowed. That option was one of the great advancements of Fortran77 over FortranIV. Coming from C, I was immediately glad to be done with those darn braces. tjr From darcy at druid.net Tue May 4 12:07:25 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 May 2010 12:07:25 -0400 Subject: Teaching Programming In-Reply-To: References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> Message-ID: <20100504120725.1dfdf513.darcy@druid.net> On Tue, 4 May 2010 17:00:11 +0200 Andre Engels wrote: > Although I have little or no experience with this, I still dare to say > that I don't agree. The difference is that in C you do not _need_ to > know where in the braces-defined hierarchy you are. You just embed or > change a piece of code at the right location. In Python however you > _do_ need to know how far your code is to be indented. Well, I'm afraid your lack of experience shows. Experienced C coders will tell you that one of the most annoying things is counting braces to make sure that you have the right number in the right places. In fact, they add indentation so that they can use the visual layout to check the brace layout. Braces are the added step. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From clp2 at rebertia.com Tue May 4 12:11:44 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 May 2010 09:11:44 -0700 Subject: Teaching Programming In-Reply-To: <20100504114925.af9e3224.darcy@druid.net> References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> <20100504114925.af9e3224.darcy@druid.net> Message-ID: On Tue, May 4, 2010 at 8:49 AM, D'Arcy J.M. Cain wrote: > On Wed, 5 May 2010 00:35:18 +1000 > James Mills wrote: >> In my experience of non-indentation sensitive languages >> such as C-class (curly braces) it's just as hard to keep track >> of opening and closing braces. > > Harder. ?That was the big "Aha!" for me with Python. ?My first > programming language was Fortran in 1969 so when I saw indentation as > syntax I also recoiled in horror for about 0.5 seconds. The amount of mental scaring that Fortran has caused regarding indentation is astounding. Maybe the PSF should run re-education camps for Fortran programmers... :P > However, I > immediately realized that from now on I could be sure that if it looked > right then it was right. > > ? ?for (x = 0; x++; x < 10); > ? ? ? ?printf("Current number is %d\n", x); > > Or... > > ? ?for (x = 0; x++; x < 10); > ? ?{ > ? ? ? ?printf("Current number is %d\n", x); > ? ?} > > Oops. ?Looks right but isn't. ?Try to make that mistake in Python. Technically, that pitfall /could/ be eliminated if curly-braces languages simply always required the curly-braces for bodies and stopped special-casing the null body case, in which case both your examples would be syntax errors. Removing the special-casing of single-line bodies too would remove a further class of errors. However, I've yet to encounter a language that takes such an approach. Quite a pity. Cheers, Chris -- I've thought a lot about this. http://blog.rebertia.com/2010/01/24/of-braces-and-semicolons/ From clp2 at rebertia.com Tue May 4 12:13:38 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 May 2010 09:13:38 -0700 Subject: Teaching Programming In-Reply-To: References: <304036.63124.qm@web58706.mail.re1.yahoo.com> Message-ID: On Tue, May 4, 2010 at 8:52 AM, Stefan Behnel wrote: > Ed Keith, 04.05.2010 17:43: >> The PITA is having to keep track of the indentation of each embedded >> chunk and summing it for each level of indentation. This requires a fair >> amount of bookkeeping that would not otherwise be necessary. >> >> The original prototype simply replaced each embedded chunk with the text >> from the chunk definition, all indenting information was lost. It worked >> for most languages, but not Python. >> >> In testing the program I used two languages, Python and J. > > Well, then both of the language generators have benefited from your effort > because the generated complete code is properly indented and therefore much > more readable during debugging. I'd say it was worth it. Though there are auto-re-indenting programs for curly-brace languages you know. Cheers, Chris -- http://blog.rebertia.com From tjreedy at udel.edu Tue May 4 12:15:17 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 12:15:17 -0400 Subject: Teaching Programming In-Reply-To: <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> Message-ID: On 5/4/2010 8:46 AM, superpollo wrote: > but i do not think i can use it myself, since my template system wants > the input to generate the code to stay on a single line ( don't ask :-( ) I think we can agree that Python (unlike C, for instance) is not good for writing non-humanly-readable one-unbounded-length-line code. That is contrary to its design goal. But I would think that you would have similar problems with other manditorily multiline languages, like Fortran and Basic. Terry Jan Reedy From davea at ieee.org Tue May 4 12:22:08 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 04 May 2010 12:22:08 -0400 Subject: Teaching Programming In-Reply-To: <4BE03D08.1080108@stoneleaf.us> References: <9210a992-a90c-4535-9e7b-0fc5553543e3@h37g2000pra.googlegroups.com> <952067.92151.qm@web58703.mail.re1.yahoo.com> <4BE03D08.1080108@stoneleaf.us> Message-ID: <4BE049B0.1060805@ieee.org> Ethan Furman wrote: >
Andre > Engels wrote: >> On Tue, May 4, 2010 at 4:35 PM, James Mills >> wrote: >>> On Wed, May 5, 2010 at 12:21 AM, Ed Keith wrote: >>>> To deal with indentation I had to >>>> >>>> 1) keep track of indentation of all chunks of code embedded in the >>>> document and indent inserted chunks to the sum of all the >>>> indentation of the enclosing chunks. >>> In my experience of non-indentation sensitive languages >>> such as C-class (curly braces) it's just as hard to keep track >>> of opening and closing braces. >> >> Although I have little or no experience with this, I still dare to say >> that I don't agree. The difference is that in C you do not _need_ to >> know where in the braces-defined hierarchy you are. You just embed or >> change a piece of code at the right location. In Python however you >> _do_ need to know how far your code is to be indented. > > And how do you know where the right location is? You have to figure > it out from the different (nested) braces at the 'right' location. > For me, at least, it's much easier to get that information from the > already indented Python code, as opposed to indenting (and > double-checking the indents) on the braces language. > > ~Ethan~ > > Much more important to be able to read code reliably than write it quickly. When I was heavily doing C++ I found myself wishing that incorrect indentation would be an error or at least a warning. And I hadn't ever heard of Python. When I did, I said "About time!" Of course, I was surrounded by many programmers who ignored any warning that the compiler produced, while I cranked up warnings to max, with pedantic. On one project I generated C++ code, about 20k lines. And it was all indented and commented. Most of that code went through the code generator twice. The "source" was a header file from outside my organization. The generator used that to create a new header, more detailed. Then the generator used that to create source & headers that were actually used by the project. DaveA From gherron at islandtraining.com Tue May 4 12:23:58 2010 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 04 May 2010 09:23:58 -0700 Subject: Teaching Programming In-Reply-To: References: Message-ID: <4BE04A1E.7040903@islandtraining.com> Terry Reedy wrote: > On 5/3/2010 7:46 PM, cjw wrote: > >> Nobody likes indentation at first, > > Speak for yourself, please. For two decades before I met Python, I > indented code nicely whenever it was allowed. That option was one of > the great advancements of Fortran77 over FortranIV. Coming from C, I > was immediately glad to be done with those darn braces. > > tjr > Right. Somewhere in the 80's I read a paper in sigplan which demonstrated that indentation-only was sufficient to communicate the structure of a program. I immediately *knew* that was the right way to go. Sadly, I had to wait a decade or so before discovering Python in the mid 90's, but I never forgot that paper nor lost my eager anticipation waiting for language design to catch up with that idea. Gary Herron From stefan_ml at behnel.de Tue May 4 12:30:46 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 May 2010 18:30:46 +0200 Subject: Teaching Programming In-Reply-To: <4be0436a$0$1125$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be0173c$0$1122$4fafbaef@reader3.news.tin.it> <4be01df4$0$1134$4fafbaef@reader3.news.tin.it> <4be0436a$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: superpollo, 04.05.2010 17:55: > since i have some kind of computer literacy (as opposed to most of my > colleagues), some years ago i was kindly asked to try and solve a > "simple" particular problem, that is to write a program that generates > math exercises (q+a) from an example taken from the textbook. for > instance, this: > > %%TITLE:Sample worksheet > %% > %%SCHEMA:\lim_{x \to } > %%SCHEMA:\frac > %%SCHEMA:{x^3-x^2-x} > %%SCHEMA:{x^3-x^2+x-}\\ > %% > %%ANS:FRAC > %%ANSNUM: > %%ANSDEN: > %% > %%AMIN:1 > %%AINC:1 > %%AMAX:2 > %%BMIN:3 > %%BINC:1 > %%BMAX:4 > %%CMIN:2 > %%CINC:1 > %%CMAX:3 > > should generate this latex source document: > > \documentclass[a4paper,10pt,twocolumn,fleqn]{article} > \title{Sample worksheet} > \pagestyle{empty} > \usepackage[italian]{babel} > \usepackage{amsmath} > \usepackage{amssymb} > \usepackage{cancel} > \usepackage{mathrsfs} > \usepackage[dvips]{graphicx} > \usepackage{eurosym} > \usepackage{pstricks} > \usepackage{pst-eucl} > \usepackage{pst-poly} > \usepackage{pst-plot} > \frenchspacing > \begin{document} > \section*{\center{\framebox{Sample worksheet}}} > \noindent > \begin{enumerate} > \item > \begin{multline*} > \lim_{x \to 1} > \frac > {x^3+3x^2-4x} > {x^3-x^2+2x-2}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 2} > \frac > {x^3+x^2-6x} > {x^3-2x^2+2x-4}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 2} > \frac > {x^3+2x^2-8x} > {x^3-2x^2+2x-4}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 1} > \frac > {x^3+2x^2-3x} > {x^3-x^2+2x-2}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 1} > \frac > {x^3+2x^2-3x} > {x^3-x^2+3x-3}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 1} > \frac > {x^3+3x^2-4x} > {x^3-x^2+3x-3}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 2} > \frac > {x^3+x^2-6x} > {x^3-2x^2+3x-6}\\ > \end{multline*} > \item > \begin{multline*} > \lim_{x \to 2} > \frac > {x^3+2x^2-8x} > {x^3-2x^2+3x-6}\\ > \end{multline*} > \end{enumerate} > \subsection*{\center{Answers}} > \begin{enumerate} > \item > \begin{displaymath} > \frac{5}{3} > \end{displaymath} > \item > \begin{displaymath} > \frac{5}{3} > [...] I'm not exactly sure I understand the mapping between the two formats, but it seems to me that you'll need a proper math expression parser (with a strong emphasis on *parser*) for this. Math expressions are not exactly trivial (recursion, prefix/infix/postfix notations, functions), which is why 'real' programmers don't write parsers for them but download tested, working code for that from somewhere. > another thing is that for some features i intended to include i found > convenient to use python (since it's the language i feel i am more at > ease with), so i had to cope with template lines like this: > > %%SCHEMA: You should assure that the math module is always imported, and otherwise restrict the expressiveness to expressions (terms that result in a value), not arbitrary statements (executable commands that do things without returning anything). > to make a long story short: the whole program is now 4775 lines of bash > code, Argh! > *but* it was and it is a wonderful experience to learn to program It does sound like you almost completely skipped over two very important programming lessons, though: reading code is harder than writing it (i.e. maintenance cost matters), and the best code is the code that you don't need to write (and debug and maintain). Stefan From tjreedy at udel.edu Tue May 4 12:31:06 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 12:31:06 -0400 Subject: HTTP server + SQLite? In-Reply-To: <11247616-b5da-4494-bf83-1d7416c8dbef@g5g2000pre.googlegroups.com> References: <7jvst55a3fdjnmt2u883m41o1ufv12e9uc@4ax.com> <4bdf993e$0$1669$742ec2ed@news.sonic.net> <11247616-b5da-4494-bf83-1d7416c8dbef@g5g2000pre.googlegroups.com> Message-ID: On 5/4/2010 2:07 AM, Bryan wrote: > The SQLite developers state the situation brilliantly at > http://www.sqlite.org/whentouse.html: For future reference, that link does not work with Thunderbird. This one does. http://www.sqlite.org/whentouse.html When posting links, best to put them on a line by themselves, with NO punctuation, even if 'proper' English seems to require it. A space before the colon probably would have worked too, if its complete absence bothers one too much ;=). Terry Jan Reedy From mensanator at aol.com Tue May 4 12:50:47 2010 From: mensanator at aol.com (Mensanator) Date: Tue, 4 May 2010 09:50:47 -0700 (PDT) Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: <11022b40-3360-4725-aac4-24b0d07df16c@i9g2000yqi.googlegroups.com> On May 3, 10:17?am, s... at sig.for.address (Victor Eijkhout) wrote: > I have two long ints, both too long to convert to float, but their ratio > is something reasonable. How can I compute that? The obvious "(1.*x)/y" > does not work. You could try using the gmpy module. It supports arbitrary precision floats, so converting long to float is no problem. YY = 3**10684 float(YY) Traceback (most recent call last) File "pyshell#78>", line 1, in float(YY) OverflowError: Python int too large to convert to C double import gmpy gmpy.mpf(YY) mpf('3.6600365709...0197681e5097',16936) > > Victor. > > -- > Victor Eijkhout -- eijkhout at tacc utexas edu From robin1 at cnsp.com Tue May 4 13:32:26 2010 From: robin1 at cnsp.com (Robin) Date: Tue, 4 May 2010 10:32:26 -0700 (PDT) Subject: scrolledtext download location Message-ID: Does anyone know where I can download the ScrolledText tkintewr widget, looked all over for it and had no luck, Thanks, -Robin From tjreedy at udel.edu Tue May 4 13:32:39 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 13:32:39 -0400 Subject: Recursive functions not returning lists as expected In-Reply-To: References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: On 5/4/2010 1:45 AM, rickhg12hs wrote: > On May 4, 1:34 am, Cameron Simpson wrote: >> On 03May2010 22:02, rickhg12hs wrote: >> | Would a kind soul explain something basic to a python noob? >> | >> | Why doesn't this function always return a list? >> | >> | def recur_trace(x,y): >> | print x,y >> | if not x: >> | return y >> | recur_trace(x[1:], y + [x[0]]) >> >> You need: >> return recur_trace(x[1:], y + [x[0]]) >> >> Otherwise the function returns None. > > Ah, an explicit "return" is required. Thanks! > [To bad there's no tail recursion optimization.] 8-( That issue is much more complicated than you probably imagine. Here is part of it, using your toy example of computing y +x. [Code snippets below are untested and might have typos.] Write your tail recursive function with the recursive branch first: def t_r(x,y): if x: return t_r(x[1:], y+[x[0]]) else: return y and the conversion ('optimization') to while form is trivial: def t_w(x,y): while x: x,y = x[1:], y+[x[0]] else: return y Of course, most would omit the 'else:', which I left to emphasize the paralellism. More importantly, 'while' loops are relatively rare in Python because scanning an iterable (a typical use of tail recursion) can be and usually is done (generically) with for loops instead: def t_f(x,y): for o in x: y = y + [o] return y Of course, this, like your original code, wastefully creates numerous temporary lists (two per iteration) when only one new list is needed for the entire process. This is easily fixed in the loop version: def t_f2(x,y): r = y[:] for o in x: r.append(o) return r Making that important fix in the recursive version is harder since the copying should be done exactly once, and not with every recursive call. I leave it to you to try either of the two main approaches. Terry Jan Reedy From see at sig.for.address Tue May 4 13:35:29 2010 From: see at sig.for.address (Victor Eijkhout) Date: Tue, 4 May 2010 12:35:29 -0500 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> <11022b40-3360-4725-aac4-24b0d07df16c@i9g2000yqi.googlegroups.com> Message-ID: <1jhyw5q.1jzuq46ob9mwgN%see@sig.for.address> Mensanator wrote: > You could try using the gmpy module. It supports arbitrary precision > floats, so converting long to float is no problem. I fear I may actually have to go symbolic. I'm now having to use the 12th root of 2, and I would like the twelfth power of that to be exactly 2. Victor. -- Victor Eijkhout -- eijkhout at tacc utexas edu From tjreedy at udel.edu Tue May 4 13:43:16 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 13:43:16 -0400 Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? In-Reply-To: References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> <7F0503CD69378F49BE0DC30661C6CCF6A3B87357@enbmail01.lsi.com> Message-ID: On 5/4/2010 11:37 AM, Stefan Behnel wrote: > Barak, Ron, 04.05.2010 16:11: >> The XML file seems to be valid XML (all XML viewers I tried were able >> to read it). From Internet Explorer: The XML page cannot be displayed Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later. -------------------------------------------------------------------------------- An invalid character was found in text content. Error processing resource 'file:///C:/Documents and Settings... "BROLB21 > This is what xmllint gives me: > > ----------------------- > $ xmllint /home/sbehnel/tmp.xml > tmp.xml:6: parser error : Char 0x0 out of allowed range > "MainStorage_snap > ^ > tmp.xml:6: parser error : Premature end of data in tag m_sanApiName1 line 6 > "MainStorage_snap > ^ > tmp.xml:6: parser error : Premature end of data in tag DbHbaGroup line 5 > "MainStorage_snap > ^ > tmp.xml:6: parser error : Premature end of data in tag database line 4 > "MainStorage_snap > ^ > ----------------------- > > The file contains 0-bytes - clearly not XML. IE agrees. From rouslank at msn.com Tue May 4 13:46:29 2010 From: rouslank at msn.com (Rouslan Korneychuk) Date: Tue, 04 May 2010 13:46:29 -0400 Subject: new extension generator for C++ In-Reply-To: References: Message-ID: <4BE05D75.7030301@msn.com> On 05/04/2010 03:06 AM, Samuel Williams wrote: > Dear Rouslan, > > It looks interesting. I say go for it. You will learn something and might make some improvements on existing ideas. > > I recommend putting the code on www.github.com > > Kind regards, > Samuel > > Thanks for the suggestion. I think I'll do just that. The "social" aspect sounds interesting, since up until now, this project has been a solitary exercise. On 05/04/2010 01:51 AM, Stefan Behnel wrote: > Last I heard, that was basically what PyBindGen does (and probably some > other existing binding generators). You should take a look at them > before investing too much time into a duplicated effort. > > Also, if you're interested in performance, you should take a look at > Cython, which is an optimising compiler for (basically) Python code that > can talk to C, C++ and Fortran code. It's been used a lot for writing > performance critical library wrappers. > > Stefan > I took a brief look at PyBindGen. I noticed a couple of things in the generated code of a test module. The PyObject definitions held a pointer to the contained datatype, which is one of the things I was trying to steer away from. It would generate a std::map for each new type, apparently to allow the contained type to be matched back to the PyObject when needed. I intend to use the same method that Boost.Python uses, sneak the pointer into the destruct functor of a shared_ptr. And when parsing arguments from an overloaded set, PyBindGen appears to generate complete separate functions for each overload and then try one after the other. The reason mine doesn't support overloaded named arguments is because it instead uses a bunch of nested if-statements to match the overload with as few checks as possible. Mine also orders the checks so that a base-class is never checked before a derived-class and that numeric types and string types are matched to their best fit (given func(double x) and func(int x), a python float value will always call func(double)). I'm not certain that PyBindGen doesn't generate code that takes this into consideration I haven't studied its code. I'll definitely take a look at how Cython handles arguments some time. It's also interesting to note that while PyBindGen will parse C++ types itself, to interpret arguments and return types, mine uses gccxml to do all the work. When given a specific overload, it will generate a dummy function with the same set of arguments in the file given to gccxml, along with typedefs for all built-in types. That way, you can specify types either explicitly, or with typedefs regardless of how the interface you want to expose does it, and my code doesn't have to do any extra work. The only question I have now is what about licensing? Is that something I need to worry about? Should I go with LGPL, MIT, or something else? And should the license be mentioned in the code or be in a single separate file at the top-level directory? From tjreedy at udel.edu Tue May 4 13:54:20 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 13:54:20 -0400 Subject: scrolledtext download location In-Reply-To: References: Message-ID: On 5/4/2010 1:32 PM, Robin wrote: > Does anyone know where I can download the ScrolledText tkintewr > widget, looked all over for it and had no luck, Since this is a module included with tkinter which is included with Python, (at least on Windows) I am puzzled. Perhaps you need to supply more info as to your problem. (3.1) Lib ref 24.4: "tkinter.scrolledtext module provides a class of the same name which implements a basic text widget which has a vertical scroll ..." From utente at esempio.net Tue May 4 13:56:56 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 19:56:56 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4be05fe9$0$1133$4fafbaef@reader3.news.tin.it> James Mills ha scritto: > On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: >> of course! *but* if i must generate on-the-fly python code that defines a >> function i am back again to the problem: > > One-liner: > > $ python > Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) > [GCC 4.4.1 (CRUX)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a, b = 2, 3 >>>> print a + b if a > b else a**b - b**2 > -1 >>>> a, b = 3, 2 >>>> print a + b if a > b else a**b - b**2 > 5 > > --James what if i want an elif clause? From tjreedy at udel.edu Tue May 4 14:13:19 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 14:13:19 -0400 Subject: py3 tkinter acceps bytes. why? In-Reply-To: References: Message-ID: On 5/4/2010 10:17 AM, Matthias Kievernagel wrote: > From: Matthias Kievernagel > Subject: py3 tkinter acceps bytes. why? > Newsgroups: comp.lang.python > Summary: > Keywords: > > In a recent thread named "py3 tkinter Text accepts what bytes?" > (google groups link: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/b75ed69f4e81b202/e2aff9ddd62d210c?lnk=raot) > I asked what kinds of bytes are accepted as tkinter parameters. > I still wonder why they are accepted at all. > Does anyone know a reason for this > or has a link to some relevant discussion? I do not remember any particular public discussion of tkinter on the dev lists. I suspect the reason is a) avoid breaking old code and b) tkinter (tk inter-face) passes params on to tk which expects byte strings. I would not be surprised if tkinter has to encode py3 (unicode) strings before passing them on. The Py3 changes were greatly complicated by the need to interface with the older bytes world. Terry Jan Reedy From utente at esempio.net Tue May 4 14:16:48 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 20:16:48 +0200 Subject: Teaching Programming In-Reply-To: <4be05fe9$0$1133$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be05fe9$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: <4be06491$0$1133$4fafbaef@reader3.news.tin.it> superpollo ha scritto: > James Mills ha scritto: >> On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: >>> of course! *but* if i must generate on-the-fly python code that >>> defines a >>> function i am back again to the problem: >> >> One-liner: >> >> $ python >> Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) >> [GCC 4.4.1 (CRUX)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> a, b = 2, 3 >>>>> print a + b if a > b else a**b - b**2 >> -1 >>>>> a, b = 3, 2 >>>>> print a + b if a > b else a**b - b**2 >> 5 >> >> --James > > what if i want an elif clause? > my first try obviously falied: >>> print a + b if a > b elif a=b "WOW" else a**b - b**2 File "", line 1 print a + b if a > b elif a=b "WOW" else a**b - b**2 ^ SyntaxError: invalid syntax From tjreedy at udel.edu Tue May 4 14:35:10 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 14:35:10 -0400 Subject: Teaching Programming In-Reply-To: References: Message-ID: On 5/4/2010 1:44 PM, Dennis Lee Bieber wrote: > On Tue, 04 May 2010 12:06:10 -0400, Terry Reedy > declaimed the following in gmane.comp.python.general: > >> Speak for yourself, please. For two decades before I met Python, I >> indented code nicely whenever it was allowed. That option was one of the >> great advancements of Fortran77 over FortranIV. Coming from C, I was >> immediately glad to be done with those darn braces. >> > What kept you from indenting FORTRAN-IV? There was a several year gap with learning of 'structured programming' in between. Perhaps ignorance of both the possibility (no one did it, that I know of) and desirability. Glass screens made consistent indentation a lot easier that with cards and teletypes. The new structured block constructs made indentation more useful, too. From utente at esempio.net Tue May 4 14:35:48 2010 From: utente at esempio.net (superpollo) Date: Tue, 04 May 2010 20:35:48 +0200 Subject: Teaching Programming In-Reply-To: <4be06491$0$1133$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be05fe9$0$1133$4fafbaef@reader3.news.tin.it> <4be06491$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: <4be06906$0$1122$4fafbaef@reader3.news.tin.it> superpollo ha scritto: > superpollo ha scritto: >> James Mills ha scritto: >>> On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: >>>> of course! *but* if i must generate on-the-fly python code that >>>> defines a >>>> function i am back again to the problem: >>> >>> One-liner: >>> >>> $ python >>> Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) >>> [GCC 4.4.1 (CRUX)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>>>>> a, b = 2, 3 >>>>>> print a + b if a > b else a**b - b**2 >>> -1 >>>>>> a, b = 3, 2 >>>>>> print a + b if a > b else a**b - b**2 >>> 5 >>> >>> --James >> >> what if i want an elif clause? >> > > my first try obviously falied: > > >>> print a + b if a > b elif a=b "WOW" else a**b - b**2 > File "", line 1 > print a + b if a > b elif a=b "WOW" else a**b - b**2 > ^ > SyntaxError: invalid syntax > ok i got it: >>> a,b=2,3 >>> print a + b if a > b else "WOW" if a < b else a**b - b**2 WOW >>> From benjamin.kaplan at case.edu Tue May 4 14:44:05 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 4 May 2010 14:44:05 -0400 Subject: Teaching Programming In-Reply-To: <4be06491$0$1133$4fafbaef@reader3.news.tin.it> References: <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be003cc$0$1128$4fafbaef@reader3.news.tin.it> <4be00b7b$0$1134$4fafbaef@reader3.news.tin.it> <4be05fe9$0$1133$4fafbaef@reader3.news.tin.it> <4be06491$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: On Tue, May 4, 2010 at 2:16 PM, superpollo wrote: > superpollo ha scritto: >> >> James Mills ha scritto: >>> >>> On Tue, May 4, 2010 at 9:56 PM, superpollo wrote: >>>> >>>> of course! *but* if i must generate on-the-fly python code that defines >>>> a >>>> function i am back again to the problem: >>> >>> One-liner: >>> >>> $ python >>> Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) >>> [GCC 4.4.1 (CRUX)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>>>>> >>>>>> a, b = 2, 3 >>>>>> print a + b if a > b else a**b - b**2 >>> >>> -1 >>>>>> >>>>>> a, b = 3, 2 >>>>>> print a + b if a > b else a**b - b**2 >>> >>> 5 >>> >>> --James >> >> what if i want an elif clause? >> > > my first try obviously falied: > >>>> print a + b if a > b elif a=b "WOW" else a**b - b**2 > ?File "", line 1 > ? ?print a + b if a > b elif a=b "WOW" else a**b - b**2 > ? ? ? ? ? ? ? ? ? ? ? ? ? ?^ > SyntaxError: invalid syntax That's because this technically isn't an if statement. It's the ternary conditional expression. If you want multiple conditions, you have to repeat the expression print a+b if a > b else "WOW" if a==b else a**b - b**2 > > -- > http://mail.python.org/mailman/listinfo/python-list > From e_d_k at yahoo.com Tue May 4 14:45:15 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 11:45:15 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <949627.90429.qm@web58701.mail.re1.yahoo.com> --- On Tue, 5/4/10, Stefan Behnel wrote: > From: Stefan Behnel > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 11:52 AM > Ed Keith, 04.05.2010 17:43: > > The PITA is having to keep track of the indentation of > each embedded > > chunk and summing it for each level of indentation. > This requires a fair > > amount of bookkeeping that would not otherwise be > necessary. > > > > The original prototype simply replaced each embedded > chunk with the text > > from the chunk definition, all indenting information > was lost. It worked > > for most languages, but not Python. > > > > In testing the program I used two languages, Python > and J. > > Well, then both of the language generators have benefited > from your effort because the generated complete code is > properly indented and therefore much more readable during > debugging. I'd say it was worth it. > > Stefan > > -- http://mail.python.org/mailman/listinfo/python-list > I agree, but some propellants of literate programming would not. Knuth wanted the generated source to be unreadable, so people would not be tempted to edit the generated code. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From dalamartr at gmail.com Tue May 4 15:12:38 2010 From: dalamartr at gmail.com (Hellnar) Date: Tue, 4 May 2010 12:12:38 -0700 (PDT) Subject: str.count algorithm Message-ID: Hello, I am trying to find what algorithm Python uses for the built-in str.count function, if it has a name. Thanks From python at rcn.com Tue May 4 15:25:30 2010 From: python at rcn.com (Raymond Hettinger) Date: Tue, 4 May 2010 12:25:30 -0700 (PDT) Subject: str.count algorithm References: Message-ID: <79750194-ec0d-4043-811d-c284cb2e011d@h20g2000prn.googlegroups.com> On May 4, 12:12?pm, Hellnar wrote: > Hello, > I am trying to find what algorithm Python uses for the built-in > str.count function, if it has a name. Roughly the same as: sum(1 for c in s if c == tgt) Raymond From __peter__ at web.de Tue May 4 15:54:58 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 May 2010 21:54:58 +0200 Subject: str.count algorithm References: <79750194-ec0d-4043-811d-c284cb2e011d@h20g2000prn.googlegroups.com> Message-ID: Raymond Hettinger wrote: > On May 4, 12:12 pm, Hellnar wrote: >> Hello, >> I am trying to find what algorithm Python uses for the built-in >> str.count function, if it has a name. > > Roughly the same as: > > sum(1 for c in s if c == tgt) That would be list.count(), I think. OP, the source http://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch.h?revision=77470&view=markup has a reference to http://effbot.org/zone/stringlib.htm Peter From rickhg12hs at gmail.com Tue May 4 16:10:16 2010 From: rickhg12hs at gmail.com (rickhg12hs) Date: Tue, 4 May 2010 13:10:16 -0700 (PDT) Subject: Recursive functions not returning lists as expected References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: On May 4, 1:32?pm, Terry Reedy wrote: > On 5/4/2010 1:45 AM, rickhg12hs wrote: [snip] > > [To bad there's no tail recursion optimization.] ?8-( > > That issue is much more complicated than you probably imagine. [snip] No imagination is necessary - functional languages (e.g., Erlang) do it quite well. From tjreedy at udel.edu Tue May 4 16:36:32 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 16:36:32 -0400 Subject: Generating nested code with context managers Message-ID: In a current thread, people have claimed that generating properly indented nested blocks is a pain because of the need to keep track of indent levels. Someone countered with the now rather ancient http://effbot.org/zone/python-code-generator.htm The usage example c = CodeGeneratorBackend() c.begin(tab=" ") c.write("for i in range(1000):\n") c.indent() c.write("print 'code generation is trivial'") c.dedent() illustrates three problems with the CodeGeneratorBackend class. 1) it requires explicit \n on all lines (which the second omits, though it is non-fatal since it is also the last) 2) the user still has to manually match indents and dedents, and 3) the user *cannot* indent lines that produce indented code. The relatively new with statement and associated context managers are designed, among other things, for this situation, where one needs to alter and restore a global context. So here is my updated (3.1) proof-of-concept version. class PyCodeGen: def __init__(self, tab=" "): self.code = [] self.tab = tab self.level = 0 # all attributes should be treated as read-only def end(self): return '\n'.join(self.code) def line(self, string): # new line self.code.append(self.tab * self.level + string) class For: def __init__(self, target, in_expression): target.line('for ' + in_expression + ':') self.target = target def __enter__(self): self.target.level += 1 def __exit__(self, t, v, tb): self.target.level -= 1 c = PyCodeGen() with For(c, 'i in range(1000)'): c.line('print("Code gen is easy")') c.line('# done') print(c.end()) # prints for i in range(1000): print("Code gen is easy") # done Note that the absence of .indent and .dedent is intentional. In a fleshed out system, there would be a context manager for each compound statement and these would handle all indents and dedents. If one really preferred to write, for instance, 'c.For(s); instead of 'For(c,s)' in the with statement, one could add a wrapper method like def For(self, s): return For(self, s) for each context manager. I left that out. Similar methods can be used to auto-match C braces and other open/close pairs. Terry Jan Reedy From tjreedy at udel.edu Tue May 4 17:23:20 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 May 2010 17:23:20 -0400 Subject: Recursive functions not returning lists as expected In-Reply-To: References: <2ff16113-4f79-4dcf-8310-35d2b91e89dc@o11g2000yqj.googlegroups.com> Message-ID: On 5/4/2010 4:10 PM, rickhg12hs wrote: > On May 4, 1:32 pm, Terry Reedy wrote: >> On 5/4/2010 1:45 AM, rickhg12hs wrote: > [snip] >>> [To bad there's no tail recursion optimization.] 8-( This is prinarily a space optimization to conserve stack frame space. The speedup would be minimal. Using while or for loops has the same space saving with better speedup (slow function are also gone) and easier optimization in other ways, as I showed. >> That issue is much more complicated than you probably imagine. > [snip] > > No imagination is necessary - functional languages (e.g., Erlang) do > it quite well. More complicated in the Python context. Does Erlang use static or dynamic name binding, or early versus late local name resolution? Python, by design, resolves global names within a function each time the function is called. So whether a call is recursive cannot be determined until the call is made. It is not difficult for CPython to space-optimize *all* tail calls, recursive or not. But this would have the bad effect of leaving gaps in error tracebacks and is not done for that reason. To only space-optimize simple recursive tail calls would take more time, and one would still lose traceback information. If you imagined all of the above, then indeed I underestimated you ;-). Terry Jan Reedy From pavlovevidence at gmail.com Tue May 4 17:27:58 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 4 May 2010 14:27:58 -0700 (PDT) Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> <4bdfce42$0$9110$426a34cc@news.free.fr> Message-ID: <4f8219ec-dd67-4889-bdf1-063ea5bad20c@o8g2000yqo.googlegroups.com> On May 4, 12:37?am, Bruno Desthuilliers wrote: > TomF a ?crit : > > > I'm interested in improving my python design by studying a large, > > well-designed codebase. ?Someone (not a python programmer) suggested > > Django. ?I realize that Django is popular, but can someone comment on > > whether its code is well-designed and worth studying? > > Carl makes some valid points in his answer, and there are indeed a > couple dark corners in this area - bit it's just a part of the whole > framework. There are still things worth studying in Django IHMO, > specially if you're interested in seeing metaclasses and descriptors at > work. Absolutely. I said it was "less than exemplary", i.e., still pretty good. Carl Banks From martin at v.loewis.de Tue May 4 17:29:06 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 04 May 2010 23:29:06 +0200 Subject: py3 tkinter acceps bytes. why? In-Reply-To: References: Message-ID: <4BE091A2.2010104@v.loewis.de> > In a recent thread named "py3 tkinter Text accepts what bytes?" > (google groups link: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/b75ed69f4e81b202/e2aff9ddd62d210c?lnk=raot) > I asked what kinds of bytes are accepted as tkinter parameters. > I still wonder why they are accepted at all. That's basically because the port from 2.x was shallow: it supports the exact same feature set that 2.x supports, with just the type names swapped. Tkinter in 2.x will already use Unicode strings in most situations. However, 2.x code would often also provide byte strings for text properties, and Tcl supports that "nicely" (*) Regards, Martin (*) I think you also asked how Tcl interprets things. IIUC, it first assumes that a byte string is UTF-8 (starting from 8.1 or so); if it's not, it then assumes that it's in the locale's encoding. If that turns out incorrect also, it just tries to pass it as-is to the operating system GUI API. Or something like that. From python at bdurham.com Tue May 4 17:37:51 2010 From: python at bdurham.com (python at bdurham.com) Date: Tue, 04 May 2010 17:37:51 -0400 Subject: Exclusively lock a file to prevent other processes from reading it? Message-ID: <1273009071.19963.1373400243@webmail.messagingengine.com> Is there a way to exclusively lock a file to prevent other processes from reading it while we have it open? I need to cache some overflow data to disk in a temp file and I want to make sure no other processes can read the contents of this file while I'm using it. I tried the following using an 'append binary' mode, but I can use NotePad to read the file while I'm using it: fd = open( r'a-temp-file.dat', 'ab' ) My environment is Python 2.6.4 (32-bit) under Windows, but I'm looking for a cross-platform solution if that's possible. Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From scott.freemire at gmail.com Tue May 4 17:40:20 2010 From: scott.freemire at gmail.com (Scott) Date: Tue, 4 May 2010 14:40:20 -0700 (PDT) Subject: Sharing a program I wrote Message-ID: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> I'm looking for suggestions on what to do (and how to do it) if I want to share a program that I wrote in Python. There seem to be quite a few places to post code and I don't know how to choose. I wrote a program (script?) that takes a text file containing the output of the "show access-list" command on a Cisco PIX/ASA/FWSM firewall and any number of text files containing syslog output from the same firewall and creates a report showing which access-list rules allowed which actual connections. It is written in Python 2.6 and runs on Windows. Since this is obviously something mankind has long been waiting for I am thinking about sharing it - but since I am new to Python and programming in general I am not at all familiar with dealing with source code. I'm sure that improvements and additions could be made if it was reviewed by "actual programmers" but I wouldn't exactly call it a "project" either. Of course I'd love to add a gui interface... I've seen pypi. It seems to index code that is posted on all sorts of sites - including pypi itself? And what is a "package" anyway? I've seen sourceforge. It looks like a good home for big applications or multi-developer projects. Freshmeat? Google code? My own website? Your blog? Another detail is that my program uses a library that was written by someone else. It is the most excellent netaddr written by David P. D. Moss and it lives at code.google.com. It uses the New BSD License. Since this library is required would I simply provide a link to it? Would I post the actual library? Do I have to post a copy of his copyright info anywhere? Please don't tell me I have to write some kind of installer that takes care of providing that. I really just want anyone who might need a little networking/security tool like this to be able to find it. Any advice? Thanks, Scott From python at bdurham.com Tue May 4 17:43:15 2010 From: python at bdurham.com (python at bdurham.com) Date: Tue, 04 May 2010 17:43:15 -0400 Subject: Generating nested code with context managers In-Reply-To: References: Message-ID: <1273009395.20712.1373401615@webmail.messagingengine.com> Terry, > So here is my updated (3.1) proof-of-concept version. Very clever! An excellent example of how to use the 'with' statement with something besides the traditional file open example. Not the original OP, but thank you anyway. Malcolm From philip at semanchuk.com Tue May 4 17:46:29 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 May 2010 17:46:29 -0400 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: <1273009071.19963.1373400243@webmail.messagingengine.com> References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: <647AB9C0-B8F3-4711-92D9-39799F248728@semanchuk.com> On May 4, 2010, at 5:37 PM, python at bdurham.com wrote: > Is there a way to exclusively lock a file to prevent other > processes from reading it while we have it open? > > I need to cache some overflow data to disk in a temp file and I > want to make sure no other processes can read the contents of > this file while I'm using it. > > I tried the following using an 'append binary' mode, but I can > use NotePad to read the file while I'm using it: > > fd = open( r'a-temp-file.dat', 'ab' ) > > My environment is Python 2.6.4 (32-bit) under Windows, but I'm > looking for a cross-platform solution if that's possible. Have a look at tempfile.mkstemp() in the standard library. From clp2 at rebertia.com Tue May 4 17:48:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 May 2010 14:48:59 -0700 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: <1273009071.19963.1373400243@webmail.messagingengine.com> References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: On Tue, May 4, 2010 at 2:37 PM, wrote: > Is there a way to exclusively lock a file to prevent other processes from > reading it while we have it open? > > I need to cache some overflow data to disk in a temp file and I want to make > sure no other processes can read the contents of this file while I'm using > it. > > I tried the following using an 'append binary' mode, but I can use NotePad > to read the file while I'm using it: > > fd = open( r'a-temp-file.dat', 'ab' ) > > My environment is Python 2.6.4 (32-bit) under Windows, but I'm looking for a > cross-platform solution if that's possible. I remember this recipe (or a variant) from the dead-tree Python Cookbook: http://code.activestate.com/recipes/65203-portalocker-cross-platform-posixnt-api-for-flock-s/ Cheers, Chris -- http://blog.rebertia.com From chris at simplistix.co.uk Tue May 4 18:07:11 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 04 May 2010 23:07:11 +0100 Subject: ooolib, reading writing a spread sheet and keep formatting In-Reply-To: <4BE09A9B.60404@free.fr> References: <4bd8cfc3$0$667$426a74cc@news.free.fr> <4BD94090.8060005@free.fr> <4BE09A9B.60404@free.fr> Message-ID: <4BE09A8F.5050803@simplistix.co.uk> News123 wrote: > Hi Chris, > > > Chris Withers wrote: >> News123 wrote: >>> from xlrd import open_workbook >>> from xlutils.copy import copy >>> >>> rb = open_workbook('doc1.xls') >> open_workbook('doc1.xls',formatting_info=True) > > I'll try, but the doc mentioned explicitely, that formulas will be lost. > I'll keep you updated. Yup, for them to be preserved, someone needs to either provide the patches or stump up the cash to get the features implemented. cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From news1234 at free.fr Tue May 4 18:07:23 2010 From: news1234 at free.fr (News123) Date: Wed, 05 May 2010 00:07:23 +0200 Subject: ooolib, reading writing a spread sheet and keep formatting In-Reply-To: References: <4bd8cfc3$0$667$426a74cc@news.free.fr> <4BD94090.8060005@free.fr> Message-ID: <4BE09A9B.60404@free.fr> Hi Chris, Chris Withers wrote: > News123 wrote: >> >> from xlrd import open_workbook >> from xlutils.copy import copy >> >> rb = open_workbook('doc1.xls') > > open_workbook('doc1.xls',formatting_info=True) I'll try, but the doc mentioned explicitely, that formulas will be lost. I'll keep you updated. > >> print "WB with %d sheets" % rb.nsheets >> wb = copy(rb) >> wb.save("doc2.xls") # file is created, but ALL formattng is lost and >> formulas are now diplayed as text > > From news1234 at free.fr Tue May 4 18:07:23 2010 From: news1234 at free.fr (News123) Date: Wed, 05 May 2010 00:07:23 +0200 Subject: ooolib, reading writing a spread sheet and keep formatting In-Reply-To: References: <4bd8cfc3$0$667$426a74cc@news.free.fr> <4BD94090.8060005@free.fr> Message-ID: <4BE09A9B.60404@free.fr> Hi Chris, Chris Withers wrote: > News123 wrote: >> >> from xlrd import open_workbook >> from xlutils.copy import copy >> >> rb = open_workbook('doc1.xls') > > open_workbook('doc1.xls',formatting_info=True) I'll try, but the doc mentioned explicitely, that formulas will be lost. I'll keep you updated. > >> print "WB with %d sheets" % rb.nsheets >> wb = copy(rb) >> wb.save("doc2.xls") # file is created, but ALL formattng is lost and >> formulas are now diplayed as text > > From tomf.sessile at gmail.com Tue May 4 18:34:23 2010 From: tomf.sessile at gmail.com (TomF) Date: Tue, 4 May 2010 15:34:23 -0700 Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <2010050415342385304-tomfsessile@gmailcom> Thanks to everyone for their comments. On 2010-05-04 07:11:08 -0700, alex23 said: > TomF wrote: >> I'm interested in improving my python design by studying a large, >> well-designed codebase. ?Someone (not a python programmer) suggested >> Django. ?I realize that Django is popular, but can someone comment on >> whether its code is well-designed and worth studying? > > Here's a viewpoint that says no: > http://mockit.blogspot.com/2010/04/mess-djangos-in.html > > There's a lot of good counterpoint in the comments too. I read most of the discussion. Yep, there is a LOT of disagreement about the code quality. I guess I'll dig in and see whether I can learn anything. > > (I also think there's value to be gained in studying _bad_ code, > too...) True, although whether that's time well spent is another question. Regards, -Tom From lists at cheimes.de Tue May 4 18:38:29 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 May 2010 00:38:29 +0200 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: <1273009071.19963.1373400243@webmail.messagingengine.com> References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: python at bdurham.com wrote: > Is there a way to exclusively lock a file to prevent other > processes from reading it while we have it open? > > I need to cache some overflow data to disk in a temp file and I > want to make sure no other processes can read the contents of > this file while I'm using it. > > I tried the following using an 'append binary' mode, but I can > use NotePad to read the file while I'm using it: > > fd = open( r'a-temp-file.dat', 'ab' ) > > My environment is Python 2.6.4 (32-bit) under Windows, but I'm > looking for a cross-platform solution if that's possible. I know of now mandatory file lock solution that works cross platform. On Unix file locks (flock(2)) are advisory locks. All applications must check the file lock and act accordantly. Your best choice is other a temporary file or a temporary directory owned by your application. Python's tempfile module contains several solutions to securely work with temporary files and directories. Please don't try to come up with your own solution. Your app can easily become vulnerable by symlink attacks. Christian From e_d_k at yahoo.com Tue May 4 18:51:28 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 4 May 2010 15:51:28 -0700 (PDT) Subject: Sharing a program I wrote In-Reply-To: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: <32883.64444.qm@web58708.mail.re1.yahoo.com> --- On Tue, 5/4/10, Scott wrote: > From: Scott > Subject: Sharing a program I wrote > To: python-list at python.org > Date: Tuesday, May 4, 2010, 5:40 PM > I'm looking for suggestions on what > to do (and how to do it) if I want > to share a program that I wrote in Python. There seem to be > quite a > few places to post code and I don't know how to choose. > > I wrote a program (script?) that takes a text file > containing the > output of? the "show access-list" command on a Cisco > PIX/ASA/FWSM > firewall and any number of text files containing syslog > output from > the same firewall and creates a report showing which > access-list rules > allowed which actual connections. It is written in Python > 2.6 and runs > on Windows. > > Since this is obviously something mankind has long been > waiting for I > am thinking about sharing it - but since I am new to Python > and > programming in general I am not at all familiar with > dealing with > source code. > > I'm sure that improvements and additions could be made if > it was > reviewed by "actual programmers" but I wouldn't exactly > call it a > "project" either. Of course I'd love to add a gui > interface... > > I've seen pypi. It seems to index code that is posted on > all sorts of > sites - including pypi itself? And what is a "package" > anyway? I've > seen sourceforge. It looks like a good home for big > applications or > multi-developer projects. Freshmeat? Google code? My own > website? Your > blog? > > Another detail is that my program uses a library that was > written by > someone else. It is the most excellent netaddr written by > David P. D. > Moss and it lives at code.google.com. It uses the New BSD > License. > Since this library is required would I simply provide a > link to it? > Would I post the actual library? Do I have to post a copy > of his > copyright info anywhere? Please don't tell me I have to > write some > kind of installer that takes care of providing that. > > I really just want anyone who might need a little > networking/security > tool like this to be able to find it. Any advice? > > Thanks, > Scott > -- > http://mail.python.org/mailman/listinfo/python-list > It depends on exactly what you want to do. I'd suggest you look at the following sites: http://developer.berlios.de/ http://codepad.org/ http://pastebin.com/ http://ideone.com/ One of them might be what your looking for. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From nobody at nowhere.com Tue May 4 19:44:14 2010 From: nobody at nowhere.com (Nobody) Date: Wed, 05 May 2010 00:44:14 +0100 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: On Tue, 04 May 2010 14:36:06 +0100, Baz Walter wrote: > this will work so long as the file is in a part of the filesystem that can > be traversed from the current directory to the root. what i'm not sure > about is whether it's possible to cross filesystem boundaries using this > kind of technique. At least on Linux, the kernel "fixes" the links at mount points, i.e. within the root directory of a mounted filesystem, ".." refers to the directory containing the mount point on the parent filesystem, while the mount point refers to the root directory of the mounted filesystem. This also appears to work correctly for bind mounts (mounting an arbitrary directory to another directory, which results in a directory hierarchy appearing at multiple locations within the filesystem), i.e. ".." refers to the appropriate directory for each "instance". OTOH, the algorithm can fail if a directory is moved (whether by rename() or remounting) between the stat("..") and the listdir(). From nobody at nowhere.com Tue May 4 20:03:17 2010 From: nobody at nowhere.com (Nobody) Date: Wed, 05 May 2010 01:03:17 +0100 Subject: Exclusively lock a file to prevent other processes from reading it? References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: On May 4, 2010, at 5:37 PM, python at bdurham.com wrote: > Is there a way to exclusively lock a file to prevent other processes > from reading it while we have it open? > My environment is Python 2.6.4 (32-bit) under Windows, but I'm looking > for a cross-platform solution if that's possible. Some Unix systems support mandatory locking; Linux used to, but the option appears to have been removed (and was seldom enabled). On Unix systems which support mandatory locking, it is enabled for a particular file by setting the setgid bit on a file which lacks group-execute permission. This causes fcntl() locks to be mandatory, i.e. they cause read()/write() operations to block rather than merely preventing conflicting locks from being obtained. But in general, you can't rely upon mandatory locking being available. From cs at zip.com.au Tue May 4 20:10:01 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 5 May 2010 10:10:01 +1000 Subject: strange interaction between open and cwd In-Reply-To: <4BE025AC.7070309@ftml.net> References: <4BE025AC.7070309@ftml.net> Message-ID: <20100505001000.GA8666@cskk.homeip.net> On 04May2010 14:48, Baz Walter wrote: | On 04/05/10 09:08, Gregory Ewing wrote: | >Grant Edwards wrote: | >>except that Python objects can form a generalized graph, and Unix | >>filesystems are constrained to be a tree. | > | >Actually I believe that root is allowed to create arbitrary | >hard links to directories in Unix, so it's possible to turn | >the file system in to a general graph. It's highly | >unrecommended, though, because it confuses the heck out of | >programs that recursively traverse directories (which is | >why only root is allowed to do it). | | i think there are versions of mac osx that use hard-linked | directories in their backup systems. I believe TimeMachine exploits that. I think one can make loops with recursive mounts. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ You can't go around hoping that most people have sterling moral characters. The most you can hope for is that people will pretend that they do. - Fran Lebowitz From james.harris.1 at googlemail.com Tue May 4 20:27:27 2010 From: james.harris.1 at googlemail.com (James Harris) Date: Tue, 4 May 2010 17:27:27 -0700 (PDT) Subject: Sharing a program I wrote References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: On 4 May, 22:40, Scott wrote: > I'm looking for suggestions on what to do (and how to do it) if I want > to share a program that I wrote in Python. There seem to be quite a > few places to post code and I don't know how to choose. Perhaps look at the options and then select whichever suits your needs best. > I wrote a program (script?) that takes a text file containing the > output of ?the "show access-list" command on a Cisco PIX/ASA/FWSM > firewall and any number of text files containing syslog output from > the same firewall and creates a report showing which access-list rules > allowed which actual connections. It is written in Python 2.6 and runs > on Windows. > > Since this is obviously something mankind has long been waiting for I > am thinking about sharing it - but since I am new to Python and > programming in general I am not at all familiar with dealing with > source code. > > I'm sure that improvements and additions could be made if it was > reviewed by "actual programmers" but I wouldn't exactly call it a > "project" either. Of course I'd love to add a gui interface... An option if you want reviews - and your code is short - is to post it here to comp.lang.python. > I've seen pypi. It seems to index code that is posted on all sorts of > sites - including pypi itself? And what is a "package" anyway? I've > seen sourceforge. It looks like a good home for big applications or > multi-developer projects. Freshmeat? Google code? My own website? Your > blog? Yes, many of these are well suited for significant projects. I set up http://codewiki.wikispaces.com/ Its focus is not on code size per se but on promoting sharing and updates. However, *smaller* pieces of code are preferred, i.e. code that can be viewed online and learned from. For example, see the Python programs at http://codewiki.wikispaces.com/index_by_language#x-Portable%20Python > > Another detail is that my program uses a library that was written by > someone else. It is the most excellent netaddr written by David P. D. > Moss and it lives at code.google.com. It uses the New BSD License. > Since this library is required would I simply provide a link to it? > Would I post the actual library? Do I have to post a copy of his > copyright info anywhere? Please don't tell me I have to write some > kind of installer that takes care of providing that. Unless you are worried that the original copy of the library may be deleted or lost it should be enough to post a link. Then the web site that contains the code would be responsible for explaining its licence and will include other relevant documentation. For my own code on codewiki I include installation instructions as text, where necessary. > I really just want anyone who might need a little networking/security > tool like this to be able to find it. Any advice? That was similar to my motive. Interestingly the highest number of page hits on the site is for a networking utility. James From sjmachin at lexicon.net Tue May 4 20:37:15 2010 From: sjmachin at lexicon.net (John Machin) Date: Tue, 4 May 2010 17:37:15 -0700 (PDT) Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> Message-ID: <5e4a1284-774c-4318-89a0-096f1434e942@a16g2000prg.googlegroups.com> On May 5, 12:11?am, "Barak, Ron" wrote: > > -----Original Message----- > > From: Stefan Behnel [mailto:stefan... at behnel.de] > > Sent: Tuesday, May 04, 2010 10:24 AM > > To: python-l... at python.org > > Subject: Re: How to get xml.etree.ElementTree not bomb on > > invalid characters in XML file ? > > > Barak, Ron, 04.05.2010 09:01: > > > ?I'm parsing XML files using ElementTree from xml.etree (see code > > > below (and attached xml_parse_example.py)). > > > > However, I'm coming across input XML files (attached an example: > > > tmp.xml) which include invalid characters, that produce the > > following > > > traceback: > > > > $ python xml_parse_example.py > > > Traceback (most recent call last): > > > xml.parsers.expat.ExpatError: not well-formed (invalid > > token): line 6, > > > column 34 > > > I hope you are aware that this means that the input you are > > parsing is not XML. It's best to reject the file and tell the > > producers that they are writing broken output files. You > > should always fix the source, instead of trying to make sense > > out of broken input in fragile ways. > > > > I read the documentation for xml.etree.ElementTree and see > > that it may > > > take an optional parser parameter, but I don't know what > > this parser > > > should be - to ignore the invalid characters. > > > > Could you suggest a way to call ElementTree, so it won't > > bomb on these > > > invalid characters ? > > > No. The parser in lxml.etree has a 'recover' option that lets > > it try to recover from input errors, but in general, XML > > parsers are required to reject non well-formed input. > > > Stefan > > Hi Stefan, > The XML file seems to be valid XML (all XML viewers I tried were able to read it). > You can verify this by trying to read the XML example I attached to the original message (attached again here). > Actually, when trying to view the file with an XML viewer, these offensive characters are not shown. > It's just that some of the fields include characters that the parser used by ElementTree seems to chock on. > Bye, > Ron. > > ?tmp_small.xml > < 1KViewDownload Have a look at your file with e.g. a hex editor or just Python repr() -- see below. You will see that there are four cases of good_data\x00garbage where "garbage" is repeated \x00 or just random line noise or uninitialised memory. "MainStorage_snap\x00\x00*SNIP*\x00\x00" "BROLB21\x00\xee"\x00\x00\x00\x90,\x02G\xdc\xfb\x04P\xdc \xfb\x04\x01a\xfc>(\xe8\xfb\x04" It's a toss-up whether the > in there is accidental or a deliberate attempt to sanitise the garbage !-) "Alstom\x00\x00o\x00m\x00\x00*SNIP*\x00\x00" "V5R1.28.1 [R - LA]\x00\x00*SNIP*\x00\x00" The garbage in the 2nd case is such as to make the initial declaration encoding="UTF-8" an outright lie and I'm curious as to how the XML parser managed to get as far as it did -- it must decode a line at a time. As already advised: it's much better to reject that rubbish outright than to attempt to repair it. Repair should be contemplated only if it's a one-off exercise AND you can't get a fixed copy from the source. And while we're on the subject of rubbish: """The XML file seems to be valid XML (all XML viewers I tried were able to read it).""" The conclusion from that is that all XML viewers that you tried are rubbish. From wuwei23 at gmail.com Tue May 4 20:38:27 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 May 2010 17:38:27 -0700 (PDT) Subject: Generating nested code with context managers References: Message-ID: On May 5, 6:36?am, Terry Reedy wrote: > The relatively new with statement and associated context managers are > designed, among other things, for this situation, where one needs to > alter and restore a global context. So here is my updated (3.1) > proof-of-concept version. This is what I love about c.l.p, you wait 10 mins and someone proves your point with working code :) I had a more generic 'with indentation:' context manager in mind, but I really like your approach. Cheers. From wuwei23 at gmail.com Tue May 4 20:47:07 2010 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 May 2010 17:47:07 -0700 (PDT) Subject: Teaching Programming References: Message-ID: Ed Keith wrote: > Knuth wanted the generated source to be unreadable, so people would not be tempted to edit the generated code. This is my biggest issue with Knuth's view of literate programming. If the generated source isn't readable, am I just supposed to trust it? How can I tell if an error lies in my expression of the algorithm or in the code generation itself? From sjmachin at lexicon.net Tue May 4 21:21:23 2010 From: sjmachin at lexicon.net (John Machin) Date: Tue, 4 May 2010 18:21:23 -0700 (PDT) Subject: How to get xml.etree.ElementTree not bomb on invalid characters in XML file ? References: <7F0503CD69378F49BE0DC30661C6CCF6A3B872A1@enbmail01.lsi.com> <7F0503CD69378F49BE0DC30661C6CCF6A3B87357@enbmail01.lsi.com> Message-ID: On May 5, 3:43?am, Terry Reedy wrote: > On 5/4/2010 11:37 AM, Stefan Behnel wrote: > > > Barak, Ron, 04.05.2010 16:11: > >> The XML file seems to be valid XML (all XML viewers I tried were able > >> to read it). > > ?From Internet Explorer: > > The XML page cannot be displayed > Cannot view XML input using XSL style sheet. Please correct the error > and then click the Refresh button, or try again later. > > -------------------------------------------------------------------------------- > > An invalid character was found in text content. Error processing > resource 'file:///C:/Documents and Settings... > > ? ? ? "BROLB21 > > > > > This is what xmllint gives me: > > > ----------------------- > > $ xmllint /home/sbehnel/tmp.xml > > tmp.xml:6: parser error : Char 0x0 out of allowed range > > "MainStorage_snap > > ^ > > tmp.xml:6: parser error : Premature end of data in tag m_sanApiName1 line 6 > > "MainStorage_snap > > ^ > > tmp.xml:6: parser error : Premature end of data in tag DbHbaGroup line 5 > > "MainStorage_snap > > ^ > > tmp.xml:6: parser error : Premature end of data in tag database line 4 > > "MainStorage_snap > > ^ > > ----------------------- > > > The file contains 0-bytes - clearly not XML. > > IE agrees. Look closer. IE *DOESN'T* agree. It has ignored the problem on line 6 and lurched on to the next problem (in line 11). If you edit that file to remove the line noise in line 11, leaving the 3 cases of multiple \x00 bytes, IE doesn't complain at all about the (invalid) \x00 bytes. From bazwal at ftml.net Tue May 4 21:41:09 2010 From: bazwal at ftml.net (Baz Walter) Date: Wed, 05 May 2010 02:41:09 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: <4BE0CCB5.7050307@ftml.net> On 05/05/10 00:44, Nobody wrote: > On Tue, 04 May 2010 14:36:06 +0100, Baz Walter wrote: > >> this will work so long as the file is in a part of the filesystem that can >> be traversed from the current directory to the root. what i'm not sure >> about is whether it's possible to cross filesystem boundaries using this >> kind of technique. > > At least on Linux, the kernel "fixes" the links at mount points, i.e. > within the root directory of a mounted filesystem, ".." refers to > the directory containing the mount point on the parent filesystem, while > the mount point refers to the root directory of the mounted filesystem. > > This also appears to work correctly for bind mounts (mounting an arbitrary > directory to another directory, which results in a directory hierarchy > appearing at multiple locations within the filesystem), i.e. ".." refers > to the appropriate directory for each "instance". > > OTOH, the algorithm can fail if a directory is moved (whether by rename() > or remounting) between the stat("..") and the listdir(). i think the algorithm also can't guarantee the intended result when crossing filesystem boundaries. IIUC, a stat() call on the root directory of a mounted filesystem will give the same inode number as its parent. so if several filesystems are mounted in the same parent directory, there is no way to tell which of them is the "right" one. From dchichkov at gmail.com Tue May 4 21:55:41 2010 From: dchichkov at gmail.com (dmtr) Date: Tue, 4 May 2010 18:55:41 -0700 (PDT) Subject: A python interface to google-sparsehash? Message-ID: <44f814e1-a24e-4ee6-bbd1-b28f4355af44@y6g2000pra.googlegroups.com> Anybody knows if a python sparsehash module is there in the wild? From scott.freemire at gmail.com Tue May 4 23:25:35 2010 From: scott.freemire at gmail.com (Scott) Date: Tue, 4 May 2010 20:25:35 -0700 (PDT) Subject: Sharing a program I wrote References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: James, Thanks for the comprehensive reply. I would like to post it to comp.lang.python but the main file is 169 lines long and the file for functions is 316 lines long. I'm thinking that is a little long for this format. Maybe I can put them up on a basic web page or file sharing site and just post a link. Is that well received on this forum? Thanks, Scott From michele.simionato at gmail.com Wed May 5 00:08:28 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 4 May 2010 21:08:28 -0700 (PDT) Subject: Sphinx hosting References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> Message-ID: <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> On May 4, 9:48?am, James Mills wrote: > On Tue, May 4, 2010 at 5:27 PM, Michele Simionato > > wrote: > > Cool, that's good to know. I am still accepting recommendations for > > non-Python projects ;) > > bitbucket (1) also provide static file hosting through the wiki. From > what I understand (tested) > you simply clone the wiki repository (which is it's own repository) > and commit a bunch of .html > files. > > cheers > James > > 1.http://bitbucket.org/ Interesting. I tried to see if the same was true for the Wiki in Google code but apparently it does not work. Does anybody here know if it is possible to publish raw html in the Google Code wiki and how does it work? From lie.1296 at gmail.com Wed May 5 00:16:56 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 05 May 2010 14:16:56 +1000 Subject: Sharing a program I wrote In-Reply-To: References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: <4be0f197$1@dnews.tpgi.com.au> On 05/05/10 13:25, Scott wrote: > James, > > Thanks for the comprehensive reply. I would like to post it to > comp.lang.python but the main file is 169 lines long and the file for > functions is 316 lines long. I'm thinking that is a little long for > this format. Maybe I can put them up on a basic web page or file > sharing site and just post a link. Is that well received on this > forum? > > Thanks, > Scott Make it as easy as possible for people to get to your code; file sharing site isn't very good for this (especially those that have wait time and download limits and if you have to zip your file). If you're setting up a webpage you need to take care not to mess up special characters. Using pastebin is fairly well-received as people won't have to save the file to their harddrive to see the content and their page is specifically set up for displaying code (syntax highlighting and stuffs). If your code is specifically reusable or if it illustrates a certain concept, posting it as Activestate recipe is great as well. From nagle at animats.com Wed May 5 00:19:35 2010 From: nagle at animats.com (John Nagle) Date: Tue, 04 May 2010 21:19:35 -0700 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: <4be0ec73$0$1661$742ec2ed@news.sonic.net> Philip Semanchuk wrote: > > On May 4, 2010, at 5:37 PM, python at bdurham.com wrote: > >> Is there a way to exclusively lock a file to prevent other >> processes from reading it while we have it open? If you can use SQLite to store the data, it will deal with your locking problems. The pain of getting locking right has already been dealt with by others. Classic lock files are iffy. They're not race condition free on NTFS, and all the junk needed to clean up lock files properly after a crash is a headache. John Nagle From clp2 at rebertia.com Wed May 5 00:23:10 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 May 2010 21:23:10 -0700 Subject: Sharing a program I wrote In-Reply-To: <4be0f197$1@dnews.tpgi.com.au> References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> <4be0f197$1@dnews.tpgi.com.au> Message-ID: On Tue, May 4, 2010 at 9:16 PM, Lie Ryan wrote: > On 05/05/10 13:25, Scott wrote: >> I would like to post it to >> comp.lang.python but the main file is 169 lines long and the file for >> functions is 316 lines long. I'm thinking that is a little long for >> this format. Maybe I can put them up on a basic web page or file >> sharing site and just post a link. Is that well received on this >> forum? >> > Make it as easy as possible for people to get to your code; file sharing > site isn't very good for this (especially those that have wait time and > download limits and if you have to zip your file). If you're setting up > a webpage you need to take care not to mess up special characters. Using > pastebin is fairly well-received as people won't have to save the file > to their harddrive to see the content and their page is specifically set > up for displaying code (syntax highlighting and stuffs). > > If your code is specifically reusable or if it illustrates a certain > concept, posting it as Activestate recipe is great as well. In case Scott's not familiar, obligatory link: http://code.activestate.com/recipes/langs/python/ Cheers, Chris -- http://blog.rebertia.com From prologic at shortcircuit.net.au Wed May 5 00:39:11 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 5 May 2010 14:39:11 +1000 Subject: Sphinx hosting In-Reply-To: <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> Message-ID: On Wed, May 5, 2010 at 2:08 PM, Michele Simionato wrote: > Interesting. I tried to see if the same was true for the Wiki in > Google code but apparently it does not work. Does anybody here know if > it is possible to publish raw html in the Google Code wiki and how > does it work? I may be wrong, but I recall that Google Code Hosting's Wiki Engine has a macro that will allow you to render raw HTML. cheers James From gagsl-py2 at yahoo.com.ar Wed May 5 01:09:01 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 May 2010 02:09:01 -0300 Subject: CGI python 3 write RAW BINARY References: <4bd8ae7e$0$27615$ba4acef3@reader.news.orange.fr> <4bd96540$0$27597$ba4acef3@reader.news.orange.fr> <4bd9b4c2$0$27606$ba4acef3@reader.news.orange.fr> <4bd9fc1a$0$2980$ba4acef3@reader.news.orange.fr> <4bdc07d4$0$2980$ba4acef3@reader.news.orange.fr> Message-ID: En Sat, 01 May 2010 07:52:01 -0300, Dodo escribi?: > Le 30/04/2010 17:52, Antoine Pitrou a ?crit : >> Le Thu, 29 Apr 2010 23:37:32 +0200, Dodo a ?crit : >>> ....I don't get a thing. >>> Now with the fix : >>> All browsers shows a different thing, but not the image! >>> http://ddclermont.homeip.net/misc/python/ >>> >>> If I save it to computer : >>> * Windows image viewer won't read it >>> * Irfanview can read it without problems >> >> Did you set the content-type and content-length in the HTTP headers? >> Can you post your code? >> >> > I didn't know about content-lenght > Here's the new code (I used a fixed image patch to make sure this is not > the source of the problem) > > > #!/usr/bin/python3 > import cgi, sys, cgitb > cgitb.enable() > > f = open("/home/dodo/54.jpg", "rb") > data = f.read() > l = len(data) > f.close() > > print("Content-type:image/jpg\nContent-length:%d\n\n" % l) > > sys.stdout.flush() > sys.stdout.buffer.write( data ) Computers are dumb. You have to speak to them very slow and clearly in order to be understood :) You need a space after those ':'. The correct media type for JPEG images is image/jpeg. And (the important thing) you have one more \n than necessary. Each header field finishes with \n; an empty line (just \n) marks the end of all headers; the body [your image] must follow immediately. #!/usr/bin/python3 import cgi, sys, cgitb cgitb.enable() f = open("/home/dodo/54.jpg", "rb") data = f.read() l = len(data) f.close() print("Content-Type: image/jpeg\nContent-Length: %d\n" % l) sys.stdout.flush() sys.stdout.buffer.write( data ) (Probably, a better way would be to replace all those \n with \r\n, and not use print at all, but the above code is good enough). -- Gabriel Genellina From michele.simionato at gmail.com Wed May 5 01:35:55 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 4 May 2010 22:35:55 -0700 (PDT) Subject: Sphinx hosting References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> Message-ID: <1aeaac06-ff0e-4ec1-8f7d-fc71891228c0@b18g2000yqb.googlegroups.com> On May 5, 6:39?am, James Mills wrote: > On Wed, May 5, 2010 at 2:08 PM, Michele Simionato > > wrote: > > Interesting. I tried to see if the same was true for the Wiki in > > Google code but apparently it does not work. Does anybody here know if > > it is possible to publish raw html in the Google Code wiki and how > > does it work? > > I may be wrong, but I recall that Google Code Hosting's Wiki Engine > has a macro that will allow you to render raw HTML. > > cheers > James I am sure it has, but I was talking about just putting in the repository an index.html file and have it published, the wayI hear it works in BitBucket and GitHub. From prologic at shortcircuit.net.au Wed May 5 02:00:31 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 5 May 2010 16:00:31 +1000 Subject: Sphinx hosting In-Reply-To: <1aeaac06-ff0e-4ec1-8f7d-fc71891228c0@b18g2000yqb.googlegroups.com> References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> <1aeaac06-ff0e-4ec1-8f7d-fc71891228c0@b18g2000yqb.googlegroups.com> Message-ID: On Wed, May 5, 2010 at 3:35 PM, Michele Simionato wrote: > I am sure it has, but I was talking about just putting in the > repository an index.html file and have it published, the wayI hear ?it > works in BitBucket and GitHub. I'm pretty sure Google Code Hosting doesn't support rendering text/html mime-type files in the repository (like Trac can). On a side-note, not sure if you're interested in this at all... I wrote (for the hell/fun of it) a "Sphinx Server", here's the code: http://codepad.org/ywo8pscb This uses the latest development version of circuits (1) cheers James 1. http://bitbucket.org/prologic/circuits/ From gagsl-py2 at yahoo.com.ar Wed May 5 02:05:37 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 May 2010 03:05:37 -0300 Subject: Fast Efficient way to transfer an object to another list References: Message-ID: En Fri, 30 Apr 2010 23:16:04 -0300, Jimbo escribi?: > Hello I have a relatively simple thing to do; move an object from one > to list into another. But I think my solution maybe inefficient & > slow. Is there a faster better way to move my stock object from one > list to another? (IE, without having to use a dictionary instead of a > list or is that my only solution?) > > [code] > class stock: > > code = "NULL" > price = 0 > > > stock_list1 = [] > stock_list2 = [] > > def transfer_stock(stock_code, old_list, new_list): > """ Transfer a stock from one list to another """ > # is there a more efficient & faster way to > > index = 0 > > for stock in old_list: > > temp_stock = stock > > if temp_stock.code == stock_code: > new_list.append(temp_stock) > del old_list[index] > index += 1 > > return new_list[/code] I'd do that in two steps: def transfer_stock(stock_code, old_list, new_list): # find the indexes to transfer indexes = [i for i,stock in enumerate(old_list) if stock.code==stock_code] # actually transfer them for index in reversed(indexes): stock = old_list[index] new_list.append(stock) del old_list[index] # I would not return anything -- Gabriel Genellina From nobody at nowhere.com Wed May 5 02:24:02 2010 From: nobody at nowhere.com (Nobody) Date: Wed, 05 May 2010 07:24:02 +0100 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: On Wed, 05 May 2010 02:41:09 +0100, Baz Walter wrote: > i think the algorithm also can't guarantee the intended result when > crossing filesystem boundaries. IIUC, a stat() call on the root directory > of a mounted filesystem will give the same inode number as its parent. Nope; it will have the same dev/inode pair as if it wasn't mounted, i.e. the device will refer to the mounted device, not the device it's mounted on, and the inode will be the mounted filesystem's root inode (typically #2 for Linux ext2/ext3 filesystems). And stat()ing the appropriate entry in the parent directory will return the same information, i.e. the root inode of the mounted device, not the subdirectory of the parent device (as you would see if the filesystem was unmounted). IOW, if stat("foo") reports a different device to stat("."), "foo" is a mount point, while if stat("..") reports a different device to stat("."), the current directory is the root of a mounted filesystem. > so > if several filesystems are mounted in the same parent directory, there is > no way to tell which of them is the "right" one. The only case which would cause a problem here is if you mount the same device on two different subdirectories of a common directory. But in that case, it doesn't really matter which answer you get, as they're both equivalent in any sense that matters. From davea at ieee.org Wed May 5 04:50:11 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 05 May 2010 04:50:11 -0400 Subject: Teaching Programming In-Reply-To: References: Message-ID: <4BE13143.6040904@ieee.org> alex23 wrote: > Ed Keith wrote: > >> Knuth wanted the generated source to be unreadable, so people would not be tempted to edit the generated code. >> > > This is my biggest issue with Knuth's view of literate programming. If > the generated source isn't readable, am I just supposed to trust it? > How can I tell if an error lies in my expression of the algorithm or > in the code generation itself? > > Do you think a compiler is required to make its object file conveniently readable? Do you regularly read the machine code generated by your C compiler? I admit I've frequently studied compiler output over the years, but I think I'm very unusual in that respect. I've never disassembled a python byte code file, though I wrote tools to display and manipulate both java byte code files and dot-net (before it was called that). I think the question really boils down to whether you trust the compiler. DaveA From bruno.42.desthuilliers at websiteburo.invalid Wed May 5 04:59:01 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 05 May 2010 10:59:01 +0200 Subject: Django as exemplary design In-Reply-To: <2010050415342385304-tomfsessile@gmailcom> References: <2010050312243328275-tomfsessile@gmailcom> <2010050415342385304-tomfsessile@gmailcom> Message-ID: <4be132f1$0$20639$426a74cc@news.free.fr> TomF a ?crit : > > On 2010-05-04 07:11:08 -0700, alex23 said: (snip) >> (I also think there's value to be gained in studying _bad_ code, >> too...) > > True, although whether that's time well spent is another question. The more bad code (mine or not) I have to maintain (or even just read and understand), the more I pay attention to my own design and code quality. Sometimes you only understand why something is bad, why it is bad and how bad it is when you have to deal with it :( From pavlovevidence at gmail.com Wed May 5 05:17:12 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 5 May 2010 02:17:12 -0700 (PDT) Subject: Python debuggers with sys.settrace() References: Message-ID: <1f8f2c8e-3ee1-4fc1-95e8-aae3e54ba1b4@n37g2000prc.googlegroups.com> On May 2, 11:06?am, Sarah Mount wrote: > This is a bit of an odd question, but is there any way for a Python > debugger to suppress I/O generated by the program which is being > debugged? I guess an "obvious" thing to do would be to replace core > parts of the standard library and change any relevant imports in the > locals and globals dicts to fake ones which don't generate I/O, but > this seems brittle as the standard library will change over time. Is > it possible to modify the byte-compiled code in each stack frame? Or > is there a simpler way to do this? It's not foolproof but you could try to reassign sys.stdout and sys.stderr to a bit bucket ("sys.stdout = open(os.devull)"), then invoke the debugger with stdout set to sys._stdout (the actual stdout). You'll have to create the Pdb() by hand since the built-in convience functions don't do it. Check the file pdb.py for details. Carl Banks From robin1 at cnsp.com Wed May 5 05:44:57 2010 From: robin1 at cnsp.com (Robin) Date: Wed, 5 May 2010 02:44:57 -0700 (PDT) Subject: the solution to your current problems........join this: http://www.thevoid1.net/para Message-ID: <76cf627c-3212-48ba-9fa4-37e766d4c9a1@37g2000yqm.googlegroups.com> the solution to your current problems........join this: http://www.thevoid1.net/para From e_d_k at yahoo.com Wed May 5 06:32:24 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Wed, 5 May 2010 03:32:24 -0700 (PDT) Subject: Teaching Programming In-Reply-To: Message-ID: <472926.69200.qm@web58701.mail.re1.yahoo.com> --- On Tue, 5/4/10, alex23 wrote: > From: alex23 > Subject: Re: Teaching Programming > To: python-list at python.org > Date: Tuesday, May 4, 2010, 8:47 PM > Ed Keith > wrote: > > Knuth wanted the generated source to be unreadable, so > people would not be tempted to edit the generated code. > > This is my biggest issue with Knuth's view of literate > programming. If > the generated source isn't readable, am I just supposed to > trust it? > How can I tell if an error lies in my expression of the > algorithm or > in the code generation itself? > > -- > http://mail.python.org/mailman/listinfo/python-list > My feelings exactly. I can see an argument for an option to emit obstructed code, but the default should be readable. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From hiralsmaillist at gmail.com Wed May 5 06:34:06 2010 From: hiralsmaillist at gmail.com (hiral) Date: Wed, 5 May 2010 03:34:06 -0700 (PDT) Subject: how to import subprocess into my 'subprocess.py' file Message-ID: <7a0a477e-1473-4001-b167-a9f96ff3a1d8@y18g2000prn.googlegroups.com> Hi, I am doing following in my 'subprocess.py' file... 1 from __future__ import absolute_import 2 from subprocess import * 3 from subprocess import call as myCall 4 from subprocess import Popen as myPopen 5 6 def getProperCmd(cmd): 7 cmd += 'time' # this is just an example; in fact I am doing lots of processing on cmd 8 return cmd 9 10 11 def call(cmd, **kwargs): 12 return myCall(getProperCmd(cmd), **kwargs) 13 14 def Popen(cmd, **kwargs): 15 return myPopen(getProperCmd(cmd), **kwargs) When running this it gives following error... Traceback (most recent call last): File "subprocess.py", line 2, in from subprocess import * File "subprocess.py", line 3, in from subprocess import call as myCall ImportError: cannot import name call So how can I create a python file (with the same name as standard module name) with custom methods? Thank you in advance. -Hiral From googler.1.webmaster at spamgourmet.com Wed May 5 08:04:06 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Wed, 5 May 2010 05:04:06 -0700 (PDT) Subject: Python Embedding, no correct lib Message-ID: <5d90e51f-133f-4b01-9074-9fdc3eb37d59@e35g2000yqm.googlegroups.com> Hi, I have a serious problem with Python. I am currently trying to implement Python into my app. Well this works fine, but get this: I have my own Python interpreter in a subfolder of my app. When I start my app, PYTHONHOME is set, and an environment variable is set to it can find the python DLL on startup. When Python is not installed on the system everything works fine as expected. When I now install Python on my system (so I have two python libs now) the system installation is the preferred one. print sys.path prints out ['', 'C:\Windows \system32\python26.zip', ...] and I cant explain whats going wrong here. I expected that it just uses the System lib when it cannot find it in the subfolder which I set in the environment variables before.. :-( Any ideas? Thanks a lot for help. Bye, moerchendiser2k3 From nospam at news.eternal-september.org Wed May 5 08:14:11 2010 From: nospam at news.eternal-september.org (balzer) Date: Wed, 5 May 2010 15:14:11 +0300 Subject: Portable Python Message-ID: Is there any difference in functionality between standard Python pack and portable Python? Why standard Python pack installation requires reboot after installation? Can portable Python used from hard drive folder? From bazwal at ftml.net Wed May 5 08:23:03 2010 From: bazwal at ftml.net (Baz Walter) Date: Wed, 05 May 2010 13:23:03 +0100 Subject: strange interaction between open and cwd In-Reply-To: References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: <4BE16327.5050209@ftml.net> On 05/05/10 07:24, Nobody wrote: > On Wed, 05 May 2010 02:41:09 +0100, Baz Walter wrote: > >> i think the algorithm also can't guarantee the intended result when >> crossing filesystem boundaries. IIUC, a stat() call on the root directory >> of a mounted filesystem will give the same inode number as its parent. > > Nope; it will have the same dev/inode pair as if it wasn't mounted, i.e. > the device will refer to the mounted device, not the device it's mounted > on, and the inode will be the mounted filesystem's root inode (typically > #2 for Linux ext2/ext3 filesystems). > > And stat()ing the appropriate entry in the parent directory will return > the same information, i.e. the root inode of the mounted device, not the > subdirectory of the parent device (as you would see if the filesystem was > unmounted). yes, that's actually what i meant (but probably put badly as usual). > IOW, if stat("foo") reports a different device to stat("."), "foo" > is a mount point, while if stat("..") reports a different device to > stat("."), the current directory is the root of a mounted filesystem. > >> so >> if several filesystems are mounted in the same parent directory, there is >> no way to tell which of them is the "right" one. > > The only case which would cause a problem here is if you mount the same > device on two different subdirectories of a common directory. But in that > case, it doesn't really matter which answer you get, as they're both > equivalent in any sense that matters. nope! just to be clear: here's what i get on my system, where '/dev/sda1' and '/dev/sda6' are mounted at '/boot' and '/home' respectively: >>> os.stat('/').st_ino 2L >>> os.stat('/usr').st_ino 212993L >>> os.stat('/boot').st_ino 2L >>> os.stat('/home').st_ino 2L >>> if the algorithm is climbing up from '/home/baz/tmp/xxx', what does it do when it searches os.listdir('../../../..')? how can it tell whether 'boot' or 'home' is the correct next parent if it only checks the inode number? i think the algorithm would at least need to take account of changes in the current device id. not sure whether that would be enough to cover all cases, though. From steve at REMOVE-THIS-cybersource.com.au Wed May 5 08:32:48 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 May 2010 12:32:48 GMT Subject: how to import subprocess into my 'subprocess.py' file References: <7a0a477e-1473-4001-b167-a9f96ff3a1d8@y18g2000prn.googlegroups.com> Message-ID: <4be16570$0$27823$c3e8da3@news.astraweb.com> On Wed, 05 May 2010 03:34:06 -0700, hiral wrote: > So how can I create a python file (with the same name as standard module > name) with custom methods? Don't do this. It will lead to nothing but trouble. Python doesn't support multiple modules with the same name. Unless you create a custom importer, a module called subprocess will shadow (hide) the original subprocess module. -- Steven From nospam at news.eternal-september.org Wed May 5 08:47:33 2010 From: nospam at news.eternal-september.org (balzer) Date: Wed, 5 May 2010 15:47:33 +0300 Subject: Movable Python or ActivePython Message-ID: I want Python pack that can run without being installed, mostly for testing programs. As I read, Movable Python can run without being installed. It needs no registry entries and knows the path to all the dlls (system or otherwise) that it uses. Whats about ActivePython http://www.activestate.com/activepython/downloads? Does it requires installation? From massi_srb at msn.com Wed May 5 08:56:03 2010 From: massi_srb at msn.com (Massi) Date: Wed, 5 May 2010 05:56:03 -0700 (PDT) Subject: Create a new process to run python function Message-ID: Hi everyone, in my script (python 2.5 on windows xp) I need to run a simple function in a separate process. In other words I need something similar to the fork function under UNIX. I tried with threads: import os, threading def func(s) : print "I'm thread number "+s, os.getpid() threading.Thread(target=func, args=("1",)).start() threading.Thread(target=func, args=("2",)).start() but this does not work, since the two threads share the same pid. Can anyone give me a suggestion? Thanks in advance. From jeanmichel at sequans.com Wed May 5 08:56:29 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 05 May 2010 14:56:29 +0200 Subject: how to import subprocess into my 'subprocess.py' file In-Reply-To: <7a0a477e-1473-4001-b167-a9f96ff3a1d8@y18g2000prn.googlegroups.com> References: <7a0a477e-1473-4001-b167-a9f96ff3a1d8@y18g2000prn.googlegroups.com> Message-ID: <4BE16AFD.9000805@sequans.com> hiral wrote: > Hi, > > I am doing following in my 'subprocess.py' file... > > 1 from __future__ import absolute_import > 2 from subprocess import * > 3 from subprocess import call as myCall > 4 from subprocess import Popen as myPopen > 5 > 6 def getProperCmd(cmd): > 7 cmd += 'time' # this is just an example; in fact I am doing > lots of processing on cmd > 8 return cmd > 9 > 10 > 11 def call(cmd, **kwargs): > 12 return myCall(getProperCmd(cmd), **kwargs) > 13 > 14 def Popen(cmd, **kwargs): > 15 return myPopen(getProperCmd(cmd), **kwargs) > > When running this it gives following error... > > Traceback (most recent call last): > File "subprocess.py", line 2, in > from subprocess import * > File "subprocess.py", line 3, in > from subprocess import call as myCall > ImportError: cannot import name call > > > So how can I create a python file (with the same name as standard > module name) with custom methods? > > Thank you in advance. > -Hiral > Just don't do that, find another name. Dont use * in import statement: "Namespaces are one honking great idea -- let's do more of those!" ("import this" in a shell for more rules) Using * in import statements removes namespaces. JM From python at bdurham.com Wed May 5 09:20:19 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 09:20:19 -0400 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: <1273009071.19963.1373400243@webmail.messagingengine.com> References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: <1273065619.18441.1373515393@webmail.messagingengine.com> Chris, Philip, Christian, John and others, Thank you all for your replies. Regards, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Wed May 5 09:20:19 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 09:20:19 -0400 Subject: Exclusively lock a file to prevent other processes from reading it? In-Reply-To: <1273009071.19963.1373400243@webmail.messagingengine.com> References: <1273009071.19963.1373400243@webmail.messagingengine.com> Message-ID: <1273065619.18441.1373515393@webmail.messagingengine.com> Chris, Philip, Christian, John and others, Thank you all for your replies. Regards, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From goon12 at gmail.com Wed May 5 09:20:32 2010 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 5 May 2010 09:20:32 -0400 Subject: Create a new process to run python function In-Reply-To: References: Message-ID: On Wed, May 5, 2010 at 8:56 AM, Massi wrote: > but this does not work, since the two threads share the same pid. Can > anyone give me a suggestion? Have you looked at os.fork ? http://docs.python.org/library/os.html#os.fork From lists at cheimes.de Wed May 5 09:29:25 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 May 2010 15:29:25 +0200 Subject: Create a new process to run python function In-Reply-To: References: Message-ID: Joe Riopel wrote: > On Wed, May 5, 2010 at 8:56 AM, Massi wrote: >> but this does not work, since the two threads share the same pid. Can >> anyone give me a suggestion? > > Have you looked at os.fork ? > http://docs.python.org/library/os.html#os.fork Fork on Windows XP? Have a lot of fun ... The NT Kernel has support for forking but neither the Win32 API nor Python supports it. Christian From gelonida at gmail.com Wed May 5 09:34:34 2010 From: gelonida at gmail.com (gelonida) Date: Wed, 5 May 2010 06:34:34 -0700 (PDT) Subject: find out whther byte two .pyc files contain the same byte code. Message-ID: <8d53dbc5-9ad0-44ed-881f-fa2b6fc82e96@i9g2000yqi.googlegroups.com> Hi, I'd like to know whether the byte code of two .pyc files is identical. I thought, I could just compare the md5sums of thw .pyc files. However this does not work. It seems, that .pyc ontains the time stamp of the source file. the .pyc file changes its contents when I don't change the file's contents but just save it again. Is there any way to compare two .pyc files or to just strip the timestiam or set it to a fixed value? Example: ##### I create a python file $ echo 'print 1' > tst.py ##### I compile it and display the md5sum of the .pyc file $ rm -f tst.pyc ; python -c 'import tst' ; md5sum tst.pyc 1 0d67af4c2c233dbbe89bd2dab6b12088 *tst.pyc ##### now I recompile and will get the same md5sum $ rm -f tst.pyc ; python -c 'import tst' ; md5sum tst.pyc 1 0d67af4c2c233dbbe89bd2dab6b12088 *tst.pyc #### now I change the time stamp of the python source touch tst.py #### now the md5sum will be different $ rm -f tst.pyc ; python -c 'import tst' ; md5sum tst.pyc 1 f6faf2048b6f967c73e68951558f954c *tst.pyc thanks for any suggestions / ideas From james.harris.1 at googlemail.com Wed May 5 10:29:16 2010 From: james.harris.1 at googlemail.com (James Harris) Date: Wed, 5 May 2010 07:29:16 -0700 (PDT) Subject: Sharing a program I wrote References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: <9c80c3f4-004c-4b80-9a3f-6d48abc97822@q32g2000yqb.googlegroups.com> On 5 May, 04:25, Scott wrote: > James, > > Thanks for the comprehensive reply. I would like to post it to > comp.lang.python but the main file is 169 lines long and the file for > functions is 316 lines long. I'm thinking that is a little long for > this format. You're welcome. Yes, it sounds a bit long for a direct post. In general, comments are more forthcoming on smaller pithier code fragments. > Maybe I can put them up on a basic web page or file > sharing site and just post a link. Is that well received on this > forum? I can't answer for how it would be received here but once you have addressed any Python issues you may want to let folks on either or both of comp.dcom.sys.cisco comp.dcom.net-management know about your utility. James From prologic at shortcircuit.net.au Wed May 5 10:33:29 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 6 May 2010 00:33:29 +1000 Subject: Create a new process to run python function In-Reply-To: References: Message-ID: On Wed, May 5, 2010 at 10:56 PM, Massi wrote: > in my script (python 2.5 on windows xp) I need to run a simple > function in a separate process. In other words I need something > similar to the fork function under UNIX. I tried with threads: Use the new multiprocesing package. > import os, threading > > def func(s) : > ? ?print "I'm thread number "+s, os.getpid() > > threading.Thread(target=func, args=("1",)).start() > threading.Thread(target=func, args=("2",)).start() Like this: import multiprocessing multiprocessing.Process(target=func, args=("1",)).start() multiprocessing.Process(target=func, args=("2",)).start() ... Surprise surprise it has almost the same API as the threading module :) --James From mouadino at gmail.com Wed May 5 10:36:44 2010 From: mouadino at gmail.com (mouadino) Date: Wed, 5 May 2010 07:36:44 -0700 (PDT) Subject: abc don't play well with private method Message-ID: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com> i have a problem here : i want to make a plugin architecture using abstract base class , this is my base class : # -*- coding: utf-8 -*- import abc class BASE_Connector: """ Mount point for plugins which refer to actions that can be performed. Plugins implementing this reference should provide the following methods: ======== ======================================================== connect the connection method that will initialize a transport layer __login the login method to use to login in to the server this one should be called from connect directly get this method is use for getting the files from the remote server close this method is called for closing the connection suddenly quit this method is more polite to close the connection ======== ======================================================== """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def connect(self, host, user="", passwd="", port="", private_key_file="", timeout=100): """ connect to a remote server this function call the __login function after the connection is established -- host : remote server name -- user : the user name in the remote server Default : empty string for server that don't need authentication or use private key instead -- passwd : password of the user given Default : empty string for server that don't need authentication or use private key instead -- port : the connection port Default : it's known from the protocol -- private_key_file : the file containing the private key used special for ssh connection Default : empty string -- timeout : the timeout of the connection Default : empty string """ pass @abc.abstractmethod def __login(self): """ private method to login to the remote server . it use the user name and the password or the private key for that """ @abc.abstractmethod def get(self, remote_file_path, local_path="/tmp/ housead_matcher"): """ method to download the file from the remote server -- remote_file_path : the path of the file in the remote server -- local_path : the local path where the file will be save """ pass @abc.abstractmethod def close(self): """ Close the connection unilaterally(from this host) """ @abc.abstractmethod def quit(self): """ close the connection. This is the ?polite? way to close a connection """ and i define my plugins in a differents module like this : class FTP_Connector(FTP, Base_Connector) : """ this class is for the connection to a ftp server """ def __init__(self): FTP.__init__() def connect(self, host, port, user, passwd, timeout=""): self.connect(host, port, timeout) self.___login(user, passwd) def ___login(self, username="", password=""): self.login(username, password) def get(self, remote_file_path, local_path): remote_file_path = os.path.expanduser(remote_file_path) local_path = os.path.expanduser(local_path) remote_directory, remote_file_name = os.path.split(remote_file_path) local_file = os.path.join(local_path, remote_file_name) self.cwd(remote_directory) self.retrlines("RETR " + remote_file_name, lambda s, w=local_file.write: w(s+"\n")) def close(self): self.close() def quit(self): self.quit() and when i test my code i get this error : Can't instantiate abstract class FTP_Connector with abstract methods _BASE_Connector__login i can understand why. but my problem is why why ? i can't put "private" method in the ABC class ??? From gandalf at shopzeus.com Wed May 5 10:42:21 2010 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 05 May 2010 16:42:21 +0200 Subject: Portable Python In-Reply-To: References: Message-ID: <4BE183CD.3040708@shopzeus.com> > Is there any difference in functionality between standard Python pack > and portable Python? It is not so easy to install third party modules for portable Python... > Why standard Python pack installation requires reboot after installation? It is not true for all operating systems. At least under Unbuntu Linux, BSD, Windows XP and Windows 7, you don't need to restart the OS after installation. What others have you tried? > Can portable Python used from hard drive folder? Did you read its very front page? http://www.portablepython.com/ "Just download it, extract to your portable storage device ***or hard drive*** and in 10 minutes you are ready to create your next Python application." Laszlo From bruno.42.desthuilliers at websiteburo.invalid Wed May 5 11:24:18 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 05 May 2010 17:24:18 +0200 Subject: abc don't play well with private method In-Reply-To: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com> References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com> Message-ID: <4be18d3d$0$19014$426a34cc@news.free.fr> mouadino a ?crit : > i have a problem here : > > i want to make a plugin architecture using abstract base class , this > is my base class : > > # -*- coding: utf-8 -*- > > import abc > > > class BASE_Connector: > """ > Mount point for plugins which refer to actions that can be > performed. > > Plugins implementing this reference should provide the following > methods: > > connect the connection method that will initialize a transport > layer > > __login the login method to use to login in to the server > this one should be called from connect directly Removing one of the leading underscores would solve your problem. > """ > __metaclass__ = abc.ABCMeta > > > > @abc.abstractmethod > def __login(self): > """ private method to login to the remote server . > it use the user name and the password or the private key > for that > > """ > and when i test my code i get this error : > Can't instantiate abstract class FTP_Connector with abstract methods > _BASE_Connector__login > > i can understand why. but my problem is why why ? i can't put > "private" method in the ABC class ??? There's no such thing as a "private" attribute in Python. The name-mangling mechanism invoked by "__name" is really meant to avoid accidental redefinition of the attribute in a derived class. In this case, your attribute is expected to be redefined, so you definitly don't want any name mangling here. Also and FWIW, the naming convention for "implementation attributes" is a single leading underscore. Also and FWIW: > > class FTP_Connector(FTP, Base_Connector) : > """ this class is for the connection to a ftp server > > """ > def close(self): > > self.close() > > def quit(self): > > self.quit() > Don't you see kind of a problem here ? Something like, say, an infinite recursion ? HTH From dg.gmane at thesamovar.net Wed May 5 11:51:48 2010 From: dg.gmane at thesamovar.net (Dan Goodman) Date: Wed, 05 May 2010 17:51:48 +0200 Subject: Generating nested code with context managers In-Reply-To: References: Message-ID: I tried a very similar thing, but not using with statements: http://mail.python.org/pipermail/python-list/2010-March/1239577.html Dan On 04/05/2010 22:36, Terry Reedy wrote: > In a current thread, people have claimed that generating properly > indented nested blocks is a pain because of the need to keep track of > indent levels. Someone countered with the now rather ancient > > http://effbot.org/zone/python-code-generator.htm > > The usage example > > c = CodeGeneratorBackend() > c.begin(tab=" ") > c.write("for i in range(1000):\n") > c.indent() > c.write("print 'code generation is trivial'") > c.dedent() > > illustrates three problems with the CodeGeneratorBackend class. 1) it > requires explicit \n on all lines (which the second omits, though it is > non-fatal since it is also the last) 2) the user still has to manually > match indents and dedents, and 3) the user *cannot* indent lines that > produce indented code. > > The relatively new with statement and associated context managers are > designed, among other things, for this situation, where one needs to > alter and restore a global context. So here is my updated (3.1) > proof-of-concept version. > > class PyCodeGen: > def __init__(self, tab=" "): > self.code = [] > self.tab = tab > self.level = 0 > # all attributes should be treated as read-only > def end(self): > return '\n'.join(self.code) > def line(self, string): # new line > self.code.append(self.tab * self.level + string) > > class For: > def __init__(self, target, in_expression): > target.line('for ' + in_expression + ':') > self.target = target > def __enter__(self): > self.target.level += 1 > def __exit__(self, t, v, tb): > self.target.level -= 1 > > c = PyCodeGen() > > with For(c, 'i in range(1000)'): > c.line('print("Code gen is easy")') > c.line('# done') > > print(c.end()) > > # prints > > for i in range(1000): > print("Code gen is easy") > # done > > Note that the absence of .indent and .dedent is intentional. In a > fleshed out system, there would be a context manager for each compound > statement and these would handle all indents and dedents. > > If one really preferred to write, for instance, 'c.For(s); instead of > 'For(c,s)' in the with statement, one could add a wrapper method like > def For(self, s): return For(self, s) > for each context manager. I left that out. > > Similar methods can be used to auto-match C braces and other open/close > pairs. > > Terry Jan Reedy > > > From benjamin.kaplan at case.edu Wed May 5 11:59:44 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 5 May 2010 11:59:44 -0400 Subject: Create a new process to run python function In-Reply-To: References: Message-ID: On Wed, May 5, 2010 at 10:33 AM, James Mills wrote: > On Wed, May 5, 2010 at 10:56 PM, Massi wrote: >> in my script (python 2.5 on windows xp) I need to run a simple >> function in a separate process. In other words I need something >> similar to the fork function under UNIX. I tried with threads: > > Use the new multiprocesing package. > >> import os, threading >> >> def func(s) : >> ? ?print "I'm thread number "+s, os.getpid() >> >> threading.Thread(target=func, args=("1",)).start() >> threading.Thread(target=func, args=("2",)).start() > > Like this: > > import multiprocessing > > multiprocessing.Process(target=func, args=("1",)).start() > multiprocessing.Process(target=func, args=("2",)).start() > > ... > > Surprise surprise it has almost the same API > as the threading module :) > > --James Multiprocessing wasn't added until Python 2.6. http://www.python.org/dev/peps/pep-0371/ In Python 2.5, it was still a 3rd party package. http://pypi.python.org/pypi/processing The project's website appears to be down right now though. http://developer.berlios.de/projects/pyprocessing > -- > http://mail.python.org/mailman/listinfo/python-list > From lists at cheimes.de Wed May 5 12:34:09 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 May 2010 18:34:09 +0200 Subject: Create a new process to run python function In-Reply-To: References: Message-ID: Am 05.05.2010 17:59, schrieb Benjamin Kaplan: > Multiprocessing wasn't added until Python 2.6. > http://www.python.org/dev/peps/pep-0371/ > > In Python 2.5, it was still a 3rd party package. > http://pypi.python.org/pypi/processing > > The project's website appears to be down right now though. > http://developer.berlios.de/projects/pyprocessing Why don't you try out our backport: http://pypi.python.org/pypi/multiprocessing/2.6.2.1 :) From pietro.campe at gmail.com Wed May 5 13:26:18 2010 From: pietro.campe at gmail.com (Pietro Campesato) Date: Wed, 5 May 2010 10:26:18 -0700 (PDT) Subject: Where is python31.dll? Message-ID: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> Hi, recently I've been wondering how to roll my own portable python 3.1 (since there seems to be no portable app specifically for this version). Thinking you can just copy your install folder (+ python's dll), I've noticed that there seems to be no python31.dll in my systems folder (c:\windows\system32\). I cannot find the dll inside the python installation folder either. Another reason I'm asking is because what I've found on the net so far tells you to look for this dll specifically. Am I missing something? Thanks, Alex PS: my setup is version 3.1.2 on windows vista From tjreedy at udel.edu Wed May 5 14:03:26 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 May 2010 14:03:26 -0400 Subject: Teaching Programming In-Reply-To: <4BE13143.6040904@ieee.org> References: <4BE13143.6040904@ieee.org> Message-ID: On 5/5/2010 4:50 AM, Dave Angel wrote: > alex23 wrote: >> Ed Keith wrote: >>> Knuth wanted the generated source to be unreadable, so people would >>> not be tempted to edit the generated code. >> >> This is my biggest issue with Knuth's view of literate programming. If >> the generated source isn't readable, am I just supposed to trust it? >> How can I tell if an error lies in my expression of the algorithm or >> in the code generation itself? >> > Do you think a compiler is required to make its object file conveniently > readable? Do you regularly read the machine code generated by your C > compiler? I admit I've frequently studied compiler output over the > years, but I think I'm very unusual in that respect. I've never > disassembled a python byte code file, The output from dis.dis() is quite readable, and people (developers and others) have used it to check on what the compiler is doing. From tjreedy at udel.edu Wed May 5 14:07:06 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 May 2010 14:07:06 -0400 Subject: Movable Python or ActivePython In-Reply-To: References: Message-ID: On 5/5/2010 8:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for > testing programs. As I read, Movable Python can run without being > installed. It needs no registry entries and knows the path to all the > dlls (system or otherwise) that it uses. > Whats about ActivePython > http://www.activestate.com/activepython/downloads? Does it requires > installation? Yes. It is the standard distribution with extra stuff added and installed. From sridharr at activestate.com Wed May 5 14:19:35 2010 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Wed, 5 May 2010 11:19:35 -0700 Subject: Movable Python or ActivePython In-Reply-To: References: Message-ID: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> On 2010-05-05, at 5:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for testing programs. As I read, Movable Python can run without being installed. It needs no registry entries and knows the path to all the dlls (system or otherwise) that it uses. > Whats about ActivePython http://www.activestate.com/activepython/downloads? Does it requires installation? The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ (substitute with latest version) When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 x64 machine - by extracting and running python.exe (from INSTALLDIR/) without installing - it just worked. -srid From tjreedy at udel.edu Wed May 5 14:20:15 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 May 2010 14:20:15 -0400 Subject: Where is python31.dll? In-Reply-To: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> References: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> Message-ID: On 5/5/2010 1:26 PM, Pietro Campesato wrote: > Hi, > recently I've been wondering how to roll my own portable python 3.1 > (since there seems to be no portable app specifically for this > version). Thinking you can just copy your install folder (+ python's > dll), I've noticed that there seems to be no python31.dll in my > systems folder (c:\windows\system32\). That is where it is on my WinXP system, installed for all users. > I cannot find the dll inside the python installation folder either. > Another reason I'm asking is because what I've found on the net so far > tells you to look for this dll specifically. Am I missing something? Your windows search command? Which is how I verified the above. From lists at cheimes.de Wed May 5 14:40:16 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 May 2010 20:40:16 +0200 Subject: Where is python31.dll? In-Reply-To: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> References: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> Message-ID: Am 05.05.2010 19:26, schrieb Pietro Campesato: > Hi, > recently I've been wondering how to roll my own portable python 3.1 > (since there seems to be no portable app specifically for this > version). Thinking you can just copy your install folder (+ python's > dll), I've noticed that there seems to be no python31.dll in my > systems folder (c:\windows\system32\). > > I cannot find the dll inside the python installation folder either. > Another reason I'm asking is because what I've found on the net so far > tells you to look for this dll specifically. Am I missing something? It's trivial to roll your own portable bundle of Python that doesn't installation. All you need is an installation "for me" instead of an installation for all users. When you install Python just for the current user all necessary files land in the installation directory -- including the main dll and msvcrt stuff. Note that some features like COM and Windows Services require some dependencies in the system32 directory. Christian From python at bdurham.com Wed May 5 15:04:55 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 15:04:55 -0400 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> Message-ID: <1273086295.15686.1373577021@webmail.messagingengine.com> In a recent thread ("Movable Python or ActivePython), Sridhar Ratnakumar pointed out that the ActiveState Python releases can be downloaded as ZIP files vs. MSI files. (Great idea - thank you ActiveState!) > The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: > > http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ I just took a look at the ActiveStatre 2.6.5.12 release (zip file version) and noticed that this file does not include the MSVCR90.DLL run time file - it includes MFC*.DLL files instead (and a different manifest file as well). Can anyone explain why the ActiveState release uses different MS Visual C runtime files than the official Python Foundation's release of Python? Thanks, Malcolm ----- Original message ----- From: "Sridhar Ratnakumar" To: "balzer" Cc: python-list at python.org Date: Wed, 5 May 2010 11:19:35 -0700 Subject: Re: Movable Python or ActivePython On 2010-05-05, at 5:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for testing programs. As I read, Movable Python can run without being installed. It needs no registry entries and knows the path to all the dlls (system or otherwise) that it uses. > Whats about ActivePython http://www.activestate.com/activepython/downloads? Does it requires installation? The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ (substitute with latest version) When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 x64 machine - by extracting and running python.exe (from INSTALLDIR/) without installing - it just worked. -srid From python at bdurham.com Wed May 5 15:04:55 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 15:04:55 -0400 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> Message-ID: <1273086295.15686.1373577021@webmail.messagingengine.com> In a recent thread ("Movable Python or ActivePython), Sridhar Ratnakumar pointed out that the ActiveState Python releases can be downloaded as ZIP files vs. MSI files. (Great idea - thank you ActiveState!) > The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: > > http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ I just took a look at the ActiveStatre 2.6.5.12 release (zip file version) and noticed that this file does not include the MSVCR90.DLL run time file - it includes MFC*.DLL files instead (and a different manifest file as well). Can anyone explain why the ActiveState release uses different MS Visual C runtime files than the official Python Foundation's release of Python? Thanks, Malcolm ----- Original message ----- From: "Sridhar Ratnakumar" To: "balzer" Cc: python-list at python.org Date: Wed, 5 May 2010 11:19:35 -0700 Subject: Re: Movable Python or ActivePython On 2010-05-05, at 5:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for testing programs. As I read, Movable Python can run without being installed. It needs no registry entries and knows the path to all the dlls (system or otherwise) that it uses. > Whats about ActivePython http://www.activestate.com/activepython/downloads? Does it requires installation? The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ (substitute with latest version) When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 x64 machine - by extracting and running python.exe (from INSTALLDIR/) without installing - it just worked. -srid From phd at phd.pp.ru Wed May 5 15:09:39 2010 From: phd at phd.pp.ru (Oleg Broytman) Date: Wed, 5 May 2010 23:09:39 +0400 Subject: SQLObject 0.11.6 Message-ID: <20100505190939.GC23337@phd.pp.ru> Hello! I'm pleased to announce version 0.11.6, a minor bugfix release of 0.11 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.11.6 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.11.5 ----------------- * A bug was fixed in SQLiteConnection.columnsFromSchema(): pass None as size/precision to DecimalCol; DecimalCol doesn't allow default values (to force user to pass meaningful values); but columnsFromSchema() doesn't implement proper parsing of column details. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytman http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From phd at phd.pp.ru Wed May 5 15:11:07 2010 From: phd at phd.pp.ru (Oleg Broytman) Date: Wed, 5 May 2010 23:11:07 +0400 Subject: SQLObject 0.12.4 Message-ID: <20100505191107.GG23337@phd.pp.ru> Hello! I'm pleased to announce version 0.12.4, a minor bugfix release of branch 0.12 of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.12.4 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.12.3 ----------------- * Bugs were fixed in calling from_python(). * A bug was fixed in SQLiteConnection.columnsFromSchema(): pass None as size/precision to DecimalCol; DecimalCol doesn't allow default values (to force user to pass meaningful values); but columnsFromSchema() doesn't implement proper parsing of column details. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytman http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From mgedmin at gmail.com Wed May 5 15:46:25 2010 From: mgedmin at gmail.com (Marius Gedminas) Date: Wed, 5 May 2010 12:46:25 -0700 (PDT) Subject: How to check what is holding reference to object References: <37bce451-4877-44a5-be28-6d4341f9704e@x3g2000yqd.googlegroups.com> Message-ID: <553796db-3c71-41e7-bf35-b89384fda4f2@e2g2000yqn.googlegroups.com> On Apr 28, 3:59?pm, Christian Heimes wrote: > The trick works only for objects that are tracked by CPython's garbage > collector. Simple and non-containerish objects like str, int, unicode > and some other types aren't tracked by the gc. Yes they are -- have you ever tried >>> import gc >>> gc.get_referrers(42) ? Marius Gedminas From mgedmin at gmail.com Wed May 5 15:47:35 2010 From: mgedmin at gmail.com (Marius Gedminas) Date: Wed, 5 May 2010 12:47:35 -0700 (PDT) Subject: How to check what is holding reference to object References: <37bce451-4877-44a5-be28-6d4341f9704e@x3g2000yqd.googlegroups.com> Message-ID: On Apr 27, 11:45?pm, Michal M wrote: > I've just found out that one of objects is not destroyed when it > should be. This means that something was holding reference to this > object or part of it (i.e. method). Is there any way to check what > holds that reference? I am unable to do that just looking to the code > or debugging it because it is pretty complicated, but I am able to > invoke this situation again. I wrote http://pypi.python.org/pypi/objgraph for this purpose. -- Marius Gedminas From saimapk81 at gmail.com Wed May 5 16:09:42 2010 From: saimapk81 at gmail.com (saima81) Date: Wed, 5 May 2010 13:09:42 -0700 (PDT) Subject: "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ Message-ID: <67c321d0-9061-40b3-8680-2e7dc1322da6@s4g2000prh.googlegroups.com> "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS WALLPAPERS" "SEXY HOLLYWOOD ACTRESS" "PRETTY HOLLYWOOD ACTRESS" "CUTE HOLLYWOOD ACTRESS" "HOLLYWOOD ACTRESS" ON http://hollywood6y.blogspot.com/ "HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD""HEIDI MONTAG PRATT" "HAYDEN PENETTIERE" "HAWKINS" "GWEN RENEE STEFANI" "FREIDA PINTO" "FAMKE JANSSEN" "EMMANUELLE VAUGIER" "EMMANUELLE GREY ROSSUM" "ELISHA ANN CUTHBERT" "DIANA PRINCESS OF WALES" "DIANA ROSS" "DANIELA PESTOVA" "COURTENEY BASS COX" "CLAUDIA SCHIFFER" "CHRISTINA APPLEGATE" "CHARLIZE THERON" "CATERINA MURINO" "BROOKE ELIZABETH BURNS" "BRITTANY ANNE MURPHY" "BRITENY JEAN SPEARS" "BLAKE CHRISTINA" "ASHLEY MICHELLE TISDALE" "ASHLEY MCCALL SCOTT" "ASHLEY JUDD" "ASHLEU FULLER OLSEN" "ASHLEE NICOLE WENTZ" "ARIELLE CAROLINE KEBBEL" "ANA BEATRIZ BARROS" "AMY LYSLE SMART" "AMY LOUISE ACKER" "ALEXA ELLESSE VEGA" "ADRIANA FRANCESCA LIMA" "ABIGAIL ROSE" "AMERICAN ACTRESS" "HOLLYWOOD ACTRESS" "BRITENY SPEARS" "ANGLIANA JOLI" "KATE VINSLATE" "NICOLE KIDMAN" "HOLLYWOOD ACTRESS" "BOLLYWOOD ACTRESS" "LOLLYWOOD ACTRES" "SEXY HOLLYWOOD ACTRESS" "GIRLS WITHOUT CLOTHS" ON http://hollywood6y.blogspot.com/ "SEXY GIRLS" "HOLLYWOOD SEXY GIRLS" "SUPER SEXY GIRLS" "SEX WORLD" "SEXY THIEGH" "SEXY BELLY" "SEXY LEGS" "SEXY FIGURES" "SEXY GIRLS" "SEXY MOTHERS" "SEXY SISTERS" "SEXY WORLD" From martin.hellwig at dcuktec.org Wed May 5 18:01:08 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 May 2010 23:01:08 +0100 Subject: Teaching Programming In-Reply-To: <4be00c33$0$1134$4fafbaef@reader3.news.tin.it> References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be00c33$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: On 05/04/10 12:59, superpollo wrote: > Martin P. Hellwig ha scritto: >> For the corner cases (I can think of a couple) it is good to know you >> can use ';' most of the time. >> > > most but not always as i noted (think about loops or function definition) > Well through in some exec magic then, for example: for number in [1,2,3,4]: def nprint(number): print(number) number += 1 nprint(number translates to: >>> exec('for number in [1,2,3,4]:\n\tdef nprint(number):\n\t\tprint(number)\n\tnumber += 1\n\tnprint(number)') 2 3 4 5 But if you have an example why indentation is still a problem please give it :-) -- mph From utente at esempio.net Wed May 5 18:10:52 2010 From: utente at esempio.net (superpollo) Date: Thu, 06 May 2010 00:10:52 +0200 Subject: Teaching Programming In-Reply-To: References: <35ad844e-c4e6-42fa-a5df-864f1072c54b@a16g2000vbr.googlegroups.com> <4BDFE741.40305@sequans.com> <4bdff6e3$0$1120$4fafbaef@reader3.news.tin.it> <4be00c33$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4be1eced$0$816$4fafbaef@reader5.news.tin.it> Martin P. Hellwig ha scritto: > On 05/04/10 12:59, superpollo wrote: >> Martin P. Hellwig ha scritto: > >>> For the corner cases (I can think of a couple) it is good to know you >>> can use ';' most of the time. >>> >> >> most but not always as i noted (think about loops or function definition) >> > Well through in some exec magic then, for example: > for number in [1,2,3,4]: > def nprint(number): > print(number) > number += 1 > nprint(number > > translates to: > > >>> exec('for number in [1,2,3,4]:\n\tdef > nprint(number):\n\t\tprint(number)\n\tnumber += 1\n\tnprint(number)') > 2 > 3 > 4 > 5 > > But if you have an example why indentation is still a problem please > give it :-) > i think your exec example solved most of my problems. thanks a lot. bye From trentm at activestate.com Wed May 5 19:02:53 2010 From: trentm at activestate.com (Trent Mick) Date: Wed, 05 May 2010 16:02:53 -0700 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <1273086295.15686.1373577021@webmail.messagingengine.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> <1273086295.15686.1373577021@webmail.messagingengine.com> Message-ID: <4BE1F91D.8050201@activestate.com> On 10-05-05 12:04 PM, python at bdurham.com wrote: > I just took a look at the ActiveStatre 2.6.5.12 release (zip file > version) and noticed that this file does not include the MSVCR90.DLL run > time file - it includes MFC*.DLL files instead (and a different manifest > file as well). > > Can anyone explain why the ActiveState release uses different MS Visual > C runtime files than the official Python Foundation's release of Python? It doesn't. We use the same MSVC version as the python.org builds. Note that "MFC*.dll" files (IIRC, it has been a while) are redistributable DLLs used by the included PyWin32 extensions that have Python bindings for the Microsoft Foundation Classes GUI APIs. Trent -- Trent Mick trentm at activestate.com http://trentm.com/blog/ From gagsl-py2 at yahoo.com.ar Wed May 5 19:04:23 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 May 2010 20:04:23 -0300 Subject: find out whther byte two .pyc files contain the same byte code. References: <8d53dbc5-9ad0-44ed-881f-fa2b6fc82e96@i9g2000yqi.googlegroups.com> Message-ID: En Wed, 05 May 2010 10:34:34 -0300, gelonida escribi?: > I'd like to know whether the byte code of two .pyc files is identical. > > I thought, I could just compare the md5sums of thw .pyc files. > However this does not work. > > It seems, that .pyc ontains the time stamp of the source file. > the .pyc file changes its contents when I don't change the file's > contents but just > save it again. Yes, that's what happens. First 4 bytes in a .pyc file contain a "magic" number identifying the Python version used to create it. Next 4 bytes contain the timestamp of the source file. Just ignore the first 8 bytes when computing the checksum: tail -c +8 tst.pyc | md5sum (untested) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed May 5 19:30:44 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 May 2010 20:30:44 -0300 Subject: Python Embedding, no correct lib References: <5d90e51f-133f-4b01-9074-9fdc3eb37d59@e35g2000yqm.googlegroups.com> Message-ID: En Wed, 05 May 2010 09:04:06 -0300, moerchendiser2k3 escribi?: > I have a serious problem with Python. I am currently trying to > implement Python into my app. > Well this works fine, but get this: > > I have my own Python interpreter in a subfolder of my app. When I > start my app, PYTHONHOME is set, and an environment variable is set to > it can find the python DLL on startup. You should not define any environment variables. You are embedding Python into your application, aren't you? That is, you call Py_Initialize and all that stuff - you don't invoke a separate python.exe, true? Python tries to find its standard library looking for [the directory containing the executable]\Lib\os.py and a few other places. Once it finds the "Lib" directory, all other are derived from it. > When Python is not installed on the system everything works fine as > expected. > > When I now install Python on my system (so I have two python libs now) > the system installation is the preferred one. > > print sys.path prints out ['', 'C:\Windows > \system32\python26.zip', ...] and I cant explain whats going wrong > here. Such zip file doesn't even exist in a standard Python installation; but it means that your program loaded python26.dll from the system32 directory, not your own copy. You may want to use a .local file or a manifest; see http://msdn.microsoft.com/en-us/library/ms811694.aspx > I expected that it just uses the System lib when it cannot find > it in the subfolder which I set in the environment variables > before.. :-( Note that this is a Windows issue, not a Python one. You have to ensure the Python DLL is loaded from your own directory, not the system one. (BTW, don't set any environment variables. There is no need to do so, and it may conflict with an existing installation. The reverse is true too: a PYTHONPATH variable set for the "system" Python will interfere with your private copy too. Global state is always a bad idea.) -- Gabriel Genellina From googler.1.webmaster at spamgourmet.com Wed May 5 19:51:56 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Wed, 5 May 2010 16:51:56 -0700 (PDT) Subject: Python Embedding, no correct lib References: <5d90e51f-133f-4b01-9074-9fdc3eb37d59@e35g2000yqm.googlegroups.com> Message-ID: <7d400ac1-d3dc-4212-ad98-1bd9d0a51fca@l28g2000yqd.googlegroups.com> On 6 Mai, 01:30, "Gabriel Genellina" wrote: > En Wed, 05 May 2010 09:04:06 -0300, moerchendiser2k3 ? > escribi?: > > > I have a serious problem with Python. I am currently trying to > > implement Python into my app. > > Well this works fine, but get this: > > > I have my own Python interpreter in a subfolder of my app. When I > > start my app, PYTHONHOME is set, and an environment variable is set to > > it can find the python DLL on startup. > > You should not define any environment variables. > > You are embedding Python into your application, aren't you? That is, you ? > call Py_Initialize and all that stuff - you don't invoke a separate ? > python.exe, true? > > Python tries to find its standard library looking for > [the directory containing the executable]\Lib\os.py > and a few other places. Once it finds the "Lib" directory, all other are ? > derived from it. > > > When Python is not installed on the system everything works fine as > > expected. > > > When I now install Python on my system (so I have two python libs now) > > the system installation is the preferred one. > > > print sys.path prints out ['', 'C:\Windows > > \system32\python26.zip', ...] and I cant explain whats going wrong > > here. > > Such zip file doesn't even exist in a standard Python installation; but it ? > means that your program loaded python26.dll from the system32 directory, ? > not your own copy. You may want to use a .local file or a manifest; seehttp://msdn.microsoft.com/en-us/library/ms811694.aspx > > > I expected that it just uses the System lib when it cannot find > > it in the subfolder which I set in the environment variables > > before.. :-( > > Note that this is a Windows issue, not a Python one. You have to ensure ? > the Python DLL is loaded from your own directory, not the system one. > > (BTW, don't set any environment variables. There is no need to do so, and ? > it may conflict with an existing installation. The reverse is true too: a ? > PYTHONPATH variable set for the "system" Python will interfere with your ? > private copy too. Global state is always a bad idea.) > > -- > Gabriel Genellina Hi Gabriel, thanks very much for your information. I found the solution. This is related to this one. The order of the search path is the explanation why the system one is used: http://msdn.microsoft.com/en-us/library/ms682586(VS.85).aspx So 'Alternate Search Order' is the solution. :) Bye, moerchendiser2k3 From cs at zip.com.au Wed May 5 20:21:45 2010 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 6 May 2010 10:21:45 +1000 Subject: strange interaction between open and cwd In-Reply-To: <4BE16327.5050209@ftml.net> References: <4BE16327.5050209@ftml.net> Message-ID: <20100506002144.GA26948@cskk.homeip.net> On 05May2010 13:23, Baz Walter wrote: | here's what i get on my system, where '/dev/sda1' and '/dev/sda6' | are mounted at '/boot' and '/home' respectively: | | >>> os.stat('/').st_ino | 2L | >>> os.stat('/usr').st_ino | 212993L | >>> os.stat('/boot').st_ino | 2L | >>> os.stat('/home').st_ino | 2L | >>> | | if the algorithm is climbing up from '/home/baz/tmp/xxx', what does | it do when it searches os.listdir('../../../..')? how can it tell | whether 'boot' or 'home' is the correct next parent if it only | checks the inode number? i think the algorithm would at least need | to take account of changes in the current device id. not sure | whether that would be enough to cover all cases, though. Look at the st_rdev field (== the device holding this inode). When that changes, you've crossed a mount mount point. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Usenet is essentially a HUGE group of people passing notes in class. --R. Kadel From python at bdurham.com Wed May 5 20:30:47 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 20:30:47 -0400 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <4BE1F91D.8050201@activestate.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> <1273086295.15686.1373577021@webmail.messagingengine.com> <4BE1F91D.8050201@activestate.com> Message-ID: <1273105847.779.1373624397@webmail.messagingengine.com> Hi Trent, On 10-05-05 12:04 PM, python at bdurham.com wrote: >> I just took a look at the ActiveStatre 2.6.5.12 release (zip file >> version) and noticed that this file does not include the MSVCR90.DLL run >> time file - it includes MFC*.DLL files instead (and a different manifest >> file as well). >> >> Can anyone explain why the ActiveState release uses different MS Visual >> C runtime files than the official Python Foundation's release of Python? > It doesn't. We use the same MSVC version as the python.org builds. > > Note that "MFC*.dll" files (IIRC, it has been a while) are > redistributable DLLs used by the included PyWin32 extensions that have > Python bindings for the Microsoft Foundation Classes GUI APIs. Yes, you are correct about the MFC*.dll's being shipped as part of the Py2Win32 extensions. But I don't see the MSVCR90.DLL in your ZIP release. I do see a MSVCR71.DLL. Malcolm From vincent at vincentdavis.net Wed May 5 21:12:35 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Wed, 5 May 2010 19:12:35 -0600 Subject: Encrypt password within source code. Message-ID: I can't think of a way to do this, not sure it is possible but I feel as though I might not know what I don't know. I want to share and example of a python script, to run it needs a google username and password. Is there a way for me to encrypt my username and password in the source code? I though about openID but don't really know anything about it. *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed May 5 21:44:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 May 2010 18:44:59 -0700 Subject: Encrypt password within source code. In-Reply-To: References: Message-ID: On Wed, May 5, 2010 at 6:12 PM, Vincent Davis wrote: > I can't think of a way to do this, not sure it is possible but I feel as though I might not know what I don't know. > I want to share and example of a python script, to run it needs a google username and password. Is there a way for me to encrypt my username and password in the source code? I though about openID but don't really know anything about it. Nope. What you're asking for is essentially a form of DRM by including the information in a way the program can use it but the user can't extract it; DRM schemes have been broken many times and the idea is flawed even in theory, for if a person has control of their computer (or in the limit case, at least physical access to its innards), they can just watch the computation (e.g. memory snoop) until the data gets converted to its plain form so the program can actually utilize it, and then bada-bing, they have your valuable data. Think of it this way. If you encrypted the information in your program, the program would need to be able to decrypt it later so it could actually use the login info. For it to be able to do that, you'd have to include the encryption key in plaintext somewhere in the program so it could pass it into the decryption algorithm. But then someone can put 2 and 2 together, see that "there's his key!", and decrypt your info using the key. So, to prevent this, the key *itself* would then have to be encrypted...by another key, which again would be stored in plaintext in your program somewhere, where someone could then find it and use it to decrypt the first key and then your data, so you use yet another key to encrypt that key...(as you can see, this goes on ad infinitum, and thus the whole scheme is doomed). See also section 1, "DRM Systems Don't Work", of http://changethis.com/manifesto/show/4.DRM You can alternatively just try to obfuscate it, but that's obviously not truly secure and is likewise easily circumvented. Just let the user input their own Google Account info. If you're trying to show an example that depends on your own exact account, just include a transcript of your terminal session (omitting your Google Account info obviously). Cheers, Chris -- DRM is http://defectiveByDesign.org http://blog.rebertia.com From python.list at tim.thechases.com Wed May 5 21:48:22 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 05 May 2010 20:48:22 -0500 Subject: Encrypt password within source code. In-Reply-To: References: Message-ID: <4BE21FE6.9060506@tim.thechases.com> On 05/05/2010 08:12 PM, Vincent Davis wrote: > I can't think of a way to do this, not sure it is possible but I feel as > though I might not know what I don't know. > > I want to share and example of a python script, to run it needs a google > username and password. Is there a way for me to encrypt my username and > password in the source code? No-ish. You can encrypt it, but if you encrypt it, you need to include the keys or algorithm for decrypting it, and all it takes is a pdb.set_trace() before the decrypted uname/pwd get sent to Google to get it, and poof all your encryption/decryption has been in vain: uname = SUPER_ENCRYPTED_USER pwd = SUPER_ENCRYPTED_PASSWORD u = secret_decrypt(uname) p = secret_decrypt(pwd) # regardless of how good the stuff above is # you're vulnerable right here: # print "%r %r" % (u, p) do_google_stuff(u, p) Unless the Google API you're using allows for chain-of-authority creation of sub-credentials (so your account creates secondary accounts that are then distributed in your code/config files and managed via your dev login), two possibilities that come to mind: 1) put in a bogus uname/password and make them get their own Google login to put in (which can be done in a config file if they're squeamish about editing source code) This assumes that any arbitrary Google login can grant access to what you want (sometimes this is a developer key, in which case the user would need to get their own dev key). 2) create a web-service on a server somewhere that has your credentials, but your distributed code merely hits this web service instead of having your actual credentials in the source (plain-text or encrypted). The server would have them (I'd just put them in plain-text -- no need to be fancy. If you can't trust your hosting service, don't use them) but you wouldn't expose the credentials outside the application. -tkc From dreadpiratejeff at gmail.com Wed May 5 22:47:25 2010 From: dreadpiratejeff at gmail.com (J) Date: Wed, 5 May 2010 22:47:25 -0400 Subject: Is there a better way to set a system clock in Python (on a Linux system) Message-ID: Is there a better way to do this? def SkewTime(): ''' Optional function. We can skew time by 1 hour if we'd like to see real sync changes being enforced ''' TIME_SKEW=1 logging.info('Time Skewing has been selected. Setting clock ahead 1 hour') # Let's get our current time t = TimeCheck() logging.info('Current time is: %s' % time.asctime(t)) # Now create new time string in the form MMDDhhmmYYYY for the date program hr = t.tm_hour + TIME_SKEW date_string = time.strftime('%m%d%H%M%Y',(t.tm_year, t.tm_mon, t.tm_mday, hr, t.tm_min, t.tm_sec, t.tm_wday, t.tm_yday, t.tm_isdst)) logging.debug('New date string is: %s' % date_string) logging.debug('Setting new system time/date') status = SilentCall('/bin/date %s' % date_string) logging.info('Pre-sync time is: %s' % time.asctime()) TimeCheck() as referenced above is a simple function that just returns the time.time_struct object from time.localtime(). I pull time a few times and it was a little cleaner to put that into a function and just call the function whenever I needed to. SilentCall() is a modification of subprocess.call() (which in reality just calls Popen(*popenargs,**kwargs).wait()) but it defaults to redirecting stdin and stdout to /dev/null to suppress shell output from the command being called. Anyway, what I'm wondering, is, while this works, is there a better way to do it than using part of the originally returned time_struct and injecting my own new hour argument (hr). The goal of this function is to just set the system clock one hour ahead, so when I call the Linux command 'ntpdate' I can get a real time change when it syncs the local clock to an NTP server. This just looks... well, big to me. I tried passing only the things I really needed to time.strftime(), but apparently, that requires the full 9-tuple from time_struct, not just individual parts of it. Like I said, it works well, I just wonder if there is a cleaner way of setting the local clock to a different time in python without having to do all this. The reason most of that exists, is because the linux date command expects to see the new date/time like this: MMDDhhmmYYYY.ss. Or am I just looking at this too hard and really did work it out nicely? Cheers Jeff From clp2 at rebertia.com Wed May 5 23:01:44 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 May 2010 20:01:44 -0700 Subject: Is there a better way to set a system clock in Python (on a Linux system) In-Reply-To: References: Message-ID: On Wed, May 5, 2010 at 7:47 PM, J wrote: > Is there a better way to do this? Yes: from datetime import datetime, timedelta > def SkewTime(): > ? ?''' > ? ?Optional function. We can skew time by 1 hour if we'd like to see real sync > ? ?changes being enforced > ? ?''' > ? ?TIME_SKEW=1 > ? ?logging.info('Time Skewing has been selected. Setting clock ahead 1 hour') > ? ?# Let's get our current time skewed = datetime.now() + timedelta(hours=TIME_SKEW) > ? ?# Now create new time string in the form MMDDhhmmYYYY for the date program date_time_str = skewed.strftime('%m%d%H%M%Y') ? ?logging.debug('New date string is: %s' % date_time_str) > ? ?logging.debug('Setting new system time/date') ? ?status = SilentCall('/bin/date %s' % date_time_str) > ? ?logging.info('Pre-sync time is: %s' % time.asctime()) > > Anyway, what I'm wondering, is, while this works, is there a better > way to do it than using part of the originally returned time_struct > and injecting my own new hour argument (hr). Use the datetime module roughly as shown. (Disclaimer: Code is untested). Also, I'm not sure if your original code worked properly after 11PM; my code definitely should. > This just looks... well, big to me. ?I tried passing only the things I > really needed to time.strftime(), but apparently, that requires the > full 9-tuple from time_struct, not just individual parts of it. Cheers, Chris -- http://blog.rebertia.com From killy.draw at gmail.com Wed May 5 23:01:54 2010 From: killy.draw at gmail.com (KDr2) Date: Thu, 6 May 2010 11:01:54 +0800 Subject: Is there a better way to set a system clock in Python (on a Linux system) In-Reply-To: References: Message-ID: man 2 clock_settime call it with ctypes -- Best Regards, -- KDr2 http://kdr2.net On Thu, May 6, 2010 at 10:47 AM, J wrote: > Is there a better way to do this? > > def SkewTime(): > ''' > Optional function. We can skew time by 1 hour if we'd like to see real > sync > changes being enforced > ''' > TIME_SKEW=1 > logging.info('Time Skewing has been selected. Setting clock ahead 1 > hour') > # Let's get our current time > t = TimeCheck() > logging.info('Current time is: %s' % time.asctime(t)) > # Now create new time string in the form MMDDhhmmYYYY for the date > program > hr = t.tm_hour + TIME_SKEW > date_string = time.strftime('%m%d%H%M%Y',(t.tm_year, > t.tm_mon, > t.tm_mday, > hr, > t.tm_min, > t.tm_sec, > t.tm_wday, > t.tm_yday, > t.tm_isdst)) > logging.debug('New date string is: %s' % date_string) > logging.debug('Setting new system time/date') > status = SilentCall('/bin/date %s' % date_string) > logging.info('Pre-sync time is: %s' % time.asctime()) > > TimeCheck() as referenced above is a simple function that just returns > the time.time_struct object from time.localtime(). I pull time a few > times and it was a little cleaner to put that into a function and just > call the function whenever I needed to. > > SilentCall() is a modification of subprocess.call() (which in reality > just calls Popen(*popenargs,**kwargs).wait()) but it defaults to > redirecting stdin and stdout to /dev/null to suppress shell output > from the command being called. > > Anyway, what I'm wondering, is, while this works, is there a better > way to do it than using part of the originally returned time_struct > and injecting my own new hour argument (hr). > > The goal of this function is to just set the system clock one hour > ahead, so when I call the Linux command 'ntpdate' I can get a real > time change when it syncs the local clock to an NTP server. > > This just looks... well, big to me. I tried passing only the things I > really needed to time.strftime(), but apparently, that requires the > full 9-tuple from time_struct, not just individual parts of it. > > Like I said, it works well, I just wonder if there is a cleaner way of > setting the local clock to a different time in python without having > to do all this. The reason most of that exists, is because the linux > date command expects to see the new date/time like this: > MMDDhhmmYYYY.ss. > > Or am I just looking at this too hard and really did work it out nicely? > > Cheers > Jeff > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at vincentdavis.net Wed May 5 23:10:56 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Wed, 5 May 2010 21:10:56 -0600 Subject: Encrypt password within source code. In-Reply-To: <4BE21FE6.9060506@tim.thechases.com> References: <4BE21FE6.9060506@tim.thechases.com> Message-ID: Thanks for the replies I though the answer was no. Vincent On Wed, May 5, 2010 at 7:48 PM, Tim Chase wrote: > On 05/05/2010 08:12 PM, Vincent Davis wrote: > >> I can't think of a way to do this, not sure it is possible but I feel as >> though I might not know what I don't know. >> >> I want to share and example of a python script, to run it needs a google >> username and password. Is there a way for me to encrypt my username and >> password in the source code? >> > > No-ish. You can encrypt it, but if you encrypt it, you need to include the > keys or algorithm for decrypting it, and all it takes is a pdb.set_trace() > before the decrypted uname/pwd get sent to Google to get it, and poof all > your encryption/decryption has been in vain: > > uname = SUPER_ENCRYPTED_USER > pwd = SUPER_ENCRYPTED_PASSWORD > u = secret_decrypt(uname) > p = secret_decrypt(pwd) > # regardless of how good the stuff above is > # you're vulnerable right here: > # print "%r %r" % (u, p) > do_google_stuff(u, p) > > Unless the Google API you're using allows for chain-of-authority creation > of sub-credentials (so your account creates secondary accounts that are then > distributed in your code/config files and managed via your dev login), two > possibilities that come to mind: > > 1) put in a bogus uname/password and make them get their own Google login > to put in (which can be done in a config file if they're squeamish about > editing source code) This assumes that any arbitrary Google login can grant > access to what you want (sometimes this is a developer key, in which case > the user would need to get their own dev key). > > 2) create a web-service on a server somewhere that has your credentials, > but your distributed code merely hits this web service instead of having > your actual credentials in the source (plain-text or encrypted). The server > would have them (I'd just put them in plain-text -- no need to be fancy. If > you can't trust your hosting service, don't use them) but you wouldn't > expose the credentials outside the application. > > -tkc > > > > > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Wed May 5 23:20:10 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 05 May 2010 23:20:10 -0400 Subject: Looking for a gettext and/or Babel tutorial for Windows Message-ID: <1273116010.24126.1373643559@webmail.messagingengine.com> I'm looking for a gettext and/or Babel tutorial for Windows. Any suggestions? Specific topics I'm interested in: 1. Understanding the full life cycle of PO/POT and MO files from their initial creation to their ongoing maintenance (under Windows) 2. Automating the use of pygettext and msgfmt.py (or their GNU gettext equivalents) to update PO and MO files (under Windows) 3. Where to store my MO files (under Windows) - is there a best practice location for these files? In the absence of a tutorial, I'm open to looking at source code and/or batch/command/script/make files. Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From r1chardj0n3s at gmail.com Wed May 5 23:35:30 2010 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Thu, 6 May 2010 13:35:30 +1000 Subject: PyCon Australia Early-Bird running out! Message-ID: Registration is open and the Early Bird tickets are running out. Register here: http://pycon-au.org/reg We offer two levels of registration for PyCon Australia 2010: Full (Early Bird) - $165 This is the registration rate for regular attendees. We're offering a limited Early Bird rate for the first 50 to registration. Once the Early Bird slots are filled registration will increase to $198. Full registration includes one seat at the conference dinner on Saturday night. Student - $44 For students able to present a valid student card we're offering this reduced rate. Student registrations do not include a seat at the conference dinner. Additional seats at the conference dinner may be purchased for $77 each. All prices include GST. Information about the registration process is on the PyCon Australia website. Register here: http://pycon-au.org/reg From pietro.campe at gmail.com Wed May 5 23:52:39 2010 From: pietro.campe at gmail.com (Pietro Campesato) Date: Wed, 5 May 2010 20:52:39 -0700 (PDT) Subject: Where is python31.dll? References: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> Message-ID: <78087231-bdd2-4ebc-91b0-ade65af18f9d@k19g2000yqm.googlegroups.com> > Your windows search command? > Which is how I verified the above. I looked at the folder visually. Simply using os.listdir shows there is in fact a python31.dll there: somehow it was an invisible file. This is strange since I've never touched any system folder. Thanks and forgive me if I have asked the group a silly question. From nobody at nowhere.com Thu May 6 00:16:40 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 06 May 2010 05:16:40 +0100 Subject: strange interaction between open and cwd References: <4BDEC4A5.5070801@ftml.net> <4BDED47A.7050106@ftml.net> <84a3a5Fp5nU1@mid.individual.net> Message-ID: On Wed, 05 May 2010 13:23:03 +0100, Baz Walter wrote: >>> so >>> if several filesystems are mounted in the same parent directory, there is >>> no way to tell which of them is the "right" one. >> >> The only case which would cause a problem here is if you mount the same >> device on two different subdirectories of a common directory. But in that >> case, it doesn't really matter which answer you get, as they're both >> equivalent in any sense that matters. > > nope! just to be clear: > > here's what i get on my system, where '/dev/sda1' and '/dev/sda6' are > mounted at '/boot' and '/home' respectively: > > >>> os.stat('/').st_ino > 2L > >>> os.stat('/usr').st_ino > 212993L > >>> os.stat('/boot').st_ino > 2L > >>> os.stat('/home').st_ino > 2L > >>> Right. /, /boot and /home are separate filesystems; ext2/ext3 filesystems normally use inode #2 as the root directory. If you look at the st_dev field, all three will be different (for /boot and /home, they'll correspond to sda1 and sda6 respectively). > if the algorithm is climbing up from '/home/baz/tmp/xxx', what does it > do when it searches os.listdir('../../../..')? how can it tell whether > 'boot' or 'home' is the correct next parent if it only checks the inode > number? It doesn't. Inode numbers are only unique within a single device; you need to use both st_dev and st_ino to uniquely identify an inode within a complete filesystem. > i think the algorithm would at least need to take account of > changes in the current device id. not sure whether that would be enough > to cover all cases, though. st_dev+st_ino is sufficient. From nobody at nowhere.com Thu May 6 00:24:33 2010 From: nobody at nowhere.com (Nobody) Date: Thu, 06 May 2010 05:24:33 +0100 Subject: strange interaction between open and cwd References: <4BE16327.5050209@ftml.net> Message-ID: On Thu, 06 May 2010 10:21:45 +1000, Cameron Simpson wrote: > Look at the st_rdev field (== the device holding this inode). > When that changes, you've crossed a mount mount point. st_dev reports the device on which the inode resides. st_rdev is only meaningul if the inode type is block device (S_IFBLK) or character device (S_IFCHR), in which case it identifies the device to which the inode refers, e.g.: > os.stat("/").st_dev 2049L > os.stat("/").st_rdev 0 > os.stat("/dev/sda1").st_dev 2049L > os.stat("/dev/sda1").st_rdev 2049 > os.stat("/dev/sda2").st_dev 2049L > os.stat("/dev/sda2").st_rdev 2050 (/dev/sda1 is mounted as the root filesystem). From cs at zip.com.au Thu May 6 02:00:27 2010 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 6 May 2010 16:00:27 +1000 Subject: strange interaction between open and cwd In-Reply-To: References: Message-ID: <20100506060026.GA6171@cskk.homeip.net> On 06May2010 05:24, Nobody wrote: | On Thu, 06 May 2010 10:21:45 +1000, Cameron Simpson wrote: | | > Look at the st_rdev field (== the device holding this inode). | > When that changes, you've crossed a mount mount point. | | st_dev reports the device on which the inode resides. | | st_rdev is only meaningul if the inode type is block device (S_IFBLK) or | character device (S_IFCHR), in which case it identifies the device to | which the inode refers, e.g.: Gah. Yes, you're quite right. st_dev is what I should have been citing. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ It's better, when you're riding with someone you don't know so well, to stick to the inside line - it's easier to avoid the bits... - Barry Sheene From no.email at nospam.invalid Thu May 6 02:55:23 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 05 May 2010 23:55:23 -0700 Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: <7x7hnhjz8k.fsf@ruckus.brouhaha.com> see at sig.for.address (Victor Eijkhout) writes: > I have two long ints, both too long to convert to float, but their ratio > is something reasonable. How can I compute that? The obvious "(1.*x)/y" > does not work. The math.log function has a special hack for long ints, that might help: Python 2.6.2 (r262:71600, Jan 25 2010, 18:46:47) >>> from math import * >>> a = log(3**100000) >>> a 109861.22886681097 >>> b = log(3**100001) >>> exp(b-a) 2.9999999999994813 From no.email at nospam.invalid Thu May 6 02:59:23 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 05 May 2010 23:59:23 -0700 Subject: Sharing a program I wrote References: <76a2075b-a8d8-49eb-8611-bc8f023a31fe@d39g2000yqa.googlegroups.com> Message-ID: <7x39y5jz1w.fsf@ruckus.brouhaha.com> Scott writes: > I've seen pypi. It seems to index code that is posted on all sorts of > sites - including pypi itself? And what is a "package" anyway? I've > seen sourceforge. It looks like a good home for big applications or > multi-developer projects. Freshmeat? Google code? My own website? Your > blog? My friends like github.com for code hosting. There is an xkcd about it: http://xkcd.com/624/ If it's just a one-off script that you want comments on, you can post it here on clpy. Or if you want to chat with other programmers about it, download an irc client and visit #python on irc.freenode.net. From ldo at geek-central.gen.new_zealand Thu May 6 03:14:23 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 06 May 2010 19:14:23 +1200 Subject: condition and True or False References: <685761fe-b052-4d89-92d3-17d1f2a39e34@p2g2000yqh.googlegroups.com> Message-ID: In message <685761fe-b052-4d89-92d3-17d1f2a39e34 at p2g2000yqh.googlegroups.com>, Paul McGuire wrote: > While sifting through some code looking for old "x and y or z" code > that might better be coded using "y if x else z", I came across this > puzzler: > > x = and True or False I suspect the ?boolean expression? isn?t actually evaluating to a Boolean at all, this is simply a long-winded way of converting values that Python treats as ?false? (e.g. None, 0, what else?) to actual False, and everything else to True. From news1234 at free.fr Thu May 6 03:34:50 2010 From: news1234 at free.fr (News123) Date: Thu, 06 May 2010 09:34:50 +0200 Subject: modifying open office spreadsheet (with OO installed) In-Reply-To: References: <4bd8aa92$0$2118$426a34cc@news.free.fr> <4bd9ec94$0$24904$426a74cc@news.free.fr> <4BD9FB33.90208@comcast.net> Message-ID: <4be2711a$0$12973$426a74cc@news.free.fr> Hi CHris, Chris Withers wrote: > Jim Byrnes wrote: >> News123 wrote: >>> Mumbling to myself, perhaps somebody else is interested. >> >> Yes I am. >> >>> News123 wrote: >>>> Hi, >>>> >>>> >>>> I wanted to know who can recommend a good module/library, that >>>> allows to >>>> modify an Open Office spreadsheet. >>>> >>>> One can assume, that Open Office is installed on the host. >>>> >>>> >>> Following url gives a small introduction about using the PyUno-bridge to >>> open-read-modify-save a spread sheet >>> http://stuvel.eu/ooo-python > > If .xls files are an option for you, xlutils.copy is your friend: > > https://secure.simplistix.co.uk/svn/xlutils/trunk/xlutils/docs/copy.txt > In fact I like this library and for some things I intend to do it's a rather nice option. However for changing a few fields and keeping all the rest exactly as it is it doesn't seem to be the most apropriate solution (without some hacking) as formulas might get lost. > cheers, > > Chris > From news1234 at free.fr Thu May 6 03:38:31 2010 From: news1234 at free.fr (News123) Date: Thu, 06 May 2010 09:38:31 +0200 Subject: ooolib, reading writing a spread sheet and keep formatting In-Reply-To: References: <4bd8cfc3$0$667$426a74cc@news.free.fr> <4BD94090.8060005@free.fr> <4BE09A9B.60404@free.fr> Message-ID: <4be271f7$0$12973$426a74cc@news.free.fr> Hi Chris, Chris Withers wrote: > News123 wrote: >> Hi Chris, >> >> >> Chris Withers wrote: >>> News123 wrote: >>>> from xlrd import open_workbook >>>> from xlutils.copy import copy >>>> >>>> rb = open_workbook('doc1.xls') >>> open_workbook('doc1.xls',formatting_info=True) >> >> I'll try, but the doc mentioned explicitely, that formulas will be lost. >> I'll keep you updated. > > Yup, for them to be preserved, someone needs to either provide the > patches or stump up the cash to get the features implemented. Thanks for your clarification. You want to say, that there is a newer version or patches, which will treat formulas? Might be interestng. Currently Iswitched to the uno module, which is a little bulky, but generates for my case the correct docs on any system with OO installed. N From lucaberto at libero.it Thu May 6 03:40:50 2010 From: lucaberto at libero.it (luca72) Date: Thu, 6 May 2010 00:40:50 -0700 (PDT) Subject: pysms Message-ID: Hello Has anyone used pysms can you tell me with wich gsm module it works? Thanks Luca From andreas.loescher at s2005.tu-chemnitz.de Thu May 6 03:56:41 2010 From: andreas.loescher at s2005.tu-chemnitz.de (Andreas =?ISO-8859-1?Q?L=F6scher?=) Date: Thu, 06 May 2010 09:56:41 +0200 Subject: Parser In-Reply-To: <1272830042.14469.1.camel@laptop> References: <1272830042.14469.1.camel@laptop> Message-ID: <1273132601.4785.0.camel@laptop> Am Sonntag, den 02.05.2010, 21:54 +0200 schrieb Andreas L?scher: > Hi, > I am looking for an easy to use parser. I am want to get an overview > over parsing and want to try to get some information out of a C-Header > file. Which parser would you recommend? > > Best, > Andreas > Thanks for your answers. I think I will have a look at ANTLR to do some parsing. Best, Andreas From mkiever at Pirx.sirius.org Thu May 6 04:00:30 2010 From: mkiever at Pirx.sirius.org (Matthias Kievernagel) Date: Thu, 6 May 2010 08:00:30 +0000 (UTC) Subject: py3 tkinter acceps bytes. why? References: >>Me: >> I asked what kinds of bytes are accepted as tkinter parameters. >> I still wonder why they are accepted at all. >> Does anyone know a reason for this >> or has a link to some relevant discussion? >Terry Reedy: > I do not remember any particular public discussion of tkinter on the dev > lists. I suspect the reason is a) avoid breaking old code and b) tkinter > (tk inter-face) passes params on to tk which expects byte strings. I > would not be surprised if tkinter has to encode py3 (unicode) strings > before passing them on. If I interpret the code in _tkinter.c correctly Python bytes are converted to a String Tcl_Obj and Python str to a Unicode Tcl_Obj: AsObj(PyObject *value) { ... if (PyBytes_Check(value)) return Tcl_NewStringObj(PyBytes_AS_STRING(value), PyBytes_GET_SIZE(value)); ... else if (PyUnicode_Check(value)) { ... return Tcl_NewUnicodeObj(inbuf, size); ... } And as Martin pointed out: >That's basically because the port from 2.x was shallow: it supports the >exact same feature set that 2.x supports, with just the type names >swapped. If I don't want bytes to get passed to tkinter I just have to raise an exception in AsObj, no? Or is it even sufficient to just remove the bytes case? Regards and thanks for your answers. Matthias Kievernagel. From dickinsm at gmail.com Thu May 6 04:22:09 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 6 May 2010 01:22:09 -0700 (PDT) Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> <1jhxakp.1xj5u9nd6k7x7N%see@sig.for.address> Message-ID: On May 3, 9:49?pm, s... at sig.for.address (Victor Eijkhout) wrote: > Jerry Hill wrote: > > >>> from __future__ import division > > >>> long1/long2 > > 0.5 > > Beautiful. Thanks so much guys. And if for some reason you don't want to use the 'from __future__' import, then you can do long1.__truediv__(long2): >>> n = 765*10**1000 + 1 >>> n.__truediv__(n+1) 1.0 If you care about speed at all, I'd avoid the Fractions solution; it does an expensive and slow gcd computation. -- Mark From mannu_0523 at rediffmail.com Thu May 6 04:22:53 2010 From: mannu_0523 at rediffmail.com (mannu jha) Date: 6 May 2010 08:22:53 -0000 Subject: =?utf-8?B?Y29sdW1uIHNlbGVjdGlvbg==?= Message-ID: <20100506082253.25882.qmail@f4mail-235-130.rediffmail.com> Hi, I have few files like this: 24 ALA helix (helix_alpha, helix2) 27 ALA helix (helix_alpha, helix2) 51 ALA helix (helix_alpha, helix4) 58 ALA helix (helix_alpha, helix5) 63 ALA helix (helix_alpha, helix5) now with this program: for line in open('1.txt'): columns = line.split() print columns[0], columns[2] I am trying to print only 1st and third column but it showing error like: mruser at caf:~> python split.py 24 helix Traceback (most recent call last): File "split.py", line 3, in print columns[0], columns[2] IndexError: list index out of range nmruser at caf:~> how to rectify it. Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From massi_srb at msn.com Thu May 6 04:22:54 2010 From: massi_srb at msn.com (Massi) Date: Thu, 6 May 2010 01:22:54 -0700 (PDT) Subject: ctypes:Multiple library access problem Message-ID: <87a9ce5a-aa16-44f2-bcd7-7b790fe75466@b7g2000yqk.googlegroups.com> Hi everyone, in my script I need to execute multiple separated loading of the same dll library, in order to handle the internal variables with different threads. Consider the followin piece of code: lib1 = cdll.LoadLibrary("MyLib.dll")) lib2 = cdll.LoadLibrary("MyLib.dll")) lib1.var1 = 0 lib2.var1 = 1 Now, if I print the value of lib1.var1 I get 1, that is lib1 and lib2 point to the same memory space. Is there a way to create "different instances" of the same library? Or, alternatively, does it exist any workaround to avoid lib1 and lib2 share the same memory space? Thanks in advance. From kurianmthayil at gmail.com Thu May 6 04:47:40 2010 From: kurianmthayil at gmail.com (Kurian Thayil) Date: Thu, 6 May 2010 14:17:40 +0530 Subject: Python - MySQL fetching values Message-ID: Hi All, I am pretty new to python, and I have an issue with fetching values in python using MySQLdb module. The query executed is *SELECT TIME(DATE_ADD(info_last_calltime, INTERVAL %s MINUTE)) FROM rem_call_info WHERE info_ctrlid=%s""", (retryinterval,controlid1,)* where retryinterval=30 and controlid=2, the expected output is *05:35:05*. Now, here is code snippet, cursor1=getconnect1.cursor() getrows=cursor1.execute("""SELECT TIME(DATE_ADD(info_last_calltime, INTERVAL %s MINUTE)) FROM rem_call_info WHERE info_ctrlid=%s""", (retryinterval,controlid1,)) rawstatus20result=cursor1.fetchone() print "Raw result is",rawstatus20result status20result=rawstatus20result[0] print "The query result for Status 20:",status20result,";Time now is",timeformat The output is: Raw result is (datetime.timedelta(0, 20105),) The query result for Status 20: 5:35:05 ;Time now is 05:22:00 Match not found. New call to be made Getting next value if any... If you look closer, the time fetched by python module was 5:35:05 instead of 05:35:05. How can I get this time format? Thanks in advance. Regards, Kurian Thayil. -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Thu May 6 04:48:55 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 6 May 2010 18:48:55 +1000 Subject: column selection In-Reply-To: <20100506082253.25882.qmail@f4mail-235-130.rediffmail.com> References: <20100506082253.25882.qmail@f4mail-235-130.rediffmail.com> Message-ID: You need to ignore empty lines. for line in open('1.txt'): if len(line.strip()) == 0: continue columns = line.split() print columns[0], columns[2] Cheers, Xav On Thu, May 6, 2010 at 6:22 PM, mannu jha wrote: > Hi, > > I have few files like this: > > 24 ALA helix (helix_alpha, helix2) > > > 27 ALA helix (helix_alpha, helix2) > > > 51 ALA helix (helix_alpha, helix4) > > > 58 ALA helix (helix_alpha, helix5) > > > 63 ALA helix (helix_alpha, helix5) > > now with this program: > > for line in open('1.txt'): > columns = line.split() > print columns[0], columns[2] > > I am trying to print only 1st and third column but it showing error like: > mruser at caf:~> python split.py > 24 helix > Traceback (most recent call last): > File "split.py", line 3, in > print columns[0], columns[2] > IndexError: list index out of range > nmruser at caf:~> > how to rectify it. > > Thanks, > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu May 6 05:10:16 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 06 May 2010 05:10:16 -0400 Subject: Where is python31.dll? In-Reply-To: <78087231-bdd2-4ebc-91b0-ade65af18f9d@k19g2000yqm.googlegroups.com> References: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> <78087231-bdd2-4ebc-91b0-ade65af18f9d@k19g2000yqm.googlegroups.com> Message-ID: <4BE28778.7030809@ieee.org> Pietro Campesato wrote: >> Your windows search command? >> Which is how I verified the above. >> > > I looked at the folder visually. Simply using os.listdir shows there > is in fact a python31.dll there: somehow it was an invisible file. > This is strange since I've never touched any system folder. Thanks and > forgive me if I have asked the group a silly question. > > "visually"? Lots of possibilities there. And if you're not sure, you need to get familiar with Windows quirks. IF you're using Explorer, there are a few ways you could miss a single file out of thousands. Simplest is that the listing is not necessarily completely sorted. You need to do a View->ArrangeIconsBy->Name to really trust that they're sorted today. And you may have to repeat that menu again next time you launch Explorer, or even next time you look at some other directory. Next is that Explorer is initialized by Microsoft to mostly use the worst possible defaults. One is to hide system and hidden files . Another is to hide extensions of known types. Either of these could make you overlook the file. HTH DaveA From mail at timgolden.me.uk Thu May 6 05:11:22 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 06 May 2010 10:11:22 +0100 Subject: Windows7 run python script / sub process with elevated privileges In-Reply-To: <4bdc3e60$0$12096$426a74cc@news.free.fr> References: <4bdc3e60$0$12096$426a74cc@news.free.fr> Message-ID: <4BE287BA.8070708@timgolden.me.uk> On 01/05/2010 15:44, News123 wrote: > Hi, > > I have a small python script, which has been started as normal non > privileged user. > > At a later point in time it would like to start another python script > with elevated privileges. > > How can I write my code such, that I will get the privilege elevation > prompt and I can start a sub process / python function with elevated > privileges. The canonical way is to use the "runas" verb from within ShellExecuteEx, which is exposed by the win32api module. TJG From clp2 at rebertia.com Thu May 6 05:12:50 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 02:12:50 -0700 Subject: Python - MySQL fetching values In-Reply-To: References: Message-ID: On Thu, May 6, 2010 at 1:47 AM, Kurian Thayil wrote: > the expected output is 05:35:05. > > Now, here is code snippet, > > ??????????????? cursor1=getconnect1.cursor() > ??????????????? getrows=cursor1.execute("""SELECT > TIME(DATE_ADD(info_last_calltime, INTERVAL %s MINUTE)) FROM rem_call_info > WHERE info_ctrlid=%s""", (retryinterval,controlid1,)) > ??????????????? rawstatus20result=cursor1.fetchone() > ??????????????? print "Raw result is",rawstatus20result > ??????????????? status20result=rawstatus20result[0] > ??????????????? print "The query result for Status > 20:",status20result,";Time now is",timeformat > > The output is: > > Raw result is (datetime.timedelta(0, 20105),) > The query result for Status 20: 5:35:05 ;Time now is 05:22:00 > Match not found. > New call to be made > Getting next value if any... > > If you look closer, the time fetched by python module was 5:35:05 instead of > 05:35:05. How can I get this time format? Thanks in advance. You're getting back a time delta (i.e. quantity/duration of time, e.g. "3 hours") rather than an actual time (i.e. temporal coordinates for a particular instant of time, e.g. "5:15PM and 2 seconds"), and timedelta defines its stringification differently, hence your issue. I would guess that getting back a timedelta instead of a time is some quirk of MySQLdb; haven't used it though, so I'm just guessing. Anyway, you can work around this by converting the timedelta object to a time object yourself: #Untested Code! from datetime import time minutes, seconds = divmod(status20result.seconds, 60) hours, minutes = divmod(minutes, 60) time_result = time(hours, minutes, seconds, status20result.microseconds) print "The query result for Status 20:",time_result,";Time now is",timeformat Cheers, Chris -- http://blog.rebertia.com From davea at ieee.org Thu May 6 05:21:50 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 06 May 2010 05:21:50 -0400 Subject: ctypes:Multiple library access problem In-Reply-To: <87a9ce5a-aa16-44f2-bcd7-7b790fe75466@b7g2000yqk.googlegroups.com> References: <87a9ce5a-aa16-44f2-bcd7-7b790fe75466@b7g2000yqk.googlegroups.com> Message-ID: <4BE28A2E.1080509@ieee.org> Massi wrote: > Hi everyone, > > in my script I need to execute multiple separated loading of the same > dll library, in order to handle the internal variables with different > threads. > Consider the followin piece of code: > > lib1 = cdll.LoadLibrary("MyLib.dll")) > lib2 = cdll.LoadLibrary("MyLib.dll")) > > lib1.var1 = 0 > lib2.var1 = 1 > > Now, if I print the value of lib1.var1 I get 1, that is lib1 and lib2 > point to the same memory space. Is there a way to create "different > instances" of the same library? Or, alternatively, does it exist any > workaround to avoid lib1 and lib2 share the same memory space? > > Thanks in advance. > > Windows will not load the same DLL twice into the same process in two different places. When it detects that it's the same one, it simply returns the same handle as the earlier one, without any loading or initializing. With some DLL's, you might get away with copying it to a different filename, and then loading each as an independent item. But unless you wrote it yourself, or it has been documented for that behavior, you're taking a big risk. On the other hand, if the DLL was written with threading in mind, then it'll get notified for each new thread you create, and it can manage TLS (thread local storage) rather than using extern vars. I have no idea how to get at those from Python, however. DaveA From richard.lamboj at bilcom.at Thu May 6 05:24:49 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Thu, 6 May 2010 11:24:49 +0200 Subject: Classes: nested functions vs. private methodes Message-ID: <201005061124.50324.richard.lamboj@bilcom.at> Hello, what should i take: - nested functions: class MyClass(object) def blah(self): def blub(var1, var2): do something... blub(1, 5) or class MyClass(object) def blah(self): def _blub(var1, var2): do something... _blub(1, 5) - "private" functions: class MyClass(object) def blah(self): self._blub() def _blub(self): do something... What is more pythonic? It is just for splitting up long code in classes. Kind Regards, Richi From davea at ieee.org Thu May 6 05:26:07 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 06 May 2010 05:26:07 -0400 Subject: column selection In-Reply-To: <20100506082253.25882.qmail@f4mail-235-130.rediffmail.com> References: <20100506082253.25882.qmail@f4mail-235-130.rediffmail.com> Message-ID: <4BE28B2F.2050604@ieee.org> mannu jha wrote: > Hi, > > I have few files like this: > > 24 ALA helix (helix_alpha, helix2) > > > 27 ALA helix (helix_alpha, helix2) > > > 51 ALA helix (helix_alpha, helix4) > > > 58 ALA helix (helix_alpha, helix5) > > > 63 ALA helix (helix_alpha, helix5) > > now with this program: > > for line in open('1.txt'): > columns = line.split() > print columns[0], columns[2] > > I am trying to print only 1st and third column but it showing error like: > mruser at caf:~> python split.py > 24 helix > Traceback (most recent call last): > File "split.py", line 3, in > print columns[0], columns[2] > IndexError: list index out of range > nmruser at caf:~> > how to rectify it. > > Thanks, > > If your files have two blank lines between each useful line, you have to do something to avoid trying to print those items for the blank lines. Depending how sure you are about your formatting, you could either do a if not line: continue or a if columns < 3: continue DaveA From duncan.booth at invalid.invalid Thu May 6 05:26:50 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 May 2010 09:26:50 GMT Subject: long int computations References: <1jhwv88.1hhc7vi1vqa6m8N%see@sig.for.address> Message-ID: Peter Otten <__peter__ at web.de> wrote: > Victor Eijkhout wrote: > >> I have two long ints, both too long to convert to float, but their ratio >> is something reasonable. How can I compute that? The obvious "(1.*x)/y" >> does not work. > >>>> import fractions >>>> x = 12345 * 10**1000 >>>> y = 765 * 10**1000 >>>> float(x) > Traceback (most recent call last): > File "", line 1, in > OverflowError: long int too large to convert to float >>>> fractions.Fraction(x, y) > Fraction(823, 51) >>>> float(_) > 16.137254901960784 > Another way of doing this is simply to scale the values down until they do fit in a float: >>> x = 12345 * 10**1000 >>> y = 765 * 10**1000 >>> maxfloat = 1e308 # or whatever it actually is... >>> d = max(max(abs(x),abs(y))//long(maxfloat), 1) >>> float(x//d)/float(y//d) 16.137254901960784 I think that should work for any cases where the ratio fits in a float (if it doesn't then you might get a ZeroDivisionError or inf or -inf). -- Duncan Booth http://kupuguy.blogspot.com From hihighsky at gmail.com Thu May 6 05:49:29 2010 From: hihighsky at gmail.com (Tingting HAN) Date: Thu, 6 May 2010 11:49:29 +0200 Subject: running .py files on Linux Message-ID: Dear Officer, I want to run two .py files to generate .h5 files. hantingting at tityro:~$ python2.5 Python 2.5.4 (r254:67916, Jan 20 2010, 21:43:02) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. When ruuning gentest_sphere.py, the problem is as following: hantingting at tityro:~/Downloads/triMC3D/python$ python2.5 gentest_sphere.py gsphere.h5 Usage: gentest_sphere.pynEl Testfile.h5 options: n: number of elements hantingting at tityro:~/Downloads/triMC3D/python$ I guess I should write the command in the format of usage, but I don't know how to do it. When ruuning test_detector.py, the problem is as following: hantingting at tityro:~/Downloads/triMC3D/python$ python2.5 test_detector.py tdetector.h5 h5/Opaque_material/ext_Trabecular_Bone-int_Cartilage/Nonenm/SourceNone/ lamb = None Traceback (most recent call last): File "test_detector.py", line 600, in main() File "test_detector.py", line 567, in main hdf5.subs_lamb( materials, lamb ) File "/home/hantingting/Downloads/triMC3D/python/local_modules/hdf5.py", line 703, in subs_lamb m.mu_s = m.mu_s(l) File "/home/hantingting/Downloads/triMC3D/python/local_modules/matslib.py", line 71, in [1550.0,1460.0,1360.0,1300.0,1240.0,1220.0,1220.0,1200.0,1160.0], s=300 )) File "/usr/lib/python2.5/site-packages/scipy/interpolate/fitpack.py", line 485, in splev y,ier=_fitpack._spl_(x,der,t,c,k) TypeError: array cannot be safely cast to required type hantingting at tityro:~/Downloads/triMC3D/python$ python2.5 test_detector.py usage: test_detector.py outputfile.h5 [options] options: -c Cage Material -e External Material -i Internal Material -l Lambda -o Output String -s Source Number -h Shows this help hantingting at tityro:~/Downloads/triMC3D/python$ Could you please give me some advice to solve these two problems? I sincerely apologize that I am new for python. -- Best regards, HAN Tingting -------------- next part -------------- An HTML attachment was scrubbed... URL: From SSchukat at dspace.de Thu May 6 05:56:59 2010 From: SSchukat at dspace.de (Stefan Schukat) Date: Thu, 6 May 2010 11:56:59 +0200 Subject: ctypes:Multiple library access problem In-Reply-To: <4BE28A2E.1080509@ieee.org> References: <87a9ce5a-aa16-44f2-bcd7-7b790fe75466@b7g2000yqk.googlegroups.com> <4BE28A2E.1080509@ieee.org> Message-ID: <9015A9FD792E914DADD11DDEB075333843B925F15C@exchange2007.dspace.de> Massi wrote: > > Hi everyone, > > > > in my script I need to execute multiple separated loading of the same > > dll library, in order to handle the internal variables with different > > threads. > > Consider the followin piece of code: > > > > lib1 = cdll.LoadLibrary("MyLib.dll")) > > lib2 = cdll.LoadLibrary("MyLib.dll")) > > > > lib1.var1 = 0 > > lib2.var1 = 1 > > > > Now, if I print the value of lib1.var1 I get 1, that is lib1 and lib2 > > point to the same memory space. Is there a way to create "different > > instances" of the same library? Or, alternatively, does it exist any > > workaround to avoid lib1 and lib2 share the same memory space? > > > > Thanks in advance. > > > > > Windows will not load the same DLL twice into the same process in two > different places. When it detects that it's the same one, it simply > returns the same handle as the earlier one, without any loading or > initializing. > > With some DLL's, you might get away with copying it to a different > filename, and then loading each as an independent item. But unless you > wrote it yourself, or it has been documented for that behavior, you're > taking a big risk. > > On the other hand, if the DLL was written with threading in mind, then > it'll get notified for each new thread you create, and it can manage TLS > (thread local storage) rather than using extern vars. I have no idea > how to get at those from Python, however. > > DaveA > > -- > http://mail.python.org/mailman/listinfo/python-list > The statement from Dave is as far true as the library is loaded without a path. Hence windows searches the system path and always finds the same file. If you load a DLL with an absolute path window will place the dll multiple times into the process. e.g. lib1 = cdll.LoadLibrary(r"c:\temp\MyLib.dll") lib2 = cdll.LoadLibrary(r"d:\temp\MyLib.dll") This has the same effect as renaming the library on the disk. Stefan From steven at REMOVE.THIS.cybersource.com.au Thu May 6 06:02:47 2010 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 06 May 2010 10:02:47 GMT Subject: Classes: nested functions vs. private methodes References: Message-ID: On Thu, 06 May 2010 11:24:49 +0200, Richard Lamboj wrote: > Hello, > > what should i take: > - nested functions: > class MyClass(object) > def blah(self): > def blub(var1, var2): > do something... > blub(1, 5) The disadvantage of nested functions is that it is harder to test them in isolation. > or > > class MyClass(object) > def blah(self): > def _blub(var1, var2): > do something... > _blub(1, 5) There is no real point in marking a nested function as "private" with a leading underscore, as no other object can get access to it. > - "private" functions: > class MyClass(object) > def blah(self): > self._blub() > def _blub(self): > do something... This has the advantage of allowing you to test blah() and _blub() in isolation. It has the disadvantage of polluting the namespace of MyClass with an extra visible method, _blub. > What is more pythonic? Both are Pythonic. Private methods are more object oriented, nested functions are more procedural, but it is mostly a matter of taste which you use. You can use either, or a combination of both, or even do this: class _MyClass(object): """Private class blah blah blah...""" def blah(self, arg): do something... class MyClass(_MyClass): """Public interface to _MyClass""" def blah(self, arg): arg = preprocessing(arg) x = super(MyClass, self).blah(arg) x = postprocessing(x) return x -- Steven From jonvspython at gmail.com Thu May 6 06:38:18 2010 From: jonvspython at gmail.com (jon vs. python) Date: Thu, 6 May 2010 12:38:18 +0200 Subject: pysms In-Reply-To: References: Message-ID: Hi Luca, I've never used pysms, but I just downloaded the source code and it seems that SMS related functionallity is performed using standard GSM AT commands. So if you're accessing the gsm module through a serial port you shouldn't worry at all. Hope it helps, Jon. On Thu, May 6, 2010 at 9:40 AM, luca72 wrote: > Hello > Has anyone used pysms can you tell me with wich gsm module it works? > > Thanks > > Luca > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From richard.lamboj at bilcom.at Thu May 6 06:40:16 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Thu, 6 May 2010 12:40:16 +0200 Subject: Classes: nested functions vs. private methodes In-Reply-To: References: Message-ID: <201005061240.16391.richard.lamboj@bilcom.at> Am Thursday 06 May 2010 12:02:47 schrieb Steven D'Aprano: > On Thu, 06 May 2010 11:24:49 +0200, Richard Lamboj wrote: > > Hello, > > > > what should i take: > > - nested functions: > > class MyClass(object) > > def blah(self): > > def blub(var1, var2): > > do something... > > blub(1, 5) > > The disadvantage of nested functions is that it is harder to test them in > isolation. > > > or > > > > class MyClass(object) > > def blah(self): > > def _blub(var1, var2): > > do something... > > _blub(1, 5) > > There is no real point in marking a nested function as "private" with a > leading underscore, as no other object can get access to it. > > > - "private" functions: > > class MyClass(object) > > def blah(self): > > self._blub() > > def _blub(self): > > do something... > > This has the advantage of allowing you to test blah() and _blub() in > isolation. It has the disadvantage of polluting the namespace of MyClass > with an extra visible method, _blub. > > > What is more pythonic? > > Both are Pythonic. Private methods are more object oriented, nested > functions are more procedural, but it is mostly a matter of taste which > you use. You can use either, or a combination of both, or even do this: > > > class _MyClass(object): > """Private class blah blah blah...""" > def blah(self, arg): > do something... > > class MyClass(_MyClass): > """Public interface to _MyClass""" > def blah(self, arg): > arg = preprocessing(arg) > x = super(MyClass, self).blah(arg) > x = postprocessing(x) > return x > > > > -- > Steven Thank you for the nice sample, but what is with multiple inheritance in your sample? I mean the super call. Why not _MyClass.blah(self, arg). What is when i have more then one Class from which i inherite and in both are a methode called "blah", but i just want to call one of them and not both, becouse they do different things? Kind Regards, Richi From fw at deneb.enyo.de Thu May 6 07:09:04 2010 From: fw at deneb.enyo.de (Florian Weimer) Date: Thu, 06 May 2010 13:09:04 +0200 Subject: Compression module APIs Message-ID: <874oil8ey7.fsf@mid.deneb.enyo.de> As far as I can see, the compression-related APIs (gzip, zlib, bzip2) in Python 2.5 have three distinct APIs. Is there really no unified interface, or am I missing something? From clp2 at rebertia.com Thu May 6 07:37:21 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 04:37:21 -0700 Subject: Compression module APIs In-Reply-To: <874oil8ey7.fsf@mid.deneb.enyo.de> References: <874oil8ey7.fsf@mid.deneb.enyo.de> Message-ID: On Thu, May 6, 2010 at 4:09 AM, Florian Weimer wrote: > As far as I can see, the compression-related APIs (gzip, zlib, bzip2) > in Python 2.5 have three distinct APIs. ?Is there really no unified > interface, or am I missing something? bz2.BZ2File and gzip.GzipFile both offer a file-like interface for reading/writing compressed files in their respective formats. The gzip module is already built on top of the zlib module, so there's no ZlibFile. zlib and bz2 also both offer compatible one-shot compress() and decompress() functions. So, the interfaces are sorta "unified", although it is true they're not grouped into a single generic "compression" module. Cheers, Chris -- http://blog.rebertia.com From fw at deneb.enyo.de Thu May 6 07:41:56 2010 From: fw at deneb.enyo.de (Florian Weimer) Date: Thu, 06 May 2010 13:41:56 +0200 Subject: Compression module APIs In-Reply-To: (Chris Rebert's message of "Thu, 6 May 2010 04:37:21 -0700") References: <874oil8ey7.fsf@mid.deneb.enyo.de> Message-ID: <87tyql6yuz.fsf@mid.deneb.enyo.de> * Chris Rebert: > On Thu, May 6, 2010 at 4:09 AM, Florian Weimer wrote: >> As far as I can see, the compression-related APIs (gzip, zlib, bzip2) >> in Python 2.5 have three distinct APIs. ?Is there really no unified >> interface, or am I missing something? > > bz2.BZ2File and gzip.GzipFile both offer a file-like interface for > reading/writing compressed files in their respective formats. > The gzip module is already built on top of the zlib module, so there's > no ZlibFile. > zlib and bz2 also both offer compatible one-shot compress() and > decompress() functions. > So, the interfaces are sorta "unified", although it is true they're > not grouped into a single generic "compression" module. Some overlap is there. But but there does not appear to be a way to decompress a gzip stream on the fly (which is surprising, as this is a fairly common operation), and there are no counterparts to bz2.BZ2{Dec,C}ompressor. From clp2 at rebertia.com Thu May 6 07:52:30 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 04:52:30 -0700 Subject: Compression module APIs In-Reply-To: <87tyql6yuz.fsf@mid.deneb.enyo.de> References: <874oil8ey7.fsf@mid.deneb.enyo.de> <87tyql6yuz.fsf@mid.deneb.enyo.de> Message-ID: On Thu, May 6, 2010 at 4:41 AM, Florian Weimer wrote: > * Chris Rebert: >> On Thu, May 6, 2010 at 4:09 AM, Florian Weimer wrote: >>> As far as I can see, the compression-related APIs (gzip, zlib, bzip2) >>> in Python 2.5 have three distinct APIs. ?Is there really no unified >>> interface, or am I missing something? >> >> bz2.BZ2File and gzip.GzipFile both offer a file-like interface for >> reading/writing compressed files in their respective formats. >> The gzip module is already built on top of the zlib module, so there's >> no ZlibFile. >> zlib and bz2 also both offer compatible one-shot compress() and >> decompress() functions. >> So, the interfaces are sorta "unified", although it is true they're >> not grouped into a single generic "compression" module. > > Some overlap is there. ?But but there does not appear to be a way to > decompress a gzip stream on the fly (which is surprising, as this is a > fairly common operation), and there are no counterparts to > bz2.BZ2{Dec,C}ompressor. Well, there are zlib equivalents: http://docs.python.org/library/zlib.html#zlib.decompressobj http://docs.python.org/library/zlib.html#zlib.compressobj As for gzip, you might be able to pass a StringIO object as the `fileobj` argument to zip.GzipFile's constructor; that'd give you basically the same thing as a Gzip{Dec,C}ompressor. I haven't tried it, but there's a decent chance it might work. Cheers, Chris -- http://blog.rebertia.com From rjvbertin at gmail.com Thu May 6 08:16:14 2010 From: rjvbertin at gmail.com (=?ISO-8859-1?Q?Ren=E9_J=2EV=2E_Bertin?=) Date: Thu, 6 May 2010 14:16:14 +0200 Subject: crash in Py_EnterRecursiveCall In-Reply-To: References: Message-ID: Hello, I have embedded Python into and extended it with functionality from a graphical tool I use. One of the things it allows me to do is to export Python objects to a simple scripting language ("ascanf"), and call them as if they were native functions. I have the following situation in which I get a systematic segmentation violation in Py_EnterRecursiveCall(), in Python 2.4 2.5 and 2.6 (OS X) and on Cygwin with 2.5 and 2.6 . I enter an interactive Python 'console' from within my application, either the one from the interact package, or the IPython shell. My application has a callback defined for the readline routines that calls the graphical event handler, allowing for instance refresh/redraws to continue while working in the Python console. The crash occurs when during such events handled through the readline callback, I call an exported Python object. This does not appear to be related to recursion per se, but rather to "calling a python interpreter behind the back of the currently active console/interpreter". To be clearer, suppose I have some Python code def Py_travDistCalc(a,b,c): ... return x ascanf.ExportVariable("travDistCalc", Py_travDistCalc ) I can then issue a call 1) travDistCalc[a,b,c] from an ascanf script. 2) ascanf.Eval( 'travDistCalc[a,b,c]' ) from the Python console Call 1) provokes a crash in Py_EnterRecursiveCall() when invoked through the readline callback when the Python console is open, but call 2) succeeds normally. Note that this is a single-threaded application. My workaround is to keep track of the readline callback recursion level, and compare the current level with the level recorded when entering a Python console before doing the PyObject_CallObject() required in call 1) and 2) above. In Python 2.3, the Py_xxxRecursiveCall functions are missing, but I also get a crash, so I guess I'm doing something really nasty. I'm not sure if this is a bug in Python. It is the sort of crash situation I'd try to avoid, though. From mannu_0523 at rediffmail.com Thu May 6 08:24:34 2010 From: mannu_0523 at rediffmail.com (mannu jha) Date: 6 May 2010 12:24:34 -0000 Subject: =?utf-8?B?UmU6IFJlOiBjb2x1bW4gc2VsZWN0aW9u?= In-Reply-To: <4BE28B2F.2050604@ieee.org> Message-ID: <1273140847.S.2303.13864.f4mail-235-207.rediffmail.com.1273148674.35579@webmail.rediffmail.com> I tried with this: for line in open('1.txt'): columns = line.split() print columns[0], columns[1] if not line: continue but it is showing error: nmruser at caf:~> python split.py 24 ALA Traceback (most recent call last): File "split.py", line 3, in print columns[0], columns[1] IndexError: list index out of range nmruser at caf:~> Thanks, On Thu, 06 May 2010 15:44:07 +0530 wrote >mannu jha wrote: > Hi, > > I have few files like this: > > 24 ALA helix (helix_alpha, helix2) > > > 27 ALA helix (helix_alpha, helix2) > > > 51 ALA helix (helix_alpha, helix4) > > > 58 ALA helix (helix_alpha, helix5) > > > 63 ALA helix (helix_alpha, helix5) > > now with this program: > > for line in open('1.txt'): > columns = line.split() > print columns[0], columns[2] > > I am trying to print only 1st and third column but it showing error like: > mruser at caf:~> python split.py > 24 helix > Traceback (most recent call last): > File "split.py", line 3, in > print columns[0], columns[2] > IndexError: list index out of range > nmruser at caf:~> > how to rectify it. > > Thanks, > > If your files have two blank lines between each useful line, you have to do something to avoid trying to print those items for the blank lines. Depending how sure you are about your formatting, you could either do a if not line: continue or a if columns < 3: continue DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at shopzeus.com Thu May 6 08:58:55 2010 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 06 May 2010 14:58:55 +0200 Subject: running .py files on Linux In-Reply-To: References: Message-ID: <4BE2BD0F.7090103@shopzeus.com> Tingting HAN ?rta: > Dear Officer, > I want to run two .py files to generate .h5 files. > hantingting at tityro:~$ python2.5 > Python 2.5.4 (r254:67916, Jan 20 2010, 21:43:02) > [GCC 4.4.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > When ruuning gentest_sphere.py, the problem is as following: > hantingting at tityro:~/Downloads/triMC3D/python$ > python2.5 > gentest_sphere.py gsphere.h5 > Usage: gentest_sphere.pynEl Testfile.h5 > options: > n: number of elements > hantingting at tityro:~/Downloads/triMC3D/python$ > > I guess I should write the command in the format of usage, but I don't > know how to do it. > > When ruuning test_detector.py, the problem is as following: > hantingting at tityro:~/Downloads/triMC3D/python$ > python2.5 > test_detector.py tdetector.h5 > h5/Opaque_material/ext_Trabecular_Bone-int_Cartilage/Nonenm/SourceNone/ > lamb = None > Traceback (most recent call last): > File "test_detector.py", line 600, in > main() > File "test_detector.py", line 567, in main > hdf5.subs_lamb( materials, lamb ) > File > "/home/hantingting/Downloads/triMC3D/python/local_modules/hdf5.py", > line 703, in subs_lamb > m.mu_s = m.mu_s(l) > File > "/home/hantingting/Downloads/triMC3D/python/local_modules/matslib.py", > line 71, in > [1550.0,1460.0,1360.0,1300.0,1240.0,1220.0,1220.0,1200.0,1160.0], > s=300 )) > File > "/usr/lib/python2.5/site-packages/scipy/interpolate/fitpack.py", line > 485, in splev > y,ier=_fitpack._spl_(x,der,t,c,k) > TypeError: array cannot be safely cast to required type > hantingting at tityro:~/Downloads/triMC3D/python$ > python2.5 > test_detector.py > usage: test_detector.py outputfile.h5 [options] > options: > -c Cage Material > -e External Material > -i Internal Material > -l Lambda > -o Output String > -s Source Number > -h Shows this help > hantingting at tityro:~/Downloads/triMC3D/python$ > > Could you please give me some advice to solve these two problems? I > sincerely apologize that I am new for python. Did you try this: 1.) replace the first line of gentest_sphere.py to "#!/usr/bin/python2.5" (or your path to python2.5) 2.) "chmod +x gentest_sphere.py" 3.) run this: "./gentest_sphere.py gsphere.h5" (instead of "python2.5 ./gentest_sphere.py gsphere.h5" It may not help. But... suspicious. You used the advertised command line. The program may have a bug. E.g. it uses sys.argv the incorrect way. Best, Laszlo From mount.sarah at gmail.com Thu May 6 08:59:04 2010 From: mount.sarah at gmail.com (Sarah Mount) Date: Thu, 6 May 2010 13:59:04 +0100 Subject: Python debuggers with sys.settrace() In-Reply-To: <1f8f2c8e-3ee1-4fc1-95e8-aae3e54ba1b4@n37g2000prc.googlegroups.com> References: <1f8f2c8e-3ee1-4fc1-95e8-aae3e54ba1b4@n37g2000prc.googlegroups.com> Message-ID: On 5 May 2010 10:17, Carl Banks wrote: > On May 2, 11:06?am, Sarah Mount wrote: >> This is a bit of an odd question, but is there any way for a Python >> debugger to suppress I/O generated by the program which is being >> debugged? I guess an "obvious" thing to do would be to replace core >> parts of the standard library and change any relevant imports in the >> locals and globals dicts to fake ones which don't generate I/O, but >> this seems brittle as the standard library will change over time. Is >> it possible to modify the byte-compiled code in each stack frame? Or >> is there a simpler way to do this? > > It's not foolproof but you could try to reassign sys.stdout and > sys.stderr to a bit bucket ("sys.stdout = open(os.devull)"), then > invoke the debugger with stdout set to sys._stdout (the actual > stdout). ?You'll have to create the Pdb() by hand since the built-in > convience functions don't do it. ?Check the file pdb.py for details. > Thanks Carl. I had considered this, but it won't catch things like socket communication. Hmmm..... Cheers, Sarah -- Sarah Mount, Senior Lecturer, University of Wolverhampton website: http://www.snim2.org/ twitter: @snim2 From clp2 at rebertia.com Thu May 6 09:09:16 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 06:09:16 -0700 Subject: Python debuggers with sys.settrace() In-Reply-To: References: <1f8f2c8e-3ee1-4fc1-95e8-aae3e54ba1b4@n37g2000prc.googlegroups.com> Message-ID: On Thu, May 6, 2010 at 5:59 AM, Sarah Mount wrote: > On 5 May 2010 10:17, Carl Banks wrote: >> On May 2, 11:06?am, Sarah Mount wrote: >>> This is a bit of an odd question, but is there any way for a Python >>> debugger to suppress I/O generated by the program which is being >>> debugged? I guess an "obvious" thing to do would be to replace core >>> parts of the standard library and change any relevant imports in the >>> locals and globals dicts to fake ones which don't generate I/O, but >>> this seems brittle as the standard library will change over time. Is >>> it possible to modify the byte-compiled code in each stack frame? Or >>> is there a simpler way to do this? >> >> It's not foolproof but you could try to reassign sys.stdout and >> sys.stderr to a bit bucket ("sys.stdout = open(os.devull)"), then >> invoke the debugger with stdout set to sys._stdout (the actual >> stdout). ?You'll have to create the Pdb() by hand since the built-in >> convience functions don't do it. ?Check the file pdb.py for details. >> > > Thanks Carl. I had considered this, but it won't catch things like > socket communication. Hmmm..... You could monkeypatch the socket constructors in the `socket` module to return dummies. Cheers, Chris -- http://blog.rebertia.com From davea at ieee.org Thu May 6 09:12:18 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 06 May 2010 09:12:18 -0400 Subject: column selection In-Reply-To: <1273140847.S.2303.13864.f4mail-235-207.rediffmail.com.1273148674.35579@webmail.rediffmail.com> References: <1273140847.S.2303.13864.f4mail-235-207.rediffmail.com.1273148674.35579@webmail.rediffmail.com> Message-ID: <4BE2C032.9080605@ieee.org> mannu jha wrote: > I tried with this: > > for line in open('1.txt'): > columns = line.split() > print columns[0], columns[1] > if not line: continue > > but it is showing error: > > nmruser at caf:~> python split.py > 24 ALA > Traceback (most recent call last): > File "split.py", line 3, in > print columns[0], columns[1] > IndexError: list index out of range > nmruser at caf:~> > > Thanks, > > On Thu, 06 May 2010 15:44:07 +0530 wrote > > > > If your files have two blank lines between each useful line, you have to > > do something to avoid trying to print those items for the blank lines. > > Depending how sure you are about your formatting, you could either do a > > if not line: continue > > or a > > if columns < 3: continue > > > DaveA > > > (Don't top-post. It makes the message very confusing to someone else trying to follow it. Also, enable your mail program's quoting feature -- currently it's not adding the marks at the beginning of each line you quote.) If you're going to skip over blank lines, it'd be good to do it before trying to print from it. Move the test up by a line. DaveA From cai.haibin at gmail.com Thu May 6 10:52:49 2010 From: cai.haibin at gmail.com (james_027) Date: Thu, 6 May 2010 07:52:49 -0700 (PDT) Subject: fast regex Message-ID: hi, I was working with regex on a very large text, really large but I have time constrained. Does python has any other regex library or string manipulation library that works really fast? Thanks, James From javier.collado at gmail.com Thu May 6 11:31:46 2010 From: javier.collado at gmail.com (Javier Collado) Date: Thu, 6 May 2010 17:31:46 +0200 Subject: fast regex In-Reply-To: References: Message-ID: Hello, 2010/5/6 james_027 : > I was working with regex on a very large text, really large but I have > time constrained. Does python has any other regex library or string > manipulation library that works really fast? re2 (http://code.google.com/p/re2/) is suppossed to be faster than the standard library in python. Unfortunately, it's implemented in C++ and there isn't an official python wrapper for it. However, you can find a wrapper that can be useful for you here: http://github.com/facebook/pyre2 Best regards, Javier From john at castleamber.com Thu May 6 11:33:47 2010 From: john at castleamber.com (John Bokma) Date: Thu, 06 May 2010 10:33:47 -0500 Subject: fast regex References: Message-ID: <87eihp2gf8.fsf@castleamber.com> james_027 writes: > I was working with regex on a very large text, really large but I have > time constrained. Does python has any other regex library or string > manipulation library that works really fast? Hard to answer without seeing your regex and requirements first. Your question is like: I had a meal yesterday and it upset my stomach. Can you suggest a different meal for today? -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From vriolk at gmail.com Thu May 6 11:53:49 2010 From: vriolk at gmail.com (coldpizza) Date: Thu, 6 May 2010 08:53:49 -0700 (PDT) Subject: convert Unicode filenames to good-looking ASCII Message-ID: Hello, I need to convert accented unicode chars in some audio files to similarly-looking ascii chars. Looks like the following code seems to work on windows: import os import sys import glob EXT = '*.*' lst_uni = glob.glob(unicode(EXT)) os.system('chcp 437') lst_asci = glob.glob(EXT) print sys.stdout.encoding for i in range(len(lst_asci)): try: os.rename(lst_uni[i], lst_asci[i]) except Exception as e: print e On windows it converts most of the accented chars from the latin1 encoding. This does not work in Linux since it uses 'chcp'. The questions are (1) *why* does it work on windows, and (2) what is the proper and portable way to convert unicode characters to similarly looking plain ascii chars? That is how to properly do this kind of conversion? ? > u ? > e ? > a ? > a ? > a ? > a ? > c ? > e ? > e ? > e Is there any other way apart from creating my own char replacement table? From p.f.moore at gmail.com Thu May 6 11:59:21 2010 From: p.f.moore at gmail.com (Paul Moore) Date: Thu, 6 May 2010 08:59:21 -0700 (PDT) Subject: Windows - select.select, timeout and KeyboardInterrupt Message-ID: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> >From a quick experiment, it seems that select.select with a timeout doesn't react to a keyboard interrupt until the timeout expires. Specifically, if I do s = socket.socket() select.select([s], [], [], 30) and then press Ctrl-C, Python waits for the 30 seconds before raising KeyboardInterrupt. Is this a known limitation on Windows? I see no mention of it in the documentation. Assuming it is a known limitation, is there a way round it? (I'm writing a tiny server using asyncore/asynchat, and the delayed response to Ctrl-C is a mild nuisance. Solutions such as "use twisted", while probably the sensible option in a wider context, don't really apply here - I need something within the confines of the stdlib if it's to be worth doing). Thanks, Paul From u53730 at gmail.com Thu May 6 12:22:41 2010 From: u53730 at gmail.com (Iliya) Date: Thu, 6 May 2010 20:22:41 +0400 Subject: convert Unicode filenames to good-looking ASCII In-Reply-To: References: Message-ID: Try smth like this: import unicodedata def remove_accents(str): nkfd_form = unicodedata.normalize('NFKD', unicode(str)) return u''.join([c for c in nkfd_form if not unicodedata.combining(c)]) From mal at egenix.com Thu May 6 12:26:51 2010 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 06 May 2010 18:26:51 +0200 Subject: matching strings in a large set of strings In-Reply-To: References: Message-ID: <4BE2EDCB.9090807@egenix.com> Dennis Lee Bieber wrote: > On Thu, 29 Apr 2010 11:38:28 +0200, "Karin Lagesen" > declaimed the following in comp.lang.python: > >> Hello. >> >> I have approx 83 million strings, all 14 characters long. I need to be >> able to take another string and find out whether this one is present >> within the 83 million strings. >> > Is this "another string" also exactly 14 characters long? > >> Now, I have tried storing these strings as a list, a set and a dictionary. >> I know that finding things in a set and a dictionary is very much faster >> than working with a list, so I tried those first. However, I run out of >> memory building both the set and the dictionary, so what I seem to be left >> with is the list, and using the in method. >> > So don't load them into memory... First use a file-based (not memory > limited) sort routine on the 80M strings (if position in the file is > important, make a copy with the line number on the end of each line > before sorting -- but since you've tried using Sets which do not retain > order... probably not a matter). > > Then, since you know the length of the file, and the length of each > line is fixed, you can do direct access I/O (well, since the C-stream > style I/O doesn't do "record" access, you'll need to calculate offsets > from the start of the file as (record# - 1) * recordlen)... > > That lets you do a binary search on the file. Much faster than a > linear search (linear search will average out to 41.5M read operations; > binary should be around 10000 reads) > > Or load the data into some relational database and let the compiled > code do the searching -- probably faster than byte-code interpreted > Python for the same algorithm... ... or put the data into a simple on-disc dictionary such as what mxBeeBase implements: http://www.egenix.com/products/python/mxBase/mxBeeBase/ Once you have that dict set up, lookups are very fast. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 06 2010) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From trentm at activestate.com Thu May 6 12:33:05 2010 From: trentm at activestate.com (Trent Mick) Date: Thu, 06 May 2010 09:33:05 -0700 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <1273105847.779.1373624397@webmail.messagingengine.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> <1273086295.15686.1373577021@webmail.messagingengine.com> <4BE1F91D.8050201@activestate.com> <1273105847.779.1373624397@webmail.messagingengine.com> Message-ID: <4BE2EF41.1090308@activestate.com> On 10-05-05 5:30 PM, python at bdurham.com wrote: > Hi Trent, > > On 10-05-05 12:04 PM, python at bdurham.com wrote: >>> I just took a look at the ActiveStatre 2.6.5.12 release (zip file >>> version) and noticed that this file does not include the MSVCR90.DLL run >>> time file - it includes MFC*.DLL files instead (and a different manifest >>> file as well). >>> >>> Can anyone explain why the ActiveState release uses different MS Visual >>> C runtime files than the official Python Foundation's release of Python? > >> It doesn't. We use the same MSVC version as the python.org builds. >> >> Note that "MFC*.dll" files (IIRC, it has been a while) are >> redistributable DLLs used by the included PyWin32 extensions that have >> Python bindings for the Microsoft Foundation Classes GUI APIs. > > Yes, you are correct about the MFC*.dll's being shipped as part of the > Py2Win32 extensions. > > But I don't see the MSVCR90.DLL in your ZIP release. I do see a > MSVCR71.DLL. That is probably a bug in the ZIP package (the MSI is by far the primary package for Windows so gets more attention). I've started a bug for this: http://bugs.activestate.com/show_bug.cgi?id=86794 Thanks, Trent -- Trent Mick trentm at activestate.com http://trentm.com/blog/ From __peter__ at web.de Thu May 6 12:34:42 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 May 2010 18:34:42 +0200 Subject: convert Unicode filenames to good-looking ASCII References: Message-ID: coldpizza wrote: > Hello, > > I need to convert accented unicode chars in some audio files to > similarly-looking ascii chars. Looks like the following code seems to > work on windows: > > import os > import sys > import glob > > EXT = '*.*' > > lst_uni = glob.glob(unicode(EXT)) > > os.system('chcp 437') > lst_asci = glob.glob(EXT) > print sys.stdout.encoding > > for i in range(len(lst_asci)): > try: > os.rename(lst_uni[i], lst_asci[i]) > except Exception as e: > print e > > On windows it converts most of the accented chars from the latin1 > encoding. This does not work in Linux since it uses 'chcp'. > > The questions are (1) *why* does it work on windows, and (2) what is > the proper and portable way to convert unicode characters to similarly > looking plain ascii chars? > > That is how to properly do this kind of conversion? > ? > u > ? > e > ? > a > ? > a > ? > a > ? > a > ? > c > ? > e > ? > e > ? > e > > Is there any other way apart from creating my own char replacement > table? >>> from unicodedata import normalize >>> s = u"""? > u ... ? > e ... ? > a ... ? > a ... ? > a ... ? > a ... ? > c ... ? > e ... ? > e ... ? > e ... """ >>> from unicodedata import normalize >>> print normalize("NFD", s).encode("ascii", "ignore") u > u e > e a > a a > a a > a a > a c > c e > e e > e e > e From python at bdurham.com Thu May 6 12:53:52 2010 From: python at bdurham.com (python at bdurham.com) Date: Thu, 06 May 2010 12:53:52 -0400 Subject: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) In-Reply-To: <4BE2EF41.1090308@activestate.com> References: <60DEBADE-5A39-49F7-808D-5DD9A6D07FA1@activestate.com> <1273086295.15686.1373577021@webmail.messagingengine.com> <4BE1F91D.8050201@activestate.com> <1273105847.779.1373624397@webmail.messagingengine.com> <4BE2EF41.1090308@activestate.com> Message-ID: <1273164832.14062.1373752241@webmail.messagingengine.com> Hi Trent, > That is probably a bug in the ZIP package (the MSI is by far the primary package for Windows so gets more attention). > > I've started a bug for this: > http://bugs.activestate.com/show_bug.cgi?id=86794 Thank you, Malcolm ----- Original message ----- From: "Trent Mick" To: python at bdurham.com Cc: python-list at python.org Date: Thu, 06 May 2010 09:33:05 -0700 Subject: Re: ActiveState using different MS runtime files than official Python release? (was Re: Movable Python or ActivePython) On 10-05-05 5:30 PM, python at bdurham.com wrote: > Hi Trent, > > On 10-05-05 12:04 PM, python at bdurham.com wrote: >>> I just took a look at the ActiveStatre 2.6.5.12 release (zip file >>> version) and noticed that this file does not include the MSVCR90.DLL run >>> time file - it includes MFC*.DLL files instead (and a different manifest >>> file as well). >>> >>> Can anyone explain why the ActiveState release uses different MS Visual >>> C runtime files than the official Python Foundation's release of Python? > >> It doesn't. We use the same MSVC version as the python.org builds. >> >> Note that "MFC*.dll" files (IIRC, it has been a while) are >> redistributable DLLs used by the included PyWin32 extensions that have >> Python bindings for the Microsoft Foundation Classes GUI APIs. > > Yes, you are correct about the MFC*.dll's being shipped as part of the > Py2Win32 extensions. > > But I don't see the MSVCR90.DLL in your ZIP release. I do see a > MSVCR71.DLL. That is probably a bug in the ZIP package (the MSI is by far the primary package for Windows so gets more attention). I've started a bug for this: http://bugs.activestate.com/show_bug.cgi?id=86794 Thanks, Trent -- Trent Mick trentm at activestate.com http://trentm.com/blog/ From vriolk at gmail.com Thu May 6 12:55:16 2010 From: vriolk at gmail.com (coldpizza) Date: Thu, 6 May 2010 09:55:16 -0700 (PDT) Subject: convert Unicode filenames to good-looking ASCII References: Message-ID: Cool! Thanks to both Iliya and Peter! On May 6, 7:34?pm, Peter Otten <__pete... at web.de> wrote: > coldpizza wrote: > > Hello, > > > I need to convert accented unicode chars in some audio files to > > similarly-looking ascii chars. Looks like the following code seems to > > work on windows: > > > import os > > import sys > > import glob > > > EXT = '*.*' > > > lst_uni = glob.glob(unicode(EXT)) > > > os.system('chcp 437') > > lst_asci = glob.glob(EXT) > > print sys.stdout.encoding > > > for i in range(len(lst_asci)): > > ? ? try: > > ? ? ? ? os.rename(lst_uni[i], lst_asci[i]) > > ? ? except Exception as e: > > ? ? ? ? print e > > > On windows it converts most of the accented chars from the latin1 > > encoding. This does not work in Linux since it uses 'chcp'. > > > The questions are (1) *why* does it work on windows, and (2) what is > > the proper and portable way to convert unicode characters to similarly > > looking plain ascii chars? > > > That is how to properly do this kind of conversion? > > ?? ?> u > > ?? ?> e > > ?? ?> a > > ?? ?> a > > ?? ?> a > > ?? ?> a > > ?? ?> c > > ?? ?> e > > ?? ?> e > > ?? ?> e > > > Is there any other way apart from creating my own char replacement > > table? > >>> from unicodedata import normalize > >>> s = u"""? ?> u > > ... ?? ?> e > ... ?? ?> a > ... ?? ?> a > ... ?? ?> a > ... ?? ?> a > ... ?? ?> c > ... ?? ?> e > ... ?? ?> e > ... ?? ?> e > ... """>>> from unicodedata import normalize > >>> print normalize("NFD", s).encode("ascii", "ignore") > > u ?> u > ?e ?> e > ?a ?> a > ?a ?> a > ?a ?> a > ?a ?> a > ?c ?> c > ?e ?> e > ?e ?> e > ?e ?> e From stef.mientki at gmail.com Thu May 6 13:46:21 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 06 May 2010 19:46:21 +0200 Subject: how to make a piece of code lowercase, except strings / comment ? Message-ID: <4BE3006D.5070505@gmail.com> hello, I use Python with some simplifications and a few extensions, as a scripting language for non-programmers. One of the simplifications is that the language should be case-insensitive. This is done by making the code lowercase. But now the strings in the code are also converted to lowercase. Is there an easy way to make a piece of code lowercase, except all string items (single / double /triple quoted and comment) ? thanks, Stef Mientki -------------- next part -------------- An HTML attachment was scrubbed... URL: From rouslank at msn.com Thu May 6 14:35:25 2010 From: rouslank at msn.com (Rouslan Korneychuk) Date: Thu, 06 May 2010 14:35:25 -0400 Subject: new extension generator for C++ In-Reply-To: <4BE05D75.7030301@msn.com> References: <4BE05D75.7030301@msn.com> Message-ID: I have the code up at http://github.com/Rouslan/PyExpose now. Any comments are welcome. From claird271 at gmail.com Thu May 6 14:38:43 2010 From: claird271 at gmail.com (Cameron Laird) Date: Thu, 6 May 2010 11:38:43 -0700 (PDT) Subject: Python-URL! - weekly Python news and links (May 5) Message-ID: <11e042dd-e031-4f42-93d0-e81ec1616003@d39g2000yqa.googlegroups.com> [Authored by Gabriel Genellina.] QOTW: "Even on alt.haruspicy they cannot do much without a liver now and then..." - Peter Otten http://groups.google.com/group/comp.lang.python/msg/7852938d0b92bd7b Mixing bytes and unicode when writing data in Python 3.x: http://groups.google.com.ar/group/comp.lang.python/t/72614b3e49b2efe/ The best way to join two lists: a.extend(b) or a+=b? http://groups.google.com.ar/group/comp.lang.python/t/e56703a77aff9c67/ How to check who is still holding a reference to some object: http://groups.google.com.ar/group/comp.lang.python/t/ca9ca80d1f9b13da/ Using metaclasses to define class-level, inheritable computed attributes (properties): http://groups.google.com.ar/group/comp.lang.python/t/78394a73748c176f/ How to compute a/b (a float value) when both numbers are really big integers outside the float range? http://groups.google.com.ar/group/comp.lang.python/t/bdfe5287890e5776/ When creating millions of objects, disabling the garbage collector may enormously improve performance: http://groups.google.com.ar/group/comp.lang.python/t/4294c4c585e75a6d/ The right way to define __str__, __repr__ and __unicode__ in Python 2: http://groups.google.com.ar/group/comp.lang.python/t/e208e63e399ec52a/ rfind()'s 'start' argument is quite unintuitive: http://groups.google.com.ar/group/comp.lang.python/t/d03fbdcacfbf5794/ Generating nested code using a context manager: http://groups.google.com.ar/group/comp.lang.python/t/1200df3bd70afaa6/ How can open() succeed but os.path.realpath() fail with the same file name? (and later: how the Unix filesystems work) http://groups.google.com.ar/group/comp.lang.python/t/771f233167ac6d8e/ [Windows] It may be wise to download Visual Studio Express 2008 now, to still be able to recompile C extensions in the future: http://groups.google.com.ar/group/comp.lang.python/t/65e34924e7d42c90/ The available options for Web application development (and a comparison with PHP): http://groups.google.com.ar/group/comp.lang.python/t/7caab317a1d56d6e/ The dot in a.b is not an operator, and it's quite different from a +=b (started as a new syntax proposal, the .= operator): http://groups.google.com.ar/group/comp.lang.python/t/c6f9171c7659a999/ A proposal for engineering notation (like scientific format but exponent is always multiple of 3): http://groups.google.com.ar/group/comp.lang.python/t/421f611d0235b9f6/ How strong are statements like 'dict.keys() and dict.values() correspond to each other'? http://groups.google.com.ar/group/comp.lang.python/t/29915caa46255e21/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" site: http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date nullege is an interesting search Web application, with the intelligence to distinguish between Python code and comments. It provides what appear to be relevant results, and demands neither Java nor CSS be enabled: http://www.nullege.com Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python Enjoy the *Python Magazine*. http://pymag.phparch.com/ *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From artur.siekielski at gmail.com Thu May 6 15:34:53 2010 From: artur.siekielski at gmail.com (Artur Siekielski) Date: Thu, 6 May 2010 12:34:53 -0700 (PDT) Subject: List comprehension + lambdas - strange behaviour Message-ID: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Hello. I found this strange behaviour of lambdas, closures and list comprehensions: >>> funs = [lambda: x for x in range(5)] >>> [f() for f in funs] [4, 4, 4, 4, 4] Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The 'x' was bound to the final value of 'range(5)' expression for ALL defined functions. Can you explain this? Is this only counterintuitive example or an error in CPython? Regards, Artur From aahz at pythoncraft.com Thu May 6 15:37:12 2010 From: aahz at pythoncraft.com (Aahz) Date: 6 May 2010 12:37:12 -0700 Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> <2010050415342385304-tomfsessile@gmailcom> <4be132f1$0$20639$426a74cc@news.free.fr> Message-ID: In article <4be132f1$0$20639$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: > >The more bad code (mine or not) I have to maintain (or even just read >and understand), the more I pay attention to my own design and code >quality. Sometimes you only understand why something is bad, why it is >bad and how bad it is when you have to deal with it :( ...and sometimes it takes several months of living with bad code to really understand how to rewrite it. I'm currently rewriting a chunk of bad code that merges three datasources. If I had done the rewriting five months ago (when I first started feeling that I understood the codebase well enough to do the job), I would not be doing the complete rewrite that I'm currently doing, which would have led to suboptimal code lasting longer. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From theller at ctypes.org Thu May 6 15:58:15 2010 From: theller at ctypes.org (Thomas Heller) Date: Thu, 06 May 2010 21:58:15 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: Paul Moore schrieb: >>From a quick experiment, it seems that select.select with a timeout > doesn't react to a keyboard interrupt until the timeout expires. > Specifically, if I do > > s = socket.socket() > select.select([s], [], [], 30) > > and then press Ctrl-C, Python waits for the 30 seconds before raising > KeyboardInterrupt. > > Is this a known limitation on Windows? I see no mention of it in the > documentation. Assuming it is a known limitation, is there a way round > it? (I'm writing a tiny server using asyncore/asynchat, and the > delayed response to Ctrl-C is a mild nuisance. Solutions such as "use > twisted", while probably the sensible option in a wider context, don't > really apply here - I need something within the confines of the stdlib > if it's to be worth doing). If you look at the source code for time.sleep(), which CAN be interrupted by pressing Ctrl-C, you will find that it is carefully programmed to be interruptible (sp?). Which is not the case for select.select(), obviously. I guess the best way might be to split your select.select() call into several ones, using a smaller timeout like 1 second for example. BTW: I have experimented with calling the win32 function SetConsoleCtrlHandler() before the call to select.select(). This allows to install a python callback function which is called when Ctrl+C is pressed. However it seems this callback is not able to interrupt the select() call - but it can 'raise SystemExit()' which will terminate the script. Here is the code: """ import ctypes, select, socket @ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint) def HandlerRoutine(dwCtrlType): print "hoppla", dwCtrlType if dwCtrlType == 0: # CTRL+C raise SystemExit() return 1 s = socket.socket() print "Waiting." ctypes.windll.kernel32.SetConsoleCtrlHandler(HandlerRoutine, 1) select.select([s], [], [], 30) ctypes.windll.kernel32.SetConsoleCtrlHandler(HandlerRoutine, 0) print "Done." """ From aahz at pythoncraft.com Thu May 6 16:22:30 2010 From: aahz at pythoncraft.com (Aahz) Date: 6 May 2010 13:22:30 -0700 Subject: Picking a license (was Re: new extension generator for C++) References: <4BE05D75.7030301@msn.com> Message-ID: In article <4BE05D75.7030301 at msn.com>, Rouslan Korneychuk wrote: > >The only question I have now is what about licensing? Is that something >I need to worry about? Should I go with LGPL, MIT, or something else? Which license you use depends partly on your political philosophy. Unless you have an aggressively Stallmanesque attitude that people using your code should be forced to contribute back any changes, stick with MIT. (Generally speaking, the less encumbrance in your code, the more likely people are to use it, if your goal is to encourage users.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From python at rcn.com Thu May 6 16:25:23 2010 From: python at rcn.com (Raymond Hettinger) Date: Thu, 6 May 2010 13:25:23 -0700 (PDT) Subject: List comprehension + lambdas - strange behaviour References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Message-ID: On May 6, 9:34?pm, Artur Siekielski wrote: > Hello. > I found this strange behaviour of lambdas, closures and list > comprehensions: > > >>> funs = [lambda: x for x in range(5)] > >>> [f() for f in funs] > > [4, 4, 4, 4, 4] > > Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The > 'x' was bound to the final value of 'range(5)' expression for ALL > defined functions. Can you explain this? Is this only counterintuitive > example or an error in CPython? Try binding the value of x for each of the inner functions: >>> funs = [lambda x=x: x for x in range(5)] >>> [f() for f in funs] [0, 1, 2, 3, 4] Otherwise, the 'x' is just a global value and the lambdas look it up at when the function is invoked. Really, not surprising at all: >>> x = 10 >>> def f(): ... return x ... >>> x = 20 >>> f() 20 Raymond From emile at fenx.com Thu May 6 16:26:44 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 06 May 2010 13:26:44 -0700 Subject: List comprehension + lambdas - strange behaviour In-Reply-To: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Message-ID: On 5/6/2010 12:34 PM Artur Siekielski said... > Hello. > I found this strange behaviour of lambdas, closures and list > comprehensions: > >>>> funs = [lambda: x for x in range(5)] funs is now a list of lambda functions that return 'x' (whatever it currently is from whereever it's accessible when invoked) >>> [f() for f,x in zip(funs,range(5))] [0, 1, 2, 3, 4] >>> del x >>> [f() for f in funs] Traceback (most recent call last): File "", line 1, in ? File "", line 1, in NameError: global name 'x' is not defined >>> Emile From fabiofz at gmail.com Thu May 6 16:27:10 2010 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 6 May 2010 17:27:10 -0300 Subject: 2to3 issues with execfile on python 3.0 on files with encoding Message-ID: Right now, it seems that the default implementation of execfile in 2to3 is something as: exec(compile(open(file).read()+"\n", file, 'exec'), globals, locals) But it seems it won't deal with encodings properly... and also, in CPython just making an open without a close is OK, because of the reference counting, but in Jython it shouldn't be relied on (so, an explicit close should be done). The default replacement should be really providing a new execfile that gets the encoding in the first 2 lines and opens it with the proper encoding set (and properly closes the stream). So, below is what I think would be a correct replacement... Can it be made easier? Is there any utility to get the encoding already? Maybe an execfile should be created again in Python 3? (even if not in the __builtin__, but at least somewhere, as that seems really tricky to get right) Note that some 'with' statements could be used, but I chose not to because I wanted it to be at least syntax-compatible with earlier versions of python. def execfile(file): stream = open(file) try: encoding = None #Get encoding! for i in range(2): line = stream.readline() #Should not raise an exception even if there are no more contents #Must be a comment line if line.strip().startswith('#'): #Don't import re if there's no chance that there's an encoding in the line if 'coding' in line: import re p = re.search(r"coding[:=]\s*([-\w.]+)", line) if p: encoding = p.group(1) break finally: stream.close() if encoding is not None: stream = open(file, encoding=encoding) else: stream = open(file) try: contents = stream.read() finally: stream.close() exec(compile(contents+"\n", file, 'exec'), globals, locals) #execute the script Cheers, Fabio From benjamin at python.org Thu May 6 16:29:34 2010 From: benjamin at python.org (Benjamin Peterson) Date: Thu, 6 May 2010 20:29:34 +0000 (UTC) Subject: List comprehension + lambdas - strange behaviour References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Message-ID: Artur Siekielski gmail.com> writes: > > Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The > 'x' was bound to the final value of 'range(5)' expression for ALL > defined functions. Can you explain this? Is this only counterintuitive > example or an error in CPython? The former. Closures are rebound in a loop. From vincent at vincentdavis.net Thu May 6 17:21:00 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Thu, 6 May 2010 15:21:00 -0600 Subject: 2to3 as a unittest Message-ID: I have used 2to3 from the command line. is there a way to run it as a unittest. Actually I guess my question is; is there a built in utility for running py3 compatibility on source code as a unittest? *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From pietro.campe at gmail.com Thu May 6 18:26:15 2010 From: pietro.campe at gmail.com (Pietro Campesato) Date: Thu, 6 May 2010 15:26:15 -0700 (PDT) Subject: Where is python31.dll? References: <07da6657-1f4a-4e94-a5c3-9e02074ff761@q30g2000yqd.googlegroups.com> <78087231-bdd2-4ebc-91b0-ade65af18f9d@k19g2000yqm.googlegroups.com> Message-ID: <9c1adb05-3954-4711-ab1e-a10530c575b5@11g2000prw.googlegroups.com> Dave Angel wrote: > "visually"? Lots of possibilities there. And if you're not sure, you > need to get familiar with Windows quirks. > > IF you're using Explorer, there are a few ways you could miss a single > file out of thousands. > > Simplest is that the listing is not necessarily completely sorted. You > need to do a View->ArrangeIconsBy->Name > to really trust that they're sorted today. And you may have to repeat > that menu again next time you launch Explorer, or even next time you > look at some other directory. > > Next is that Explorer is initialized by Microsoft to mostly use the > worst possible defaults. One is to hide system and hidden files > . Another is to hide extensions of known types. Either of these could > make you overlook the file. > > HTH > DaveA You are right, I guess I should rely on programmatic ways to find specific files. Thank you. From rouslank at msn.com Thu May 6 18:53:50 2010 From: rouslank at msn.com (Rouslan Korneychuk) Date: Thu, 06 May 2010 18:53:50 -0400 Subject: Picking a license (was Re: new extension generator for C++) In-Reply-To: References: <4BE05D75.7030301@msn.com> Message-ID: <4BE3487E.9000500@msn.com> On 05/06/2010 04:22 PM, Aahz wrote: > In article<4BE05D75.7030301 at msn.com>, > Rouslan Korneychuk wrote: >> >> The only question I have now is what about licensing? Is that something >> I need to worry about? Should I go with LGPL, MIT, or something else? > > Which license you use depends partly on your political philosophy. > Unless you have an aggressively Stallmanesque attitude that people using > your code should be forced to contribute back any changes, stick with > MIT. (Generally speaking, the less encumbrance in your code, the more > likely people are to use it, if your goal is to encourage users.) MIT it is, then. From fabio at aptana.com Thu May 6 19:12:53 2010 From: fabio at aptana.com (Fabio Zadrozny) Date: Thu, 6 May 2010 20:12:53 -0300 Subject: Pydev 1.5.7 Released Message-ID: Hi All, Pydev 1.5.7 has been released Details on Pydev: http://pydev.org Details on its development: http://pydev.blogspot.com Release Highlights: ------------------------------- * **Uniquely identifying editors:** * Names are never duplicated * Special treatment for __init__ * Special treatment for django on views, models and tests * See: http://pydev.blogspot.com/2010/04/identifying-your-editors.html for details * **Debugger:** * **CRITICAL**: Fixed issue which could make the debugger skip breakpoints * Properly dealing with varibles that have '<' or '>' * Debugging file in python 3 with an encoding works * Double-clicking breakpoint opens file from the workspace instead of always forcing an external file * Added '* any file' option for file selection during a debug where the file is not found * **Performance improvements for dealing with really large files:** * Code folding marks won't be shown on *really large files* for performance reasons * Performance improvements in the code-analysis (much faster for *really large files*) * Outline tree is also faster * **Interpreter configuration:** * Only restoring the needed interpreter info (so, it's much faster to add a new interpreter) * Using an asynchronous progress monitor (which makes it even faster) * Interpreter location may not be duplicated (for cases where the same interpreter is used with a different config, virtualenv should be used) * Properly refreshing internal caches (which made a ctrl+2+kill or a restart of eclipse needed sometimes after configuring the interpreter) * socket added to forced builtins * **Python 3 grammar:** * Code completion and code-analysis work when dealing with keyword only parameters * Properly reporting syntax error instead of throwing a NumberFormatException on "1.0L" * **Editor and forcing tabs:** * Option to toggle forcing tabs added to the editor context menu * Fixed tabs issue which could change the global setting on force tabs * **Indentation:** * Added rule so that indentation stops at the level of the next line def or @ (to indent to add a decorator) * Auto indent strategy may indent based on next line if the previous is empty * **General:** * Django configuration supporting version 1.2 (contribution by Kenneth Belitzky) * Fixed encoding problem when pasting encoded text with indentation * asthelper.completions no longer created on current directory when project is removed * __all__ semantics correct when a tuple is defined (and not only when a list is defined) * Fixed issue in extract method (was not creating tuple on caller function with multiple returns) * Improved heuristic for assist assign (ctrl+1) * On search open files (ctrl+2+s), dialog is opened if nothing is entered and there's no editor selection * Fixed issue where ctrl+2 would not work on linux What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python, Jython and IronPython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer Aptana http://aptana.com/ Pydev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com From martin at v.loewis.de Thu May 6 19:38:13 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Fri, 07 May 2010 01:38:13 +0200 Subject: py3 tkinter acceps bytes. why? In-Reply-To: References: Message-ID: <4BE352E5.4060004@v.loewis.de> > If I don't want bytes to get passed to tkinter > I just have to raise an exception in AsObj, no? > Or is it even sufficient to just remove the bytes case? But why would you want that? There are commands which legitimately return bytes, e.g. the file and network io libraries of Tcl (not that you would usually want to use them in Python, but Tkinter is actually Tclinter, and should support all Tcl commands). Regards, Martin From pmaupin at gmail.com Thu May 6 19:38:22 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 6 May 2010 16:38:22 -0700 (PDT) Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> <2010050415342385304-tomfsessile@gmailcom> Message-ID: <746e8b47-bb35-47a1-9832-2babe0fec044@o8g2000yqo.googlegroups.com> On May 4, 5:34?pm, TomF wrote: > On 2010-05-04 07:11:08 -0700, alex23 said: > > (I also think there's value to be gained in studying _bad_ code, > > too...) > > True, although whether that's time well spent is another question. I don't know how this applies to reading other peoples' code, but recent research shows we learn more from success than failure: http://web.mit.edu/newsoffice/2009/successes-0729.html Regards, Pat From ben+python at benfinney.id.au Thu May 6 19:56:29 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 07 May 2010 09:56:29 +1000 Subject: Picking a license References: <4BE05D75.7030301@msn.com> Message-ID: <87k4rgfutu.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > In article <4BE05D75.7030301 at msn.com>, > Rouslan Korneychuk wrote: > > > >The only question I have now is what about licensing? Is that > >something I need to worry about? Should I go with LGPL, MIT, or > >something else? > > Which license you use depends partly on your political philosophy. Yes. Unless you place such a low value the freedom of your users that you'd allow proprietary derivatives of your work to remove the freedoms you've taken care to grant, then you should choose a copyleft license like the GPL. > Unless you have an aggressively Stallmanesque attitude that people > using your code should be forced to contribute back any changes Er, no. Anyone who thinks that a copyleft license ?forces? anyone to do anything is mistaken about copyright law, or the GPL, or both. The GPL only grants permissions, like any other free software license. -- \ ?If sharing a thing in no way diminishes it, it is not rightly | `\ owned if it is not shared.? ?Augustine of Hippo (354?430 CE) | _o__) | Ben Finney From martin at v.loewis.de Thu May 6 19:57:53 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Fri, 07 May 2010 01:57:53 +0200 Subject: 2to3 issues with execfile on python 3.0 on files with encoding In-Reply-To: References: Message-ID: > The default replacement should be really providing a new execfile that > gets the encoding in the first 2 lines and opens it with the proper > encoding set (and properly closes the stream). No. The default replacement should really open the file in binary mode. Regards, Martin From marduk at letterboxes.org Thu May 6 20:18:49 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Fri, 07 May 2010 09:18:49 +0900 Subject: Django as exemplary design In-Reply-To: <746e8b47-bb35-47a1-9832-2babe0fec044@o8g2000yqo.googlegroups.com> References: <2010050312243328275-tomfsessile@gmailcom> <2010050415342385304-tomfsessile@gmailcom> <746e8b47-bb35-47a1-9832-2babe0fec044@o8g2000yqo.googlegroups.com> Message-ID: <1273191529.196773.7.camel@paska> On Thu, 2010-05-06 at 16:38 -0700, Patrick Maupin wrote: > I don't know how this applies to reading other peoples' code, but > recent research shows we learn more from success than failure That's good to learn, because for years I have been intentionally failing in order to learn from it and become successful, and it hasn't really worked out for me :| -a From mehgcap at gmail.com Thu May 6 20:33:47 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 6 May 2010 20:33:47 -0400 Subject: does this exception mean something else? Message-ID: Hi all, I have a file, pasted below for what good it will do, which makes a couple conditional calls to a function called writeDefaults. However, when I manually trigger a condition that causes the function to be called, Python gives me a name error and says that my writeDefaults does not exist. I am sure that it does, as I copied the text from the call and pasted it into the text search of my editor, and it found the line that defines the function, so the text in the call is obviously correct. Sometimes, especially in a language like Javascript, one error can mean something else or point to a problem other than the one it claims to be about, so I wondered if the same thing could be happening here? The error is on line 55, just after the if statement that uses os.path.exists to ensure my ini file is really there. TIA! BTW, speech is just a file that will output a given message through an active screen reader; changing all calls to print will work just as well. import os, sys import helpers from configobj import ConfigObj #for reading ini files from string import Template #for interpreting the template strings in the ini file from speech import speak #set up a default dict of options to be used general={ "useSpeech":"True", "printMessages":"False", "roundTo":1, "defaultStartMode":1 } enableModes={ "resourceMonitor":"True", "weather":"True", "network":"True" } weatherOptions={ "location":"04938" } armOptions={ "primaryDrive":"c:", "secondaryDrive":"j:", "currentIsPrimary":"True", "CIsSecondary":"True", "ramInfo":"used", "driveInfo":"Used" } templates={ "sayCorePercentage":"$percent% for core $core", "sayProcessorAverage":"$percent% average load", "sayRamFree":"$percent% ram free ($free of $total remaining)", "sayRamUsed":"$percent% ram used ($used of $total used)", "sayDriveFree":"$percent% free on $drive ($free of $total remaining)", "sayDriveUsed":"$percent% used on $drive ($used of $total used)", "currentWeather":"$condition, $temp degrees. $wind. $humidity.", "forecast":"$day: $condition, $low to $high." } #first, load the ini file setting #so where is the ini? script_path/config.ini, of course! iniLoc=helpers.progdir+'\\config.ini' iniLoc=r'c:\arm\config.ni' #set up the ini object to read and write settings if(os.path.exists(iniLoc)): ini=ConfigObj(iniLoc) else: speak("The i n i file was not found. Now generating a default file.") writeDefaults() #end except #now get the settings general=ini["general"] printMessages=general["printMessages"] speech=general["useSpeech"] rnd=int(general["roundTo"]) mode=int(general["defaultStartMode"]) enable=ini['enableModes'] rmOn=enable["resourceMonitor"] weatherOn=enable["weather"] networkOn=enable["network"] aop=ini["armOptions"] #the options section drive1=aop["primaryDrive"] drive2=aop["secondaryDrive"] ramInfo=aop["ramInfo"] driveInfo=aop["driveInfo"] useCurrentDrive=aop["currentIsPrimary"] CIsSecondary=aop["CIsSecondary"] wop=ini["weatherOptions"] zip=str(wop["location"]) subs=ini["templates"] #short for substitute corePercent=Template(subs["sayCorePercentage"]) avg=Template(subs["sayProcessorAverage"]) sayRamFree=Template(subs["sayRamFree"]) sayRamUsed=Template(subs["sayRamUsed"]) sayDriveFree=Template(subs["sayDriveFree"]) sayDriveUsed=Template(subs["sayDriveUsed"]) currentWeather=Template(subs["currentWeather"]) forecast=Template(subs["forecast"]) def setOptions(): global ini try: ini.reload() except: speak("The i n i file was not found. Now generating a default file.") writeDefaults() #end except #now just a few settings that depend on the options #if useCurrentDrive is true, get that drive and set drive1 to it if(useCurrentDrive=="True"): #get current drive and assign it to primary currentDrive=os.path.splitdrive(sys.argv[0])[0] drive1=currentDrive #furthermore, if CIsSecondary is true, set that here, #since useCurrentDrive must be true for this one to take effect if(CIsSecondary=="True"): drive2="c:" #endif #endif #end def def writeDefaults(): global ini global iniLoc ini.filename=iniLoc ini["general"]=general ini["enableModes"]=enableModes ini["weatherOptions"]=weatherOptions ini["armOptions"]=armOptions ini["templates"]=templates #create the new file ini.write() #end def def speakSetOptions(): #just calls setOptions, but I use this separate def so I can speak a "reloaded" msg setOptions() speak("Settings reloaded.") #end def -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From python at mrabarnett.plus.com Thu May 6 20:37:26 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 May 2010 01:37:26 +0100 Subject: Django as exemplary design In-Reply-To: <1273191529.196773.7.camel@paska> References: <2010050312243328275-tomfsessile@gmailcom> <2010050415342385304-tomfsessile@gmailcom> <746e8b47-bb35-47a1-9832-2babe0fec044@o8g2000yqo.googlegroups.com> <1273191529.196773.7.camel@paska> Message-ID: <4BE360C6.3040503@mrabarnett.plus.com> Albert Hopkins wrote: > On Thu, 2010-05-06 at 16:38 -0700, Patrick Maupin wrote: >> I don't know how this applies to reading other peoples' code, but >> recent research shows we learn more from success than failure > > That's good to learn, because for years I have been intentionally > failing in order to learn from it and become successful, and it hasn't > really worked out for me :| > Failure just teaches you what you shouldn't do, not what you should... From clp2 at rebertia.com Thu May 6 20:50:22 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 17:50:22 -0700 Subject: does this exception mean something else? In-Reply-To: References: Message-ID: On Thu, May 6, 2010 at 5:33 PM, Alex Hall wrote: > Hi all, > I have a file, pasted below for what good it will do, which makes a > couple conditional calls to a function called writeDefaults. However, > when I manually trigger a condition that causes the function to be > called, Python gives me a name error and says that my writeDefaults > does not exist. I am sure that it does, as I copied the text from the > call and pasted it into the text search of my editor, and it found the > line that defines the function, so the text in the call is obviously > correct. You're calling the function before you've defined it; that doesn't work in Python. `def`s are executable statements, not declarations like in statically-typed languages. Move the "def writeDefaults():" and its body so it comes before the "#first, load the ini file setting" code. Cheers, Chris -- http://blog.rebertia.com From darwin at nowhere.com Thu May 6 21:03:55 2010 From: darwin at nowhere.com (Paul Hemans) Date: Fri, 7 May 2010 11:03:55 +1000 Subject: Extract a bordered, skewed rectangle from an image Message-ID: We have a scanned document on which a label has been attached. The label has been designed to have a border that makes it easy to determine the correct orientation and area of the label. The label portion of the scanned image needs to be extracted and deskewed as an image. The contents of the label will change, but the border won't I originally posted this onto RentAcoder as a project, but I am not getting a lot of responses. It might be that I requested it be done in Python, its too hard or I am too stingy. You can see the project here: http://www.RentACoder.com/RentACoder/misc/BidRequests/ShowBidRequest.asp?lngBidRequestId=1402446 It may not be feasible to do this project without the use of an image processing engine such as openCV. There is a routine in openCV called cvMinAreaRect2() that may do the job of returning a matching rectangle that is inclined. There is a Python to openCV interface available. So I think all the pieces are there, but this is out of my league as I have had very little experience with image processing. I am wondering whether there are any people here that have experience with openCV and Python. If so, could you either give me some pointers on how to approach this, or if you feel so inclined, bid on the project. There are 2 problems: How do I get openCV to ignore the contents of the label and just focus on the border? How to do this through Python into openCV? I am a newbie to Python, not strong in Maths and ignorant of the usage of openCV. Thanks. From python at mrabarnett.plus.com Thu May 6 21:03:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 May 2010 02:03:59 +0100 Subject: does this exception mean something else? In-Reply-To: References: Message-ID: <4BE366FF.3050509@mrabarnett.plus.com> Alex Hall wrote: > Hi all, > I have a file, pasted below for what good it will do, which makes a > couple conditional calls to a function called writeDefaults. However, > when I manually trigger a condition that causes the function to be > called, Python gives me a name error and says that my writeDefaults > does not exist. I am sure that it does, as I copied the text from the > call and pasted it into the text search of my editor, and it found the > line that defines the function, so the text in the call is obviously > correct. Sometimes, especially in a language like Javascript, one > error can mean something else or point to a problem other than the one > it claims to be about, so I wondered if the same thing could be > happening here? The error is on line 55, just after the if statement > that uses os.path.exists to ensure my ini file is really there. TIA! > BTW, speech is just a file that will output a given message through an > active screen reader; changing all calls to print will work just as > well. > You need to remember that 'def' and 'class' are _statements_, not declarations; they have the side-effect of adding a name to the current namespace. A Python script is run from the first line. If/when Python reaches line 55 the 'def' statement that defines the function 'writeDefaults' hasn't been run yet. BTW, you should avoid 'bare excepts' (an except clause that doesn't say which exception to catch) because they catch _every_ exception, even KeyboardInterrupt and NameError. You might also want to look at PEP 8: http://www.python.org/dev/peps/pep-0008/ which is the Style Guide for Python code. From trent at snakebite.org Thu May 6 21:20:02 2010 From: trent at snakebite.org (Trent Nelson) Date: Fri, 7 May 2010 09:20:02 +0800 Subject: Django as exemplary design In-Reply-To: <2010050312243328275-tomfsessile@gmailcom> References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <000001caed83$71a68e80$54f3ab80$@snakebite.org> > I'm interested in improving my python design by studying a large, > well-designed codebase. I'll tell you one of the best ways to improve your Python code: attend one of Raymond Hettinger's Code Clinic workshops at a Python conference and put some up of your work up on the projector for 20+ developers to rip apart, line by line ;-) You'll pick up more in 30 minutes than you ever thought possible. Trent. From contact at xavierho.com Thu May 6 21:33:16 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 7 May 2010 11:33:16 +1000 Subject: [Python-ideas] division oddness In-Reply-To: References: <4BE3623E.5000900@gmx.net> Message-ID: On Fri, May 7, 2010 at 11:13 AM, Chris Rebert wrote: > On Thu, May 6, 2010 at 5:43 PM, Mathias Panzenb?ck > wrote: > > Shouldn't by mathematical definition -x // y be the same as -(x // y)? > > I think this rather odd. Is there any deeper reason to this behaviour? I > > guess changing this will break a lot of code, but why does it behave like > > this? > > I would suppose it's what programmers have found more > useful/intuitive. Most programmers aren't number theorists. > Yeah, I was stinged by that before, too. I really don't find it intuitive at all - to keep the modulos remainer equal, you lose on negations and possibly integer equality. Ah well, too bad I didn't invent Python. =]. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu May 6 21:49:07 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 06 May 2010 21:49:07 -0400 Subject: List comprehension + lambdas - strange behaviour In-Reply-To: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Message-ID: On 5/6/2010 3:34 PM, Artur Siekielski wrote: > Hello. > I found this strange behaviour of lambdas, closures and list > comprehensions: > >>>> funs = [lambda: x for x in range(5)] >>>> [f() for f in funs] > [4, 4, 4, 4, 4] You succumbed to lambda hypnosis, a common malady ;-). The above will not work in 3.x, which does not leak comprehension iteration variables. It is equivalent to funs = [lambda: x for y in range(5)] del y # only for 2.x. y is already gone in 3.x x = 4 [f() for f in funs] Now, I am sure, you would expect what you got. and nearly equivalent to def f(): return x x=8 funs = [f for x in range(5)] [f() for f in funs] # [8,8,8,8,8] in 3.x Ditto Terry Jan Reedy From tjreedy at udel.edu Thu May 6 22:01:07 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 06 May 2010 22:01:07 -0400 Subject: does this exception mean something else? In-Reply-To: References: Message-ID: On 5/6/2010 8:33 PM, Alex Hall wrote: > Hi all, > I have a file, pasted below for what good it will do, which makes a > couple conditional calls to a function called writeDefaults. However, > when I manually trigger a condition that causes the function to be > called, Python gives me a name error and says that my writeDefaults > does not exist. It does not, when you try to call it, because the call occurs before you define it. Python code is executed top to bottom and function defines are executable statements. I suspect that you have used some other language that operates differently. ... > #first, load the ini file setting > #so where is the ini? script_path/config.ini, of course! > iniLoc=helpers.progdir+'\\config.ini' > iniLoc=r'c:\arm\config.ni' > #set up the ini object to read and write settings > if(os.path.exists(iniLoc)): > ini=ConfigObj(iniLoc) > else: > speak("The i n i file was not found. Now generating a default file.") > writeDefaults() > #end except writeDefaults is not yet defined ... > def writeDefaults(): > global ini > global iniLoc > ini.filename=iniLoc > ini["general"]=general > ini["enableModes"]=enableModes > ini["weatherOptions"]=weatherOptions > ini["armOptions"]=armOptions > ini["templates"]=templates > #create the new file > ini.write() > #end def Now it is. Move you def statements up closer to the top of the file. Terry Jan Reedy From mehgcap at gmail.com Thu May 6 22:01:15 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 6 May 2010 22:01:15 -0400 Subject: does this exception mean something else? In-Reply-To: <4BE366FF.3050509@mrabarnett.plus.com> References: <4BE366FF.3050509@mrabarnett.plus.com> Message-ID: Changing the order so the function is first did it. Thanks. That is what I get for working with Java all semester... On 5/6/10, MRAB wrote: > Alex Hall wrote: >> Hi all, >> I have a file, pasted below for what good it will do, which makes a >> couple conditional calls to a function called writeDefaults. However, >> when I manually trigger a condition that causes the function to be >> called, Python gives me a name error and says that my writeDefaults >> does not exist. I am sure that it does, as I copied the text from the >> call and pasted it into the text search of my editor, and it found the >> line that defines the function, so the text in the call is obviously >> correct. Sometimes, especially in a language like Javascript, one >> error can mean something else or point to a problem other than the one >> it claims to be about, so I wondered if the same thing could be >> happening here? The error is on line 55, just after the if statement >> that uses os.path.exists to ensure my ini file is really there. TIA! >> BTW, speech is just a file that will output a given message through an >> active screen reader; changing all calls to print will work just as >> well. >> > You need to remember that 'def' and 'class' are _statements_, not > declarations; they have the side-effect of adding a name to the current > namespace. > > A Python script is run from the first line. If/when Python reaches line > 55 the 'def' statement that defines the function 'writeDefaults' hasn't > been run yet. > > BTW, you should avoid 'bare excepts' (an except clause that doesn't say > which exception to catch) because they catch _every_ exception, even > KeyboardInterrupt and NameError. > > You might also want to look at PEP 8: > > http://www.python.org/dev/peps/pep-0008/ > > which is the Style Guide for Python code. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From cai.haibin at gmail.com Thu May 6 22:11:11 2010 From: cai.haibin at gmail.com (james_027) Date: Thu, 6 May 2010 19:11:11 -0700 (PDT) Subject: fast regex References: <87eihp2gf8.fsf@castleamber.com> Message-ID: On May 6, 11:33?pm, John Bokma wrote: > james_027 writes: > > I was working with regex on a very large text, really large but I have > > time constrained. Does python has any other regex library or string > > manipulation library that works really fast? > > Hard to answer without seeing your regex and requirements first. > Your question is like: I had a meal yesterday and it upset my > stomach. Can you suggest a different meal for today? > > -- > John Bokma ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? j3b > > Hacking & Hiking in Mexico - ?http://johnbokma.com/http://castleamber.com/- Perl & Python Development I am doing something like this for key, value in words_list.items(): compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) search = compile.sub(value, content) where the content is a large text about 500,000 characters and the word list is about 5,000 Any optimization for the code above? From clp2 at rebertia.com Thu May 6 22:14:41 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 19:14:41 -0700 Subject: [Python-ideas] division oddness In-Reply-To: References: <4BE3623E.5000900@gmx.net> Message-ID: On Thu, May 6, 2010 at 6:33 PM, Xavier Ho wrote: > On Fri, May 7, 2010 at 11:13 AM, Chris Rebert wrote: >> On Thu, May 6, 2010 at 5:43 PM, Mathias Panzenb?ck >> wrote: >> > Shouldn't by mathematical definition -x // y be the same as -(x // y)? >> > I think this rather odd. Is there any deeper reason to this behaviour? I >> > guess changing this will break a lot of code, but why does it behave >> > like >> > this? >> >> I would suppose it's what programmers have found more >> useful/intuitive. Most programmers aren't number theorists. > > Yeah, I was stinged by that before, too. I really don't find it intuitive at > all - to keep the modulos remainer equal, you lose on negations and possibly > integer equality. Ah well, too bad I didn't invent Python. =]. Personally, I find the following the most unintuitive: divmod(-11, 3) == (-4, 1) So, we overshoot -11 and then add 1 to go back to the right place? That violates my intuitive thought that abs((n//d)*d) <= abs(n) ought to hold. Cheers, Chris -- This is why we don't rely on intuition alone. http://blog.rebertia.com From cai.haibin at gmail.com Thu May 6 22:44:33 2010 From: cai.haibin at gmail.com (james_027) Date: Thu, 6 May 2010 19:44:33 -0700 (PDT) Subject: fast regex References: <87eihp2gf8.fsf@castleamber.com> Message-ID: <35bb1a8a-6f63-428e-8b96-1dcc41c4cb76@h20g2000prn.googlegroups.com> On May 6, 11:33?pm, John Bokma wrote: > james_027 writes: > > I was working with regex on a very large text, really large but I have > > time constrained. Does python has any other regex library or string > > manipulation library that works really fast? > > Hard to answer without seeing your regex and requirements first. > Your question is like: I had a meal yesterday and it upset my > stomach. Can you suggest a different meal for today? > > -- > John Bokma ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? j3b > > Hacking & Hiking in Mexico - ?http://johnbokma.com/http://castleamber.com/- Perl & Python Development I am doing something like this for key, value in words_list.items(): compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) search = compile.sub(value, content) where the content is a large text about 500,000 characters and the word list is about 5,000 Any optimization for the code above? From python.list at tim.thechases.com Thu May 6 22:47:18 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 06 May 2010 21:47:18 -0500 Subject: fast regex In-Reply-To: References: <87eihp2gf8.fsf@castleamber.com> Message-ID: <4BE37F36.3090701@tim.thechases.com> On 05/06/2010 09:11 PM, james_027 wrote: > for key, value in words_list.items(): > compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) > search = compile.sub(value, content) > > where the content is a large text about 500,000 characters and the > word list is about 5,000 You don't specify what you want to do with "search" vs. "content"...are you then reassigning content = search so that subsequent replacements happen? (your current version creates "search", only to discard it) My first thought would be to make use of re.sub()'s ability to take a function and do something like # a regexp that finds all possible # matches/words of interest r = re.compile(r'\b[a-zA-Z]+\b') def replacer(match): text = match.group(0) # assuming your dict.keys() are all lowercase: return word_list.get(text.lower(), text) results = r.sub(replacer, content) This does a replacement for every word in the input corpus (possibly with itself), but only takes one pass through the source text. If you wanted to get really fancy (and didn't butt up against the max size for a regexp), I suppose you could do something like r = re.compile(r'\b(%s)\b' % ( '|'.join(re.escape(s) for s in words_list.keys())), re.IGNORECASE) def replacer(match): return word_list[match.group(0).lower()] # assume lower keys results = r.sub(replacer, content) which would only do replacements on your keys rather than every "word" in your input, but I'd start with the first version before abusing programmatic regexp generation. -tkc From tomf.sessile at gmail.com Thu May 6 22:48:12 2010 From: tomf.sessile at gmail.com (TomF) Date: Thu, 6 May 2010 19:48:12 -0700 Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> Message-ID: <2010050619481239450-tomfsessile@gmailcom> On 2010-05-06 18:20:02 -0700, Trent Nelson said: >> I'm interested in improving my python design by studying a large, >> well-designed codebase. > > I'll tell you one of the best ways to improve your Python code: attend > one of Raymond Hettinger's Code Clinic workshops at a Python conference > and put some up of your work up on the projector for 20+ developers to > rip apart, line by line ;-) You'll pick up more in 30 minutes than you > ever thought possible. I don't doubt it. But I'm not really interested in line (micro) level code issues at the moment. Not that my code couldn't stand being improved, but I'm more interested in seeing how medium/large OO python systems are designed. If I could get this from a book I would, but I suspect I need to study real code. -Tom From apt.shansen at gmail.com Thu May 6 23:01:46 2010 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 6 May 2010 20:01:46 -0700 Subject: Picking a license In-Reply-To: <87k4rgfutu.fsf@benfinney.id.au> References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: On Thu, May 6, 2010 at 4:56 PM, Ben Finney > wrote: > aahz at pythoncraft.com (Aahz) writes: > > > In article <4BE05D75.7030301 at msn.com>, > > Rouslan Korneychuk wrote: > > > > > >The only question I have now is what about licensing? Is that > > >something I need to worry about? Should I go with LGPL, MIT, or > > >something else? > > > > Which license you use depends partly on your political philosophy. > > Yes. > > Unless you place such a low value the freedom of your users that you'd > allow proprietary derivatives of your work to remove the freedoms you've > taken care to grant, then you should choose a copyleft license like the > GPL. > > Unless you have an aggressively Stallmanesque attitude that people > > using your code should be forced to contribute back any changes > Meh, both of these responses are... tiring and full of political rhetoric instead of just giving the guy the facts and letting him pick what he wants and suits himself. So, to the OP: If you release the code under the GPL, then anyone is free to take and use it and do anything in the world they want with it. However, should they choose to distribute it to anyone else, then any changes they make to it must be provided to this "anyone else" according to the same terms. So, someone who takes your code and say, adds a module to it-- that module can't be in any license but the GPL (or rather, no license more restrictive then the GPL). Notably, this code can't end up in any closed or proprietary product. If you release the code under a "permissive" license, like MIT or the 3-clause BSD, you're basically giving everyone in the world free reign to do -- anything they want with it, without any sort of "but's". They just can't say you endorsed it generally, and can't sue you for it, and they can't claim it was theirs (though they aren't required to admit it was yours, either). Someone can take it, rename it, and re-release it as a closed-source program if they want. Or, someone could incorporate it into any number of projects that are open source and not GPL-- whereas GPL code can't ever be incorporated into non-GPL code, without the whole codebase becoming GPL. Notably, Python has a permissive license, albeit one which is very, very wordy. What you decide on is up to you. Me, I'm very strongly in the MIT camp. I consider what I may release as a sort of donation, and don't expect anything of anyone-- and don't even mind if someone makes money off of it without being a good sport. "Freedom" and software have nothing to do with anything to me. I do open source because I think its an excellent way to get technically excellent products. The decision of which camp you find yourself is up to you. :) (Then there's others, like Artistic, the Apache, and on and on) --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From cai.haibin at gmail.com Thu May 6 23:18:01 2010 From: cai.haibin at gmail.com (james_027) Date: Thu, 6 May 2010 20:18:01 -0700 (PDT) Subject: fast regex References: <87eihp2gf8.fsf@castleamber.com> Message-ID: On May 6, 11:33?pm, John Bokma wrote: > james_027 writes: > > I was working with regex on a very large text, really large but I have > > time constrained. Does python has any other regex library or string > > manipulation library that works really fast? > > Hard to answer without seeing your regex and requirements first. > Your question is like: I had a meal yesterday and it upset my > stomach. Can you suggest a different meal for today? > > -- > John Bokma ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? j3b > > Hacking & Hiking in Mexico - ?http://johnbokma.com/http://castleamber.com/- Perl & Python Development I am doing something like this for key, value in words_list.items(): compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) search = compile.sub(value, content) where the content is a large text about 500,000 characters and the word list is about 5,000 Any optimization for the code above? From ncohen at ucsd.edu Thu May 6 23:50:01 2010 From: ncohen at ucsd.edu (Ben Cohen) Date: Thu, 6 May 2010 21:50:01 -0600 Subject: idiomatic way to collect and report multiple exceptions? Message-ID: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> Is there a pythonic way to collect and display multiple exceptions at the same time? For example let's say you're trying to validate the elements of a list and you'd like to validate as many of the elements as possible in one run and still report exception's raised while validating a failed element. eg -- I'd like to do something like this: errors = [] for item in data: try: process(item) except ValidationError as e: errors.append(e) raise MultipleValidationErrors(*errors) where if the raised MultipleValidationErrors exception goes uncaught the interpreter will print a nice traceback that includes the tracebacks of each raised ValidationError. But I don't know how MultipleValidationErrors should be written ... I'm targeting python 2.6 at the moment -- googling around for advice I see some pep's relating to exception handling changes in python3 that might be relevant but I've ended up more confused. Thanks in advance, Ben From crebert at ucsd.edu Fri May 7 00:56:10 2010 From: crebert at ucsd.edu (Chris Rebert) Date: Thu, 6 May 2010 21:56:10 -0700 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> Message-ID: On Thu, May 6, 2010 at 8:50 PM, Ben Cohen wrote: > Is there a pythonic way to collect and display multiple exceptions at the same time? > > For example let's say you're trying to validate the elements of a list and you'd like to validate as many of the elements as possible in one run and still report exception's raised while validating a failed element. > > eg -- I'd like to do something like this: > > errors = [] > for item in data: > ? ? ? ?try: > ? ? ? ? ? ? ? ?process(item) > ? ? ? ?except ValidationError as e: > ? ? ? ? ? ? ? ?errors.append(e) > raise MultipleValidationErrors(*errors) > > where if the raised MultipleValidationErrors exception goes uncaught the interpreter will print a nice traceback that includes the tracebacks of each raised ValidationError. ?But I don't know how MultipleValidationErrors should be written ... import sys, traceback def _traceback_for(exc_info): return ''.join(traceback.format_exception(*exc_info)) # StandardError can obviously be replaced with # whatever exception superclass you want. class MultipleValidationErrors(StandardError): def __init__(self, errors=None): self.errors = errors or [] def __str__(self): tracebacks = "\n\n".join(_traceback_for(exc_info) for exc_info in \ self.errors) parts=("See the following exception tracebacks:", "="*78, tracebacks) msg = '\n'.join(parts) return msg def capture_current_exception(self): self.errors.append(sys.exc_info()) def do_raise(self): """Raises itself if it contains any errors""" if self.errors: raise self #Example usage: multiple_err = MultipleValidationErrors() for c in "hello": try: int(c) # obviously fails except ValueError: # whatever error type you care about multiple_err.capture_current_exception() multiple_err.do_raise() Output from example: Traceback (most recent call last): File "tmp.py", line 35, in multiple_err.do_raise() File "tmp.py", line 25, in do_raise raise self __main__.MultipleValidationErrors: See the following exception tracebacks: ============================================================================== Traceback (most recent call last): File "tmp.py", line 32, in int(c) # obviously fails ValueError: invalid literal for int() with base 10: 'h' Traceback (most recent call last): File "tmp.py", line 32, in int(c) # obviously fails ValueError: invalid literal for int() with base 10: 'e' Traceback (most recent call last): File "tmp.py", line 32, in int(c) # obviously fails ValueError: invalid literal for int() with base 10: 'l' Traceback (most recent call last): File "tmp.py", line 32, in int(c) # obviously fails ValueError: invalid literal for int() with base 10: 'l' Traceback (most recent call last): File "tmp.py", line 32, in int(c) # obviously fails ValueError: invalid literal for int() with base 10: 'o' Cheers, Chris -- Go Tritons! http://blog.rebertia.com From tjreedy at udel.edu Fri May 7 00:57:52 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 May 2010 00:57:52 -0400 Subject: [Python-ideas] division oddness In-Reply-To: References: <4BE3623E.5000900@gmx.net> Message-ID: > On Thu, May 6, 2010 at 5:43 PM, Mathias Panzenb?ck >> Shouldn't by mathematical definition -x // y be the same as -(x// y)? Tradeoffs, tradeoffs. Most everyone agrees on this rule for the relation between // and %: x == y*(x//y) + x%y If // is defined as above, then, for instance, x%2 has 3 possible values (-1, 0, 1) rather than just 2. Not so good. Since y is usually positive in practical applications (what does dividing by a negative number mean?), having the sign of x%y governed by the sign of y rather than the sign of x seems advantageous. Judging from the chart at http://en.wikipedia.org/wiki/Modulo_operation languages are pretty evenly split on which definitions to use. Terry Jan Reedy From tjreedy at udel.edu Fri May 7 01:06:07 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 May 2010 01:06:07 -0400 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> Message-ID: On 5/6/2010 11:50 PM, Ben Cohen wrote: > Is there a pythonic way to collect and display multiple exceptions at > the same time? > > For example let's say you're trying to validate the elements of a > list and you'd like to validate as many of the elements as possible > in one run and still report exception's raised while validating a > failed element. > > eg -- I'd like to do something like this: > > errors = [] for item in data: try: process(item) except ValidationError as e: errors.append(e) I believe each exception replaces the traceback message. So I would collect tracebacks rather than exceptions. Try the traceback module. Terry Jan Reedy From timr at probo.com Fri May 7 01:24:28 2010 From: timr at probo.com (Tim Roberts) Date: Thu, 06 May 2010 22:24:28 -0700 Subject: Classes: nested functions vs. private methodes References: Message-ID: <9m87u59fmhjp8hhmm9anbhggllhuudl6nk@4ax.com> Richard Lamboj wrote: > >Thank you for the nice sample, but what is with multiple inheritance in your >sample? I mean the super call. Why not _MyClass.blah(self, arg). Because then I have to remember to change the name if I should happen to change the base class, or copy this code into another class. >What is when >i have more then one Class from which i inherite and in both are a methode >called "blah", but i just want to call one of them and not both, becouse they >do different things? Then you'd need use the full class name, of course. The search order is well-defined, so super() is still meaningful. However, in that case, you are rapidly getting into a design that is too complicated to understand at a glance. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ron.eggler at gmail.com Fri May 7 01:27:28 2010 From: ron.eggler at gmail.com (cerr) Date: Thu, 6 May 2010 22:27:28 -0700 (PDT) Subject: Broken pipe Message-ID: Hi There, I'm very new to Python and i wanna write a script that sends a certain string to a server. The code I came up with looks like this: #!/usr/bin/python import sys import string from socket import * usage="USAGE: "+sys.argv[0]+" "; if len(sys.argv) != 3: print usage; sys.exit(0); host = sys.argv[1]; port = sys.argv[2]; buf = 1024; addr = (host,port); sock = socket(AF_INET, SOCK_STREAM); data = string.join("NovaxTest",'\n'); sock.send(data); sock.close(); and I'm calling this script like that: "./TestService.py 127.0.0.1 1514" but when I call it I get following back: sending data to 127.0.0.1:1514 data: NovaxTest Traceback (most recent call last): File "./TestService.py", line 18, in sock.send(data); socket.error: [Errno 32] Broken pipe I understand that UNIX sends an Errno32 if the server closes the connection. But if i telnet to localhost on 1514 and send NovaxTest by hand everything works just fine. So what might be wrong here? Thank you very much! Ron From contact at xavierho.com Fri May 7 01:32:18 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 7 May 2010 15:32:18 +1000 Subject: [Python-ideas] division oddness In-Reply-To: References: <4BE3623E.5000900@gmx.net> Message-ID: On Fri, May 7, 2010 at 12:14 PM, Chris Rebert wrote: > Personally, I find the following the most unintuitive: > divmod(-11, 3) == (-4, 1) > > So, we overshoot -11 and then add 1 to go back to the right place? > That violates my intuitive thought that abs((n//d)*d) <= abs(n) ought to > hold. > Haha, really? *gives it a try* Oh wow... Yeah. I don't like that either. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Fri May 7 01:37:14 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 22:37:14 -0700 Subject: Broken pipe In-Reply-To: References: Message-ID: On Thu, May 6, 2010 at 10:27 PM, cerr wrote: > Hi There, > > I'm very new to Python and i wanna write a script that sends a certain > string to a server. The code I came up with looks like this: > #!/usr/bin/python > > import sys > import string > > from socket import * > usage="USAGE: "+sys.argv[0]+" "; > if len(sys.argv) != 3: > ? ? ? ? ? ? ?print usage; > ? ? ? ? ? ? ?sys.exit(0); > host = sys.argv[1]; > port = sys.argv[2]; > buf = 1024; > addr = (host,port); > sock = socket(AF_INET, SOCK_STREAM); > data = string.join("NovaxTest",'\n'); > sock.send(data); > sock.close(); > and I'm calling this script like that: "./TestService.py 127.0.0.1 > 1514" but when I call it I get following back: > sending data to 127.0.0.1:1514 > data: NovaxTest > Traceback (most recent call last): > ?File "./TestService.py", line 18, in > ? ?sock.send(data); > socket.error: [Errno 32] Broken pipe > I understand that UNIX sends an Errno32 if the server closes the > connection. But if i telnet to localhost on 1514 and send NovaxTest by > hand everything works just fine. So what might be wrong here? You never called sock.connect(addr). Your code doesn't even use `addr` at all. Also, please don't use semicolons in your code. It's bad style. Cheers, Chris -- http://blog.rebertia.com From ron.eggler at gmail.com Fri May 7 02:11:22 2010 From: ron.eggler at gmail.com (Ron Eggler) Date: Thu, 6 May 2010 23:11:22 -0700 Subject: Broken pipe In-Reply-To: References: Message-ID: <201005062311.23076.ron.eggler@gmail.com> On May 6, 2010 10:37:14 pm Chris Rebert wrote: > On Thu, May 6, 2010 at 10:27 PM, cerr wrote: > > Hi There, > > > > I'm very new to Python and i wanna write a script that sends a certain > > string to a server. The code I came up with looks like this: > > #!/usr/bin/python > > > > import sys > > import string > > > > from socket import * > > usage="USAGE: "+sys.argv[0]+" "; > > if len(sys.argv) != 3: > > print usage; > > sys.exit(0); > > host = sys.argv[1]; > > port = sys.argv[2]; > > buf = 1024; > > addr = (host,port); > > sock = socket(AF_INET, SOCK_STREAM); > > data = string.join("NovaxTest",'\n'); > > sock.send(data); > > sock.close(); > > and I'm calling this script like that: "./TestService.py 127.0.0.1 > > 1514" but when I call it I get following back: > > sending data to 127.0.0.1:1514 > > data: NovaxTest > > Traceback (most recent call last): > > File "./TestService.py", line 18, in > > sock.send(data); > > socket.error: [Errno 32] Broken pipe > > I understand that UNIX sends an Errno32 if the server closes the > > connection. But if i telnet to localhost on 1514 and send NovaxTest by > > hand everything works just fine. So what might be wrong here? > > You never called sock.connect(addr). Your code doesn't even use `addr` at > all. Oh, yeah, hOOps :$ > Also, please don't use semicolons in your code. It's bad style. Is it, eh? Well, I'm from C, C++ and for me it just belongs there..:) but i'll try to change my habits... :) Hm weird now I get something like: Traceback (most recent call last): File "./TestService.py", line 14, in sock.connect((host,port)) File "", line 1, in connect TypeError: an integer is required with this code: #!/usr/bin/python import sys import string from socket import * usage="USAGE: "+sys.argv[0]+" " if len(sys.argv) != 3: print usage sys.exit(0) host = sys.argv[1] port = sys.argv[2] sock = socket(AF_INET, SOCK_STREAM) sock.connect((host,port)) data = string.join("NovaxTest",'\n') sock.send(data) sock.close() What does that mean? :( Thanks, Ron From clp2 at rebertia.com Fri May 7 02:13:56 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 6 May 2010 23:13:56 -0700 Subject: Broken pipe In-Reply-To: <201005062311.23076.ron.eggler@gmail.com> References: <201005062311.23076.ron.eggler@gmail.com> Message-ID: On Thu, May 6, 2010 at 11:11 PM, Ron Eggler wrote: > On May 6, 2010 10:37:14 pm Chris Rebert wrote: >> On Thu, May 6, 2010 at 10:27 PM, cerr wrote: >> > Hi There, >> > >> > I'm very new to Python and i wanna write a script that sends a certain >> > string to a server. The code I came up with looks like this: >> > #!/usr/bin/python >> > >> > import sys >> > import string >> > >> > from socket import * >> > usage="USAGE: "+sys.argv[0]+" "; >> > if len(sys.argv) != 3: >> > ? ? ? ? ? ? ?print usage; >> > ? ? ? ? ? ? ?sys.exit(0); >> > host = sys.argv[1]; >> > port = sys.argv[2]; >> > buf = 1024; >> > addr = (host,port); >> > sock = socket(AF_INET, SOCK_STREAM); >> > data = string.join("NovaxTest",'\n'); >> > sock.send(data); >> > sock.close(); >> > and I'm calling this script like that: "./TestService.py 127.0.0.1 >> > 1514" but when I call it I get following back: >> > sending data to 127.0.0.1:1514 >> > data: NovaxTest >> > Traceback (most recent call last): >> > ?File "./TestService.py", line 18, in >> > ? ?sock.send(data); >> > socket.error: [Errno 32] Broken pipe >> > I understand that UNIX sends an Errno32 if the server closes the >> > connection. But if i telnet to localhost on 1514 and send NovaxTest by >> > hand everything works just fine. So what might be wrong here? >> >> You never called sock.connect(addr). Your code doesn't even use `addr` at >> all. > Oh, yeah, hOOps :$ > Hm weird now I get something like: > Traceback (most recent call last): > ?File "./TestService.py", line 14, in > ? ?sock.connect((host,port)) > ?File "", line 1, in connect > TypeError: an integer is required > What does that mean? :( You never converted `port` to an int, it's still a string. You might consider reading the socket module docs: http://docs.python.org/library/socket.html Cheers, Chris -- http://blog.rebertia.com From kurianmthayil at gmail.com Fri May 7 03:21:25 2010 From: kurianmthayil at gmail.com (Kurian Thayil) Date: Fri, 7 May 2010 12:51:25 +0530 Subject: Python - MySQL fetching values In-Reply-To: References: Message-ID: On Thu, May 6, 2010 at 2:42 PM, Chris Rebert wrote: > On Thu, May 6, 2010 at 1:47 AM, Kurian Thayil > wrote: > > > the expected output is 05:35:05. > > > > Now, here is code snippet, > > > > cursor1=getconnect1.cursor() > > getrows=cursor1.execute("""SELECT > > TIME(DATE_ADD(info_last_calltime, INTERVAL %s MINUTE)) FROM rem_call_info > > WHERE info_ctrlid=%s""", (retryinterval,controlid1,)) > > rawstatus20result=cursor1.fetchone() > > print "Raw result is",rawstatus20result > > status20result=rawstatus20result[0] > > print "The query result for Status > > 20:",status20result,";Time now is",timeformat > > > > The output is: > > > > Raw result is (datetime.timedelta(0, 20105),) > > The query result for Status 20: 5:35:05 ;Time now is 05:22:00 > > Match not found. > > New call to be made > > Getting next value if any... > > > > If you look closer, the time fetched by python module was 5:35:05 instead > of > > 05:35:05. How can I get this time format? Thanks in advance. > > You're getting back a time delta (i.e. quantity/duration of time, e.g. > "3 hours") rather than an actual time (i.e. temporal coordinates for a > particular instant of time, e.g. "5:15PM and 2 seconds"), and > timedelta defines its stringification differently, hence your issue. I > would guess that getting back a timedelta instead of a time is some > quirk of MySQLdb; haven't used it though, so I'm just guessing. > > Anyway, you can work around this by converting the timedelta object to > a time object yourself: > #Untested Code! > from datetime import time > minutes, seconds = divmod(status20result.seconds, 60) > hours, minutes = divmod(minutes, 60) > time_result = time(hours, minutes, seconds, status20result.microseconds) > print "The query result for Status 20:",time_result,";Time now > is",timeformat > > Cheers, > Chris > -- > http://blog.rebertia.com > That worked Chris. Thank you. Regards, Kurian Thayil. -------------- next part -------------- An HTML attachment was scrubbed... URL: From t.lehmann at rtsgroup.net Fri May 7 03:54:52 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Fri, 7 May 2010 00:54:52 -0700 (PDT) Subject: No module named server Message-ID: <16aa8195-bbd6-4b22-a9bf-35fd63edda7d@e1g2000yqe.googlegroups.com> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Script: from http.server import HTTPServer, CGIHTTPRequestHandler Result: Traceback (most recent call last): File "http.py", line 1, in from http.server import HTTPServer, CGIHTTPRequestHandler File "F:\Checkouts\projects\python\http.py", line 1, in from http.server import HTTPServer, CGIHTTPRequestHandler ImportError: No module named server From jarausch at igpm.rwth-aachen.de Fri May 7 04:00:46 2010 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Fri, 07 May 2010 10:00:46 +0200 Subject: fast regex In-Reply-To: References: Message-ID: <84hvleFm3U1@mid.dfncis.de> On 05/06/10 16:52, james_027 wrote: > hi, > > I was working with regex on a very large text, really large but I have > time constrained. Does python has any other regex library or string > manipulation library that works really fast? Have a look at http://www.egenix.com/products/python/mxBase/mxTextTools/doc/ it claims to be fast, Helmut. From t.lehmann at rtsgroup.net Fri May 7 04:02:48 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Fri, 7 May 2010 01:02:48 -0700 (PDT) Subject: No module named server References: <16aa8195-bbd6-4b22-a9bf-35fd63edda7d@e1g2000yqe.googlegroups.com> Message-ID: <32529ed8-5052-40f1-ba4e-339ba5c22d49@o11g2000yqj.googlegroups.com> > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit Also after installing Python 3.1.2 the problem is still there. From albrecht.andi at googlemail.com Fri May 7 04:05:11 2010 From: albrecht.andi at googlemail.com (Andi Albrecht) Date: Fri, 7 May 2010 08:05:11 +0000 (UTC) Subject: No module named server References: <16aa8195-bbd6-4b22-a9bf-35fd63edda7d@e1g2000yqe.googlegroups.com> Message-ID: Thomas Lehmann schrieb: > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit > (Intel)] on win32 > > Script: > from http.server import HTTPServer, CGIHTTPRequestHandler > > Result: > Traceback (most recent call last): > File "http.py", line 1, in > from http.server import HTTPServer, CGIHTTPRequestHandler > File "F:\Checkouts\projects\python\http.py", line 1, in > from http.server import HTTPServer, CGIHTTPRequestHandler > ImportError: No module named server You should rename http.py since it collides with the "http" module you're trying to import the server and request handler classes from. Andi From t.lehmann at rtsgroup.net Fri May 7 04:24:13 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Fri, 7 May 2010 01:24:13 -0700 (PDT) Subject: No module named server References: <16aa8195-bbd6-4b22-a9bf-35fd63edda7d@e1g2000yqe.googlegroups.com> <32529ed8-5052-40f1-ba4e-339ba5c22d49@o11g2000yqj.googlegroups.com> Message-ID: <6f98f802-b0db-44d6-90bd-71eee6605a40@37g2000yqm.googlegroups.com> On 7 Mai, 10:02, Thomas Lehmann wrote: > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit > > Also after installing Python 3.1.2 the problem is still there. I know the problem. Reading a book about a simple cgi web server the descriptions says to use httpd.py as name for the file and I forgot the 'd'. This leads to the wrong behaviour. From p.f.moore at gmail.com Fri May 7 04:48:01 2010 From: p.f.moore at gmail.com (Paul Moore) Date: Fri, 7 May 2010 01:48:01 -0700 (PDT) Subject: Windows - select.select, timeout and KeyboardInterrupt References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: On 6 May, 20:58, Thomas Heller wrote: > If you look at the source code for time.sleep(), which CAN be interrupted > by pressing Ctrl-C, you will find that it is carefully programmed to be > interruptible (sp?). ?Which is not the case for select.select(), obviously. Thanks - given this, would it be worth me submitting a documentation patch noting that select.select is not interruptible on Windows? > I guess the best way might be to split your select.select() call into several > ones, using a smaller timeout like 1 second for example. Yes, that's probably good enough for my case. > BTW: I have experimented with calling the win32 function SetConsoleCtrlHandler() > before the call to select.select(). ?This allows to install a python callback > function which is called when Ctrl+C is pressed. ?However it seems this callback > is not able to interrupt the select() call - but it can 'raise SystemExit()' > which will terminate the script. ?Here is the code: That's useful - I doubt I'll need it for this case, but I'll keep it in mind for the future. Thanks for the help. Paul. From nospam at news.eternal-september.org Fri May 7 06:24:27 2010 From: nospam at news.eternal-september.org (balzer) Date: Fri, 7 May 2010 13:24:27 +0300 Subject: ActivePython - how to configure portable framework? Message-ID: I downloaded ActivePython-2.6.5.12-win32-x86.zip, it contains two folders and 3 files: SystemFolder INSTALLDIR sh2.py install.bat _install.py Anyone know how to configure this Python environment as "portable application" to work with it without installation, to set a fully-functional Python environment that executes entirely from hard drive (or USB stick) without leaving no registry entries, no mess with windows system files, etc on machine it's run on. I created folder "Python", what files I should copy inside? thanks. From nagarazang at yahoo.co.in Fri May 7 06:51:29 2010 From: nagarazang at yahoo.co.in (Nathas) Date: Fri, 07 May 2010 10:51:29 -0000 Subject: Openings at Aspire Systems, Chennai. (Product Dev. Company) Message-ID: Hi All, Please find below the openings at Aspire Systems, Chennai (www.aspiresys.com) 1. Testing - Selenium, TestComplete, RFT, Manual - SSE and Engineers - 2 + years 2. Java, Swings - Project Leader Position ? 5+ years 3. Java, J2EE ? Enngineer, SSE, Tech Arch ? 2+ Yrs 4. .NET - SSE and Tech Architect ? 3+ years 5. Silverlight, Sharepoint - Engineer, SSE ? 2+ yrs 6. PHP, Python, RoR, Great Plains - Engineer, SSE ? 2+ yrs 7. UI Developer - 2+ years 8. Sales - Sr. Exe. ? 3+ yrs Kindly circulate with your friends and do forward your / your friend's resume to the below email id. nagarajan.ganesan at aspiresys.com Thanks, Nagarajan. From richard.lamboj at bilcom.at Fri May 7 06:55:48 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Fri, 7 May 2010 12:55:48 +0200 Subject: importing modules Message-ID: <201005071255.48902.richard.lamboj@bilcom.at> Hello, I have a question about importing python modules. I have modul package, with submodules. So how can a submodul access a modul that is on level upper? Is there something like "import ../../blah"? I don't mean something like this: "import bla.blub.moep" Kind Regards, Richi From mehgcap at gmail.com Fri May 7 07:02:41 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 7 May 2010 07:02:41 -0400 Subject: importing modules In-Reply-To: <201005071255.48902.richard.lamboj@bilcom.at> References: <201005071255.48902.richard.lamboj@bilcom.at> Message-ID: I have a main folder. Inside that I have a "modes" package (subfolder holding __init__.py) as well as a "misc" package. When modes has to import helpers.py from misc, I use this: from .misc import helpers The period makes Python look up one level for misc, then go into it to find helpers. On 5/7/10, Richard Lamboj wrote: > > Hello, > > I have a question about importing python modules. > > I have modul package, with submodules. So how can a submodul access a modul > that is on level upper? > > Is there something like "import ../../blah"? I don't mean something like > this: "import bla.blub.moep" > > Kind Regards, > > Richi > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From albrecht.andi at googlemail.com Fri May 7 07:19:03 2010 From: albrecht.andi at googlemail.com (Andi Albrecht) Date: Fri, 7 May 2010 11:19:03 +0000 (UTC) Subject: importing modules References: Message-ID: Richard Lamboj schrieb: > > Hello, > > I have a question about importing python modules. > > I have modul package, with submodules. So how can a submodul access a modul > that is on level upper? > > Is there something like "import ../../blah"? I don't mean something like > this: "import bla.blub.moep" > > Kind Regards, > > Richi Hi Richi, starting with 2.5 Python allows relative imports, e.g. import ..blah Andi From nick at granger-brown.net Fri May 7 07:48:15 2010 From: nick at granger-brown.net (NickGB) Date: Fri, 7 May 2010 04:48:15 -0700 (PDT) Subject: listing exported functions in a DLL Message-ID: <9fc62d78-3163-43f7-b815-3b5b6d370681@l31g2000yqm.googlegroups.com> is there a way using ctypes to list the exported functions of a DLL? This is what I was hoping to do... from ctypes import * myDLL = windll.some_dll # what is this method? does it exist? list_of_exported_functions = myDLL.list_exported_functions() From jeanmichel at sequans.com Fri May 7 07:50:15 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 07 May 2010 13:50:15 +0200 Subject: importing modules In-Reply-To: <201005071255.48902.richard.lamboj@bilcom.at> References: <201005071255.48902.richard.lamboj@bilcom.at> Message-ID: <4BE3FE77.10005@sequans.com> Richard Lamboj wrote: > Hello, > > I have a question about importing python modules. > > I have modul package, with submodules. So how can a submodul access a modul > that is on level upper? > > Is there something like "import ../../blah"? I don't mean something like > this: "import bla.blub.moep" > > Kind Regards, > > Richi > I would advise to use absolute imports whenever possible (always ?). If 'pkg' is your package, then module sub1 should import sub2 that way: file pkg/sub1.py: import pkg.sub2 see http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports " the python-dev community chose absolute imports as the default because they're the more common use case and because absolute imports can provide all the functionality of relative (intra-package) imports -- albeit at the cost of difficulty when renaming package pieces higher up in the hierarchy or when moving one package inside another." You can still use relative import if you want, they've been implemented for a purpose, but I woudl highly discourage the ambiguous relative imports of python 2.4. JM From aahz at pythoncraft.com Fri May 7 08:23:07 2010 From: aahz at pythoncraft.com (Aahz) Date: 7 May 2010 05:23:07 -0700 Subject: Django as exemplary design References: <2010050312243328275-tomfsessile@gmailcom> <2010050619481239450-tomfsessile@gmailcom> Message-ID: In article <2010050619481239450-tomfsessile at gmailcom>, TomF wrote: > >I don't doubt it. But I'm not really interested in line (micro) level >code issues at the moment. Not that my code couldn't stand being >improved, but I'm more interested in seeing how medium/large OO python >systems are designed. If I could get this from a book I would, but I >suspect I need to study real code. My suspicion is that very very few medium/large systems are truly "well-designed". I've had occasion to dive into the CherryPy and Cheetah code, you might look there. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From richard.lamboj at bilcom.at Fri May 7 08:25:40 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Fri, 7 May 2010 14:25:40 +0200 Subject: importing modules In-Reply-To: <4BE3FE77.10005@sequans.com> References: <201005071255.48902.richard.lamboj@bilcom.at> <4BE3FE77.10005@sequans.com> Message-ID: <201005071425.40959.richard.lamboj@bilcom.at> Am Friday 07 May 2010 13:50:15 schrieb Jean-Michel Pichavant: > Richard Lamboj wrote: > > Hello, > > > > I have a question about importing python modules. > > > > I have modul package, with submodules. So how can a submodul access a > > modul that is on level upper? > > > > Is there something like "import ../../blah"? I don't mean something like > > this: "import bla.blub.moep" > > > > Kind Regards, > > > > Richi > > I would advise to use absolute imports whenever possible (always ?). > If 'pkg' is your package, then module sub1 should import sub2 that way: > > file pkg/sub1.py: > > import pkg.sub2 > > > see http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports > > " the python-dev community chose absolute imports as the default because > they're the more common use case and because absolute imports can > provide all the functionality of relative (intra-package) imports -- > albeit at the cost of difficulty when renaming package pieces higher up > in the hierarchy or when moving one package inside another." > > You can still use relative import if you want, they've been implemented > for a purpose, but I woudl highly discourage the ambiguous relative > imports of python 2.4. > > JM Hello, I always use absolute imports, but sometimes i does not work. I got: ImportError: No module named mail. When i import it from top of the module it works. If i import it from a level down, it works not always - strange? Kind Regards, Richi From nospam at news.eternal-september.org Fri May 7 08:31:32 2010 From: nospam at news.eternal-september.org (balzer) Date: Fri, 7 May 2010 15:31:32 +0300 Subject: Movable Python or ActivePython References: Message-ID: "Sridhar Ratnakumar" wrote in message news:mailman.2638.1273083585.23598.python-list at python.org... On 2010-05-05, at 5:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for > testing programs. As I read, Movable Python can run without being > installed. It needs no registry entries and knows the path to all the dlls > (system or otherwise) that it uses. > Whats about ActivePython > http://www.activestate.com/activepython/downloads? Does it requires > installation? The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ (substitute with latest version) When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 x64 machine - by extracting and running python.exe (from INSTALLDIR/) without installing - it just worked. -srid =========== Not works for me. I tried run python script from INSTALLDIR/ - not works for me. Looks, its extremely inconveniet, not user-friendly. There's a vaste quanity of various stuff inside pyhon folders. From neilc at norwich.edu Fri May 7 08:31:33 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 7 May 2010 12:31:33 GMT Subject: List comprehension + lambdas - strange behaviour References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> Message-ID: <84ifh5Fj5aU5@mid.individual.net> On 2010-05-07, Terry Reedy wrote: > On 5/6/2010 3:34 PM, Artur Siekielski wrote: >> Hello. >> I found this strange behaviour of lambdas, closures and list >> comprehensions: >> >>>>> funs = [lambda: x for x in range(5)] >>>>> [f() for f in funs] >> [4, 4, 4, 4, 4] > > You succumbed to lambda hypnosis, a common malady ;-). The > above will not work in 3.x, which does not leak comprehension > iteration variables. It functions the same in 3.1. Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> funs = [lambda: x for x in range(5)] >>> [f() for f in funs] [4, 4, 4, 4, 4] -- Neil Cerutti *** Your child was bitten by a Bat-Lizard. *** From python.list at tim.thechases.com Fri May 7 08:32:33 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 May 2010 07:32:33 -0500 Subject: fast regex In-Reply-To: References: <87eihp2gf8.fsf@castleamber.com> <4BE37F36.3090701@tim.thechases.com> Message-ID: <4BE40861.8080801@tim.thechases.com> [your reply appears to have come only to me instead of the mailing list; CC'ing c.l.p in reply] On 05/06/2010 10:12 PM, James Cai wrote: > When you say "This does a replacement for every word in the input corpus > (possibly with itself), but only takes one pass through the source text. " > It sounds great, but I am kinda lost with your code, sorry I am a regex > newbie. > > calling statement > > results = r.sub(replacer, content) > > the replacer is a function that needs parameter. How does the replacer know > what parameter? The documentation on the .sub() method says that the replacement can either be some text (as you used) or something callable (in my case a function, but could be an object with a __call__ method too), and that this callable is passed the match-object that's found. > why is r = re.compile(r'\b[a-zA-Z]+\b') when the words i want to find should > be in the word_list? You don't detail what sorts of words are in your word_list.keys() but you'd want your pattern to match those. My first regexp (that you quote) matches single words, but rather loosely (thus my caveat about "replace[s] every word in the input"). The replacement function checks to see if the replacement is in your word-list, and does the replacement, otherwise, it just returns the input. To watch it in action, you can try this: d = { # keys are all lowercase 'hello': 'goodbye', 'world': 'Python', } def replacer(match): text = match.group(0) replacement = d.get(text.lower(), text) # see what we're doing for explanation purposes print "Replacing %r with %r" % (text, replacement) return replacement r = re.compile(r'\b[a-zA-Z]+\b') print r.sub(replacer, "Hello there world, this is a test") > Is the match here the match of regex or just a variable name? If the keys in your word_list are more than just words, then the regexp may not find them all, and thus not replace them all. In that case you may have to resort to my 2nd regexp which builds the 5k branch regexp from your actual dictionary keys: >> r = re.compile(r'\b(%s)\b' % ( >> '|'.join(re.escape(s) for s in words_list.keys()) >> ), >> re.IGNORECASE) This method on the above dictionary (modified) d = { 'hello': 'goodbye', 'world': 'python', 'stuff with spaces?': 'tadah!', } would create a regexp of \b(hello|world|stuff\ with\ spaces\?)\b This has considerable performance implications as len(word_list) grows, unless you can figure a way to determine that some replacements are more probable than others and push them to the front of this regexp, but that's more complex and requires knowledge of your word-list. However, if all your keys are simply alpha (or alphanumeric, or findable by a simple regexp; likely one that doesn't include whitespace), you'll likely get much better performance with a generic regexp that over-captures, tries to find a replacement in your dict, returning that as the replacement; or if it's not in the dict, returning the original text unchanged. My simple test would be: test_regex = r'\w+' r = re.compile(r'^\b%s\b$' % test_regex) # added the "^....$" to anchor for testing purposes for key in word_list: # keys by default if not r.match(key): print "Failed to match %r" % key break If this passes, then the regexp should likely be sufficient to capture everything needed to use my replacer() function above. -tkc From jeanmichel at sequans.com Fri May 7 08:43:36 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 07 May 2010 14:43:36 +0200 Subject: importing modules In-Reply-To: <201005071425.40959.richard.lamboj@bilcom.at> References: <201005071255.48902.richard.lamboj@bilcom.at> <4BE3FE77.10005@sequans.com> <201005071425.40959.richard.lamboj@bilcom.at> Message-ID: <4BE40AF8.7070907@sequans.com> Richard Lamboj wrote: > Am Friday 07 May 2010 13:50:15 schrieb Jean-Michel Pichavant: > >> Richard Lamboj wrote: >> >>> Hello, >>> >>> I have a question about importing python modules. >>> >>> I have modul package, with submodules. So how can a submodul access a >>> modul that is on level upper? >>> >>> Is there something like "import ../../blah"? I don't mean something like >>> this: "import bla.blub.moep" >>> >>> Kind Regards, >>> >>> Richi >>> >> I would advise to use absolute imports whenever possible (always ?). >> If 'pkg' is your package, then module sub1 should import sub2 that way: >> >> file pkg/sub1.py: >> >> import pkg.sub2 >> >> >> see http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports >> >> " the python-dev community chose absolute imports as the default because >> they're the more common use case and because absolute imports can >> provide all the functionality of relative (intra-package) imports -- >> albeit at the cost of difficulty when renaming package pieces higher up >> in the hierarchy or when moving one package inside another." >> >> You can still use relative import if you want, they've been implemented >> for a purpose, but I woudl highly discourage the ambiguous relative >> imports of python 2.4. >> >> JM >> > > Hello, > > I always use absolute imports, but sometimes i does not work. > > I got: ImportError: No module named mail. When i import it from top of the > module it works. If i import it from a level down, it works not always - > strange? > > Kind Regards, > > Richi > Absolute imports works, 100%. You're doing something wrong. "No module named mail" means you forgot to prefix your submodule mail by the package name. It should be something like import pkg.mail The rule is simple, if pkg is your package, any import of a submodule should start with import pkg. Also note that your package must be properly installed (i.e. import pkg should work, no matter the directory you're in). If you don't want to install your package (don't wanna mess your PYTHONPATH with dev package), then you have to run your scripts from pkg/.. JM From davea at ieee.org Fri May 7 08:45:33 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 07 May 2010 08:45:33 -0400 Subject: column selection In-Reply-To: <4BE2C032.9080605@ieee.org> References: <1273140847.S.2303.13864.f4mail-235-207.rediffmail.com.1273148674.35579@webmail.rediffmail.com> <4BE2C032.9080605@ieee.org> Message-ID: <4BE40B6D.80508@ieee.org> Dave Angel wrote: >
mannu jha > wrote: >> I tried with this: >> >> for line in open('1.txt'): >> columns = line.split() >> print columns[0], columns[1] >> if not line: continue >> >> but it is showing error: >> >> nmruser at caf:~> python split.py >> 24 ALA >> Traceback (most recent call last): >> File "split.py", line 3, in print columns[0], columns[1] >> IndexError: list index out of range >> nmruser at caf:~> >> >> Thanks, >> >> On Thu, 06 May 2010 15:44:07 +0530 wrote >> >> >> If your files have two blank lines between each useful line, you have to >> do something to avoid trying to print those items for the blank lines. >> Depending how sure you are about your formatting, you could either do a >> >> if not line: continue >> >> or a >> >> if columns < 3: continue >> >> >> DaveA >> >> >> > (Don't top-post. It makes the message very confusing to someone else > trying to follow it. Also, enable your mail program's quoting feature > -- currently it's not adding the marks at the beginning of each line > you quote.) > > If you're going to skip over blank lines, it'd be good to do it before > trying to print from it. Move the test up by a line. > > DaveA > for line in open('1.txt'): columns = line.split() if len(columns) < 2: continue #skip over lines that don't have at least 2 columns print columns[0], columns[1] DaveA From python at bdurham.com Fri May 7 09:01:06 2010 From: python at bdurham.com (python at bdurham.com) Date: Fri, 07 May 2010 09:01:06 -0400 Subject: Movable Python or ActivePython In-Reply-To: References: Message-ID: <1273237266.16860.1373896225@webmail.messagingengine.com> Balzer, I took a look at the zip version of ActiveState's Python. There's a related thread in on this mailing list where I asked if the zip files are missing the Microsoft VC runtime files required by the Python interpreter. According to Trent from ActiveState, this is indeed the case. I recommend taking a look at this thread and contacting ActiveState to see when they expect to have a fix. You might also try taking a look at Py2exe and building your own Python "run time" (minus Idle). Malcolm ----- Original message ----- From: "balzer" To: python-list at python.org Date: Fri, 7 May 2010 15:31:32 +0300 Subject: Re: Movable Python or ActivePython "Sridhar Ratnakumar" wrote in message news:mailman.2638.1273083585.23598.python-list at python.org... On 2010-05-05, at 5:47 AM, balzer wrote: > I want Python pack that can run without being installed, mostly for > testing programs. As I read, Movable Python can run without being > installed. It needs no registry entries and knows the path to all the dlls > (system or otherwise) that it uses. > Whats about ActivePython > http://www.activestate.com/activepython/downloads? Does it requires > installation? The .MSI installer does require installation, but there is also a .ZIP package which doesn't. It is not visible in the downloads page, but you can always get it here: http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ (substitute with latest version) When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 x64 machine - by extracting and running python.exe (from INSTALLDIR/) without installing - it just worked. -srid =========== Not works for me. I tried run python script from INSTALLDIR/ - not works for me. Looks, its extremely inconveniet, not user-friendly. There's a vaste quanity of various stuff inside pyhon folders. -- http://mail.python.org/mailman/listinfo/python-list From nospam at news.eternal-september.org Fri May 7 09:48:55 2010 From: nospam at news.eternal-september.org (balzer) Date: Fri, 7 May 2010 16:48:55 +0300 Subject: Movable Python or ActivePython References: Message-ID: wrote in message news:mailman.2732.1273237281.23598.python-list at python.org... > Balzer, > > I took a look at the zip version of ActiveState's Python. > > There's a related thread in on this mailing list where I asked if the > zip files are missing the Microsoft VC runtime files required by the > Python interpreter. > > According to Trent from ActiveState, this is indeed the case. > > I recommend taking a look at this thread and contacting ActiveState to > see when they expect to have a fix. > > You might also try taking a look at Py2exe and building your own Python > "run time" (minus Idle). > > Malcolm > > > ----- Original message ----- > From: "balzer" > To: python-list at python.org > Date: Fri, 7 May 2010 15:31:32 +0300 > Subject: Re: Movable Python or ActivePython > > > "Sridhar Ratnakumar" wrote in message > news:mailman.2638.1273083585.23598.python-list at python.org... > > On 2010-05-05, at 5:47 AM, balzer wrote: > >> I want Python pack that can run without being installed, mostly for >> testing programs. As I read, Movable Python can run without being >> installed. It needs no registry entries and knows the path to all the >> dlls >> (system or otherwise) that it uses. >> Whats about ActivePython >> http://www.activestate.com/activepython/downloads? Does it requires >> installation? > > The .MSI installer does require installation, but there is also a .ZIP > package which doesn't. It is not visible in the downloads page, but you > can > always get it here: > > http://downloads.activestate.com/ActivePython/releases/2.6.5.12/ > (substitute with latest version) > > When I just tried the "ActivePython-2.6.5.12-win64-x64.zip" on my Win7 > x64 > machine - by extracting and running python.exe (from INSTALLDIR/) > without > installing - it just worked. > > -srid > > =========== > Not works for me. I tried run python script from INSTALLDIR/ - not works > for > me. Looks, its extremely inconveniet, not user-friendly. > There's a vaste quanity of various stuff inside pyhon folders. > > -- > http://mail.python.org/mailman/listinfo/python-list --------------- Is there some better, simpler ways for newbee? I need "install" Python on Windows XP without connection with windows system files or registry. And run Python it as independent framework. I just need test a few python scripts. Other question: how difficult is to convert Python code to pure C code? Thanks. From luke.leighton at googlemail.com Fri May 7 10:06:00 2010 From: luke.leighton at googlemail.com (lkcl) Date: Fri, 7 May 2010 07:06:00 -0700 (PDT) Subject: pyjamas 0.7 released References: <5cf8017c-d2e1-4ee4-b5d4-48e0cda19396@i37g2000yqn.googlegroups.com> <823f6745-c63a-45c5-a11e-860b7f344262@o11g2000yqj.googlegroups.com> <518it5t6hpvv4pdlue6cljmb09mse7ctov@4ax.com> <80d02ac5-b6ed-43fa-9508-67996cbedfde@b18g2000yqb.googlegroups.com> Message-ID: <04524266-6791-467c-b74d-40d4fd54486d@g21g2000yqk.googlegroups.com> On May 2, 7:16?am, Wolfgang Strobl wrote: > lkcl : > > > at least _some_ input would be good! ?the knowledge doesn't have to > >be there: just the bugreports saying "there's a problem and here's > >exactly how you reproduce it" would be a start! > >> So please make it simpler for more people to help. > > ... how?? there's a bugtracker, wiki, svn repository, over 30 > >examples and a developer list. ?the code really _is_ very very small > >(the UI widget set, with around 75 widgets, minus the license header > >text is only around 4,000 lines _total_, making it very very simple > >and very very easy for people to get used to). ?suggestions welcome! > > Well, the bunch of programming languages and APIs I collected over the > years is large enough already. These days I prefer to stay with python > and c, spiced with an occasional domain specific language. That's why I > was attracted bypyjamas, to begin with!. ?If I'd like to program using > Eclipse and Java or fool around with JavaScript, I'd do just that. But I > don't. ?IMHO, that ist a general problem of translation tools - they > attract the wrong people, from the point of view a developer who looks > for people sharing some of the workload. :-) > > So, Luke, I can only answer your question from the point of view of > somebody who is mostly a potentional consumer of your work, and most > problably not another developer. If you want to delegate some work you'd > like not to do yourself (for example because you prefer designing and > coding to testing and reorganizing and polishing the docs), than you > have at least to _define_ those pieces and to monitor progress. the project's run on a much much simpler basis than that: anyone who wants to contribute absolutely anything, ask, and you get svn access - simple as that. you get told what the rules are (code that's committed to trunk must work, must have a commit message, must be "single-purpose", must follow PEP8 mostly and so on - the usual obvious stuff). that's pretty much it. the project really _is_ run on the basis of it being "a useful tool for the developers, and if other people benefit from it that's great". kees wanted a better interpreter, i granted him svn rights, and in about four to five months he absolutely smacked the compiler into incredible and amazing shape, including implementing "yield" - fully and properly across _all_ browsers so that it passes even the python regression tests. me, personally, i would be happy with the state the compiler was in, back in 0.5, because that limited functionality served _my_ purposes. but, for kees, it definitely didn't: he wanted to be able to compile http://puremvc.org python code "as-is" and that meant that the compiler _had_ to be improved. so it's much _much_ simpler than "delegation of tasks". someone wants to do something? _great_ - knock yourself out. that having been said: we do have a TODO list. unsurprisingly, it's in the top level directory, called "TODO" :) > >> > then please issue bugreports for as many as you feel comfortable > >> >with / have time for. ? > > Well, ok. I put my notes in a Google chart, see http://spreadsheets.google.com/pub?key=0Au5LhqNQyrfCdGpDbTVjZFJwSERzV... ouaaaah, absolutely absolutely fantastic, thank you. ok. yep. the Controls one, someone provided a patch contributing the 2-axis slider and base class, but it was a bit of a mess, and i belieeve it only compile(s/d) with --strict. i've made some changes, _thank_ you for pointing these errors out, i've recorded them in issues. > I had to write a short patch against compile.py (see issue 397) in order > to make it compile the showcase examples on Windows. okaay, good stuff. > In addition, I've tried to create Selenium tests for automating the time > consuming job of checking all those examples, using Selenium IDE in > Firefox. I was my first experience using this against Ajax apps. The > results are somewhat mixed. Playing a round of "lightout" was a breeze, > but so far I hadn't much luck in driving the showcase example(s). I > didn't try very hard, though, because I ran out of time, as I do now. ? hell, your input has been incredibly valuable, i'm very grateful for the time you've put in. btw yes i started doing a UITest because yes, it's silly to have to do so much manual work. by writing a UITest app the goal is to be able to run the tests automated even across pyjd platforms. it'd be possible but raather tricky to run selenium under xulrunner/pyjd. l. From steve at REMOVE-THIS-cybersource.com.au Fri May 7 10:17:36 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 May 2010 14:17:36 GMT Subject: idiomatic way to collect and report multiple exceptions? References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> Message-ID: <4be420ff$0$8754$c3e8da3@news.astraweb.com> On Thu, 06 May 2010 21:56:10 -0700, Chris Rebert wrote: [...] > Output from example: > Traceback (most recent call last): > File "tmp.py", line 35, in > multiple_err.do_raise() > File "tmp.py", line 25, in do_raise > raise self > __main__.MultipleValidationErrors: See the following exception > tracebacks: > ============================================================================== > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'h' > > > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'e' [...] That's a nice trick, but I'd really hate to see it in real life code. Especially when each traceback was deep rather than shallow. Imagine having fifty errors, each one of which was ten or twenty levels deep! I also question how useful this would be in real life. Errors can cascade in practice, and so you would very likely get spurious errors that were caused by the first error. You see the same thing in doctests, e.g. if you do this: >>> x = 42/0 # oops, I meant 10 >>> y = x+1 not only do you get a legitimate DivideByZero error, but then you get a spurious NameError because x doesn't exist. (This is, I believe, a weakness of doctests.) Also, unless I'm badly mistaken, don't traceback objects interfere with garbage deletion? So keeping all those tracebacks around for some indefinite time could be very expensive. -- Steven From python at bdurham.com Fri May 7 10:21:39 2010 From: python at bdurham.com (python at bdurham.com) Date: Fri, 07 May 2010 10:21:39 -0400 Subject: Movable Python or ActivePython In-Reply-To: References: Message-ID: <1273242099.29417.1373909289@webmail.messagingengine.com> Balzer, > I just need test a few python scripts. I recommend you look at Movable Python or Portable Python. Malcolm From mannu_0523 at rediffmail.com Fri May 7 10:24:56 2010 From: mannu_0523 at rediffmail.com (mannu jha) Date: 7 May 2010 14:24:56 -0000 Subject: =?utf-8?B?UmU6IFJlOiBjb2x1bW4gc2VsZWN0aW9u?= In-Reply-To: <4BE40A74.8040706@ieee.org> Message-ID: <1273238939.S.3700.1037.H.TkRhdmUgQW5nZWwAUmU6IGNvbHVtbiBzZWxlY3Rpb24_.f4-234-118.1273242294.58146@webmail.rediffmail.com> On Fri, 07 May 2010 18:58:59 +0530 wrote >mannu jha wrote: > On Thu, 06 May 2010 18:54:59 +0530 wrote > >> mannu jha wrote: >> > > >> I tried with this: >> > > > > >> for line in open('1.txt'): >> > > >> columns = line.split() >> > > >> print columns[0], columns[1] >> > > >> if not line: continue >> > > > > >> but it is showing error: >> > > > > >> nmruser at caf:~> python split.py >> > > >> 24 ALA >> > > >> Traceback (most recent call last): >> > > >> File "split.py", line 3, in >> > > >> print columns[0], columns[1] >> > > >> IndexError: list index out of range >> > > >> nmruser at caf:~> >> > > > > >> Thanks, >> > > > > >> On Thu, 06 May 2010 15:44:07 +0530 wrote >> > > >> >> > > > > > > >> If your files have two blank lines between each useful line, you have to >> > > > > >> do something to avoid trying to print those items for the blank lines. >> > > > > >> Depending how sure you are about your formatting, you could either do a >> > > > > >> if not line: continue >> > > > > >> or a >> > > > > >> if columns < 3: continue >> > > > > > > >> DaveA >> > > > with this > > for line in open('8.txt'): > columns = line.split() > if columns python split.py > 24 ALA > Traceback (most recent call last): > File "split.py", line 4, in > print columns[0], columns[1] > IndexError: list index out of range > nmruser at caf:~> > > > > > > > >> >> > > (Don't top-post. It makes the message very confusing to someone else > > trying to follow it. Also, enable your mail program's quoting feature > > -- currently it's not adding the marks at the beginning of each line you > > quote.) > > > > If you're going to skip over blank lines, it'd be good to do it before > > trying to print from it. Move the test up by a line. > > > > DaveA > > > You forgot to include the list in your reply. Use reply-all, it's much easier. No clue what that "if columns..." line is supposed to be. It should get a parse error. DaveA Thankyou very much sir........Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From utabintarbo at gmail.com Fri May 7 10:32:49 2010 From: utabintarbo at gmail.com (utabintarbo) Date: Fri, 7 May 2010 07:32:49 -0700 (PDT) Subject: Cross-platform file paths Message-ID: Until now, I have used the UNC under Windows (XP) to allow my program to access files located on a Samba-equipped *nix box (eg. os.path.normpath(r"\\serverFQDN\sharename\dir\filename")). When I try to open this file under Linux (Red Hat 5), I get a file not found error. Is there a cross-platform method for accessing files on a network share using Python 2.X? TIA From dodo_do_not_wake_up at yahoo.Fr Fri May 7 10:33:13 2010 From: dodo_do_not_wake_up at yahoo.Fr (Dodo) Date: Fri, 07 May 2010 16:33:13 +0200 Subject: CGI python 3 write RAW BINARY In-Reply-To: <4bdc07d4$0$2980$ba4acef3@reader.news.orange.fr> References: <4bd8ae7e$0$27615$ba4acef3@reader.news.orange.fr> <4bd96540$0$27597$ba4acef3@reader.news.orange.fr> <4bd9b4c2$0$27606$ba4acef3@reader.news.orange.fr> <4bd9fc1a$0$2980$ba4acef3@reader.news.orange.fr> <4bdc07d4$0$2980$ba4acef3@reader.news.orange.fr> Message-ID: <4be424a8$0$27586$ba4acef3@reader.news.orange.fr> Le 01/05/2010 12:52, Dodo a ?crit : > Le 30/04/2010 17:52, Antoine Pitrou a ?crit : >> Le Thu, 29 Apr 2010 23:37:32 +0200, Dodo a ?crit : >>> ....I don't get a thing. >>> Now with the fix : >>> All browsers shows a different thing, but not the image! >>> http://ddclermont.homeip.net/misc/python/ >>> >>> If I save it to computer : >>> * Windows image viewer won't read it >>> * Irfanview can read it without problems >> >> Did you set the content-type and content-length in the HTTP headers? >> Can you post your code? >> >> > I didn't know about content-lenght > Here's the new code (I used a fixed image patch to make sure this is not > the source of the problem) > > > #!/usr/bin/python3 > import cgi, sys, cgitb > cgitb.enable() > > f = open("/home/dodo/54.jpg", "rb") > data = f.read() > l = len(data) > f.close() > > print("Content-type:image/jpg\nContent-length:%d\n\n" % l) > > sys.stdout.flush() > sys.stdout.buffer.write( data ) > > > > Dorian Anyone? From g.rodola at gmail.com Fri May 7 10:36:44 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Fri, 7 May 2010 16:36:44 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: You can easily avoid this by setting a lower timeout when calling asyncore.loop(), like 1 second or less (for example, Twisted uses 0.001 secs). Actually there's no reason for asyncore to have such a high default timeout (30 seconds). I think this should be signaled on the bug tracker. --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil 2010/5/6 Paul Moore : > >From a quick experiment, it seems that select.select with a timeout > doesn't react to a keyboard interrupt until the timeout expires. > Specifically, if I do > > s = socket.socket() > select.select([s], [], [], 30) > > and then press Ctrl-C, Python waits for the 30 seconds before raising > KeyboardInterrupt. > > Is this a known limitation on Windows? I see no mention of it in the > documentation. Assuming it is a known limitation, is there a way round > it? (I'm writing a tiny server using asyncore/asynchat, and the > delayed response to Ctrl-C is a mild nuisance. Solutions such as "use > twisted", while probably the sensible option in a wider context, don't > really apply here - I need something within the confines of the stdlib > if it's to be worth doing). > > Thanks, > Paul > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVE-THIS-cybersource.com.au Fri May 7 10:41:39 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 May 2010 14:41:39 GMT Subject: Classes: nested functions vs. private methodes References: Message-ID: <4be426a2$0$8754$c3e8da3@news.astraweb.com> On Thu, 06 May 2010 12:40:16 +0200, Richard Lamboj wrote: > Thank you for the nice sample, but what is with multiple inheritance in > your sample? I mean the super call. Why not _MyClass.blah(self, arg). super() should work correctly when you have more complicated multiple inheritance, while calling the parent class directly may not. Of course you can call _MyClass.blah if you prefer, for single inheritance it should be good enough. > What is when i have more then one Class from which i inherite and in > both are a methode called "blah", but i just want to call one of them > and not both, becouse they do different things? super() will not call both, it will call the first method that matches. Unfortunately, multiple inheritance is complicated. Here is a good article on super(): http://www.artima.com/weblogs/viewpost.jsp?thread=236275 And for fairness, here is an article which argues that super() is harmful: http://fuhm.net/super-harmful/ but really, it seems to me that he is arguing that super() is hard to get right, not harmful, and that is not because super() is hard, but because multiple inheritance is hard. -- Steven From pmaupin at gmail.com Fri May 7 10:45:02 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 7 May 2010 07:45:02 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: On May 6, 6:56?pm, Ben Finney wrote: > a... at pythoncraft.com (Aahz) writes: > > In article <4BE05D75.7030... at msn.com>, > > Rouslan Korneychuk ? wrote: > > > >The only question I have now is what about licensing? Is that > > >something I need to worry about? Should I go with LGPL, MIT, or > > >something else? > > > Which license you use depends partly on your political philosophy. > > Yes. > > Unless you place such a low value the freedom of your users that you'd > allow proprietary derivatives of your work to remove the freedoms you've > taken care to grant, Oh, you mean like Guido and the PSF, and all the Apache people. Yes, they're an uncaring bunch. I wouldn't trust software written by any of them, or attempt to emulate them in any way. > then you should choose a copyleft license like the > GPL. This is certainly appropriate in some circumstances. The only time I personally would use the GPL is if I thought I wrote something so wonderful and uneasily replicated that I wanted to directly make money off it, and thus wanted to make it harder for others to take it and sell enhanced versions without giving me the code back. For years, I have viewed the GPL as more of a commercial license than the permissive ones, a view that has been validated by several high profile events recently. > > Unless you have an aggressively Stallmanesque attitude that people > > using your code should be forced to contribute back any changes > > Er, no. Anyone who thinks that a copyleft license ?forces? anyone to do > anything is mistaken about copyright law Perhaps you feel "forces" is too loaded of a word. There is no question, however, that a copyright license can require that if you do "X" with some code, you must also do "Y". There is also no question that the GPL uses this capability in copyright law to require anybody who distributes a derivative work to provide the source. Thus, "forced to contribute back any changes" is definitely what happens once the decision is made to distribute said changes in object form. >, or the GPL, or both. The GPL > only grants permissions, like any other free software license. But the conditions attached to those permissions make it not at all "like any other free software license." And that's true whether we use the word "forces" or not. Regards, Pat From pmaupin at gmail.com Fri May 7 10:58:30 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 7 May 2010 07:58:30 -0700 (PDT) Subject: fast regex References: <87eihp2gf8.fsf@castleamber.com> <35bb1a8a-6f63-428e-8b96-1dcc41c4cb76@h20g2000prn.googlegroups.com> Message-ID: On May 6, 9:44?pm, james_027 wrote: > On May 6, 11:33?pm, John Bokma wrote: > > > james_027 writes: > > > I was working with regex on a very large text, really large but I have > > > time constrained. Does python has any other regex library or string > > > manipulation library that works really fast? > > > Hard to answer without seeing your regex and requirements first. > > Your question is like: I had a meal yesterday and it upset my > > stomach. Can you suggest a different meal for today? > > > -- > > John Bokma ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? j3b > > > Hacking & Hiking in Mexico - ?http://johnbokma.com/http://castleamber.com/-Perl & Python Development > > I am doing something like this > > for key, value in words_list.items(): > ? ? compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) > ? ? search = compile.sub(value, content) > > where the content is a large text about 500,000 characters and the > word list is about 5,000 > > Any optimization for the code above? Sure. for key, value in words_list.items(): pass compile = re.compile(r"""\b%s\b""" % key, re.IGNORECASE) search = compile.sub(value, content) From fpm at u.washington.edu Fri May 7 11:23:53 2010 From: fpm at u.washington.edu (cassiope) Date: Fri, 7 May 2010 08:23:53 -0700 (PDT) Subject: Cross-platform file paths References: Message-ID: <421e3c4c-df08-40bc-89dc-33254d990639@t26g2000prt.googlegroups.com> On May 7, 7:32?am, utabintarbo wrote: > Until now, I have used the UNC under Windows (XP) to allow my program > to access files located on a Samba-equipped *nix box (eg. > os.path.normpath(r"\\serverFQDN\sharename\dir\filename")). When I try > to open this file under Linux (Red Hat 5), I get a file not found > error. > > Is there a cross-platform method for accessing files on a network > share using Python 2.X? > > TIA normpath will convert forward slashes to backslashes on WinXX systems, but does not seem to do the reverse on posix systems...so try changing your string to use forward slashes. Also- is the path otherwise the same on your Linux system? HTH.. -f From mkiever at Pirx.sirius.org Fri May 7 11:45:52 2010 From: mkiever at Pirx.sirius.org (Matthias Kievernagel) Date: Fri, 7 May 2010 15:45:52 +0000 (UTC) Subject: py3 tkinter acceps bytes. why? References: <4BE352E5.4060004@v.loewis.de> Message-ID: Me: >> If I don't want bytes to get passed to tkinter >> I just have to raise an exception in AsObj, no? >> Or is it even sufficient to just remove the bytes case? Martin v. Loewis wrote: > But why would you want that? There are commands which legitimately > return bytes, e.g. the file and network io libraries of Tcl (not that > you would usually want to use them in Python, but Tkinter is actually > Tclinter, and should support all Tcl commands). I'm just looking for a reliable error message when I pass something to GUI functions which is not fit for display, i.e. not a string. If bytes pass unnoticed, I'll sooner or later have a surprise. Just to make sure I decode all bytes (coming from a socket) before I pass them on to the GUI. Regards, Matthias Kievernagel From wrw at mac.com Fri May 7 12:30:10 2010 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Fri, 07 May 2010 12:30:10 -0400 Subject: Frustration debugging serial code Message-ID: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> Hello World - I'm new to both Python and this list, but here's hoping someone can spot my problem. System: Mac OS-X, 10.6.3 (Intel dual quad processor) Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 The following snippet of code is designed to open a port via a KeySpan USB-to-serial converter and communicate with an X10 power line signaling system. Before you look at the code, let me mention that my frustration is the it executes perfectly if i enter it line by line at the Python prompt, and executes perfectly if I run it under the Wing IDE. It fails silently (no errors) if I run it as a standalone script. Clearly, I'm missing something. TIA, Bill Wing import serial, string port = '/dev/tty.KeySerial1' ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port stat1 = ser.write('\x02') # Write "Attention" to PowerLink print(' Stat1 is:', stat1) ack = ser.read(2) # Check to see if PowerLink is ready if ack == '\x06\r': # It returns ACK (\x06) \r if it is stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at House Code B, device code 2 print(' Stat2 is:', stat2) stat3 = ser.close() # Close serial port print(' Stat3 is:', stat3) elif ack =='\x15': # PowerLink sends NAC (hex 15) if it isn't. print('Received NAK after first open') else: print("Something's wrong at 1.\n") dummy = raw_input(' Hit any key to continue: ') -------------- next part -------------- An HTML attachment was scrubbed... URL: From utabintarbo at gmail.com Fri May 7 12:33:20 2010 From: utabintarbo at gmail.com (utabintarbo) Date: Fri, 7 May 2010 09:33:20 -0700 (PDT) Subject: Cross-platform file paths References: <421e3c4c-df08-40bc-89dc-33254d990639@t26g2000prt.googlegroups.com> Message-ID: <277ec1e8-85d0-44f2-b7ce-6efd42694a66@g21g2000yqk.googlegroups.com> On May 7, 11:23?am, cassiope wrote: > > normpath will convert forward slashes to backslashes on WinXX systems, > but > does not seem to do the reverse on posix systems...so try changing > your > string to use forward slashes. ?Also- is the path otherwise the same > on > your Linux system? > > HTH.. > ? -f I tried forward slashes: lst_p = open(os.path.normpath('//serverFQDN/sharename/dir/ filename'),'r').readlines() Traceback (most recent call last): File "", line 1, in IOError: [Errno 2] No such file or directory: '//serverFQDN/sharename/ dir/filename' BTW, this works on WinXP. It is as if it does not resolve, yet I have '//serverFQDN/sharename' mounted, proving that it does resolve. Is this an issue with the way python deals with the network? It does not seem like a network-only issue. From ron.eggler at gmail.com Fri May 7 12:45:10 2010 From: ron.eggler at gmail.com (Ron Eggler) Date: Fri, 7 May 2010 09:45:10 -0700 Subject: Broken pipe In-Reply-To: References: <201005062311.23076.ron.eggler@gmail.com> Message-ID: <201005070945.11284.ron.eggler@gmail.com> -- Ron Eggler Suite# 1804 1122 Gilford St Vancouver, BC V6G 2P5 Canada (778) 230-9442 > On Thu, May 6, 2010 at 11:11 PM, Ron Eggler wrote: > > On May 6, 2010 10:37:14 pm Chris Rebert wrote: > >> On Thu, May 6, 2010 at 10:27 PM, cerr wrote: > >> > Hi There, > >> > > >> > I'm very new to Python and i wanna write a script that sends a certain > >> > string to a server. The code I came up with looks like this: > >> > #!/usr/bin/python > >> > > >> > import sys > >> > import string > >> > > >> > from socket import * > >> > usage="USAGE: "+sys.argv[0]+" "; > >> > if len(sys.argv) != 3: > >> > print usage; > >> > sys.exit(0); > >> > host = sys.argv[1]; > >> > port = sys.argv[2]; > >> > buf = 1024; > >> > addr = (host,port); > >> > sock = socket(AF_INET, SOCK_STREAM); > >> > data = string.join("NovaxTest",'\n'); > >> > sock.send(data); > >> > sock.close(); > >> > and I'm calling this script like that: "./TestService.py 127.0.0.1 > >> > 1514" but when I call it I get following back: > >> > sending data to 127.0.0.1:1514 > >> > data: NovaxTest > >> > Traceback (most recent call last): > >> > File "./TestService.py", line 18, in > >> > sock.send(data); > >> > socket.error: [Errno 32] Broken pipe > >> > I understand that UNIX sends an Errno32 if the server closes the > >> > connection. But if i telnet to localhost on 1514 and send NovaxTest by > >> > hand everything works just fine. So what might be wrong here? > >> > >> You never called sock.connect(addr). Your code doesn't even use `addr` > >> at all. > > > > Oh, yeah, hOOps :$ > > > > > Hm weird now I get something like: > > Traceback (most recent call last): > > File "./TestService.py", line 14, in > > sock.connect((host,port)) > > File "", line 1, in connect > > TypeError: an integer is required > > > > > What does that mean? :( > > You never converted `port` to an int, it's still a string. port = int(sys.argv[2]) doesn't seem to help it either :( > > You might consider reading the socket module docs: > http://docs.python.org/library/socket.html mh, i browsed through it but didn't quite find what i'm looking for, do you have any more hints? Thanks, Ron From ron.eggler at gmail.com Fri May 7 13:24:10 2010 From: ron.eggler at gmail.com (cerr) Date: Fri, 7 May 2010 10:24:10 -0700 (PDT) Subject: Broken pipe References: <201005062311.23076.ron.eggler@gmail.com> Message-ID: <1bbfbae8-3eef-4268-8b86-e0326e74a5ac@a34g2000yqn.googlegroups.com> On May 7, 9:45?am, Ron Eggler wrote: > -- > Ron Eggler > Suite# 1804 > 1122 Gilford St > Vancouver, BC V6G 2P5 > Canada > (778) 230-9442 > > > > > > > On Thu, May 6, 2010 at 11:11 PM, Ron Eggler wrote: > > > On May 6, 2010 10:37:14 pm Chris Rebert wrote: > > >> On Thu, May 6, 2010 at 10:27 PM, cerr wrote: > > >> > Hi There, > > > >> > I'm very new to Python and i wanna write a script that sends a certain > > >> > string to a server. The code I came up with looks like this: > > >> > #!/usr/bin/python > > > >> > import sys > > >> > import string > > > >> > from socket import * > > >> > usage="USAGE: "+sys.argv[0]+" "; > > >> > if len(sys.argv) != 3: > > >> > ? ? ? ? ? ? ?print usage; > > >> > ? ? ? ? ? ? ?sys.exit(0); > > >> > host = sys.argv[1]; > > >> > port = sys.argv[2]; > > >> > buf = 1024; > > >> > addr = (host,port); > > >> > sock = socket(AF_INET, SOCK_STREAM); > > >> > data = string.join("NovaxTest",'\n'); > > >> > sock.send(data); > > >> > sock.close(); > > >> > and I'm calling this script like that: "./TestService.py 127.0.0.1 > > >> > 1514" but when I call it I get following back: > > >> > sending data to 127.0.0.1:1514 > > >> > data: NovaxTest > > >> > Traceback (most recent call last): > > >> > ?File "./TestService.py", line 18, in > > >> > ? ?sock.send(data); > > >> > socket.error: [Errno 32] Broken pipe > > >> > I understand that UNIX sends an Errno32 if the server closes the > > >> > connection. But if i telnet to localhost on 1514 and send NovaxTest by > > >> > hand everything works just fine. So what might be wrong here? > > > >> You never called sock.connect(addr). Your code doesn't even use `addr` > > >> at all. > > > > Oh, yeah, hOOps :$ > > > > > > > Hm weird now I get something like: > > > Traceback (most recent call last): > > > ?File "./TestService.py", line 14, in > > > ? ?sock.connect((host,port)) > > > ?File "", line 1, in connect > > > TypeError: an integer is required > > > > > > > What does that mean? :( > > > You never converted `port` to an int, it's still a string. > > port = int(sys.argv[2]) > > doesn't seem to help it either :( > > > > > You might consider reading the socket module docs: > >http://docs.python.org/library/socket.html > > mh, i browsed through it but didn't quite find what i'm looking for, do you > have any more hints? > Ah, okay, I figured that out! I actually just needed to add a \n at the end to signal the server that this is the end of the line. All good now, thanks for your help! -- Ron From python at mrabarnett.plus.com Fri May 7 14:08:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 May 2010 19:08:59 +0100 Subject: Frustration debugging serial code In-Reply-To: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> Message-ID: <4BE4573B.2020809@mrabarnett.plus.com> William R. Wing (Bill Wing) wrote: > Hello World - > I'm new to both Python and this list, but here's hoping someone can spot > my problem. > > System: Mac OS-X, 10.6.3 (Intel dual quad processor) > Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 > > The following snippet of code is designed to open a port via a KeySpan > USB-to-serial converter and communicate with an X10 power line signaling > system. Before you look at the code, let me mention that my frustration > is the it executes perfectly if i enter it line by line at the Python > prompt, and executes perfectly if I run it under the Wing IDE. It fails > silently (no errors) if I run it as a standalone script. Clearly, I'm > missing something. > What do you mean "It fails silently"? It might be unable to find the modules if you double-click on the script. You could check for that by printing a message if the import statement raises an ImportError. > TIA, > Bill Wing > > import serial, string > > port = '/dev/tty.KeySerial1' > > ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port > stat1 = ser.write('\x02') # Write "Attention" to > PowerLink > print(' Stat1 is:', stat1) > ack = ser.read(2) # Check to see if PowerLink > is ready > if ack == '\x06\r': # It returns ACK (\x06) \r > if it is > stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at > House Code B, device code 2 > print(' Stat2 is:', stat2) > stat3 = ser.close() # Close serial port > print(' Stat3 is:', stat3) > elif ack =='\x15': # PowerLink sends NAC (hex > 15) if it isn't. > print('Received NAK after first open') > else: print("Something's wrong at 1.\n") > > dummy = raw_input(' Hit any key to continue: ') > From solipsis at pitrou.net Fri May 7 14:37:25 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Fri, 7 May 2010 18:37:25 +0000 (UTC) Subject: Windows - select.select, timeout and KeyboardInterrupt References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: Le Fri, 07 May 2010 16:36:44 +0200, Giampaolo Rodol? a ?crit?: > You can easily avoid this by setting a lower timeout when calling > asyncore.loop(), like 1 second or less (for example, Twisted uses 0.001 > secs). > Actually there's no reason for asyncore to have such a high default > timeout (30 seconds). The reason for a high default timeout would be to avoid waking the CPU and do useless work too often. This is important on laptops and smaller devices, in order to conserve power. Under Unix, it's easy to have a separate fd on which you write a byte when an signal comes, and which wakes up your select() call. Under Windows, it may be more involved -- first because select() only takes sockets, not pipes. From jim.vickroy at noaa.gov Fri May 7 14:44:01 2010 From: jim.vickroy at noaa.gov (j vickroy) Date: Fri, 07 May 2010 12:44:01 -0600 Subject: unable to get Hudson to run unit tests Message-ID: Hello, I apologize if this is not the appropriate forum for a question about Hudson (http://hudson-ci.org/), but I did not know where else to ask and my web searches have not been fruitful. I'm attempting to use Hudson to run nose (http://somethingaboutorange.com/mrl/projects/nose/0.11.3/) unit tests but without success. The Hudson job configuration contains the following entry in the **Source Code Management** section: svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 which successfully retrieves the desired project code from the subversion repository. The *Build* section, of the job configuration page, contains the following entry: "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" in the *Execute Python Script* subsection. Note, the above nose command runs as expected from a command shell prompt on my computer. As an additional check, I added the following command: #!python.exe print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' in the *Execute shell* subsection of the job configuration *Build* section. The Hudson console output for this job after a *Build Now* request is: Started by user anonymous Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 At revision 3379 no change for svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build [workspace] $ python C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson6901585295620519415.py [workspace] $ python.exe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson851004747320097491.sh FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO Recording test results Test reports were found but none of them are new. Did tests run? For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml is 20 min old Finished: FAILURE which seems to indicate the unit tests were not run since nosetests.xml was generated by a previous execution of nose from a command shell. I have been unable to get this to work (after trying many permutations in the Hudson job configuration section) and would appreciate your guidance. Thanks, -- jv P.S. My system particulars are: Microsoft Windows XP Professional (Service Pack 3) Python 2.6.4 nose 0.11.3 Hudson 1.355 From scott.freemire at gmail.com Fri May 7 15:14:35 2010 From: scott.freemire at gmail.com (Scott) Date: Fri, 7 May 2010 12:14:35 -0700 (PDT) Subject: Help running Windows programs from Python Message-ID: <6acc04da-41bf-473e-a502-bfe2a9c4e9fa@r34g2000yqj.googlegroups.com> I want to write a script to automate log archiving/compressing on a Win2003 server. I have Python 2.6 installed. I am planning to use 7- zip for compression (because I have been using it manually for a while now). For now all operations will be local in the C: drive. As a total beginner I'm having trouble grasping the control of external programs. I have found these options but have not tried any yet - I would like some advice on which approach would be the most appropriate to begin with. Command Line Application Approach: os.system os.spawn* os.popen* popen2.* commands.* All of the above recommend replacing with subprocess module subprocess - latest way to do command line? pexpect module - http://sourceforge.net/projects/pexpect/, Most recent file is dated 1/5/2008 It should work on any platform that supports the standard Python pty module. (Windows?) pty - "On Windows, only sockets are supported; on Unix, all file descriptors." (gulp, ??) COM Application Approach: Per the 7-zip FAQ: Use the 7z.dll or 7za.dll - I haven't found these files yet on sf.net. comtypes 0.6.2 - has the word COM in it? pywin32 / win32com - there's that word again. And then there is this whole idea of "wrappers." Thanks, Scott From python at mrabarnett.plus.com Fri May 7 15:23:38 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 May 2010 20:23:38 +0100 Subject: Frustration debugging serial code In-Reply-To: References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> Message-ID: <4BE468BA.7090907@mrabarnett.plus.com> William R. Wing (Bill Wing) wrote: > > On May 7, 2010, at 2:08 PM, MRAB wrote: > >> William R. Wing (Bill Wing) wrote: >>> Hello World - >>> I'm new to both Python and this list, but here's hoping someone can >>> spot my problem. >>> System: Mac OS-X, 10.6.3 (Intel dual quad processor) >>> Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 >>> The following snippet of code is designed to open a port via a >>> KeySpan USB-to-serial converter and communicate with an X10 power >>> line signaling system. Before you look at the code, let me mention >>> that my frustration is the it executes perfectly if i enter it line >>> by line at the Python prompt, and executes perfectly if I run it >>> under the Wing IDE. It fails silently (no errors) if I run it as a >>> standalone script. Clearly, I'm missing something. >> What do you mean "It fails silently"? It might be unable to find the >> modules if you double-click on the script. You could check for that by >> printing a message if the import statement raises an ImportError. > > Maybe I should have been more explicit. The first line in the Python > file is: > > #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results > either way). > > and what I meant was that when I invoke it from a terminal window, it fails. > If the import were failing, wouldn't I get failures on the serial > operations? If the import fails then you wouldn't be able to create a serial object. > In particular, the ser object is exactly what it should be. If I print > it out, I get > the same value for ser in either terminal window mode or in the debugger. > > The various status print statements give exactly the expected results in > both > cases. But when invoked from the terminal window, the X10 controller > doesn't > get commands. > So you can execute: stat1 = ser.write('\x02') but the X10 controller just isn't receiving it? Is stat1 the same in both cases (ie, working and non-working)? >>> import serial, string >>> port = '/dev/tty.KeySerial1' >>> ser = serial.Serial(port, 9600, timeout=1) # Set up handle to >>> serial port >>> stat1 = ser.write('\x02') # Write "Attention" to >>> PowerLink >>> print(' Stat1 is:', stat1) ack = ser.read(2) >>> # Check to see if PowerLink is ready >>> if ack == '\x06\r': # It returns ACK (\x06) >>> \r if it is >>> stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at >>> House Code B, device code 2 >>> print(' Stat2 is:', stat2) >>> stat3 = ser.close() # Close serial port >>> print(' Stat3 is:', stat3) >>> elif ack =='\x15': # PowerLink sends NAC >>> (hex 15) if it isn't. >>> print('Received NAK after first open') >>> else: print("Something's wrong at 1.\n") >>> dummy = raw_input(' Hit any key to continue: ') >> From p.f.moore at gmail.com Fri May 7 15:25:56 2010 From: p.f.moore at gmail.com (Paul Moore) Date: Fri, 7 May 2010 20:25:56 +0100 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: On 7 May 2010 15:36, Giampaolo Rodol? wrote: > You can easily avoid this by setting a lower timeout when calling > asyncore.loop(), like 1 second or less (for example, Twisted uses > 0.001 secs). Thanks, that's what I was considering. > Actually there's no reason for asyncore to have such a high default > timeout (30 seconds). I assumed it was to avoid busy waiting. > I think this should be signaled on the bug tracker. If a longer timeout doesn't have issues with busy waiting, then I'd agree. Paul From wrw at mac.com Fri May 7 15:36:20 2010 From: wrw at mac.com (William R. Wing) Date: Fri, 07 May 2010 15:36:20 -0400 Subject: Frustration debugging serial code In-Reply-To: <4BE4573B.2020809@mrabarnett.plus.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> Message-ID: <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> On May 7, 2010, at 2:08 PM, MRAB wrote: > William R. Wing (Bill Wing) wrote: >> Hello World - >> I'm new to both Python and this list, but here's hoping someone can spot my problem. >> System: Mac OS-X, 10.6.3 (Intel dual quad processor) >> Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 >> The following snippet of code is designed to open a port via a KeySpan USB-to-serial converter and communicate with an X10 power line signaling system. Before you look at the code, let me mention that my frustration is the it executes perfectly if i enter it line by line at the Python prompt, and executes perfectly if I run it under the Wing IDE. It fails silently (no errors) if I run it as a standalone script. Clearly, I'm missing something. > What do you mean "It fails silently"? It might be unable to find the > modules if you double-click on the script. You could check for that by > printing a message if the import statement raises an ImportError. Maybe I should have been more explicit. The first line in the Python file is: #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results either way). and what I meant was that when I invoke it from a UNIX CLI window, it fails. If the import were failing, wouldn't I get failures on the serial operations? In particular, the ser object is exactly what it should be. If I print it out, I get the same value for ser from either the UNIX CLI or in the debugger, and in both cases it says "open=True" The various status print statements give exactly the same (expected) results in both cases. But when invoked from the terminal window, the X10 controller doesn't get commands. If I invoke python from the same window, and enter the script code interactively one line at a time - it works just fine. >> TIA, >> Bill Wing >> import serial, string >> port = '/dev/tty.KeySerial1' >> ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port >> stat1 = ser.write('\x02') # Write "Attention" to PowerLink >> print(' Stat1 is:', stat1) ack = ser.read(2) # Check to see if PowerLink is ready >> if ack == '\x06\r': # It returns ACK (\x06) \r if it is >> stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at House Code B, device code 2 >> print(' Stat2 is:', stat2) >> stat3 = ser.close() # Close serial port >> print(' Stat3 is:', stat3) >> elif ack =='\x15': # PowerLink sends NAC (hex 15) if it isn't. >> print('Received NAK after first open') >> else: print("Something's wrong at 1.\n") >> dummy = raw_input(' Hit any key to continue: ') > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid.invalid Fri May 7 15:40:22 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 7 May 2010 19:40:22 +0000 (UTC) Subject: Frustration debugging serial code References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> Message-ID: William R. Wing (Bill Wing) wrote: > Hello World - > I'm new to both Python and this list, but here's hoping someone can spot > my problem. > > System: Mac OS-X, 10.6.3 (Intel dual quad processor) > Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 > > The following snippet of code is designed to open a port via a KeySpan > USB-to-serial converter and communicate with an X10 power line signaling > system. Before you look at the code, let me mention that my frustration > is the it executes perfectly if i enter it line by line at the Python > prompt, and executes perfectly if I run it under the Wing IDE. It fails > silently (no errors) if I run it as a standalone script. Clearly, I'm > missing something. Well, the timing is vastly different in the two cases you cite. Have you tried adding some delays in your code? -- Grant Edwards grant.b.edwards Yow! Don't SANFORIZE me!! at gmail.com From invalid at invalid.invalid Fri May 7 15:41:41 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 7 May 2010 19:41:41 +0000 (UTC) Subject: Frustration debugging serial code References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> Message-ID: On 2010-05-07, Grant Edwards wrote: > William R. Wing (Bill Wing) wrote: >> Hello World - >> I'm new to both Python and this list, but here's hoping someone can spot >> my problem. >> >> System: Mac OS-X, 10.6.3 (Intel dual quad processor) >> Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 >> >> The following snippet of code is designed to open a port via a KeySpan >> USB-to-serial converter and communicate with an X10 power line signaling >> system. Before you look at the code, let me mention that my frustration >> is the it executes perfectly if i enter it line by line at the Python >> prompt, and executes perfectly if I run it under the Wing IDE. It fails >> silently (no errors) if I run it as a standalone script. Clearly, I'm >> missing something. > > Well, the timing is vastly different in the two cases you cite. Have > you tried adding some delays in your code? Never mind. I missed the fact that there were 3 cases. The timing in the IDE (which works) is going to be pretty much the same as when you run it stand-alone (which doesn't work). -- Grant Edwards grant.b.edwards Yow! Well, I'm INVISIBLE at AGAIN ... I might as well gmail.com pay a visit to the LADIES ROOM ... From g.rodola at gmail.com Fri May 7 15:55:15 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Fri, 7 May 2010 21:55:15 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: 2010/5/7 Antoine Pitrou : > Le Fri, 07 May 2010 16:36:44 +0200, Giampaolo Rodol? a ?crit?: >> You can easily avoid this by setting a lower timeout when calling >> asyncore.loop(), like 1 second or less (for example, Twisted uses 0.001 >> secs). >> Actually there's no reason for asyncore to have such a high default >> timeout (30 seconds). > > The reason for a high default timeout would be to avoid waking the CPU > and do useless work too often. This is important on laptops and smaller > devices, in order to conserve power. > Of course, but 30 seconds look a little bit too much to me, also because (I might be wrong here) I noticed that a smaller timeout seems to result in better performances. Plus, if scheduled callbacks are ever gonna be added to asyncore we would be forced to lower the default timeout anyway in order to have a decent reactivity. --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From python.list at tim.thechases.com Fri May 7 16:05:53 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 May 2010 15:05:53 -0500 Subject: ConfigParser.get() defaults? Message-ID: <4BE472A1.3010208@tim.thechases.com> With a normal dictionary, I can specify a default fallback value in the event the requested key isn't present: d = {} print d.get(42, 'Some default goes here') However, with the ConfigParser object, there doesn't seem to be any way to do a similar cp = ConfigParser(...) # ... print cp.get('MySection', 'MyValue', 'Some default goes here') that, in the event either "MySection" doesn't exist in the config file, or "MyValue" doesn't exist within "MySection", it simply & quietly returns my default. At the moment, I have to mimic this with try: val = cp.get('MySection', 'MyValue') except (NoSectionError, NoOptionError), e: val = 'Some default goes here' print val which is a real pain when you have multiple options, some using various combinations of get(), getboolean(), getint(), or getfloat(). Yes, I can write some cheap wrappers to do these, but it feels like something that should be built-in. I've played with the DEFAULT, but that seems to just create its own section that I have to *ask* for: cp.get('DEFAULT', 'MyValue') I've thumbed through the source to ConfigParser.py but don't see any indication that it's possible to do what I'd like short of wrapping all my cp.get*() calls in try/except blocks or creating a forked version of ConfigParser.py locally. Is there anything I'm missing, or a better workaround to this? Thanks, -tkc From mensanator at aol.com Fri May 7 16:07:01 2010 From: mensanator at aol.com (Mensanator) Date: Fri, 7 May 2010 13:07:01 -0700 (PDT) Subject: Help running Windows programs from Python References: <6acc04da-41bf-473e-a502-bfe2a9c4e9fa@r34g2000yqj.googlegroups.com> Message-ID: On May 7, 2:14?pm, Scott wrote: > I want to write a script to automate log archiving/compressing on a > Win2003 server. I have Python 2.6 installed. I am planning to use 7- > zip for compression (because I have been using it manually for a while > now). For now all operations will be local in the C: drive. > > As a total beginner I'm having trouble grasping the control of > external programs. > > I have found these options but have not tried any yet - I would like > some advice on which approach would be the most appropriate to begin > with. > > Command Line Application Approach: > os.system > os.spawn* > os.popen* > popen2.* > commands.* > All of the above recommend replacing with subprocess module > subprocess - latest way to do command line? > pexpect module -http://sourceforge.net/projects/pexpect/, Most recent > file is dated 1/5/2008 > ? ? It should work on any platform that supports the standard Python > pty ?module. (Windows?) > ? ? ? ? pty - "On Windows, only sockets are supported; on Unix, all > file descriptors." (gulp, ??) > > COM Application Approach: > Per the 7-zip FAQ: Use the 7z.dll or 7za.dll - I haven't found these > files yet on sf.net. > comtypes 0.6.2 - has the word COM in it? > pywin32 / win32com ?- there's that word again. > > And then there is this whole idea of "wrappers." > > Thanks, > Scott Here's a simple example: >>> import os >>> the_output = os.popen("dir "+"c:\\python31\\user\\*.py").readlines() >>> for i in the_output:print(i,end='') Volume in drive C has no label. Volume Serial Number is 06DE-55B4 Directory of c:\python31\user 09/08/2009 01:38 PM 689 3435.py 11/10/2009 06:43 PM 614 4697.py 03/09/2010 08:42 PM 5,922 5x.py 03/30/2010 07:51 PM 1,937 7[18] impure.py 08/28/2009 08:43 PM 1,867 bones.py 05/05/2010 07:21 PM 441 code.py 03/22/2010 04:31 PM 639 collatz_curiosity.py 09/18/2009 08:06 PM 17,125 collatz_game.py 08/20/2009 03:09 PM 406 csv_file_fix__minimal_2_all.py 11/06/2009 08:18 PM 432 digitsets.py 07/20/2009 07:03 PM 14,451 gmpy_geni_test_3.py 10/23/2009 05:35 PM 2,952 hit_target.py 03/19/2010 07:52 PM 245 how_many_random.py 04/15/2010 07:06 PM 217 issquare.py 07/31/2009 05:14 PM 1,132 itune.py 07/31/2009 04:41 PM 527 itune_stats.py 10/08/2009 08:08 PM 6,202 make_numbers.py 04/14/2010 08:00 PM 354 montyhall4.py 04/21/2010 07:46 PM 1,196 Ryan_Whited.py 03/25/2010 07:53 PM 4,318 ultimate_cycle.py 20 File(s) 61,666 bytes 0 Dir(s) 102,634,008,576 bytes free >>> From jcd at sdf.lonestar.org Fri May 7 16:12:23 2010 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 07 May 2010 16:12:23 -0400 Subject: Frustration debugging serial code In-Reply-To: <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> Message-ID: <1273263143.8440.4.camel@cliff-laptop> On Fri, 2010-05-07 at 15:36 -0400, William R. Wing wrote: > > Maybe I should have been more explicit. The first line in the Python > file is: > > > #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results > either way). > python should be lowercased when referring to the name of the executable. Unix filesystems are, of course, case sensitive. From jcd at sdf.lonestar.org Fri May 7 16:12:38 2010 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 07 May 2010 16:12:38 -0400 Subject: Frustration debugging serial code In-Reply-To: <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> Message-ID: <1273263158.8440.5.camel@cliff-laptop> On Fri, 2010-05-07 at 15:36 -0400, William R. Wing wrote: > > Maybe I should have been more explicit. The first line in the Python > file is: > > > #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results > either way). > python should be lowercased when referring to the name of the executable. Unix filesystems are, of course, case sensitive. From jim.vickroy at noaa.gov Fri May 7 16:38:34 2010 From: jim.vickroy at noaa.gov (j vickroy) Date: Fri, 07 May 2010 14:38:34 -0600 Subject: Help running Windows programs from Python In-Reply-To: <6acc04da-41bf-473e-a502-bfe2a9c4e9fa@r34g2000yqj.googlegroups.com> References: <6acc04da-41bf-473e-a502-bfe2a9c4e9fa@r34g2000yqj.googlegroups.com> Message-ID: Scott wrote: > I want to write a script to automate log archiving/compressing on a > Win2003 server. I have Python 2.6 installed. I am planning to use 7- > zip for compression (because I have been using it manually for a while > now). For now all operations will be local in the C: drive. > > As a total beginner I'm having trouble grasping the control of > external programs. > > I have found these options but have not tried any yet - I would like > some advice on which approach would be the most appropriate to begin > with. > > Command Line Application Approach: > os.system > os.spawn* > os.popen* > popen2.* > commands.* > All of the above recommend replacing with subprocess module > subprocess - latest way to do command line? > pexpect module - http://sourceforge.net/projects/pexpect/, Most recent > file is dated 1/5/2008 > It should work on any platform that supports the standard Python > pty module. (Windows?) > pty - "On Windows, only sockets are supported; on Unix, all > file descriptors." (gulp, ??) > > COM Application Approach: > Per the 7-zip FAQ: Use the 7z.dll or 7za.dll - I haven't found these > files yet on sf.net. > comtypes 0.6.2 - has the word COM in it? > pywin32 / win32com - there's that word again. > > And then there is this whole idea of "wrappers." > > Thanks, > Scott Hello Scott, I did not see what version of Python you are using (3.x?, 2.x?) so I'll answer based on Python 2.6.4 which I am using. If you already can accomplish your task with a series of commands, from a console window, my recommendation is to first read the Python documentation for os.system(...) which allows you to pass, as a parameter, any command you can type at a console window. Then, read the subprocess module documentation (particularly Section "18.1.3.3. Replacing os.system()"). Use the subprocess module Popen(...) function as a replacement for os.system(...). You may include as many calls to Popen(...), in your Python script, as needed. I do not know much about 7-zip so I can not say if the above command-line-like approach is feasible, but a quick glance at the FAQ indicates it probably is. Since you are just getting started, for simplicity, I would recommend against trying to use the 7-zip COM (http://en.wikipedia.org/wiki/Component_Object_Model) interface or the 7z.dll (which should be in the C:\Program Files\7-Zip\ folder) directly via the Python ctypes module (included in Python 2.6). HTH, -- jv From solipsis at pitrou.net Fri May 7 16:45:20 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Fri, 7 May 2010 20:45:20 +0000 (UTC) Subject: Windows - select.select, timeout and KeyboardInterrupt References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: Le Fri, 07 May 2010 21:55:15 +0200, Giampaolo Rodol? a ?crit?: > Of course, but 30 seconds look a little bit too much to me, also because > (I might be wrong here) I noticed that a smaller timeout seems to result > in better performances. That's probably bogus. > Plus, if scheduled callbacks are ever gonna be added to asyncore we > would be forced to lower the default timeout anyway in order to have a > decent reactivity. Why? From tjreedy at udel.edu Fri May 7 16:54:21 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 May 2010 16:54:21 -0400 Subject: List comprehension + lambdas - strange behaviour In-Reply-To: <84ifh5Fj5aU5@mid.individual.net> References: <23a73fff-3b3c-4c3a-b39c-9fd0df5bd6c3@b7g2000yqk.googlegroups.com> <84ifh5Fj5aU5@mid.individual.net> Message-ID: On 5/7/2010 8:31 AM, Neil Cerutti wrote: > On 2010-05-07, Terry Reedy wrote: >> On 5/6/2010 3:34 PM, Artur Siekielski wrote: >>> Hello. >>> I found this strange behaviour of lambdas, closures and list >>> comprehensions: >>> >>>>>> funs = [lambda: x for x in range(5)] >>>>>> [f() for f in funs] >>> [4, 4, 4, 4, 4] >> >> You succumbed to lambda hypnosis, a common malady ;-). The >> above will not work in 3.x, which does not leak comprehension >> iteration variables. > > It functions the same in 3.1. > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> funs = [lambda: x for x in range(5)] >>>> [f() for f in funs] > [4, 4, 4, 4, 4] Ok. >>> x Traceback (most recent call last): File "", line 1, in x NameError: name 'x' is not defined #only in 3.x But because the list comp is implemented in 3.x as an anonymous function, which is then called and discarded (an implementation that I believe is not guaranteed by the language ref), the lambda expression defines a nested function which captures the (final) value of x. >>> funs[0].__closure__[0].cell_contents 4 So it works (runs without exception), but somewhat accidentally and for a different reason than in 2.x, where 'x' is 4 at the global level. Terry Jan Reedy From aahz at pythoncraft.com Fri May 7 17:28:05 2010 From: aahz at pythoncraft.com (Aahz) Date: 7 May 2010 14:28:05 -0700 Subject: idiomatic way to collect and report multiple exceptions? References: Message-ID: In article , Ben Cohen wrote: > >eg -- I'd like to do something like this: > >errors = [] >for item in data: > try: > process(item) > except ValidationError as e: > errors.append(e) >raise MultipleValidationErrors(*errors) First of all, please DO NOT post code with TABs in it. In fact, you shouldn't even be writing code with TABs -- TAB characters are obsolete for new Python code. I would write your code this way: errors = [] for item in data: try: process(item) except ValidationError as e: errors.append(str(e)) if errors: raise MultipleValidationErrors(errors) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From db3l.net at gmail.com Fri May 7 17:41:16 2010 From: db3l.net at gmail.com (David Bolen) Date: Fri, 07 May 2010 17:41:16 -0400 Subject: Extract a bordered, skewed rectangle from an image References: Message-ID: "Paul Hemans" writes: > I am wondering whether there are any people here that have experience with > openCV and Python. If so, could you either give me some pointers on how to > approach this, or if you feel so inclined, bid on the project. There are 2 > problems: Can't offer actual services, but I've done image tracking and object identification in Python with OpenCV so can suggest some approaches. You might also try the OpenCV mailing list, though it's sometimes varies wildly in terms of S/N ratio. And for OpenCV specifically, I definitely recommend the book "Learning OpenCV" by O'Reilly. It's really hard to grasp the concepts and applications of the raw OpenCV calls from the API documentation, and I found the book (albeit not cheap) helped me out tremendously and was well worth it. I'll flip the two questions since the second is quicker to answer. > How to do this through Python into openCV? I am a newbie to Python, not > strong in Maths and ignorant of the usage of openCV. After trying a few wrappers, the bulk of my experience is with the ctypes-opencv wrapper and OpenCV 1.x (either 1.0 or 1.1pre). Things change a lot with the recent 2.x (which needs C++ wrappers), and I'm not sure the various wrappers are as stable yet. So if you don't have a hard requirement for 2.x, I might suggest at least starting with 1.x and ctypes-opencv, which is very robust, though I'm a little biased as I've contributed code to the wrapper. > How do I get openCV to ignore the contents of the label and just focus on > the border? There's likely no single answer, since multiple mechanisms for identifying features in an image exist, and you can also derive additional heuristics based on your own knowledge of the domain space (your own images). Without knowing exactly what the border design to make it easy to detect is, it's hard to say anything definitive. But in broad strokes, you'll often: 1. Normalize the image in some way. This can be to adjust for brightness from various scans to make later processing more consistent, or to switch spaces (to make color matching more effective) or even to remove color altogether if it just complicates matters. You may also mask of entire portions of the image if you have information that says they can't possibly be part of what you are looking for. 2. Attempt to remove noise. Even when portions of an image looks like a solid color, at the pixel level there can be may different variations in pixel values. Operations such as blurring or smoothing help to average out those values and simplify matching entire regions. 3. Attempt to identify the regions or features of interest. Here's where a ton of algorithms may apply due to your needs, but the simplest form to start with is basic color matching. For edge detection (like of your label) convolutions (such as gradient detection) might also ideal. 4. Process identified regions to attempt to clean them up, if possible weakening regions likely to be extraneous, and strengthening those more likely to be correct. Morphology operations are one class of processing likely to help here. 5. Select among features (if more than one) to identify the best match, using any knowledge you may have that can be used to rank them (e.g., size, position in image, etc...) My own processing is ball tracking in motion video, so I have some additional data in terms of adjacent frames that helps me remove static background information and minimize the regions under consideration for step 3, but a single image probably won't have that. But given that you have scanned documents, there may be other simplifying rules you can use, like eliminating anything too white or too black (depending on label color). My own flow works like: 1. Normalize each frame 1. Blur the frame (cvSmooth with CV_BLUR, 5x5 matrix). This smooths out the pixel values, improving the color conversion. 2. Balance brightess (in RGB space). I ended up just offsetting the image a fixed (x,x,x) value to maximize the RGB values. Found it worked better doing it in RGB before Lab conversion. 3. Convert the image to the "Lab" color space. I used Lab because the conversion process was fastest, but when frame rate isn't critical, HLS is likely better since hue/saturation are completely separate from lightness which makes for easier color matching. 2. Identify uninteresting regions in the current frame This may not apply to you, but here is where I mask out static information from prior background frames, based on difference calculations with the current frame, or very dark areas that I knew couldn't include what I was interested in. In your case, for example, if you know the label is going to show up fairly saturated (say it's a solid red or something), you could probably eliminate everything that is below a certain saturation level. Or if they are black and white documents, but the label has a color, it might be very easy to filter out everything but the label. If you're lucky, some simple heuristics applied here might have the net effect of masking the majority of your document image away, leaving primarily the label. 3. Color matching 1. Mask off regions of the image not falling within a specific Lab pixel range, sufficient to encompass my object under a variety of lighting/camera conditions. I typically use cvInRangeS to set the mask bits for pixels within the range. 2. Perform an erosion/dilation process - cvMorphologyEx against the mask as CV_MOP_CLOSE. What this does is apply an erosion followed by a dilation. The erosion removes very small features (likely unnecessary matches) while the dilation combines nearby features with each other. The net effect is to strengthen larger matched areas (and help them become contiguous) while removing tiny features. Note in my case I was looking for a relatively solid color ball (it had gaps since it was a whiffle ball), so if, for example, your label is alternating colors, or dashed lines or something like that it might not work as well. There are more complicated algorithms that can match more elaborate patterns, sometimes with initial training on target images. 4. Object selection 1. Locate all top level contours of any remaining solid areas in the mask (cvFindContours). This will identify connected areas in the mask, so in your case, ideally one of the located contours would be the label edge. This does assume that your feature identification in the prior step is likely to create contiguous areas. Even just a few pixels of gaps will net a non-closed contour which is harder to work with, though the morphology operation will sometimes close those gaps. 2. Evaluate "best" contour when multiple choices exist. Very small areas are eliminated, and remaining areas are evaluated for average Lab value distance from a target point (somewhat arbitrarily chosen at this point to represent the "ideal" ball). The nearest (in color distance) contour is picked, except in the case of two "close" contours where the further contour can win if it is at least 4x (arbitrarily chosen) as large. In your case, for example, any contours located within the label itself would necessarily be smaller than the label, so you could probably just pick largest. Also, when calling cvFindContours you can prevent it from finding "interior" contours. 3. Compute and return a minimum bounding circle (center, radius) for the selected contour. In your case, you'd likely just use the contour itself - you can use the contour (with 'n' line segments) as is, or convert into an approximate polygon. The nice thing about Python with OpenCV is the interactive experimentation you can do right in the interpreter. Open a highgui window, load in your image and then experiment. After performing various processes, just quickly show the new image in the existing or a new window. You can keep several windows up to date when you test process an image through several transforms to see the results. Hope this at least gives you some thoughts as to how to proceed. -- David From joncle at googlemail.com Fri May 7 17:46:26 2010 From: joncle at googlemail.com (Jon Clements) Date: Fri, 7 May 2010 14:46:26 -0700 (PDT) Subject: ConfigParser.get() defaults? References: Message-ID: <1aa30045-be87-4dba-88c5-37ba8e4c94fd@e1g2000yqe.googlegroups.com> On 7 May, 21:05, Tim Chase wrote: > With a normal dictionary, I can specify a default fallback value > in the event the requested key isn't present: > > ? ?d = {} > ? ?print d.get(42, 'Some default goes here') > > However, with the ConfigParser object, there doesn't seem to be > any way to do a similar > > ? ?cp = ConfigParser(...) > ? ?# ... > ? ?print cp.get('MySection', 'MyValue', 'Some default goes here') > > that, in the event either "MySection" doesn't exist in the config > file, or "MyValue" doesn't exist within "MySection", it simply & > quietly returns my default. ?At the moment, I have to mimic this with > > ? ?try: > ? ? ?val = cp.get('MySection', 'MyValue') > ? ?except (NoSectionError, NoOptionError), e: > ? ? ?val = 'Some default goes here' > ? ?print val > > which is a real pain when you have multiple options, some using > various combinations of get(), getboolean(), getint(), or > getfloat(). ?Yes, I can write some cheap wrappers to do these, > but it feels like something that should be built-in. > > I've played with the DEFAULT, but that seems to just create its > own section that I have to *ask* for: > > ? ?cp.get('DEFAULT', 'MyValue') > > I've thumbed through the source to ConfigParser.py but don't see > any indication that it's possible to do what I'd like short of > wrapping all my cp.get*() calls in try/except blocks or creating > a forked version of ConfigParser.py locally. ?Is there anything > I'm missing, or a better workaround to this? > > Thanks, > > -tkc Not convinced about this, but a quick "work-around" would be something like: def get_config(config, section, option, ctype=str, default=None): if default is None: ret = config.get(section, option) else: confdict = config.__dict__.get('_sections') ret = confdict.get(section).get(option, default) return ctype(ret) That should cover most exceptions and the get* functions..., just provide your own factory function to post-parse it... Of course, I'm probably missing something as usual... Anyway, Cheers, Jon. From bryanjugglercryptographer at yahoo.com Fri May 7 17:51:13 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Fri, 7 May 2010 14:51:13 -0700 (PDT) Subject: Fast Efficient way to transfer an object to another list References: Message-ID: <69b59d77-3f22-4f57-8f92-63e674da1fd8@a39g2000prb.googlegroups.com> Gabriel Genellina wrote: > I'd do that in two steps: > > def transfer_stock(stock_code, old_list, new_list): > ? ?# find the indexes to transfer > ? ?indexes = [i for i,stock in enumerate(old_list) > ? ? ? ? ? ? ? if stock.code==stock_code] > ? ?# actually transfer them > ? ?for index in reversed(indexes): > ? ? ?stock = old_list[index] > ? ? ?new_list.append(stock) > ? ? ?del old_list[index] > ? ?# I would not return anything The first step -- finding the items -- looks great. The step of adding items to new_list is just a bit squirly in that it reverse the order they had in old_list. The last step -- deleting them from old_list -- is a sluggish order n**2 run-time; it can be done in order n. (That's worst-case; your solution is linear time if either very few elements get transferred or very few do not get transferred.) Inspired by your use of list comprehension, and noting the simplicity of the condition for transferring an item, I suggest the following compact, order-preserving, linear-time solution: def transfer_stock(stock_code, old_list, new_list): new_list.extend(s for s in old_list if s.code==stock_code) old_list[:] = [s for s in old_list if s.code!=stock_code] # # Even obviously-correct code deserves testing: # from random import choice class Blurf: def __init__(self, code): self.code = code for nitems in range(10): for _ in range(17): nl_prefix = choice(range(13)) new_list = [Blurf(3) for _ in range(nl_prefix)] old_list = [Blurf(choice([3, 9])) for _ in range(nitems)] nitems = len(new_list) + len(old_list) original_new_list = new_list[:] original_old_list = old_list[:] transfer_stock(3, old_list, new_list) assert len(old_list) + len(new_list) == nitems for n in new_list: assert n.code == 3 assert n in original_new_list or n in original_old_list source = original_new_list + original_old_list assert new_list == [s for s in source if s in new_list] for n in old_list: assert n.code != 3 assert n in original_new_list or n in original_old_list assert old_list == [s for s in original_old_list if s in old_list] -- --Bryan From ben+python at benfinney.id.au Fri May 7 18:33:15 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 08 May 2010 08:33:15 +1000 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: <8739y3fil0.fsf@benfinney.id.au> Patrick Maupin writes: > On May 6, 6:56?pm, Ben Finney wrote: > > Er, no. Anyone who thinks that a copyleft license ?forces? anyone to > > do anything is mistaken about copyright law > > Perhaps you feel "forces" is too loaded of a word. There is no > question, however, that a copyright license can require that if you do > "X" with some code, you must also do "Y". No. A free software license doesn't require anything. It permits the recipient to do things otherwise prohibited. Copyright law taketh, and the license giveth as an exception to the law. That is: it is copyright law that forces the recipient to abstain from a broad range of actions. A free software license grants exceptions, explicitly allowing specific actions to be performed. > There is also no question that the GPL uses this capability in > copyright law to require anybody who distributes a derivative work to > provide the source. Thus, "forced to contribute back any changes" is > definitely what happens once the decision is made to distribute said > changes in object form. You might as well say that a restaurant ?forces? patrons to pay for their meal. They don't; it's merely a proviso for performing the act of eating the food. Since no-one is forcing anyone to take any of the actions permitted in the license, and since those actions would not otherwise be permitted under copyright law, it's both false and misleading to refer to them as ?forced?. -- \ ?We are stuck with technology when what we really want is just | `\ stuff that works.? ?Douglas Adams | _o__) | Ben Finney From pmaupin at gmail.com Fri May 7 19:27:17 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 7 May 2010 16:27:17 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> Message-ID: On May 7, 5:33?pm, Ben Finney wrote: > Patrick Maupin writes: > > On May 6, 6:56?pm, Ben Finney wrote: > > > Er, no. Anyone who thinks that a copyleft license ?forces? anyone to > > > do anything is mistaken about copyright law > > > Perhaps you feel "forces" is too loaded of a word. There is no > > question, however, that a copyright license can require that if you do > > "X" with some code, you must also do "Y". > > No. A free software license doesn't require anything. It permits the > recipient to do things otherwise prohibited. Copyright law taketh, and > the license giveth as an exception to the law. Finely parsed semantics with a meaningless difference when applied to what I said in the context of comparing GPL vs. permissive licenses. > That is: it is copyright law that forces the recipient to abstain from a > broad range of actions. A free software license grants exceptions, > explicitly allowing specific actions to be performed. Yes, and as I said, the exceptions are not as encompassing, and come with more restrictions, when using the GPL vs. using a permissive license. > > There is also no question that the GPL uses this capability in > > copyright law to require anybody who distributes a derivative work to > > provide the source. Thus, "forced to contribute back any changes" is > > definitely what happens once the decision is made to distribute said > > changes in object form. > > You might as well say that a restaurant ?forces? patrons to pay for > their meal. They don't; it's merely a proviso for performing the act of > eating the food. I certainly *would* say that. Try eating at a restaurant with a halfway watchful staff near a police station and see if you can get away without payment. Same thing with buying groceries or dry goods. The restaurants and the stores, with the full weight of the government, force you to do certain things if you partake of their wares. So do do software authors via their licenses, which, as you correctly point out, derive their power from the fact that your legal rights may be very limited absent a valid license to a piece of software. On the odd occasion that a restaurant or a store offers you something for "free" (with no asterisks or fine print) they really mean it -- you can take it home and do what you want with it, with no force applied. (Don't start on the whole libre vs. gratis thing -- as far as I'm concerned, neither "free as in beer" software nor GPLed software is as free as the occasional free meal or trinket I get, which is much more akin to "public domain" in software.) > Since no-one is forcing anyone to take any of the actions permitted in > the license, and since those actions would not otherwise be permitted > under copyright law, it's both false and misleading to refer to them as > ?forced?. Again, the force is applied once you choose to do a particular thing with the software -- is is really that hard to understand that concept? Even the permissive licenses force you to retain the copyright notice on the source, but other than that, they don't try to exert any kind of control over derivative works. By the way, in selectively quoting from my email, you conveniently neglected to address the significant issue of Guido et al apparently disrespecting their users by "placing a low value on their freedom". You may think that "force" has been misused here; I happen to think that you are (and with a lot of other company, no doubt) misusing the word "freedom" to mean only those *particular* freedoms that *you* deem appropriate, and trying to paint others who disagree with your priorities as somehow immoral. Yet when good examples of these apparently immoral people and their software are given, somehow the conversation is always directed back away from this issue. Personally, I usually like to give my customers (paid or unpaid) the ability to use the software as they see fit. It's basically a gift; although I force them to include my copyright notice on subsequent source copies, I don't expect anything else in return, either directly or indirectly. I certainly don't attempt to control the licensing of any software they write that happens to use my software; I would view that as an attempted abrogation of their freedom. But this just gets back to the ancient philosophical question of whether a man is really free if he is not allowed to sell himself into slavery. I would argue that he is not; obviously you and Stallman believe that the man is not free unless someone forces him to remain free by keeping him from selling himself. Regards, Pat From ben+python at benfinney.id.au Fri May 7 19:44:06 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 08 May 2010 09:44:06 +1000 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> Message-ID: <87tyqje0qh.fsf@benfinney.id.au> Patrick Maupin writes: > On May 7, 5:33?pm, Ben Finney wrote: > > Since no-one is forcing anyone to take any of the actions permitted > > in the license, and since those actions would not otherwise be > > permitted under copyright law, it's both false and misleading to > > refer to them as ?forced?. > > Again, the force is applied once you choose to do a particular thing > with the software And again, that would be the case with or without the specific free software license, so it's false and misleading to say the license forces anything. The actions that are prohibited are prohibited by copyright law, not by the license. I think we're done here. -- \ ?Members of the general public commonly find copyright rules | `\ implausible, and simply disbelieve them.? ?Jessica Litman, | _o__) _Digital Copyright_ | Ben Finney From steve at REMOVE-THIS-cybersource.com.au Fri May 7 20:56:48 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 00:56:48 GMT Subject: ConfigParser.get() defaults? References: Message-ID: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> On Fri, 07 May 2010 15:05:53 -0500, Tim Chase wrote: > With a normal dictionary, I can specify a default fallback value in the > event the requested key isn't present: [...] > However, with the ConfigParser object, there doesn't seem to be any way > to do a similar [...] Sounds like a nice feature to have. When you submit a patch (*grin*), please make sure the caller can specify what to do on missing section and missing option independently. > I've thumbed through the source to ConfigParser.py but don't see any > indication that it's possible to do what I'd like short of wrapping all > my cp.get*() calls in try/except blocks or creating a forked version of > ConfigParser.py locally. Is there anything I'm missing, or a better > workaround to this? Don't fork the source code, that's ridiculously overkill. Subclass ConfigParser and add the required functionality. -- Steven From ncohen at ucsd.edu Fri May 7 21:06:43 2010 From: ncohen at ucsd.edu (Ben Cohen) Date: Fri, 7 May 2010 19:06:43 -0600 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> Message-ID: <4D388C82-9DE8-43C3-89D8-F2C72623338E@ucsd.edu> Many thanks for the excellent example!! You rock! Ben On May 6, 2010, at 10:56 PM, Chris Rebert wrote: > On Thu, May 6, 2010 at 8:50 PM, Ben Cohen wrote: >> Is there a pythonic way to collect and display multiple exceptions at the same time? >> >> For example let's say you're trying to validate the elements of a list and you'd like to validate as many of the elements as possible in one run and still report exception's raised while validating a failed element. >> >> eg -- I'd like to do something like this: >> >> errors = [] >> for item in data: >> try: >> process(item) >> except ValidationError as e: >> errors.append(e) >> raise MultipleValidationErrors(*errors) >> >> where if the raised MultipleValidationErrors exception goes uncaught the interpreter will print a nice traceback that includes the tracebacks of each raised ValidationError. But I don't know how MultipleValidationErrors should be written ... > > import sys, traceback > > def _traceback_for(exc_info): > return ''.join(traceback.format_exception(*exc_info)) > > # StandardError can obviously be replaced with > # whatever exception superclass you want. > class MultipleValidationErrors(StandardError): > def __init__(self, errors=None): > self.errors = errors or [] > > def __str__(self): > tracebacks = "\n\n".join(_traceback_for(exc_info) for exc_info in \ > self.errors) > parts=("See the following exception tracebacks:", "="*78, tracebacks) > msg = '\n'.join(parts) > return msg > > def capture_current_exception(self): > self.errors.append(sys.exc_info()) > > def do_raise(self): > """Raises itself if it contains any errors""" > if self.errors: > raise self > > > #Example usage: > multiple_err = MultipleValidationErrors() > for c in "hello": > try: > int(c) # obviously fails > except ValueError: # whatever error type you care about > multiple_err.capture_current_exception() > multiple_err.do_raise() > > > Output from example: > Traceback (most recent call last): > File "tmp.py", line 35, in > multiple_err.do_raise() > File "tmp.py", line 25, in do_raise > raise self > __main__.MultipleValidationErrors: See the following exception tracebacks: > ============================================================================== > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'h' > > > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'e' > > > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'l' > > > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'l' > > > Traceback (most recent call last): > File "tmp.py", line 32, in > int(c) # obviously fails > ValueError: invalid literal for int() with base 10: 'o' > > > Cheers, > Chris > -- > Go Tritons! > http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Fri May 7 21:11:59 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 01:11:59 GMT Subject: idiomatic way to collect and report multiple exceptions? References: Message-ID: <4be4ba5e$0$27798$c3e8da3@news.astraweb.com> On Fri, 07 May 2010 14:28:05 -0700, Aahz wrote: > In article , Ben > Cohen wrote: >> >>eg -- I'd like to do something like this: >> >>errors = [] >>for item in data: >> try: >> process(item) >> except ValidationError as e: >> errors.append(e) >>raise MultipleValidationErrors(*errors) > > First of all, please DO NOT post code with TABs in it. In fact, you > shouldn't even be writing code with TABs -- TAB characters are obsolete > for new Python code. I don't believe this is correct. Do you have a source for this? Four spaces are recommended by PEP 8, and are compulsory for patches to the standard library, but Python continues to accept either multi-space indents or tabs, and in your own personal code you can use whichever you like. The documentation for Python 3 continues to state that either spaces or tabs will be accepted (and warns against mixing them): http://docs.python.org/py3k/reference/lexical_analysis.html#indentation According to my tests, Python 3.1 continues to accept both spaces and tabs. Tabs on their own are accepted without warning: [steve at sylar ~]$ cat tabs.py def f(x): # This function uses tabs for indents. return x print(f("tabs")) [steve at sylar ~]$ python3.1 tabs.py tabs Even mixing tabs and spaces in the one indent is allowed: [steve at sylar ~]$ cat mixed.py def f(x): # This uses mixed tabs and spaces. return x print(f("mixed tabs and spaces")) [steve at sylar ~]$ python3.1 mixed.py mixed tabs and spaces But using both tab-based indents and space-based indents is not: [steve at sylar ~]$ cat both.py def f(x): # This uses both tabs and spaces. pass # space-indent return x # tab-indent print(f("both tabs and spaces")) [steve at sylar ~]$ python3.1 both.py File "both.py", line 4 return x # tab-indent ^ TabError: inconsistent use of tabs and spaces in indentation -- Steven From crebert at ucsd.edu Fri May 7 21:24:24 2010 From: crebert at ucsd.edu (Chris Rebert) Date: Fri, 7 May 2010 18:24:24 -0700 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: <4D388C82-9DE8-43C3-89D8-F2C72623338E@ucsd.edu> References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> <4D388C82-9DE8-43C3-89D8-F2C72623338E@ucsd.edu> Message-ID: > On May 6, 2010, at 10:56 PM, Chris Rebert wrote: >> On Thu, May 6, 2010 at 8:50 PM, Ben Cohen wrote: >>> Is there a pythonic way to collect and display multiple exceptions at the same time? >>> >>> For example let's say you're trying to validate the elements of a list and you'd like to validate as many of the elements as possible in one run and still report exception's raised while validating a failed element. >>> >>> eg -- I'd like to do something like this: >>> >>> errors = [] >>> for item in data: >>> ? ? ? ?try: >>> ? ? ? ? ? ? ? ?process(item) >>> ? ? ? ?except ValidationError as e: >>> ? ? ? ? ? ? ? ?errors.append(e) >>> raise MultipleValidationErrors(*errors) >>> >>> where if the raised MultipleValidationErrors exception goes uncaught the interpreter will print a nice traceback that includes the tracebacks of each raised ValidationError. ?But I don't know how MultipleValidationErrors should be written ... On Fri, May 7, 2010 at 6:06 PM, Ben Cohen wrote: > Many thanks for the excellent example!! You rock! > > Ben However, I do agree with Steven that this approach to error handling is unusual. But I assume you have your reasons for wanting to do it this way. Cheers, Chris -- Python + Bioinformatics = Win http://blog.rebertia.com From wrw at mac.com Fri May 7 21:33:43 2010 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Fri, 07 May 2010 21:33:43 -0400 Subject: Frustration debugging serial code In-Reply-To: <4BE468BA.7090907@mrabarnett.plus.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <4BE468BA.7090907@mrabarnett.plus.com> Message-ID: See comments in-line. On May 7, 2010, at 3:23 PM, MRAB wrote: > William R. Wing (Bill Wing) wrote: >> On May 7, 2010, at 2:08 PM, MRAB wrote: >>> William R. Wing (Bill Wing) wrote: >>>> Hello World - >>>> I'm new to both Python and this list, but here's hoping someone can spot my problem. >>>> System: Mac OS-X, 10.6.3 (Intel dual quad processor) >>>> Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 >>>> The following snippet of code is designed to open a port via a KeySpan USB-to-serial converter and communicate with an X10 power line signaling system. Before you look at the code, let me mention that my frustration is the it executes perfectly if i enter it line by line at the Python prompt, and executes perfectly if I run it under the Wing IDE. It fails silently (no errors) if I run it as a standalone script. Clearly, I'm missing something. >>> What do you mean "It fails silently"? It might be unable to find the >>> modules if you double-click on the script. You could check for that by >>> printing a message if the import statement raises an ImportError. >> Maybe I should have been more explicit. The first line in the Python file is: >> #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results either way). >> and what I meant was that when I invoke it from a terminal window, it fails. >> If the import were failing, wouldn't I get failures on the serial operations? > > If the import fails then you wouldn't be able to create a serial object. Which I can, in all three cases. > >> In particular, the ser object is exactly what it should be. If I print it out, I get >> the same value for ser in either terminal window mode or in the debugger. >> The various status print statements give exactly the expected results in both >> cases. But when invoked from the terminal window, the X10 controller doesn't >> get commands. > So you can execute: > > stat1 = ser.write('\x02') > > but the X10 controller just isn't receiving it? Is stat1 the same in > both cases (ie, working and non-working)? The X10 controller not only receives it, it echos the response (\x06\r) that means it saw it and is ready for the next command in all three cases. The serial write that immediately follows, in which five hex bytes get sent to it is the one which succeeds interactively and in the IDE, and fails when executed as a bash script. > >>>> import serial, string >>>> port = '/dev/tty.KeySerial1' >>>> ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port >>>> stat1 = ser.write('\x02') # Write "Attention" to PowerLink >>>> print(' Stat1 is:', stat1) ack = ser.read(2) # Check to see if PowerLink is ready >>>> if ack == '\x06\r': # It returns ACK (\x06) \r if it is >>>> stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at House Code B, device code 2 >>>> print(' Stat2 is:', stat2) >>>> stat3 = ser.close() # Close serial port >>>> print(' Stat3 is:', stat3) >>>> elif ack =='\x15': # PowerLink sends NAC (hex 15) if it isn't. >>>> print('Received NAK after first open') >>>> else: print("Something's wrong at 1.\n") >>>> dummy = raw_input(' Hit any key to continue: ') >>> > -- > http://mail.python.org/mailman/listinfo/python-list From gallium.arsenide at gmail.com Fri May 7 21:37:57 2010 From: gallium.arsenide at gmail.com (John Yeung) Date: Fri, 7 May 2010 18:37:57 -0700 (PDT) Subject: Help running Windows programs from Python References: <6acc04da-41bf-473e-a502-bfe2a9c4e9fa@r34g2000yqj.googlegroups.com> Message-ID: <000675ee-0f6c-46d4-822c-f1ea8f4627cb@40g2000vbr.googlegroups.com> On May 7, 3:14?pm, Scott wrote: > I want to write a script to automate log archiving/compressing on a > Win2003 server. I have Python 2.6 installed. I am planning to use 7- > zip for compression (because I have been using it manually for a while > now). For now all operations will be local in the C: drive. For your purposes, I personally think os.system() is enough of an interface to 7-Zip and any other basic operating system commands you might need for your task. It's what I use myself to do batch archiving with 7-Zip. I think you will find everything you need within the os module (to get the names of files and such), and of course Python's built-in string methods. Especially since you say you are a beginner, my recommendation is to keep it simple; and to me, using only the os module is the simplest way to go. (That is why I went with it, after all. ;) Also, don't be afraid to try stuff. I can understand not wanting to mess stuff up. Well, create your own test directory and dummy files to practice on first, and just have at it. John From wrw at mac.com Fri May 7 21:38:33 2010 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Fri, 07 May 2010 21:38:33 -0400 Subject: Frustration debugging serial code In-Reply-To: <1273263143.8440.4.camel@cliff-laptop> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <5302B706-286A-4360-9AB9-E73C74B142E0@mac.com> <1273263143.8440.4.camel@cliff-laptop> Message-ID: <56733D2A-F1F1-4DA3-B48E-C8A6C1E46C36@mac.com> On May 7, 2010, at 4:12 PM, J. Cliff Dyer wrote: > On Fri, 2010-05-07 at 15:36 -0400, William R. Wing wrote: > >> >> Maybe I should have been more explicit. The first line in the Python >> file is: >> >> >> #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results >> either way). >> > > python should be lowercased when referring to the name of the > executable. Unix filesystems are, of course, case sensitive. > Cliff, True, although on a Mac the case is ignored. But you're right, best practice would make it lower case. However, I've tried it both ways with the same results. But thanks. Still frustrated, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Fri May 7 21:46:47 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 May 2010 20:46:47 -0500 Subject: ConfigParser.get() defaults? In-Reply-To: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> References: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4BE4C287.9070505@tim.thechases.com> On 05/07/2010 07:56 PM, Steven D'Aprano wrote: > On Fri, 07 May 2010 15:05:53 -0500, Tim Chase wrote: >> With a normal dictionary, I can specify a default fallback value in the >> event the requested key isn't present: > [...] >> However, with the ConfigParser object, there doesn't seem to be any way >> to do a similar > > Sounds like a nice feature to have. When you submit a patch (*grin*), I'm game to create and provide a patch, though I've had no success in the past trying to push tweaks into the Python Core (adding a subclass of optparse.HelpFormatter that respects newlines for text-wrapping). But if there's a straightforward way to do this, I'd love to patch the file and submit the deltas. I just need to know - what sort of patch (unified diff, context diff, ed) - against which version? I'm currently running the 2.5 that Debian Testing defaults to, though I have 2.6 available through my repository. - any tests needed/expected? run how? internal as an "if __name__ == '__main__'" block, or an external test suite? - where (or to whom) to I submit the patch (and possibly tests) I asked these questions about my optparse patch and never heard anything back (it was against 2.4 so I'm sure optparse has changed enough to render my past patches somewhat defunct) > please make sure the caller can specify what to do on missing section and > missing option independently. Could you detail what you envision here? For my use case, it's that the option doesn't exist, whether because there's no section, or there's a section but no option. Either way, something failed and I want a default value back. I don't have a mental model of what you expect in the "section exists but no option" that would behave differently from the "section doesn't exist" case. Do you also have suggestions for how it should interact with the weird [DEFAULT] section oddities (that don't really seem to default the way I expect them to)? Perhaps the two interrelate? >> I've thumbed through the source to ConfigParser.py but don't see any >> indication that it's possible to do what I'd like short of wrapping all >> my cp.get*() calls in try/except blocks or creating a forked version of >> ConfigParser.py locally. Is there anything I'm missing, or a better >> workaround to this? > > Don't fork the source code, that's ridiculously overkill. Subclass > ConfigParser and add the required functionality. Sorry for such loaded terms -- my "forking" suggestion wasn't intended to be Python, the Tim Version(tm), but rather, "copy the ConfigParser.py into my project directory, make the edits I need/want, and have it available to my project" (something similar to what I did for one of my projects copying in the python2.6 zipfile.py to my python2.4 code-base to supersede the standard 2.4 library's zipfile.py). Ideally, I'd tweak the base RawConfigParser class (and its subclasses if needed) rather than subclass, as it's functionality that would be useful in all cases (Raw, regular, and Safe). But yes, doing this would allow me to proffer the above-suggested patches. Thanks for your input, -tkc From vincent at vincentdavis.net Fri May 7 22:04:41 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Fri, 7 May 2010 20:04:41 -0600 Subject: is there a functional assert(x==y, 'error msg') Message-ID: Is there a functional assert(x==y, 'error msg') ? I can only find the assert that is used like; assert x==y, 'error msg' *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Fri May 7 22:18:56 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 08 May 2010 03:18:56 +0100 Subject: Frustration debugging serial code In-Reply-To: References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <4BE468BA.7090907@mrabarnett.plus.com> Message-ID: <4BE4CA10.4010608@mrabarnett.plus.com> William R. Wing (Bill Wing) wrote: > See comments in-line. > > On May 7, 2010, at 3:23 PM, MRAB wrote: > >> William R. Wing (Bill Wing) wrote: >>> On May 7, 2010, at 2:08 PM, MRAB wrote: >>>> William R. Wing (Bill Wing) wrote: >>>>> Hello World - >>>>> I'm new to both Python and this list, but here's hoping someone can spot my problem. >>>>> System: Mac OS-X, 10.6.3 (Intel dual quad processor) >>>>> Using Python 2.6.1, and pyserial-2.5_rc2-py2.6 >>>>> The following snippet of code is designed to open a port via a KeySpan USB-to-serial converter and communicate with an X10 power line signaling system. Before you look at the code, let me mention that my frustration is the it executes perfectly if i enter it line by line at the Python prompt, and executes perfectly if I run it under the Wing IDE. It fails silently (no errors) if I run it as a standalone script. Clearly, I'm missing something. >>>> What do you mean "It fails silently"? It might be unable to find the >>>> modules if you double-click on the script. You could check for that by >>>> printing a message if the import statement raises an ImportError. >>> Maybe I should have been more explicit. The first line in the Python file is: >>> #!/usr/bin/env Python (alternatively #!/usr/bin/Python - same results either way). >>> and what I meant was that when I invoke it from a terminal window, it fails. >>> If the import were failing, wouldn't I get failures on the serial operations? >> If the import fails then you wouldn't be able to create a serial object. > > Which I can, in all three cases. > >>> In particular, the ser object is exactly what it should be. If I print it out, I get >>> the same value for ser in either terminal window mode or in the debugger. >>> The various status print statements give exactly the expected results in both >>> cases. But when invoked from the terminal window, the X10 controller doesn't >>> get commands. >> So you can execute: >> >> stat1 = ser.write('\x02') >> >> but the X10 controller just isn't receiving it? Is stat1 the same in >> both cases (ie, working and non-working)? > > The X10 controller not only receives it, it echos the response (\x06\r) that means > it saw it and is ready for the next command in all three cases. The serial write > that immediately follows, in which five hex bytes get sent to it is the one which > succeeds interactively and in the IDE, and fails when executed as a bash script. > Does the ' Hit any key to continue: ' message appear when run as a bash script? I'm just wondering whether it's that when run from the Python prompt or IDE the 'ser' object continues to exist for a while, but when run as a bash script Python is terminating before all of the bytes have been sent. Of course, I'd expect 'ser.close()' to return only when there's nothing left to be sent, or, at least, for there to be enough time while it's waiting for you to press ENTER. >>>>> import serial, string >>>>> port = '/dev/tty.KeySerial1' >>>>> ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port >>>>> stat1 = ser.write('\x02') # Write "Attention" to PowerLink >>>>> print(' Stat1 is:', stat1) ack = ser.read(2) # Check to see if PowerLink is ready >>>>> if ack == '\x06\r': # It returns ACK (\x06) \r if it is >>>>> stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at House Code B, device code 2 >>>>> print(' Stat2 is:', stat2) >>>>> stat3 = ser.close() # Close serial port >>>>> print(' Stat3 is:', stat3) >>>>> elif ack =='\x15': # PowerLink sends NAC (hex 15) if it isn't. >>>>> print('Received NAK after first open') >>>>> else: print("Something's wrong at 1.\n") >>>>> dummy = raw_input(' Hit any key to continue: ') From prologic at shortcircuit.net.au Fri May 7 22:38:25 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 8 May 2010 12:38:25 +1000 Subject: is there a functional assert(x==y, 'error msg') In-Reply-To: References: Message-ID: On Sat, May 8, 2010 at 12:04 PM, Vincent Davis wrote: > Is there a functional assert(x==y, 'error msg') ? > I can only find the assert that is used like; > assert x==y, 'error msg' > What about: def assertfunc(expr, msg): assert expr, msg cheers James -------------- next part -------------- An HTML attachment was scrubbed... URL: From wrw at mac.com Fri May 7 22:42:00 2010 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Fri, 07 May 2010 22:42:00 -0400 Subject: Frustration debugging serial code In-Reply-To: <4BE4CA10.4010608@mrabarnett.plus.com> References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <4BE468BA.7090907@mrabarnett.plus.com> <4BE4CA10.4010608@mrabarnett.plus.com> Message-ID: On May 7, 2010, at 10:18 PM, MRAB wrote: > William R. Wing (Bill Wing) wrote: >> See comments in-line. >> On May 7, 2010, at 3:23 PM, MRAB wrote: >>> William R. Wing (Bill Wing) wrote: >>>> On May 7, 2010, at 2:08 PM, MRAB wrote: [byte -byte- byte] >>>>> >> The X10 controller not only receives it, it echos the response (\x06\r) that means >> it saw it and is ready for the next command in all three cases. The serial write >> that immediately follows, in which five hex bytes get sent to it is the one which >> succeeds interactively and in the IDE, and fails when executed as a bash script. > Does the ' Hit any key to continue: ' message appear when run as a bash > script? Yes, in all three cases, and just for completeness, the neither of the error returns from the first open statement ever are taken - that is, I never get either the \x15, which would print "Received NAK" nor the "Something's wrong" print that would indicate any other random return. > I'm just wondering whether it's that when run from the Python prompt or > IDE the 'ser' object continues to exist for a while, but when run as a > bash script Python is terminating before all of the bytes have been > sent. > > Of course, I'd expect 'ser.close()' to return only when there's nothing > left to be sent, or, at least, for there to be enough time while it's > waiting for you to press ENTER. > >>>>>> import serial, string >>>>>> port = '/dev/tty.KeySerial1' >>>>>> ser = serial.Serial(port, 9600, timeout=1) # Set up handle to serial port >>>>>> stat1 = ser.write('\x02') # Write "Attention" to PowerLink >>>>>> print(' Stat1 is:', stat1) ack = ser.read(2) # Check to see if PowerLink is ready >>>>>> if ack == '\x06\r': # It returns ACK (\x06) \r if it is >>>>>> stat2 = ser.write('\x63\x4E\x5C\x45\x41')# send "On" to module at House Code B, device code 2 >>>>>> print(' Stat2 is:', stat2) >>>>>> stat3 = ser.close() # Close serial port >>>>>> print(' Stat3 is:', stat3) >>>>>> elif ack =='\x15': # PowerLink sends NAC (hex 15) if it isn't. >>>>>> print('Received NAK after first open') >>>>>> else: print("Something's wrong at 1.\n") >>>>>> dummy = raw_input(' Hit any key to continue: ') > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at vincentdavis.net Fri May 7 22:43:22 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Fri, 7 May 2010 20:43:22 -0600 Subject: is there a functional assert(x==y, 'error msg') In-Reply-To: References: Message-ID: On Fri, May 7, 2010 at 8:38 PM, James Mills wrote: > On Sat, May 8, 2010 at 12:04 PM, Vincent Davis wrote: > >> Is there a functional assert(x==y, 'error msg') ? >> I can only find the assert that is used like; >> assert x==y, 'error msg' >> > > What about: > > def assertfunc(expr, msg): > assert expr, msg > I know but there are such nice asserts in unittest, but should (I assume can) they only be used in a unittest or would it be ok to use in code like the "normal" assert? *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri May 7 22:48:23 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 08 May 2010 12:48:23 +1000 Subject: recursive converting object to string which hasn't __str__ or/and__repr__ In-Reply-To: References: Message-ID: <4be4d153$1@dnews.tpgi.com.au> On 05/06/10 14:40, Daneel Yaitskov wrote: > Hi, > > > > Everybody knows class's __str__ and __repr__ can be used to get readable > user representation of an object. > > > But for simple classes or debug aims it is tediously to code these > methods. And Python has very powerful reflection. I believe that > somebody has already written such library with this method. > > I search library which can universally print state all not callable > attributes of an object. If object's attribute isn't int and float and > string and boolean and none then the method calls itself recursively. does dir() or printing __dict__ works for you? From python at mrabarnett.plus.com Fri May 7 22:49:29 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 08 May 2010 03:49:29 +0100 Subject: Frustration debugging serial code In-Reply-To: References: <5D13B687-EF19-45B0-BE92-DDDB8CED947D@mac.com> <4BE4573B.2020809@mrabarnett.plus.com> <4BE468BA.7090907@mrabarnett.plus.com> <4BE4CA10.4010608@mrabarnett.plus.com> Message-ID: <4BE4D139.1060503@mrabarnett.plus.com> William R. Wing (Bill Wing) wrote: > > On May 7, 2010, at 10:18 PM, MRAB wrote: > >> William R. Wing (Bill Wing) wrote: >>> See comments in-line. >>> On May 7, 2010, at 3:23 PM, MRAB wrote: >>>> William R. Wing (Bill Wing) wrote: >>>>> On May 7, 2010, at 2:08 PM, MRAB wrote: > > [byte -byte- byte] > >>>>>> >>> The X10 controller not only receives it, it echos the response >>> (\x06\r) that means >>> it saw it and is ready for the next command in all three cases. The >>> serial write >>> that immediately follows, in which five hex bytes get sent to it is >>> the one which >>> succeeds interactively and in the IDE, and fails when executed as a >>> bash script. >> Does the ' Hit any key to continue: ' message appear when run as a bash >> script? > > Yes, in all three cases, and just for completeness, the neither of the > error returns > from the first open statement ever are taken - that is, I never get > either the \x15, which > would print "Received NAK" nor the "Something's wrong" print that would > indicate > any other random return. > So clutching at straws doesn't work either... :-( >> I'm just wondering whether it's that when run from the Python prompt or >> IDE the 'ser' object continues to exist for a while, but when run as a >> bash script Python is terminating before all of the bytes have been >> sent. >> >> Of course, I'd expect 'ser.close()' to return only when there's nothing >> left to be sent, or, at least, for there to be enough time while it's >> waiting for you to press ENTER. >> From exarkun at twistedmatrix.com Fri May 7 23:18:30 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sat, 08 May 2010 03:18:30 -0000 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: <20100508031830.1660.308996474.divmod.xquotient.16@localhost.localdomain> On 7 May, 07:25 pm, p.f.moore at gmail.com wrote: >On 7 May 2010 15:36, Giampaolo Rodol? wrote: >>You can easily avoid this by setting a lower timeout when calling >>asyncore.loop(), like 1 second or less (for example, Twisted uses >>0.001 secs). > >Thanks, that's what I was considering. This is a good example of why it's a bad idea to use select on Windows. Instead, use WaitForMultipleObjects. >>Actually there's no reason for asyncore to have such a high default >>timeout (30 seconds). > >I assumed it was to avoid busy waiting. >>I think this should be signaled on the bug tracker. > >If a longer timeout doesn't have issues with busy waiting, then I'd >agree. The *default* timeout is only the default. An application that knows better can supply a different value. I'm not sure how much good can be done by fiddling with the default. Jean-Paul From greg.ewing at canterbury.ac.nz Sat May 8 00:21:39 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 08 May 2010 16:21:39 +1200 Subject: Teaching Programming In-Reply-To: References: Message-ID: <84k6k1Fl14U1@mid.individual.net> alex23 wrote: > This is my biggest issue with Knuth's view of literate programming. If > the generated source isn't readable, am I just supposed to trust it? > How can I tell if an error lies in my expression of the algorithm or > in the code generation itself? Knuth would say that the code generator should itself be a literate program, so that it's obviously correct. :-) -- Greg From stefan_ml at behnel.de Sat May 8 00:27:50 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 08 May 2010 06:27:50 +0200 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: j vickroy, 07.05.2010 20:44: > I apologize if this is not the appropriate forum for a question about > Hudson (http://hudson-ci.org/), but I did not know where else to ask and > my web searches have not been fruitful. Certainly nice to read something about Hudson in this forum, which is rare enough. It's seriously the greatest CI tool I've ever used, and it works great with Python apps. > "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" > > in the *Execute Python Script* subsection. The problem is that this isn't a "Python Script". I's a an executable, native program. Use the "execute shell" build step instead. Stefan From ncohen at ucsd.edu Sat May 8 01:22:08 2010 From: ncohen at ucsd.edu (Ben Cohen) Date: Fri, 7 May 2010 23:22:08 -0600 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: References: Message-ID: <36BDE98F-BE47-431D-971E-732B6A9B2289@ucsd.edu> Apologies for the TABs -- I wrote that example for demonstration purposes in my mail client -- I'll copy and paste from a real code editor in the future. Ben On May 7, 2010, at 3:28 PM, Aahz wrote: > In article , > Ben Cohen wrote: >> >> eg -- I'd like to do something like this: >> >> errors = [] >> for item in data: >> try: >> process(item) >> except ValidationError as e: >> errors.append(e) >> raise MultipleValidationErrors(*errors) > > First of all, please DO NOT post code with TABs in it. In fact, you > shouldn't even be writing code with TABs -- TAB characters are obsolete > for new Python code. > > I would write your code this way: > > errors = [] > for item in data: > try: > process(item) > except ValidationError as e: > errors.append(str(e)) > if errors: > raise MultipleValidationErrors(errors) > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > f u cn rd ths, u cn gt a gd jb n nx prgrmmng. > -- > http://mail.python.org/mailman/listinfo/python-list From brandshoes08 at yahoo.com Sat May 8 01:47:43 2010 From: brandshoes08 at yahoo.com (brandtrade) Date: Fri, 7 May 2010 22:47:43 -0700 (PDT) Subject: Parmigiani Fleurier Watch wholesale from china,paypal payment and free shipping Message-ID: Ebel Watch wholesale (paypal payment) (http://www.jordanonline06/) Bape Watch wholesale (paypal payment) (http://www.jordanonline06/) Bell&Ross Watch wholesale (paypal payment) (http:// www.jordanonline06/) Breit Ling Watch wholesale (paypal payment) (http:// www.jordanonline06/) Burberry Watch wholesale (paypal payment) (http://www.jordanonline06/) Cartier Watch wholesale (paypal payment) (http://www.jordanonline06/) Chopard Watch wholesale (paypal payment) (http://www.jordanonline06/) D&G Watch wholesale (paypal payment) (http://www.jordanonline06/) Givenchy Watch wholesale (paypal payment) (http://www.jordanonline06/) Jacob&Co Watch wholesale (paypal payment) (http://www.jordanonline06/) Kappa Watch wholesale (paypal payment) (http://www.jordanonline06/ ) Prada Watch wholesale (paypal payment) (http://www.jordanonline06/) Tissot Watch wholesale (paypal payment) (http://www.jordanonline06/) Titoni Watch wholesale (paypal payment) (http://www.jordanonline06/) U-BOAT Watch wholesale (paypal payment) (http://www.jordanonline06/) Zenith Watch wholesale (paypal payment) (http://www.jordanonline06/) A.Lange&Sohne Watch wholesale (paypal payment) (http:// www.jordanonline06/) Audemars Piguet Watch wholesale (paypal payment) (http:// www.jordanonline06/) Baume&Mercier Watch wholesale (paypal payment) (http:// www.jordanonline06/) Blancpain Watch wholesale (paypal payment) (http:// www.jordanonline06/) Breguet Watch wholesale (paypal payment) (http://www.jordanonline06/) BRM Watch wholesale (paypal payment) (http://www.jordanonline06/) Bvlgari Watch wholesale (paypal payment) (http://www.jordanonline06/) Chanel Watch wholesale (paypal payment) (http://www.jordanonline06/) Concord Watch wholesale (paypal payment) (http://www.jordanonline06/) Corum Watch wholesale (paypal payment) (http://www.jordanonline06/) Dewitt Watch wholesale (paypal payment) (http://www.jordanonline06/) Ferrari Watch wholesale (paypal payment) (http://www.jordanonline06/) Franck Muller Watch wholesale (paypal payment) (http:// www.jordanonline06/) Girard Perregaux Watch (paypal payment) (http://www.jordanonline06/) Glashutte Watch (paypal payment) (http://www.jordanonline06/) Graham Watch wholesale (paypal payment) (http://www.jordanonline06/) GUCCI Watch wholesale (paypal payment) (http://www.jordanonline06/) GUESS Watch wholesale (paypal payment) (http://www.jordanonline06/) Hamilton Watch wholesale (paypal payment) (http://www.jordanonline06/) Hermes Watch wholesale (paypal payment) (http://www.jordanonline06/) Hublot Watch wholesale (paypal payment) (http://www.jordanonline06/) IWC Watch wholesale (paypal payment) (http://www.jordanonline06/) Jaeger Le Coultre Watch wholesale (paypal payment) (http:// www.jordanonline06/) Longines Watch wholesale (paypal payment) (http://www.jordanonline06/) LV Watch wholesale (paypal payment) (http://www.jordanonline06/) Montblanc Watch wholesale (paypal payment) (http:// www.jordanonline06/) Movado Watch wholesale (paypal payment) (http://www.jordanonline06/) Omega Watch wholesale (paypal payment) (http://www.jordanonline06/) Oris Watch wholesale (paypal payment) (http://www.jordanonline06/) Paket Philippe Watch wholesale (paypal payment) (http:// www.jordanonline06/) Panerai Watch wholesale (paypal payment) (http://www.jordanonline06/) Parmigiani Fleurier Watch wholesale (paypal payment) (http:// www.jordanonline06/) Piaget Watch wholesale (paypal payment) (http://www.jordanonline06/) Porsche Design Watch wholesale (paypal payment) (http:// www.jordanonline06/) Rolex Watch wholesale (paypal payment) (http://www.jordanonline06/) Romain Jerome Titanic-Dna Watch wholesale (paypal payment)(http:// www.jordanonline06/) Tag Heuer Watch wholesale (paypal payment) (http:// www.jordanonline06/) Tudor Watch wholesale (paypal payment) (http://www.jordanonline06/) Vach.Constantine Watch wholesale (paypal payment) (http:// www.jordanonline06/) Armani Watch wholesale (paypal payment) (http://www.jordanonline06/) RADO Watch wholesale (paypal payment) (http://www.jordanonline06/) From ncohen at ucsd.edu Sat May 8 02:34:14 2010 From: ncohen at ucsd.edu (Ben Cohen) Date: Sat, 8 May 2010 00:34:14 -0600 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: References: <2782BC41-D516-4B71-ADB2-B97D430194EF@ucsd.edu> <4D388C82-9DE8-43C3-89D8-F2C72623338E@ucsd.edu> Message-ID: <3DB109B4-71D3-483D-B63D-165B49A98251@ucsd.edu> I've condensed the advice from this thread into this. import sys import traceback class ExceptionList(object): def __init__(self, msg, errors=None, *args): self.errortb = errors or [] super(ExceptionList, self).__init__(msg, *args) def __str__(self): """Print a pretty traceback of captured tracebacks """ tracebacks = '\n'.join(self.errortb) msg = super(ExceptionList, self).__str__() parts=(msg, "="*78, tracebacks) msg = '\n'.join(parts) return msg def capture_traceback(limit=None): tb = traceback.format_exception(limit=None, *sys.exc_info()) tb = "".join(traceback for traceback in tb) return tb class SomeException(ExceptionList, Exception): pass errors = [] for c in 'hello': try: int(c) except ValueError: errors.append(capture_traceback()) if errors: raise SomeException('Multiple Exceptions encountered, see below tracebacks', errors) This is like Aahz's method but I wanted to include the whole traceback and his example only captures the exception's error message. I changed the example from Chris to only capture the text of the traceback rather than the whole traceback. As for whether this is terribly strange or not useful -- Steven said > That's a nice trick, but I'd really hate to see it in real life code. > Especially when each traceback was deep rather than shallow. Imagine > having fifty errors, each one of which was ten or twenty levels deep! I don't want to get buried in overlong stack traces either so I included the optional limit parameter to the format_traceback call -- > I also question how useful this would be in real life. Errors can cascade > in practice, and so you would very likely get spurious errors that were > caused by the first error. You see the same thing in doctests, e.g. if > you do this: I think this has use as in the example case -- when sequentially processing the elements of a list with the processing of each element being sufficiently 'independent' of the processing of the other elements so that the errors won't cascade. This seems handy for debugging situations like that, as might be common when developing a command line tool... Or as in my case, when 'validating' a sequence of elements. I'd be curious if others think this use seems odd or a bad idea ... Thanks to all for the free advice! Ben On May 7, 2010, at 7:24 PM, Chris Rebert wrote: >> On May 6, 2010, at 10:56 PM, Chris Rebert wrote: >>> On Thu, May 6, 2010 at 8:50 PM, Ben Cohen wrote: >>>> Is there a pythonic way to collect and display multiple exceptions at the same time? >>>> >>>> For example let's say you're trying to validate the elements of a list and you'd like to validate as many of the elements as possible in one run and still report exception's raised while validating a failed element. >>>> >>>> eg -- I'd like to do something like this: >>>> >>>> errors = [] >>>> for item in data: >>>> try: >>>> process(item) >>>> except ValidationError as e: >>>> errors.append(e) >>>> raise MultipleValidationErrors(*errors) >>>> >>>> where if the raised MultipleValidationErrors exception goes uncaught the interpreter will print a nice traceback that includes the tracebacks of each raised ValidationError. But I don't know how MultipleValidationErrors should be written ... > > > On Fri, May 7, 2010 at 6:06 PM, Ben Cohen wrote: >> Many thanks for the excellent example!! You rock! >> >> Ben > > However, I do agree with Steven that this approach to error handling > is unusual. But I assume you have your reasons for wanting to do it > this way. > > Cheers, > Chris > -- > Python + Bioinformatics = Win > http://blog.rebertia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Sat May 8 02:40:22 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 7 May 2010 23:40:22 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> Message-ID: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> On May 7, 6:44?pm, Ben Finney wrote: > Patrick Maupin writes: > > On May 7, 5:33?pm, Ben Finney wrote: > > > Since no-one is forcing anyone to take any of the actions permitted > > > in the license, and since those actions would not otherwise be > > > permitted under copyright law, it's both false and misleading to > > > refer to them as ?forced?. > > > Again, the force is applied once you choose to do a particular thing > > with the software > > And again, that would be the case with or without the specific free > software license But the OP wasn't asking whether he should supply a license or not (the absence of a license would presumably force everybody who wanted to use the software to download a copy from an authorized site, and not allow them to make copies for friends); he was asking *which* license he should use, and he explicitly mentioned MIT and LGPL. In the post you directly responded to, Aahz had responded to the OP with a suggested license of "MIT". So, in the context of the original question and original answer, the comparison is permissive vs. (L)GPL, *not* (L)GPL vs. no license at all. > so it's false and misleading to say the license forces > anything. I have already adequately covered what I believe Aahz meant by "forced" and I think it's a reasonable term for the discussed situation. Personally, I believe that if anything is false and misleading, it is the attempt to try to completely change the discussion from MIT vs. GPL to GPL vs. no license (and thus very few rights for the software users), after first trying to imply that people who distribute software under permissive licenses (that give the user *more* rights than the GPL) are somehow creating a some sort of moral hazard that might adversely affect their users, and then refusing to have any further discussion on that particular issue. So which is it? GPL good because a user can do more with the software than if he had no license, or MIT bad because a user can do more with the software than if it were licensed under GPL? > The actions that are prohibited are prohibited by copyright > law, not by the license. Yes, just like the taking of food from the restaurant is prohibited by laws against theft, and in both cases, these prohibitions may be backed up by the force of the government. But as discussed, this does not mean that the restaurant or software author cannot give you something for free if they desire to. > I think we're done here. Certainly appears that neither of us is going to convince the other of anything. Regards, Pat From varnikat22 at gmail.com Sat May 8 02:54:57 2010 From: varnikat22 at gmail.com (varnikat t) Date: Sat, 8 May 2010 12:24:57 +0530 Subject: how to play a sound file repeatedly in loop Message-ID: How to run sound file repeatedly in loop ? When I do this, it does nothing and terminates: import pygst pygst.require("0.10") import gst, gtk n=0 while n<10: player = gst.element_factory_make("playbin2", "player") player.set_property("uri", "file:/home/varnika/hello.ogg") player.set_state(gst.STATE_PLAYING) n=n+1 Regards Varnika Tewari -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Sat May 8 03:48:11 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 08 May 2010 19:48:11 +1200 Subject: Windows - select.select, timeout and KeyboardInterrupt References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: In message , exarkun at twistedmatrix.com wrote: > This is a good example of why it's a bad idea to use select on Windows. > Instead, use WaitForMultipleObjects. How are you supposed to write portable code, then? From steve at REMOVE-THIS-cybersource.com.au Sat May 8 04:37:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 08:37:01 GMT Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> Message-ID: <4be522ac$0$27798$c3e8da3@news.astraweb.com> On Fri, 07 May 2010 23:40:22 -0700, Patrick Maupin wrote: > Personally, I believe that if anything is false and misleading, it is > the attempt to try to completely change the discussion from MIT vs. GPL > to GPL vs. no license (and thus very few rights for the software users), > after first trying to imply that people who distribute software under > permissive licenses (that give the user *more* rights than the GPL) are > somehow creating a some sort of moral hazard that might adversely affect > their users If encouraging third parties to take open source code and lock it up behind proprietary, closed licences *isn't* a moral hazard, then I don't know what one is. For the record, I've published software under an MIT licence because I judged the cost of the moral hazard introduced by encouraging freeloaders to be less than the benefits of having a more permissive licence that encourages freeloading and therefore attracts more users. For other software, I might judge that the cost/benefit ratio falls in a different place, and hence choose the GPL. > So which is it? GPL good because a user can do more with the software > than if he had no license, or MIT bad because a user can do more with > the software than if it were licensed under GPL? Good or bad isn't just a matter of which gives you more freedoms, they're also a matter of *what* freedoms they give. Weaponized ebola would allow you to kill hundreds of millions of people in a matter of a few weeks, but it takes a very special sort of mind to consider that the freedom to bring about the extinction of the human race a "good". I consider the freedom granted by the MIT licence for my users to take my source code and lock it up behind restrictive licences (and therefore *not* grant equivalent freedoms to their users in turn) to be a bad, not a good. But in some cases it is a cost worth paying, primarily because not all people who use MIT-licenced software go on to re-publish it under a restrictive licence, but nevertheless won't consider the GPL (possibly due to misunderstandings, confusion or political interference). -- Steven From martin.hellwig at dcuktec.org Sat May 8 05:33:46 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 08 May 2010 10:33:46 +0100 Subject: Picking a license In-Reply-To: <4be522ac$0$27798$c3e8da3@news.astraweb.com> References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: On 05/08/10 09:37, Steven D'Aprano wrote: > If encouraging third parties to take open source code and lock it up > behind proprietary, closed licences *isn't* a moral hazard, then I don't > know what one is. I fail to see what is morally wrong with it. When I ,as the author, share my work to the public, I should have made peace with the fact that I, for all intends and purposes, lost control over its use. And that is rightfully so; who am I to say: "Yeah you can use it but only once in a blue moon when Jupiter aligns with Mars and a solar eclipse reaches its high on Greenwich at noon exactly." But just for argument sake say that you can put restrictions on the use, who is going to enforce these restrictions? The author/Police/special interest groups? Anyway I usually put stuff under the MIT/BSD license, but when I can I use the beerware license (http://people.freebsd.org/~phk/) and I fully agree with PHK's reasoning. -- mph From g.rodola at gmail.com Sat May 8 07:47:53 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Sat, 8 May 2010 13:47:53 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: 2010/5/7 Antoine Pitrou : > Le Fri, 07 May 2010 21:55:15 +0200, Giampaolo Rodol? a ?crit?: >> Of course, but 30 seconds look a little bit too much to me, also because >> (I might be wrong here) I noticed that a smaller timeout seems to result >> in better performances. > > That's probably bogus. Probably, I'll try to write a benchmark script and see what happens. >> Plus, if scheduled callbacks are ever gonna be added to asyncore we >> would be forced to lower the default timeout anyway in order to have a >> decent reactivity. > > Why? Assuming loop() function does something like this: ... select.select(r, w, e, timeout) scheduler() # checks for scheduled calls to be fired ... ...imagine a case where there's a connection (aka a dispatcher instance) which does not receive or send any data *and* a scheduled call which is supposed to be fired after, say, 5 seconds. The entire loop would hang on select.select() which won't return for 30 seconds because the socket is not ready for reading and/or writing resulting in scheduler() be called too late. --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From promptc2 at hotmail.com Sat May 8 08:34:21 2010 From: promptc2 at hotmail.com (www.promptc.com) Date: Sat, 8 May 2010 05:34:21 -0700 (PDT) Subject: MBT shoes($62,1:1 quality),online shopping www.promptc.com Message-ID: <18331a69-4dfb-49e8-bb47-d9786b301540@32g2000prq.googlegroups.com> dear Mr/Ms, Great day! welcome to visit online shopping website www.Promptc.com Basic information: 1)Payment:Paypal,WU,TT etc 2)Delivery time:3-7 days door to door safety delivery 3)Delivery methods:DHL,TNT,EMS etc 4)quality condition:Super A 5) Price range:$30-$37 6)various brands ,various 2010 newest fashion style,various colors 7)can do drop-ship to your customers! 8)more order more discount ! ! ! 9)we would send out your order within 24-36 hours once confirmed your Pyament and then send you the tracking number via email for you to track the status of the goods. Main trade:Jersey,handbag,brand shoes like nike shox,nike air max,nike jordan,MBT shoes ,Skirt,T-shirt,sunglass,caps etc We are manufacture-sale company.Other companies invest fund in advertisement but our company invest in improving the quality of our goods and offer our customers the lowest price.We believe that the excellent quality itself is our company's advertisment.Since now the excellent of our goods have found a good market in many countries. some links of the nike shox : 1)http://www.promptc.com/index.php?main_page=index&cPath=168_183 2)http://www.promptc.com/index.php? main_page=index&cPath=168_183&sort=20a&page=6 3)http://www.promptc.com/index.php?main_page=index&cPath=168_189 4)http://www.promptc.com/index.php? main_page=index&cPath=168_183&sort=20a&page=10 5)http://www.promptc.com/index.php?main_page=index&cPath=168_190 6)http://www.promptc.com/index.php?main_page=index&cPath=168_184 7)http://www.promptc.com/index.php?main_page=index&cPath=168_174 8)http://www.promptc.com/index.php?main_page=index&cPath=168_188 Don't hesitate,take action !You can shopping online or contact us for more details! waitting for your early reply. Best wishes Sale Manager Megan Li Promptc Co.,Ltd www.promptc.com From news1234 at free.fr Sat May 8 08:51:32 2010 From: news1234 at free.fr (News123) Date: Sat, 08 May 2010 14:51:32 +0200 Subject: Cross-platform file paths In-Reply-To: References: Message-ID: <4be55e54$0$32091$426a74cc@news.free.fr> Hi TIA, utabintarbo wrote: > Until now, I have used the UNC under Windows (XP) to allow my program > to access files located on a Samba-equipped *nix box (eg. > os.path.normpath(r"\\serverFQDN\sharename\dir\filename")). When I try > to open this file under Linux (Red Hat 5), I get a file not found > error. > > Is there a cross-platform method for accessing files on a network > share using Python 2.X? > Up to my knowledge there is now path name under linux, which gives you access to samba shares without mounting then. Perhaps there's some special user space file system drivers providing that functionality, but I don't expect it to be standard linux behaviour. What is your linux distribution? I would suggest to change the subject line to something like: "accessing samba shares from a linux host without mounting them" or "cross-platform liibrary to access samba shares" From martin at v.loewis.de Sat May 8 09:26:55 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 08 May 2010 15:26:55 +0200 Subject: py3 tkinter acceps bytes. why? In-Reply-To: References: <4BE352E5.4060004@v.loewis.de> Message-ID: <4BE5669F.1090408@v.loewis.de> Matthias Kievernagel wrote: > Me: >>> If I don't want bytes to get passed to tkinter >>> I just have to raise an exception in AsObj, no? >>> Or is it even sufficient to just remove the bytes case? > Martin v. Loewis wrote: >> But why would you want that? There are commands which legitimately >> return bytes, e.g. the file and network io libraries of Tcl (not that >> you would usually want to use them in Python, but Tkinter is actually >> Tclinter, and should support all Tcl commands). > > I'm just looking for a reliable error message when I pass > something to GUI functions which is not fit for display, > i.e. not a string. If bytes pass unnoticed, > I'll sooner or later have a surprise. > Just to make sure I decode all bytes (coming from a socket) > before I pass them on to the GUI. I see. I think it's just not possible to provide such a check, given Tcl's (non-existent) type system. Regards, Martin From python.list at tim.thechases.com Sat May 8 09:52:27 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 08 May 2010 08:52:27 -0500 Subject: [PATCH] Re: ConfigParser.get() defaults? In-Reply-To: <4BE4C287.9070505@tim.thechases.com> References: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> <4BE4C287.9070505@tim.thechases.com> Message-ID: <4BE56C9B.8010309@tim.thechases.com> > On 05/07/2010 07:56 PM, Steven D'Aprano wrote: >> On Fri, 07 May 2010 15:05:53 -0500, Tim Chase wrote: >>> With a normal dictionary, I can specify a default fallback value in the >>> event the requested key isn't present: >> [...] >>> However, with the ConfigParser object, there doesn't seem to be any way >>> to do a similar >> >> Sounds like a nice feature to have. When you submit a patch (*grin*), > > I'm game to create and provide a patch, Attached is my initial patch against 2.6's ConfigParser.py to work in some defaults (though it should also apply fairly cleanly against 2.5). It doesn't differentiate between missing sections and missing options, as both cases are the same in my use: the user didn't provide a setting, so I want to specify a default without lots of try/except wrapping. For the type-specific get[int/float/boolean]() functions, it also provides an optional parameter to raise the ValueError or just return the default if it's provided-but-bogus (it may also yell at you if your default creates a ValueError). My distributed ConfigParser.py didn't seem to have any tests, so I didn't include any; but would be glad to write a few if they'd be integrated into the standard core testing. Is this the sort of things that should also be sent to python-dev, or are the powers-that-be lurking sufficiently on this list to see this patch fly? -tkc -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ConfigParser.diff URL: From exarkun at twistedmatrix.com Sat May 8 09:57:48 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sat, 08 May 2010 13:57:48 -0000 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: <20100508135748.1660.423455733.divmod.xquotient.21@localhost.localdomain> On 07:48 am, ldo at geek-central.gen.new_zealand wrote: >In message , >exarkun at twistedmatrix.com wrote: >>This is a good example of why it's a bad idea to use select on >>Windows. >>Instead, use WaitForMultipleObjects. > >How are you supposed to write portable code, then? With WaitForMultipleObjects on Windows, epoll on Linux, kqueue on BSD, event completion on Solaris, etc... Sound like more work than using select() everywhere? Yea, a bit. But not once you abstract it away from your actual application code. After all, it's not like these *do* different things. They all do the same thing (basically) - differently. Jean-Paul From exarkun at twistedmatrix.com Sat May 8 10:00:02 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sat, 08 May 2010 14:00:02 -0000 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: <20100508140002.1660.1843072524.divmod.xquotient.25@localhost.localdomain> On 11:47 am, g.rodola at gmail.com wrote: >2010/5/7 Antoine Pitrou : >>Le Fri, 07 May 2010 21:55:15 +0200, Giampaolo Rodol? a ?crit?: >>>Of course, but 30 seconds look a little bit too much to me, also >>>because >>>(I might be wrong here) I noticed that a smaller timeout seems to >>>result >>>in better performances. >> >>That's probably bogus. > >Probably, I'll try to write a benchmark script and see what happens. >>>Plus, if scheduled callbacks are ever gonna be added to asyncore we >>>would be forced to lower the default timeout anyway in order to have >>>a >>>decent reactivity. >> >>Why? > >Assuming loop() function does something like this: > > ... > select.select(r, w, e, timeout) > scheduler() # checks for scheduled calls to be fired > ... > >...imagine a case where there's a connection (aka a dispatcher >instance) which does not receive or send any data *and* a scheduled >call which is supposed to be fired after, say, 5 seconds. >The entire loop would hang on select.select() which won't return for >30 seconds because the socket is not ready for reading and/or writing >resulting in scheduler() be called too late. This would be an intensely lame way to implement support for scheduled callbacks. Try this trivial modification instead, to make it awesome: ... select.select(r, w, e, scheduler.time_until_next_call()) scheduler.run() ... (Or maybe just use Twisted. ;) Jean-Paul From solipsis at pitrou.net Sat May 8 10:00:09 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sat, 8 May 2010 16:00:09 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: <20100508160009.749631d9@pitrou.net> On Sat, 8 May 2010 13:47:53 +0200 Giampaolo Rodol? wrote: > > Assuming loop() function does something like this: > > ... > select.select(r, w, e, timeout) > scheduler() # checks for scheduled calls to be fired > ... > > ...imagine a case where there's a connection (aka a dispatcher > instance) which does not receive or send any data *and* a scheduled > call which is supposed to be fired after, say, 5 seconds. > The entire loop would hang on select.select() which won't return for > 30 seconds because the socket is not ready for reading and/or writing > resulting in scheduler() be called too late. Well, obviously you have to change the timeout based on the delay for the next scheduled call. If your patch doesn't do that, it probably needs fixing :) Regards Antoine. From mehgcap at gmail.com Sat May 8 10:08:08 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 8 May 2010 10:08:08 -0400 Subject: shortcut for large amount of global var declarations? Message-ID: Hi all, I am sorry if this is the second message about this you get; I typed this and hit send (on gmail website) but I got a 404 error, so I am not sure if the previous message made it out or not. Anyway, I have about fifteen vars in a function which have to be global. Is there a faster and more space-efficient way of doing this than putting each var on its own line; that is, fifteen "global varName" declarations? Thanks. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From luke.leighton at googlemail.com Sat May 8 10:08:08 2010 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 8 May 2010 07:08:08 -0700 (PDT) Subject: Python is cool!! References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> <4BA8F56D.6060305@timgolden.me.uk> <62d1f435-e473-4ba5-a7a6-334f5c69e4e3@d37g2000yqn.googlegroups.com> Message-ID: <29222386-00a0-46bf-89c2-e055d1bf1fca@d19g2000yqf.googlegroups.com> On Mar 23, 9:24?pm, Patrick Maupin wrote: > On Mar 23, 3:12?pm, Tim Golden wrote: > > > I can't say I thought *very* hard before sending that but... > > The OP asked for "integrate Python in Web Pages with HTML" > > which I understood -- perhaps wrongly -- to mean: run Python > > in the browser. The only two ways I'm aware of doing that > > in Python are the undersupported Python-as-IE-scripting-language > > and IronPython/Silverlight. > > If I had to run Python in a browser, the first thing I would do is > turn toPyjamas: ?http://pyjs.org/ or http://skulpt.org or an old version of pypy with the JS back-end (no longer maintained) ... but there's another way - actually several. i documented them all here: http://wiki.python.org/moin/WebBrowserProgramming solutions include appcelerator, pxpcomext and so on. appcelerator comprises, as best i can make out, some simple "glue" logic which connects silverlight/moonlight to DOM access functions via .NET (and from there to languages such as python or ruby, through IronRuby and IronPython) all pretty fucking horrendous, to be honest, and non-portable, making pyjs and skulpt the infinitely better choices for cross-platform / cross-browser interoperability. skulpt doesn't come with any UI widgets (not in JS nor in python) but pyjamas does. it entirely depends what you want to do. l. From bryanjugglercryptographer at yahoo.com Sat May 8 10:08:55 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sat, 8 May 2010 07:08:55 -0700 (PDT) Subject: fast regex References: <87eihp2gf8.fsf@castleamber.com> <4BE37F36.3090701@tim.thechases.com> Message-ID: Tim Chase wrote: > James wrote: > > [Tim had written:] > If the keys in your word_list are more than just words, then the > regexp may not find them all, and thus not replace them all. ?In > that case you may have to resort to my 2nd regexp which builds > the 5k branch regexp from your actual dictionary keys: > > >> ?r = re.compile(r'\b(%s)\b' % ( > >> ? ?'|'.join(re.escape(s) for s in words_list.keys()) > >> ? ?), > >> ? ?re.IGNORECASE) > > This method on the above dictionary (modified) > > ? ?d = { > ? ? ?'hello': 'goodbye', > ? ? ?'world': 'python', > ? ? ?'stuff with spaces?': 'tadah!', > ? ? ?} > > would create a regexp of > > ? ?\b(about|world|stuff\ with\ spaces\?)\b There's a subtle issue of the order of the keywords. Pythons (ir)regular expressions do not strictly guarantee to find the longest match. For example, re.findall(r'\b(about|about\-faced)\b', 'does about-faced match?') returns ['about'], which is the first complete match, not the longest. Sorting the keywords into longest-first order avoids the problem. > This has considerable performance implications as len(word_list) > grows, unless you can figure a way to determine that some > replacements are more probable than others and push them to the > front of this regexp, but that's more complex and requires > knowledge of your word-list. There is another method which is to factor out common prefixes, so the re module's search-and-backtrack engine never has a choice of multiple paths. Instead of: \b(abolished|abolition)\b we'd use: \b(aboli(shed|tion)\b The RE-generator is of course more complex than Tim's one-liner, but I happen to have code, which I'll include below. It's probably academic, as I'd agree with Tim that his first solution is the better candidate at this point. With my giant prefix-combined RE's, I can re.compile one with 4000 words randomly chosen from a Unix words file, but 5000 results in "regular expression code size limit exceeded". Tim's version which doesn't combine prefixes tops out a little lower. This is on 32-bit Windows, standard distribution. One could, of course, build multiple smaller RE's, but that starts to suck. -Bryan Olson from random import sample import re def build_big_re(str_list): """ Build a non-backtracking regular expression matching any of the words in str_list. """ def trie_insert(table, str): if str: submap = table.setdefault(str[0], {}) trie_insert(submap, str[1:]) else: table[""] = {} def sequentialize(table, lst): if table: keys = table.keys() keys.sort(key=len, reverse=True) lst.append('(?:') seperator = '' for key in keys: lst.append(seperator + re.escape(key)) submap = table[key] while len(submap) == 1: key = submap.keys()[0] submap = submap[key] lst.append(re.escape(key)) sequentialize(submap, lst) seperator = '|' lst.append(')') table = {} for str in str_list: trie_insert(table, str) lst = [r'\b'] sequentialize(table, lst) lst.append(r'\b') re_str = "".join(lst) # print "RE is: '%s'\n" % re_str return re.compile(re_str, re.IGNORECASE) def simple_re(str_list): str_list = sorted(str_list, key=len, reverse=True) re_str = r'\b(%s)\b' % ( '|'.join(re.escape(s) for s in str_list)) # print "RE is", re_str return re.compile(re_str, re.IGNORECASE) def testy(): words_file = r'/usr/share/dict/words' # Common Unix # words_file = r'C:\z\wordlist.txt' # Just my box nkeywords = 3500 from random import sample with open(words_file, 'r') as f: allwords = [w.strip() for w in f.readlines()] keywords = sample(allwords, nkeywords) bigtext = ' '.join(allwords) print 'Building simple RE...' simpre = simple_re(keywords) print 'Run simple re...' z1 = simpre.findall(bigtext) print 'Done.\n' print 'Building complex RE...' compre = build_big_re(keywords) print 'Run complex re...' z2 = compre.findall(bigtext) print 'Done.' assert z1 == z2 testy() From luke.leighton at googlemail.com Sat May 8 10:11:57 2010 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 8 May 2010 07:11:57 -0700 (PDT) Subject: Python is cool!! References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> <4bab7acb$0$2873$426a74cc@news.free.fr> Message-ID: On Mar 25, 3:01?pm, Bruno Desthuilliers wrote: > Jose Manuel a ?crit : > > > I have been learning Python, and it is amazing .... I am using the > > tutorial that comes with the official distribution. > > > At the end my goal is to develop applied mathematic in engineering > > applications to be published on the Web, specially on app. oriented to > > simulations and control systems, I was about to start learning Java > > but I found Python which seems easier to learn that Java. > > Python is indeed quite lightweight when compared to Java. But it has > it's share of non-obvious features, dark corners, gotchas, and plain > warts too. good god. it does?? :) that's news to me, bruno! where? i haven't found _any_ of those things - it's aaalll been blindingly obvious and... ok maybe not metaclasses i alllmost grok those :) l. From python at mrabarnett.plus.com Sat May 8 10:26:14 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 08 May 2010 15:26:14 +0100 Subject: fast regex In-Reply-To: References: <87eihp2gf8.fsf@castleamber.com> <4BE37F36.3090701@tim.thechases.com> Message-ID: <4BE57486.3060908@mrabarnett.plus.com> Bryan wrote: > Tim Chase wrote: >> James wrote: >>> [Tim had written:] >> If the keys in your word_list are more than just words, then the >> regexp may not find them all, and thus not replace them all. In >> that case you may have to resort to my 2nd regexp which builds >> the 5k branch regexp from your actual dictionary keys: >> >>>> r = re.compile(r'\b(%s)\b' % ( >>>> '|'.join(re.escape(s) for s in words_list.keys()) >>>> ), >>>> re.IGNORECASE) >> This method on the above dictionary (modified) >> >> d = { >> 'hello': 'goodbye', >> 'world': 'python', >> 'stuff with spaces?': 'tadah!', >> } >> >> would create a regexp of >> >> \b(about|world|stuff\ with\ spaces\?)\b > > > There's a subtle issue of the order of the keywords. Pythons > (ir)regular expressions do not strictly guarantee to find the longest > match. For example, > > re.findall(r'\b(about|about\-faced)\b', > 'does about-faced match?') > > returns ['about'], which is the first complete match, not the longest. > Sorting the keywords into longest-first order avoids the problem. > > >> This has considerable performance implications as len(word_list) >> grows, unless you can figure a way to determine that some >> replacements are more probable than others and push them to the >> front of this regexp, but that's more complex and requires >> knowledge of your word-list. > > There is another method which is to factor out common prefixes, so the > re module's search-and-backtrack engine never has a choice of multiple > paths. Instead of: > > \b(abolished|abolition)\b > > we'd use: > > \b(aboli(shed|tion)\b > > The RE-generator is of course more complex than Tim's one-liner, but I > happen to have code, which I'll include below. It's probably academic, > as I'd agree with Tim that his first solution is the better candidate > at this point. > > With my giant prefix-combined RE's, I can re.compile one with 4000 > words randomly chosen from a Unix words file, but 5000 results in > "regular expression code size limit exceeded". Tim's version which > doesn't combine prefixes tops out a little lower. This is on 32-bit > Windows, standard distribution. One could, of course, build multiple > smaller RE's, but that starts to suck. > There's an alternative regex module at: http://bugs.python.org/issue2636 and also at: http://pypi.python.org/pypi/regex/0.1.2010414 It looks for common prefixes and suffixes internally and can handle much larger regexes. From joncle at googlemail.com Sat May 8 10:26:16 2010 From: joncle at googlemail.com (Jon Clements) Date: Sat, 8 May 2010 07:26:16 -0700 (PDT) Subject: shortcut for large amount of global var declarations? References: Message-ID: On 8 May, 15:08, Alex Hall wrote: > Hi all, > I am sorry if this is the second message about this you get; I typed > this and hit send (on gmail website) but I got a 404 error, so I am > not sure if the previous message made it out or not. > Anyway, I have about fifteen vars in a function which have to be > global. Is there a faster and more space-efficient way of doing this > than putting each var on its own line; that is, fifteen "global > varName" declarations? Thanks. > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg... at gmail.com;http://www.facebook.com/mehgcap About 15 that *need* to be global; smells bad to me. However, you can amend a function's .func_globals attribute. Just wouldn't be going there myself. Why do you have this many? What's your use case? Jon. From aahz at pythoncraft.com Sat May 8 10:26:31 2010 From: aahz at pythoncraft.com (Aahz) Date: 8 May 2010 07:26:31 -0700 Subject: Picking a license References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: In article <4be522ac$0$27798$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > >For the record, I've published software under an MIT licence because I >judged the cost of the moral hazard introduced by encouraging freeloaders >to be less than the benefits of having a more permissive licence that >encourages freeloading and therefore attracts more users. For other >software, I might judge that the cost/benefit ratio falls in a different >place, and hence choose the GPL. Well, yes, which is more-or-less what I posted in the first place. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From python at mrabarnett.plus.com Sat May 8 10:29:30 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 08 May 2010 15:29:30 +0100 Subject: shortcut for large amount of global var declarations? In-Reply-To: References: Message-ID: <4BE5754A.9040106@mrabarnett.plus.com> Alex Hall wrote: > Hi all, > I am sorry if this is the second message about this you get; I typed > this and hit send (on gmail website) but I got a 404 error, so I am > not sure if the previous message made it out or not. > Anyway, I have about fifteen vars in a function which have to be > global. Is there a faster and more space-efficient way of doing this > than putting each var on its own line; that is, fifteen "global > varName" declarations? Thanks. > 'global' will accept multiple names: def foo(): global a, b, c ... From mehgcap at gmail.com Sat May 8 11:03:04 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 8 May 2010 11:03:04 -0400 Subject: shortcut for large amount of global var declarations? In-Reply-To: References: Message-ID: On 5/8/10, Jon Clements wrote: > On 8 May, 15:08, Alex Hall wrote: >> Hi all, >> I am sorry if this is the second message about this you get; I typed >> this and hit send (on gmail website) but I got a 404 error, so I am >> not sure if the previous message made it out or not. >> Anyway, I have about fifteen vars in a function which have to be >> global. Is there a faster and more space-efficient way of doing this >> than putting each var on its own line; that is, fifteen "global >> varName" declarations? Thanks. >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehg... at gmail.com;http://www.facebook.com/mehgcap > > About 15 that *need* to be global; smells bad to me. However, you can > amend a function's .func_globals attribute. How do you do this exactly? > Just wouldn't be going there myself. Why do you have this many? What's your > use case? They are in a "setOptions" function in config.py, which reads from an ini file and sets up all options for the program. All other files then can read these options. For example, anyone else can import config, then, if they are rounding a number, they can know how many places to round to by looking at config.rnd. I have everything in a function instead of being initialized upon importing since I offer a function to reload the ini file if the user changes something. Eventually I will have a gui for setting options, and that gui, to save options, will write an ini file then call setOptions so all options are then reset according to the newly created ini. If I do not make everything in setOptions global, no other file seems able to read it; I get an exception the first time another file tries to access a setting. Thanks. > > Jon. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From g.rodola at gmail.com Sat May 8 11:03:07 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Sat, 8 May 2010 17:03:07 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: <20100508160009.749631d9@pitrou.net> References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> <20100508160009.749631d9@pitrou.net> Message-ID: 2010/5/8 Antoine Pitrou : > On Sat, 8 May 2010 13:47:53 +0200 > Giampaolo Rodol? wrote: >> >> Assuming loop() function does something like this: >> >> ? ? ?... >> ? ? ?select.select(r, w, e, timeout) >> ? ? ?scheduler() ?# checks for scheduled calls to be fired >> ? ? ?... >> >> ...imagine a case where there's a connection (aka a dispatcher >> instance) which does not receive or send any data *and* a scheduled >> call which is supposed to be fired after, say, 5 seconds. >> The entire loop would hang on select.select() which won't return for >> 30 seconds because the socket is not ready for reading and/or writing >> resulting in scheduler() be called too late. > > Well, obviously you have to change the timeout based on the delay for > the next scheduled call. If your patch doesn't do that, it probably > needs fixing :) > > Regards > > Antoine. No it doesn't and I didn't consider this solution at the time. Thanks. =) --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From prologic at shortcircuit.net.au Sat May 8 11:13:17 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sun, 9 May 2010 01:13:17 +1000 Subject: shortcut for large amount of global var declarations? In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 12:08 AM, Alex Hall wrote: > Hi all, > I am sorry if this is the second message about this you get; I typed > this and hit send (on gmail website) but I got a 404 error, so I am > not sure if the previous message made it out or not. > Anyway, I have about fifteen vars in a function which have to be > global. Is there a faster and more space-efficient way of doing this > than putting each var on its own line; that is, fifteen "global > varName" declarations? Thanks. Using "globals" (global variables) is generally considered bad practise. Consider instead using a class/object. You could for example have a "config" object that is shared by other modules. cheers James From sridharr at activestate.com Sat May 8 11:34:36 2010 From: sridharr at activestate.com (Sridhar) Date: Sat, 08 May 2010 08:34:36 -0700 Subject: ActivePython - how to configure portable framework? In-Reply-To: References: Message-ID: <4BE5848C.3010606@activestate.com> Copy all the files in the ZIP to your USB stick and run INSTALLDIR\python.exe -srid On 5/7/2010 3:24 AM, balzer wrote: > I downloaded ActivePython-2.6.5.12-win32-x86.zip, it contains two > folders and 3 files: > > SystemFolder > INSTALLDIR > sh2.py > install.bat > _install.py > > Anyone know how to configure this Python environment as "portable > application" to work with it without installation, to set a > fully-functional Python environment that executes entirely from hard > drive (or USB stick) without leaving no registry entries, no mess with > windows system files, etc on machine it's run on. > > I created folder "Python", what files I should copy inside? > > thanks. From joncle at googlemail.com Sat May 8 13:04:30 2010 From: joncle at googlemail.com (Jon Clements) Date: Sat, 8 May 2010 10:04:30 -0700 (PDT) Subject: shortcut for large amount of global var declarations? References: Message-ID: <96ddcf17-4ee1-471a-9422-323b7063f926@24g2000yqy.googlegroups.com> On 8 May, 16:03, Alex Hall wrote: > On 5/8/10, Jon Clements wrote: > > > On 8 May, 15:08, Alex Hall wrote: > >> Hi all, > >> I am sorry if this is the second message about this you get; I typed > >> this and hit send (on gmail website) but I got a 404 error, so I am > >> not sure if the previous message made it out or not. > >> Anyway, I have about fifteen vars in a function which have to be > >> global. Is there a faster and more space-efficient way of doing this > >> than putting each var on its own line; that is, fifteen "global > >> varName" declarations? Thanks. > > >> -- > >> Have a great day, > >> Alex (msg sent from GMail website) > >> mehg... at gmail.com;http://www.facebook.com/mehgcap > > > About 15 that *need* to be global; smells bad to me. However, you can > > amend a function's .func_globals attribute. > > How do you do this exactly?> Just wouldn't be going there myself. Why do you have this many? What's your > > use case? > > They are in a "setOptions" function in config.py, which reads from an > ini file and sets up all options for the program. All other files then > can read these options. For example, anyone else can import config, > then, if they are rounding a number, they can know how many places to > round to by looking at config.rnd. I have everything in a function > instead of being initialized upon importing since I offer a function > to reload the ini file if the user changes something. Eventually I > will have a gui for setting options, and that gui, to save options, > will write an ini file then call setOptions so all options are then > reset according to the newly created ini. If I do not make everything > in setOptions global, no other file seems able to read it; I get an > exception the first time another file tries to access a setting. > Thanks. > > > > > Jon. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg... at gmail.com;http://www.facebook.com/mehgcap Umm, okay at least now we know the context. Similar to what James suggested just have a dict object in your config module called 'settings' or something and access that. I still prefer the "giveth rather than taketh" approach though. But heck, if it works, who cares? Jon. From pmaupin at gmail.com Sat May 8 13:14:18 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 10:14:18 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: On May 8, 3:37?am, Steven D'Aprano wrote: > On Fri, 07 May 2010 23:40:22 -0700, Patrick Maupin wrote: > > Personally, I believe that if anything is false and misleading, it is > > the attempt to try to completely change the discussion from MIT vs. GPL > > to GPL vs. no license (and thus very few rights for the software users), > > after first trying to imply that people who distribute software under > > permissive licenses (that give the user *more* rights than the GPL) are > > somehow creating a some sort of moral hazard that might adversely affect > > their users > > If encouraging third parties to take open source code and lock it up > behind proprietary, closed licences *isn't* a moral hazard, then I don't > know what one is. For a start, there is a difference between "encouraging" and "allowing". But in point of fact, you have it exactly backwards. Putting the code out there and making it a tort to republish it under a closed license creates a moral hazard -- a trap that many companies including Linksys/Cisco have fallen into. If I expect nothing in return, if it's a gift, then the likelihood of moral hazard is significantly reduced. Unless you are somehow suggesting that I owe my user's customers anything (which suggestion, btw, is frequently made in veiled terms, and always pisses me off), there is no other moral hazard produced by me choosing a permissive license for my code. > > So which is it? ?GPL good because a user can do more with the software > > than if he had no license, or MIT bad because a user can do more with > > the software than if it were licensed under GPL? > > Good or bad isn't just a matter of which gives you more freedoms, they're > also a matter of *what* freedoms they give. Weaponized ebola would allow > you to kill hundreds of millions of people in a matter of a few weeks, > but it takes a very special sort of mind to consider that the freedom to > bring about the extinction of the human race a "good". You're missing the context where Mr. Finney keeps changing what he's arguing about. I agree completely that different licenses are valid for different expectations, and said as much in my first post on this subject. But it's extremely silly to compare weaponized ebola to publishing free software, unless you want to give ammunition to those amoral profiteers who claim that it is so dangerous for hackers to give out source code at all that doing so should be criminalized. > I consider the freedom granted by the MIT licence for my users to take my > source code and lock it up behind restrictive licences (and therefore > *not* grant equivalent freedoms to their users in turn) to be a bad, not > a good. But in some cases it is a cost worth paying, primarily because > not all people who use MIT-licenced software go on to re-publish it under > a restrictive licence, but nevertheless won't consider the GPL (possibly > due to misunderstandings, confusion or political interference). "Political interference" is certainly the main reason that I won't use the GPL, but it is probably not the same politics you are thinking of. When I seriously consider investing in learning a piece of software so that I can make it part of my "toolbox," a major consideration is how well it plays with the other tools in my toolbox, and exactly which construction jobs I can use it on. RMS has managed to create a scenario where the GPL not only doesn't play nicely with some other licenses, but now doesn't even always play nicely with itself -- some people who liked GPL v2 but weren't willing to cede control of their future licensing terms to the FSF now have GPL v2 code that can't be linked to GPL v3 code. So, when a package is GPL licensed, for me it can create more contemplation about whether the package is worth dealing with or not. If the package is large, well-maintained, and standalone, and I'm just planning on being a user, the fact that it's GPL-licensed is not at all a negative. If I'm looking at two roughly equivalent programming toolkits, I will take the BSD/MIT one any day, because I know that when I learn it, I "own" it to the extent that I can use it on anything I want in any fashion in the future. Regards, Pat From dasacc22 at gmail.com Sat May 8 13:19:16 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sat, 8 May 2010 10:19:16 -0700 (PDT) Subject: Fastest way to calculate leading whitespace Message-ID: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Hi This is a simple question. I'm looking for the fastest way to calculate the leading whitespace (as a string, ie ' '). Here are some different methods I have tried so far --- solution 1 a = ' some content\n' b = a.strip() c = ' '*(len(a)-len(b)) --- solution 2 a = ' some content\n' b = a.strip() c = a.partition(b[0])[0] --- solution 3 def get_leading_whitespace(s): def _get(): for x in s: if x != ' ': break yield x return ''.join(_get()) --- Solution 1 seems to be about as fast as solution 2 except in certain circumstances where the value of b has already been determined for other purposes. Solution 3 is slower due to the function overhead. Curious to see what other types of solutions people might have. Thanks, Daniel From shashank.sunny.singh at gmail.com Sat May 8 13:33:39 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Sat, 8 May 2010 23:03:39 +0530 Subject: Fastest way to calculate leading whitespace In-Reply-To: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: On Sat, May 8, 2010 at 10:49 PM, dasacc22 wrote: > Hi > > This is a simple question. I'm looking for the fastest way to > calculate the leading whitespace (as a string, ie ' '). > > Here are some different methods I have tried so far > --- solution 1 > > a = ' some content\n' > b = a.strip() > c = ' '*(len(a)-len(b)) > use lstrip if you want to remove leading whitespaces only. strip removes trailing white spaces too > > --- solution 2 > > a = ' some content\n' > b = a.strip() > c = a.partition(b[0])[0] > > --- solution 3 > > def get_leading_whitespace(s): > def _get(): > for x in s: > if x != ' ': > break > yield x > return ''.join(_get()) > why do you need a generator (and as you mentioned the extra function call overheads)? How about this? def get_leading_whitespaces(s): count = 0 for c in s: if c != ' ': break count += 1 return ' ' * count > > --- > > Solution 1 seems to be about as fast as solution 2 except in certain > circumstances where the value of b has already been determined for > other purposes. Solution 3 is slower due to the function overhead. > > Curious to see what other types of solutions people might have. > > Thanks, > Daniel > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From dasacc22 at gmail.com Sat May 8 13:48:06 2010 From: dasacc22 at gmail.com (Daniel Skinner) Date: Sat, 8 May 2010 12:48:06 -0500 Subject: Fastest way to calculate leading whitespace In-Reply-To: References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: That solution actually runs slower then the generator method. On Sat, May 8, 2010 at 12:33 PM, Shashank Singh < shashank.sunny.singh at gmail.com> wrote: > > > On Sat, May 8, 2010 at 10:49 PM, dasacc22 wrote: > >> Hi >> >> This is a simple question. I'm looking for the fastest way to >> calculate the leading whitespace (as a string, ie ' '). >> >> Here are some different methods I have tried so far >> --- solution 1 >> >> a = ' some content\n' >> b = a.strip() >> c = ' '*(len(a)-len(b)) >> > > use lstrip if you want to remove leading whitespaces only. > strip removes trailing white spaces too > >> >> --- solution 2 >> >> a = ' some content\n' >> b = a.strip() >> c = a.partition(b[0])[0] >> >> --- solution 3 >> >> def get_leading_whitespace(s): >> def _get(): >> for x in s: >> if x != ' ': >> break >> yield x >> return ''.join(_get()) >> > > why do you need a generator (and as you mentioned the extra function call > overheads)? > > How about this? > > def get_leading_whitespaces(s): > count = 0 > for c in s: > if c != ' ': break > count += 1 > return ' ' * count > > >> >> --- >> >> Solution 1 seems to be about as fast as solution 2 except in certain >> circumstances where the value of b has already been determined for >> other purposes. Solution 3 is slower due to the function overhead. >> >> Curious to see what other types of solutions people might have. >> >> Thanks, >> Daniel >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > Regards > Shashank Singh > Senior Undergraduate, Department of Computer Science and Engineering > Indian Institute of Technology Bombay > shashank.sunny.singh at gmail.com > http://www.cse.iitb.ac.in/~shashanksingh > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dasacc22 at gmail.com Sat May 8 13:50:51 2010 From: dasacc22 at gmail.com (Daniel Skinner) Date: Sat, 8 May 2010 12:50:51 -0500 Subject: Fastest way to calculate leading whitespace In-Reply-To: References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: sorry, my mistake it runs faster (looking at the wrong line of code). But the first two solutions are still faster. On Sat, May 8, 2010 at 12:48 PM, Daniel Skinner wrote: > That solution actually runs slower then the generator method. > > > On Sat, May 8, 2010 at 12:33 PM, Shashank Singh < > shashank.sunny.singh at gmail.com> wrote: > >> >> >> On Sat, May 8, 2010 at 10:49 PM, dasacc22 wrote: >> >>> Hi >>> >>> This is a simple question. I'm looking for the fastest way to >>> calculate the leading whitespace (as a string, ie ' '). >>> >>> Here are some different methods I have tried so far >>> --- solution 1 >>> >>> a = ' some content\n' >>> b = a.strip() >>> c = ' '*(len(a)-len(b)) >>> >> >> use lstrip if you want to remove leading whitespaces only. >> strip removes trailing white spaces too >> >>> >>> --- solution 2 >>> >>> a = ' some content\n' >>> b = a.strip() >>> c = a.partition(b[0])[0] >>> >>> --- solution 3 >>> >>> def get_leading_whitespace(s): >>> def _get(): >>> for x in s: >>> if x != ' ': >>> break >>> yield x >>> return ''.join(_get()) >>> >> >> why do you need a generator (and as you mentioned the extra function call >> overheads)? >> >> How about this? >> >> def get_leading_whitespaces(s): >> count = 0 >> for c in s: >> if c != ' ': break >> count += 1 >> return ' ' * count >> >> >>> >>> --- >>> >>> Solution 1 seems to be about as fast as solution 2 except in certain >>> circumstances where the value of b has already been determined for >>> other purposes. Solution 3 is slower due to the function overhead. >>> >>> Curious to see what other types of solutions people might have. >>> >>> Thanks, >>> Daniel >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> >> -- >> Regards >> Shashank Singh >> Senior Undergraduate, Department of Computer Science and Engineering >> Indian Institute of Technology Bombay >> shashank.sunny.singh at gmail.com >> http://www.cse.iitb.ac.in/~shashanksingh >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Sat May 8 13:59:03 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 10:59:03 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: <5b36caaf-f1d6-47a5-ae0c-b11b0f3078b9@l28g2000yqd.googlegroups.com> On May 8, 12:19?pm, dasacc22 wrote: > Hi > > This is a simple question. I'm looking for the fastest way to > calculate the leading whitespace (as a string, ie ' ? ?'). > > Here are some different methods I have tried so far > --- solution 1 > > a = ' ? ?some content\n' > b = a.strip() > c = ' '*(len(a)-len(b)) > > --- solution 2 > > a = ' ? ?some content\n' > b = a.strip() > c = a.partition(b[0])[0] > > --- solution 3 > > def get_leading_whitespace(s): > ? ? def _get(): > ? ? ? ? for x in s: > ? ? ? ? ? ? if x != ' ': > ? ? ? ? ? ? ? ? break > ? ? ? ? ? ? yield x > ? ? return ''.join(_get()) > > --- > > Solution 1 seems to be about as fast as solution 2 except in certain > circumstances where the value of b has already been determined for > other purposes. Solution 3 is slower due to the function overhead. > > Curious to see what other types of solutions people might have. > > Thanks, > Daniel Well, you could try a solution using re, but that's probably only likely to be faster if you can use it on multiple concatenated lines. I usually use something like your solution #1. One thing to be aware of, though, is that strip() with no parameters will strip *any* whitespace, not just spaces, so the implicit assumption in your code that what you have stripped is spaces may not be justified (depending on the source data). OTOH, depending on how you use that whitespace information, it may not really matter. But if it does matter, you can use strip(' ') If speed is really an issue for you, you could also investigate mxtexttools, but, like re, it might perform better if the source consists of several batched lines. Regards, Pat From dasacc22 at gmail.com Sat May 8 14:16:49 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sat, 8 May 2010 11:16:49 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <5b36caaf-f1d6-47a5-ae0c-b11b0f3078b9@l28g2000yqd.googlegroups.com> Message-ID: On May 8, 12:59?pm, Patrick Maupin wrote: > On May 8, 12:19?pm, dasacc22 wrote: > > > > > > > Hi > > > This is a simple question. I'm looking for the fastest way to > > calculate the leading whitespace (as a string, ie ' ? ?'). > > > Here are some different methods I have tried so far > > --- solution 1 > > > a = ' ? ?some content\n' > > b = a.strip() > > c = ' '*(len(a)-len(b)) > > > --- solution 2 > > > a = ' ? ?some content\n' > > b = a.strip() > > c = a.partition(b[0])[0] > > > --- solution 3 > > > def get_leading_whitespace(s): > > ? ? def _get(): > > ? ? ? ? for x in s: > > ? ? ? ? ? ? if x != ' ': > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? yield x > > ? ? return ''.join(_get()) > > > --- > > > Solution 1 seems to be about as fast as solution 2 except in certain > > circumstances where the value of b has already been determined for > > other purposes. Solution 3 is slower due to the function overhead. > > > Curious to see what other types of solutions people might have. > > > Thanks, > > Daniel > > Well, you could try a solution using re, but that's probably only > likely to be faster if you can use it on multiple concatenated lines. > I usually use something like your solution #1. ?One thing to be aware > of, though, is that strip() with no parameters will strip *any* > whitespace, not just spaces, so the implicit assumption in your code > that what you have stripped is spaces may not be justified (depending > on the source data). ?OTOH, depending on how you use that whitespace > information, it may not really matter. ?But if it does matter, you can > use strip(' ') > > If speed is really an issue for you, you could also investigate > mxtexttools, but, like re, it might perform better if the source > consists of several batched lines. > > Regards, > Pat Hi, thanks for the info. Using .strip() to remove all whitespace in solution 1 is a must. If you only stripped ' ' spaces then line endings would get counted in the len() call and when multiplied against ' ', would produce an inaccurate result. Regex is significantly slower for my purposes but ive never heard of mxtexttools. Even if it proves slow its spurred my curiousity as to what functionality it provides (on an unrelated note) From mmanns at gmx.net Sat May 8 14:43:45 2010 From: mmanns at gmx.net (Martin Manns) Date: Sat, 8 May 2010 20:43:45 +0200 Subject: [ANN] Pyspread 0.1.1 released Message-ID: Pyspread 0.1.1 released ======================= I am pleased to announce the new release 0.1.1 of pyspread. About: ------ Pyspread is a cross-platform Python spreadsheet application. It is based on and written in the programming language Python. Instead of spreadsheet formulas, Python expressions are entered into the spreadsheet cells. Each expression returns a Python object that can be accessed from other cells. These objects can represent anything including lists or matrices. Pyspread runs on Linux and *nix platforms with GTK support as well as on Windows (XP and Vista tested). On Mac OS X, some icons are too small but the application basically works. Homepage -------- http://pyspread.sourceforge.net Changes to 0.1 -------------- * Grid is faster. * Copying only partly filled cells works now. * Cells that get attributes but no string no longer display None. Enjoy Martin From steve at REMOVE-THIS-cybersource.com.au Sat May 8 14:46:26 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 18:46:26 GMT Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: <4be5b182$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 10:19:16 -0700, dasacc22 wrote: > Hi > > This is a simple question. I'm looking for the fastest way to calculate > the leading whitespace (as a string, ie ' '). Is calculating the amount of leading whitespace really the bottleneck in your application? If not, then trying to shave off microseconds from something which is a trivial part of your app is almost certainly a waste of your time. [...] > a = ' some content\n' > b = a.strip() > c = ' '*(len(a)-len(b)) I take it that you haven't actually tested this code for correctness, because it's buggy. Let's test it: >>> leading_whitespace = " "*2 + "\t"*2 >>> a = leading_whitespace + "some non-whitespace text\n" >>> b = a.strip() >>> c = " "*(len(a)-len(b)) >>> assert c == leading_whitespace Traceback (most recent call last): File "", line 1, in AssertionError Not only doesn't it get the whitespace right, but it doesn't even get the *amount* of whitespace right: >>> assert len(c) == len(leading_whitespace) Traceback (most recent call last): File "", line 1, in AssertionError It doesn't even work correctly if you limit "whitespace" to mean spaces and nothing else! It's simply wrong in every possible way. This is why people say that premature optimization is the root of all (programming) evil. Instead of wasting time and energy trying to optimise code, you should make it correct first. Your solutions 2 and 3 are also buggy. And solution 3 can be easily re- written to be more straightforward. Instead of the complicated: > def get_leading_whitespace(s): > def _get(): > for x in s: > if x != ' ': > break > yield x > return ''.join(_get()) try this version: def get_leading_whitespace(s): accumulator = [] for c in s: if c in ' \t\v\f\r\n': accumulator.append(c) else: break return ''.join(accumulator) Once you're sure this is correct, then you can optimise it: def get_leading_whitespace(s): t = s.lstrip() return s[:len(s)-len(t)] >>> c = get_leading_whitespace(a) >>> assert c == leading_whitespace >>> Unless your strings are very large, this is likely to be faster than any other pure-Python solution you can come up with. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 8 14:47:32 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 18:47:32 GMT Subject: shortcut for large amount of global var declarations? References: Message-ID: <4be5b1c4$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 10:08:08 -0400, Alex Hall wrote: > Hi all, > I am sorry if this is the second message about this you get; I typed > this and hit send (on gmail website) but I got a 404 error, so I am not > sure if the previous message made it out or not. Anyway, I have about > fifteen vars in a function which have to be global. Is there a faster > and more space-efficient way of doing this than putting each var on its > own line; that is, fifteen "global varName" declarations? Thanks. global google, for_, global_, variables, considered, harmful -- Steven From dluzius at comcast.net Sat May 8 14:52:33 2010 From: dluzius at comcast.net (Dave Luzius) Date: Sat, 08 May 2010 18:52:33 GMT Subject: Need help with my 1st python program Message-ID: Pleaser help me with this. Here's a copy of the program, but it keeps calling for me to define pressure. # A small program to fetch local barometer reading from weather.com # and convert the value from metric to imperial. # My first attempt at Python. #-------------------------------------------------------------------- import urllib # next line does the fetching urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", pressure) # next line does the conversion to imperial imppress = 0.029875 * float(pressure) # next line shows the results. print imppress as you can see, I'm stuck on what should be relatively simple. TIA, Dave From benjamin at python.org Sat May 8 14:56:01 2010 From: benjamin at python.org (Benjamin Peterson) Date: Sat, 8 May 2010 13:56:01 -0500 Subject: [RELEASED] Python 2.7 beta 2 Message-ID: On behalf of the Python development team, I'm elated to announce the second beta release of Python 2.7. Python 2.7 is scheduled (by Guido and Python-dev) to be the last major version in the 2.x series. 2.7 will have an extended period of bugfix maintenance. 2.7 includes many features that were first released in Python 3.1. The faster io module, the new nested with statement syntax, improved float repr, set literals, dictionary views, and the memoryview object have been backported from 3.1. Other features include an ordered dictionary implementation, unittests improvements, a new sysconfig module, and support for ttk Tile in Tkinter. For a more extensive list of changes in 2.7, see http://doc.python.org/dev/whatsnew/2.7.html or Misc/NEWS in the Python distribution. To download Python 2.7 visit: http://www.python.org/download/releases/2.7/ While this is a development release and is thus not suitable for production use, we encourage Python application and library developers to test the release with their code and report any bugs they encounter to: http://bugs.python.org/ 2.7 documentation can be found at: http://docs.python.org/2.7/ Enjoy! -- Benjamin Peterson 2.7 Release Manager benjamin at python.org (on behalf of the entire python-dev team and 2.7's contributors) From steve at REMOVE-THIS-cybersource.com.au Sat May 8 14:58:41 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 18:58:41 GMT Subject: ConfigParser.get() defaults? References: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4be5b460$0$27798$c3e8da3@news.astraweb.com> On Fri, 07 May 2010 20:46:47 -0500, Tim Chase wrote: > On 05/07/2010 07:56 PM, Steven D'Aprano wrote: >> On Fri, 07 May 2010 15:05:53 -0500, Tim Chase wrote: >>> With a normal dictionary, I can specify a default fallback value in >>> the event the requested key isn't present: >> [...] >>> However, with the ConfigParser object, there doesn't seem to be any >>> way to do a similar >> >> Sounds like a nice feature to have. When you submit a patch (*grin*), > > I'm game to create and provide a patch, though I've had no success in > the past trying to push tweaks into the Python Core (adding a subclass > of optparse.HelpFormatter that respects newlines for text-wrapping). If your patch doesn't attract the interest of a Python-Dev developer, you might need to give them a prod occasionally. Their time for reviewing bugs and patches is always in short supply. > But if there's a straightforward way to do this, I'd love to patch the > file and submit the deltas. I just need to know > > - what sort of patch (unified diff, context diff, ed) > > - against which version? I'm currently running the 2.5 that Debian > Testing defaults to, though I have 2.6 available through my repository. > > - any tests needed/expected? run how? internal as an "if __name__ == > '__main__'" block, or an external test suite? > > - where (or to whom) to I submit the patch (and possibly tests) Submit the patch and tests to the bug tracker at http://bugs.python.org/ Look at the tests in (e.g.) /usr/local/lib/python2.6/test/ for an idea of what you should do. Because this is a new feature, and 2.5 (and 2.6?) are in bug fix only mode, you should probably aim for 2.7 or 3.2 as the ideal. Patches written against 2.6 or 3.1 are probably good enough though. And you want a unified diff. See also: http://www.python.org/dev/patches/ >> please make sure the caller can specify what to do on missing section >> and missing option independently. > > Could you detail what you envision here? For my use case, it's that the > option doesn't exist, whether because there's no section, or there's a > section but no option. Either way, something failed and I want a > default value back. I don't have a mental model of what you expect in > the "section exists but no option" that would behave differently from > the "section doesn't exist" case. > > Do you also have suggestions for how it should interact with the weird > [DEFAULT] section oddities (that don't really seem to default the way I > expect them to)? > > Perhaps the two interrelate? I haven't really given it any detailed thought, but what I was thinking was something like: config.set_missing_section("FOO") config.set_missing_value("missing") Then if you ask for the value of key 'x' in section BAR, and BAR doesn't exist, then 'x' is looked up in FOO instead; if 'x' doesn't exist there either, then "missing" is returned. If section BAR *does* exist, but 'x' doesn't, then "missing" is also returned. >>> I've thumbed through the source to ConfigParser.py but don't see any >>> indication that it's possible to do what I'd like short of wrapping >>> all my cp.get*() calls in try/except blocks or creating a forked >>> version of ConfigParser.py locally. Is there anything I'm missing, or >>> a better workaround to this? >> >> Don't fork the source code, that's ridiculously overkill. Subclass >> ConfigParser and add the required functionality. > > Sorry for such loaded terms -- my "forking" suggestion wasn't intended > to be Python, the Tim Version(tm), but rather, "copy the ConfigParser.py > into my project directory, make the edits I need/want, and have it > available to my project" (something similar to what I did for one of my > projects copying in the python2.6 zipfile.py to my python2.4 code-base > to supersede the standard 2.4 library's zipfile.py). That's what I thought you meant. Forking is the right term in this case (you are forking the ConfigParser module, not all of Python), and I still say it is overkill. Generally speaking, when a module doesn't do what you want, and modifying it isn't an option, there are five things you can do. In order of decreasing desirability: (1) Write a small wrapper function to tweak the behaviour. (2) Sub-class the class to gain new behaviour. (3) Monkey-patch the module at runtime. (4) Fork the module and modify that. (5) Re-write the whole thing from scratch. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 8 15:02:42 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 19:02:42 GMT Subject: Need help with my 1st python program References: Message-ID: <4be5b552$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 18:52:33 +0000, Dave Luzius wrote: > Pleaser help me with this. Here's a copy of the program, but it keeps > calling for me to define pressure. That's because you haven't defined pressure. When Python tells you there is a bug in your program, it is almost always correct. > # A small program to fetch local barometer reading from weather.com > # and convert the value from metric to imperial. > # My first attempt at Python. > #-------------------------------------------------------------------- > import urllib > > # next line does the fetching > urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", > pressure) What is pressure? It is an undefined name. Where does pressure get its value from? -- Steven From dluzius at comcast.net Sat May 8 15:13:12 2010 From: dluzius at comcast.net (Dave Luzius) Date: Sat, 08 May 2010 19:13:12 GMT Subject: Need help with my 1st python program References: <4be5b552$0$27798$c3e8da3@news.astraweb.com> Message-ID: On Sat, 08 May 2010 19:02:42 +0000, Steven D'Aprano wrote: > On Sat, 08 May 2010 18:52:33 +0000, Dave Luzius wrote: > >> Pleaser help me with this. Here's a copy of the program, but it keeps >> calling for me to define pressure. > > That's because you haven't defined pressure. > > When Python tells you there is a bug in your program, it is almost > always correct. > > >> # A small program to fetch local barometer reading from weather.com # >> and convert the value from metric to imperial. # My first attempt at >> Python. >> #-------------------------------------------------------------------- >> import urllib >> >> # next line does the fetching >> urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", >> pressure) > > What is pressure? It is an undefined name. Where does pressure get its > value from? Pressure is a term for barometric pressure, and is understood by Conky, which this program is designed to work with, and is understood by weather.com. But the value it passes to conky is metric, and I want it to display in imperial. What should I do.... From wolfram.hinderer at googlemail.com Sat May 8 15:15:22 2010 From: wolfram.hinderer at googlemail.com (Wolfram Hinderer) Date: Sat, 8 May 2010 12:15:22 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: On 8 Mai, 20:46, Steven D'Aprano wrote: > def get_leading_whitespace(s): > ? ? t = s.lstrip() > ? ? return s[:len(s)-len(t)] > > >>> c = get_leading_whitespace(a) > >>> assert c == leading_whitespace > > Unless your strings are very large, this is likely to be faster than any > other pure-Python solution you can come up with. Returning s[:-1 - len(t)] is faster. From wb4REMOVE_THIS_TEXT at wbrameld4.name Sat May 8 15:35:37 2010 From: wb4REMOVE_THIS_TEXT at wbrameld4.name (Walter Brameld IV) Date: Sat, 08 May 2010 15:35:37 -0400 Subject: Need help with my 1st python program In-Reply-To: References: <4be5b552$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4BE5BD09.2020908@wbrameld4.name> Dave Luzius wrote: > On Sat, 08 May 2010 19:02:42 +0000, Steven D'Aprano wrote: > >> On Sat, 08 May 2010 18:52:33 +0000, Dave Luzius wrote: >> >>> Pleaser help me with this. Here's a copy of the program, but it keeps >>> calling for me to define pressure. >> That's because you haven't defined pressure. >> >> When Python tells you there is a bug in your program, it is almost >> always correct. >> >> >>> # A small program to fetch local barometer reading from weather.com # >>> and convert the value from metric to imperial. # My first attempt at >>> Python. >>> #-------------------------------------------------------------------- >>> import urllib >>> >>> # next line does the fetching >>> urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", >>> pressure) >> What is pressure? It is an undefined name. Where does pressure get its >> value from? > > Pressure is a term for barometric pressure, and is understood by Conky, > which this program is designed to work with, and is understood by > weather.com. But the value it passes to conky is metric, and I want it to > display in imperial. > > What should I do.... You're passing in the value of pressure as the 'data' parameter to urllib.urlopen. So...what is the value of pressure? You haven't assigned any value to it before calling urlopen. Therein lies the problem. From steve at REMOVE-THIS-cybersource.com.au Sat May 8 15:38:52 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 19:38:52 GMT Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 10:14:18 -0700, Patrick Maupin wrote: > On May 8, 3:37?am, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 07 May 2010 23:40:22 -0700, Patrick Maupin wrote: >> > Personally, I believe that if anything is false and misleading, it is >> > the attempt to try to completely change the discussion from MIT vs. >> > GPL to GPL vs. no license (and thus very few rights for the software >> > users), after first trying to imply that people who distribute >> > software under permissive licenses (that give the user *more* rights >> > than the GPL) are somehow creating a some sort of moral hazard that >> > might adversely affect their users >> >> If encouraging third parties to take open source code and lock it up >> behind proprietary, closed licences *isn't* a moral hazard, then I >> don't know what one is. > > For a start, there is a difference between "encouraging" and "allowing". Finely parsed semantics with a meaningless difference when applied to what I said in the context of comparing GPL vs. more permissive licenses. > But in point of fact, you have it exactly backwards. Putting the code > out there and making it a tort to republish it under a closed license > creates a moral hazard -- a trap that many companies including > Linksys/Cisco have fallen into. What? That's crazy talk. You think Linksys and Cisco don't have people capable of reading licences? What sort of two-bit organisation do you think they are? They have lawyers, they have people whose job it is to make sure that they don't infringe other people's copyright. They wouldn't use software copyrighted by Microsoft without making sure they were legally licenced. One can only wonder why they thought they didn't need to treat the GPL with an equal amount of respect. Since you raised the analogy of a restaurant giving away freebies, if a restaurant stuck a sign on the door saying "Free softdrink with every burger", and some Cisco engineer walked in the door and started loading up a trolley with cans of drink from the fridge ("they're free, right?"), would you argue that this was the restaurant's fault for creating a moral hazard? I don't think you understand what a moral hazard is. Under no circumstances is it a moral hazard to say "If you do X, I will do Y" -- in this case, "If you obey these restrictions on redistribution, I'll licence this copyrighted work to you". Perhaps you should check the definition before arguing further that the GPL imposes a moral hazard on anyone: http://en.wikipedia.org/wiki/Moral_hazard > If I expect nothing in return, if it's > a gift, then the likelihood of moral hazard is significantly reduced. > Unless you are somehow suggesting that I owe my user's customers > anything (which suggestion, btw, is frequently made in veiled terms, and > always pisses me off), there is no other moral hazard produced by me > choosing a permissive license for my code. No, you don't *owe* them anything, but this brings us back to Ben's original post. If you care about the freedoms of Cisco's customers as much as you care about the freedoms of Cisco, then that's a good reason to grant those customers the same rights as you granted Cisco. And let's not forget self-interest -- if you care about *your own freedoms*, then it is in your own self-interest to encourage others to use open licences rather than closed ones. The MIT licence merely encourages openness by example, while the GPL makes it a legal requirement. Which brings us back full circle to Ben's position, which you took exception to. If the global freedoms granted by the GPL are sufficiently important to you, then you should use the GPL. If you have other factors which are more important, then choose another licence. Why you considered this controversial enough to require sarcastic comments about the untrustworthiness of Guido and the PSF, I don't know. -- Steven From benjamin.kaplan at case.edu Sat May 8 15:41:26 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 8 May 2010 15:41:26 -0400 Subject: Need help with my 1st python program In-Reply-To: References: <4be5b552$0$27798$c3e8da3@news.astraweb.com> Message-ID: On Sat, May 8, 2010 at 3:13 PM, Dave Luzius wrote: > > Pressure is a term for barometric pressure, and is understood by Conky, > which this program is designed to work with, and is understood by > weather.com. But the value it passes to conky is metric, and I want it to > display in imperial. > > What should I do.... > -- Don't tell us what pressure is. Tell Python. >>> urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", pressure) What do you think this line does? Because it does absolutely nothing. Assuming pressure is defined It creates a file-like object connected to that URL. But because that file-like object is never assigned to anything, it's reference count drops to 0 and it's immediately closed and deleted. You have to 1) Assign the file-like object to some name. 2) Read the data from the file-like object 3) convert the string you read from the file-like object into a float 4) use the float to do math Python is succinct, but it isn't magic. Just like every other programming language, it can't guess what you want it to do. From steve at REMOVE-THIS-cybersource.com.au Sat May 8 15:42:24 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 19:42:24 GMT Subject: Need help with my 1st python program References: <4be5b552$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4be5be9f$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 19:13:12 +0000, Dave Luzius wrote: >> What is pressure? It is an undefined name. Where does pressure get its >> value from? > > Pressure is a term for barometric pressure, and is understood by Conky, > which this program is designed to work with, and is understood by > weather.com. But the value it passes to conky is metric, and I want it > to display in imperial. I know what pressure is in English. What is it in your program? When the Python compiler sees the word "pressure", what do you expect it to do? > What should I do.... Perhaps you should start with a few simple tutorials and introductions to programming before tackling this program. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat May 8 15:46:56 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 May 2010 19:46:56 GMT Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 12:15:22 -0700, Wolfram Hinderer wrote: > On 8 Mai, 20:46, Steven D'Aprano > wrote: > >> def get_leading_whitespace(s): >> ? ? t = s.lstrip() >> ? ? return s[:len(s)-len(t)] >> >> >>> c = get_leading_whitespace(a) >> >>> assert c == leading_whitespace >> >> Unless your strings are very large, this is likely to be faster than >> any other pure-Python solution you can come up with. > > Returning s[:-1 - len(t)] is faster. I'm sure it is. Unfortunately, it's also incorrect. >>> z = "*****abcde" >>> z[:-1-5] '****' >>> z[:len(z)-5] '*****' However, s[:-len(t)] should be both faster and correct. -- Steven From vincent at vincentdavis.net Sat May 8 15:49:49 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Sat, 8 May 2010 13:49:49 -0600 Subject: Need help with my 1st python program In-Reply-To: <4BE5BD09.2020908@wbrameld4.name> References: <4be5b552$0$27798$c3e8da3@news.astraweb.com> <4BE5BD09.2020908@wbrameld4.name> Message-ID: I think what is not clear by what is being said is that you have passed in pressure and not 'pressure'. The first is undefined, pressure = 1 would define it. Where as 'pressure' is a string type. On Sat, May 8, 2010 at 1:35 PM, Walter Brameld IV < wb4REMOVE_THIS_TEXT at wbrameld4.name> wrote: > Dave Luzius wrote: > >> On Sat, 08 May 2010 19:02:42 +0000, Steven D'Aprano wrote: >> >> On Sat, 08 May 2010 18:52:33 +0000, Dave Luzius wrote: >>> >>> Pleaser help me with this. Here's a copy of the program, but it keeps >>>> calling for me to define pressure. >>>> >>> That's because you haven't defined pressure. >>> >>> When Python tells you there is a bug in your program, it is almost >>> always correct. >>> >>> >>> # A small program to fetch local barometer reading from weather.com # >>>> and convert the value from metric to imperial. # My first attempt at >>>> Python. >>>> #-------------------------------------------------------------------- >>>> import urllib >>>> >>>> # next line does the fetching >>>> urllib.urlopen("http://xoap.weather.com/weather/local/USMI0060", >>>> pressure) >>>> >>> What is pressure? It is an undefined name. Where does pressure get its >>> value from? >>> >> >> Pressure is a term for barometric pressure, and is understood by Conky, >> which this program is designed to work with, and is understood by >> weather.com. But the value it passes to conky is metric, and I want it to >> display in imperial. >> >> What should I do.... >> > > You're passing in the value of pressure as the 'data' parameter to > urllib.urlopen. So...what is the value of pressure? You haven't assigned > any value to it before calling urlopen. Therein lies the problem. > > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Sat May 8 16:05:21 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 13:05:21 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> Message-ID: <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> On May 8, 2:38?pm, Steven D'Aprano wrote: > I don't think you understand what a moral hazard is. Under no > circumstances is it a moral hazard to say "If you do X, I will do Y" -- > in this case, "If you obey these restrictions on redistribution, I'll > licence this copyrighted work to you". Perhaps you should check the > definition before arguing further that the GPL imposes a moral hazard on > anyone: > > http://en.wikipedia.org/wiki/Moral_hazard Well, definition is a tricky thing. Note that the wikipedia article is disputed. One definition of moral hazard is "The tendency of a person or entity that is imperfectly monitored to engage in undesirable behavior." Under this definition, Linksys apparently thought that the imperfect monitoring would let it get away with GPL violations. Certainly, even if Linksys as a corporation wasn't trying to get away with anything, their employees were improperly monitored, and getting a product out was more important than any potential copyright violation at the time (which shows there was a moral hazard their employees took advantage of under either the definition I gave or the wikipedia definition.) There are probably other companies (or employees of those companies) getting away with GPL violations right now -- certainly the risk of discovery if you just use a small portion of GPL code and don't distribute your source must be very small. There are certainly fewer companies getting away with MIT license violations, simply because the license is so much harder to violate. > > If I expect nothing in return, if it's > > a gift, then the likelihood of moral hazard is significantly reduced. > > Unless you are somehow suggesting that I owe my user's customers > > anything (which suggestion, btw, is frequently made in veiled terms, and > > always pisses me off), there is no other moral hazard produced by me > > choosing a permissive license for my code. > > No, you don't *owe* them anything, but this brings us back to Ben's > original post. If you care about the freedoms of Cisco's customers as > much as you care about the freedoms of Cisco, then that's a good reason > to grant those customers the same rights as you granted Cisco. But I *do* grant them the same rights -- they can come to my site and download my software!!! > And let's not forget self-interest -- if you care about *your own > freedoms*, then it is in your own self-interest to encourage others to > use open licences rather than closed ones. The MIT licence merely > encourages openness by example, while the GPL makes it a legal > requirement. But I *do* care about my own freedom. I thought I made that crystal clear. If I produce something under the MIT license, it's because I want to give it away with no strings. If I produce something under the GPL (that's not merely a small addendum to a preexisting project), it's probably going to be because I think it's pretty valuable stuff, maybe even valuable enough I might be able to make some money with it. If I'm going to use any prebuilt components, those *can't* be licensed under the GPL if I want to deliver the final package under the MIT license. Even if I'm using the GPL for my valuable software, my monetization options are more limited if I use a third party component that is licensed under the GPL, because I now don't have the viable option of dual-licensing. So, that gets back to my argument about what I like to see in a package I use, and how I license things according to what I would like see. For me, the golden rule dictates that when I give a gift of software, I release it under a permissive license. I realize that others see this differently. > Which brings us back full circle to Ben's position, which you took > exception to. If the global freedoms granted by the GPL are sufficiently > important to you, then you should use the GPL. If you have other factors > which are more important, then choose another licence. Why you considered > this controversial enough to require sarcastic comments about the > untrustworthiness of Guido and the PSF, I don't know. To me, the clear implication of the blanket statement that you have to use the GPL if you care at all about users is that anybody who doesn't use the GPL is uncaring. I think that's a silly attitude, and will always use any tool at hand, including sarcasm, to point out when other people try to impose their own narrow sense of morality on others by painting what I perceive to be perfectly normal, moral, decent, and legal behavior as somehow detrimental to the well-being of the species (honestly -- ebola???) Regards, Pat From rolf.oltmans at gmail.com Sat May 8 16:41:44 2010 From: rolf.oltmans at gmail.com (Oltmans) Date: Sat, 8 May 2010 13:41:44 -0700 (PDT) Subject: Kindly show me a better way to do it Message-ID: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Hi, I've a list that looks like following a = [ [1,2,3,4], [5,6,7,8] ] Currently, I'm iterating through it like for i in [k for k in a]: for a in i: print a but I was wondering if there is a shorter, more elegant way to do it? From python.list at tim.thechases.com Sat May 8 16:41:55 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 08 May 2010 15:41:55 -0500 Subject: ConfigParser.get() defaults? In-Reply-To: <4be5b460$0$27798$c3e8da3@news.astraweb.com> References: <4be4b6cf$0$27798$c3e8da3@news.astraweb.com> <4be5b460$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4BE5CC93.9060700@tim.thechases.com> On 05/08/2010 01:58 PM, Steven D'Aprano wrote: > If your patch doesn't attract the interest of a Python-Dev > developer, you might need to give them a prod occasionally. > Their time for reviewing bugs and patches is always in short > supply. > >> - where (or to whom) to I submit the patch (and possibly >> tests) > > Submit the patch and tests to the bug tracker at > http://bugs.python.org/ Okay -- a good first stop, and vastly more helpful than the non-reply I got regarding my optparse patch. >> - any tests needed/expected? run how? internal as an "if >> __name__ == '__main__'" block, or an external test suite? >> > Look at the tests in (e.g.) /usr/local/lib/python2.6/test/ for > an idea of what you should do. I poked in my Debian analogue (/usr/bin/lib/python2.6/test/) but the tests there seemed a bit...um...lacking? There was nothing testing ConfigParser at all, just three high-level test modules. Granted, I could create some tests that exercise my code, and perhaps some that should have been there in the first place, but that's a big jump from merely adding a couple tests (non)existing ConfigParser tests. > Because this is a new feature, and 2.5 (and 2.6?) are in bug fix only > mode, you should probably aim for 2.7 or 3.2 as the ideal. Patches > written against 2.6 or 3.1 are probably good enough though. Okay, I've submitted the patch to dev.python.org in the hopes something comes of it, even if it's 2.7 or 3.2 > That's what I thought you meant. Forking is the right term in this case > (you are forking the ConfigParser module, not all of Python), and I still > say it is overkill. Generally speaking, when a module doesn't do what you > want, and modifying it isn't an option, there are five things you can do. > In order of decreasing desirability: > > (1) Write a small wrapper function to tweak the behaviour. > > (2) Sub-class the class to gain new behaviour. > > (3) Monkey-patch the module at runtime. > > (4) Fork the module and modify that. > > (5) Re-write the whole thing from scratch. I'd say the ordering of your #3 and #4 are more ambiguous -- if I'm distributing/deploying a project and my monkey-patching gets broken (there's a reason monkey-patching feels dirty) by some python lib upgrade external to my control, then I & my code look bad. If I freeze a modified/locally-forked library module, it continues to work regardless of the environment. Maybe that's an indicator that I did a bad job of monkey patching, but I prefer to prevent breakage where I can. -tkc From dickinsm at gmail.com Sat May 8 16:46:59 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 May 2010 13:46:59 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> Message-ID: <489ffaa0-1563-45a1-93aa-cc83cdd6abd9@j35g2000yqm.googlegroups.com> On May 8, 8:46?pm, Steven D'Aprano wrote: > On Sat, 08 May 2010 12:15:22 -0700, Wolfram Hinderer wrote: > > On 8 Mai, 20:46, Steven D'Aprano > > wrote: > > >> def get_leading_whitespace(s): > >> ? ? t = s.lstrip() > >> ? ? return s[:len(s)-len(t)] > > >> >>> c = get_leading_whitespace(a) > >> >>> assert c == leading_whitespace > > >> Unless your strings are very large, this is likely to be faster than > >> any other pure-Python solution you can come up with. > > > Returning s[:-1 - len(t)] is faster. > > I'm sure it is. Unfortunately, it's also incorrect. > > >>> z = "*****abcde" > >>> z[:-1-5] > '****' > >>> z[:len(z)-5] > > '*****' > > However, s[:-len(t)] should be both faster and correct. Unless len(t) == 0, surely? -- Mark From utente at esempio.net Sat May 8 16:53:33 2010 From: utente at esempio.net (superpollo) Date: Sat, 08 May 2010 22:53:33 +0200 Subject: Kindly show me a better way to do it In-Reply-To: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> Oltmans ha scritto: > Hi, I've a list that looks like following > > a = [ [1,2,3,4], [5,6,7,8] ] > > Currently, I'm iterating through it like > > for i in [k for k in a]: > for a in i: i think you used te a identifier for two meanings... > print a > > but I was wondering if there is a shorter, more elegant way to do it? add = lambda a,b: a+b for i in reduce(add,a): print i From clp2 at rebertia.com Sat May 8 16:55:30 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 8 May 2010 13:55:30 -0700 Subject: Kindly show me a better way to do it In-Reply-To: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: On Sat, May 8, 2010 at 1:41 PM, Oltmans wrote: > Hi, I've a list that looks like following > > a = [ [1,2,3,4], [5,6,7,8] ] > > Currently, I'm iterating through it like > > for i in [k for k in a]: > ? ? ? ?for a in i: > ? ? ? ? ? ? ? ?print a > > but I was wondering if there is a shorter, more elegant way to do it? Just use a different variable name besides `a` in the nested loop so you don't have to make the copy of `a`. I arbitrarily chose `b`: for i in a: for b in i: print b Cheers, Chris -- http://blog.rebertia.com From utente at esempio.net Sat May 8 16:56:17 2010 From: utente at esempio.net (superpollo) Date: Sat, 08 May 2010 22:56:17 +0200 Subject: Kindly show me a better way to do it In-Reply-To: <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> Message-ID: <4be5cff2$0$815$4fafbaef@reader5.news.tin.it> superpollo ha scritto: > Oltmans ha scritto: >> Hi, I've a list that looks like following >> >> a = [ [1,2,3,4], [5,6,7,8] ] >> >> Currently, I'm iterating through it like >> >> for i in [k for k in a]: >> for a in i: > > i think you used te a identifier for two meanings... > >> print a >> >> but I was wondering if there is a shorter, more elegant way to do it? > > > add = lambda a,b: a+b or: from operator import add > for i in reduce(add,a): > print i From alain at dpt-info.u-strasbg.fr Sat May 8 16:56:25 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sat, 08 May 2010 22:56:25 +0200 Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: <87eihmxgcm.fsf@dpt-info.u-strasbg.fr> Oltmans writes: > a = [ [1,2,3,4], [5,6,7,8] ] > > Currently, I'm iterating through it like > > for i in [k for k in a]: > for a in i: > print a I would prefer: for i in a: for v in i: print v i.e., not messing with a and avoiding an additional list. > but I was wondering if there is a shorter, more elegant way to do it? I can't see any, but if you need to save space, you may use for v in (e for l in a for e in l): ... -- Alain. From tycho at tycho.ws Sat May 8 17:00:47 2010 From: tycho at tycho.ws (Tycho Andersen) Date: Sat, 8 May 2010 16:00:47 -0500 Subject: Kindly show me a better way to do it In-Reply-To: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: On Sat, May 8, 2010 at 3:41 PM, Oltmans wrote: > Hi, I've a list that looks like following > > a = [ [1,2,3,4], [5,6,7,8] ] > > Currently, I'm iterating through it like > > for i in [k for k in a]: > ? ? ? ?for a in i: > ? ? ? ? ? ? ? ?print a > > but I was wondering if there is a shorter, more elegant way to do it? How about itertools? In python 2.6: >>> a = [ [1,2,3,4], [5,6,7,8] ] >>> from itertools import chain >>> for i in chain(*a): ... print i ... 1 2 3 4 5 6 7 8 From rolf.oltmans at gmail.com Sat May 8 17:06:33 2010 From: rolf.oltmans at gmail.com (Oltmans) Date: Sat, 8 May 2010 14:06:33 -0700 (PDT) Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> Message-ID: <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> On May 9, 1:53?am, superpollo wrote: > add = lambda a,b: a+b > for i in reduce(add,a): > ? ? ?print i This is very neat. Thank you. Sounds like magic to me. Can you please explain how does that work? Many thanks again. From gd.usenet at spamfence.net Sat May 8 17:09:06 2010 From: gd.usenet at spamfence.net (=?UTF-8?Q?G=C3=BCnther?= Dietrich) Date: Sat, 08 May 2010 23:09:06 +0200 Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: Tycho Andersen wrote: >On Sat, May 8, 2010 at 3:41 PM, Oltmans wrote: >> Hi, I've a list that looks like following >> >> a = [ [1,2,3,4], [5,6,7,8] ] >> >> Currently, I'm iterating through it like >> >> for i in [k for k in a]: >> ? ? ? ?for a in i: >> ? ? ? ? ? ? ? ?print a >> >> but I was wondering if there is a shorter, more elegant way to do it? > >How about itertools? In python 2.6: > >>>> a = [ [1,2,3,4], [5,6,7,8] ] >>>> from itertools import chain >>>> for i in chain(*a): >... print i >... >1 >2 >3 >4 >5 >6 >7 >8 Why not this way? >>> a = [[1,2,3,4], [5,6,7,8]] >>> for i in a: ... for j in i: ... print(j) ... 1 2 3 4 5 6 7 8 Too simple? Best regards, G?nther From utente at esempio.net Sat May 8 17:10:43 2010 From: utente at esempio.net (superpollo) Date: Sat, 08 May 2010 23:10:43 +0200 Subject: Kindly show me a better way to do it In-Reply-To: <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> Message-ID: <4be5d354$0$815$4fafbaef@reader5.news.tin.it> Oltmans ha scritto: > On May 9, 1:53 am, superpollo wrote: > >> add = lambda a,b: a+b >> for i in reduce(add,a): >> print i > > This is very neat. Thank you. Sounds like magic to me. Can you please > explain how does that work? Many thanks again. > here: http://tinyurl.com/3xpdddd and here: http://tinyurl.com/39kdge5 bye From dasacc22 at gmail.com Sat May 8 17:27:32 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sat, 8 May 2010 14:27:32 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: U presume entirely to much. I have a preprocessor that normalizes documents while performing other more complex operations. Theres nothing buggy about what im doing On May 8, 1:46?pm, Steven D'Aprano wrote: > On Sat, 08 May 2010 10:19:16 -0700, dasacc22 wrote: > > Hi > > > This is a simple question. I'm looking for the fastest way to calculate > > the leading whitespace (as a string, ie ' ? ?'). > > Is calculating the amount of leading whitespace really the bottleneck in > your application? If not, then trying to shave off microseconds from > something which is a trivial part of your app is almost certainly a waste > of your time. > > [...] > > > a = ' ? ?some content\n' > > b = a.strip() > > c = ' '*(len(a)-len(b)) > > I take it that you haven't actually tested this code for correctness, > because it's buggy. Let's test it: > > >>> leading_whitespace = " "*2 + "\t"*2 > >>> a = leading_whitespace + "some non-whitespace text\n" > >>> b = a.strip() > >>> c = " "*(len(a)-len(b)) > >>> assert c == leading_whitespace > > Traceback (most recent call last): > ? File "", line 1, in > AssertionError > > Not only doesn't it get the whitespace right, but it doesn't even get the > *amount* of whitespace right: > > >>> assert len(c) == len(leading_whitespace) > > Traceback (most recent call last): > ? File "", line 1, in > AssertionError > > It doesn't even work correctly if you limit "whitespace" to mean spaces > and nothing else! It's simply wrong in every possible way. > > This is why people say that premature optimization is the root of all > (programming) evil. Instead of wasting time and energy trying to optimise > code, you should make it correct first. > > Your solutions 2 and 3 are also buggy. And solution 3 can be easily re- > written to be more straightforward. Instead of the complicated: > > > def get_leading_whitespace(s): > > ? ? def _get(): > > ? ? ? ? for x in s: > > ? ? ? ? ? ? if x != ' ': > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? yield x > > ? ? return ''.join(_get()) > > try this version: > > def get_leading_whitespace(s): > ? ? accumulator = [] > ? ? for c in s: > ? ? ? ? if c in ' \t\v\f\r\n': > ? ? ? ? ? ? accumulator.append(c) > ? ? ? ? else: > ? ? ? ? ? ? break > ? ? return ''.join(accumulator) > > Once you're sure this is correct, then you can optimise it: > > def get_leading_whitespace(s): > ? ? t = s.lstrip() > ? ? return s[:len(s)-len(t)] > > >>> c = get_leading_whitespace(a) > >>> assert c == leading_whitespace > > Unless your strings are very large, this is likely to be faster than any > other pure-Python solution you can come up with. > > -- > Steven From tycho at tycho.ws Sat May 8 17:40:05 2010 From: tycho at tycho.ws (Tycho Andersen) Date: Sat, 8 May 2010 16:40:05 -0500 Subject: Kindly show me a better way to do it In-Reply-To: References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: On Sat, May 8, 2010 at 4:09 PM, G?nther Dietrich wrote: [snip] > Too simple? No, not at all. I really only intended to point the OP to itertools, because it does lots of useful things exactly like this one. \t From pmaupin at gmail.com Sat May 8 18:18:00 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 15:18:00 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <5b36caaf-f1d6-47a5-ae0c-b11b0f3078b9@l28g2000yqd.googlegroups.com> Message-ID: On May 8, 1:16?pm, dasacc22 wrote: > On May 8, 12:59?pm, Patrick Maupin wrote: > > > > > On May 8, 12:19?pm, dasacc22 wrote: > > > > Hi > > > > This is a simple question. I'm looking for the fastest way to > > > calculate the leading whitespace (as a string, ie ' ? ?'). > > > > Here are some different methods I have tried so far > > > --- solution 1 > > > > a = ' ? ?some content\n' > > > b = a.strip() > > > c = ' '*(len(a)-len(b)) > > > > --- solution 2 > > > > a = ' ? ?some content\n' > > > b = a.strip() > > > c = a.partition(b[0])[0] > > > > --- solution 3 > > > > def get_leading_whitespace(s): > > > ? ? def _get(): > > > ? ? ? ? for x in s: > > > ? ? ? ? ? ? if x != ' ': > > > ? ? ? ? ? ? ? ? break > > > ? ? ? ? ? ? yield x > > > ? ? return ''.join(_get()) > > > > --- > > > > Solution 1 seems to be about as fast as solution 2 except in certain > > > circumstances where the value of b has already been determined for > > > other purposes. Solution 3 is slower due to the function overhead. > > > > Curious to see what other types of solutions people might have. > > > > Thanks, > > > Daniel > > > Well, you could try a solution using re, but that's probably only > > likely to be faster if you can use it on multiple concatenated lines. > > I usually use something like your solution #1. ?One thing to be aware > > of, though, is that strip() with no parameters will strip *any* > > whitespace, not just spaces, so the implicit assumption in your code > > that what you have stripped is spaces may not be justified (depending > > on the source data). ?OTOH, depending on how you use that whitespace > > information, it may not really matter. ?But if it does matter, you can > > use strip(' ') > > > If speed is really an issue for you, you could also investigate > > mxtexttools, but, like re, it might perform better if the source > > consists of several batched lines. > > > Regards, > > Pat > > Hi, > > thanks for the info. Using .strip() to remove all whitespace in > solution 1 is a must. If you only stripped ' ' spaces then line > endings would get counted in the len() call and when multiplied > against ' ', would produce an inaccurate result. Regex is > significantly slower for my purposes but ive never heard of > mxtexttools. Even if it proves slow its spurred my curiousity as to > what functionality it provides (on an unrelated note) Could you reorganize your code to do multiple lines at a time? That might make regex competitive. Regards, Pat From nathan.alexander.rice at gmail.com Sat May 8 18:31:26 2010 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Sat, 8 May 2010 18:31:26 -0400 Subject: Kindly show me a better way to do it In-Reply-To: References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: itertools is also written in c, so if you're working with a big nested list is long it will be a lot faster. On Sat, May 8, 2010 at 5:40 PM, Tycho Andersen wrote: > On Sat, May 8, 2010 at 4:09 PM, G?nther Dietrich > wrote: > [snip] > > Too simple? > > No, not at all. I really only intended to point the OP to itertools, > because it does lots of useful things exactly like this one. > > \t > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat May 8 19:29:07 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 09 May 2010 00:29:07 +0100 Subject: how to play a sound file repeatedly in loop In-Reply-To: References: Message-ID: <4BE5F3C3.7030206@mrabarnett.plus.com> varnikat t wrote: > > How to run sound file repeatedly in loop ? > > When I do this, it does nothing and terminates: > > import pygst > pygst.require("0.10") > import gst, gtk > > > n=0 > > while n<10: > player = gst.element_factory_make("playbin2", "player") > player.set_property("uri", "file:/home/varnika/hello.ogg") > player.set_state(gst.STATE_PLAYING) > n=n+1 > It's not doing nothing, it's repeatedly making a player, starting it, and then on the next iteration making another player and starting it. The line: player.set_state(gst.STATE_PLAYING) doesn't wait until the sound file has finished before returning. From pavlovevidence at gmail.com Sat May 8 19:39:33 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 8 May 2010 16:39:33 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: On May 6, 4:56?pm, Ben Finney wrote: > a... at pythoncraft.com (Aahz) writes: > > In article <4BE05D75.7030... at msn.com>, > > Rouslan Korneychuk ? wrote: > > > >The only question I have now is what about licensing? Is that > > >something I need to worry about? Should I go with LGPL, MIT, or > > >something else? > > > Which license you use depends partly on your political philosophy. > > Yes. > > Unless you place such a low value the freedom of your users that you'd > allow proprietary derivatives of your work to remove the freedoms you've > taken care to grant, then you should choose a copyleft license like the > GPL. GPL is about fighting a holy war against commercial software. People who esteem their users give them freedom to use software however they see fit, including combining it with proprietary software. Carl Banks From thomasstruth at gmail.com Sat May 8 19:50:11 2010 From: thomasstruth at gmail.com (ben) Date: Sat, 8 May 2010 16:50:11 -0700 (PDT) Subject: accessing superclass methods from subclass Message-ID: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Why doesn't this work: class C1: def f1(self): print("f1") class C2(C1): f1() It throws this error: Traceback (most recent call last): File "./c1.py", line 7, in class C2(C1): File "./c1.py", line 8, in C2 f1() NameError: name 'f1' is not defined f1() is an attribute of class C1, C2 inherits C1, so why can't it see it? thanks! From clp2 at rebertia.com Sat May 8 20:05:44 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 8 May 2010 17:05:44 -0700 Subject: accessing superclass methods from subclass In-Reply-To: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: On Sat, May 8, 2010 at 4:50 PM, ben wrote: > Why doesn't this work: > > class C1: > ? ?def f1(self): > ? ? ? ?print("f1") > > class C2(C1): > ? ?f1() > > > It throws this error: > > Traceback (most recent call last): > ?File "./c1.py", line 7, in > ? ?class C2(C1): > ?File "./c1.py", line 8, in C2 > ? ?f1() > NameError: name 'f1' is not defined > > > f1() is an attribute of class C1, C2 inherits C1, so why can't it see > it? The way classes work in Python, C2 isn't actually created until after its body suite has been executed, so that's why Python can't find f1. Additionally, it makes no sense to call an *instance* method such as f1() in a class context. Or in Java-speak: you can't call a non-static method in a static context. Cheers, Chris -- http://blog.rebertia.com From python at mrabarnett.plus.com Sat May 8 20:13:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 09 May 2010 01:13:18 +0100 Subject: accessing superclass methods from subclass In-Reply-To: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: <4BE5FE1E.5070809@mrabarnett.plus.com> ben wrote: > Why doesn't this work: > > class C1: > def f1(self): > print("f1") > > class C2(C1): > f1() > > > It throws this error: > > Traceback (most recent call last): > File "./c1.py", line 7, in > class C2(C1): > File "./c1.py", line 8, in C2 > f1() > NameError: name 'f1' is not defined > > > f1() is an attribute of class C1, C2 inherits C1, so why can't it see > it? > Name lookup works differently from some other languages. You need to be explicit and tell it where 'f1' is defined: C1.f1() However, that will raise a different exception. I don't know what you're trying to do. From aahz at pythoncraft.com Sat May 8 20:36:51 2010 From: aahz at pythoncraft.com (Aahz) Date: 8 May 2010 17:36:51 -0700 Subject: Picking a license References: <87k4rgfutu.fsf@benfinney.id.au> Message-ID: In article , Carl Banks wrote: > >GPL is about fighting a holy war against commercial software. And really, that's a Good Thing. We wouldn't have Python, to some extent, were it not for Stallman and his crusade. That doesn't mean we should slavishly worship him, though. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From ben+python at benfinney.id.au Sat May 8 21:41:11 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 09 May 2010 11:41:11 +1000 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> Message-ID: <87fx21ets8.fsf@benfinney.id.au> Patrick Maupin writes: > On May 8, 2:38?pm, Steven D'Aprano cybersource.com.au> wrote: > > Which brings us back full circle to Ben's position, which you took > > exception to. [?] > To me, the clear implication of the blanket statement that you have to > use the GPL if you care at all about users is that anybody who doesn't > use the GPL is uncaring. I think that's a silly attitude [?] Fortunately, neither that silly blanket statement nor its implication are represented in any of my messages in this thread. I hope that helps. -- \ ?I've always wanted to be somebody, but I see now that I should | `\ have been more specific.? ?Jane Wagner, via Lily Tomlin | _o__) | Ben Finney From ben+python at benfinney.id.au Sat May 8 21:42:11 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 09 May 2010 11:42:11 +1000 Subject: Picking a license References: <87k4rgfutu.fsf@benfinney.id.au> Message-ID: <87bpcpetqk.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > In article , > Carl Banks wrote: > > > >GPL is about fighting a holy war against commercial software. > > And really, that's a Good Thing. We wouldn't have Python, to some > extent, were it not for Stallman and his crusade. That doesn't mean we > should slavishly worship him, though. +1. -- \ ?A child of five could understand this. Fetch me a child of | `\ five.? ?Groucho Marx | _o__) | Ben Finney From pmaupin at gmail.com Sat May 8 22:34:24 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 19:34:24 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <87fx21ets8.fsf@benfinney.id.au> Message-ID: On May 8, 8:41?pm, Ben Finney wrote: > Patrick Maupin writes: > > On May 8, 2:38?pm, Steven D'Aprano > cybersource.com.au> wrote: > > > Which brings us back full circle to Ben's position, which you took > > > exception to. > > [?] > > > To me, the clear implication of the blanket statement that you have to > > use the GPL if you care at all about users is that anybody who doesn't > > use the GPL is uncaring. ?I think that's a silly attitude [?] > > Fortunately, neither that silly blanket statement nor its implication > are represented in any of my messages in this thread. Hmm, I must have misunderstood this: "Unless you place such a low value the freedom of your users that you'd allow proprietary derivatives of your work to remove the freedoms you've taken care to grant, then you should choose a copyleft license like the GPL." To me, placing "such a low value on the freedom of [my] users" sounds like I'm ready to consign them to slavery or something, so I certainly originally viewed this as a "blanket" (e.g. unqualified) "statement" (well, that should be obvious) that I have to use the GPL "if [I] care at all about [my] users". > I hope that helps. Well, perhaps you meant less by your wording of "a low value on the freedom" than could be read into it, just as Aahz and I meant less by "forced" than you apparently read into that. I think we all have more or less accurate understandings of the differences between GPL and permissive licenses, but only disagree somewhat on how important the various features are, and at the end of the day we all come to some reasonably nuanced view of how to proceed with our projects. One thing I realized that I didn't cover in my earlier posts is that I think that for a lot of library-type projects, LGPL v2.1 is a really fine license, offering a great balance of competing interests. I view the new licensing on QT from Nokia (commercial, GPL v3, or LGPL v2.1) as a good example of a balanced strategy. Regards, Pat From timr at probo.com Sat May 8 22:47:33 2010 From: timr at probo.com (Tim Roberts) Date: Sat, 08 May 2010 19:47:33 -0700 Subject: Cross-platform file paths References: Message-ID: <1e8cu5tcvl87979vq5r0mecos28m9vat6v@4ax.com> utabintarbo wrote: > >Until now, I have used the UNC under Windows (XP) to allow my program >to access files located on a Samba-equipped *nix box (eg. >os.path.normpath(r"\\serverFQDN\sharename\dir\filename")). When I try >to open this file under Linux (Red Hat 5), I get a file not found >error. > >Is there a cross-platform method for accessing files on a network >share using Python 2.X? No. On Linux, you need to mount the share in some empty directory (using mount or smbmount), then read the files from that directory. It's kind of odd to use a Windows network protocol to access a Linux file system from another Linux machine. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From no.email at nospam.invalid Sat May 8 22:58:48 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 19:58:48 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: <7x39y1vl07.fsf@ruckus.brouhaha.com> Carl Banks writes: > People who esteem their users give them freedom to use software > however they see fit, including combining it with proprietary > software. Huh???? That makes no sense at all. Why should a standard like that be expected from free software developers, when it isn't expected from the makers of the proprietary software who you're proposing deserve to rake in big bucks from locking up other people's work that they didn't pay for? I've got no problem writing stuff for inclusion in proprietary products. But I do that as a professional, which means I expect to get paid for it. And I think you have the "esteem" issue backwards. Users who esteem developers who write and share software for community benefit, should not whine and pout that the largesse doesn't extend as far as inviting monopolistic corporations to lock it away from further sharing. From no.email at nospam.invalid Sat May 8 23:03:32 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 20:03:32 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: <7xy6ftu67v.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > I fail to see what is morally wrong with it. When I ,as the author, > share my work to the public, I should have made peace with the fact > that I, for all intends and purposes, lost control over its use. Does the same thing apply to Microsoft? If I get a copy of MS Office, do you think I should be able to incorporate its code into my own products for repackaging and sale any way that I want, without their having any say? If not, why should Microsoft be entitled to do that with software that -I- write? Is there something in the water making people think these inequitable things? If Microsoft's licenses are morally respectable then so is the GPL. From no.email at nospam.invalid Sat May 8 23:12:47 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 20:12:47 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> Message-ID: <7xtyqhu5sg.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > For the record, I've published software under an MIT licence because I > judged the cost of the moral hazard introduced by encouraging freeloaders > to be less than the benefits of having a more permissive licence that > encourages freeloading and therefore attracts more users. For other > software, I might judge that the cost/benefit ratio falls in a different > place, and hence choose the GPL. I don't know if it counts as a moral hazard but some programmers simply don't want to do proprietary product development for free. That's why Linux (GPL) has far more developers (and consequentially far more functionality and more users) than the free versions of BSD, and GCC (GPL) has far more developers than Python. Of course the BSD license did allow Bill Gates and Steve Jobs to become billionaires off the work off the developers who actually wrote the Berkeley code and are now struggling to make their rent. But at least those developers can be proud that the Microsoft and Apple DRM empires benefited so much from their efforts. THAT's a level of self-sacrifice that I can do without. Note, "permissive license" is a Microsoft propaganda term from what I can tell. "Forbidding forbidden" is how I like to think of the GPL. From thomasstruth at gmail.com Sat May 8 23:24:28 2010 From: thomasstruth at gmail.com (ben) Date: Sat, 8 May 2010 20:24:28 -0700 (PDT) Subject: accessing superclass methods from subclass References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: Ok, thanks for the info. What would be a better way to do this? What I'm trying to do is treat things in a reasonable OOP manner (all fairly new to me, esp. in Python). Here's a made-up example with a little more context. Let's say you're making a drawing program that can draw various shapes. So in the interest of not repeating oneself, I want a class Shape that handles everything that shapes have, such as a color, and a location. Then I can subclass Shape to create Square, which has code specific to drawing a square (e.g. 4 equal sides). So, like this: class Shape: x = 0 y = 0 def setColor(self,color): self.color = color def setLocation(self,x,y): self.x = x self.y = y def getLocation(self): return [self.x,self.y] class Square(Shape): size = 0 def __init__(self,size): self.size = size def draw(self): location = getLocation() # code to draw shape from location[0],location[1] at size size # etc... It seems to me that you would want the location code handled in the Shape class so that I'm not rewriting it for Circle, Triangle, etc., but I'm not allowed to call any of those methods from the subclass. I must be thinking of this in the wrong way. Help? thanks! On May 8, 7:05?pm, Chris Rebert wrote: > On Sat, May 8, 2010 at 4:50 PM, ben wrote: > > Why doesn't this work: > > > class C1: > > ? ?def f1(self): > > ? ? ? ?print("f1") > > > class C2(C1): > > ? ?f1() > > > It throws this error: > > > Traceback (most recent call last): > > ?File "./c1.py", line 7, in > > ? ?class C2(C1): > > ?File "./c1.py", line 8, in C2 > > ? ?f1() > > NameError: name 'f1' is not defined > > > f1() is an attribute of class C1, C2 inherits C1, so why can't it see > > it? > > The way classes work in Python, C2 isn't actually created until after > its body suite has been executed, so that's why Python can't find f1. > > Additionally, it makes no sense to call an *instance* method such as > f1() in a class context. Or in Java-speak: you can't call a non-static > method in a static context. > > Cheers, > Chris > --http://blog.rebertia.com From 1 at depikt.net Sat May 8 23:33:14 2010 From: 1 at depikt.net (3Jane) Date: Sat, 8 May 2010 20:33:14 -0700 (PDT) Subject: A more general solution Message-ID: <44e7ce5a-6ec3-460e-9f36-05762ebe59b0@i9g2000yqi.googlegroups.com> You could interpret [[1,2,3,4],[5,6,7,8]] as a tree and your task as traversal of its leaves. All solutions before would not work with trees with bigger height. Here is how to traverse such trees recursively: def eventualPrint(x): for v in x: if isinstance(v, list): eventualPrint(x) else: print(v) Then eventualPrint(a) does the job. This would only cope with lists as proper nodes. More general tests than isinstance() could be tried, hasattr(x, 'getitem') would match all sequence types for example. Also "for v in x:" should perhaps tested for exceptions. Optimal directives for both alternatives depend on the scope of the code's purpose. As often the price for generality is performance here. Good luck, Joost From robert.kern at gmail.com Sat May 8 23:38:00 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 08 May 2010 22:38:00 -0500 Subject: Picking a license In-Reply-To: <7xy6ftu67v.fsf@ruckus.brouhaha.com> References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> Message-ID: On 2010-05-08 22:03 , Paul Rubin wrote: > "Martin P. Hellwig" writes: >> I fail to see what is morally wrong with it. When I ,as the author, >> share my work to the public, I should have made peace with the fact >> that I, for all intends and purposes, lost control over its use. > > Does the same thing apply to Microsoft? If I get a copy of MS Office, > do you think I should be able to incorporate its code into my own > products for repackaging and sale any way that I want, without their > having any say? If not, why should Microsoft be entitled to do that > with software that -I- write? Martin is not saying that you *ought* to release your code under a liberal license. He is only saying that he does not believe he is inviting moral hazard when *he* decides to release *his* code under a liberal license. He was responding to Steven who was claiming otherwise. > Is there something in the water making > people think these inequitable things? Is there something in the water making people think that every statement of opinion about how one licenses one's own code is actually an opinion about how everyone should license their code? > If Microsoft's licenses are > morally respectable then so is the GPL. Martin is not saying that the GPL is not morally respectable. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Sat May 8 23:44:21 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 08 May 2010 22:44:21 -0500 Subject: Picking a license In-Reply-To: <7xtyqhu5sg.fsf@ruckus.brouhaha.com> References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> Message-ID: On 2010-05-08 22:12 , Paul Rubin wrote: > Steven D'Aprano writes: >> For the record, I've published software under an MIT licence because I >> judged the cost of the moral hazard introduced by encouraging freeloaders >> to be less than the benefits of having a more permissive licence that >> encourages freeloading and therefore attracts more users. For other >> software, I might judge that the cost/benefit ratio falls in a different >> place, and hence choose the GPL. > > I don't know if it counts as a moral hazard but some programmers simply > don't want to do proprietary product development for free. That's why > Linux (GPL) has far more developers (and consequentially far more > functionality and more users) than the free versions of BSD, and GCC > (GPL) has far more developers than Python. Post hoc ergo propter hoc? Show me some controlled studies demonstrating that this is actually the causative agent in these cases, then maybe I'll believe you. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From clp2 at rebertia.com Sat May 8 23:44:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 8 May 2010 20:44:59 -0700 Subject: accessing superclass methods from subclass In-Reply-To: References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: > On May 8, 7:05?pm, Chris Rebert wrote: >> On Sat, May 8, 2010 at 4:50 PM, ben wrote: >> > Why doesn't this work: >> >> > class C1: >> > ? ?def f1(self): >> > ? ? ? ?print("f1") >> >> > class C2(C1): >> > ? ?f1() >> >> > It throws this error: >> >> > Traceback (most recent call last): >> > ?File "./c1.py", line 7, in >> > ? ?class C2(C1): >> > ?File "./c1.py", line 8, in C2 >> > ? ?f1() >> > NameError: name 'f1' is not defined >> >> > f1() is an attribute of class C1, C2 inherits C1, so why can't it see >> > it? >> >> The way classes work in Python, C2 isn't actually created until after >> its body suite has been executed, so that's why Python can't find f1. >> >> Additionally, it makes no sense to call an *instance* method such as >> f1() in a class context. Or in Java-speak: you can't call a non-static >> method in a static context. On Sat, May 8, 2010 at 8:24 PM, ben wrote: > Ok, thanks for the info. > > What would be a better way to do this? What I'm trying to do is treat > things in a reasonable OOP manner (all fairly new to me, esp. in > Python). Here's a made-up example with a little more context. Let's > say you're making a drawing program that can draw various shapes. So > in the interest of not repeating oneself, I want a class Shape that > handles everything that shapes have, such as a color, and a location. > Then I can subclass Shape to create Square, which has code specific to > drawing a square (e.g. 4 equal sides). So, like this: > > class Shape: > > x = 0 > y = 0 > > def setColor(self,color): > self.color = color > > def setLocation(self,x,y): > self.x = x > self.y = y > > def getLocation(self): > return [self.x,self.y] > > class Square(Shape): > > size = 0 > > def __init__(self,size): > self.size = size > > def draw(self): > location = getLocation() > # code to draw shape from location[0],location[1] at size size > # etc... > > It seems to me that you would want the location code handled in the > Shape class so that I'm not rewriting it for Circle, Triangle, etc., > but I'm not allowed to call any of those methods from the subclass. I > must be thinking of this in the wrong way. Help? Your code suggests you need to read a tutorial on Python's object-oriented features. The relevant part of Python's official tutorial is http://docs.python.org/tutorial/classes.html For starters, Python is not Java and getters/setters are not usually necessary nor Pythonic; see http://dirtsimple.org/2004/12/python-is-not-java.html Secondly, Python does not have instance variable declarations; doing `x = 0` at the class-level creates a static/class variable, it *does not* declare an instance variable. Thirdly, to call an instance method such as getLocation, you need to specify the receiver, i.e. `self.getLocation()`, not merely `getLocation()` Here is how I would rewrite your example: class Shape(object): def __init__(self, x=0, y=0): self.x = x self.y = y @property def location(self): return (self.x, self.y) @location.setter def location(self, val): self.x, self.y = val class Square(Shape): def __init__(self,size): super(Square, self).__init__() self.size = size def draw(self): x, y = self.location # code to draw shape from location[0],location[1] at size size # etc... This uses some minor magic involving property(), see http://docs.python.org/library/functions.html#property for how that works. Cheers, Chris -- http://blog.rebertia.com From dasacc22 at gmail.com Sat May 8 23:48:36 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sat, 8 May 2010 20:48:36 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <5b36caaf-f1d6-47a5-ae0c-b11b0f3078b9@l28g2000yqd.googlegroups.com> Message-ID: <69fb31dc-f5f8-4fc7-bb47-5e60e92e6485@24g2000yqy.googlegroups.com> On May 8, 5:18?pm, Patrick Maupin wrote: > On May 8, 1:16?pm, dasacc22 wrote: > > > > > > > On May 8, 12:59?pm, Patrick Maupin wrote: > > > > On May 8, 12:19?pm, dasacc22 wrote: > > > > > Hi > > > > > This is a simple question. I'm looking for the fastest way to > > > > calculate the leading whitespace (as a string, ie ' ? ?'). > > > > > Here are some different methods I have tried so far > > > > --- solution 1 > > > > > a = ' ? ?some content\n' > > > > b = a.strip() > > > > c = ' '*(len(a)-len(b)) > > > > > --- solution 2 > > > > > a = ' ? ?some content\n' > > > > b = a.strip() > > > > c = a.partition(b[0])[0] > > > > > --- solution 3 > > > > > def get_leading_whitespace(s): > > > > ? ? def _get(): > > > > ? ? ? ? for x in s: > > > > ? ? ? ? ? ? if x != ' ': > > > > ? ? ? ? ? ? ? ? break > > > > ? ? ? ? ? ? yield x > > > > ? ? return ''.join(_get()) > > > > > --- > > > > > Solution 1 seems to be about as fast as solution 2 except in certain > > > > circumstances where the value of b has already been determined for > > > > other purposes. Solution 3 is slower due to the function overhead. > > > > > Curious to see what other types of solutions people might have. > > > > > Thanks, > > > > Daniel > > > > Well, you could try a solution using re, but that's probably only > > > likely to be faster if you can use it on multiple concatenated lines. > > > I usually use something like your solution #1. ?One thing to be aware > > > of, though, is that strip() with no parameters will strip *any* > > > whitespace, not just spaces, so the implicit assumption in your code > > > that what you have stripped is spaces may not be justified (depending > > > on the source data). ?OTOH, depending on how you use that whitespace > > > information, it may not really matter. ?But if it does matter, you can > > > use strip(' ') > > > > If speed is really an issue for you, you could also investigate > > > mxtexttools, but, like re, it might perform better if the source > > > consists of several batched lines. > > > > Regards, > > > Pat > > > Hi, > > > thanks for the info. Using .strip() to remove all whitespace in > > solution 1 is a must. If you only stripped ' ' spaces then line > > endings would get counted in the len() call and when multiplied > > against ' ', would produce an inaccurate result. Regex is > > significantly slower for my purposes but ive never heard of > > mxtexttools. Even if it proves slow its spurred my curiousity as to > > what functionality it provides (on an unrelated note) > > Could you reorganize your code to do multiple lines at a time? ?That > might make regex competitive. > > Regards, > Pat I have tried this already, the problem here is that it's not a trivial matter. Iterating over each line is unavoidable, and I found that using various python builtins to perform string operations (like say the wonderful partition builtin) during each iteration works 3 fold faster then regexing the entire document with various needs. Another issue is having to keep a line count and when iterating over regex matches and counting lines, it doesn't scale nearly as well as a straight python solution using builtins to process the information. At the heart of this here, determining the leading white-space is a trivial matter. I have much more complex problems to deal with. I was much more interested in seeing what kind of solutions ppl would come up with to such a problem, and perhaps uncover something new in python that I can apply to a more complex problem. What spurred the thought was this piece written up by guido concerning "what's the best way to convert a list of integers into a string". It's a simple question where concepts are introduced that can lead to solving more complex problems. http://www.python.org/doc/essays/list2str.html From no.email at nospam.invalid Sat May 8 23:49:59 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 20:49:59 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> Message-ID: <7xk4rdpwd4.fsf@ruckus.brouhaha.com> Martin wrote: >>> I fail to see what is morally wrong with it. When I ,as the author, >>> share my work to the public, I should have made peace with the fact >>> that I, for all intends and purposes, lost control over its use. Robert Kern writes: > Martin is not saying that you *ought* to release your code under a > liberal license. He is only saying that he does not believe he is > inviting moral hazard when *he* decides to release *his* code under a > liberal license. He was responding to Steven who was claiming > otherwise. As I read it, he is saying that when someone releases free software, they have "for all intends and purposes lost control over its use", so they "should have made peace with the fact" and surrender gracefully. I'm asking why he doesn't think Microsoft has lost control the same way. From pavlovevidence at gmail.com Sun May 9 00:04:44 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 8 May 2010 21:04:44 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <7x39y1vl07.fsf@ruckus.brouhaha.com> Message-ID: <73bcbd04-4e31-4532-a220-9389c5c299d9@r11g2000yqa.googlegroups.com> On May 8, 7:58?pm, Paul Rubin wrote: > Carl Banks writes: > > People who esteem their users give them freedom to use software > > however they see fit, including combining it with proprietary > > software. > > Huh???? ?That makes no sense at all. ?Why should a standard like that be > expected from free software developers, when it isn't expected from the > makers of the proprietary software who you're proposing deserve to rake > in big bucks from locking up other people's work that they didn't pay > for? Same thing's true commercial software, Sparky. If a commercial developer has a EULA that prevents users from combining their tools with tools from (say) their competitors, they would be very much disrespecting their users. The GPL does exactly that, and people who release GPL software disrespect their users just as much as a commercial entity that requires you not to use competing products. But for some reason when someone and inflicts the disrespect of the GPL on the community they're considered folk heroes. Bah. > I've got no problem writing stuff for inclusion in proprietary products. > But I do that as a professional, which means I expect to get paid for > it. ?And I think you have the "esteem" issue backwards. ?Users who > esteem developers who write and share software for community benefit, > should not whine and pout that the largesse doesn't extend as far as > inviting monopolistic corporations to lock it away from further sharing. In your petty jealous zeal to prevent megacorporations from profiting off free software, you prevent guys like me from doing useful, community-focused things like writing extensions for commercial software that uses GPL-licensed code. The GPL drives a wedge between commercial and free software, making it difficult for the two to coexist. That is far more detrimental to open source community than the benefits of making a monopolistic corporation do a little extra work to avoid having their codebase tainted by GPL. Carl Banks From aahz at pythoncraft.com Sun May 9 00:18:31 2010 From: aahz at pythoncraft.com (Aahz) Date: 8 May 2010 21:18:31 -0700 Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> Message-ID: In article <7xtyqhu5sg.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >I don't know if it counts as a moral hazard but some programmers simply >don't want to do proprietary product development for free. That's why >Linux (GPL) has far more developers (and consequentially far more >functionality and more users) than the free versions of BSD, and GCC >(GPL) has far more developers than Python. What does your argument claim about Apache? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From dasacc22 at gmail.com Sun May 9 00:24:50 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sat, 8 May 2010 21:24:50 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> Message-ID: <8b1ac372-ebe0-4b11-8bb8-8b5379134aa5@r11g2000yqa.googlegroups.com> On May 8, 2:46?pm, Steven D'Aprano wrote: > On Sat, 08 May 2010 12:15:22 -0700, Wolfram Hinderer wrote: > > On 8 Mai, 20:46, Steven D'Aprano > > wrote: > > >> def get_leading_whitespace(s): > >> ? ? t = s.lstrip() > >> ? ? return s[:len(s)-len(t)] > > >> >>> c = get_leading_whitespace(a) > >> >>> assert c == leading_whitespace > > >> Unless your strings are very large, this is likely to be faster than > >> any other pure-Python solution you can come up with. > > > Returning s[:-1 - len(t)] is faster. > > I'm sure it is. Unfortunately, it's also incorrect. > > >>> z = "*****abcde" > >>> z[:-1-5] > '****' > >>> z[:len(z)-5] > > '*****' > > However, s[:-len(t)] should be both faster and correct. > > -- > Steven This is without a doubt faster and simpler then any solution thus far. Thank you for this From no.email at nospam.invalid Sun May 9 00:29:26 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 21:29:26 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <7x39y1vl07.fsf@ruckus.brouhaha.com> <73bcbd04-4e31-4532-a220-9389c5c299d9@r11g2000yqa.googlegroups.com> Message-ID: <7x4oihn1eh.fsf@ruckus.brouhaha.com> Carl Banks writes: > If a commercial developer has a EULA that prevents users from > combining their tools with tools from (say) their competitors, Do you mean something like a EULA that stops you from buying a copy of Oracle and combining it with tools from IBM on the computer that you install Oracle on? Those EULAs exist but are not remotely comparable to the GPL. > The GPL does exactly that, No it doesn't (not like the above). You, the licensee under the GPL, can make those combinations and use them as much as you want on your own computers. You just can't distribute the resulting derivative to other people. With proprietary software you can't redistribute the software to other people from day zero (or even use more copies within your own company than you've paid for), regardless of whether you've combined it with anything. And since you usually don't get the source code, it's awfully hard to make derived combinatoins. From no.email at nospam.invalid Sun May 9 00:36:11 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 21:36:11 -0700 Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> Message-ID: <7xwrvdlmis.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > What does your argument claim about Apache? No idea. I don't have the impression the developer communities are really similar, and Apache httpd doesn't have all that many developers compared with something like Linux (I don't know what happens if you add all the sister projects like Lucene). I do know that the GPL has gotten companies to release major GCC improvements that they would have preferred to make proprietary if they'd had the option. That includes G++. From wolfgang at rohdewald.de Sun May 9 00:52:25 2010 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Sun, 9 May 2010 06:52:25 +0200 Subject: Cross-platform file paths In-Reply-To: <1e8cu5tcvl87979vq5r0mecos28m9vat6v@4ax.com> References: <1e8cu5tcvl87979vq5r0mecos28m9vat6v@4ax.com> Message-ID: <201005090652.25777.wolfgang@rohdewald.de> On Sonntag 09 Mai 2010, Tim Roberts wrote: > No. On Linux, you need to mount the share in some empty > directory (using mount or smbmount), then read the files from > that directory. actually the mount directory does not have to be empty - whatever it contains is invisible while someting is mounted in it. But of course using an empty directory gets you less surprises. -- Wolfgang From simula67 at comcast.net Sun May 9 00:56:36 2010 From: simula67 at comcast.net (Eric Stechmann) Date: Sat, 8 May 2010 23:56:36 -0500 Subject: [ANN] Leipzig Python User Group - Meeting, May 11, 2010, 08:00pm In-Reply-To: <4BE43936.7080600@sschwarzer.net> References: <4BE43936.7080600@sschwarzer.net> Message-ID: On May 7, 2010, at 11:00 AM, Stefan Schwarzer wrote: > === Leipzig Python User Group === > > We will meet on Tuesday, May 11, 8:00 pm at the training > center of Python Academy in Leipzig, Germany > ( http://www.python-academy.com/center/find.html ). > > Julian Moritz will give a talk about CouchDB. > > Food and soft drinks are provided. Please send a short > confirmation mail to info at python-academy.de, so we can prepare > appropriately. > > Everybody who uses Python, plans to do so or is interested in > learning more about the language is encouraged to participate. > > While the meeting language will be mainly German, we will provide > English translation if needed. > > Current information about the meetings are at > http://www.python-academy.com/user-group . > > Stefan > > > == Leipzig Python User Group === > > Wir treffen uns am Dienstag, 11.05.2010 um 20:00 Uhr > im Schulungszentrum der Python Academy in Leipzig > ( http://www.python-academy.de/Schulungszentrum/anfahrt.html ). > > Julian Moritz h?lt einen Vortrag ?ber CouchDB. > > F?r das leibliche Wohl wird gesorgt. Eine Anmeldung unter > info at python-academy.de w?re nett, damit wir genug Essen > besorgen k?nnen. > > Willkommen ist jeder, der Interesse an Python hat, die Sprache > bereits nutzt oder nutzen m?chte. > > Aktuelle Informationen zu den Treffen sind unter > http://www.python-academy.de/User-Group zu finden. > > Viele Gr??e > Stefan > > > > > > > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations/ From pmaupin at gmail.com Sun May 9 01:01:48 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 22:01:48 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <7x39y1vl07.fsf@ruckus.brouhaha.com> <73bcbd04-4e31-4532-a220-9389c5c299d9@r11g2000yqa.googlegroups.com> <7x4oihn1eh.fsf@ruckus.brouhaha.com> Message-ID: On May 8, 11:29?pm, Paul Rubin wrote: > No it doesn't (not like the above). ?You, the licensee under the GPL, > can make those combinations and use them as much as you want on your own > computers. ?You just can't distribute the resulting derivative to other > people. ?With proprietary software you can't redistribute the software > to other people from day zero (or even use more copies within your own > company than you've paid for), regardless of whether you've combined it > with anything. ?And since you usually don't get the source code, it's > awfully hard to make derived combinatoins. But the point is that a lot of small developers who are writing software don't need to distribute any software other than software they wrote themselves. Their customers will have Oracle/Microsoft/IBM/ CA/whatever licenses already. Companies like Oracle support various APIs that allow custom software to be connected to their software, so if Carl is writing stuff to support Oracle, he can just distribute his software to the customer, and let the customer link it himself. Now when Carl's software links to GPLed software, it gets interesting. Although it's probably a legal overreach, the FSF often attempts to claim that software like Carl's, *by itself*, must be licensed under the GPL, simply because it can link to GPLed software, even if it doesn't actually contain any GPLed software. (Whether it's a legal overreach or not, it's the position of the FSF, and of a lot of authors who use the GPL, so morally it's probably best to follow their wishes.) The end result is that Carl can deliver software to his customer that lets the customer link Oracle and Microsoft software together, for example, but is prohibited from delivering software that lets the customer link GPLed code to Oracle code, because the FSF considers that software that would do that is a "derived work" and that Carl is making a distribution when he gives it to his customer, and he is not allowed to distribute GPLed code that links to proprietary Oracle code. Regards, Pat From pmaupin at gmail.com Sun May 9 01:09:14 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 22:09:14 -0700 (PDT) Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> Message-ID: <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> On May 8, 11:36?pm, Paul Rubin wrote: > a... at pythoncraft.com (Aahz) writes: > > What does your argument claim about Apache? > > No idea. ?I don't have the impression the developer communities are > really similar, and Apache httpd doesn't have all that many developers > compared with something like Linux (I don't know what happens if you add > all the sister projects like Lucene). > > I do know that the GPL has gotten companies to release major GCC > improvements that they would have preferred to make proprietary if > they'd had the option. ?That includes G++. Absolutely, and as Aahz acknowledges, RMS was a pioneer in introducing people to the concept of free software. But fast forward to today, and as ESR points out, the FOSS development model is so superior for many classes of software that proprietary companies contribute to free software even when they don't have to, and are working hard to support hybrid models that the GPL doesn't support. See, for example, Apple's support of BSD, Webkit, and LLVM. Apple is not a "do no evil" corporation, and their contributions back to these packages are driven far more by hard-nosed business decisions than by any expectation of community goodwill. Regards, Pat From steve at REMOVE-THIS-cybersource.com.au Sun May 9 01:13:11 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 05:13:11 GMT Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> <489ffaa0-1563-45a1-93aa-cc83cdd6abd9@j35g2000yqm.googlegroups.com> Message-ID: <4be64467$0$27783$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 13:46:59 -0700, Mark Dickinson wrote: >> However, s[:-len(t)] should be both faster and correct. > > Unless len(t) == 0, surely? Doh! The hazards of insufficient testing. Thanks for catching that. -- Steven From lie.1296 at gmail.com Sun May 9 01:17:38 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 09 May 2010 15:17:38 +1000 Subject: Kindly show me a better way to do it In-Reply-To: References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> Message-ID: <4be645cf@dnews.tpgi.com.au> On 05/09/10 07:09, G?nther Dietrich wrote: > > Why not this way? > >>>> a = [[1,2,3,4], [5,6,7,8]] >>>> for i in a: > .... for j in i: > .... print(j) > .... > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > > Too simple? IMHO that's more complex due to the nested loop, though I would personally do it as: a = [ [1,2,3,4], [5,6,7,8] ] from itertools import chain for i in chain.from_iterable(a): print i so it won't choke when 'a' is an infinite stream of iterables. From steve at REMOVE-THIS-cybersource.com.au Sun May 9 01:19:47 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 05:19:47 GMT Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> Message-ID: <4be645f2$0$27783$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 16:39:33 -0700, Carl Banks wrote: > GPL is about fighting a holy war against commercial software. Much GPL software *is* commercial software. Given that you're so badly misinformed about the GPL that you think it can't be commercial, why should we pay any attention to your opinions about it? -- Steven From no.email at nospam.invalid Sun May 9 01:27:25 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 22:27:25 -0700 Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> Message-ID: <7x39y14pc2.fsf@ruckus.brouhaha.com> Patrick Maupin writes: > hybrid models that the GPL doesn't support. See, for example, Apple's > support of BSD, Webkit, and LLVM. Apple is not a "do no evil" > corporation, and their contributions back to these packages are driven > far more by hard-nosed business decisions than by any expectation of > community goodwill. That is true. They've also supported GPL projects. I think they just don't want to be in the business of selling those sorts of products. They're making too much money selling iphones and laptops to want such a distraction. Things were different with G++. The company that developed it would have liked to go into the compiler business with it, but it wasn't an option, so they released under GPL. Linus has said similar things have happened with Linux, but I don't know details. From pmaupin at gmail.com Sun May 9 02:01:52 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 8 May 2010 23:01:52 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> Message-ID: <9f54536c-8428-4de8-bba8-fa16fe728a1f@n15g2000yqf.googlegroups.com> On May 9, 12:19?am, Steven D'Aprano wrote: > On Sat, 08 May 2010 16:39:33 -0700, Carl Banks wrote: > > GPL is about fighting a holy war against commercial software. > > Much GPL software *is* commercial software. Given that you're so badly > misinformed about the GPL that you think it can't be commercial, why > should we pay any attention to your opinions about it? I think, when Carl wrote "commercial" he meant what many others, including RMS, would call "proprietary." And, although many people who use the GPL license may not be fighting the holy war, the original author of the license certainly is. When asked how he sees proprietary software businesses making a profit when more and more software is free, RMS replied "That's unethical, they shouldn't be making any money. I hope to see all proprietary software wiped out. That's what I aim for. That would be a World in which our freedom is respected. A proprietary program is a program that is not free. That is to say, a program that does respect the user's essential rights. That's evil. A proprietary program is part of a predatory scheme where people who don't value their freedom are drawn into giving it up in order to gain some kind of practical convenience." And while I agree somewhat with RMS when the subject is certain proprietary companies that try really hard to lock in users and lock up their data, I don't view all proprietary software as evil, and I certainly agree that RMS's language is couched in religious rhetoric. Regards, Pat From steve at REMOVE-THIS-cybersource.com.au Sun May 9 02:17:07 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 06:17:07 GMT Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> Message-ID: <4be65362$0$27783$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 14:06:33 -0700, Oltmans wrote: > On May 9, 1:53?am, superpollo wrote: > >> add = lambda a,b: a+b >> for i in reduce(add,a): >> ? ? ?print i > > This is very neat. Thank you. Sounds like magic to me. Can you please > explain how does that work? Many thanks again. Don't use this except for small lists, it is very inefficient and will be slow for large lists. It is a Shlemiel The Painter algorithm: http://www.joelonsoftware.com/articles/fog0000000319.html The most idiomatic solution is a simple, straightforward nested iteration: for sublist in a: for item in sublist: do_something_with(item) Say that there are 10 sublists with 10 items each. Then nested iteration will iterate 100 times in total. The solution with reduce will iterate: 10+10 # add the first sublist and the second sublist 20+10 # add the third sublist 30+10 # add the fourth sublist 40+10 # and so on... 50+10 60+10 70+10 80+10 90+10 # add the last sublist 100 # and now iterate over the combined list or 640 times in total. If there are 100 sublists of 10 items each, the performance is even worse: 51,490 for the reduce solution, versus 1000 for the nested iteration. Admittedly those iterations will be in fast C code instead of slow Python code, which is why you might not notice the difference at first, but you're still doing a lot of unnecessary work which takes time. How much time? Python makes it easy to find out. >>> from timeit import Timer >>> setup = "data = [range(10) for i in range(10)]" >>> t1 = Timer("""for sublist in data: ... for item in sublist: ... pass""", setup) >>> t2 = Timer("""for item in reduce(lambda x,y: x+y, data): ... pass""", setup) >>> >>> min(t1.repeat(number=100000)) 0.94107985496520996 >>> min(t2.repeat(number=100000)) 1.7509880065917969 So for ten sublists of ten items each, the solution using reduce is nearly twice as slow as the nested iteration. If we make the number of lists ten times larger, the nested for-loop solution takes ten times longer, as you would expect: >>> setup = "data = [range(10) for i in range(100)]" >>> t1 = Timer("""for sublist in data: ... for item in sublist: ... pass""", setup) >>> min(t1.repeat(number=100000)) 10.349304914474487 But the reduce solution slows down by a factor of thirty-two rather than ten: >>> t2 = Timer("""for item in reduce(lambda x,y: x+y, data): ... pass""", setup) >>> min(t2.repeat(number=100000)) 58.116463184356689 If we were to increase the number of sublists further, the reduce solution will perform even more badly. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun May 9 02:25:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 06:25:01 GMT Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: <4be6553d$0$27783$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 14:27:32 -0700, dasacc22 wrote: > U presume entirely to much. I have a preprocessor that normalizes > documents while performing other more complex operations. Theres > nothing buggy about what im doing I didn't *presume* anything, I took your example code and ran it and discovered that it didn't do what you said it was doing. -- Steven From no.email at nospam.invalid Sun May 9 02:42:31 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 08 May 2010 23:42:31 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <9f54536c-8428-4de8-bba8-fa16fe728a1f@n15g2000yqf.googlegroups.com> Message-ID: <7xr5lllgo8.fsf@ruckus.brouhaha.com> Patrick Maupin writes: > I certainly agree that RMS's language is couched in religious rhetoric. I would say political movement rhetoric. He's not religious. He uses the word "spiritual" sometimes but has made it clear he doesn't mean that in a religious sense. From pavlovevidence at gmail.com Sun May 9 03:05:59 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 9 May 2010 00:05:59 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> Message-ID: On May 8, 10:19?pm, Steven D'Aprano wrote: > On Sat, 08 May 2010 16:39:33 -0700, Carl Banks wrote: > > GPL is about fighting a holy war against commercial software. > > Much GPL software *is* commercial software. Given that you're so badly > misinformed about the GPL that you think it can't be commercial, why > should we pay any attention to your opinions about it? In the interests of not allowing petty semantics to interfere with this rational discussion, I will correct myself slightly although I diagree with the terminology. The GPL is a holy war against closed source commercial software. Anyone who GPL's their code is fighting that war whether they intend to or not. And losing it, I might add. There are a small number--maybe 20--of GPLed packages that have the leverage to force monopolistic corporations to release their code when they wouldn't have otherwise. Even then it's only bits and pieces (e.g., NVIDIA's kernel model-- fortunately the X Video driver is allowed to be closed source, otherwise there'd be no driver on Linux). Meanwhile there's thousands of GPL packages the corporations won't touch and they--and we--suffer because of it. I might like to buy a commercial plugin for Blender, but there aren't any because it's GPL. If good commercial plugins are available, maybe some firms would find Blender a reasonable low-cost alternative to expensive products like Maya, thus benefiting the whole community. As it is, there is no chance of that happening, all thanks to GPL. That's the real effect of the GPL, the one that happens on the ground every day. But if you want to think that the GPL is furthering the cause of open souce on account of a few companies who donated a few lines of code to GCC, be my guest. As for open-source "commercial" software, there's a different holy war being waged against it, namely reality. No one actually makes money on it. Open source is the bait to attract customers to buy other services, ans that's what they make money on. To me this means it's not commercial but it doesn't matter: the GPL even interferes with this. Companies do make money supporting GPL, but it's in spite of GPL and not because of it. A permissive license would allow companies more freedom to offer their proprietary enhancements. Bottom line is, GPL hurts everyone: the companies and open source community. Unless you're one of a handful of projects with sufficient leverage, or are indeed a petty jealous person fighting a holy war, the GPL is a bad idea and everyone benefits from a more permissive licence. Carl Banks From pavlovevidence at gmail.com Sun May 9 03:22:21 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 9 May 2010 00:22:21 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <7x39y1vl07.fsf@ruckus.brouhaha.com> <73bcbd04-4e31-4532-a220-9389c5c299d9@r11g2000yqa.googlegroups.com> <7x4oihn1eh.fsf@ruckus.brouhaha.com> Message-ID: <3bf126e8-0f77-48a9-ba29-8650ae79f09b@j35g2000yqm.googlegroups.com> On May 8, 9:29?pm, Paul Rubin wrote: > Carl Banks writes: > > If a commercial developer has a EULA that prevents users from > > combining their tools with tools from (say) their competitors, > > Do you mean something like a EULA that stops you from buying a copy of > Oracle and combining it with tools from IBM on the computer that you > install Oracle on? Yes > ?Those EULAs exist but are not remotely comparable to > the GPL. They're not exactly the same but they're quite comparable and both disrespectful to the user. > > The GPL does exactly that, > > No it doesn't (not like the above). ?You, the licensee under the GPL, > can make those combinations and use them as much as you want on your own > computers. ?You just can't distribute the resulting derivative to other > people. ?With proprietary software you can't redistribute the software > to other people from day zero (or even use more copies within your own > company than you've paid for), regardless of whether you've combined it > with anything. ?And since you usually don't get the source code, it's > awfully hard to make derived combinatoins. Really, commercial closed source programs don't have APIs? If the EULA isn't disrespectful likle the GPL, then I could write a program that links against multiple closed source API and distribute closed or open source binaries. Can't do either if you change one of the proprietary programs to GPL. GPL is a lot more restrictive than mere closed source proprietary when it comes to stuff like that. Carl Banks From isso.moh at gmail.com Sun May 9 04:15:59 2010 From: isso.moh at gmail.com (mohamed issolah) Date: Sun, 9 May 2010 10:15:59 +0200 Subject: win32com Message-ID: hey, there is an alternative of win32com in linux? what i want to say : can communicate with application (ex: evolution or another) throught python like in windows with win32com thanks, sorry for my english need help -- issolah mohamed -------------- next part -------------- An HTML attachment was scrubbed... URL: From dasarathulagopi at gmail.com Sun May 9 04:16:21 2010 From: dasarathulagopi at gmail.com (gopi krishna) Date: Sun, 9 May 2010 13:46:21 +0530 Subject: flattening list Message-ID: Hi , Anyone can pls help me in flattening the list. if p is the my list which is defined below p=[1,[2,3,4],[5,6,],9,[[11,12]]] from the above how to get a list as [1,2,3,4,5,6,9,11,12] -------------- next part -------------- An HTML attachment was scrubbed... URL: From dasarathulagopi at gmail.com Sun May 9 04:19:20 2010 From: dasarathulagopi at gmail.com (gopi krishna) Date: Sun, 9 May 2010 13:49:20 +0530 Subject: can we change the variables with function Message-ID: Hi can I change the variable in a function using the function suppose >>>def a(): x=20 can we change the variable using the function -------------- next part -------------- An HTML attachment was scrubbed... URL: From dasarathulagopi at gmail.com Sun May 9 04:20:18 2010 From: dasarathulagopi at gmail.com (gopi krishna) Date: Sun, 9 May 2010 13:50:18 +0530 Subject: Why list comprehension faster than for loop? Message-ID: Why list comprehension faster than for loop? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun May 9 04:21:38 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 May 2010 01:21:38 -0700 Subject: flattening list In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 1:16 AM, gopi krishna wrote: > Hi , > ??? Anyone can pls help me in flattening the list. > if p is the my list which is defined below > p=[1,[2,3,4],[5,6,],9,[[11,12]]] > from the above how to get a list > as [1,2,3,4,5,6,9,11,12] http://www.lmgtfy.com/?q=python+flatten+list Cheers, Chris -- python-list doesn't like doing other people's homework. http://blog.rebertia.com From clp2 at rebertia.com Sun May 9 04:25:02 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 May 2010 01:25:02 -0700 Subject: can we change the variables with function In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 1:19 AM, gopi krishna wrote: > Hi > ?? can I change the variable in a function using the function > suppose >>>>def a(): > x=20 > can we change the variable using the function Your question is incomprehensible. Please rephrase it more clearly and provide more details. Regards, Chris -- http://blog.rebertia.com From matthew.brett at gmail.com Sun May 9 04:28:14 2010 From: matthew.brett at gmail.com (Matthew Brett) Date: Sun, 9 May 2010 01:28:14 -0700 (PDT) Subject: zlib.decompress fails, zlib.decompressobj succeeds - bug or feature? Message-ID: <089c36fa-a2a9-463d-af21-06403e0e6afb@t14g2000prm.googlegroups.com> Hi, I sorry if this is a bad place to ask, but I wanted to find out if the behavior I'm seeing is a bug. I maintain scipy's matlab file readers, and I came across a zlib compressed string that causes a zlib error on decompression, but only with zlib.decompress, not zlib.decompressobj. I saved the original compressed string as a binary file at http://dl.dropbox.com/u/794947/mat.bin Now if I do: import zlib data = open('mat.bin', 'rb').read() out = zlib.decompress(data) I get an error : Error -5 while decompressing data) If instead I do this: out = zlib.decompressobj().decompress(data) I get a usable uncompressed string. I was expecting these two calls to do the same thing. Is that expectation right? If not, is there somewhere I could find out why? Thanks a lot, Matthew From contact at xavierho.com Sun May 9 04:29:27 2010 From: contact at xavierho.com (Xavier Ho) Date: Sun, 9 May 2010 18:29:27 +1000 Subject: Why list comprehension faster than for loop? In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 6:20 PM, gopi krishna wrote: > Why list comprehension faster than for loop? > > Because Python optimises for certain special cases, when the number of iterations is predicable in a list comprehension. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Sun May 9 04:37:12 2010 From: contact at xavierho.com (Xavier Ho) Date: Sun, 9 May 2010 18:37:12 +1000 Subject: can we change the variables with function In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 6:19 PM, gopi krishna wrote: > Hi > can I change the variable in a function using the function > suppose > >>>def a(): > x=20 > can we change the variable using the function > Can you give us an example of how you'd like to "change the variable", in code, and show us what didn't work? We might be able to help with some sample code. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From ideamonk at gmail.com Sun May 9 04:38:29 2010 From: ideamonk at gmail.com (Abhishek Mishra) Date: Sun, 9 May 2010 14:08:29 +0530 Subject: flattening list In-Reply-To: References: Message-ID: thanks for the excercise just figured out this - #!/usr/bin/env python import sys sys.setrecursionlimit(2000) def flatten(l): flattened = [] for i in l: if type(i) == type([]): flattened += flatten(i) else: flattened.append(i) return flattened if __name__=='__main__': p=[1,[2,3,4],[5,6,],9,[[11,12]]] print flatten(p) But a google search will lead you to more elegant generic solutions :) On Sun, May 9, 2010 at 1:46 PM, gopi krishna wrote: > Hi , > Anyone can pls help me in flattening the list. > if p is the my list which is defined below > p=[1,[2,3,4],[5,6,],9,[[11,12]]] > from the above how to get a list > as [1,2,3,4,5,6,9,11,12] > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ideamonk at gmail.com Sun May 9 04:39:52 2010 From: ideamonk at gmail.com (Abhishek Mishra) Date: Sun, 9 May 2010 14:09:52 +0530 Subject: can we change the variables with function In-Reply-To: References: Message-ID: Could you also demonstrate with an example as to what kind of effect you're expecting from whatever you've been desiring to do? On Sun, May 9, 2010 at 1:49 PM, gopi krishna wrote: > Hi > can I change the variable in a function using the function > suppose > >>>def a(): > x=20 > can we change the variable using the function > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun May 9 04:47:12 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 May 2010 01:47:12 -0700 Subject: win32com In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 1:15 AM, mohamed issolah wrote: > hey, > > there is an alternative of win32com in linux? > > what i want to say : can communicate with application (ex: evolution or > another) throught python like in windows with win32com The closest equivalent would probably be python-dbus. See the "Python" section of http://www.freedesktop.org/wiki/Software/DBusBindings Information on D-Bus generally: http://en.wikipedia.org/wiki/D-Bus Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Sun May 9 05:01:58 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 May 2010 02:01:58 -0700 Subject: can we change the variables with function In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 1:33 AM, gopi krishna wrote: > My Question is > can we access the variables defined in a function ? >>>> class A: > ? ? def b(self): > ? ? ? ? x=40 > ? ? z=40 > > >>>> q=A() >>>> q.z > 40 >>>> q.z=60 >>>> q.z > 60 > We can access the variables defined in a class as shown above ?in the same > way can we access the variables defined in a method? There is likely a very hackish way to do it involving bytecode disassembly, but it's ill-advised. Further, what if the variable isn't a constant, as `y` is in the following example?: ? ?def foo(self, x): ? ? ? ?y = x + 3 What would you expect to get for y's value? Why would you want such an ability in the first place? I suspect that if you explained your use-case/situation, someone could offer a much better alternative approach. Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun May 9 05:18:10 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 09:18:10 GMT Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be645cf@dnews.tpgi.com.au> Message-ID: <4be67dd2$0$27783$c3e8da3@news.astraweb.com> On Sun, 09 May 2010 15:17:38 +1000, Lie Ryan wrote: > On 05/09/10 07:09, G?nther Dietrich wrote: >> >> Why not this way? >> >>>>> a = [[1,2,3,4], [5,6,7,8]] >>>>> for i in a: >> .... for j in i: >> .... print(j) >> .... >> 1 >> 2 >> 3 >> 4 >> 5 >> 6 >> 7 >> 8 >> >> Too simple? > > IMHO that's more complex due to the nested loop, What's so complex about a nested loop? And why are you saying that it is "more complex" than the Original Poster's solution, which also had a nested loop, plus a pointless list comprehension? > though I would > personally do it as: > > a = [ [1,2,3,4], [5,6,7,8] ] > from itertools import chain > for i in chain.from_iterable(a): > print i > > so it won't choke when 'a' is an infinite stream of iterables. Neither will a nested for-loop. -- Steven From utente at esempio.net Sun May 9 05:20:35 2010 From: utente at esempio.net (superpollo) Date: Sun, 09 May 2010 11:20:35 +0200 Subject: solve a newspaper quiz Message-ID: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> "if a b c are digits, solve ab:c=a*c+b" solved in one minute with no thought: for a in range(10): for b in range(10): for c in range(10): try: if (10.*a+b)/c==a*c+b: print "%i%i:%i=%i*%i+%i" % (a,b,c,a,c,b) except: pass any suggestion for improvement? bye From martin.hellwig at dcuktec.org Sun May 9 05:22:47 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sun, 09 May 2010 10:22:47 +0100 Subject: Picking a license In-Reply-To: <7xk4rdpwd4.fsf@ruckus.brouhaha.com> References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> Message-ID: On 05/09/10 04:49, Paul Rubin wrote: > As I read it, he is saying that when someone releases free software, > they have "for all intends and purposes lost control over its use", so > they "should have made peace with the fact" and surrender gracefully. > I'm asking why he doesn't think Microsoft has lost control the same way. Microsoft has indeed lost control of it in the same way, it is just because we here in the 'western' world spend huge amount of money on prosecuting and bringing to 'justice' does who, whether for commercial purposes or otherwise, make a copy of a piece of code. Think about it, it is not stealing, the original is still there and no further resources where needed from the original developer. What I am saying is that all this license crap is only needed because we are used to a commercial environment where we can repeatedly profit from the same work already done. I am not saying that you should not profit, of course you should otherwise there is no interest in making it in the first place. What I am saying is that we as developers should encourage pay for work and not pay for code. This will, as I believe it, keep everything much more healthy and balanced. At least we can cut all the crap of software patents and copyrights. For those who say it can't be done, sure it can, all you have to do is nothing, it takes effort to enforce policies. -- mph From contact at xavierho.com Sun May 9 05:31:49 2010 From: contact at xavierho.com (Xavier Ho) Date: Sun, 9 May 2010 19:31:49 +1000 Subject: solve a newspaper quiz In-Reply-To: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> References: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> Message-ID: On Sun, May 9, 2010 at 7:20 PM, superpollo wrote: > "if a b c are digits, solve ab:c=a*c+b" > Sorry, what does the notation ab:c mean? Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sun May 9 05:58:17 2010 From: andreengels at gmail.com (Andre Engels) Date: Sun, 9 May 2010 11:58:17 +0200 Subject: solve a newspaper quiz In-Reply-To: References: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> Message-ID: On Sun, May 9, 2010 at 11:31 AM, Xavier Ho wrote: > On Sun, May 9, 2010 at 7:20 PM, superpollo wrote: >> >> "if a b c are digits, solve ab:c=a*c+b" > > Sorry, what does the notation ab:c mean? The number ab divided by c. -- Andr? Engels, andreengels at gmail.com From ldo at geek-central.gen.new_zealand Sun May 9 05:59:15 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 09 May 2010 21:59:15 +1200 Subject: Windows - select.select, timeout and KeyboardInterrupt References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: In message , exarkun at twistedmatrix.com wrote: > On 07:48 am, ldo at geek-central.gen.new_zealand wrote: > >>In message , >>exarkun at twistedmatrix.com wrote: >> >>>This is a good example of why it's a bad idea to use select on >>>Windows. >>>Instead, use WaitForMultipleObjects. >> >>How are you supposed to write portable code, then? > > With WaitForMultipleObjects on Windows, epoll on Linux, kqueue on BSD, > event completion on Solaris, etc... > > Sound like more work than using select() everywhere? Yea, a bit. But > not once you abstract it away from your actual application code. After > all, it's not like these *do* different things. They all do the same > thing (basically) - differently. Do you understand what ?portable? means? From trent at snakebite.org Sun May 9 07:02:28 2010 From: trent at snakebite.org (Trent Nelson) Date: Sun, 9 May 2010 04:02:28 -0700 Subject: Why list comprehension faster than for loop? In-Reply-To: References: Message-ID: <58440DD8-A427-4280-BF0F-509BC7DEF750@snakebite.org> On 9 May 2010, at 16:29, Xavier Ho wrote: On Sun, May 9, 2010 at 6:20 PM, gopi krishna > wrote: Why list comprehension faster than for loop? Because Python optimises for certain special cases, when the number of iterations is predicable in a list comprehension. The fact that list comprehensions can only be comprised of expressions, not statements, is a considerable factor, as much less work is required behind the scenes for each iteration. Another factor is that the underlying iteration mechanism for list comprehensions is much closer to a C loop than execution of a for loop. Exact same reason Perl's map { } is much faster than an equivalent for/foreach loop. (Psyco can speed up certain list comprehensions quite significantly, too, but it isn't able to perform the same magic on an equivalent for loop.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alain at dpt-info.u-strasbg.fr Sun May 9 07:02:45 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sun, 09 May 2010 13:02:45 +0200 Subject: solve a newspaper quiz References: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> Message-ID: <87aas9xrqi.fsf@dpt-info.u-strasbg.fr> superpollo writes: > "if a b c are digits, solve ab:c=a*c+b" > > solved in one minute with no thought: Obviously. > for a in range(10): > for b in range(10): > for c in range(10): > try: > if (10.*a+b)/c==a*c+b: > print "%i%i:%i=%i*%i+%i" % (a,b,c,a,c,b) > except: > pass > > any suggestion for improvement? Here is my take (sorry, no nice prints): # c = 0 has no solution # c = 1 -> 9a = 0 whatever b for b in xrange(10): print 0,b,1 # c = 2 -> 6a = b for a in xrange(2): print a,a*6,2 # c = 3 -> a = 2b for b in xrange(0,5): print 2*b,b,3 # c = 4-9 -> a = b = 0 for c in xrange(4,10): print 0,0,c Improvements: a lot more fun to design, a lot more efficient to run -- Alain. From isso.moh at gmail.com Sun May 9 07:37:19 2010 From: isso.moh at gmail.com (mohamed issolah) Date: Sun, 9 May 2010 13:37:19 +0200 Subject: win32com In-Reply-To: References: Message-ID: hey, I wich to have an example please need help 2010/5/9 Chris Rebert > On Sun, May 9, 2010 at 1:15 AM, mohamed issolah > wrote: > > hey, > > > > there is an alternative of win32com in linux? > > > > what i want to say : can communicate with application (ex: evolution or > > another) throught python like in windows with win32com > > The closest equivalent would probably be python-dbus. See the "Python" > section of http://www.freedesktop.org/wiki/Software/DBusBindings > > Information on D-Bus generally: http://en.wikipedia.org/wiki/D-Bus > > Cheers, > Chris > -- > http://blog.rebertia.com > -- issolah mohamed -------------- next part -------------- An HTML attachment was scrubbed... URL: From pan-news at infocentrality.co.uk Sun May 9 07:39:13 2010 From: pan-news at infocentrality.co.uk (TFH) Date: Sun, 09 May 2010 11:39:13 GMT Subject: accessing superclass methods from subclass References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: On Sat, 08 May 2010 16:50:11 -0700, ben wrote: > Why doesn't this work: > > class C1: > def f1(self): > print("f1") > > class C2(C1): > f1() > > > It throws this error: > > Traceback (most recent call last): > File "./c1.py", line 7, in > class C2(C1): > File "./c1.py", line 8, in C2 > f1() > NameError: name 'f1' is not defined > > > f1() is an attribute of class C1, C2 inherits C1, so why can't it see > it? > > thanks! Try this: class C1: def f1(self): return "From C1: f1" class C2(C1): def f2(self): return self.f1() c2 = C2() print c2.f2() regards Trevor From python.list at tim.thechases.com Sun May 9 07:42:02 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 09 May 2010 06:42:02 -0500 Subject: A more general solution In-Reply-To: <44e7ce5a-6ec3-460e-9f36-05762ebe59b0@i9g2000yqi.googlegroups.com> References: <44e7ce5a-6ec3-460e-9f36-05762ebe59b0@i9g2000yqi.googlegroups.com> Message-ID: <4BE69F8A.9040304@tim.thechases.com> On 05/08/2010 10:33 PM, 3Jane wrote: > You could interpret [[1,2,3,4],[5,6,7,8]] as a tree and > your task as traversal of its leaves. All solutions before > would not work with trees with bigger height. > > Here is how to traverse such trees recursively: > > def eventualPrint(x): > for v in x: > if isinstance(v, list): eventualPrint(x) > else: print(v) > > Then eventualPrint(a) does the job. Caveat: ...but wanders off into the bushes for recursive lists :) x = [1,2,3] x.append (x) eventualPrint(x) Not a particular concern in this case since I'm now two levels of hypothetical removed from the OP's question (from flatten one layer to recursively flattening arbitrary nestings to recursively flattening arbitrary & self-referential nestings)... For the record, I'm in the itertools camp of proposed solutions to the OP's question. -tkc From qq13234722 at gmail.com Sun May 9 07:56:41 2010 From: qq13234722 at gmail.com (=?UTF-8?B?55av5Zu+54G1?=) Date: Sun, 9 May 2010 04:56:41 -0700 (PDT) Subject: The python theme T-shirt is cool ? Message-ID: <065df098-2db4-4743-b3ff-7fd244573fe0@40g2000pry.googlegroups.com> To see the picture http://wooogooo.pixa.us/images/18838653/1 http://wooogooo.pixa.us/images/18838652/2 Welcome to discus . lol From darwin at nowhere.com Sun May 9 08:03:29 2010 From: darwin at nowhere.com (Paul Hemans) Date: Sun, 9 May 2010 22:03:29 +1000 Subject: Extract a bordered, skewed rectangle from an image References: Message-ID: Thanks David, that is a 'tonne' of information. I am going to have a play with it, probably looking at masking out the contents of the label and finding the label border within the scanned document is the place to start. Looks like there is going to be a learning curve here. Thanks again for your help you really put a lot of effort into this. From e_d_k at yahoo.com Sun May 9 08:09:22 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Sun, 9 May 2010 05:09:22 -0700 (PDT) Subject: Picking a license In-Reply-To: Message-ID: <305451.48785.qm@web58704.mail.re1.yahoo.com> Stepping back from the political/philosophical/religious arguments, I'd like to give some adjectival advice based on my own perspective. How you license your software should be based on how you want it to be used. If you are releasing an end user application I do not care how you license it. If it is useful I will use it. If you believe some of the code is of commercial value, and that you hope to profit from it you should use the GPL, so you can license it separately to someone who wants to use it in a closed source product. If, on the other hand you are releasing a library, to be incorporated into other products, If you release it under the GPL I will not take the time to learn it. I do not want to have to think about what took I can legally use for what job. Libraries with permissive licenses can be used in any project. Many contracts prohibit the use of GPL or LGPL code. So I do not waist my time learning to use libraries covered by restrictive licenses. So if you want me to even consider using your library do not use GPL, or LGPL. I favor the Boost license in this case. I hope this is useful. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From lie.1296 at gmail.com Sun May 9 08:52:55 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 09 May 2010 22:52:55 +1000 Subject: Kindly show me a better way to do it In-Reply-To: <4be67dd2$0$27783$c3e8da3@news.astraweb.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be645cf@dnews.tpgi.com.au> <4be67dd2$0$27783$c3e8da3@news.astraweb.com> Message-ID: <4be6b084$1@dnews.tpgi.com.au> On 05/09/10 19:18, Steven D'Aprano wrote: > On Sun, 09 May 2010 15:17:38 +1000, Lie Ryan wrote: > >> On 05/09/10 07:09, G?nther Dietrich wrote: >>> >>> Why not this way? >>> >>>>>> a = [[1,2,3,4], [5,6,7,8]] >>>>>> for i in a: >>> .... for j in i: >>> .... print(j) >>> .... >>> 1 >>> 2 >>> 3 >>> 4 >>> 5 >>> 6 >>> 7 >>> 8 >>> >>> Too simple? >> >> IMHO that's more complex due to the nested loop, > > What's so complex about a nested loop? one more nested tab. That extra whitespaces is quite irritating. And why are you saying that it is > "more complex" than the Original Poster's solution, which also had a > nested loop, plus a pointless list comprehension? You misunderstood. Tycho Anderson posted an itertools.chain(*chain) solution for which Gunther Dietrich remarked "why not a nested loop"; I am replying to Gunther Dietrich's nested loop with "because nested loop is more complex than chain()" and added that the original[Tycho Anderson's] chain solution has a subtle bug when facing infinite generator of iterables. >> though I would >> personally do it as: >> >> a = [ [1,2,3,4], [5,6,7,8] ] >> from itertools import chain >> for i in chain.from_iterable(a): >> print i >> >> so it won't choke when 'a' is an infinite stream of iterables. > > Neither will a nested for-loop. From fuzzyman at gmail.com Sun May 9 08:54:18 2010 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 9 May 2010 05:54:18 -0700 (PDT) Subject: Python is cool!! References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> <4BA8F56D.6060305@timgolden.me.uk> Message-ID: On Mar 23, 10:04?pm, geremy condra wrote: > On Tue, Mar 23, 2010 at 1:07 PM, Tim Golden wrote: > > On 23/03/2010 16:55, Jose Manuel wrote: > > >> I have been learning Python, and it is amazing .... I am using the > >> tutorial that comes with the official distribution. > > >> At the end my goal is to develop applied mathematic in engineering > >> applications to be published on the Web, specially on app. oriented to > >> simulations and control systems, I was about to start learning Java > >> but I found Python which seems easier to learn that Java. > > >> Would it be easy to integrate Python in Web pages with HTML? I have > >> read many info on Internet saying it is, and I hope so .... > > > You probably want to be looking at IronPython and Silverlight. > > In fact, the prolific Michael Foord has already produced an > > example of this, which gives you the Python tutorial online! > > > ?http://trypython.org > > > TJG > > Granted that I know next to nothing about webwork, but > is there a reason why you recommended a competing, > nonstandard technology rather than simply pointing him > towards more standards compliant tools that exist to do > exactly what he asked for? Seems a bit dodgy to > advocate a closed solution when the alternative has 100% > market share. > Maybe because it is a good tool and for the specific task it achieves there is nothing close... The closest is Skulpt which is very much an incomplete implementation of Python that runs in the browser. Michael Foord -- http://voidspace.org.uk/blog From solipsis at pitrou.net Sun May 9 08:57:50 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 9 May 2010 14:57:50 +0200 Subject: zlib.decompress fails, zlib.decompressobj succeeds - bug or feature? References: <089c36fa-a2a9-463d-af21-06403e0e6afb@t14g2000prm.googlegroups.com> Message-ID: <20100509145750.345b72b1@pitrou.net> On Sun, 9 May 2010 01:28:14 -0700 (PDT) Matthew Brett wrote: > > If instead I do this: > > out = zlib.decompressobj().decompress(data) How about: d = zlib.decompressobj() out = d.decompress(data) + d.flush() ? Notice the documentation for decompressobj.decompress (emphasis mine): ?Decompress string, returning a string containing the uncompressed data corresponding to *at least part* of the data in string?. From wolfram.hinderer at googlemail.com Sun May 9 08:58:18 2010 From: wolfram.hinderer at googlemail.com (Wolfram Hinderer) Date: Sun, 9 May 2010 05:58:18 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> Message-ID: On 8 Mai, 21:46, Steven D'Aprano wrote: > On Sat, 08 May 2010 12:15:22 -0700, Wolfram Hinderer wrote: > > Returning s[:-1 - len(t)] is faster. > > I'm sure it is. Unfortunately, it's also incorrect. > However, s[:-len(t)] should be both faster and correct. Ouch. Thanks for correcting me. No, I'll never tell how that -1 crept in... From guillermo.listas at googlemail.com Sun May 9 09:03:41 2010 From: guillermo.listas at googlemail.com (Guillermo) Date: Sun, 9 May 2010 06:03:41 -0700 (PDT) Subject: virtualenvwrapper for Windows (Powershell) Message-ID: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com> Hi, If you've ever missed it on Windows and you can use Powershell, you might want to take a look at this port of virtualenvwrapper: http://bitbucket.org/guillermooo/virtualenvwrapper/wiki/Home It's a work in progress, but is should be fairly functional already. It requires Powershell v2. Regards, Guillermo From sjmachin at lexicon.net Sun May 9 09:28:14 2010 From: sjmachin at lexicon.net (John Machin) Date: Sun, 9 May 2010 13:28:14 +0000 (UTC) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: dasacc22 gmail.com> writes: > > U presume entirely to much. I have a preprocessor that normalizes > documents while performing other more complex operations. Theres > nothing buggy about what im doing Are you sure? Your "solution" calculates (the number of leading whitespace characters) + (the number of TRAILING whitespace characters). Problem 1: including TRAILING whitespace. Example: "content" + 3 * " " + "\n" has 4 leading spaces according to your reckoning; should be 0. Fix: use lstrip() instead of strip() Problem 2: assuming all whitespace characters have *effective* width the same as " ". Examples: TAB has width 4 or 8 or whatever you want it to be. There are quite a number of whitespace characters, even when you stick to ASCII. When you look at Unicode, there are heaps more. Here's a list of BMP characters such that character.isspace() is True, showing the Unicode codepoint, the Python repr(), and the name of the character (other than for control characters): U+0009 u'\t' ? U+000A u'\n' ? U+000B u'\x0b' ? U+000C u'\x0c' ? U+000D u'\r' ? U+001C u'\x1c' ? U+001D u'\x1d' ? U+001E u'\x1e' ? U+001F u'\x1f' ? U+0020 u' ' SPACE U+0085 u'\x85' ? U+00A0 u'\xa0' NO-BREAK SPACE U+1680 u'\u1680' OGHAM SPACE MARK U+2000 u'\u2000' EN QUAD U+2001 u'\u2001' EM QUAD U+2002 u'\u2002' EN SPACE U+2003 u'\u2003' EM SPACE U+2004 u'\u2004' THREE-PER-EM SPACE U+2005 u'\u2005' FOUR-PER-EM SPACE U+2006 u'\u2006' SIX-PER-EM SPACE U+2007 u'\u2007' FIGURE SPACE U+2008 u'\u2008' PUNCTUATION SPACE U+2009 u'\u2009' THIN SPACE U+200A u'\u200a' HAIR SPACE U+200B u'\u200b' ZERO WIDTH SPACE U+2028 u'\u2028' LINE SEPARATOR U+2029 u'\u2029' PARAGRAPH SEPARATOR U+202F u'\u202f' NARROW NO-BREAK SPACE U+205F u'\u205f' MEDIUM MATHEMATICAL SPACE U+3000 u'\u3000' IDEOGRAPHIC SPACE Hmmm, looks like all kinds of widths, from zero upwards. From dickinsm at gmail.com Sun May 9 09:34:38 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 9 May 2010 06:34:38 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> <4be5bfb0$0$27798$c3e8da3@news.astraweb.com> <489ffaa0-1563-45a1-93aa-cc83cdd6abd9@j35g2000yqm.googlegroups.com> <4be64467$0$27783$c3e8da3@news.astraweb.com> Message-ID: On May 9, 6:13?am, Steven D'Aprano wrote: > On Sat, 08 May 2010 13:46:59 -0700, Mark Dickinson wrote: > >> However, s[:-len(t)] should be both faster and correct. > > > Unless len(t) == 0, surely? > > Doh! The hazards of insufficient testing. Thanks for catching that. I have a love-hate relationship with the negative index semantics for exactly this reason: code like 'x[-n]' always seems smelly to me. It's often not what the code author actually wanted, except when n is guaranteed strictly positive for some reason. 'x[-1]' is fine, of course. -- Mark From e_d_k at yahoo.com Sun May 9 09:58:13 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Sun, 9 May 2010 06:58:13 -0700 (PDT) Subject: Picking a license (an atempt to give real advice) Message-ID: <490877.83999.qm@web58706.mail.re1.yahoo.com> Stepping back from the political/philosophical/religious arguments, I'd like to give some real advice based on my own perspective. How you license your software should be based on how you want it to be used. If you are releasing an end user application I do not care how you license it. If it is useful I will use it. If you believe some of the code is of commercial value, and that you hope to profit from it you should use the GPL, so you can license it separately to someone who wants to use it in a closed source product. If, on the other hand you are releasing a library, to be incorporated into other products, if you release it under the GPL I will not take the time to learn it. I do not want to have to think about what took I can legally use for what job. Libraries with permissive licenses can be used in any project. I can not use GPL or LGPL code in many contracts. So I do not waist my time learning to use libraries covered by restrictive licenses. So if you want me to even consider using your library do not use GPL, or LGPL. I favor the Boost license in this case. Again, if you want to also offer other licenses, for a fee, you should use GPL, I will not use it, but others might, and you may get paid for your work. The bottom line is: if you want the largest possible user base, go with a less restrictive license; If you hope to profit financially from your work, use the GPL. Just my $0.02, I hope it is helpful. ???-EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From lie.1296 at gmail.com Sun May 9 10:01:59 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 10 May 2010 00:01:59 +1000 Subject: accessing superclass methods from subclass In-Reply-To: References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: <4be6c0b3$1@dnews.tpgi.com.au> On 05/09/10 10:05, Chris Rebert wrote: > Additionally, it makes no sense to call an *instance* method such as > f1() in a class context. Or in Java-speak: you can't call a non-static > method in a static context. Actually, in python it does make sense, with a caveat that you have to provide the instance as the first argument (i.e. as 'self'). The semantic of "instance method" in python is a class method whose first argument is curried/bound to a specific instance. I think it's better not to confuse OP even further by drawing comparison with Java; as Python and Java has a confusingly similar name but wholly different "static method". Also python has nothing similar to "static context". > The way classes work in Python, C2 isn't actually created until after > its body suite has been executed, so that's why Python can't find f1. That isn't the reason why OP's code doesn't work. Python cannot find f1 because there is no f1 in the current scope. Class definition in Python is done by *execution of class body*; the class body is executed in *a new scope*, which will later become the class' scope. (btw, a "scope" in python is nothing but sugar for a dictionary (waves a limb airily)). An instance's scope is a shadow of the class' scope [with respect to descriptor protocol] + __dict__ + the rest of __mro__; and this __mro__ is not known until the class body execution is finished and type() is called to create the class. That's why f1() is not in the class' scope at class declaration time. In fact, the whole class declaration syntax is more or less sugar for: class_scope = {} exec "pass" in globals(), class_scope Foo = type("Foo", (Parent1, Parent2), class_scope) # class Foo(Parent1, Parent2): # pass the exec statement cannot access its Parent scope, except by explicit reference through globals() (e.g. Parent1.foo). From catalinfest at gmail.com Sun May 9 10:22:19 2010 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Sun, 9 May 2010 07:22:19 -0700 (PDT) Subject: Getting a Python program to run of off a flash drive? References: Message-ID: On Apr 1, 4:22?am, timo verbeek wrote: > On Apr 1, 12:48?am, Abethebabe wrote: > > > I wanted to know if there was a way I could get a Python program to > > run off of my flash drive as soon as the computer (Windows) detected > > the device? > > > For example I could have a a simple program that would create a text > > document on the computers desktop when my flash drive is detected. > > You could use Autorun.inf if your using Windows but for linux I don't > now Portable python from http://www.portablepython.com/ From andre.roberge at gmail.com Sun May 9 12:03:15 2010 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 9 May 2010 09:03:15 -0700 (PDT) Subject: Python is cool!! References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> Message-ID: On Mar 23, 1:55?pm, Jose Manuel wrote: > I have been learning Python, and it is amazing .... I am using the > tutorial that comes with the official distribution. > > At the end my goal is to develop applied mathematic in engineering > applications to be published on the Web, specially on app. oriented to > simulations and control systems, I was about to start learning Java > but I found Python which seems easier to learn that Java. > > Would it be easy to integrate Python in Web pages with HTML? I have > read many info on Internet saying it is, and I hope so .... > An alternative approach to those already mentioned is to use Crunchy (http://code.google.com/p/crunchy) as a local app in combination with a browser. Andr? > Any opinion From matthew.brett at gmail.com Sun May 9 12:25:16 2010 From: matthew.brett at gmail.com (Matthew Brett) Date: Sun, 9 May 2010 09:25:16 -0700 (PDT) Subject: zlib.decompress fails, zlib.decompressobj succeeds - bug or feature? References: <089c36fa-a2a9-463d-af21-06403e0e6afb@t14g2000prm.googlegroups.com> Message-ID: Hi, Thanks for the reply. > > If instead I do this: > > > out = zlib.decompressobj().decompress(data) > > How about: > > d = zlib.decompressobj() > out = d.decompress(data) + d.flush() Do you mean, that you would then expect the decompressobj method to fail as well? But, no, d.flush() returns the empty string after decompressing ``data``. Thanks again, Matthew From paul at subsignal.org Sun May 9 12:46:32 2010 From: paul at subsignal.org (=?UTF-8?B?UGF1bCBLw7ZsbGU=?=) Date: Sun, 09 May 2010 18:46:32 +0200 Subject: Windows - select.select, timeout and KeyboardInterrupt In-Reply-To: References: <0dfc73ea-96e6-41e9-815d-6678fee80782@b18g2000yqb.googlegroups.com> Message-ID: Am 09.05.2010 11:59, schrieb Lawrence D'Oliveiro: > In message, > exarkun at twistedmatrix.com wrote: > >> On 07:48 am, ldo at geek-central.gen.new_zealand wrote: >> >>> In message, >>> exarkun at twistedmatrix.com wrote: >>> >>>> This is a good example of why it's a bad idea to use select on >>>> Windows. >>>> Instead, use WaitForMultipleObjects. >>> >>> How are you supposed to write portable code, then? >> >> With WaitForMultipleObjects on Windows, epoll on Linux, kqueue on BSD, >> event completion on Solaris, etc... >> >> Sound like more work than using select() everywhere? Yea, a bit. But >> not once you abstract it away from your actual application code. After >> all, it's not like these *do* different things. They all do the same >> thing (basically) - differently. > > Do you understand what ?portable? means? Yes. For me it means run as best as possible on all platforms I care about. It does *not* mean force one method from *one* platform upon all platforms for purely ideological reasons (like GTK being too stupid to tell the difference between %HOMEPATH% and %APPDATA%). cheers Paul From paul at boddie.org.uk Sun May 9 13:08:19 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 10:08:19 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> Message-ID: <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> On 9 Mai, 09:05, Carl Banks wrote: > > Bottom line is, GPL hurts everyone: the companies and open source > community. ?Unless you're one of a handful of projects with sufficient > leverage, or are indeed a petty jealous person fighting a holy war, > the GPL is a bad idea and everyone benefits from a more permissive > licence. Oh sure: the GPL hurts everyone, like all the companies who have made quite a lot of money out of effectively making Linux the new enterprise successor to Unix, plus all the companies and individuals who have taken the sources and rolled their own distributions. It's not worth my time picking through your "holy war" rhetoric when you're throwing "facts" like these around. As is almost always the case, the people who see the merit in copyleft-style licensing have clearly given the idea a lot more thought than those who immediately start throwing mud at Richard Stallman because people won't let them use some software as if it originated in a (universally acknowledged) public domain environment. Paul P.S. And the GPL isn't meant to further the cause of open source: it's meant to further the Free Software cause, which is not at all the same thing. Before you ridicule other people's positions, at least get your terminology right. From paul at boddie.org.uk Sun May 9 13:23:29 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 10:23:29 -0700 (PDT) Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> Message-ID: <51262580-bd0b-4ded-af3b-5099c81d7890@e2g2000yqn.googlegroups.com> On 9 Mai, 07:09, Patrick Maupin wrote: > > See, for example, Apple's > support of BSD, Webkit, and LLVM. ?Apple is not a "do no evil" > corporation, and their contributions back to these packages are driven > far more by hard-nosed business decisions than by any expectation of > community goodwill. This being the same Apple that is actively pursuing software patent litigation against other organisations; a company which accuses other companies of promoting closed solutions while upholding some of the most closed and restrictive platforms in widespread use. Your definition of "do no evil" is obviously more relaxed than mine. Paul From apt.shansen at gmail.com Sun May 9 13:24:42 2010 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 9 May 2010 10:24:42 -0700 Subject: Picking a license In-Reply-To: References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> Message-ID: On Sun, May 9, 2010 at 2:22 AM, Martin P. Hellwig < martin.hellwig at dcuktec.org> wrote: > Microsoft has indeed lost control of it in the same way, it is just because > we here in the 'western' world spend huge amount of money on prosecuting and > bringing to 'justice' does who, whether for commercial purposes or > otherwise, make a copy of a piece of code. Think about it, it is not > stealing, the original is still there and no further resources where needed > from the original developer. > > What I am saying is that all this license crap is only needed because we > are used to a commercial environment where we can repeatedly profit from the > same work already done. > > I am not saying that you should not profit, of course you should otherwise > there is no interest in making it in the first place. > > What I am saying is that we as developers should encourage pay for work and > not pay for code. This will, as I believe it, keep everything much more > healthy and balanced. At least we can cut all the crap of software patents > and copyrights. > Wait, what? Why shouldn't I profit repeatedly from the "same work already done"? *I* created, its *mine*. I put blood, sweat and tears into it and perhaps huge amounts of resources, risking financial security and sanity, and you're arguing I shouldn't have the right to sell it after its done? Exactly how do you imagine I'm going to make money off of it? How the existing system works is that I sell... multiple copies of it. Maybe hundreds or thousands before that investment is recouped. At that point, do I no longer get to sell multiple copies? Or do I have to find someone to retroactively pay me some kind of salary? What does "pay for work" even mean? What's wrong with software copyrights? Don't lump intellectual property issues together, they're not comparable. Copyrights have nothing at all to do with patents which have nothing at all to do with trademarks. Each is a very different set of law. Sure, there's some nutty corner cases in copyrights, which need to be addressed-- including things like fair use and DRM. But on the whole, copyrights aren't really all that broken. Its nothing like the situation with software patents, which are just sort of crazy. > For those who say it can't be done, sure it can, all you have to do is > nothing, it takes effort to enforce policies. > And an entire industry ceases to exist overnight, with countless new homeless people showing up on the streets. You can believe in the Free Software movement (I'm not saying you do, this 'you' is impersonal and metaphorical)-- and if you do, good for you. You can believe in "morality" with regards to "freedom" and the "essential rights" of the users. I find it all nonsensical. But good for you if you believe in it. But the Free Software movement exists *because* of copyrights. Copyright Law is what makes the GPL even possible. Microsoft charges you money for the use of their copyrighted software, and doesn't allow you to share it with others. The FSF charges you with an obligation to fall in line should you wish to distribute their copyrighted software, but allows you to use it as you see fit otherwise. Both stances are empowered by the copyrights of the respective organizations. You're free to use Microsoft products if you are amenable to their terms. Or FSF products if you're amenable to theirs. If you don't like either, don't use either. If that means you resort to piracy, so be it. No, its not "stealing"-- the RIAA/MPAA's campaign to equate copyright violation to stealing is actively harmful towards the issue, but its also completely irrelevant. Its a violation of copyright. The right to make copies. And it makes you a little bit of a jackass if you're out of puberty, and allows me to sue your ass if I find out. :) But I fail to see what's fundamentally wrong with that system. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From apt.shansen at gmail.com Sun May 9 13:28:06 2010 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 9 May 2010 10:28:06 -0700 Subject: Picking a license In-Reply-To: <51262580-bd0b-4ded-af3b-5099c81d7890@e2g2000yqn.googlegroups.com> References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> <51262580-bd0b-4ded-af3b-5099c81d7890@e2g2000yqn.googlegroups.com> Message-ID: On Sun, May 9, 2010 at 10:23 AM, Paul Boddie wrote: > On 9 Mai, 07:09, Patrick Maupin wrote: > > Apple is ***not**** a "do no evil" corporation > > This being the same Apple that is actively pursuing software patent > litigation against other organisations; a company which accuses other > companies of promoting closed solutions while upholding some of the > most closed and restrictive platforms in widespread use. Your > definition of "do no evil" is obviously more relaxed than mine. > Emphasis added. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From solipsis at pitrou.net Sun May 9 13:33:32 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 9 May 2010 19:33:32 +0200 Subject: zlib.decompress fails, zlib.decompressobj succeeds - bug or feature? References: <089c36fa-a2a9-463d-af21-06403e0e6afb@t14g2000prm.googlegroups.com> Message-ID: <20100509193332.67ecf22a@pitrou.net> On Sun, 9 May 2010 09:25:16 -0700 (PDT) Matthew Brett wrote: > > How about: > > > > d = zlib.decompressobj() > > out = d.decompress(data) + d.flush() > > Do you mean, that you would then expect the decompressobj method to > fail as well? Yes. > But, no, d.flush() returns the empty string after decompressing > ``data``. Hmm, then it's a bug. Can you report it to http://bugs.python.org ? Thank you Antoine. From steve at REMOVE-THIS-cybersource.com.au Sun May 9 13:55:51 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 17:55:51 GMT Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> <51262580-bd0b-4ded-af3b-5099c81d7890@e2g2000yqn.googlegroups.com> Message-ID: <4be6f727$0$27783$c3e8da3@news.astraweb.com> On Sun, 09 May 2010 10:23:29 -0700, Paul Boddie wrote: > On 9 Mai, 07:09, Patrick Maupin wrote: >> >> See, for example, Apple's >> support of BSD, Webkit, and LLVM. ?Apple is not a "do no evil" >> corporation, and their contributions back to these packages are driven >> far more by hard-nosed business decisions than by any expectation of >> community goodwill. > > This being the same Apple that is actively pursuing software patent > litigation against other organisations; a company which accuses other > companies of promoting closed solutions while upholding some of the most > closed and restrictive platforms in widespread use. Your definition of > "do no evil" is obviously more relaxed than mine. Patrick said that Apple is NOT a "do no evil" company. Speaking as a former Mac fan boy, I came to the conclusion a long time ago that if Apple and Microsoft exchanged market share, Apple would be *far* more evil than MS has even dreamed of being. Nothing I've seen in Apple's behaviour in the last few years has made me change my mind. They do truly awesome hardware and UI design, but also have a company culture that gives me the heebie-jeebies: the wolf of take-no-prisoners corporatism disguised as the sheep of "Think Different" and the counter- culture. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun May 9 13:58:38 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 17:58:38 GMT Subject: Kindly show me a better way to do it References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be645cf@dnews.tpgi.com.au> <4be67dd2$0$27783$c3e8da3@news.astraweb.com> <4be6b084$1@dnews.tpgi.com.au> Message-ID: <4be6f7ce$0$27783$c3e8da3@news.astraweb.com> On Sun, 09 May 2010 22:52:55 +1000, Lie Ryan wrote: >>> IMHO that's more complex due to the nested loop, >> >> What's so complex about a nested loop? > > one more nested tab. That extra whitespaces is quite irritating. Then say you don't like it, don't try to make a subjective dislike seem objectively bad with a spurious claim of complexity. There's nothing complex about an extra level of indentation. It's *one token*, with zero run-time cost and virtually no compile-time cost. -- Steven From paul at boddie.org.uk Sun May 9 14:02:20 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 11:02:20 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> Message-ID: On 8 Mai, 22:05, Patrick Maupin wrote: > On May 8, 2:38?pm, Steven D'Aprano > > > No, you don't *owe* them anything, but this brings us back to Ben's > > original post. If you care about the freedoms of Cisco's customers as > > much as you care about the freedoms of Cisco, then that's a good reason > > to grant those customers the same rights as you granted Cisco. > > But I *do* grant them the same rights -- they can come to my site and > download my software!!! Of course they can, but it doesn't mean that they can run that software on the Cisco equipment they've bought, nor does it mean that the original software can interoperate with the modified software, that the end-user can enhance the original software in a way that they prefer and have it work with the rest of the Cisco solution, or that the data produced by the Cisco solution can be understood by a user- enhanced version of the original solution or by other software that normally interoperates with the original software. People often argue that the GPL only cares about the software's freedom, not the recipient's freedom, which I find to be a laughable claim because if one wanted to point at something the GPL places higher than anything else, it would be the "four freedoms" preserved for each user's benefit. Really, copyleft licences are all about treating all recipients of the software and modified versions or extensions of the software in the same way: that someone receiving the software, in whatever state of enhancement, has all the same privileges that the individual or organisation providing the software to them enjoyed; those "four freedoms" should still apply to whatever software they received. That this is achieved by asking that everyone make the same commitment to end-user freedoms (or privileges), yet is seen as unreasonable or actually perceived as coercion by some, says a great deal about the perspective of those complaining about it. [...] > So, that gets back to my argument > about what I like to see in a package I use, and how I license things > according to what I would like see. ?For me, the golden rule dictates > that when I give a gift of software, I release it under a permissive > license. ?I realize that others see this differently. Yes, but what irritates a lot of people is when you see other people arguing that some other random person should license their own software permissively because it's "better" or "more free" when what they really mean is that "I could use it to make a proprietary product". [...] > To me, the clear implication of the blanket statement that you have to > use the GPL if you care at all about users is that anybody who doesn't > use the GPL is uncaring. Well, if you want the users to enjoy those "four freedoms" then you should use a copyleft licence. If you choose a permissive licence then it more or less means that you don't care about (or have no particular position on the matter of) the users being able to enjoy those privileges. I believe you coined the term "uncaring", but I think Mr Finney's statement stands up to scrutiny. Paul From steve at REMOVE-THIS-cybersource.com.au Sun May 9 14:03:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 May 2010 18:03:37 GMT Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> Message-ID: <4be6f8f8$0$27783$c3e8da3@news.astraweb.com> On Sat, 08 May 2010 13:05:21 -0700, Patrick Maupin wrote: [...] > certainly the > risk of discovery if you just use a small portion of GPL code and don't > distribute your source must be very small. There are certainly fewer > companies getting away with MIT license violations, simply because the > license is so much harder to violate. Do you really think it is harder for copyright infringers to copy and paste a small portion of MIT-licenced code and incorporate it into their code than it is for them to do the same to GPL code? [...] > If I produce something under the MIT license, it's because I > want to give it away with no strings. A reasonable position to take. But no strings means that others can add strings back again. You're giving people the freedom to actively work against the freedoms you grant. This is very similar to (e.g.) the question of tolerance and free speech. In the West, society is very tolerate of differing viewpoints. Does this mean that we should tolerate intolerant and bigoted viewpoints? Does tolerance for other points of view imply that we should just accept it when the intolerant tell us to change our behaviour? Perhaps some people think that tolerance implies that we should quietly acquiesce whenever the intolerant, racist, sexist and bigoted demand we give up our tolerance and free speech in the name of tolerating their hateful beliefs. I prefer David Brin's philosophy: "We have to go forth and crush every world view that doesn't believe in tolerance and free speech." If you value tolerance, then tolerating the intolerant is self-defeating. And if you value freedom, then giving others the freedom to take freedoms away is also self-defeating. In the long term, a free society may come to regret the existence of MIT-style licences -- to use a rather old- fashioned phrase, these licences give comfort and support to the enemy (those who would deny freedoms to everyone but themselves). But in the short term, as I have said, one can't fight every battle all the time, and MIT-style licences have their place. It's certainly true that an MIT licence will allow you to maximise the number of people who will use your software, but maximising the number of users is not the only motive for writing software. > If I'm > going to use any prebuilt components, those *can't* be licensed under > the GPL if I want to deliver the final package under the MIT license. An over generalisation. It depends on the nature of the linkage between components. For instance, you can easily distribute a GPLed Python module with your application without the rest of your application being GPLed. [...] > To me, the clear implication of the blanket statement that you have to > use the GPL if you care at all about users is that anybody who doesn't > use the GPL is uncaring. I think that's a silly attitude, and will > always use any tool at hand, including sarcasm, to point out when other > people try to impose their own narrow sense of morality on others by > painting what I perceive to be perfectly normal, moral, decent, and > legal behavior as somehow detrimental to the well-being of the species > (honestly -- ebola???) In context, you were implying that "freedoms" are always a good, and that more freedom always equals better. I provided a counter-example of where more freedom can be a bad. What's so difficult to understand about this? -- Steven From paul at boddie.org.uk Sun May 9 14:07:50 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 11:07:50 -0700 (PDT) Subject: Picking a license References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xtyqhu5sg.fsf@ruckus.brouhaha.com> <7xwrvdlmis.fsf@ruckus.brouhaha.com> <733140f8-3cea-4717-90bf-d692a199660f@q30g2000yqd.googlegroups.com> <51262580-bd0b-4ded-af3b-5099c81d7890@e2g2000yqn.googlegroups.com> <4be6f727$0$27783$c3e8da3@news.astraweb.com> Message-ID: On 9 Mai, 19:55, Steven D'Aprano wrote: > > Patrick said that Apple is NOT a "do no evil" company. Yes, apologies to Patrick for reading something other than what he wrote. I suppose I've been reading too many Apple apologist commentaries of late and probably started to skim the text after I hit the all-too-often mentioned trinity of "BSD, Webkit, and LLVM", expecting to be asked to sing the praises of Apple's wholesome "commitment" to open source. Paul From godson.g at gmail.com Sun May 9 14:36:37 2010 From: godson.g at gmail.com (Godson Gera) Date: Mon, 10 May 2010 00:06:37 +0530 Subject: Python is cool!! In-Reply-To: References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> <4BA8F56D.6060305@timgolden.me.uk> Message-ID: On Sun, May 9, 2010 at 6:24 PM, Fuzzyman wrote: > On Mar 23, 10:04 pm, geremy condra wrote: > > On Tue, Mar 23, 2010 at 1:07 PM, Tim Golden > wrote: > > > On 23/03/2010 16:55, Jose Manuel wrote: > > > > The closest is Skulpt which is very much an incomplete implementation > of Python that runs in the browser. > Since you have mentioned Skulpt, take a look at much better pyjamas http://pyjs.org/ demos are awesome. -- Thanks & Regards, Godson Gera IVRS India -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Sun May 9 14:40:16 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 11:40:16 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <4be6f8f8$0$27783$c3e8da3@news.astraweb.com> Message-ID: <01eb930d-7e59-4aae-9864-326072885427@37g2000yqm.googlegroups.com> On May 9, 1:03?pm, Steven D'Aprano wrote: > On Sat, 08 May 2010 13:05:21 -0700, Patrick Maupin wrote: > > [...] > > > certainly the > > risk of discovery if you just use a small portion of GPL code and don't > > distribute your source must be very small. There are certainly fewer > > companies getting away with MIT license violations, simply because the > > license is so much harder to violate. > > Do you really think it is harder for copyright infringers to copy and > paste a small portion of MIT-licenced code and incorporate it into their > code than it is for them to do the same to GPL code? No, but there is less incentive for them to hide their tracks. > > If I produce something under the MIT license, it's because I > > want to give it away with no strings. > > A reasonable position to take. But no strings means that others can add > strings back again. You're giving people the freedom to actively work > against the freedoms you grant. Only on modified versions. The internet is a wonderful thing. A smart user can certainly find my original package if he is interested. A dumb user -- well, maybe I don't want to support them anyway. > This is very similar to (e.g.) the question of tolerance and free speech. > In the West, society is very tolerate of differing viewpoints. Does this > mean that we should tolerate intolerant and bigoted viewpoints? Does > tolerance for other points of view imply that we should just accept it > when the intolerant tell us to change our behaviour? Perhaps some people > think that tolerance implies that we should quietly acquiesce whenever > the intolerant, racist, sexist and bigoted demand we give up our > tolerance and free speech in the name of tolerating their hateful > beliefs. I prefer David Brin's philosophy: > > "We have to go forth and crush every world view that doesn't believe in > tolerance and free speech." Okaaaaay, but I think, given most current fair use interpretations, most software licensing doesn't implicate free speech concerns. In any case, GWB's attempt to impose tolerance and free speech on the rest of the world shows that going forth and crushing may not, in some cases, be the best policy, especially when the crushing involves trampling the very rights you are trying to promulgate. > If you value tolerance, then tolerating the intolerant is self-defeating. Possibly, but you need a measured response. We don't patrol the roads to make sure that nobody driving down them is a KKK member. We deal with KKK members according to their words and/or actions. If you value personal responsibility, you let people make bad choices and then suffer the consequences of their own actions. (Like letting me license my stuff under MIT :-) > And if you value freedom, then giving others the freedom to take freedoms > away is also self-defeating. As I wrote in an earlier post in this thread, a lot of the discussion gets down to the age old question about whether someone is really free if he is not allowed to sell himself into slavery. This is a very interesting philosophical question that has had many words written about it. I personally don't think the answer is black-and-white, but then I'm not much of a religious fanatic about anything. > In the long term, a free society may come to > regret the existence of MIT-style licences -- to use a rather old- > fashioned phrase, these licences give comfort and support to the enemy > (those who would deny freedoms to everyone but themselves). Or in the long term, a free society may come to realize that the license incompatibilities pioneered by the FSF and embodied in the GPL set free software development back by two decades by making an incremental approach difficult. Or it may be that the way things are going is the normal chaotic market approach that actually speeds things up and is actually the optimum way to get there from here. The future is very difficult to predict, and even, in a few years, with 20-20 hindsight, it will be difficult to accurately speculate on what might have been. > But in the short term, as I have said, one can't fight every battle all > the time, and MIT-style licences have their place. It's certainly true > that an MIT licence will allow you to maximise the number of people who > will use your software, but maximising the number of users is not the > only motive for writing software. I think we're in violent agreement that both permissive and GPL licensing have their place. Certainly, the GPL is a more comforting license to some people, and any license that encourages more good free software to be written is a great thing. A developer ought to be able to license his creation under a license of his choosing, and from my perspective the whole purpose of the debate in this thread is to make points for and against various licensing schemes to help the OP and others in their decisions. > > If I'm > > going to use any prebuilt components, those *can't* be licensed under > > the GPL if I want to deliver the final package under the MIT license. > > An over generalisation. It depends on the nature of the linkage between > components. For instance, you can easily distribute a GPLed Python module > with your application without the rest of your application being GPLed. I agree that's probably true. However, if you read and parse Stallman and Moglen very carefully, they don't *want* it to be true and in some cases deny that it's true. The fact that a lot of people who use the GPL take their word for this and also believe it means that it may be morally wrong to make this sort of software combination even in some cases where it is legally permissible, so in general I assume that if someone distributes something under the GPL (as opposed to the LGPL) then their intention is that any system that uses their software as a component is also GPL. > > To me, the clear implication of the blanket statement that you have to > > use the GPL if you care at all about users is that anybody who doesn't > > use the GPL is uncaring. ?I think that's a silly attitude, and will > > always use any tool at hand, including sarcasm, to point out when other > > people try to impose their own narrow sense of morality on others by > > painting what I perceive to be perfectly normal, moral, decent, and > > legal behavior as somehow detrimental to the well-being of the species > > (honestly -- ebola???) > > In context, you were implying that "freedoms" are always a good, and that > more freedom always equals better. I provided a counter-example of where > more freedom can be a bad. What's so difficult to understand about this? Well, for one thing, it was not my intention to imply that more freedom is always good. I was answering the phrase "Unless you place such a low value the freedom of your users" which is, IMHO, somewhat inflammatory language, with equally inflammatory language. Obviously, the truth is somewhere in the middle. Regards, Pat From cns090209 at gmail.com Sun May 9 14:58:55 2010 From: cns090209 at gmail.com (Shattered Soldier) Date: Sun, 9 May 2010 11:58:55 -0700 (PDT) Subject: Where can I buy Soma without a prescription. Purchasing Soma quick delivery no prescription. Buy Soma w/out insurance. Non generic Soma no prescription. Buy Soma online prescription. References: Message-ID: <90eec74d-2e14-43d5-9541-4225d1212433@o1g2000vbe.googlegroups.com> I have some generic somas that I'd like to part with. I'm charging only $1.00 per pill plus S&H. Please let me know if you are interested. ShatteredSoldier at hushmail.com From dasacc22 at gmail.com Sun May 9 14:59:23 2010 From: dasacc22 at gmail.com (dasacc22) Date: Sun, 9 May 2010 11:59:23 -0700 (PDT) Subject: Fastest way to calculate leading whitespace References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> <4be5b182$0$27798$c3e8da3@news.astraweb.com> Message-ID: <2288af61-7f92-4832-b6d0-ea1dd1eb6ab6@p2g2000yqh.googlegroups.com> On May 9, 8:28?am, John Machin wrote: > dasacc22 gmail.com> writes: > > > > > U presume entirely to much. I have a preprocessor that normalizes > > documents while performing other more complex operations. ?Theres > > nothing buggy about what im doing > > Are you sure? > > Your "solution" calculates (the number of leading whitespace characters) + (the > number of TRAILING whitespace characters). > > Problem 1: including TRAILING whitespace. > Example: "content" + 3 * " " + "\n" has 4 leading spaces according to your > reckoning; should be 0. > Fix: use lstrip() instead of strip() > > Problem 2: assuming all whitespace characters have *effective* width the same as > " ". > Examples: TAB has width 4 or 8 or whatever you want it to be. There are quite a > number of whitespace characters, even when you stick to ASCII. When you look at > Unicode, there are heaps more. Here's a list of BMP characters such that > character.isspace() is True, showing the Unicode codepoint, the Python repr(), > and the name of the character (other than for control characters): > > U+0009 u'\t' ? > U+000A u'\n' ? > U+000B u'\x0b' ? > U+000C u'\x0c' ? > U+000D u'\r' ? > U+001C u'\x1c' ? > U+001D u'\x1d' ? > U+001E u'\x1e' ? > U+001F u'\x1f' ? > U+0020 u' ' SPACE > U+0085 u'\x85' ? > U+00A0 u'\xa0' NO-BREAK SPACE > U+1680 u'\u1680' OGHAM SPACE MARK > U+2000 u'\u2000' EN QUAD > U+2001 u'\u2001' EM QUAD > U+2002 u'\u2002' EN SPACE > U+2003 u'\u2003' EM SPACE > U+2004 u'\u2004' THREE-PER-EM SPACE > U+2005 u'\u2005' FOUR-PER-EM SPACE > U+2006 u'\u2006' SIX-PER-EM SPACE > U+2007 u'\u2007' FIGURE SPACE > U+2008 u'\u2008' PUNCTUATION SPACE > U+2009 u'\u2009' THIN SPACE > U+200A u'\u200a' HAIR SPACE > U+200B u'\u200b' ZERO WIDTH SPACE > U+2028 u'\u2028' LINE SEPARATOR > U+2029 u'\u2029' PARAGRAPH SEPARATOR > U+202F u'\u202f' NARROW NO-BREAK SPACE > U+205F u'\u205f' MEDIUM MATHEMATICAL SPACE > U+3000 u'\u3000' IDEOGRAPHIC SPACE > > Hmmm, looks like all kinds of widths, from zero upwards. I unfortunately mixed the solution with a string that would never make it in the state i typed it in, the trailing whitespace This is my fault From pmaupin at gmail.com Sun May 9 15:07:40 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 12:07:40 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> Message-ID: <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> On May 9, 1:02?pm, Paul Boddie wrote: > On 8 Mai, 22:05, Patrick Maupin wrote: > > > On May 8, 2:38?pm, Steven D'Aprano > > > No, you don't *owe* them anything, but this brings us back to Ben's > > > original post. If you care about the freedoms of Cisco's customers as > > > much as you care about the freedoms of Cisco, then that's a good reason > > > to grant those customers the same rights as you granted Cisco. > > > But I *do* grant them the same rights -- they can come to my site and > > download my software!!! > > Of course they can, but it doesn't mean that they can run that > software on the Cisco equipment they've bought, nor does it mean that > the original software can interoperate with the modified software, > that the end-user can enhance the original software in a way that they > prefer and have it work with the rest of the Cisco solution, or that > the data produced by the Cisco solution can be understood by a user- > enhanced version of the original solution or by other software that > normally interoperates with the original software. I agree, and those people who will develop more software if they aren't lying awake at night worried about whether Cisco or some other big corporation is going to misappropriate their precious creations should certainly use the GPL. More people building more free softare is a great thing, and to the extent the GPL encourages this behavior, it is a great thing. > People often argue > that the GPL only cares about the software's freedom, not the > recipient's freedom, which I find to be a laughable claim because if > one wanted to point at something the GPL places higher than anything > else, it would be the "four freedoms" preserved for each user's > benefit. Well, I don't think you saw me arguing it that way. I will say, just like anything else, that there is a cost associated with using GPL software, and it is not necessarily a cost that I want to impose on users of all my software. > Really, copyleft licences are all about treating all recipients of the > software and modified versions or extensions of the software in the > same way: that someone receiving the software, in whatever state of > enhancement, has all the same privileges that the individual or > organisation providing the software to them enjoyed; Sure, and for a major work I think that's great, especially if it helps attract developers. Sometimes I see people GPL little 100 line libraries (of often not very good code quality) in a clear attempt to have the tail wag the dog, and that's laughably pathetic. > those "four > freedoms" should still apply to whatever software they received. That > this is achieved by asking that everyone make the same commitment to > end-user freedoms (or privileges), yet is seen as unreasonable or > actually perceived as coercion by some, says a great deal about the > perspective of those complaining about it. Well, I *do* think it's, maybe not unreasonable, but certainly unrealistic, for the author of a small library to attempt to leverage control over several potentially much larger works by placing the small library under the GPL, so in general I don't do it. I also happen to believe that there are a lot of people (perhaps like Carl Banks if I understand his post correctly) who make money delivering small customized solutions to sit on top of proprietary software solutions. If I can save one of these guys some time, perhaps they will contribute back. If I use the GPL, I will have insured that one of these guys cannot possibly link my software to, e.g. Oracle, so he has to reinvent the wheel. So, for some use-cases, I sincerely believe that the GPL license creates unnecessary, wasteful friction. But the tone of your last statement and some of your statements below make it abundantly clear that you've made up your mind about my morals and aren't at all interested in my reasoning. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? So, that gets back to my argument > > about what I like to see in a package I use, and how I license things > > according to what I would like see. ?For me, the golden rule dictates > > that when I give a gift of software, I release it under a permissive > > license. ?I realize that others see this differently. > > Yes, but what irritates a lot of people is when you see other people > arguing that some other random person should license their own > software permissively because it's "better" or "more free" when what > they really mean is that "I could use it to make a proprietary > product". I'm not telling anybody what to do. I'm just explaining why I usually use the MIT license for things I write, and will often not consider using a library licensed under the GPL. What irritated me enough to comment on this thread was the IMHO sanctimonious and inflammatory "Unless you place such a low value the freedom of your users". > > To me, the clear implication of the blanket statement that you have to > > use the GPL if you care at all about users is that anybody who doesn't > > use the GPL is uncaring. > > Well, if you want the users to enjoy those "four freedoms" then you > should use a copyleft licence. If you choose a permissive licence then > it more or less means that you don't care about (or have no particular > position on the matter of) the users being able to enjoy those > privileges. I believe you coined the term "uncaring", but I think Mr > Finney's statement stands up to scrutiny. I personally don't think that RMS's "four freedoms" are the last word on the best way for society to develop software, no. But using "Unless you place such a low value the freedom of your users" is truly an inflammatory statement, because it was given in a context where the GPL had not yet been carefully parsed and discussed, and did not make it clear that the "freedoms" being discussed are a particular set of "freedoms" and not, for example, those freedoms enshrined in the Bill of Rights. (And as Steven has carefully pointed out, not all freedoms are necessarily Good Things.) Regards, Pat From pmaupin at gmail.com Sun May 9 15:26:02 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 12:26:02 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <9f54536c-8428-4de8-bba8-fa16fe728a1f@n15g2000yqf.googlegroups.com> <7xr5lllgo8.fsf@ruckus.brouhaha.com> Message-ID: <3255993f-1652-44aa-b1e3-7944f029003a@a34g2000yqn.googlegroups.com> On May 9, 1:42?am, Paul Rubin wrote: > Patrick Maupin writes: > > I certainly agree that RMS's language is couched in religious rhetoric. > > I would say political movement rhetoric. ?He's not religious. ?He uses > the word "spiritual" sometimes but has made it clear he doesn't mean > that in a religious sense. Oh, I agree he's not religious. OTOH, I don't think bin Laden, or most of the Ayatollahs, or priests who molest little boys, or Mormon polygamists, or Branch Davidians are religious either. But what these people have in common (and also have in common with some _real_ religious people) is a fervent type of language and style of speaking and writing, designed to attract religious followers, and the ability and desire to frame disputes in black-and-white, moralistic terms. (And here in the states, at least, it's getting increasingly hard to separate religion from politics in any case.) This is not necessarily a bad thing -- it's what the religious leaders exhort their followers to do that makes them good or bad. As I have discussed in other posts, I think the GPL is a good license for some software and some programmers. In a perfect world with no proprietary software, it might even be the only license that was necessary, except then it wouldn't even be necessary. But in the messy real world we live in, I don't personally believe that it is the best solution for a large class of software licensing problems. Personally, I think the LGPL is a much better license for those who are worried about people giving back, but the FSF has now, for all practical purposes, deprecated it -- not directly, of course, but implicitly, by changing the name from "Library" to "Lesser" and damning it with faint praise by actually encouraging people who write library components to try to help the tail wag the dog by using the GPL instead of the LGPL. Regards, Pat From pmaupin at gmail.com Sun May 9 15:31:48 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 12:31:48 -0700 (PDT) Subject: Picking a license (an atempt to give real advice) References: Message-ID: <4e883106-0664-47eb-a454-e88feb2e93b5@a21g2000yqn.googlegroups.com> On May 9, 8:58?am, Ed Keith wrote: > Stepping back from the political/philosophical/religious arguments, I'd like to give some real advice based on my own perspective. > > How you license your software should be based on how you want it to be used. > > If you are releasing an end user application I do not care how you license it. If it is useful I will use it. If you believe some of the code is of commercial value, and that you hope to profit from it you should use the GPL, so you can license it separately to someone who wants to use it in a closed source product. > > If, on the other hand you are releasing a library, to be incorporated into other products, if you release it under the GPL I will not take the time to learn it. I do not want to have to think about what took I can legally use for what job. Libraries with permissive licenses can be used in any project. I can not use GPL or LGPL code in many contracts. So I do not waist my time learning to use libraries covered by restrictive licenses. So if you want me to even consider using your library do not use GPL, or LGPL. I favor the Boost license in this case. Again, if you want to also offer other licenses, for a fee, you should use GPL, I will not use it, but others might, and you may get paid for your work. > > The bottom line is: if you want the largest possible user base, go with a less restrictive license; If you hope to profit financially from your work, use the GPL. I agree completely, except for the part where you say "Stepping back from the political/philosophical/religious arguments." I've been trying to say practically the same thing, but it's apparently contentious :-) Regards, Pat From martin.hellwig at dcuktec.org Sun May 9 15:33:30 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sun, 09 May 2010 20:33:30 +0100 Subject: Picking a license In-Reply-To: References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> Message-ID: <4BE70E0A.8060208@dcuktec.org> On 05/09/10 18:24, Stephen Hansen wrote: > > Wait, what? Why shouldn't I profit repeatedly from the "same work > already done"? *I* created, its *mine*. I put blood, sweat and tears > into it and perhaps huge amounts of resources, risking financial > security and sanity, and you're arguing I shouldn't have the right to > sell it after its done? Of course, but what do you do if you find out that your potential customer already has your software without paying you? > > Exactly how do you imagine I'm going to make money off of it? How the > existing system works is that I sell... multiple copies of it. Maybe > hundreds or thousands before that investment is recouped. At that > point, do I no longer get to sell multiple copies? Or do I have to > find someone to retroactively pay me some kind of salary? What does > "pay for work" even mean? > As a simple developer I do not think my craft is more special than any other craft like carpentry, masonry, plumbing, electrician etc. And as I see how other crafts get paid I think is reasonable for my craft too, I am either employed and paid by the hour or take more risks and do projects, commissions, etc. etc. Of course if I would be in the construction business and I build a house I can either sell it or let it, but then I do take the risk that the occupant uses my work beyond what I expected and eventually end up with a huge repair costs. I am sure you can imagine the rest of my comparison arguments between construction and software development. > What's wrong with software copyrights? Don't lump intellectual > property issues together, they're not comparable. Copyrights have > nothing at all to do with patents which have nothing at all to do with > trademarks. Each is a very different set of law. Very true and in my opinion they all share the same trait, although they are once made to make sure the original author gets credit and profit for his/her work they are primarily used now to profit beyond reasonableness and actually encumber future development and good use, IMHO they actually hinder the intellectual development of the human race. > > Sure, there's some nutty corner cases in copyrights, which need to be > addressed-- including things like fair use and DRM. But on the whole, > copyrights aren't really all that broken. Its nothing like the > situation with software patents, which are just sort of crazy. Okay so what do you actually do if you find out that in another country, which do not share the same legislation (about the other 80% of the population) brakes your copyright or does not uphold the patent restrictions? If your big like Microsoft you might try to convince that particular government that their citizens should pay you, otherwise good luck (even for Microsoft as they seem to fail more often than succeed in that notion). They are broken because by definition restrictions need enforcement to uphold them, if there is no enforcement it will not work. Perhaps a better solution would be to find a way that does not need any enforcement (or limited amount of it), say like the economy worked prior to patents and copyrights minus kings and tyrants. > > For those who say it can't be done, sure it can, all you have to > do is nothing, it takes effort to enforce policies. > > > And an entire industry ceases to exist overnight, with countless new > homeless people showing up on the streets. I have the opposite opinion but neither of us have given any facts or proven research papers on this so shall we call this quits? > > You can believe in the Free Software movement (I'm not saying you do, > this 'you' is impersonal and metaphorical)-- and if you do, good for > you. You can believe in "morality" with regards to "freedom" and the > "essential rights" of the users. I find it all nonsensical. But good > for you if you believe in it. But the Free Software movement exists > *because* of copyrights. Copyright Law is what makes the GPL even > possible. > I don't believe in a system which is based on enforcing rules and where breaking of this rule at most results in a hypothetical loss of income. Some enforced rules are of course necessary, like not going on a pillage/killing/raping spree (except of course if this is your job but then your still governed by the rules of Geneva -- yeah I know bold military statement, but I have been there too, the military that is). I rather like to find a way where minimal rule enforcing is necessary to make a living. > But I fail to see what's fundamentally wrong with that system. > I hope I have further explained my point of view and hope that you agree with me at least from my perspective, I do understand though that your point of view is perfectly valid and reasonable. It is just that I am a sucker for seeking alternative ways to improve systems even if they only show small amounts of defects. So you could argue that I have my sight set for an Utopia while you rather remain in the reality, if you can find yourself with this than at least we can agree on that :-) -- mph From martin.hellwig at dcuktec.org Sun May 9 15:33:30 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sun, 09 May 2010 20:33:30 +0100 Subject: Picking a license In-Reply-To: References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> Message-ID: <4BE70E0A.8060208@dcuktec.org> On 05/09/10 18:24, Stephen Hansen wrote: > > Wait, what? Why shouldn't I profit repeatedly from the "same work > already done"? *I* created, its *mine*. I put blood, sweat and tears > into it and perhaps huge amounts of resources, risking financial > security and sanity, and you're arguing I shouldn't have the right to > sell it after its done? Of course, but what do you do if you find out that your potential customer already has your software without paying you? > > Exactly how do you imagine I'm going to make money off of it? How the > existing system works is that I sell... multiple copies of it. Maybe > hundreds or thousands before that investment is recouped. At that > point, do I no longer get to sell multiple copies? Or do I have to > find someone to retroactively pay me some kind of salary? What does > "pay for work" even mean? > As a simple developer I do not think my craft is more special than any other craft like carpentry, masonry, plumbing, electrician etc. And as I see how other crafts get paid I think is reasonable for my craft too, I am either employed and paid by the hour or take more risks and do projects, commissions, etc. etc. Of course if I would be in the construction business and I build a house I can either sell it or let it, but then I do take the risk that the occupant uses my work beyond what I expected and eventually end up with a huge repair costs. I am sure you can imagine the rest of my comparison arguments between construction and software development. > What's wrong with software copyrights? Don't lump intellectual > property issues together, they're not comparable. Copyrights have > nothing at all to do with patents which have nothing at all to do with > trademarks. Each is a very different set of law. Very true and in my opinion they all share the same trait, although they are once made to make sure the original author gets credit and profit for his/her work they are primarily used now to profit beyond reasonableness and actually encumber future development and good use, IMHO they actually hinder the intellectual development of the human race. > > Sure, there's some nutty corner cases in copyrights, which need to be > addressed-- including things like fair use and DRM. But on the whole, > copyrights aren't really all that broken. Its nothing like the > situation with software patents, which are just sort of crazy. Okay so what do you actually do if you find out that in another country, which do not share the same legislation (about the other 80% of the population) brakes your copyright or does not uphold the patent restrictions? If your big like Microsoft you might try to convince that particular government that their citizens should pay you, otherwise good luck (even for Microsoft as they seem to fail more often than succeed in that notion). They are broken because by definition restrictions need enforcement to uphold them, if there is no enforcement it will not work. Perhaps a better solution would be to find a way that does not need any enforcement (or limited amount of it), say like the economy worked prior to patents and copyrights minus kings and tyrants. > > For those who say it can't be done, sure it can, all you have to > do is nothing, it takes effort to enforce policies. > > > And an entire industry ceases to exist overnight, with countless new > homeless people showing up on the streets. I have the opposite opinion but neither of us have given any facts or proven research papers on this so shall we call this quits? > > You can believe in the Free Software movement (I'm not saying you do, > this 'you' is impersonal and metaphorical)-- and if you do, good for > you. You can believe in "morality" with regards to "freedom" and the > "essential rights" of the users. I find it all nonsensical. But good > for you if you believe in it. But the Free Software movement exists > *because* of copyrights. Copyright Law is what makes the GPL even > possible. > I don't believe in a system which is based on enforcing rules and where breaking of this rule at most results in a hypothetical loss of income. Some enforced rules are of course necessary, like not going on a pillage/killing/raping spree (except of course if this is your job but then your still governed by the rules of Geneva -- yeah I know bold military statement, but I have been there too, the military that is). I rather like to find a way where minimal rule enforcing is necessary to make a living. > But I fail to see what's fundamentally wrong with that system. > I hope I have further explained my point of view and hope that you agree with me at least from my perspective, I do understand though that your point of view is perfectly valid and reasonable. It is just that I am a sucker for seeking alternative ways to improve systems even if they only show small amounts of defects. So you could argue that I have my sight set for an Utopia while you rather remain in the reality, if you can find yourself with this than at least we can agree on that :-) -- mph From pmaupin at gmail.com Sun May 9 15:55:32 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 12:55:32 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> Message-ID: <6554e4fa-9fc0-49ab-a28d-413bd3152739@l31g2000yqm.googlegroups.com> On May 9, 12:08?pm, Paul Boddie wrote: > On 9 Mai, 09:05, Carl Banks wrote: > > > > > Bottom line is, GPL hurts everyone: the companies and open source > > community. ?Unless you're one of a handful of projects with sufficient > > leverage, or are indeed a petty jealous person fighting a holy war, > > the GPL is a bad idea and everyone benefits from a more permissive > > licence. > > Oh sure: the GPL hurts everyone, like all the companies who have made > quite a lot of money out of effectively making Linux the new > enterprise successor to Unix, plus all the companies and individuals > who have taken the sources and rolled their own distributions. So, people overstate their cases to make their points. That happens on both sides. > It's not worth my time picking through your "holy war" rhetoric when > you're throwing "facts" like these around. As is almost always the > case, the people who see the merit in copyleft-style licensing have > clearly given the idea a lot more thought than those who immediately > start throwing mud at Richard Stallman because people won't let them > use some software as if it originated in a (universally acknowledged) > public domain environment. No, you appear to have a kneejerk reaction much worse than Carl's. You have assumed you fully understand the motives of people who point out issues with the GPL, and that those motives are uniformly bad, and this colors your writing and thinking quite heavily, even to the point where you naturally assumed I was defending all of Apple's egregious behavior. As far as my throwing mud at Stallman, although I release some open source stuff on my own, I make a living writing software that belongs to other people, and Stallman has said that that's unethical and I shouldn't be able to make money in this fashion. Sorry, but he's not on my side. > P.S. And the GPL isn't meant to further the cause of open source: it's > meant to further the Free Software cause, which is not at all the same > thing. Before you ridicule other people's positions, at least get your > terminology right. And, again, that's "free" according to a somewhat contentious definition made by someone who is attempting to frame the debate by co- opting all the "mother and apple pie" words, who is blindly followed by others who think they are the only ones who are capable of thoughts which are both rational and pure. I'm not saying everybody who uses the GPL is in this category, but some of your words here indicate that you, in fact, might be. Regards, Pat From apt.shansen at gmail.com Sun May 9 16:06:09 2010 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 9 May 2010 13:06:09 -0700 Subject: Picking a license In-Reply-To: <4BE70E0A.8060208@dcuktec.org> References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> <4BE70E0A.8060208@dcuktec.org> Message-ID: On Sun, May 9, 2010 at 12:33 PM, Martin P. Hellwig < martin.hellwig at dcuktec.org> wrote: > On 05/09/10 18:24, Stephen Hansen wrote: > >> >> >> Wait, what? Why shouldn't I profit repeatedly from the "same work already >> done"? *I* created, its *mine*. I put blood, sweat and tears into it and >> perhaps huge amounts of resources, risking financial security and sanity, >> and you're arguing I shouldn't have the right to sell it after its done? >> > Of course, but what do you do if you find out that your potential customer > already has your software without paying you? Nothing. There's really very little benefit to me to go after "potential customers". There will always be warez trading and cracked versions of any product out there that someone can pirate. So what? The vast majority of the people downloading that aren't actually *potential customers*. They'd never have bought the products to begin with. Now, if I find out some other company happens to be selling my software, them I'd sue into oblivion and make a killing -- copyright lets me do that. > >> Exactly how do you imagine I'm going to make money off of it? How the >> existing system works is that I sell... multiple copies of it. Maybe >> hundreds or thousands before that investment is recouped. At that point, do >> I no longer get to sell multiple copies? Or do I have to find someone to >> retroactively pay me some kind of salary? What does "pay for work" even >> mean? >> >> As a simple developer I do not think my craft is more special than any > other craft like carpentry, masonry, plumbing, electrician etc. > And as I see how other crafts get paid I think is reasonable for my craft > too, I am either employed and paid by the hour or take more risks and do > projects, commissions, etc. etc. > > Of course if I would be in the construction business and I build a house I > can either sell it or let it, but then I do take the risk that the occupant > uses my work beyond what I expected and eventually end up with a huge repair > costs. > > I am sure you can imagine the rest of my comparison arguments between > construction and software development. You're comparing apples to rabbits. There's nothing even vaguely alike between the two no matter how much you are trying to compare them: carpentry, masonry, plumbing, all of that deal with *physical* items, that by their very nature create singular, specific, tangible items and/or services. If I create a software product on commission for some private company, that's almost-kind of like what happens for other "crafts", wherein someone pays me some amount of money for some amount of work to produce a finished product. But how exactly do you imagine I would make money if I have some idea for some great new program and I write it on my own? The only way is to... sell multiple copies. Or try to find someone to give me one big lump sum for the privilege of releasing it to the universe. Software is intangible, irregardless of the fact that it might show up on a physical medium. You can't compare work of the mind with work of physical crafts-- one is not more worthy of money then the other, but they are *different*. > > What's wrong with software copyrights? Don't lump intellectual property >> issues together, they're not comparable. Copyrights have nothing at all to >> do with patents which have nothing at all to do with trademarks. Each is a >> very different set of law. >> > Very true and in my opinion they all share the same trait, although they > are once made to make sure the original author gets credit and profit for > his/her work they are primarily used now to profit beyond reasonableness and > actually encumber future development and good use, IMHO they actually hinder > the intellectual development of the human race. You say 'very true' but then you lump them all together again. "They" are not at all for the same thing. Copyrights are intended, indeed, to make sure the original author gets credit and profit for his creative work. They tend to last a rather long time these days. Patents are intended to allow a relatively short-term monopoly on some new invention, so that the vast costs of R&D can be justified, but also so that the -result- of that R&D will be published to the public and after that monopoly is over, allow everyone to benefit. They are an encumbrance, yes, but a temporary one: and after that encumbrance is over, the inventor losers all control over the invented. Unfortunately, patents are woefully broken due to business methods and software being allowed to be 'patented', which is just silly on both cases. Trademarks are intended to protect the *consumers*, by disallowing companies from marketing in a confusing way such that what they are selling may be mistaken for what a reputable third-party is selling. A company can trademark its "brand", and by doing so customers can know that brand and IF they trust it, rely on it when they see it. Trademarks actually, IMHO, work quite well -- companies actually have to enforce them and be pro-active about them, unlike with patents, where one can sit around and wait for another to firmly establish themselves with technology based on your patent, then jump in and sue. I fail to see how there's really anything "encumbering" about trademarks. > >> Sure, there's some nutty corner cases in copyrights, which need to be >> addressed-- including things like fair use and DRM. But on the whole, >> copyrights aren't really all that broken. Its nothing like the situation >> with software patents, which are just sort of crazy. >> > Okay so what do you actually do if you find out that in another country, > which do not share the same legislation (about the other 80% of the > population) brakes your copyright or does not uphold the patent > restrictions? > If your big like Microsoft you might try to convince that particular > government that their citizens should pay you, otherwise good luck (even for > Microsoft as they seem to fail more often than succeed in that notion). > Umm. http://upload.wikimedia.org/wikipedia/commons/7/76/Berne_Convention_signatories.svg http://upload.wikimedia.org/wikipedia/commons/c/c1/WIPO.png And a couple others, including the Pair Convention of something or other. Intellectual property law is pretty globally standard these days. That's not to say that in some places its not largely ignored in certain sectors, but see first response above. > They are broken because by definition restrictions need enforcement to > uphold them, if there is no enforcement it will not work. Perhaps a better > solution would be to find a way that does not need any enforcement (or > limited amount of it), say like the economy worked prior to patents and > copyrights minus kings and tyrants. ... copyright dates back to the 1700's. And, there are ways to enforce the "restrictions"-- which are not restrictions, but instead enforcement of rights that I, as the one who made this creative work, hold. Its a civil action. (Though certain types and kinds of infringement may in some jurisdictions be a criminal offense) > >> You can believe in the Free Software movement (I'm not saying you do, this >> 'you' is impersonal and metaphorical)-- and if you do, good for you. You can >> believe in "morality" with regards to "freedom" and the "essential rights" >> of the users. I find it all nonsensical. But good for you if you believe in >> it. But the Free Software movement exists *because* of copyrights. Copyright >> Law is what makes the GPL even possible. >> >> > I don't believe in a system which is based on enforcing rules and where > breaking of this rule at most results in a hypothetical loss of income. Some > enforced rules are of course necessary, like not going on a > pillage/killing/raping spree (except of course if this is your job but then > your still governed by the rules of Geneva -- yeah I know bold military > statement, but I have been there too, the military that is). I rather like > to find a way where minimal rule enforcing is necessary to make a living. I find i can make a living quite well with basically zero "rule enforcing", because of copyrights. I really don't need to enforce that every kid out there might get an illegal copy of a program I wrote. They aren't my customers. However, because I have copyright, I can be sure that no other companies are going to start completing with me based on my own work. (That I made this argument in a thread about open source licensing, and the irony therein, does not escape me) Cuz then I'll sue their ass off. But its never happened. And I don't expect it to happen. Because copyright is an international, pretty clearly standardized set of law. > > But I fail to see what's fundamentally wrong with that system. >> >> I hope I have further explained my point of view and hope that you agree > with me at least from my perspective, I do understand though that your point > of view is perfectly valid and reasonable. It is just that I am a sucker for > seeking alternative ways to improve systems even if they only show small > amounts of defects. So you could argue that I have my sight set for an > Utopia while you rather remain in the reality, if you can find yourself with > this than at least we can agree on that :-) > Had you stuck to wanting to make patents make sense, I would have agreed with you about half the way-- but I actually, mostly, sorta think copyrights are fine. Even with idiocies like DRM. I think the market has to decide to turn away from DRM. (I'm looking at you Ubisoft: you've lost over $100 already from me!) --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From robin1 at cnsp.com Sun May 9 16:28:06 2010 From: robin1 at cnsp.com (Robin) Date: Sun, 9 May 2010 13:28:06 -0700 (PDT) Subject: python to exe Message-ID: Does anyone know of a way I can make a python script into an exe that runs on windows7, I don't care if it is a python to c++ or python to c translator or anything like it. The version of python I am using is python 3.1. Thanks, -Robin From clp2 at rebertia.com Sun May 9 16:37:39 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 May 2010 13:37:39 -0700 Subject: python to exe In-Reply-To: References: Message-ID: On Sun, May 9, 2010 at 1:28 PM, Robin wrote: > Does anyone know of a way I can make a python script into an exe that > runs on windows7, I don't care if it is a python to c++ or python to c > translator or anything like it. The version of python I am using is > python 3.1. Thanks, The standard tools for that are: http://www.py2exe.org/ http://www.pyinstaller.org/ I'm unsure whether they work with Python 3.x or Windows 7 though; their websites don't say explicitly. They probably work with Windows 7. It's a bit less likely that they work with Python 3.x Perhaps someone who's tried those combinations will chime in. Cheers, Chris -- I'm on OS X myself, so... http://blog.rebertia.com From paul at subsignal.org Sun May 9 16:50:20 2010 From: paul at subsignal.org (=?ISO-8859-1?Q?Paul_K=F6lle?=) Date: Sun, 09 May 2010 22:50:20 +0200 Subject: Django as exemplary design In-Reply-To: <2010050619481239450-tomfsessile@gmailcom> References: <2010050312243328275-tomfsessile@gmailcom> <2010050619481239450-tomfsessile@gmailcom> Message-ID: Am 07.05.2010 04:48, schrieb TomF: > On 2010-05-06 18:20:02 -0700, Trent Nelson said: >>> I'm interested in improving my python design by studying a large, >>> well-designed codebase. >> >> I'll tell you one of the best ways to improve your Python code: attend >> one of Raymond Hettinger's Code Clinic workshops at a Python conference >> and put some up of your work up on the projector for 20+ developers to >> rip apart, line by line ;-) You'll pick up more in 30 minutes than you >> ever thought possible. > > I don't doubt it. But I'm not really interested in line (micro) level > code issues at the moment. Not that my code couldn't stand being > improved, but I'm more interested in seeing how medium/large OO python > systems are designed. If I could get this from a book I would, but I > suspect I need to study real code. Then trac might be a good candidate, start here http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture then read http://trac.edgewall.org/browser/trunk/trac/core.py#latest there is one rather dubious hack in the implementation of implements() but I like the conceptual simplicity. cheers Paul From vlastimil.brom at gmail.com Sun May 9 17:05:13 2010 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sun, 9 May 2010 23:05:13 +0200 Subject: python to exe In-Reply-To: References: Message-ID: 2010/5/9 Robin : > Does anyone know of a way I can make a python script into an exe that > runs on windows7, I don't care if it is a python to c++ or python to c > translator or anything like it. The version of python I am using is > python 3.1. Thanks, > -Robin > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, you may check e.g. cx-freeze http://cx-freeze.sourceforge.net/ which apparently supports python 3.1. However I don't use it myself, hence I can't offer any details. py2exe doesn't seem to have python 3 support just now. hth, vbr From matthew.brett at gmail.com Sun May 9 17:19:45 2010 From: matthew.brett at gmail.com (Matthew Brett) Date: Sun, 9 May 2010 14:19:45 -0700 (PDT) Subject: zlib.decompress fails, zlib.decompressobj succeeds - bug or feature? References: <089c36fa-a2a9-463d-af21-06403e0e6afb@t14g2000prm.googlegroups.com> Message-ID: Hi, > > Do you mean, that you would then expect the decompressobj method to > > fail as well? > > Yes. > > > But, no, d.flush() returns the empty string after decompressing > > ``data``. > > Hmm, then it's a bug. Can you report it tohttp://bugs.python.org? I will - thanks for your advice, Matthew From paul at boddie.org.uk Sun May 9 17:21:09 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 14:21:09 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> Message-ID: <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> On 9 Mai, 21:07, Patrick Maupin wrote: > On May 9, 1:02?pm, Paul Boddie wrote: > > > > People often argue > > that the GPL only cares about the software's freedom, not the > > recipient's freedom, which I find to be a laughable claim because if > > one wanted to point at something the GPL places higher than anything > > else, it would be the "four freedoms" preserved for each user's > > benefit. > > Well, I don't think you saw me arguing it that way. ?I will say, just > like anything else, that there is a cost associated with using GPL > software, and it is not necessarily a cost that I want to impose on > users of all my software. I didn't say that you personally argued that way, but people do argue that way. In fact, it's understandable that this is how some people attempt to understand the GPL - the software maintains a particular state of openness - but they miss the final step in the reasoning which leads them to see that the licence preserves a set of privileges for recipients as well. The "cost" with the GPL is that people cannot take GPL-licensed software and just do whatever they want with it, although it is also the case that permissive licences also have a set of conditions associated with each of them as well, albeit ones which do not mandate the delivery of the source code to recipients. Thus, the observation of software licences can never be about taking code which was publicly available and combining it without thought to what those licences say. Thus, remarks about Cisco and Linksys - that they were somehow "caught out" - are disingenuous: if you're in the business of distributing software, particularly if that software itself has a restrictive licence, you cannot claim ignorance about licensing or that you just "found some good code". > > Really, copyleft licences are all about treating all recipients of the > > software and modified versions or extensions of the software in the > > same way: that someone receiving the software, in whatever state of > > enhancement, has all the same privileges that the individual or > > organisation providing the software to them enjoyed; > > Sure, and for a major work I think that's great, especially if it > helps attract developers. ?Sometimes I see people GPL little 100 line > libraries (of often not very good code quality) in a clear attempt to > have the tail wag the dog, and that's laughably pathetic. Why is it pathetic that someone gets to choose the terms under which their work is made available? By default, if I release something without any licence, the recipient has very few privileges with respect to that work: it's literally a case of "all rights reserved" for the creator. And if it's such a trivial library then why not reimplement the solution yourself? > > those "four > > freedoms" should still apply to whatever software they received. That > > this is achieved by asking that everyone make the same commitment to > > end-user freedoms (or privileges), yet is seen as unreasonable or > > actually perceived as coercion by some, says a great deal about the > > perspective of those complaining about it. > > Well, I *do* think it's, maybe not unreasonable, but certainly > unrealistic, for the author of a small library to attempt to leverage > control over several potentially much larger works by placing the > small library under the GPL, so in general I don't do it. I dislike the way that when someone releases something under the GPL, it is claimed that they are coercing or attempting to "leverage" something. They have merely shared something on their terms. If you don't like the terms, don't use their software. > ?I also > happen to believe that there are a lot of people (perhaps like Carl > Banks if I understand his post correctly) who make money delivering > small customized solutions to sit on top of proprietary software > solutions. ?If I can save one of these guys some time, perhaps they > will contribute back. ?If I use the GPL, I will have insured that one > of these guys cannot possibly link my software to, e.g. Oracle, so he > has to reinvent the wheel. ?So, for some use-cases, I sincerely > believe that the GPL license creates unnecessary, wasteful friction. But it is not universally true that GPL-licensed software cannot be linked to proprietary software: there are a number of caveats in the GPL covering cases where existing proprietary systems are in use. Otherwise, you'd never have GPL-licensed software running on proprietary systems at all. > But the tone of your last statement and some of your statements below > make it abundantly clear that you've made up your mind about my morals > and aren't at all interested in my reasoning. Not at all. Recently, I've had the misfortune to hear lots of arguments about how the GPL supposedly restricts stuff like "collaboration" and "growth" despite copious evidence to the contrary, usually from people who seem to be making a career of shouting down the GPL or the FSF at every available occasion. Now I'm not saying that you have the same apparent motivations as these people, but I maintain that when someone claims that people are "forced" to share their work when they voluntarily make use of someone else's work, or that they are at the peril of some "moral hazard", it does have a lot to say about their perspective. (Not least because people are only obliged to make their work available under a GPL-compatible licence so that people who are using the combined work may redistribute it under the GPL. You yourself have mentioned elsewhere in this discussion one well-known software project that is not GPL-licensed but was effectively distributed under the GPL to most of its users for a considerable period of time.) [...] > > Yes, but what irritates a lot of people is when you see other people > > arguing that some other random person should license their own > > software permissively because it's "better" or "more free" when what > > they really mean is that "I could use it to make a proprietary > > product". > > I'm not telling anybody what to do. ?I'm just explaining why I usually > use the MIT license for things I write, and will often not consider > using a library licensed under the GPL. ?What irritated me enough to > comment on this thread was the IMHO sanctimonious and inflammatory > "Unless you place such a low value the freedom of your users". It is hardly a rare occurrence now that I come across someone who has written in some corner of the Internet, "It's a shame project XYZ is GPL-licensed because I can't use it for commercial software development. Can the project maintainers not choose another licence?" Sometimes, someone who is seeking licensing advice might not want to be unpopular and might choose a permissive licence because people reassure them that their project will only be widely used if the licence lets people use it "commercially" (or, in other words, in proprietary software). My impression is that many in the core community around Python seem to emphasise such popularity over all other concerns. What I want to point out, and some have done so much more directly than I have in other forums and in other discussions, is that some advice about licensing often stems from a direct motivation amongst those giving the advice to secure preferential terms for themselves, and that although such advice may be dressed up as doing the "right" or "best" thing, those giving the advice stand to gain directly and even selfishly from having their advice followed. I'm not saying you have done this, but this is frequently seen in the core Python community, such that anyone suggesting a copyleft licence is seen as obstructing or undermining some community dynamic or other, while those suggesting a permissive licence are somehow doing so "in the spirit of Python" (to the point where the inappropriate PSF licence for Python is used for independent projects). > > Well, if you want the users to enjoy those "four freedoms" then you > > should use a copyleft licence. If you choose a permissive licence then > > it more or less means that you don't care about (or have no particular > > position on the matter of) the users being able to enjoy those > > privileges. I believe you coined the term "uncaring", but I think Mr > > Finney's statement stands up to scrutiny. > > I personally don't think that RMS's "four freedoms" are the last word > on the best way for society to develop software, no. ?But using > "Unless you place such a low value the freedom of your users" is truly > an inflammatory statement, because it was given in a context where the > GPL had not yet been carefully parsed and discussed, and did not make > it clear that the "freedoms" being discussed are a particular set of > "freedoms" and not, for example, those freedoms enshrined in the Bill > of Rights. ?(And as Steven has carefully pointed out, not all freedoms > are necessarily Good Things.) I tend not to use the terms "freedom" or "right" except when mentioning things like the "four freedoms": the word "privilege" is adequate in communicating what actually is conferred when combining copyright and software licences. Nevertheless, the "four freedoms" and "freedom of your users" are still useful notions: if a proprietary variant of Python became widespread and dominant, although various parts of the software might be freely available in their original forms, the ability to reconstruct or change the software would be impaired and provide fewer opportunities for user involvement than the primary implementations of Python available today. And should such proprietary software become mandated by government agencies or become a de-facto standard, that really does have an effect on the freedom of users. Paul From fuzzyman at gmail.com Sun May 9 17:38:27 2010 From: fuzzyman at gmail.com (Michael Foord) Date: Sun, 9 May 2010 23:38:27 +0200 Subject: Python is cool!! In-Reply-To: References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> <4BA8F56D.6060305@timgolden.me.uk> Message-ID: On 9 May 2010 20:36, Godson Gera wrote: > > > On Sun, May 9, 2010 at 6:24 PM, Fuzzyman wrote: > >> On Mar 23, 10:04 pm, geremy condra wrote: >> > On Tue, Mar 23, 2010 at 1:07 PM, Tim Golden >> wrote: >> > > On 23/03/2010 16:55, Jose Manuel wrote: >> > >> >> The closest is Skulpt which is very much an incomplete implementation >> of Python that runs in the browser. >> > > Since you have mentioned Skulpt, take a look at much better pyjamas > http://pyjs.org/ demos are awesome. > > I'm aware of Pyjamas. It is a Python to Javascript translator and *not* (as far as I know) capable of running an interpreter in the browser. Michael > -- > Thanks & Regards, > Godson Gera > IVRS India > -- http://www.ironpythoninaction.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Sun May 9 18:02:03 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 15:02:03 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> Message-ID: <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> On May 9, 4:21?pm, Paul Boddie wrote: (Lots of good and balanced commentary snipped...) > I didn't say that you personally argued that way, but people do argue > that way. In fact, it's understandable that this is how some people > attempt to understand the GPL - the software maintains a particular > state of openness - but they miss the final step in the reasoning > which leads them to see that the licence preserves a set of privileges > for recipients as well. Obviously, that's a bit subtle and certainly some people might miss the step that says "the final user can always use *my* software, and by choice of license I could decide to insure that if anybody else fixes bugs in my software or combines it with other software they write, then my end users will always be able to use that as well." But others might notice that and still decide that it isn't the right license for their software. > Thus, remarks about Cisco and Linksys - that they were somehow "caught > out" - are disingenuous: if you're in the business of distributing > software, particularly if that software itself has a restrictive > licence, you cannot claim ignorance about licensing or that you just > "found some good code". Any remarks I made about this were only in the debate about "moral hazard" by which I meant something different than Steven did. I'm not at all attempting to condone what Cisco did, just pointing out that if I license code under the MIT license and Cisco uses it, I certainly have no reason to complain about it, and wouldn't dream of doing so in any case, but if I license code under the GPL, then yes, my intentions are clear, and Cisco is complicit in either deliberately turning a blind eye, or inadvertently not watching employees closely enough. I thought I made it clear that I believe that at some level, some human being had to do something that was wrong in order to get Cisco into that position. My sole argument was that in general, I don't want to be the one to put Cisco in that position, and conversely, I don't want anybody else putting me in that position (I want to do the right thing) so I usually don't license stuff under the GPL, or incorporate stuff licensed under the GPL into anything I do. > Why is it pathetic that someone gets to choose the terms under which > their work is made available? By default, if I release something > without any licence, the recipient has very few privileges with > respect to that work: it's literally a case of "all rights reserved" > for the creator. And if it's such a trivial library then why not > reimplement the solution yourself? You just answered your own question. It's pathetic to try to change people's behavior by offering them something worthless if they change their license to match yours. (I'm not at all saying that all GPL code is worthless, but I have seen things like under 30 line snippets that weren't even very well written that were "licensed" under the GPL.) > I dislike the way that when someone releases something under the GPL, > it is claimed that they are coercing or attempting to "leverage" > something. They have merely shared something on their terms. If you > don't like the terms, don't use their software. Well, I don't always make that claim, but I do make it when I see a little "recipe" under the GPL. Often these recipes require so much customization for any particular task that they are really just pedagogical, and some of them aren't even very good. Color me a cynic, but when I see something so short and generic that any sort of judicial test would declare that there was no copyrightable "there" there, that has an arguably politicized license slapped on it, I smell an agenda. > But it is not universally true that GPL-licensed software cannot be > linked to proprietary software: there are a number of caveats in the > GPL covering cases where existing proprietary systems are in use. > Otherwise, you'd never have GPL-licensed software running on > proprietary systems at all. Agreed, but most of those are at very clearly delineated boundaries, like the OS. > > But the tone of your last statement and some of your statements below > > make it abundantly clear that you've made up your mind about my morals > > and aren't at all interested in my reasoning. > > Not at all. Recently, I've had the misfortune to hear lots of > arguments about how the GPL supposedly restricts stuff like > "collaboration" and "growth" despite copious evidence to the contrary, > usually from people who seem to be making a career of shouting down > the GPL or the FSF at every available occasion. Now I'm not saying > that you have the same apparent motivations as these people, but I > maintain that when someone claims that people are "forced" to share > their work when they voluntarily make use of someone else's work, or > that they are at the peril of some "moral hazard", it does have a lot > to say about their perspective. (Not least because people are only > obliged to make their work available under a GPL-compatible licence so > that people who are using the combined work may redistribute it under > the GPL. You yourself have mentioned elsewhere in this discussion one > well-known software project that is not GPL-licensed but was > effectively distributed under the GPL to most of its users for a > considerable period of time.) Sorry, guess I misunderstood where you are coming from. > It is hardly a rare occurrence now that I come across someone who has > written in some corner of the Internet, "It's a shame project XYZ is > GPL-licensed because I can't use it for commercial software > development. Can the project maintainers not choose another licence?" > Sometimes, someone who is seeking licensing advice might not want to > be unpopular and might choose a permissive licence because people > reassure them that their project will only be widely used if the > licence lets people use it "commercially" (or, in other words, in > proprietary software). My impression is that many in the core > community around Python seem to emphasise such popularity over all > other concerns. Yes, but I see the same sort of popularity effects tilt towards the GPL sometimes, too. > What I want to point out, and some have done so much more directly > than I have in other forums and in other discussions, is that some > advice about licensing often stems from a direct motivation amongst > those giving the advice to secure preferential terms for themselves, > and that although such advice may be dressed up as doing the "right" > or "best" thing, those giving the advice stand to gain directly and > even selfishly from having their advice followed. I'm not saying you > have done this, but this is frequently seen in the core Python > community, such that anyone suggesting a copyleft licence is seen as > obstructing or undermining some community dynamic or other, while > those suggesting a permissive licence are somehow doing so "in the > spirit of Python" (to the point where the inappropriate PSF licence > for Python is used for independent projects). Agreed that every project is different, and lots of considerations should be taken into account. > > I tend not to use the terms "freedom" or "right" except when > mentioning things like the "four freedoms": the word "privilege" is > adequate in communicating what actually is conferred when combining > copyright and software licences. Nevertheless, the "four freedoms" and > "freedom of your users" are still useful notions: if a proprietary > variant of Python became widespread and dominant, although various > parts of the software might be freely available in their original > forms, the ability to reconstruct or change the software would be > impaired and provide fewer opportunities for user involvement than the > primary implementations of Python available today. And should such > proprietary software become mandated by government agencies or become > a de-facto standard, that really does have an effect on the freedom of > users. I don't worry too much about that happening. I think that ESR is right that the powerful network effects of free development would overwhelm any attempt to take something like Python private. Regards, Pat From paul at boddie.org.uk Sun May 9 18:05:04 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 15:05:04 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> <6554e4fa-9fc0-49ab-a28d-413bd3152739@l31g2000yqm.googlegroups.com> Message-ID: On 9 Mai, 21:55, Patrick Maupin wrote: > On May 9, 12:08?pm, Paul Boddie wrote: > > > Oh sure: the GPL hurts everyone, like all the companies who have made > > quite a lot of money out of effectively making Linux the new > > enterprise successor to Unix, plus all the companies and individuals > > who have taken the sources and rolled their own distributions. > > So, people overstate their cases to make their points. ?That happens > on both sides. Overstate their cases? The "GPL hurts everyone" is a flat-out falsehood. > > It's not worth my time picking through your "holy war" rhetoric when > > you're throwing "facts" like these around. As is almost always the > > case, the people who see the merit in copyleft-style licensing have > > clearly given the idea a lot more thought than those who immediately > > start throwing mud at Richard Stallman because people won't let them > > use some software as if it originated in a (universally acknowledged) > > public domain environment. > > No, you appear to have a kneejerk reaction much worse than Carl's. > You have assumed you fully understand the motives of people who point > out issues with the GPL, and that those motives are uniformly bad, and > this colors your writing and thinking quite heavily, even to the point > where you naturally assumed I was defending all of Apple's egregious > behavior. I skimmed your post in that particular case and apologised for doing so. How have I not understood the motives of people who do not like the GPL? The GPL sets out a number of conditions on the use of a particular work; these conditions are not liked by some people typically because it means that they cannot use that work as part of a proprietary product or solution, just as the authors of the licence intended; various people would prefer that authors license their works permissively, precisely because this lets them use such works in proprietary software; some of the rhetoric employed to persuade people to permissively license their work involves phrases like "more freedom" (which are subjective at best, although never acknowledged as such) or the more absurd "holy war", evidently. I once attended a talk by someone from the FSF Europe, a few years ago now, where the inevitable assertion that the BSD licences were "more free" was made by an audience member. In my experience, such people are very reluctant to acknowledge the different philosophical dimensions of "freedom", whereas people who apply copyleft licences to their works have typically had to confront such issues even before being asked over and over again to relicense them. > As far as my throwing mud at Stallman, although I release some open > source stuff on my own, I make a living writing software that belongs > to other people, and Stallman has said that that's unethical and I > shouldn't be able to make money in this fashion. ?Sorry, but he's not > on my side. A lot of people seem to take issue with the GPL because they don't like Stallman, but that only leads to their judgement being clouded as a consequence. When Stallman's warnings become fulfilled, as has been the case with things like BitKeeper, this only serves to infuriate people further, often because they know they could have ignored the messenger but should not have ignored the message. Most people writing software are doing so for other people, and many people are doing so as part of a proprietary process. Thus, the only way to interpret what Stallman has to say (should you not wish to reject it completely) is to consider it as some kind of absolute guidance, not some kind of personal judgement. > > P.S. And the GPL isn't meant to further the cause of open source: it's > > meant to further the Free Software cause, which is not at all the same > > thing. Before you ridicule other people's positions, at least get your > > terminology right. > > And, again, that's "free" according to a somewhat contentious > definition made by someone who is attempting to frame the debate by co- > opting all the "mother and apple pie" words, who is blindly followed > by others who think they are the only ones who are capable of thoughts > which are both rational and pure. ?I'm not saying everybody who uses > the GPL is in this category, but some of your words here indicate that > you, in fact, might be. No, I am saying that the Free Software movement is a well-defined thing - that's why the name uses capital letters, but it could be called the "Planet of the Zebras movement" for all the name should reasonably distract from what the movement is actually about - and that it has a very different agenda from the "open source" movement which advocates very similar licensing on the basis of things like higher software quality and other "pragmatic" consequences of using such licensing. As for the terminology, I've already noted that I prefer the term "privileges" to "rights" or "freedoms" because it communicates that something is gained. Again, some people assume that the natural state of a work is (or should be) a free-for-all and that the GPL revokes privileges: this is a misrepresentation of how copyright and licensing functions. Paul From martin.hellwig at dcuktec.org Sun May 9 19:05:31 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 10 May 2010 00:05:31 +0100 Subject: Picking a license In-Reply-To: References: <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <7xy6ftu67v.fsf@ruckus.brouhaha.com> <7xk4rdpwd4.fsf@ruckus.brouhaha.com> <4BE70E0A.8060208@dcuktec.org> Message-ID: <4BE73FBB.3050405@dcuktec.org> On 05/09/10 21:06, Stephen Hansen wrote: > On Sun, May 9, 2010 at 12:33 PM, Martin P. Hellwig > > wrote: > > On 05/09/10 18:24, Stephen Hansen wrote: > > > > Wait, what? Why shouldn't I profit repeatedly from the "same > work already done"? *I* created, its *mine*. I put blood, > sweat and tears into it and perhaps huge amounts of resources, > risking financial security and sanity, and you're arguing I > shouldn't have the right to sell it after its done? > > Of course, but what do you do if you find out that your potential > customer already has your software without paying you? > > > Nothing. There's really very little benefit to me to go after > "potential customers". There will always be warez trading and cracked > versions of any product out there that someone can pirate. So what? > The vast majority of the people downloading that aren't actually > *potential customers*. They'd never have bought the products to begin > with. > > Now, if I find out some other company happens to be selling my > software, them I'd sue into oblivion and make a killing -- copyright > lets me do that. Assuming that you have enough financial resources and that company is within the same jurisdiction, granted otherwise it is still possible but often seen unfeasible. > > > Exactly how do you imagine I'm going to make money off of it? > How the existing system works is that I sell... multiple > copies of it. Maybe hundreds or thousands before that > investment is recouped. At that point, do I no longer get to > sell multiple copies? Or do I have to find someone to > retroactively pay me some kind of salary? What does "pay for > work" even mean? > > As a simple developer I do not think my craft is more special than > any other craft like carpentry, masonry, plumbing, electrician etc. > And as I see how other crafts get paid I think is reasonable for > my craft too, I am either employed and paid by the hour or take > more risks and do projects, commissions, etc. etc. > > Of course if I would be in the construction business and I build a > house I can either sell it or let it, but then I do take the risk > that the occupant uses my work beyond what I expected and > eventually end up with a huge repair costs. > > I am sure you can imagine the rest of my comparison arguments > between construction and software development. > > > You're comparing apples to rabbits. There's nothing even vaguely alike > between the two no matter how much you are trying to compare them: > carpentry, masonry, plumbing, all of that deal with *physical* items, > that by their very nature create singular, specific, tangible items > and/or services. > > If I create a software product on commission for some private company, > that's almost-kind of like what happens for other "crafts", wherein > someone pays me some amount of money for some amount of work to > produce a finished product. But how exactly do you imagine I would > make money if I have some idea for some great new program and I write > it on my own? > > The only way is to... sell multiple copies. Or try to find someone to > give me one big lump sum for the privilege of releasing it to the > universe. I have seen a couple of times when one organization/user has not the financial resources to commission or further develop an (software) idea that they through trade or sector organization combine their resources to get there, this happen quite often in education institutes for the development for administration programs. Personally I think that where there is a will there is a way. > > Software is intangible, irregardless of the fact that it might show up > on a physical medium. You can't compare work of the mind with work of > physical crafts-- one is not more worthy of money then the other, but > they are *different*. Like poetry, music and the such, which indeed share much of the same problems as software. Still they flourished even before rule enforcement. I am sure that Muhammad ibn M?s? al-Khw?rizm?, didn't have too much problems in that regard. > > What's wrong with software copyrights? Don't lump intellectual > property issues together, they're not comparable. Copyrights have > nothing at all to do with patents which have nothing at all to do > with trademarks. Each is a very different set of law. > > Very true and in my opinion they all share the same trait, > although they are once made to make sure the original author gets > credit and profit for his/her work they are primarily used now to > profit beyond reasonableness and actually encumber future > development and good use, IMHO they actually hinder the > intellectual development of the human race. > > > You say 'very true' but then you lump them all together again. "They" > are not at all for the same thing. I said they share a same trait, I did not say they where the same thing and above that I said it was IMHO, which should indicate that I am aware that opinions differ on that. > > Copyrights are intended, indeed, to make sure the original author gets > credit and profit for his creative work. They tend to last a rather > long time these days. > > Patents are intended to allow a relatively short-term monopoly on some > new invention, so that the vast costs of R&D can be justified, but > also so that the -result- of that R&D will be published to the public > and after that monopoly is over, allow everyone to benefit. They are > an encumbrance, yes, but a temporary one: and after that encumbrance > is over, the inventor losers all control over the invented. > Unfortunately, patents are woefully broken due to business methods and > software being allowed to be 'patented', which is just silly on both > cases. > > Trademarks are intended to protect the *consumers*, by disallowing > companies from marketing in a confusing way such that what they are > selling may be mistaken for what a reputable third-party is selling. A > company can trademark its "brand", and by doing so customers can know > that brand and IF they trust it, rely on it when they see it. > Trademarks actually, IMHO, work quite well -- companies actually have > to enforce them and be pro-active about them, unlike with patents, > where one can sit around and wait for another to firmly establish > themselves with technology based on your patent, then jump in and sue. > I fail to see how there's really anything "encumbering" about trademarks. Uh I missed the bit about me being against trademarks, I actually agree that this is a good thing, because this prevents fraud. > > > Sure, there's some nutty corner cases in copyrights, which > need to be addressed-- including things like fair use and DRM. > But on the whole, copyrights aren't really all that broken. > Its nothing like the situation with software patents, which > are just sort of crazy. > > Okay so what do you actually do if you find out that in another > country, which do not share the same legislation (about the other > 80% of the population) brakes your copyright or does not uphold > the patent restrictions? > If your big like Microsoft you might try to convince that > particular government that their citizens should pay you, > otherwise good luck (even for Microsoft as they seem to fail more > often than succeed in that notion). > > > Umm. > > http://upload.wikimedia.org/wikipedia/commons/7/76/Berne_Convention_signatories.svg > http://upload.wikimedia.org/wikipedia/commons/c/c1/WIPO.png > > And a couple others, including the Pair Convention of something or other. > > Intellectual property law is pretty globally standard these days. > That's not to say that in some places its not largely ignored in > certain sectors, but see first response above. > > They are broken because by definition restrictions need > enforcement to uphold them, if there is no enforcement it will not > work. Perhaps a better solution would be to find a way that does > not need any enforcement (or limited amount of it), say like the > economy worked prior to patents and copyrights minus kings and > tyrants. > > > ... copyright dates back to the 1700's. In Europe (UK) and US. > > And, there are ways to enforce the "restrictions"-- which are not > restrictions, but instead enforcement of rights that I, as the one who > made this creative work, hold. Its a civil action. (Though certain > types and kinds of infringement may in some jurisdictions be a > criminal offense) > > > You can believe in the Free Software movement (I'm not saying > you do, this 'you' is impersonal and metaphorical)-- and if > you do, good for you. You can believe in "morality" with > regards to "freedom" and the "essential rights" of the users. > I find it all nonsensical. But good for you if you believe in > it. But the Free Software movement exists *because* of > copyrights. Copyright Law is what makes the GPL even possible. > > > I don't believe in a system which is based on enforcing rules and > where breaking of this rule at most results in a hypothetical loss > of income. Some enforced rules are of course necessary, like not > going on a pillage/killing/raping spree (except of course if this > is your job but then your still governed by the rules of Geneva -- > yeah I know bold military statement, but I have been there too, > the military that is). I rather like to find a way where minimal > rule enforcing is necessary to make a living. > > > I find i can make a living quite well with basically zero "rule > enforcing", because of copyrights. I really don't need to enforce that > every kid out there might get an illegal copy of a program I wrote. > They aren't my customers. However, because I have copyright, I can be > sure that no other companies are going to start completing with me > based on my own work. (That I made this argument in a thread about > open source licensing, and the irony therein, does not escape me) It makes perfect sense to me, just as you said open source license is just another form of copyright. > > Cuz then I'll sue their ass off. > > But its never happened. And I don't expect it to happen. Because > copyright is an international, pretty clearly standardized set of law. Stating the fact that copyright is a clear international standard, only on a limited scale contributes to the argument that it is an effective process. Supporting this argument that is has never happened to you nor that you expect it to happen only demonstrates that your software is just not popular enough to suffer infringement, because _all_ other popular software does (according to virtual every lobby group). Actually you could go so far and define the popularity of software by the amount of copyright infringements. > > > But I fail to see what's fundamentally wrong with that system. > > I hope I have further explained my point of view and hope that you > agree with me at least from my perspective, I do understand though > that your point of view is perfectly valid and reasonable. It is > just that I am a sucker for seeking alternative ways to improve > systems even if they only show small amounts of defects. So you > could argue that I have my sight set for an Utopia while you > rather remain in the reality, if you can find yourself with this > than at least we can agree on that :-) > > > Had you stuck to wanting to make patents make sense, I would have > agreed with you about half the way-- but I actually, mostly, sorta > think copyrights are fine. Even with idiocies like DRM. I think the > market has to decide to turn away from DRM. (I'm looking at you > Ubisoft: you've lost over $100 already from me!) > > --S Well if may sum it up (minus trademarks as we both agree on the need for it): Your opinion is that copyrights, within reason, work on a global scale. Patents are necessary and also work on a global scale. I have no doubt that copyrights and patents exist. I have no doubt that globally governments indicate that they are enforcing it. However I do doubt that they work, I think the enforcing is highly ineffective. If at average at least 1 in 5 software products use is an 'illegal' version (http://www.nationmaster.com/graph/cri_sof_pir_rat-crime-software-piracy-rate) then by no way you can say if is effectively enforced. Take it from another perspective, everybody who uses illegal software in full awareness (according to those terms) is by that definition a criminal, equal to somebody stealing a car radio. This would make most of the people out there criminals, from primary school goers to senior citizens. And to be true this is what bothers me the most, it criminalizes people who otherwise would never be attributed to malice. I took a firm stand against copyrights and patents in this thread, but I am not that fanatic, in reality I prefer open-source, but I do buy software, like recently Spore. I don't buy my Microsoft software because I can download and use them for free (I have an MSDN & Technet subscription). However for myself I do not contribute to copyrights, but because the rest of the world does I need to stick at least the MIT/BSD license on it. Patents, well I suppose big corporation that have huge investment need to see a ROI, I mean Amazon would have been in a financial crisis if they didn't patented their innovating the single-click shopping. Small time and accidental inventors don't have the financial means anyway to afford a global patent these days. -- mph -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Sun May 9 19:39:12 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 9 May 2010 16:39:12 -0700 (PDT) Subject: Picking a license References: <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> Message-ID: <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> On 10 Mai, 00:02, Patrick Maupin wrote: > > You just answered your own question. ?It's pathetic to try to change > people's behavior by offering them something worthless if they change > their license to match yours. ?(I'm not at all saying that all GPL > code is worthless, but I have seen things like under 30 line snippets > that weren't even very well written that were "licensed" under the > GPL.) If this is code that you would consider using in an existing project, but if they aren't pitching it directly at you, why would you believe that they are trying to change your behaviour? It is you who gets to decide whether you use the code or not. If the licence isn't acceptable to you, what prevents you from asking for a special licence, especially if you are going to incorporate the code in a product which is sold? In the more general case of people just releasing small programs and libraries, all such people are doing is saying, "Here is something I have done, and here are the terms through which this is shared." If anything, they are reaching out to see if anyone will work together with them on making something better, where everyone agrees to a common framework upon which that work will be done. I'm sure people didn't think much of Linus Torvalds' work in the beginning, either. Paul From aharrisreid at googlemail.com Sun May 9 19:43:01 2010 From: aharrisreid at googlemail.com (Alan Harris-Reid) Date: Mon, 10 May 2010 00:43:01 +0100 Subject: Binary file email attachment problem Message-ID: <4BE74885.8010602@googlemail.com> Hi there, Using Python 3.1.2 I am having a problem sending binary attachment files (jpeg, pdf, etc.) - MIMEText attachments work fine. The code in question is as follows... for file in self.attachments: part = MIMEBase('application', "octet-stream") part.set_payload(open(file,"rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % file) msg.attach(part) # msg is an instance of MIMEMultipart() server = smtplib.SMTP(host, port) server.login(username, password) server.sendmail(from_addr, all_recipients, msg.as_string()) However, way down in the calling-stack (see traceback below), it looks as though msg.as_string() has received an attachment which creates a payload of 'bytes' type instead of string. I suspect the error lies in the encoding somewhere, but I've no idea where. I have also tried MIMEApplication and MIMEImage, but the error still remains. I have seen many similar code examples on the web, all of which fail for me, so I wonder if there is something wrong with my environment. Has anyone any idea what might be causing the problem? Any help would be appreciated. Alan ________________________________________________________________ builtins.TypeError: string payload expected: File "c:\Dev\CommonPY\Scripts\email_send.py", line 147, in send server.sendmail(self.from_addr, all_recipients, msg.as_string()) File "c:\Program Files\Python31\Lib\email\message.py", line 136, in as_string g.flatten(self, unixfrom=unixfrom) File "c:\Program Files\Python31\Lib\email\generator.py", line 76, in flatten self._write(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 101, in _write self._dispatch(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 127, in _dispatch meth(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 181, in _handle_multipart g.flatten(part, unixfrom=False) File "c:\Program Files\Python31\Lib\email\generator.py", line 76, in flatten self._write(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 101, in _write self._dispatch(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 127, in _dispatch meth(msg) File "c:\Program Files\Python31\Lib\email\generator.py", line 155, in _handle_text raise TypeError('string payload expected: %s' % type(payload)) ____________________________________________________________ From pmaupin at gmail.com Sun May 9 21:09:59 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 18:09:59 -0700 (PDT) Subject: Picking a license References: <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> Message-ID: On May 9, 6:39?pm, Paul Boddie wrote: > On 10 Mai, 00:02, Patrick Maupin wrote: > If this is code that you would consider using in an existing project, Well, in a few cases I'm talking about, I wouldn't consider using the code -- I just stumbled across it when researching some terms, and discounted it immediately. Honestly, I'm talking about code that is so small and generic that it doesn't deserve any copyright protection (and wouldn't get any if it came to that in court). > but if they aren't pitching it directly at you, why would you believe > that they are trying to change your behaviour? Because I've seen people specifically state that their purpose in GPLing small libraries is to encourage other people to change their behavior. I take those statements at face value. Certainly RMS carefully lays out that the LGPL should be used sparingly in his "Why you shouldn't use the Lesser GPL for your next library" post. (Hint: he's not suggesting a permissive license instead.) > It is you who gets to > decide whether you use the code or not. If the licence isn't > acceptable to you, what prevents you from asking for a special > licence, especially if you are going to incorporate the code in a > product which is sold? Well, the only time I can remember even hinting around for any kind of different license was when I was found an svglib bug for use with rst2pdf. svglib is a "real" library (unlike the code snippets I was discussing) licensed under the GPL. I would be quite happy to consider learning it and contributing patches to it, but I didn't want to maintain a fork myself, and the maintainer doesn't have a public repository and was quite busy with other stuff, and when I asked him if he would accept patches, it was ten days before he got back to me. rst2pdf was licensed under the MIT license before I started contributing to it, and there is no way I was going to even consider adding patches for a GPLed package (which would certainly have to be GPLed) into the rst2pdf repository. (Say what you will about how sometimes differently licensed code can be combined, but RMS has to share quite a bit of the blame/credit for the whole combining licenses FUD.) So I took a completely different path and right now the best way to use .svg files with rst2pdf is to use inkscape to convert them to PDFs, and use some code I wrote that allows you to use preexisting PDFs as images. Despite being a real library, svglib is quite small at ca. 1200 lines, and if the license were compatible with the rst2pdf codebase license (e.g. even if it were LGPL), I would have just stuffed the file into the rst2pdf codebase and started hacking on it. So there's a nice little piece of GPLed code that isn't getting as much attention as it would have if it were LGPLed or licensed permissively, or even if the author had just dumped it onto sourceforge or googlecode under the GPL but given me commit rights. As it is, I don't think it's been maintained in 8 years. This is exactly the same situation that Carl was describing, only with two different open source packages rather than with a proprietary package and a GPL package. The whole reason people use words like "force" and "viral" with the GPL is that this issue would not have come up if svglib were MIT and rst2pdf were GPL. (Note that the LGPL forces you to give back changes, but not in a way that makes it incompatible with software under other licenses. That's why you see very few complaints about the LGPL.) > In the more general case of people just releasing small programs and > libraries, all such people are doing is saying, "Here is something I > have done, and here are the terms through which this is shared." Sure, and all I'm explaining is why I reject the terms in some cases. I particularly reject the terms when a license that was originally designed for a whole program is used for a small library, with the express intent of getting more people to use said license. > If anything, they are reaching out to see if anyone will work together > with them on making something better, where everyone agrees to a > common framework upon which that work will be done. That's absolutely not always the case. Often, it's more "here's something I've done; take it or leave it but if you take it, it's on these terms." > I'm sure people > didn't think much of Linus Torvalds' work in the beginning, either. I think the GPL was a great license for the development model for Linux. I have no issues with how that worked. Part of that is that Linus was always active in the development. I think that, particularly when the concept of free software was relatively new, the license might have been an effective focal point for rallying contributions. But I have definitely seen cases where people are offering something that is not of nearly as much value as they seem to think it is, where one of the goals is obviously to try to spread the GPL. Regards, Pat From pmaupin at gmail.com Sun May 9 21:41:32 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 9 May 2010 18:41:32 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> <6554e4fa-9fc0-49ab-a28d-413bd3152739@l31g2000yqm.googlegroups.com> Message-ID: On May 9, 5:05?pm, Paul Boddie wrote: > On 9 Mai, 21:55, Patrick Maupin wrote: > > > On May 9, 12:08?pm, Paul Boddie wrote: > > > > Oh sure: the GPL hurts everyone, like all the companies who have made > > > quite a lot of money out of effectively making Linux the new > > > enterprise successor to Unix, plus all the companies and individuals > > > who have taken the sources and rolled their own distributions. > > > So, people overstate their cases to make their points. ?That happens > > on both sides. > > Overstate their cases? The "GPL hurts everyone" is a flat-out > falsehood. Well, just like in some cases it makes us all richer, in some cases it also makes us all poorer. See my prior example about svglib. > > > It's not worth my time picking through your "holy war" rhetoric when > > > you're throwing "facts" like these around. As is almost always the > > > case, the people who see the merit in copyleft-style licensing have > > > clearly given the idea a lot more thought than those who immediately > > > start throwing mud at Richard Stallman because people won't let them > > > use some software as if it originated in a (universally acknowledged) > > > public domain environment. > > > No, you appear to have a kneejerk reaction much worse than Carl's. > > You have assumed you fully understand the motives of people who point > > out issues with the GPL, and that those motives are uniformly bad, and > > this colors your writing and thinking quite heavily, even to the point > > where you naturally assumed I was defending all of Apple's egregious > > behavior. > > I skimmed your post in that particular case and apologised for doing > so. Apology accepted. > How have I not understood the motives of people who do not like the > GPL? The GPL sets out a number of conditions on the use of a > particular work; these conditions are not liked by some people > typically because it means that they cannot use that work as part of a > proprietary product or solution, just as the authors of the licence > intended; As I have shown in another post, in one case, I wanted to contribute a fix for making one piece of GPLed software work better with another case of MIT licensed software. The fact that one piece was GPLed and the author didn't have a repository and was relatively unresponsive via email, combined with the fact that I was too lazy to start a new repository just to maintain a fork of one small library, means that I didn't devote any time to fixing bugs and making the GPLed software better. A "proprietary product or solution" never entered into the picture. > various people would prefer that authors license their works > permissively, precisely because this lets them use such works in > proprietary software; You also are ignoring the fact that a lot of people practice what they preach on the other side of this issue. Since I don't want to make other people jump through these sorts of licensing hoops, I license stuff under the MIT license. MIT, BSD, and Apache are "universal donor licenses" and just like type O blood, I think this increases the value of the code licensed under them. > some of the rhetoric employed to persuade people > to permissively license their work involves phrases like "more > freedom" (which are subjective at best, although never acknowledged as > such) or the more absurd "holy war", evidently. Well, I think the reason "more freedom" is used is because RMS has attempted to co-opt the word "freedom" and I think "holy war," though inflammatory, accurately portrays the kind of language RMS uses to attract his followers. YMMV > I once attended a talk by someone from the FSF Europe, a few years ago > now, where the inevitable assertion that the BSD licences were "more > free" was made by an audience member. In my experience, such people > are very reluctant to acknowledge the different philosophical > dimensions of "freedom", whereas people who apply copyleft licences to > their works have typically had to confront such issues even before > being asked over and over again to relicense them. Well, the whole reason I got involved in this thread was I felt that I was, by association, being accused of not caring about others' "freedom" so this is a pot/kettle issue. Also, when you're deeply involved in an issue, you might miss or ignore insults hurled by others seemingly on your side; it's always easier to spot the logical fallacies made by members of the opposing side, and come to the conclusion that your side is smarter, more moral, and generally superior. > > As far as my throwing mud at Stallman, although I release some open > > source stuff on my own, I make a living writing software that belongs > > to other people, and Stallman has said that that's unethical and I > > shouldn't be able to make money in this fashion. ?Sorry, but he's not > > on my side. > > A lot of people seem to take issue with the GPL because they don't > like Stallman, but that only leads to their judgement being clouded as > a consequence. When Stallman's warnings become fulfilled, as has been > the case with things like BitKeeper, this only serves to infuriate > people further, often because they know they could have ignored the > messenger but should not have ignored the message. Most people writing > software are doing so for other people, and many people are doing so > as part of a proprietary process. Thus, the only way to interpret what > Stallman has to say (should you not wish to reject it completely) is > to consider it as some kind of absolute guidance, not some kind of > personal judgement. Oh, but I do consider the licenses separately, and describe when I think they are appropriate. Again, if you're addressing half the debaters, you're missing the people on your side (not necessarily in this particular thread) who quote Stallman and Moglen as if their word is the final word on everything. Even in the example you quote here, it was obvious what was going to happen with bitkeeper to the most casual observer, so I don't think that by itself shows incredible powers of observation on Stallman's part. I also think that if Stallman didn't exist, we would have invented him -- it was time for that particular philosophy. > > > P.S. And the GPL isn't meant to further the cause of open source: it's > > > meant to further the Free Software cause, which is not at all the same > > > thing. Before you ridicule other people's positions, at least get your > > > terminology right. > > > And, again, that's "free" according to a somewhat contentious > > definition made by someone who is attempting to frame the debate by co- > > opting all the "mother and apple pie" words, who is blindly followed > > by others who think they are the only ones who are capable of thoughts > > which are both rational and pure. ?I'm not saying everybody who uses > > the GPL is in this category, but some of your words here indicate that > > you, in fact, might be. > > No, I am saying that the Free Software movement is a well-defined > thing - that's why the name uses capital letters, but it could be > called the "Planet of the Zebras movement" for all the name should > reasonably distract from what the movement is actually about - and > that it has a very different agenda from the "open source" movement > which advocates very similar licensing on the basis of things like > higher software quality and other "pragmatic" consequences of using > such licensing. But you're missing the point that it is called the "Free Software" movement precisely for all the religious/political reasons that piss some people off. People wouldn't get all hot and bothered about it if it were the Planet of the Zebras movement, but RMS never would have called it that. > As for the terminology, I've already noted that I prefer the term > "privileges" to "rights" or "freedoms" because it communicates that > something is gained. That's a reasonable starting point, but you still need a way to distinguish who is getting the privileges -- in the case of the GPL, it's often the non-programming general public, whereas in the case of the MIT license, it's anybody who wants to do the software equivalent of mash-ups, whether they want to generally share with the public or not. Even that's not quite right -- the GPL allows me to make any kind of mash-up I want as long as I don't want to share it with *anybody* else; it's only when I want to share that it becomes a problem if I used the wrong ingredients inside my mash-up. That's where the "force" and "viral" words come from -- Microsoft doesn't force me to use their license if I code to their API and don't distribute their code, but the FSF's viewpoint is that any linking (static or dynamic) forces me to use the GPL on my code even if I'm not distributing the GPLed code I'm dynamically linking to. (Legally, I think that's probably wrong, but that's their opinion, and apparently the opinion of a lot of their adherents, so morally it would be wrong for me to go against their wishes.) > Again, some people assume that the natural state > of a work is (or should be) a free-for-all and that the GPL revokes > privileges: this is a misrepresentation of how copyright and licensing > functions. As I said earlier in the thread, the OP's question was not "no license or GPL" but rather "MIT or GPL" so the relevance of a non-licensed alternative wasn't really a point of this particular discussion. Regards, Pat From zhongby at ucweb.com Sun May 9 22:40:51 2010 From: zhongby at ucweb.com (=?gb2312?B?1tOx/tPC?=) Date: Mon, 10 May 2010 10:40:51 +0800 Subject: Queue.Queue() AttributeError exception Message-ID: <201005101040516097598@ucweb.com> I have a multi-thread program work with Queue.Queue(), sometimes put request to the work queue, but throw an exception as below traceback information, it will always throw the exception until restart program, cound please have any experience, your help will be greatly appreciated! File "/usr/local/lib/python2.4/Queue.py", line 71, in put self.not_full.acquire() AttributeError: '_Condition' object has no attribute 'acquire' -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at nospam.invalid Sun May 9 23:58:08 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 09 May 2010 20:58:08 -0700 Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <8739y3fil0.fsf@benfinney.id.au> <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <4be6f8f8$0$27783$c3e8da3@news.astraweb.com> Message-ID: <7xhbmgwgq7.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > It's certainly true > that an MIT licence will allow you to maximise the number of people who > will use your software, but maximising the number of users is not the > only motive for writing software. I'd say proprietary licenses where you spend billions on marketing and lobbying get you the most users. Windows has orders of magnitude more users than either Linux or BSD. FOSS under any license isn't about maximizing users. From pavlovevidence at gmail.com Mon May 10 02:31:13 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 9 May 2010 23:31:13 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> Message-ID: <99386b28-1636-4f81-beec-3756970d37e8@11g2000prv.googlegroups.com> On May 9, 10:08?am, Paul Boddie wrote: > On 9 Mai, 09:05, Carl Banks wrote: > > Bottom line is, GPL hurts everyone: the companies and open source > > community. ?Unless you're one of a handful of projects with sufficient > > leverage, or are indeed a petty jealous person fighting a holy war, > > the GPL is a bad idea and everyone benefits from a more permissive > > licence. > > Oh sure: the GPL hurts everyone, like all the companies who have made > quite a lot of money out of effectively making Linux the new > enterprise successor to Unix, plus all the companies and individuals > who have taken the sources and rolled their own distributions. Relative to what they could have done with a more permissive license? Yes. GPL hurts everyone relative to licenses that don't drive wedges and prevent interoperability between software. You might argue that GPL is sometimes better than proprietary closed source, and I won't disagree, but it's nearly always worse than other open source licenses. > P.S. And the GPL isn't meant to further the cause of open source: it's > meant to further the Free Software cause, which is not at all the same > thing. It doesn't matter what the GPL "meant" to do, it matters what it does, which is hurt everyone (relative to almost all other licenses). > Before you ridicule other people's positions, at least get your > terminology right. I don't agree with FSF's defintion of free software and refuse to abide by it. GPL isn't free software; any software that tells me I can't compile it in with a closed source API isn't free. Period. Carl Banks From stefan_ml at behnel.de Mon May 10 02:54:19 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 May 2010 08:54:19 +0200 Subject: Fastest way to calculate leading whitespace In-Reply-To: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: dasacc22, 08.05.2010 19:19: > This is a simple question. I'm looking for the fastest way to > calculate the leading whitespace (as a string, ie ' '). Here is an (untested) Cython 0.13 solution: from cpython.unicode cimport Py_UNICODE_ISSPACE def leading_whitespace(unicode ustring): cdef Py_ssize_t i cdef Py_UNICODE uchar for i, uchar in enumerate(ustring): if not Py_UNICODE_ISSPACE(uchar): return ustring[:i] return ustring Cython compiles this to the obvious C code, so this should be impossible to beat in plain Python code. However, since Cython 0.13 hasn't been officially released yet (may take another couple of weeks or so), you'll need to use the current developer version from here: http://hg.cython.org/cython-devel Stefan From stefan_ml at behnel.de Mon May 10 03:25:43 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 May 2010 09:25:43 +0200 Subject: Fastest way to calculate leading whitespace In-Reply-To: References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com> Message-ID: Stefan Behnel, 10.05.2010 08:54: > dasacc22, 08.05.2010 19:19: >> This is a simple question. I'm looking for the fastest way to >> calculate the leading whitespace (as a string, ie ' '). > > Here is an (untested) Cython 0.13 solution: > > from cpython.unicode cimport Py_UNICODE_ISSPACE > > def leading_whitespace(unicode ustring): > cdef Py_ssize_t i > cdef Py_UNICODE uchar > > for i, uchar in enumerate(ustring): > if not Py_UNICODE_ISSPACE(uchar): > return ustring[:i] > return ustring > > Cython compiles this to the obvious C code, so this should be impossible > to beat in plain Python code. ... and it is. For a simple string like u = u" abcdefg" + u"fsdf"*20 timeit gives me this for "s=u.lstrip(); u[:-len(s)]": 1000000 loops, best of 3: 0.404 usec per loop and this for "leading_whitespace(u)": 10000000 loops, best of 3: 0.0901 usec per loop It's closer for the extreme case of an all whitespace string like " "*60, where I get this for the lstrip variant: 1000000 loops, best of 3: 0.277 usec per loop and this for the Cython code: 10000000 loops, best of 3: 0.177 usec per loop But I doubt that this is the main use case of the OP. Stefan From bieffe62 at gmail.com Mon May 10 03:40:17 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Mon, 10 May 2010 00:40:17 -0700 (PDT) Subject: solve a newspaper quiz References: <4be67e64$0$1123$4fafbaef@reader3.news.tin.it> Message-ID: <89888164-41a1-4306-ad7a-2e7d3957c02a@37g2000yqm.googlegroups.com> On 9 Mag, 11:20, superpollo wrote: > "if a b c are digits, solve ab:c=a*c+b" > > solved in one minute with no thought: > > for a in range(10): > ? ? ?for b in range(10): > ? ? ? ? ?for c in range(10): > ? ? ? ? ? ? ?try: > ? ? ? ? ? ? ? ? ?if (10.*a+b)/c==a*c+b: > ? ? ? ? ? ? ? ? ? ? ?print "%i%i:%i=%i*%i+%i" % (a,b,c,a,c,b) > ? ? ? ? ? ? ?except: > ? ? ? ? ? ? ? ? ?pass > > any suggestion for improvement? > > bye The obvious one-liner. Maybe not an improvement, but more compact (I included the solutions for the really lazy ones). But you need to think just one second to exclude 0 from the values of c and avoid a divide by zero exception. >>> [(a,b,c) for a in range(10) for b in range(10) for c in range(1,10) if (a*10+b)/c == a*c+b ] [(0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 0, 5), (0, 0, 6), (0, 0, 7), (0, 0, 8), (0, 0, 9), (0, 1, 1), (0, 2, 1), (0, 3, 1), (0, 4, 1), (0, 5, 1), (0, 6, 1), (0, 7, 1), (0, 8, 1), (0, 9, 1), (1, 0, 3), (1, 5, 2), (1, 6, 2), (2, 0, 3), (2, 1, 3), (3, 1, 3), (4, 1, 3), (4, 2, 3), (5, 2, 3), (6, 2, 3), (6, 3, 3), (7, 3, 3), (8, 3, 3), (8, 4, 3), (9, 4, 3)] Ciao --- FB From nilly16 at yahoo.com Mon May 10 04:40:05 2010 From: nilly16 at yahoo.com (Jimbo) Date: Mon, 10 May 2010 01:40:05 -0700 (PDT) Subject: Extract all words that begin with x Message-ID: Hello I am trying to find if there is a string OR list function that will search a list of strings for all the strings that start with 'a' & return a new list containing all the strings that started with 'a'. I have had a search of Python site & I could not find what I am looking for, does a function like this exist? The only one that I think could work is, use the string function .count() algorithm: to exract all the words inside a list that start with 'a' - make sure the list is arranged in alphabetical order - convert the list to a big string - use list_string.count(',a') to obtain the index where the last 'a' word occurs - convert back into string (yes this is a REAL hack :P) - and then create a new list, ie, new_list = list[0:32] - & return new_list Ok that algorithm is terrible, I know, & I just realise that it wont work for letters after 'a'. So if anyone could suggest a function or algorithm it would be extremely helpful From contact at xavierho.com Mon May 10 04:50:56 2010 From: contact at xavierho.com (Xavier Ho) Date: Mon, 10 May 2010 18:50:56 +1000 Subject: Extract all words that begin with x In-Reply-To: References: Message-ID: Have I missed something, or wouldn't this work just as well: >>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas'] >>> [word for word in list_of_strings if word[0] == 'a'] ['awes', 'asdgas'] Cheers, Xav On Mon, May 10, 2010 at 6:40 PM, Jimbo wrote: > Hello > > I am trying to find if there is a string OR list function that will > search a list of strings for all the strings that start with 'a' & > return a new list containing all the strings that started with 'a'. > > I have had a search of Python site & I could not find what I am > looking for, does a function like this exist? > > The only one that I think could work is, use the string > function .count() > > algorithm: to exract all the words inside a list that start with 'a' > - make sure the list is arranged in alphabetical order > - convert the list to a big string > - use list_string.count(',a') to obtain the index where the last 'a' > word occurs > - convert back into string (yes this is a REAL hack :P) > - and then create a new list, ie, new_list = list[0:32] > - & return new_list > > Ok that algorithm is terrible, I know, & I just realise that it wont > work for letters after 'a'. So if anyone could suggest a function or > algorithm it would be extremely helpful > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From utente at esempio.net Mon May 10 05:11:59 2010 From: utente at esempio.net (superpollo) Date: Mon, 10 May 2010 11:11:59 +0200 Subject: Extract all words that begin with x In-Reply-To: References: Message-ID: <4be7cddf$0$1105$4fafbaef@reader4.news.tin.it> Jimbo ha scritto: > Hello > > I am trying to find if there is a string OR list function that will > search a list of strings for all the strings that start with 'a' & > return a new list containing all the strings that started with 'a'. > > I have had a search of Python site & I could not find what I am > looking for, does a function like this exist? >>> sw = lambda s: lambda t: t.startswith(s) >>> list = ["a string","another one","this is a string","and so is this one"] >>> filter(sw("a"),list) ['a string', 'another one', 'and so is this one'] >>> bye From jeanmichel at sequans.com Mon May 10 05:26:56 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 11:26:56 +0200 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: <4BE7D160.8030300@sequans.com> Stefan Behnel wrote: > j vickroy, 07.05.2010 20:44: >> I apologize if this is not the appropriate forum for a question about >> Hudson (http://hudson-ci.org/), but I did not know where else to ask and >> my web searches have not been fruitful. > > Certainly nice to read something about Hudson in this forum, which is > rare enough. It's seriously the greatest CI tool I've ever used, and > it works great with Python apps. > We use it, but this is a python list that's why there's few topics about it. :) Speaking for myself, I use it to execute the linter (pylint) on the code and run unitary tests. Great tool for sure. JM From jiazhao62 at yahoo.com Mon May 10 05:30:00 2010 From: jiazhao62 at yahoo.com (world-trade) Date: Mon, 10 May 2010 02:30:00 -0700 (PDT) Subject: NFL NBA MLB NHL jersey Message-ID: <1297af1d-09da-4b72-b08f-d166c8a4f4fb@31g2000prc.googlegroups.com> AAA quality clothes cheap wholesale . (http:// www.jordanonline06.com/) NFL jersey wholesale (http://www.jordanonline06.com/) NFL NBA MLB NHL soccer soccer jerseys (http:// www.jordanonline06.com/) nike brand,MLB jerseys china supplier (http:// www.jordanonline06.com/) MLB jerseys china wholesaler.(http://www.jordanonline06.com/) wholesale MLB jerseys.(http://www.jordanonline06.com/) NFL shop,,NFL NBA MLB NHL jerser wholesale,NFL NBA MLB NHL (http://www.jordanonline06.com/) jersey supplier(http://www.jordanonline06.com/) NFL NBA MLB NHL jersey korea supplier (http:// www.jordanonline06.com/) NFL NBA jersey stock (http://www.jordanonline06.com/) alibaba,wholesale NFL NBA MLB NHL jerseys.(http:// www.jordanonline06.com/) soccer jersey china supplier (http://www.jordanonline06.com/) soccer jerseys china wholesale.(http://www.jordanonline06.com/) wholesale soccer jersey,supply soccer jerseys (http:// www.jordanonline06.com/) NFL NBA MLB NHL copy jersey (http://www.jordanonline06.com/) copy www.guoshitrade.com paypal paymentjerseys from china (http://www.jordanonline06.com/) NFL jerseys from china.(http://www.jordanonline06.com/) NBA www.guoshitrade.com paypal payment shop (http:// www.jordanonline06.com/) NFL jersey wholesale womens NBA jersey (http:// www.jordanonline06.com/) NBA jersey sale (http://www.jordanonline06.com/) cheap authentic NBA jersey (http://www.jordanonline06.com/) 07 jersey NBA star (http://www.jordanonline06.com/) NBA jersey numbers (http://www.jordanonline06.com/) NBA vintage jersey NBA throw back jersey (http://www.jordanonline06.com/) NBA jersey dress for woman (http://www.jordanonline06.com/) reebok NBA jersey (http://www.jordanonline06.com/) NBA jersey for toddler (http://www.jordanonline06.com/) old NBA jersey (http://www.jordanonline06.com/) youth NBA swingman jersey (http://www.jordanonline06.com/) NBA authentic basketball jersey (http://www.jordanonline06.com/) basketball jersey NBA new style (http://www.jordanonline06.com/) NBA all star game jersey (http://www.jordanonline06.com/) NBA new jersey (http://www.jordanonline06.com/) adidas NBA jersey (http://www.jordanonline06.com/) official NBA jersey (http://www.jordanonline06.com/) classics hardwood jersey NBA (http://www.jordanonline06.com/) old school NBA jersey (http://www.jordanonline06.com/) NBA jersey for woman (http://www.jordanonline06.com/) classic NBA jersey (http://www.jordanonline06.com/) NFL jersey korea supplier(http://www.jordanonline06.com/) mitchell and ness NBA jersey (http://www.jordanonline06.com/) 2009 game jersey NBA star (http://www.jordanonline06.com/) alternate jersey NBA (http://www.jordanonline06.com/) best selling NBA jersey (http://www.jordanonline06.com/) NBA jersey card (http://www.jordanonline06.com/) authenic NBA jersey (http://www.jordanonline06.com/) discount NBA jersey (http://www.jordanonline06.com/) Wholesale MLB jerseys,paypal,cheap MLB jersey(http:// www.jordanonline06.com/) wholesale football jerseys,(http://www.jordanonline06.com/) reebok MLB player jerseys,(http://www.jordanonline06.com/) authentic MLB jerseys,discount MLB jerseys,mitchell ness jerseys,throwback (http:// www.jordanonline06.com/) Nice jerseys,replica MLB jerseys,(http://www.jordanonline06.com/) women MLB jerseys,youth MLB (http://www.jordanonline06.com/) jerseys,official MLB jerseys,(http://www.jordanonline06.com/) pro Bowl jerseys,super bowl jerseys,(http://www.jordanonline06.com/) nhljerseys,hockey jerseys,nba jerseys,(http:// www.jordanonline06.com/) all star jersey,mlb baseball jerseys (http://www.jordanonline06.com/) (http://www.jordanonline06.com/) From prologic at shortcircuit.net.au Mon May 10 05:35:05 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 10 May 2010 19:35:05 +1000 Subject: Extract all words that begin with x In-Reply-To: References: Message-ID: On Mon, May 10, 2010 at 6:50 PM, Xavier Ho wrote: > Have I missed something, or wouldn't this work just as well: > >>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas'] >>>> [word for word in list_of_strings if word[0] == 'a'] > ['awes', 'asdgas'] I would do this for completeness (just in case): >>>> [word for word in list_of_strings if word and word[0] == 'a'] Just guards against empty strings which may or may not be in the list. --James From utente at esempio.net Mon May 10 05:41:08 2010 From: utente at esempio.net (superpollo) Date: Mon, 10 May 2010 11:41:08 +0200 Subject: Extract all words that begin with x In-Reply-To: <4be7cddf$0$1105$4fafbaef@reader4.news.tin.it> References: <4be7cddf$0$1105$4fafbaef@reader4.news.tin.it> Message-ID: <4be7d4b5$0$1106$4fafbaef@reader4.news.tin.it> superpollo ha scritto: > Jimbo ha scritto: >> Hello >> >> I am trying to find if there is a string OR list function that will >> search a list of strings for all the strings that start with 'a' & >> return a new list containing all the strings that started with 'a'. >> >> I have had a search of Python site & I could not find what I am >> looking for, does a function like this exist? > > >>> sw = lambda s: lambda t: t.startswith(s) > >>> list = ["a string","another one","this is a string","and so is this > one"] > >>> filter(sw("a"),list) > ['a string', 'another one', 'and so is this one'] > >>> > > bye of course there is a simpler way: >>> [string for string in list if string.startswith("a")] ['a string', 'another one', 'and so is this one'] >>> bye From jeanmichel at sequans.com Mon May 10 05:50:59 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 11:50:59 +0200 Subject: idiomatic way to collect and report multiple exceptions? In-Reply-To: <36BDE98F-BE47-431D-971E-732B6A9B2289@ucsd.edu> References: <36BDE98F-BE47-431D-971E-732B6A9B2289@ucsd.edu> Message-ID: <4BE7D703.7050100@sequans.com> Ben Cohen wrote: > Apologies for the TABs -- I wrote that example for demonstration purposes in my mail client -- I'll copy and paste from a real code editor in the future. > Ben > There's nothing to apologies for. Be wary of those trying to get you out of the right path, they will lie to you stating python does not support Tabs while it surely does. Did you know that before generating bytecode, python replace all 4 spaces by a tabulations ? If that is not a proof that TABS is the all mighty indentation, I'm Mickey Mouse. Feel free to join our group for promoting TABS (monthly fee 50$). You an also purchase the book 'TABS Are Beautiful' (12 pages, 380$). JM From paul at boddie.org.uk Mon May 10 07:01:29 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 10 May 2010 04:01:29 -0700 (PDT) Subject: Picking a license References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> Message-ID: <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> On 10 Mai, 03:09, Patrick Maupin wrote: > On May 9, 6:39?pm, Paul Boddie wrote: > > but if they aren't pitching it directly at you, why would you believe > > that they are trying to change your behaviour? > > Because I've seen people specifically state that their purpose in > GPLing small libraries is to encourage other people to change their > behavior. ?I take those statements at face value. ?Certainly RMS > carefully lays out that the LGPL should be used sparingly in his "Why > you shouldn't use the Lesser GPL for your next library" post. ?(Hint: > he's not suggesting a permissive license instead.) Sure, but all he's asking you to do is to make the software available under a GPL-compatible licence. [...] > rst2pdf was licensed under the MIT license before I started > contributing to it, and there is no way I was going to even consider > adding patches for a GPLed package (which would certainly have to be > GPLed) into the rst2pdf repository. ?(Say what you will about how > sometimes differently licensed code can be combined, but RMS has to > share quite a bit of the blame/credit for the whole combining licenses > FUD.) I think the FSF are quite clear about combining licences - they even go to the trouble of telling you which ones are compatible with the GPL - so I don't see where "FUD" comes into it, apart from possible corner cases where people are trying to circumvent the terms of a licence and probably know themselves that what they're trying to do is at the very least against the spirit of the licence. Even then, warning people about their little project to make proprietary plugins, or whatever, is not really "FUD". As for rst2pdf, what your modifications would mean is that the software would need to be redistributed under a GPL-compatible licence. I'll accept that this does affect what people can then do with the project, but once again, you've mentioned at least one LGPL- licensed project which was previously in this very situation, and it was never actually GPL-licensed itself. Here's the relevant FAQ entry: http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL [...] > This is exactly the same situation that Carl was describing, only with > two different open source packages rather than with a proprietary > package and a GPL package. ?The whole reason people use words like > "force" and "viral" with the GPL is that this issue would not have > come up if svglib were MIT and rst2pdf were GPL. ?(Note that the LGPL > forces you to give back changes, but not in a way that makes it > incompatible with software under other licenses. ?That's why you see > very few complaints about the LGPL.) Actually, the copyleft licences don't "force" anyone to "give back changes": they oblige people to pass on changes. [...] > But I have definitely seen cases where people are offering something > that is not of nearly as much value as they seem to think it is, where > one of the goals is obviously to try to spread the GPL. Well, even the FSF doesn't approve of trivial projects using the GPL: http://www.gnu.org/licenses/gpl-faq.html#WhatIfWorkIsShort Paul From jeanmichel at sequans.com Mon May 10 07:14:47 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 13:14:47 +0200 Subject: accessing superclass methods from subclass In-Reply-To: References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com> Message-ID: <4BE7EAA7.1030103@sequans.com> ben wrote: > Ok, thanks for the info. > > What would be a better way to do this? What I'm trying to do is treat > things in a reasonable OOP manner (all fairly new to me, esp. in > Python). Here's a made-up example with a little more context. Let's > say you're making a drawing program that can draw various shapes. So > in the interest of not repeating oneself, I want a class Shape that > handles everything that shapes have, such as a color, and a location. > Then I can subclass Shape to create Square, which has code specific to > drawing a square (e.g. 4 equal sides). So, like this: > > class Shape: > > x = 0 > y = 0 > > def setColor(self,color): > self.color = color > > def setLocation(self,x,y): > self.x = x > self.y = y > > def getLocation(self): > return [self.x,self.y] > > class Square(Shape): > > size = 0 > > def __init__(self,size): > self.size = size > > def draw(self): > location = getLocation() > # code to draw shape from location[0],location[1] at size size > # etc... > > It seems to me that you would want the location code handled in the > Shape class so that I'm not rewriting it for Circle, Triangle, etc., > but I'm not allowed to call any of those methods from the subclass. I > must be thinking of this in the wrong way. Help? > > thanks! > > > > Hi Ben, Please do not top post. You already been given good advices, especially the one suggesting to go through the tutorial. You're making basic mistakes here. Here is a very simple version of your code. class Shape: def __init__(self, x=0, y=0): self.x = 0 self.y = 0 self.color = None def draw(self): print 'drawing %s' % self class Square(Shape): def __init__(self,size): self.size = size def draw(self): Shape.draw(self) # this is one way to call the base class method location = (self.x, self.y) # code to draw shape from self.x, self.y at size self.size # etc... mySquare = Square(5,2) mySquare.color = 'red' print mySquare.x >>> 5 Since your attributes are flagged as public, you don't really need setters & getters. JM From jeanmichel at sequans.com Mon May 10 07:30:00 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 13:30:00 +0200 Subject: Kindly show me a better way to do it In-Reply-To: <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> References: <73fc98c1-6bf7-40c3-bc41-3202bf82be57@a27g2000prj.googlegroups.com> <4be5cf4f$0$818$4fafbaef@reader5.news.tin.it> <1de728c4-9952-496e-836e-4c1e13e889e3@32g2000prq.googlegroups.com> Message-ID: <4BE7EE38.5040100@sequans.com> Oltmans wrote: > On May 9, 1:53 am, superpollo wrote: > > >> add = lambda a,b: a+b >> for i in reduce(add,a): >> print i >> > > This is very neat. Thank you. Sounds like magic to me. Can you please > explain how does that work? Many thanks again. > > shorter <> nicer IMO. Those alternatives are interesting from a tech point of view, but nothing can beat the purity of a vintage 'for' loop with *meaningful names*. salads = [['apple', 'banana'], ['apple', 'lemon', 'kiwi']] ingredients = [] for salad in salads: for fruit in salad: ingredients.append(fruit) print 'Remember to buy %s' % ingredients Lame & effective (1st adjective is irrelevant outside a geek contest) JM From luke.leighton at googlemail.com Mon May 10 07:35:43 2010 From: luke.leighton at googlemail.com (lkcl) Date: Mon, 10 May 2010 04:35:43 -0700 (PDT) Subject: Python is cool!! References: <09813819-e3d3-4998-85e0-71fce5992227@u9g2000yqb.googlegroups.com> Message-ID: On Mar 23, 4:55?pm, Jose Manuel wrote: > I have been learning Python, and it is amazing .... I am using the > tutorial that comes with the official distribution. > > At the end my goal is to develop applied mathematic in engineering > applications to be published on the Web, specially on app. oriented to > simulations and control systems, I was about to start learning Java > but I found Python which seems easier to learn that Java. > > Would it be easy to integrate Python in Web pages with HTML? I have > read many info on Internet saying it is, and I hope so .... jose, hi, perhaps it should be pointed out that there are four completely different types of answers, as outlined here: http://www.advogato.org/article/993.html python can be involved in absolutely every single one of those four separate types of answers. you should ideally read that article to determine which of the four approaches is most appropriate for you, and let people here know; and then people here will be able to respond accordingly and advise you accurately and with less time spent on their part, in guessing what it is that you want to do. l. From space.ship.traveller at gmail.com Mon May 10 08:24:22 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 11 May 2010 00:24:22 +1200 Subject: Is Python a functional programming language? Message-ID: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> Dear Friends, Is Python a functional programming language? Is this a paradigm that is well supported by both the language syntax and the general programming APIs? I heard that lambdas were limited to a single expression, and that other functional features were slated for removal in Python 3... is this the case or have I been misinformed? Finally, even if Python supports functional features, is this a model that is used often in client/application code? Kind regards, Samuel From jayeola at gmail.com Mon May 10 08:38:49 2010 From: jayeola at gmail.com (John Maclean) Date: Mon, 10 May 2010 13:38:49 +0100 Subject: unittest not being run Message-ID: <4BE7FE59.408@gmail.com> hi, can some one explain why the __first__ test is not being run? #!/usr/bin/env python import unittest # {{{ class T1TestCase(unittest.TestCase): def setUp(self): pass # can we use global variables here? def tearDown(self): pass # garbage collection def test_T1(self): '''this test aint loading''' self.assertEquals(1, 0) def test_T2(self): ## test method names begin 'test*' self.assertEquals((1 + 2), 3) self.assertEquals(0 + 1, 1) def test_T3(self): self.assertEquals((0 * 10), 0) self.assertEquals((5 * 8), 40) # the output is better. prints each test and ok or fail suite = unittest.TestLoader().loadTestsFromTestCase(T1TestCase) unittest.TextTestRunner(verbosity=2).run(suite) # }}} ''' halp! the first test ain't loading... python blaht.py test_T2 (__main__.T1TestCase) ... ok test_T3 (__main__.T1TestCase) ... ok ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK ''' From paul at boddie.org.uk Mon May 10 08:39:57 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 10 May 2010 05:39:57 -0700 (PDT) Subject: Picking a license References: <4BE05D75.7030301@msn.com> <87k4rgfutu.fsf@benfinney.id.au> <4be645f2$0$27783$c3e8da3@news.astraweb.com> <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> <99386b28-1636-4f81-beec-3756970d37e8@11g2000prv.googlegroups.com> Message-ID: <1e93ddfd-ea89-4062-bc46-ba3db0b4f359@d39g2000yqa.googlegroups.com> On 10 Mai, 08:31, Carl Banks wrote: > On May 9, 10:08?am, Paul Boddie wrote: > > Oh sure: the GPL hurts everyone, like all the companies who have made > > quite a lot of money out of effectively making Linux the new > > enterprise successor to Unix, plus all the companies and individuals > > who have taken the sources and rolled their own distributions. > > Relative to what they could have done with a more permissive license? Well, yes. Some people would have it that the only reason why BSD variants never became as popular as Linux (or rather, GNU/Linux, but lets keep this focused) is because the litigation around the BSD code base "scared people away". Yet I remember rather well back in the mid-1990s when people using the same proprietary-and-doomed platform as myself started looking into Unix-flavoured operating systems, and a group of people deliberately chose NetBSD because of the favourable licensing conditions and because there was a portability headstart over Linux, which at the time people seriously believed was rather non- portable. So, that "scary AT&T" myth can be sunk, at least when considering its impact on what people were doing in 1994. Although the NetBSD port in question lives on, and maybe the people responsible all took jobs in large companies, its success on that platform and its derivatives has been dwarfed by that of the corresponding Linux port. > Yes. ?GPL hurts everyone relative to licenses that don't drive wedges > and prevent interoperability between software. I can think of another case, actually connected to the above proprietary platform and its practitioners, where software licensing stood in the way of "just getting on with business" which is what you seem to be advocating: a company released their application under the GPL, except for one critical library which remained proprietary software. Now, although you can argue that everyone's life would be richer had the GPL not prohibited "interoperability" (although I imagine that the application's licensing actually employed an exception to glue everything together in that particular case), a community never formed because people probably assumed that their role would only ever be about tidying up someone else's code so that the original authors could profit from it. All the GPL is designed to do in such cases is to encourage people to seek control (in terms of the "four freedoms") of all the technology, rather than be placated by the occasional airdrop of proprietary software and to be convinced never to explore the possibility of developing something similar for themselves. The beneficiary of the refusal to work on the above application was the GPL-licensed Inkscape, which might not be as well-liked by many people, but it does demonstrate, firstly, that permissive licences do not have the monopoly on encouraging people to work on stuff, and secondly, that actually going and improving something else is the answer if you don't like the licensing of something. > You might argue that GPL is sometimes better than proprietary closed > source, and I won't disagree, but it's nearly always worse than other > open source licenses. For me, I would argue that the GPL is always better than "proprietary closed source", recalling that the consideration is that of licensing and not mixing in other concerns like whether a particular program is technically better. In ensuring that an end-user gets some code and can break out those "four freedoms" on it, it is clearly not "worse than other open source licenses", and I don't accept that this is some rare thing that only happens outside a theoretical setting on an occasional basis. > > P.S. And the GPL isn't meant to further the cause of open source: it's > > meant to further the Free Software cause, which is not at all the same > > thing. > > It doesn't matter what the GPL "meant" to do, it matters what it does, > which is hurt everyone (relative to almost all other licenses). This is your opinion, not objectively established fact. > > Before you ridicule other people's positions, at least get your > > terminology right. > > I don't agree with FSF's defintion of free software and refuse to > abide by it. ?GPL isn't free software; any software that tells me I > can't compile it in with a closed source API isn't free. ?Period. Well, if you can't (or can't be bothered) to distinguish between what is known as Free Software and "open source", then I'm hardly surprised that you take offence at people releasing software for one set of reasons while you only consider another set of reasons to be valid ones. Throughout this discussion I've been accused of not being able to put myself in the position of the other side, but I completely understand that people just want as much publicly available software as possible to be permissively licensed, frequently for the reason that it will "grease the wheels of commerce", that it reduces (but, contrary to popular belief, does *not* eliminate) the amount of thought required when combining works, and that "the boss" or "the company lawyers" feel more comfortable with permissive licences, perhaps because they are scared about what might happen to their patent portfolio or something (in which case they might want to re- read some of those licences). It isn't news to me that some people emphasise developer "freedoms" and others emphasise user "freedoms", and frequently advocates of the former can only consider unrestricted personal gratification as "freedom". But to argue for the latter, I don't need to argue about how some style of licence is "better" according to some hastily arranged and fragile criteria: it's clear what the goal of copyleft licensing is; take it or leave it. There's no real disinformation campaign or "propaganda"; the FSF aren't "forcing" people to do anything, in contrast to various proprietary software licences and the way that most people are more obviously "forced" to buy a Microsoft product when they buy a computer (and be told that there's no refund, that it's "part of the product", contrary to what the EULA actually says for obvious regulatory reasons). So, given an acknowledgement of the motivation for copyleft licensing, the argument for applying it practically makes itself. I don't need to bring terminology like "holy war" or references to Bin Laden to make my case. I wonder, then, why people feel the need to do just that. Paul From werner.bruhin at free.fr Mon May 10 08:42:35 2010 From: werner.bruhin at free.fr (Werner F. Bruhin) Date: Mon, 10 May 2010 14:42:35 +0200 Subject: Upgrade Python 2.6.4 to 2.6.5 Message-ID: <4BE7FF3B.7030101@free.fr> Just upgraded on my Windows 7 machine my copy of 2.6.4 to 2.6.5. However doing sys.version still shows 2.6.4 even so python.exe is dated 19. March 2010 with a size of 26.624 bytes. Is this a known issue? Or did I do something wrong? If I install to a new folder all is well, but I would have to install all my other stuff again (kinterbasdb, matplotlib, sphinx etc etc). Werner From goon12 at gmail.com Mon May 10 08:44:44 2010 From: goon12 at gmail.com (Joe Riopel) Date: Mon, 10 May 2010 08:44:44 -0400 Subject: unittest not being run In-Reply-To: <4BE7FE59.408@gmail.com> References: <4BE7FE59.408@gmail.com> Message-ID: On Mon, May 10, 2010 at 8:38 AM, John Maclean wrote: > hi, > > can some one explain why the __first__ test is not being run? It looks like you defined test_T1 inside of the tearDown method. From stefan_ml at behnel.de Mon May 10 08:52:51 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 May 2010 14:52:51 +0200 Subject: Is Python a functional programming language? In-Reply-To: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> Message-ID: Samuel Williams, 10.05.2010 14:24: > Is Python a functional programming language? No. Python is a multi-paradigm language. But it does have functions (and methods) as first-class objects. > Is this a paradigm that is well supported by both the language syntax > and the general programming APIs? I'd say so, but it certainly depends on what functional language features you desire. > I heard that lambdas were limited to a single expression ... which is a good thing. An expression in Python can do pretty complex things already. Not allowing more puts a limit to code readability degradation. > and that other > functional features were slated for removal in Python 3... is this the > case or have I been misinformed? No such functionality has been removed in Py3, and in fact, several core language features were adapted to make functional programming easier and more efficient. > Finally, even if Python supports functional features, is this a model > that is used often in client/application code? From my point of view, yes. But the beauty is that Python is multi-paradigm, so you're not restricted to functional language features. Stefan From bruno.42.desthuilliers at websiteburo.invalid Mon May 10 09:11:13 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 10 May 2010 15:11:13 +0200 Subject: Is Python a functional programming language? In-Reply-To: References: Message-ID: <4be805f0$0$12228$426a34cc@news.free.fr> Samuel Williams a ?crit : > Dear Friends, > > Is Python a functional programming language? Depends on your definition of "functional programming language", but well, not really. It's mostly an imperative, object-oriented (but not pure-object) language. It has some restricted support for some functional idioms but trying to use it a true FPL would be a waste of time (both developper's and computer's). > Is this a paradigm that is well supported by both the language syntax and the general programming APIs? No. > I heard that lambdas were limited to a single expression, True. > and that other functional features were slated for removal in Python 3... False. Some FP-inspired functions and types are moving from builtins to a dedicated module, but they are still available. > is this the case or have I been misinformed? > > Finally, even if Python supports functional features, is this a model that is used often in client/application code? Once again, depends on your definitions of what's "functional". Some FP-inspired idioms and features are definitly idiomatic, but that doesn't make for true functional programming. Once again, trying to do pure FP in Python would be fighting against the language. From jim.vickroy at noaa.gov Mon May 10 09:30:32 2010 From: jim.vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 07:30:32 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: <4BE80A78.2030502@noaa.gov> Stefan Behnel wrote: > j vickroy, 07.05.2010 20:44: >> I apologize if this is not the appropriate forum for a question about >> Hudson (http://hudson-ci.org/), but I did not know where else to ask and >> my web searches have not been fruitful. > > Certainly nice to read something about Hudson in this forum, which is > rare enough. It's seriously the greatest CI tool I've ever used, and it > works great with Python apps. > > >> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >> >> in the *Execute Python Script* subsection. > > The problem is that this isn't a "Python Script". I's a an executable, > native program. Use the "execute shell" build step instead. > > Stefan > Thanks for your reply, Stefan. When the above command "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" is moved to the "Execute shell" section of the job configuration page along with the following "tracer" command: #!python.exe print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' their is still no indication the unit tests are run. Here is the output from the Hudson Console Output page ------------------------------------------------------------------- Started by user anonymous Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 At revision 3401 no change for svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build [workspace] $ python.exe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2011616575490005324.sh FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO [workspace] $ cmd.exe -xe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson902246697107326581.sh Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace>Recording test results Test reports were found but none of them are new. Did tests run? For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml is 2 days 19 hr old Finished: FAILURE ------------------------------------------------------------------- As a side note, my Hudson "global" configuration page contains: cmd.exe in the "Shell executable" section and NOSEDIR C:\Python26\Scripts in the "Global properties" section. -- jv From Jim.Vickroy at noaa.gov Mon May 10 09:30:32 2010 From: Jim.Vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 07:30:32 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: <4BE80A78.2030502@noaa.gov> Stefan Behnel wrote: > j vickroy, 07.05.2010 20:44: >> I apologize if this is not the appropriate forum for a question about >> Hudson (http://hudson-ci.org/), but I did not know where else to ask and >> my web searches have not been fruitful. > > Certainly nice to read something about Hudson in this forum, which is > rare enough. It's seriously the greatest CI tool I've ever used, and it > works great with Python apps. > > >> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >> >> in the *Execute Python Script* subsection. > > The problem is that this isn't a "Python Script". I's a an executable, > native program. Use the "execute shell" build step instead. > > Stefan > Thanks for your reply, Stefan. When the above command "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" is moved to the "Execute shell" section of the job configuration page along with the following "tracer" command: #!python.exe print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' their is still no indication the unit tests are run. Here is the output from the Hudson Console Output page ------------------------------------------------------------------- Started by user anonymous Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 At revision 3401 no change for svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build [workspace] $ python.exe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2011616575490005324.sh FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO [workspace] $ cmd.exe -xe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson902246697107326581.sh Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace>Recording test results Test reports were found but none of them are new. Did tests run? For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml is 2 days 19 hr old Finished: FAILURE ------------------------------------------------------------------- As a side note, my Hudson "global" configuration page contains: cmd.exe in the "Shell executable" section and NOSEDIR C:\Python26\Scripts in the "Global properties" section. -- jv From jim.vickroy at noaa.gov Mon May 10 09:31:57 2010 From: jim.vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 07:31:57 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: <4BE80ACD.8080805@noaa.gov> Jean-Michel Pichavant wrote: > Stefan Behnel wrote: >> j vickroy, 07.05.2010 20:44: >>> I apologize if this is not the appropriate forum for a question about >>> Hudson (http://hudson-ci.org/), but I did not know where else to ask and >>> my web searches have not been fruitful. >> >> Certainly nice to read something about Hudson in this forum, which is >> rare enough. It's seriously the greatest CI tool I've ever used, and >> it works great with Python apps. >> > We use it, but this is a python list that's why there's few topics about > it. :) > Speaking for myself, I use it to execute the linter (pylint) on the > code and run unitary tests. Great tool for sure. > > JM > Is there a more appropriate forum to ass about Python and Hudson? -- jv From Jim.Vickroy at noaa.gov Mon May 10 09:31:57 2010 From: Jim.Vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 07:31:57 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: Message-ID: <4BE80ACD.8080805@noaa.gov> Jean-Michel Pichavant wrote: > Stefan Behnel wrote: >> j vickroy, 07.05.2010 20:44: >>> I apologize if this is not the appropriate forum for a question about >>> Hudson (http://hudson-ci.org/), but I did not know where else to ask and >>> my web searches have not been fruitful. >> >> Certainly nice to read something about Hudson in this forum, which is >> rare enough. It's seriously the greatest CI tool I've ever used, and >> it works great with Python apps. >> > We use it, but this is a python list that's why there's few topics about > it. :) > Speaking for myself, I use it to execute the linter (pylint) on the > code and run unitary tests. Great tool for sure. > > JM > Is there a more appropriate forum to ass about Python and Hudson? -- jv From jcd at sdf.lonestar.org Mon May 10 09:38:44 2010 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 10 May 2010 09:38:44 -0400 Subject: unittest not being run In-Reply-To: <4BE7FE59.408@gmail.com> References: <4BE7FE59.408@gmail.com> Message-ID: <1273498724.2997.3.camel@cliff-laptop> My guess is you mixed tabs and spaces. One tab is always treated by the python interpreter as being equal to eight spaces, which is two indentation levels in your code. Though if it were exactly as you show it, you'd be getting a syntax error, because even there, it looks like the indentation of your `def test_T1(self):` line is off by one column, relative to pass, and by three columns relative to the other methods. Cheers, Cliff On Mon, 2010-05-10 at 13:38 +0100, John Maclean wrote: > hi, > > can some one explain why the __first__ test is not being run? > > #!/usr/bin/env python > import unittest # {{{ > class T1TestCase(unittest.TestCase): > > def setUp(self): > pass # can we use global variables here? > > def tearDown(self): > pass # garbage collection > > def test_T1(self): > '''this test aint loading''' > self.assertEquals(1, 0) > > def test_T2(self): ## test method names begin 'test*' > self.assertEquals((1 + 2), 3) > self.assertEquals(0 + 1, 1) > > def test_T3(self): > self.assertEquals((0 * 10), 0) > self.assertEquals((5 * 8), 40) > > # the output is better. prints each test and ok or fail > suite = unittest.TestLoader().loadTestsFromTestCase(T1TestCase) > unittest.TextTestRunner(verbosity=2).run(suite) # }}} > > > ''' halp! > > the first test ain't loading... > > python blaht.py > test_T2 (__main__.T1TestCase) ... ok > test_T3 (__main__.T1TestCase) ... ok > > ---------------------------------------------------------------------- > Ran 2 tests in 0.000s > > OK > > ''' From kaklis at gmail.com Mon May 10 10:00:54 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Mon, 10 May 2010 07:00:54 -0700 (PDT) Subject: HTTP Post Request Message-ID: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> Hi to all, i want to ask you a question, concerning the best way to do the following as a POST request: There is server-servlet that accepts xml commands It had the following HTTP request headers: Host: somehost.com User-Agent: Jakarta Commons-HttpClient Content-Type: text/xml Content-Length: 415 and the following request body (reformatted here for clarity): search How can i send the above to the Listener Servlet? Thanks in advance From googler.1.webmaster at spamgourmet.com Mon May 10 10:06:48 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Mon, 10 May 2010 07:06:48 -0700 (PDT) Subject: INCREF DECREF manually Message-ID: <6033c45c-1eb7-45c7-9cb8-9597cd5e0e8d@o14g2000yqb.googlegroups.com> Hi, just a small question. Is it possible to change the refcount of a reference manually? For debugging / ... Thanks! moerchendiser2k3 From jeanmichel at sequans.com Mon May 10 10:14:19 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 16:14:19 +0200 Subject: INCREF DECREF manually In-Reply-To: <6033c45c-1eb7-45c7-9cb8-9597cd5e0e8d@o14g2000yqb.googlegroups.com> References: <6033c45c-1eb7-45c7-9cb8-9597cd5e0e8d@o14g2000yqb.googlegroups.com> Message-ID: <4BE814BB.9020106@sequans.com> moerchendiser2k3 wrote: > Hi, > > just a small question. Is it possible to change the refcount of a > reference manually? For debugging / ... > > Thanks! > > moerchendiser2k3 > Why don't you just create a global reference to the object ? Unless this one is removed, the object will be kept in memory. JM From jayeola at gmail.com Mon May 10 10:21:26 2010 From: jayeola at gmail.com (John Maclean) Date: Mon, 10 May 2010 15:21:26 +0100 Subject: unittest not being run In-Reply-To: <1273498724.2997.3.camel@cliff-laptop> References: <4BE7FE59.408@gmail.com> <1273498724.2997.3.camel@cliff-laptop> Message-ID: <4BE81666.80301@gmail.com> On 10/05/2010 14:38, J. Cliff Dyer wrote: > My guess is you mixed tabs and spaces. One tab is always treated by the > python interpreter as being equal to eight spaces, which is two > indentation levels in your code. > > Though if it were exactly as you show it, you'd be getting a syntax > error, because even there, it looks like the indentation of your `def > test_T1(self):` line is off by one column, relative to pass, and by > three columns relative to the other methods. > > Cheers, > Cliff 'twas a spaces/indent issue. thanks! From kushal.kumaran+python at gmail.com Mon May 10 10:22:53 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Mon, 10 May 2010 19:52:53 +0530 Subject: HTTP Post Request In-Reply-To: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> Message-ID: On Mon, May 10, 2010 at 7:30 PM, kaklis at gmail.com wrote: > Hi to all, i want to ask you a question, concerning the best way to do > the following as a POST request: > There is server-servlet that accepts xml commands > It had the following HTTP request headers: > > ? ? ? ? ? ?Host: somehost.com > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient > ? ? ? ? ? ?Content-Type: text/xml > ? ? ? ? ? ?Content-Length: 415 > > and the following request body (reformatted here for clarity): > > ? ? ? ? ? ? > ? ? ? ? ? ? > ? ? ? ? ? ? ?search > ? ? ? ? ? ? > How can i send the above to the Listener Servlet? > Thanks in advance Use the xmlrpclib module. -- regards, kushal From jeanmichel at sequans.com Mon May 10 10:26:13 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 May 2010 16:26:13 +0200 Subject: unable to get Hudson to run unit tests In-Reply-To: <4BE80A78.2030502@noaa.gov> References: <4BE80A78.2030502@noaa.gov> Message-ID: <4BE81785.8090402@sequans.com> j vickroy wrote: > Stefan Behnel wrote: >> j vickroy, 07.05.2010 20:44: >>> I apologize if this is not the appropriate forum for a question about >>> Hudson (http://hudson-ci.org/), but I did not know where else to ask >>> and >>> my web searches have not been fruitful. >> >> Certainly nice to read something about Hudson in this forum, which is >> rare enough. It's seriously the greatest CI tool I've ever used, and >> it works great with Python apps. >> >> >>> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >>> >>> in the *Execute Python Script* subsection. >> >> The problem is that this isn't a "Python Script". I's a an >> executable, native program. Use the "execute shell" build step instead. >> >> Stefan >> > Thanks for your reply, Stefan. > > When the above command > > "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" > > is moved to the "Execute shell" section of the job configuration page > along with the following "tracer" command: > > #!python.exe > print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' > > their is still no indication the unit tests are run. > > Here is the output from the Hudson Console Output page > > ------------------------------------------------------------------- > Started by user anonymous > Updating svn://vm-svn/GOES data > processing/trunk/GOES/13,14,15/SXI/level-1 > At revision 3401 > no change for svn://vm-svn/GOES data > processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build > [workspace] $ python.exe > C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2011616575490005324.sh > FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO > [workspace] $ cmd.exe -xe > C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson902246697107326581.sh > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI > Level-1 Products Generation\workspace>Recording test results > Test reports were found but none of them are new. Did tests run? > For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES > 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml > is 2 days 19 hr old > > Finished: FAILURE > ------------------------------------------------------------------- > > As a side note, my Hudson "global" configuration page contains: > > cmd.exe > > in the "Shell executable" section and > > NOSEDIR > C:\Python26\Scripts > > in the "Global properties" section. > > -- jv Maybe something is missing on the machine hosting hudson, did you try to execute nosetests.exe on that machine ? I'm also confused with something, you do not provide nosetests with the location of your package, assuming the current directory contains that package (my guess). Instead of printing 'FOOO', try "import os ; print os.getcwd(); print os.listdir(os.getcwd())" to know where you are exactly and if this dir contains your python package. JM From googler.1.webmaster at spamgourmet.com Mon May 10 10:26:42 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Mon, 10 May 2010 07:26:42 -0700 (PDT) Subject: INCREF DECREF manually References: <6033c45c-1eb7-45c7-9cb8-9597cd5e0e8d@o14g2000yqb.googlegroups.com> Message-ID: Do to some debugging if a version contains a bug and needs to be fixed there manually. From kaklis at gmail.com Mon May 10 10:56:34 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Mon, 10 May 2010 07:56:34 -0700 (PDT) Subject: HTTP Post Request References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> Message-ID: <06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com> On May 10, 10:22?am, Kushal Kumaran wrote: > On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com wrote: > > Hi to all, i want to ask you a question, concerning the best way to do > > the following as a POST request: > > There is server-servlet that accepts xml commands > > It had the following HTTP request headers: > > > ? ? ? ? ? ?Host: somehost.com > > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient > > ? ? ? ? ? ?Content-Type: text/xml > > ? ? ? ? ? ?Content-Length: 415 > > > and the following request body (reformatted here for clarity): > > > ? ? ? ? ? ? > > ? ? ? ? ? ? > > ? ? ? ? ? ? ?search > > ? ? ? ? ? ? > > How can i send the above to the Listener Servlet? > > Thanks in advance > > Use the xmlrpclib module. > > -- > regards, > kushal OK, sending headers with xmlrpclib, but how do i send the XML message? Thanks A.K. From pmaupin at gmail.com Mon May 10 11:01:55 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Mon, 10 May 2010 08:01:55 -0700 (PDT) Subject: Picking a license References: <87tyqje0qh.fsf@benfinney.id.au> <570e9dbd-1624-4aed-953d-dd86221a3ed2@o14g2000yqb.googlegroups.com> <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> Message-ID: On May 10, 6:01?am, Paul Boddie wrote: > On 10 Mai, 03:09, Patrick Maupin wrote: > > > On May 9, 6:39?pm, Paul Boddie wrote: > > > but if they aren't pitching it directly at you, why would you believe > > > that they are trying to change your behaviour? > > > Because I've seen people specifically state that their purpose in > > GPLing small libraries is to encourage other people to change their > > behavior. ?I take those statements at face value. ?Certainly RMS > > carefully lays out that the LGPL should be used sparingly in his "Why > > you shouldn't use the Lesser GPL for your next library" post. ?(Hint: > > he's not suggesting a permissive license instead.) > > Sure, but all he's asking you to do is to make the software available > under a GPL-compatible licence. I'll be charitable and assume the fact that you can make that statement without apparent guile merely means that you haven't read the post I was referring to: http://www.gnu.org/philosophy/why-not-lgpl.html > [...] > > > rst2pdf was licensed under the MIT license before I started > > contributing to it, and there is no way I was going to even consider > > adding patches for a GPLed package (which would certainly have to be > > GPLed) into the rst2pdf repository. ?(Say what you will about how > > sometimes differently licensed code can be combined, but RMS has to > > share quite a bit of the blame/credit for the whole combining licenses > > FUD.) > > I think the FSF are quite clear about combining licences - they even > go to the trouble of telling you which ones are compatible with the > GPL Yes, but one of the things they are quite clear on is that the overall work must be licensed as GPL, if any of the components are licensed as GPL. They claim this is true, even if a non-GPL work dynamically links to a GPL work. - so I don't see where "FUD" comes into it, apart from possible > corner cases where people are trying to circumvent the terms of a > licence and probably know themselves that what they're trying to do is > at the very least against the spirit of the licence. Legally, I don't think they can dictate the license terms of, e.g. clisp just because it can link to readline. But practically, they DID manage to do this, simply because Bruno Haible, the clisp author, was more concerned about writing software than spending too much time sparring with Stallman over the license, so he finally licensed clisp under the gpl. clisp *could* use readline, but didn't require it; nonetheless Stallman argued that clisp was a "derivative" of readline. That case of the tail wagging the dog would be laughable if it hadn't worked. In any case, Stallman's success at that tactic is probably one of the things that led him to write the paper on why you should use GPL for your library. (As an aside, since rst2pdf *can* use GPL-licensed svglib, it could possibly be subject to the same kind of political pressure as clisp. But the fact that more people are better informed now and that the internet would publicize the dispute more widely more quickly means that this is a battle Stallman is unlikely to wage at this point, because if the leader of any such targeted project has enough cojones, the FSF's inevitable loss would reduce some of the FUD dramatically.) > Even then, > warning people about their little project to make proprietary plugins, > or whatever, is not really "FUD". I think that, legally, they probably don't have a leg to stand on for some of their overarching claims (e.g. about shipping proprietary software that could link to readline, without even shipping readline). But morally -- well, they've made their position reasonably clear and I try to abide by it. That still doesn't make it "not really FUD." I'd call this sort of badgering "copyright misuse" myself. > As for rst2pdf, what your modifications would mean is that the > software would need to be redistributed under a GPL-compatible > licence. That's parsing semantics rather finely. In practice, what it really means is that the combination (e.g. the whole program) would effectively be GPL-licensed. This then means that downstream users would have to double-check that they are not combining the whole work with licenses which are GPL-incompatible, even if they are not using the svg feature. Hence, the term "viral." > I'll accept that this does affect what people can then do > with the project, but once again, you've mentioned at least one LGPL- > licensed project which was previously in this very situation, and it > was never actually GPL-licensed itself. Here's the relevant FAQ entry: > > http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL Yes, I've read that, but this is much more informative: http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystem "A system incorporating a GPL-covered program is an extended version of that program. The GPL says that any extended version of the program must be released under the GPL if it is released at all." This makes it clear that the overall work must be GPLed. Now, all of a sudden, downstream users cannot do some things they could have done before. Can you not see that taking a preexisting MIT-licensed project and adding code to make it GPL could negatively affect some of its users and that that is not necessarily an unalloyed good? > [...] > > > This is exactly the same situation that Carl was describing, only with > > two different open source packages rather than with a proprietary > > package and a GPL package. ?The whole reason people use words like > > "force" and "viral" with the GPL is that this issue would not have > > come up if svglib were MIT and rst2pdf were GPL. ?(Note that the LGPL > > forces you to give back changes, but not in a way that makes it > > incompatible with software under other licenses. ?That's why you see > > very few complaints about the LGPL.) > > Actually, the copyleft licences don't "force" anyone to "give back > changes": they oblige people to pass on changes. True, if pedantic. I meant "give back" in the more general sense. > [...] > > > But I have definitely seen cases where people are offering something > > that is not of nearly as much value as they seem to think it is, where > > one of the goals is obviously to try to spread the GPL. > > Well, even the FSF doesn't approve of trivial projects using the GPL: > > http://www.gnu.org/licenses/gpl-faq.html#WhatIfWorkIsShort Sure, that's a pragmatic view -- copyright might not even be permitted on something that short that is mainly functional. However, length is not the only arbiter of trivial. To stay with the same example, personally, I would consider readline "trivial" within the context of a lot of software which might use it, regardless of whether the readline implementation itself used all sorts of fancy neural net technology to predict what word the user was going to type or whatever. But whether it was trivial or not, if I ship software that *could* link to it but doesn't *require* it (like the case of clisp) without shipping readline, I think it's FUD and an attempt at copyright misuse to call my software a derivative work of readline. But obviously YMMV Regards, Pat From aahz at pythoncraft.com Mon May 10 11:06:24 2010 From: aahz at pythoncraft.com (Aahz) Date: 10 May 2010 08:06:24 -0700 Subject: Picking a license References: <30aff350- <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> Message-ID: In article <074b412a-c2f4-4090-a52c-4d69edb29a22 at d39g2000yqa.googlegroups.com>, Paul Boddie wrote: > >Actually, the copyleft licences don't "force" anyone to "give back >changes": they oblige people to pass on changes. IMO, that's a distinction without a difference, particularly if you define "give back" as referring to the community rather than the original project. With the FSF itself using "pressure" in the FAQ entry you linked to, I have no clue why you and Ben Finney object to my use of "force". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From zhangdongche001 at gmail.com Mon May 10 11:12:40 2010 From: zhangdongche001 at gmail.com (xiao wu) Date: Mon, 10 May 2010 08:12:40 -0700 (PDT) Subject: Wholesale Sports Shoes Clear Air Force One AAA++quality(www.cnnshoe.com) Message-ID: <8b973d50-0857-4257-8eee-52aea3ae04b9@z15g2000prh.googlegroups.com> supply sports shoes. The brand Sports shoes basketball shoes, Boot, walling shoes, Athletic shoes, Jogging shoes, running shoes, leather shoes, football, shoe sports shoe Footwear Sneaker, Shox Max Rift T- shirts, womens t-shirts, Clothing womens clothing, wear hats Caps Jersey jeans Sock Jacks, Watches, wallet, handbags, and Jeans Lady Clothing and so on. Please contact us by email to get more information. please kindly visite our website: http://www.cnnshoe.com msn: cnnshoe2009 at hotmail.com email: cnnshoe at gmail.com From solipsis at pitrou.net Mon May 10 11:17:07 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Mon, 10 May 2010 17:17:07 +0200 Subject: INCREF DECREF manually References: <6033c45c-1eb7-45c7-9cb8-9597cd5e0e8d@o14g2000yqb.googlegroups.com> Message-ID: <20100510171707.565ebb79@pitrou.net> On Mon, 10 May 2010 07:26:42 -0700 (PDT) moerchendiser2k3 wrote: > > Do to some debugging if a version contains a bug and needs to be fixed > there manually. This is certainly the wrong approach. To know if your Python code is leaking references, use either sys.getrefcount(), or (better) a weakref -- and don't forget to call gc.collect(). To know if some C extension is buggy, use your C debugger (or your favourite alternative debugging method, such as printf()). Changing reference counts from Python will lead to two possible consequences: - if you increment a reference count, you will have a permanent memory leak - if you decrement a reference count, you will eventually crash the interpreter From aahz at pythoncraft.com Mon May 10 11:21:14 2010 From: aahz at pythoncraft.com (Aahz) Date: 10 May 2010 08:21:14 -0700 Subject: Picking a license References: <3e49d127-069b-44f4-9eb1-2dc2aca5b0e3@24g2000yqy.googlegroups.com> <99386b28-1636-4f81-beec-3756970d37e8@11g2000prv.googlegroups.com> Message-ID: [we have previously been using "MIT-style" and "BSD-style" licensing in this thread for the most part -- given the poster who suggested that Apache makes more sense these days, I'm switching to that terminology] In article <99386b28-1636-4f81-beec-3756970d37e8 at 11g2000prv.googlegroups.com>, Carl Banks wrote: > >You might argue that GPL is sometimes better than proprietary closed >source, and I won't disagree, but it's nearly always worse than other >open source licenses. That I completely disagree with. I'm not going to bother making arguments (Paul Boddie et al has done a much better job than I could), but I wanted to register my disagreement as someone who generally prefers Apache-style licenses. I will just add that I believe that Apache-style licensing could not work in the absence of GPL software. IOW, I believe that GPL confers a form of herd immunity to Open Source in general, and Stallman gets full credit for creating the idea of GPL to protect Open Source. I believe that Stallman understands this perfectly well and it in part represents why he is so opposed to non-GPL licensing; it makes sense that he feels some resentment toward the "freeloading" from the rest of the Open Source community. OTOH, I also believe that having only GPL would destroy Open Source as a viable development environment and community; it's too restrictive for some very valuable projects (including Python in specific, to bring this back on topic). Each project needs to think carefully about its relationship to the Open Source ecosystem and community before deciding on a license. But for small projects trying to get users, defaulting to Apache makes sense. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From Jim.Vickroy at noaa.gov Mon May 10 11:39:14 2010 From: Jim.Vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 09:39:14 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: <4BE80A78.2030502@noaa.gov> Message-ID: <4BE828A2.2070106@noaa.gov> Jean-Michel Pichavant wrote: > j vickroy wrote: >> Stefan Behnel wrote: >>> j vickroy, 07.05.2010 20:44: >>>> I apologize if this is not the appropriate forum for a question about >>>> Hudson (http://hudson-ci.org/), but I did not know where else to ask >>>> and >>>> my web searches have not been fruitful. >>> >>> Certainly nice to read something about Hudson in this forum, which is >>> rare enough. It's seriously the greatest CI tool I've ever used, and >>> it works great with Python apps. >>> >>> >>>> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >>>> >>>> in the *Execute Python Script* subsection. >>> >>> The problem is that this isn't a "Python Script". I's a an >>> executable, native program. Use the "execute shell" build step instead. >>> >>> Stefan >>> >> Thanks for your reply, Stefan. >> >> When the above command >> >> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >> >> is moved to the "Execute shell" section of the job configuration page >> along with the following "tracer" command: >> >> #!python.exe >> print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' >> >> their is still no indication the unit tests are run. >> >> Here is the output from the Hudson Console Output page >> >> ------------------------------------------------------------------- >> Started by user anonymous >> Updating svn://vm-svn/GOES data >> processing/trunk/GOES/13,14,15/SXI/level-1 >> At revision 3401 >> no change for svn://vm-svn/GOES data >> processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build >> [workspace] $ python.exe >> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2011616575490005324.sh >> FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO >> [workspace] $ cmd.exe -xe >> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson902246697107326581.sh >> Microsoft Windows XP [Version 5.1.2600] >> (C) Copyright 1985-2001 Microsoft Corp. >> >> C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI >> Level-1 Products Generation\workspace>Recording test results >> Test reports were found but none of them are new. Did tests run? >> For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES >> 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml >> is 2 days 19 hr old >> >> Finished: FAILURE >> ------------------------------------------------------------------- >> >> As a side note, my Hudson "global" configuration page contains: >> >> cmd.exe >> >> in the "Shell executable" section and >> >> NOSEDIR >> C:\Python26\Scripts >> >> in the "Global properties" section. >> >> -- jv > Maybe something is missing on the machine hosting hudson, did you try to > execute nosetests.exe on that machine ? Hudson is running on my workstation (which also has python and nose installed). > I'm also confused with something, you do not provide nosetests with the > location of your package, assuming the current directory contains that > package (my guess). That is correct but see below ... > Instead of printing 'FOOO', try "import os ; print os.getcwd(); print > os.listdir(os.getcwd())" to know where you are exactly and if this dir > contains your python package. great suggestion ! This showed the current working directory to be one level above where I expected so that was definitely a problem so I changed my nose command, in the Hudson Job configuration Execute shell box, to be nosetests.exe --where=level-1 --with-xunit --verbose and saved the configuration change. This works as expected when run from a command shell in the Hudson current working directory for this Hudson job. Unfortunately, when "Hudson Build now" is performed, the Hudson Console output, for this job, is: ------------------------------------------------------------ Started by user anonymous Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 At revision 3403 no change for svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build [workspace] $ python.exe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson5273111667332806239.sh os.getcwd(): C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace os.listdir(os.getcwd()): ['level-1'] [workspace] $ cmd.exe -xe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson991194264891924641.sh Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace>Recording test results No test report files were found. Configuration error? Finished: FAILURE ------------------------------------------------------------ The second [workspace] section output (above) looks like cmd.exe is being executed with no parameters (i.e., without the "nosetests.exe --where=level-1 --with-xunit --verbose") parameter. Thanks for thinking about this; I realize how difficult it is to remotely troubleshoot a problem like this. -- jv > > JM > > From jim.vickroy at noaa.gov Mon May 10 11:39:14 2010 From: jim.vickroy at noaa.gov (j vickroy) Date: Mon, 10 May 2010 09:39:14 -0600 Subject: unable to get Hudson to run unit tests In-Reply-To: References: <4BE80A78.2030502@noaa.gov> Message-ID: <4BE828A2.2070106@noaa.gov> Jean-Michel Pichavant wrote: > j vickroy wrote: >> Stefan Behnel wrote: >>> j vickroy, 07.05.2010 20:44: >>>> I apologize if this is not the appropriate forum for a question about >>>> Hudson (http://hudson-ci.org/), but I did not know where else to ask >>>> and >>>> my web searches have not been fruitful. >>> >>> Certainly nice to read something about Hudson in this forum, which is >>> rare enough. It's seriously the greatest CI tool I've ever used, and >>> it works great with Python apps. >>> >>> >>>> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >>>> >>>> in the *Execute Python Script* subsection. >>> >>> The problem is that this isn't a "Python Script". I's a an >>> executable, native program. Use the "execute shell" build step instead. >>> >>> Stefan >>> >> Thanks for your reply, Stefan. >> >> When the above command >> >> "C:\Python26\Scripts\nosetests.exe --with-xunit --verbose" >> >> is moved to the "Execute shell" section of the job configuration page >> along with the following "tracer" command: >> >> #!python.exe >> print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' >> >> their is still no indication the unit tests are run. >> >> Here is the output from the Hudson Console Output page >> >> ------------------------------------------------------------------- >> Started by user anonymous >> Updating svn://vm-svn/GOES data >> processing/trunk/GOES/13,14,15/SXI/level-1 >> At revision 3401 >> no change for svn://vm-svn/GOES data >> processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build >> [workspace] $ python.exe >> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2011616575490005324.sh >> FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO >> [workspace] $ cmd.exe -xe >> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson902246697107326581.sh >> Microsoft Windows XP [Version 5.1.2600] >> (C) Copyright 1985-2001 Microsoft Corp. >> >> C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI >> Level-1 Products Generation\workspace>Recording test results >> Test reports were found but none of them are new. Did tests run? >> For example, C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES >> 13-15 SXI Level-1 Products Generation\workspace\level-1\nosetests.xml >> is 2 days 19 hr old >> >> Finished: FAILURE >> ------------------------------------------------------------------- >> >> As a side note, my Hudson "global" configuration page contains: >> >> cmd.exe >> >> in the "Shell executable" section and >> >> NOSEDIR >> C:\Python26\Scripts >> >> in the "Global properties" section. >> >> -- jv > Maybe something is missing on the machine hosting hudson, did you try to > execute nosetests.exe on that machine ? Hudson is running on my workstation (which also has python and nose installed). > I'm also confused with something, you do not provide nosetests with the > location of your package, assuming the current directory contains that > package (my guess). That is correct but see below ... > Instead of printing 'FOOO', try "import os ; print os.getcwd(); print > os.listdir(os.getcwd())" to know where you are exactly and if this dir > contains your python package. great suggestion ! This showed the current working directory to be one level above where I expected so that was definitely a problem so I changed my nose command, in the Hudson Job configuration Execute shell box, to be nosetests.exe --where=level-1 --with-xunit --verbose and saved the configuration change. This works as expected when run from a command shell in the Hudson current working directory for this Hudson job. Unfortunately, when "Hudson Build now" is performed, the Hudson Console output, for this job, is: ------------------------------------------------------------ Started by user anonymous Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 At revision 3403 no change for svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build [workspace] $ python.exe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson5273111667332806239.sh os.getcwd(): C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace os.listdir(os.getcwd()): ['level-1'] [workspace] $ cmd.exe -xe C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson991194264891924641.sh Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products Generation\workspace>Recording test results No test report files were found. Configuration error? Finished: FAILURE ------------------------------------------------------------ The second [workspace] section output (above) looks like cmd.exe is being executed with no parameters (i.e., without the "nosetests.exe --where=level-1 --with-xunit --verbose") parameter. Thanks for thinking about this; I realize how difficult it is to remotely troubleshoot a problem like this. -- jv > > JM > > From michele.simionato at gmail.com Mon May 10 11:53:48 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 10 May 2010 08:53:48 -0700 (PDT) Subject: Sphinx hosting References: <4BDFB9B4.1040400@v.loewis.de> <51f91095-6687-4434-9af1-7bc4faaa2ce7@e1g2000yqe.googlegroups.com> <4BDFC0AC.40609@v.loewis.de> <6c3f8496-8414-4bd5-a843-e190c84eb9f2@s29g2000yqd.googlegroups.com> <140c1cda-145c-42eb-b633-e7c1c93e2e92@k29g2000yqh.googlegroups.com> <1aeaac06-ff0e-4ec1-8f7d-fc71891228c0@b18g2000yqb.googlegroups.com> Message-ID: <7ec09351-f77a-4fa1-bb9e-13b0f01cf923@n15g2000yqf.googlegroups.com> On May 5, 8:00?am, James Mills wrote: > On Wed, May 5, 2010 at 3:35 PM, Michele Simionato > > wrote: > > I am sure it has, but I was talking about just putting in the > > repository an index.html file and have it published, the wayI hear ?it > > works in BitBucket and GitHub. > > I'm pretty sure Google Code Hosting doesn't support > rendering text/html mime-type files in the repository (like Trac can). At the end I discovered that if you put HTML files into a Googlecode repository and you click on "display raw file" it just works (TM). So my problem was already solved and I my worries were unjustified. I have just committed my talk at the Italian PyCon and all the stylesheets are recognized just fine: http://micheles.googlecode.com/hg/pypers/pycon10/talk.html From aahz at pythoncraft.com Mon May 10 12:48:21 2010 From: aahz at pythoncraft.com (Aahz) Date: 10 May 2010 09:48:21 -0700 Subject: Extract all words that begin with x References: Message-ID: In article , James Mills wrote: >On Mon, May 10, 2010 at 6:50 PM, Xavier Ho wrote: >> Have I missed something, or wouldn't this work just as well: >> >>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas'] >>>>> [word for word in list_of_strings if word[0] == 'a'] >> ['awes', 'asdgas'] > >I would do this for completeness (just in case): > >>>>> [word for word in list_of_strings if word and word[0] == 'a'] > >Just guards against empty strings which may or may not be in the list. No need to do that with startswith(): >>> ''.startswith('x') False You would only need to use your code if you suspected that some elements might be None. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From paul at boddie.org.uk Mon May 10 13:37:24 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 10 May 2010 10:37:24 -0700 (PDT) Subject: Picking a license References: <30aff350- <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> Message-ID: <9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com> On 10 Mai, 17:06, a... at pythoncraft.com (Aahz) wrote: > In article <074b412a-c2f4-4090-a52c-4d69edb29... at d39g2000yqa.googlegroups.com>, > Paul Boddie ? wrote: > >Actually, the copyleft licences don't "force" anyone to "give back > >changes": they oblige people to pass on changes. > > IMO, that's a distinction without a difference, particularly if you > define "give back" as referring to the community rather than the original > project. There is a difference: I know of at least one vendor of GPL-licensed solutions who received repeated requests that they make their sources available to all-comers, even though the only obligation is to those receiving the software in the first place. Yes, the code can then become public - if Red Hat decided to only release sources to their customers, and those customers shared the sources publicly, then CentOS would still be around as a Red Hat "clone" - but there are situations where recipients of GPL-licensed code may decide that it is in their best interests not to just upload it to the public Internet. > ?With the FSF itself using "pressure" in the FAQ entry you > linked to, I have no clue why you and Ben Finney object to my use of > "force". Because no-one is being forced to do anything. Claiming that "force" is involved is like hearing a schoolboy saying, "I really wanted that chocolate, but why is that man forcing me to pay for it?" Well, you only have to pay for it if you decide you want to take it - that's the only reasonable response. Paul From no.email at nospam.invalid Mon May 10 14:00:57 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 10 May 2010 11:00:57 -0700 Subject: Is Python a functional programming language? References: Message-ID: <7xvdavd4bq.fsf@ruckus.brouhaha.com> Samuel Williams writes: > Is Python a functional programming language? It supports some aspects of functional programming but I wouldn't go as far as to call it an FPL. > Is this a paradigm that is well supported by both the language syntax > and the general programming APIs? I'd say "somewhat supported" rather than "well supported". > I heard that lambdas were limited to a single expression, and that > other functional features were slated for removal in Python 3... is > this the case or have I been misinformed? I think, some features were slated for removal, but after some discussion they were moved to libraries instead of eliminated completely. > Finally, even if Python supports functional features, is this a model > that is used often in client/application code? That's more a question of the programmers than the programs. If you're comfortable programming in functional style, that will tend to show up in your python code. There are some contortions you have to do though. If your goal is to engage in functional programming, you're better off using a language designed for that purpose. Python is a pragmatic language from an imperative tradition, that has some functional features tacked on. Python is pleasant for imperative programming while letting you make some use of functional style. From aahz at pythoncraft.com Mon May 10 14:18:04 2010 From: aahz at pythoncraft.com (Aahz) Date: 10 May 2010 11:18:04 -0700 Subject: Is Python a functional programming language? References: <7xvdavd4bq.fsf@ruckus.brouhaha.com> Message-ID: In article <7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >If your goal is to engage in functional programming, you're better off >using a language designed for that purpose. Python is a pragmatic >language from an imperative tradition, that has some functional features >tacked on. While your first sentence is spot-on, saying that functional features are "tacked on" understates the case. Consider how frequently people reach for list comps and gen exps. Function dispatch through dicts is the standard replacement for a switch statement. Lambda callbacks are common. Etc, etc, etc -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From aclark at aclark.net Mon May 10 14:29:49 2010 From: aclark at aclark.net (Alex Clark) Date: Mon, 10 May 2010 18:29:49 +0000 (UTC) Subject: Turbogears 2 training this weekend in Washington, DC USA Message-ID: Hi all, Sorry for the short notice. We (the Zope/Python Users Group of DC) are having a TurboGears 2 training class this weekend in Washington, DC USA taught by core developer Chris Perkins. Please consider attending! And, I would appreciate you spreading the word to anyone you think may be interested as well. Details are here: http://www.meetup.com/python-meetup-dc/messages/10123013/ And here is a taste: --- The DC Python Meetup is pleased to present Turbogears 2 training, delivered by Turbogears core developer Christopher Perkins. You can register now at http://tg2-class.eventbrite.com/ Turbogears is a modern python web framework with a powerful ORM (the one and only SQLAlchemy), designer friendly templates, and a widget system that simplifies Ajax development. If you're a web developer interested in expanding your toolkit or a python developer who wants to dabble in the web space, this training is an excellent opportunity to learn an agile and mature web framework. The training itself will be wonderfully practical, taking you from basic setup to a real application over the course of a day. You're invited to bring your own data, so that you can work with Chris to start migrating that legacy PHP app you have sitting around to Python beauty. This hands-on training aims to bring students up to speed with TurboGears 2, its administration interface, and touch common deployment scenarios. Students will also get to customize auto generated forms and tables. --- I hope to see you there! Alex, http://zpugdc.org -- Alex Clark ? http://aclark.net Author of Plone 3.3 Site Administration ? http://aclark.net/plone-site-admin From pmaupin at gmail.com Mon May 10 14:36:27 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Mon, 10 May 2010 11:36:27 -0700 (PDT) Subject: Picking a license References: <30aff350- <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> <9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com> Message-ID: <7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> On May 10, 12:37?pm, Paul Boddie wrote: > On 10 Mai, 17:06, a... at pythoncraft.com (Aahz) wrote: > > > In article <074b412a-c2f4-4090-a52c-4d69edb29... at d39g2000yqa.googlegroups.com>, > > Paul Boddie ? wrote: > > >Actually, the copyleft licences don't "force" anyone to "give back > > >changes": they oblige people to pass on changes. > > > IMO, that's a distinction without a difference, particularly if you > > define "give back" as referring to the community rather than the original > > project. > > There is a difference: I know of at least one vendor of GPL-licensed > solutions who received repeated requests that they make their sources > available to all-comers, even though the only obligation is to those > receiving the software in the first place. Yes, the code can then > become public - if Red Hat decided to only release sources to their > customers, and those customers shared the sources publicly, then > CentOS would still be around as a Red Hat "clone" - but there are > situations where recipients of GPL-licensed code may decide that it is > in their best interests not to just upload it to the public Internet. > > > ?With the FSF itself using "pressure" in the FAQ entry you > > linked to, I have no clue why you and Ben Finney object to my use of > > "force". > > Because no-one is being forced to do anything. Claiming that "force" > is involved is like hearing a schoolboy saying, "I really wanted that > chocolate, but why is that man forcing me to pay for it?" Well, you > only have to pay for it if you decide you want to take it - that's the > only reasonable response. I've addressed this before. Aahz used a word in an accurate, but to you, inflammatory, sense, but it's still accurate -- the man *would* force you to pay for the chocolate if you took it. You're making it sound like whining, but Aahz was simply trying to state a fact. The fact is, I know the man would force me to pay for the chocolate, so in some cases that enters into the equation and keeps me from wanting the chocolate. This isn't whining; just a common-sense description of reality. Personally, I think this use of the word "force" is much less inflammatory than the deliberate act of co-opting the word "freedom" to mean "if you think you can take this software and do anything you want with it, you're going to find out differently when we sue you." Regards, Pat From nobody at nowhere.com Mon May 10 15:45:51 2010 From: nobody at nowhere.com (Nobody) Date: Mon, 10 May 2010 20:45:51 +0100 Subject: Is Python a functional programming language? References: Message-ID: On Tue, 11 May 2010 00:24:22 +1200, Samuel Williams wrote: > Is Python a functional programming language? Not in any meaningful sense of the term. > Is this a paradigm that is well supported by both the language syntax and > the general programming APIs? No. > I heard that lambdas were limited to a single expression, Yes. In a functional language that wouldn't be a problem, as there's no limit to the complexity of an expression. Python's expressions are far more limited, which restricts what can be done with a lambda. > and that other > functional features were slated for removal in Python 3... is this the > case or have I been misinformed? I don't know about this. > Finally, even if Python supports functional features, is this a model that > is used often in client/application code? Not really. List comprehensions are probably the most common example of functional idioms, but again they're limited by Python's rather limited concept of an expression. From anthony.cole at gmail.com Mon May 10 15:55:10 2010 From: anthony.cole at gmail.com (Anthony Cole) Date: Mon, 10 May 2010 20:55:10 +0100 Subject: Hex String Message-ID: How can I concatenate 2 hex strings (e.g. '\x16' and '\xb9') then convert the answer to an integer? When I try i always end up with the ASCII equivalent! Thanks, Anthony From matt at tplus1.com Mon May 10 16:13:44 2010 From: matt at tplus1.com (Matthew Wilson) Date: Mon, 10 May 2010 20:13:44 +0000 (UTC) Subject: How to measure speed improvements across revisions over time? Message-ID: I know how to use timeit and/or profile to measure the current run-time cost of some code. I want to record the time used by some original implementation, then after I rewrite it, I want to find out if I made stuff faster or slower, and by how much. Other than me writing down numbers on a piece of paper on my desk, does some tool that does this already exist? If it doesn't exist, how should I build it? Matt From clp2 at rebertia.com Mon May 10 16:15:05 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 10 May 2010 13:15:05 -0700 Subject: Hex String In-Reply-To: References: Message-ID: On Mon, May 10, 2010 at 12:55 PM, Anthony Cole wrote: > How can I concatenate 2 hex strings (e.g. '\x16' and '\xb9') then convert > the answer to an integer? > > When I try i always end up with the ASCII equivalent! I think you want the `struct` module: struct ? Interpret strings as packed binary data http://docs.python.org/library/struct.html Cheers, Chris -- http://blog.rebertia.com From python at mrabarnett.plus.com Mon May 10 16:15:20 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 10 May 2010 21:15:20 +0100 Subject: Hex String In-Reply-To: References: Message-ID: <4BE86958.6080407@mrabarnett.plus.com> Anthony Cole wrote: > How can I concatenate 2 hex strings (e.g. '\x16' and '\xb9') then convert > the answer to an integer? > > When I try i always end up with the ASCII equivalent! > Those are just bytestrings (assuming you're using Python 2.x), ie strings using 1 byte per character. You can convert a bytestring to an integer using the functions in the 'struct' module. From martin at v.loewis.de Mon May 10 16:25:37 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 10 May 2010 22:25:37 +0200 Subject: Upgrade Python 2.6.4 to 2.6.5 In-Reply-To: References: Message-ID: <4BE86BC1.8040102@v.loewis.de> Werner F. Bruhin wrote: > Just upgraded on my Windows 7 machine my copy of 2.6.4 to 2.6.5. > > However doing sys.version still shows 2.6.4 even so python.exe is dated > 19. March 2010 with a size of 26.624 bytes. > > Is this a known issue? Or did I do something wrong? Look at the copy of python26.dll. This should be the new one; perhaps you have another copy in the system32 folder? Did the upgrade inform you that it was an upgrade, or did it warn you that you would overwrite the previous installation? Regards, Martin From martin at v.loewis.de Mon May 10 16:25:37 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 10 May 2010 22:25:37 +0200 Subject: Upgrade Python 2.6.4 to 2.6.5 In-Reply-To: References: Message-ID: <4BE86BC1.8040102@v.loewis.de> Werner F. Bruhin wrote: > Just upgraded on my Windows 7 machine my copy of 2.6.4 to 2.6.5. > > However doing sys.version still shows 2.6.4 even so python.exe is dated > 19. March 2010 with a size of 26.624 bytes. > > Is this a known issue? Or did I do something wrong? Look at the copy of python26.dll. This should be the new one; perhaps you have another copy in the system32 folder? Did the upgrade inform you that it was an upgrade, or did it warn you that you would overwrite the previous installation? Regards, Martin From phlip2005 at gmail.com Mon May 10 16:29:04 2010 From: phlip2005 at gmail.com (Phlip) Date: Mon, 10 May 2010 13:29:04 -0700 (PDT) Subject: [Epydoc-devel] How to? epydoc --top=README Message-ID: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> Pythonistas: I have a question to epydoc-devel, but it might be languishing: http://sourceforge.net/mailarchive/forum.php?thread_name=l2n860c114f1005061707k1ccf68cdz277a3d875b99fe04%40mail.gmail.com&forum_name=epydoc-devel How do you populate the index.html output with your (insanely clever) contents of your README file? When I try the obvious notations, such as --top=README or -- top=README.html, I get: Warning: Identifier 'README' looks suspicious; using it anyway. Warning: Could not find top page 'README'; using module-tree.html instead And, yes, the README is included in the input list, and yes I get a script-README-module.html ----8<------------------------------------------ The question for the rest of Python-Land: Should I be using a better documentation extractor? (pydoc is too mundane so far.) Or should I be using a better forum for epydoc users questions? -- yes-I-know-topicality-ly-yrs Phlip http://c2.com/cgi/wiki?ZeekLand From clp2 at rebertia.com Mon May 10 16:39:25 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 10 May 2010 13:39:25 -0700 Subject: [Epydoc-devel] How to? epydoc --top=README In-Reply-To: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> Message-ID: On Mon, May 10, 2010 at 1:29 PM, Phlip wrote: > Pythonistas: > The question for the rest of Python-Land: Should I be using a better > documentation extractor? (pydoc is too mundane so far.) Sphinx is in vogue right now: http://sphinx.pocoo.org/ It's used for the official docs and its results are quite pretty. Cheers, Chris -- http://blog.rebertia.com From phlip2005 at gmail.com Mon May 10 16:51:17 2010 From: phlip2005 at gmail.com (Phlip) Date: Mon, 10 May 2010 13:51:17 -0700 (PDT) Subject: How to? epydoc --top=README References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> Message-ID: <4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com> On May 10, 1:39?pm, Chris Rebert wrote: > Sphinx is in vogue right now:http://sphinx.pocoo.org/ > > It's used for the official docs and its results are quite pretty. The manager said to hold off on Sphinx until the next phase - then ran off to get married or something. But yet I persevere... From amphioxus at yahoo.com Mon May 10 17:01:10 2010 From: amphioxus at yahoo.com (Armin) Date: Mon, 10 May 2010 14:01:10 -0700 Subject: Problem displaying jpgs in Tkinter via PIL Message-ID: <2010051014011093749-amphioxus@yahoocom> Hi everyone, I'm new to Python and have been playing around with it using the Enthought Python distribution for Mac OS X 10.6.3 (EPD academic license, version 6.1 with python 2.6.4). It's been great learning the basics, but I've started running into problems when I'm trying to use the PIL library with Tkinter. All I'm trying to do is display a JPG as a Tkinter label: # code below: from Tkinter import * import Image, ImageTk def main(): filename = "images/testimg.jpg" imgPIL = Image.open(filename) root = Tk() imgTK = ImageTk.PhotoImage(imgPIL) label = Label(root, image=imgTK) label.pack() root.mainloop() main() # end of code It all works fine when I'm just using GIF images through Tkinter's photoimage object, but as soon as I'm trying to convert an image through ImageTk, I get the following error: ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/PIL/_imagingtk.so, 2): Library not loaded: /System at rpath/Tcl Referenced from: /Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/PIL/_imagingtk.so Reason: image not found I have no idea what that means, but I've always assumed the EPD includes all the stuff that's needed to make Tkinter work with PIL. Any advice would be greatly appreciated. Thanks! From phlip2005 at gmail.com Mon May 10 17:11:33 2010 From: phlip2005 at gmail.com (Phlip) Date: Mon, 10 May 2010 14:11:33 -0700 (PDT) Subject: lame sphinx questions [Was: lame epydoc questions] References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> <4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com> Message-ID: <289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com> On May 10, 1:51?pm, Phlip wrote: > On May 10, 1:39?pm, Chris Rebert wrote: > > > Sphinx is in vogue right now:http://sphinx.pocoo.org/ Okay, we have ten thousand classes to document. How to add them all to index.rst? From cjw at ncf.ca Mon May 10 17:17:24 2010 From: cjw at ncf.ca (cjw) Date: Mon, 10 May 2010 17:17:24 -0400 Subject: unittest not being run In-Reply-To: References: <4BE7FE59.408@gmail.com> <1273498724.2997.3.camel@cliff-laptop> Message-ID: On 10-May-10 10:21 AM, John Maclean wrote: > On 10/05/2010 14:38, J. Cliff Dyer wrote: >> My guess is you mixed tabs and spaces. One tab is always treated by the >> python interpreter as being equal to eight spaces, which is two >> indentation levels in your code. >> >> Though if it were exactly as you show it, you'd be getting a syntax >> error, because even there, it looks like the indentation of your `def >> test_T1(self):` line is off by one column, relative to pass, and by >> three columns relative to the other methods. >> >> Cheers, >> Cliff > > 'twas a spaces/indent issue. thanks! > > > PyScripter and PythonWin permit the user to choose the equivalence of tabs and spaces. I like two spaces = on tab, it's a matter of taste. I feel that eight spaces is too much. Colin W. From exarkun at twistedmatrix.com Mon May 10 19:04:36 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 10 May 2010 23:04:36 -0000 Subject: How to measure speed improvements across revisions over time? In-Reply-To: References: Message-ID: <20100510230436.1843.386684761.divmod.xquotient.13@localhost.localdomain> On 08:13 pm, matt at tplus1.com wrote: >I know how to use timeit and/or profile to measure the current run-time >cost of some code. > >I want to record the time used by some original implementation, then >after I rewrite it, I want to find out if I made stuff faster or >slower, >and by how much. > >Other than me writing down numbers on a piece of paper on my desk, does >some tool that does this already exist? > >If it doesn't exist, how should I build it? http://github.com/tobami/codespeed sounds like the kind of thing you're looking for. You can see an example of what it does at http://speed.pypy.org/ Jean-Paul > >Matt > >-- >http://mail.python.org/mailman/listinfo/python-list From aonlazio at gmail.com Mon May 10 19:25:35 2010 From: aonlazio at gmail.com (AON LAZIO) Date: Mon, 10 May 2010 19:25:35 -0400 Subject: Difference between 'is not' and '!=' ? Message-ID: As subject says, what is the differences of 'is not' and '!='. Confusing.. -- Passion is my style -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon May 10 19:31:54 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 10 May 2010 16:31:54 -0700 Subject: Difference between 'is not' and '!=' ? In-Reply-To: References: Message-ID: On Mon, May 10, 2010 at 4:25 PM, AON LAZIO wrote: > As subject says, what is the differences of 'is not' and '!='. Confusing.. != checks value inequality, `is not` checks object identity / "pointer" inequality Unless you're doing `foo is not None`, you almost always want !=. By way of demonstration (using the non-negated versions to be less confusing): >>> x = [1, 2] >>> y = [1, 2] >>> x == y True >>> x is y False >>> z = x >>> x is z True >>> z is y False >>> x.append(3) >>> x [1, 2, 3] >>> y [1, 2] >>> z [1, 2, 3] >>> x is z True Cheers, Chris -- http://blog.rebertia.com From lists at cheimes.de Mon May 10 19:32:45 2010 From: lists at cheimes.de (Christian Heimes) Date: Tue, 11 May 2010 01:32:45 +0200 Subject: Difference between 'is not' and '!=' ? In-Reply-To: References: Message-ID: AON LAZIO wrote: > As subject says, what is the differences of 'is not' and '!='. Confusing.. "is not" checks if two objects are not identical. "!=" checks if two objects are not equal. Example: Two apples may be equal in size, form and color but they can never be identical because they are made up from different atoms. Christian From goon12 at gmail.com Mon May 10 19:36:25 2010 From: goon12 at gmail.com (Joe Riopel) Date: Mon, 10 May 2010 19:36:25 -0400 Subject: unittest not being run In-Reply-To: References: <4BE7FE59.408@gmail.com> <1273498724.2997.3.camel@cliff-laptop> Message-ID: On Mon, May 10, 2010 at 5:17 PM, cjw wrote: > PyScripter and PythonWin permit the user to choose the equivalence of tabs > and spaces. ?I like two spaces = on tab, it's a matter of taste. ?I feel > that eight spaces is too much. While it is a matter of taste, PEP 8 recommends 4 spaces per indentation level. http://www.python.org/dev/peps/pep-0008/ From luismgz at gmail.com Mon May 10 21:04:29 2010 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 10 May 2010 18:04:29 -0700 (PDT) Subject: Is Python a functional programming language? References: Message-ID: <06f5541f-ccbe-427a-83ad-176fcb947d29@e35g2000yqm.googlegroups.com> On 10 mayo, 09:24, Samuel Williams wrote: > Dear Friends, > > Is Python a functional programming language? > > Is this a paradigm that is well supported by both the language syntax and the general programming APIs? > > I heard that lambdas were limited to a single expression, and that other functional features were slated for removal in Python 3... is this the case or have I been misinformed? > > Finally, even if Python supports functional features, is this a model that is used often in client/application code? > > Kind regards, > Samuel I'm no expert of functional programming at all, but I read many times (from famous programmers) that Python is very lisp-like, but with a more conventional syntax. For example, Paul Graham and others have some interesting views on this subject: http://www.prescod.net/python/IsPythonLisp.html That doesn't mean python can compete with other purely functional languages, but it's probably as functional as it can be for a more conventional, multiparadigm language. Luis From ben+python at benfinney.id.au Mon May 10 21:15:37 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 11 May 2010 11:15:37 +1000 Subject: Picking a license References: <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> Message-ID: <87vdavck7a.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > Paul Boddie wrote: > >Actually, the copyleft licences don't "force" anyone to "give back > >changes": they oblige people to pass on changes. > > IMO, that's a distinction without a difference, particularly if you > define "give back" as referring to the community rather than the > original project. With the FSF itself using "pressure" in the FAQ > entry you linked to, I have no clue why you and Ben Finney object to > my use of "force". Precisely because there *is* force involved: copyright law is enforced, ultimately, by police with threats to put you in a box forcibly. But that force, it must be recognised, comes from the force of law. The GPL, and all free software licenses, do *not* force anyone to do anything; exactly the opposite is the case. Free software licenses grant specific exceptions to the enforcement of copyright law. They grant freedom to do things that would otherwise be prevented by force or the threat of force. This is obvious when you consider what would be the case in the absence of any free software license: everything that was prohibited is still prohibited in the absence of the license, and indeed some more things are now prohibited as well. Conversely, in the absence of any copyright law (not that I advocate that situation), copyright licenses would have no force in or behind them. So I object to muddying the issue by misrepresenting the source of that force. Whatever force there is in copyright comes from law, not any free software license. -- \ ?Let others praise ancient times; I am glad I was born in | `\ these.? ?Ovid (43 BCE?18 CE) | _o__) | Ben Finney From steven at REMOVE.THIS.cybersource.com.au Mon May 10 22:06:01 2010 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 May 2010 02:06:01 GMT Subject: How to measure speed improvements across revisions over time? References: Message-ID: On Mon, 10 May 2010 20:13:44 +0000, Matthew Wilson wrote: > I know how to use timeit and/or profile to measure the current run-time > cost of some code. > > I want to record the time used by some original implementation, then > after I rewrite it, I want to find out if I made stuff faster or slower, > and by how much. > > Other than me writing down numbers on a piece of paper on my desk, does > some tool that does this already exist? > > If it doesn't exist, how should I build it? from timeit import Timer before = Timer(before_code, setup) after = Timer(after_code, setup) improvement = min(before.repeat()) - min(after.repeat()) -- Steven From kushal.kumaran+python at gmail.com Mon May 10 22:06:53 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 11 May 2010 07:36:53 +0530 Subject: HTTP Post Request In-Reply-To: <06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com> References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> <06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com> Message-ID: On Mon, May 10, 2010 at 8:26 PM, kaklis at gmail.com wrote: > On May 10, 10:22?am, Kushal Kumaran > wrote: >> On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com wrote: >> > Hi to all, i want to ask you a question, concerning the best way to do >> > the following as a POST request: >> > There is server-servlet that accepts xml commands >> > It had the following HTTP request headers: >> >> > ? ? ? ? ? ?Host: somehost.com >> > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient >> > ? ? ? ? ? ?Content-Type: text/xml >> > ? ? ? ? ? ?Content-Length: 415 >> >> > and the following request body (reformatted here for clarity): >> >> > ? ? ? ? ? ? >> > ? ? ? ? ? ? >> > ? ? ? ? ? ? ?search >> > ? ? ? ? ? ? >> > How can i send the above to the Listener Servlet? >> > Thanks in advance >> >> Use the xmlrpclib module. >> > > OK, sending headers with xmlrpclib, > but how do i send the XML message? > Your XML message is an XML RPC message. You will use xmlrpclib like this: server_proxy = xmlrpclib.ServerProxy(('somehost.com', 80)) result = server_proxy.search() The call to server_proxy.search will result in an actual XML RPC message being sent. Read up on the xmlrpclib documentation here: http://docs.python.org/library/xmlrpclib.html, and the XMLRPC spec here: http://www.xmlrpc.com/spec -- regards, kushal From space.ship.traveller at gmail.com Mon May 10 23:17:49 2010 From: space.ship.traveller at gmail.com (Samuel Williams) Date: Tue, 11 May 2010 15:17:49 +1200 Subject: Is Python a functional programming language? In-Reply-To: References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> Message-ID: Thanks to everyone for their great feedback, it is highly appreciated. Kind regards, Samuel From tjreedy at udel.edu Mon May 10 23:23:01 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 May 2010 23:23:01 -0400 Subject: Extract all words that begin with x In-Reply-To: References: Message-ID: On 5/10/2010 5:35 AM, James Mills wrote: > On Mon, May 10, 2010 at 6:50 PM, Xavier Ho wrote: >> Have I missed something, or wouldn't this work just as well: >> >>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas'] >>>>> [word for word in list_of_strings if word[0] == 'a'] >> ['awes', 'asdgas'] > > I would do this for completeness (just in case): > >>>>> [word for word in list_of_strings if word and word[0] == 'a'] > > Just guards against empty strings which may or may not be in the list. ... word[0:1] does the same thing. All Python programmers should learn to use slicing to extract a char from a string that might be empty. The method call of .startswith() will be slower, I am sure. From tycho at tycho.ws Tue May 11 00:17:30 2010 From: tycho at tycho.ws (Tycho Andersen) Date: Mon, 10 May 2010 23:17:30 -0500 Subject: Extract all words that begin with x In-Reply-To: References: Message-ID: On Mon, May 10, 2010 at 10:23 PM, Terry Reedy wrote: > On 5/10/2010 5:35 AM, James Mills wrote: >> >> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho ?wrote: >>> >>> Have I missed something, or wouldn't this work just as well: >>> >>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas'] >>>>>> [word for word in list_of_strings if word[0] == 'a'] >>> >>> ['awes', 'asdgas'] >> >> I would do this for completeness (just in case): >> >>>>>> [word for word in list_of_strings if word and word[0] == 'a'] >> >> Just guards against empty strings which may or may not be in the list. > > ?... word[0:1] does the same thing. All Python programmers should learn to > use slicing to extract a ?char from a string that might be empty. > The method call of .startswith() will be slower, I am sure. Why? Isn't slicing just sugar for a method call? \t From ldo at geek-central.gen.new_zealand Tue May 11 01:43:59 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 May 2010 17:43:59 +1200 Subject: virtualenvwrapper for Windows (Powershell) References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com> Message-ID: In message <22cf35af-44d1-43fe-8b90-07f2c6545f63 at i10g2000yqh.googlegroups.com>, Guillermo wrote: > If you've ever missed it on Windows and you can use Powershell ... I thought the whole point of Windows was to get away from this command-line stuff. Not such a good idea after all? From ldo at geek-central.gen.new_zealand Tue May 11 01:46:56 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 May 2010 17:46:56 +1200 Subject: shortcut for large amount of global var declarations? References: Message-ID: In message , Alex Hall wrote: > ... I have about fifteen vars in a function which have to be > global. Why not make them class variables, e.g. class my_namespace : var1 = ... var2 = ... #end my_namespace def my_function(...) : ... can directly read/assign my_namespace.var1 etc here ... #end my_function Also has the benefit of minimizing pollution of the global namespace. From ldo at geek-central.gen.new_zealand Tue May 11 01:48:41 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 May 2010 17:48:41 +1200 Subject: fast regex References: Message-ID: In message , james_027 wrote: > I was working with regex on a very large text, really large but I have > time constrained. ?Fast regex? is a contradiction in terms. You use regexes when you want ease of definition and application, not speed. For speed, consider hand-coding your own state machine. Preferably in a compiled language like C. From stefan_ml at behnel.de Tue May 11 02:35:52 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 11 May 2010 08:35:52 +0200 Subject: unable to get Hudson to run unit tests In-Reply-To: <4BE828A2.2070106@noaa.gov> References: <4BE80A78.2030502@noaa.gov> <4BE828A2.2070106@noaa.gov> Message-ID: j vickroy, 10.05.2010 17:39: > Unfortunately, when "Hudson Build now" is performed, the Hudson Console > output, for this job, is: > > ------------------------------------------------------------ > Started by user anonymous > Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1 > At revision 3403 > no change for svn://vm-svn/GOES data > processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build > [workspace] $ python.exe > C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson5273111667332806239.sh > os.getcwd(): C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES > 13-15 SXI Level-1 Products Generation\workspace > os.listdir(os.getcwd()): ['level-1'] > [workspace] $ cmd.exe -xe > C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson991194264891924641.sh > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI > Level-1 Products Generation\workspace>Recording test results > No test report files were found. Configuration error? > Finished: FAILURE > ------------------------------------------------------------ > > The second [workspace] section output (above) looks like cmd.exe is > being executed with no parameters (i.e., without the > "nosetests.exe --where=level-1 --with-xunit --verbose") parameter. No, what Hudson actually does, is, it writes your command(s) into a text file and runs it with the system's shell interpreter (which, unless otherwise configured, is "cmd.exe" on Windows). This assures the highest possible compatibility with the executed script. You can even use the shebang in Hudson's scripts that way, so that you can execute scripts in basically any scripting language. The likely reason why it doesn't find your test results is that you didn't tell it where to look. Put a wildcard path into the unit test config box that finds the XML files that nosetest writes. It's also best to tell nosetest where to put them explicitly using a command line option. Stefan From martin at v.loewis.de Tue May 11 02:44:28 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 11 May 2010 08:44:28 +0200 Subject: How to measure speed improvements across revisions over time? In-Reply-To: References: Message-ID: <4BE8FCCC.1060103@v.loewis.de> Matthew Wilson wrote: > I know how to use timeit and/or profile to measure the current run-time > cost of some code. > > I want to record the time used by some original implementation, then > after I rewrite it, I want to find out if I made stuff faster or slower, > and by how much. > > Other than me writing down numbers on a piece of paper on my desk, does > some tool that does this already exist? I recommend to use rrd. This can record time series, and then generate diagrams. Regards, Martin From isso.moh at gmail.com Tue May 11 02:52:43 2010 From: isso.moh at gmail.com (mohamed issolah) Date: Tue, 11 May 2010 08:52:43 +0200 Subject: win32com In-Reply-To: References: Message-ID: hey, I need help . 2010/5/9 mohamed issolah > hey, > I wich to have an example please > > need help > > > > 2010/5/9 Chris Rebert > > On Sun, May 9, 2010 at 1:15 AM, mohamed issolah >> wrote: >> > hey, >> > >> > there is an alternative of win32com in linux? >> > >> > what i want to say : can communicate with application (ex: evolution or >> > another) throught python like in windows with win32com >> >> The closest equivalent would probably be python-dbus. See the "Python" >> section of http://www.freedesktop.org/wiki/Software/DBusBindings >> >> Information on D-Bus generally: http://en.wikipedia.org/wiki/D-Bus >> >> Cheers, >> Chris >> -- >> http://blog.rebertia.com >> > > > > -- > issolah mohamed > -- issolah mohamed -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at nospam.invalid Tue May 11 03:08:13 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 11 May 2010 00:08:13 -0700 Subject: fast regex References: Message-ID: <7xaas6gbky.fsf@ruckus.brouhaha.com> Lawrence D'Oliveiro writes: > ?Fast regex? is a contradiction in terms. You use regexes when you want ease > of definition and application, not speed. > > For speed, consider hand-coding your own state machine. Preferably in a > compiled language like C. But, nothing stops a regexp library from doing that, and some of them do. From eckhardt at satorlaser.com Tue May 11 03:09:42 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 11 May 2010 09:09:42 +0200 Subject: Iterating a sequence two items at a time Message-ID: Hi! I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4), (5,6). I can of course roll my own, but I was wondering if there was already some existing library function that already does this. def as_pairs(seq): i = iter(seq) yield (i.next(), i.next()) Question to this code: Is the order of the "i.next()" calls guaranteed to be from left to right? Or could I end up with pairs being switched? Thanks! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From werner.bruhin at free.fr Tue May 11 03:10:24 2010 From: werner.bruhin at free.fr (Werner F. Bruhin) Date: Tue, 11 May 2010 09:10:24 +0200 Subject: Upgrade Python 2.6.4 to 2.6.5 In-Reply-To: <4BE86BC1.8040102@v.loewis.de> References: <4BE86BC1.8040102@v.loewis.de> Message-ID: <4BE902E0.8060108@free.fr> Martin, Thanks for the quick reply. On 10/05/2010 22:25, Martin v. Loewis wrote: > Werner F. Bruhin wrote: > >> Just upgraded on my Windows 7 machine my copy of 2.6.4 to 2.6.5. >> >> However doing sys.version still shows 2.6.4 even so python.exe is dated >> 19. March 2010 with a size of 26.624 bytes. >> >> Is this a known issue? Or did I do something wrong? >> > Look at the copy of python26.dll. This should be the new one; perhaps > you have another copy in the system32 folder? > The one in system32 is 2.6.5 and the one in c:\python26 is 2.6.4. When will it install into system32? > Did the upgrade inform you that it was an upgrade, or did it warn you > that you would overwrite the previous installation? > It warned me that there is a previous installation. Best regards Werner From no.email at nospam.invalid Tue May 11 03:17:30 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 11 May 2010 00:17:30 -0700 Subject: Is Python a functional programming language? References: <06f5541f-ccbe-427a-83ad-176fcb947d29@e35g2000yqm.googlegroups.com> Message-ID: <7xzl06ewl1.fsf@ruckus.brouhaha.com> Luis M. Gonz?lez writes: > That doesn't mean python can compete with other purely functional > languages, but it's probably as functional as it can be for a more > conventional, multiparadigm language. Ben Lippmeier made the interesting claim that one of the defining characteristics of functional programming is type systems based on the Curry-Howard correspondence. By that standard I think even Scheme (perhaps the grandaddy of functional languages) wouldn't qualify. I do think of Scheme as a functional language, but of Python and Lisp as imperative languages with functional aspects. I like learnyouahaskell.com if you want to get some exposure to Haskell, probably the archetypal functional language these days. I've been fooling with it on and off for the past couple years. I'm still not convinced that it's that good a vehicle for practical general purpose software development, but there are some specific areas where it works out just beautifully. And in terms of the challenges it presents and the amount I've learned from it, it's one of the most interesting things I've done as a programmer in as long as I can remember. It really is mind altering. From clp2 at rebertia.com Tue May 11 03:33:59 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 11 May 2010 00:33:59 -0700 Subject: Iterating a sequence two items at a time In-Reply-To: References: Message-ID: On Tue, May 11, 2010 at 12:09 AM, Ulrich Eckhardt wrote: > Hi! > > I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4), > (5,6). I can of course roll my own, but I was wondering if there was > already some existing library function that already does this. When a problem involves iteration, always check the `itertools` module in the std lib. >From the module docs's recipe section (http://docs.python.org/library/itertools.html#recipes): import itertools def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itertools.izip_longest(fillvalue=fillvalue, *args) >>> # Let's try it out. >>> list(grouper(2, [1,2,3,4,5,6])) [(1, 2), (3, 4), (5, 6)] >>> # Success! > def as_pairs(seq): > ? ?i = iter(seq) > ? ?yield (i.next(), i.next()) > > Question to this code: Is the order of the "i.next()" calls guaranteed to be > from left to right? Or could I end up with pairs being switched? Pretty sure left-to-right is guaranteed; see http://bugs.python.org/issue448679 Also, if you're using Python 2.6+, the line should be: yield (next(i), next(i)) See http://docs.python.org/library/functions.html#next Cheers, Chris -- http://blog.rebertia.com From kaklis at gmail.com Tue May 11 03:56:33 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 11 May 2010 00:56:33 -0700 (PDT) Subject: HTTP Post Request References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> <06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com> Message-ID: <95e73ff4-abe5-4874-8652-647818ed224a@k29g2000yqh.googlegroups.com> On May 11, 5:06?am, Kushal Kumaran wrote: > On Mon, May 10, 2010 at 8:26 PM, kak... at gmail.com wrote: > > On May 10, 10:22?am, Kushal Kumaran > > wrote: > >> On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com wrote: > >> > Hi to all, i want to ask you a question, concerning the best way to do > >> > the following as a POST request: > >> > There is server-servlet that accepts xml commands > >> > It had the following HTTP request headers: > > >> > ? ? ? ? ? ?Host: somehost.com > >> > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient > >> > ? ? ? ? ? ?Content-Type: text/xml > >> > ? ? ? ? ? ?Content-Length: 415 > > >> > and the following request body (reformatted here for clarity): > > >> > ? ? ? ? ? ? > >> > ? ? ? ? ? ? > >> > ? ? ? ? ? ? ?search > >> > ? ? ? ? ? ? > >> > How can i send the above to the Listener Servlet? > >> > Thanks in advance > > >> Use the xmlrpclib module. > > > OK, sending headers with xmlrpclib, > > but how do i send the XML message? > > Your XML message is an XML RPC message. ?You will use xmlrpclib like this: > > server_proxy = xmlrpclib.ServerProxy(('somehost.com', 80)) > result = server_proxy.search() > > The call to server_proxy.search will result in an actual XML RPC > message being sent. > > Read up on the xmlrpclib documentation here:http://docs.python.org/library/xmlrpclib.html, and the XMLRPC spec > here:http://www.xmlrpc.com/spec > > -- > regards, > kushal Ok I got it! Thank you!!! A.K From bruno.42.desthuilliers at websiteburo.invalid Tue May 11 04:05:37 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 11 May 2010 10:05:37 +0200 Subject: Iterating a sequence two items at a time In-Reply-To: References: Message-ID: <4be90fca$0$31987$426a74cc@news.free.fr> Ulrich Eckhardt a ?crit : > Hi! > > I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4), > (5,6). I can of course roll my own, but I was wondering if there was > already some existing library function that already does this. >>> l = range(10) >>> for x, y in zip(l[::2], l[1::2]): ... print x, y ... 0 1 2 3 4 5 6 7 8 9 SimplestThingThatCouldPossiblyWork(tm) - but might not be the most efficient idiom, specially with large lists... From richard.lamboj at bilcom.at Tue May 11 04:38:52 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Tue, 11 May 2010 10:38:52 +0200 Subject: inherit from data type Message-ID: <201005111038.52390.richard.lamboj@bilcom.at> Hello, i want to inherit from a data type. How can i do this? Can anyone explain more abou this? How knows python that it is a float, or a string? Kind Regards Richi From eckhardt at satorlaser.com Tue May 11 04:43:23 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 11 May 2010 10:43:23 +0200 Subject: Iterating a sequence two items at a time References: Message-ID: Ulrich Eckhardt wrote: > I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4), > (5,6). I can of course roll my own, but I was wondering if there was > already some existing library function that already does this. > > > def as_pairs(seq): > i = iter(seq) > yield (i.next(), i.next()) Obviously this code does _not_ do what I want, it must be like this: def as_pairs(seq): i = iter(seq) while True: yield (i.next(), i.next()) Gah! Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From eckhardt at satorlaser.com Tue May 11 04:47:35 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 11 May 2010 10:47:35 +0200 Subject: inherit from data type References: Message-ID: <76inb7-m2g.ln1@satorlaser.homedns.org> Richard Lamboj wrote: > i want to inherit from a data type. How can i do this? Can anyone explain > more abou this? Other than in e.g. C++ where int and float are special types, you can inherit from them in Python like from any other type. The only speciality of int, float and string is that they are immutable. > How knows python that it is a float, or a string? I'm not actually sure I understand this question. If you derive from float, Python obviously knows that you derive from float.... Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From bryanjugglercryptographer at yahoo.com Tue May 11 04:50:19 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 11 May 2010 01:50:19 -0700 (PDT) Subject: fast regex References: Message-ID: <9a10e0e6-c8ac-4488-acee-f981cd416f68@k25g2000prh.googlegroups.com> Lawrence D'Oliveiro wrote: > ?Fast regex? is a contradiction in terms. You use > regexes when you want ease of definition and > application, not speed. Python or Perl regex's are not actually regular expressions. Real regular expression compilers produce blazing fast results, but they cannot support many of the features of offered by the search-and- backtrack engines that Python and Perl use. > For speed, consider hand-coding your own state > machine. Preferably in a compiled language like C. The speed of a real regular expression engine is hard to beat. I assume you're not actually suggesting hand-writing a state machine for the problem at issue here, which requires recognizing about 5000 different words. -- --Bryan From bruno.42.desthuilliers at websiteburo.invalid Tue May 11 04:55:17 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 11 May 2010 10:55:17 +0200 Subject: inherit from data type In-Reply-To: References: Message-ID: <4be91b6f$0$21797$426a74cc@news.free.fr> Richard Lamboj a ?crit : > Hello, > > i want to inherit from a data type. How can i do this? Hmmm, let's see... Could it be possible that it's documented somewhere ? Like, in the FineManual(tm) ?-) http://docs.python.org/tutorial/classes.html#inheritance > Can anyone explain more > abou this? How knows python that it is a float, or a string? which "it" ? Sorry, I'd like to help but I can't make sense of this question... From prologic at shortcircuit.net.au Tue May 11 04:58:00 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 11 May 2010 18:58:00 +1000 Subject: inherit from data type In-Reply-To: <201005111038.52390.richard.lamboj@bilcom.at> References: <201005111038.52390.richard.lamboj@bilcom.at> Message-ID: On Tue, May 11, 2010 at 6:38 PM, Richard Lamboj wrote: > i want to inherit from a data type. How can i do this? Can anyone explain more > abou this? How knows python that it is a float, or a string? $ python Python 2.6.5 (r265:79063, Apr 27 2010, 18:26:49) [GCC 4.4.1 (CRUX)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class MyFloat(float): ... def __repr__(self): ... return "MyFloat(%f)" % self ... >>> x = MyFloat(3.1415926535897931) >>> x MyFloat(3.141593) >>> --James From Ron.Barak at lsi.com Tue May 11 05:10:19 2010 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 11 May 2010 10:10:19 +0100 Subject: How to eliminate "Debug: src/helpers.cpp(140): 'CreateActCtx' failed" message ? In-Reply-To: References: Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6A3B87789@enbmail01.lsi.com> Hi, I created my first py2exe windows exe, and when it's run, I see on the console: $ ./svm_ts_tool_in_progress.exe 11:49:32: Debug: src/helpers.cpp(140): 'CreateActCtx' failed with error 0x0000007b (the filename, directory name, or volume label syntax is incorrect.). This is a non-fatal error and the application continues to run. I googled, but did not find a way to eliminate this Debug message. Could you suggest how to eliminate this message ? Thanks, Ron. ________________________________ Notes: $ python -V Python 2.6.4 $ cat setup.py #!/usr/bin/env python from distutils.core import setup import py2exe from glob import glob """ data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\HHD Software\Hex Editor Neo\Microsoft.VC90.CRT\*.*'))] icon_files = [("icons", glob(r'c:\views\cc_view\TS_svm_ts_tool\svm_ts_tool\*.gif'))] """ file_list = [] for i in glob(r'c:\views\cc_view\TS_svm_ts_tool\svm_ts_tool\*.gif'): file_list.append(i) data_files = [("data", file_list)] setup( data_files=data_files ) setup( console=["svm_ts_tool_in_progress.py"], zipfile=None, options={ "py2exe" : { "optimize" : 1 } } ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From richard.lamboj at bilcom.at Tue May 11 05:18:54 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Tue, 11 May 2010 11:18:54 +0200 Subject: inherit from data type In-Reply-To: <76inb7-m2g.ln1@satorlaser.homedns.org> References: <76inb7-m2g.ln1@satorlaser.homedns.org> Message-ID: <201005111118.54491.richard.lamboj@bilcom.at> Am Tuesday 11 May 2010 10:47:35 schrieb Ulrich Eckhardt: > Richard Lamboj wrote: > > i want to inherit from a data type. How can i do this? Can anyone explain > > more abou this? > > Other than in e.g. C++ where int and float are special types, you can > inherit from them in Python like from any other type. The only speciality > of int, float and string is that they are immutable. > > > How knows python that it is a float, or a string? > > I'm not actually sure I understand this question. If you derive from float, > Python obviously knows that you derive from float.... > > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 "How knows python that it is a float, or a string?" Sorry this was bad expressed. I want to create a new data type, which inherits from float. I just know the "dir" function and the "help" function to get more infromations about the class, but i need to get more information about the class structure. What i also want to know: >>> variable1 = 10.50 >>> type(variable1) Is there a way to tell python that it use antoher class than float for float, like myfloat? Its just a "tell-me-what-is-possible". Sample: >>> variable1 = 10.50 >>> type(variable1) Kind Regards, Richi From mftian at gmail.com Tue May 11 05:29:25 2010 From: mftian at gmail.com (Xie&Tian) Date: Tue, 11 May 2010 17:29:25 +0800 Subject: How to make this doctest work? Message-ID: Hello I ran across this accidentally and wonders how to make the doctest in following code snippet work: import doctest def a(): """ >>> a = '\\r\\n' >>> print a No matter how many blank lines I add here, it just can't get enough -_- """ pass doctest.testmod() ps: I want variable "a" to be '\r\n', but python kept telling me ValueError: line 4 of the docstring has inconsistent leading whitespace: "'" Why can't doctest module deal with statement "a='\r\n'"? -- Luyun Xie http://magefromhell.blogspot.com/ (http://blog.hellmage.info/) -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue May 11 05:30:39 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 11 May 2010 02:30:39 -0700 Subject: inherit from data type In-Reply-To: <201005111118.54491.richard.lamboj@bilcom.at> References: <76inb7-m2g.ln1@satorlaser.homedns.org> <201005111118.54491.richard.lamboj@bilcom.at> Message-ID: On Tue, May 11, 2010 at 2:18 AM, Richard Lamboj wrote: > What i also want to know: >>>> variable1 = 10.50 >>>> type(variable1) > > > Is there a way to tell python that it use antoher class than float for float, > like myfloat? Its just a "tell-me-what-is-possible". > > Sample: >>>> variable1 = 10.50 >>>> type(variable1) > No, it's not possible to have the float literal syntax produce instances of your custom subclass. Cheers, Chris -- http://blog.rebertia.com From dguthriemail at gmail.com Tue May 11 05:35:30 2010 From: dguthriemail at gmail.com (Dave Guthrie) Date: Tue, 11 May 2010 02:35:30 -0700 (PDT) Subject: Dynamically compiling and reloading SWIG .pyd file Message-ID: I am creating an application which has it's code split between python and C. The Python is used to provide a high level GUI interface and the C is for low level functions. I use SWIG to create Python Bindings for the C functions. I want to implement a feature where there is a button in the toolbar of the GUI which will automatically compile the C code into a .pyd file. The problem I have is when the GUI is running, the .pyd is loaded as a DLL and thus is locked by the GUI, so I can't get "gcc" to overwrite the .pyd file. I have tried to force the GUI to close it's handle on the file handle = ctypes.windll.kernel32.GetModuleHandleA("_FirmwareSubSys.pyd") if handle == 0: print "_FirmwareSubSys.pyd not loaded" else: _ctypes.FreeLibrary(handle) But by doing this the next time I load the DLL python crashes. Do anyone know how to dynamically compile and load SWIG Python Bindings? From eckhardt at satorlaser.com Tue May 11 05:38:42 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 11 May 2010 11:38:42 +0200 Subject: inherit from data type References: <76inb7-m2g.ln1@satorlaser.homedns.org> Message-ID: <26lnb7-t6g.ln1@satorlaser.homedns.org> Richard Lamboj wrote: > "How knows python that it is a float, or a string?" Sorry this was bad > expressed. I want to create a new data type, which inherits from float. I > just know the "dir" function and the "help" function to get more > infromations about the class, but i need to get more information about the > class structure. I'd suggest the tutorial, see http://docs.python.org, though your question is already beyond the range of beginners' questions. > What i also want to know: >>>> variable1 = 10.50 >>>> type(variable1) > > > Is there a way to tell python that it use antoher class than float for > float, like myfloat? Its just a "tell-me-what-is-possible". > > Sample: >>>> variable1 = 10.50 >>>> type(variable1) > The expression "10.5" will always be a float, you can't change that. What you can do is create your own type, derived from float: >>> class myfloat(float): ... pass ... and then create an object of that type: >>> x = myfloat(3.14) >>> type(x) >>> Lastly one warning: In many cases where people wanted to derive from a concrete data type, their problems were easier solved by external code. I don't know your problem though. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From paul at boddie.org.uk Tue May 11 06:24:26 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 11 May 2010 03:24:26 -0700 (PDT) Subject: Picking a license References: <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> Message-ID: <3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> On 10 Mai, 17:01, Patrick Maupin wrote: > > I'll be charitable and assume the fact that you can make that > statement without apparent guile merely means that you haven't read > the post I was referring to: > > http://www.gnu.org/philosophy/why-not-lgpl.html Of course I have read it, and not just recently either. But this is a position paper by the author of the licence, and it doesn't mean that someone who has written a GPL-licensed library completely agrees with that position. And anyway, it's a case of "take it or leave it" - it's not like the author or the FSF are sneaking stuff into every product and every corner of the market and then telling you that you can't "unchoose" their stuff. [...] > Legally, I don't think they can dictate the license terms of, e.g. > clisp just because it can link to readline. ?But practically, they DID > manage to do this, simply because Bruno Haible, the clisp author, was > more concerned about writing software than spending too much time > sparring with Stallman over the license, so he finally licensed clisp > under the gpl. ?clisp *could* use readline, but didn't require it; > nonetheless Stallman argued that clisp was a "derivative" of > readline. ?That case of the tail wagging the dog would be laughable if > it hadn't worked. ?In any case, Stallman's success at that tactic is > probably one of the things that led him to write the paper on why you > should use GPL for your library. Although it seems quite unfair, the e-mail discussion about the licence does show that Stallman was not initially convinced that works should be affected in such a way (with regard to the Objective-C compiler developed by NeXT), and that Haible was not strongly opposed to changing the licence. You can argue that Stallman overreached by demanding a licence change and that consideration of such matters has progressed since that time, but Haible always had the option of not using or supporting readline - only the latter is contentious, and the obligation of GPL-compatible licensing (as opposed to GPL-licensing) now diminishes how contentious this is today. [...] > I think that, legally, they probably don't have a leg to stand on for > some of their overarching claims (e.g. about shipping proprietary > software that could link to readline, without even shipping > readline). ?But morally -- well, they've made their position > reasonably clear and I try to abide by it. ?That still doesn't make it > "not really FUD." ?I'd call this sort of badgering "copyright misuse" > myself. Again, you have to consider the intent of the licensing: that some software which links to readline results in a software system that should offer the "four freedoms", because that's the price of linking to readline whose licence has promised that any system which builds upon it shall offer those privileges. > > As for rst2pdf, what your modifications would mean is that the > > software would need to be redistributed under a GPL-compatible > > licence. > > That's parsing semantics rather finely. ?In practice, what it really > means is that the combination (e.g. the whole program) would > effectively be GPL-licensed. ?This then means that downstream users > would have to double-check that they are not combining the whole work > with licenses which are GPL-incompatible, even if they are not using > the svg feature. ?Hence, the term "viral." Once again, I refer you to the intent of the licensing: if someone has the software in front of them which uses svglib, then they need to have the privileges granted to them by the GPL. Yes, if the software also uses some component with a GPL-incompatible licence, then this causes a problem. [...] > http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystem > > "A system incorporating a GPL-covered program is an extended version > of that program. The GPL says that any extended version of the program > must be released under the GPL if it is released at all." > > This makes it clear that the overall work must be GPLed. ?Now, all of > a sudden, downstream users cannot do some things they could have done > before. ?Can you not see that taking a preexisting MIT-licensed > project and adding code to make it GPL could negatively affect some of > its users and that that is not necessarily an unalloyed good? Well, I have referred several times to WebKit without you taking the hint, but that provides a specific case of a project which is LGPL- licensed despite being based on (in GPLv3 terminology) libraries which were distributed under the GPL and combined with that software. Similarly, the effort to ensure that CPython's licence was GPL- compatible had a lot to do with the right to redistribute with GPL- licensed code (actually readline, if I remember correctly). [...] > > Well, even the FSF doesn't approve of trivial projects using the GPL: > > >http://www.gnu.org/licenses/gpl-faq.html#WhatIfWorkIsShort > > Sure, that's a pragmatic view -- copyright might not even be permitted > on something that short that is mainly functional. ?However, length is > not the only arbiter of trivial. ?To stay with the same example, > personally, I would consider readline "trivial" within the context of > a lot of software which might use it, regardless of whether the > readline implementation itself used all sorts of fancy neural net > technology to predict what word the user was going to type or > whatever. ?But whether it was trivial or not, if I ship software that > *could* link to it but doesn't *require* it (like the case of clisp) > without shipping readline, I think it's FUD and an attempt at > copyright misuse to call my software a derivative work of readline. > But obviously YMMV Is readline trivial? Was readline trivial in 1992? Does it even matter, because the author is more or less saying that they don't want their code incorporated in a proprietary system? It's interesting to see that GPLv3 doesn't talk about derived works or derivatives (at least not as much as GPLv2), but instead talks about things being "based on" other things, but as I've already said, at the point of someone running a bunch of software components together, the intent of copyleft licences is to say that the user should be able to take that (or part of it, in the case of "weak copyleft" licences) and change, recompile and distribute its sources, modified or not. Paul From kaklis at gmail.com Tue May 11 06:29:22 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 11 May 2010 03:29:22 -0700 (PDT) Subject: HTTP Post Request References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com> <06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com> <95e73ff4-abe5-4874-8652-647818ed224a@k29g2000yqh.googlegroups.com> Message-ID: <2b94f35e-b3a0-49db-a66a-9ee1bf104a41@h20g2000prn.googlegroups.com> On May 11, 10:56?am, "kak... at gmail.com" wrote: > On May 11, 5:06?am, Kushal Kumaran > wrote: > > > > > On Mon, May 10, 2010 at 8:26 PM, kak... at gmail.com wrote: > > > On May 10, 10:22?am, Kushal Kumaran > > > wrote: > > >> On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com wrote: > > >> > Hi to all, i want to ask you a question, concerning the best way to do > > >> > the following as a POST request: > > >> > There is server-servlet that accepts xml commands > > >> > It had the following HTTP request headers: > > > >> > ? ? ? ? ? ?Host: somehost.com > > >> > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient > > >> > ? ? ? ? ? ?Content-Type: text/xml > > >> > ? ? ? ? ? ?Content-Length: 415 > > > >> > and the following request body (reformatted here for clarity): > > > >> > ? ? ? ? ? ? > > >> > ? ? ? ? ? ? > > >> > ? ? ? ? ? ? ?search > > >> > ? ? ? ? ? ? > > >> > How can i send the above to the Listener Servlet? > > >> > Thanks in advance > > > >> Use the xmlrpclib module. > > > > OK, sending headers with xmlrpclib, > > > but how do i send the XML message? > > > Your XML message is an XML RPC message. ?You will use xmlrpclib like this: > > > server_proxy = xmlrpclib.ServerProxy(('somehost.com', 80)) > > result = server_proxy.search() > > > The call to server_proxy.search will result in an actual XML RPC > > message being sent. > > > Read up on the xmlrpclib documentation here:http://docs.python.org/library/xmlrpclib.html, and the XMLRPC spec > > here:http://www.xmlrpc.com/spec > > > -- > > regards, > > kushal > > Ok I got it! > Thank you!!! > > A.K Apparently the server i'm trying to connect accepts only POST connections. So xmlrpclib is useless. I think I need the httplib library module. Any hints? A.K. From paul at boddie.org.uk Tue May 11 06:34:49 2010 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 11 May 2010 03:34:49 -0700 (PDT) Subject: Picking a license References: <30aff350- <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> <9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com> <7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> Message-ID: On 10 Mai, 20:36, Patrick Maupin wrote: > > I've addressed this before. ?Aahz used a word in an accurate, but to > you, inflammatory, sense, but it's still accurate -- the man *would* > force you to pay for the chocolate if you took it. Yes, *if* you took it. He isn't forcing you to take it, though, is he? > You're making it sound like whining, but Aahz was simply trying to state a fact. It is whining if someone says, "I really want that chocolate, but that nasty man is going to make me pay for it!" >?The fact is, I know the man would force me to pay for the chocolate, so in > some cases that enters into the equation and keeps me from wanting the > chocolate. If the man said, "please take the chocolate, but I want you to share it with your friends", and you refused to do so because you couldn't accept that condition, would it be right to say, "that man is forcing me to share chocolate with my friends"? > ?This isn't whining; just a common-sense description of > reality. ?Personally, I think this use of the word "force" is much > less inflammatory than the deliberate act of co-opting the word > "freedom" to mean "if you think you can take this software and do > anything you want with it, you're going to find out differently when > we sue you." The word "freedom" means a number of things. If you don't like the way Messrs Finney and Stallman use the term, please take it up with them. But to say that someone entering a voluntary agreement is "forced" to do something, when they weren't forced into that agreement in the first place, is just nonsense. It's like saying that the shopkeeper is some kind of Darth Vader character who is coercing people to take the chocolate and then saddling them with obligations against their will. Paul From alt.mcarter at googlemail.com Tue May 11 06:40:03 2010 From: alt.mcarter at googlemail.com (Mark Carter) Date: Tue, 11 May 2010 03:40:03 -0700 (PDT) Subject: win32com sql update problem Message-ID: Consider the following snippet of code: import win32com.client DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=M:\\Finance\\camel\ \camel.mdb;' conn.Open(DSN) cursor = conn.Execute("UPDATE tblInvoice SET InvComments='Python' WHERE InvBillingPeriod = 'April 2010' AND InvJobCode = '2169'") rows = cursor.Affected_Rows() print rows conn.Close() I am using Python 2.6.5, and pywin32. If I try to run it, I get the response: Traceback (most recent call last): File "C:/Users/mcarter/tacc/pypms/post.py", line 79, in AdjustPms(d) File "C:/Users/mcarter/tacc/pypms/post.py", line 64, in AdjustPms cursor = conn.Execute("UPDATE tblInvoice SET InvComments='Python' WHERE InvBillingPeriod = 'April 2010' AND InvJobCode = '2169'") File "", line 3, in Execute File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 272, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft JET Database Engine', u"Cannot open database ''. It may not be a database that your application recognizes, or the file may be corrupt.", None, 5003049, -2147467259), None) I have used the same DNS to retrieve data from the database using SELECT statements, so I'm at a loss to figure out what's going wrong. It seems to think the database name as an empty string. I'm not sure if that's the root cause of the problem, though. Any ideas? From jeanmichel at sequans.com Tue May 11 06:54:49 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 11 May 2010 12:54:49 +0200 Subject: lame sphinx questions [Was: lame epydoc questions] In-Reply-To: <289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com> References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> <4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com> <289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com> Message-ID: <4BE93779.4030609@sequans.com> Phlip wrote: > On May 10, 1:51 pm, Phlip wrote: > >> On May 10, 1:39 pm, Chris Rebert wrote: >> >> >>> Sphinx is in vogue right now:http://sphinx.pocoo.org/ >>> > > Okay, we have ten thousand classes to document. How to add them all to > index.rst? > I remember trying using Sphinx for auto documented APIs, but it was not suitable at that time. You can include API docs generated from the code, but you still need to write the docs around. If I'm correct, Sphinx is one of the best tool to document public APIs. However to build internal documentation with everything from interfaces to implementations, epydoc is still the best, it builds everything with no additional writing, just press the button. JM From ldo at geek-central.gen.new_zealand Tue May 11 07:11:01 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 May 2010 23:11:01 +1200 Subject: Is Python a functional programming language? References: <7xvdavd4bq.fsf@ruckus.brouhaha.com> Message-ID: In message <7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Python is a pragmatic language from an imperative tradition ... I thought the opposite of ?functional? was ?procedural?, not ?imperative?. The opposite to the latter is ?declarative?. But (nearly) all procedural languages also have declarative constructs, not just imperative ones (certainly Python does). Presumably an ?imperative? language would not. From ldo at geek-central.gen.new_zealand Tue May 11 07:13:10 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 11 May 2010 23:13:10 +1200 Subject: Is Python a functional programming language? References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> Message-ID: In message , Stefan Behnel wrote: > But the beauty is that Python is multi-paradigm ... The trouble with ?multi-paradigm? is that it offends the zealots on all sides. It?s like saying that, to effect a compromise among multiple conflicting monotheistic religions, we should create a polytheistic amalgam of them. From steve at REMOVE-THIS-cybersource.com.au Tue May 11 07:18:07 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 May 2010 11:18:07 GMT Subject: Picking a license References: <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> <9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com> <7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> Message-ID: <4be93cee$0$27837$c3e8da3@news.astraweb.com> On Tue, 11 May 2010 03:34:49 -0700, Paul Boddie wrote: > It's like saying that the shopkeeper is some kind of Darth Vader > character who is coercing people to take the chocolate Last time I came home with chocolate, I tried that excuse on my wife. She didn't believe it for a second. Next time, I'll try claiming that I was obliged to eat the chocolate because of the GPL. -- Steven From stefan_ml at behnel.de Tue May 11 07:32:47 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 11 May 2010 13:32:47 +0200 Subject: Is Python a functional programming language? In-Reply-To: References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com> Message-ID: Lawrence D'Oliveiro, 11.05.2010 13:13: > Stefan Behnel wrote: > >> But the beauty is that Python is multi-paradigm ... > > The trouble with ?multi-paradigm? is that it offends the zealots on all > sides. It?s like saying that, to effect a compromise among multiple > conflicting monotheistic religions, we should create a polytheistic amalgam > of them. The Romans were pretty successful in doing so, for several hundred years. Let's see if Python will conquer and rule for that long. Stefan From jayeola at gmail.com Tue May 11 07:41:12 2010 From: jayeola at gmail.com (John Maclean) Date: Tue, 11 May 2010 12:41:12 +0100 Subject: unittest basics Message-ID: <4BE94258.7010409@gmail.com> is there a way to test that a certian library or module is or can be loaded successfully? self.assert('import blah') -- John Maclean MSc. (DIC) BSc. (Hons) Linux Systems and Applications 07739 171 531 From richard.lamboj at bilcom.at Tue May 11 07:51:46 2010 From: richard.lamboj at bilcom.at (Richard Lamboj) Date: Tue, 11 May 2010 13:51:46 +0200 Subject: inherit from data type In-Reply-To: <26lnb7-t6g.ln1@satorlaser.homedns.org> References: <26lnb7-t6g.ln1@satorlaser.homedns.org> Message-ID: <201005111351.46892.richard.lamboj@bilcom.at> Am Tuesday 11 May 2010 11:38:42 schrieb Ulrich Eckhardt: > Richard Lamboj wrote: > > "How knows python that it is a float, or a string?" Sorry this was bad > > expressed. I want to create a new data type, which inherits from float. I > > just know the "dir" function and the "help" function to get more > > infromations about the class, but i need to get more information about > > the class structure. > > I'd suggest the tutorial, see http://docs.python.org, though your question > is already beyond the range of beginners' questions. > > > What i also want to know: > >>>> variable1 = 10.50 > >>>> type(variable1) > > > > > > > > Is there a way to tell python that it use antoher class than float for > > float, like myfloat? Its just a "tell-me-what-is-possible". > > > > Sample: > >>>> variable1 = 10.50 > >>>> type(variable1) > > > > > > The expression "10.5" will always be a float, you can't change that. What > > you can do is create your own type, derived from float: > >>> class myfloat(float): > > ... pass > ... > > and then create an object of that type: > >>> x = myfloat(3.14) > >>> type(x) > > > > > > Lastly one warning: In many cases where people wanted to derive from a > concrete data type, their problems were easier solved by external code. I > don't know your problem though. > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 I just want to test what is possible with python and what not. There is no problem that i need to solve. This is what i'am searching for: http://docs.python.org/reference/datamodel.html Last year i have stopped programming python, but now i'am back with a big black hole in my brain and i want to understand what the interpreter is doing in the background. I think my question was not well formulated... Kind Regards From g.rodola at gmail.com Tue May 11 08:03:58 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Tue, 11 May 2010 14:03:58 +0200 Subject: unittest basics In-Reply-To: <4BE94258.7010409@gmail.com> References: <4BE94258.7010409@gmail.com> Message-ID: There's no reason for such a thing. You can just make "import module" in your test and if something goes wrong that will be treated as any other test failure. --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil 2010/5/11 John Maclean : > is there a way to test that a certian library or module is or can be loaded > successfully? > > self.assert('import blah') > > -- > John Maclean > MSc. (DIC) BSc. (Hons) > Linux Systems and Applications > 07739 171 531 > -- > http://mail.python.org/mailman/listinfo/python-list > From aurelien.gourrier at yahoo.fr Tue May 11 08:04:18 2010 From: aurelien.gourrier at yahoo.fr (=?iso-8859-1?Q?Aur=E9_Gourrier?=) Date: Tue, 11 May 2010 12:04:18 +0000 (GMT) Subject: how to import a module for global use in a library package ? Message-ID: <577270.86860.qm@web23105.mail.ird.yahoo.com> Dear all, I am building a library package of the form: rootlib ---__init__ ---subpackage1 ------__init__ ------sub1module1 ------sub1module2 ------... ---subpackage2 ------ __init__ ------sub2module1 ------sub2module2 ------... My rootlib.__init__ file contains: __name__ = ... __version__ = ... __author__ = ... __author_email__= ... __url__ = ... __description__ = ... import subpackage1 import subpackage2 __all__ = [] __all__.extend(['subpackage1','subpackage2']) My question is the following: I need to import an external package, say numpy, for use in various submodules. So far, I simply do an import numpy as _numpy where needed, say sub1module1 and sub2module2. This means that I import this package a number of times which doesn't seem to be a logical thing to do (?). In the end, I would like to make this module a "global" module for my library. I would find it more practical to simply do this import in the __init__ of rootlib and then use it directly in the submodules as rootlib._numpy calls, but I'm not sure exactly how to do this because it would mean that I would have to do an import rootlib in my subpackages which doesn't sound so good... Can anyone give me a hint ? Cheers, Aur? -------------- next part -------------- An HTML attachment was scrubbed... URL: From e_d_k at yahoo.com Tue May 11 08:12:23 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 11 May 2010 05:12:23 -0700 (PDT) Subject: Picking a license In-Reply-To: <87vdavck7a.fsf@benfinney.id.au> Message-ID: <388056.46566.qm@web58704.mail.re1.yahoo.com> --- On Mon, 5/10/10, Ben Finney wrote: > So I object to muddying the issue by misrepresenting the > source of that > force. Whatever force there is in copyright comes from law, > not any free > software license. You are the one muddying the waters. It does not mater whether you break my kneecaps, or hire someone else to break my kneecaps, either way my kneecaps are broken. You can use any license you want, but the simple fact is that if there are fewer restrictions in the license then the user has more freedom in how he uses the licensed code. If there are more restrictions he/she has less freedom in how he/she uses the licensed code. We can debate which is better (whether a man should be free to sell himself into slavery) but to claim that putting more restrictions on someone give them more freedom is pure Orwellian double speak. Sophistry is the last resort of those who have run out of good arguments. The more you engage in it the weaker you make your position. This thread is generating more heat than light, and probably should be dropped. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From jeanmichel at sequans.com Tue May 11 08:30:32 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 11 May 2010 14:30:32 +0200 Subject: how to import a module for global use in a library package ? In-Reply-To: <577270.86860.qm@web23105.mail.ird.yahoo.com> References: <577270.86860.qm@web23105.mail.ird.yahoo.com> Message-ID: <4BE94DE8.3000301@sequans.com> Aur? Gourrier wrote: > [snip] > My question is the following: I need to import an external package, > say numpy, for use in various submodules. So far, I simply do an > import numpy as _numpy where needed, say sub1module1 and sub2module2. > This means that I import this package a number of times which doesn't > seem to be a logical thing to do (?). No problem at all. You need numpy in a file, then import numpy at the very beginning of the file. You have 100 files requiring numpy? you'll end up with 100 'import numpy' statements, but who cares ? This is perfectly logic and pythonic in the way it is explicit. You could reference numpy as member of you rootlib package, but any call of numpy methods will be prefixed by rootlib.numpy, and you still need a import rootlib (circular imports since rootlib is importing your submodules !) JM > Aur? > > From guillermo.listas at googlemail.com Tue May 11 08:33:51 2010 From: guillermo.listas at googlemail.com (Guillermo) Date: Tue, 11 May 2010 05:33:51 -0700 (PDT) Subject: virtualenvwrapper for Windows (Powershell) References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com> Message-ID: <973ca0fa-4a2f-4e3b-91b9-e38917885c0f@d27g2000yqc.googlegroups.com> On May 11, 7:43?am, Lawrence D'Oliveiro wrote: > In message > <22cf35af-44d1-43fe-8b90-07f2c6545... at i10g2000yqh.googlegroups.com>, > > Guillermo wrote: > > If you've ever missed it on Windows and you can use Powershell ... > > I thought the whole point of Windows was to get away from this command-line > stuff. Not such a good idea after all? I suppose it depends. From chris at simplistix.co.uk Tue May 11 08:40:35 2010 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 11 May 2010 13:40:35 +0100 Subject: unittest basics In-Reply-To: <4BE94258.7010409@gmail.com> References: <4BE94258.7010409@gmail.com> Message-ID: <4BE95043.8030201@simplistix.co.uk> import unittest class MyTestCase(unittest.TestCase): def test_my_import(self): import blah cheers, Chris John Maclean wrote: > is there a way to test that a certian library or module is or can be > loaded successfully? > > self.assert('import blah') > -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From mhv at dmu.dk Tue May 11 08:54:06 2010 From: mhv at dmu.dk (Hvidberg, Martin) Date: Tue, 11 May 2010 14:54:06 +0200 Subject: reading xml from python Message-ID: I'm looking for at way to read (and later write) small simple .xml file from Python. e.g. I would like to read the following from a small ini.xml file into a dictionary. default False False UBMlight True I would prefer a relative simple (not too much creating new classes) way to do this. Any suggestions appreciated. :-) Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: From drobinow at gmail.com Tue May 11 08:59:37 2010 From: drobinow at gmail.com (David Robinow) Date: Tue, 11 May 2010 08:59:37 -0400 Subject: virtualenvwrapper for Windows (Powershell) In-Reply-To: References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com> Message-ID: On Tue, May 11, 2010 at 1:43 AM, Lawrence D'Oliveiro wrote: > In message > <22cf35af-44d1-43fe-8b90-07f2c6545f63 at i10g2000yqh.googlegroups.com>, > Guillermo wrote: >> If you've ever missed it on Windows and you can use Powershell ... > I thought the whole point of Windows was to get away from this command-line > stuff. Not such a good idea after all? The whole point of Windows was to make money for Microsoft. Microsoft can be criticized for many things but a mindless devotion to principle is not one of them. From lie.1296 at gmail.com Tue May 11 09:00:22 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 11 May 2010 23:00:22 +1000 Subject: Picking a license In-Reply-To: <3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> References: <4be522ac$0$27798$c3e8da3@news.astraweb.com> <4be5bdcb$0$27798$c3e8da3@news.astraweb.com> <888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> <30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> <4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> <4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> <40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> <074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> <3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> Message-ID: <4be95545$1@dnews.tpgi.com.au> On 05/11/10 20:24, Paul Boddie wrote: > On 10 Mai, 17:01, Patrick Maupin wrote: >> >> I'll be charitable and assume the fact that you can make that >> statement without apparent guile merely means that you haven't read >> the post I was referring to: >> >> http://www.gnu.org/philosophy/why-not-lgpl.html > > Of course I have read it, and not just recently either. But this is a > position paper by the author of the licence, and it doesn't mean that > someone who has written a GPL-licensed library completely agrees with > that position. And anyway, it's a case of "take it or leave it" - it's > not like the author or the FSF are sneaking stuff into every product > and every corner of the market and then telling you that you can't > "unchoose" their stuff. Come on, 99% of the projects released under GPL did so because they don't want to learn much about the law; they just need to release it under a certain license so their users have some legal certainty. Most programmers are not lawyers and don't care about the law and don't care about the GPL; if a commercial programmer want to use the GPL-code in an incompatible licensed program, and he comes up asking, many would just be happy to say yes. Most people release their code in GPL just because it's popular, not for the exact clauses in it. Heck, many people that releases code in GPL might not actually have read the full license. Only big GPL projects have the resources to waste on a lawyer. And only very big projects have the resources to waste on enforcing the license they uses. The rest of us just don't care. From clp2 at rebertia.com Tue May 11 09:17:07 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 11 May 2010 06:17:07 -0700 Subject: reading xml from python In-Reply-To: References: Message-ID: On Tue, May 11, 2010 at 5:54 AM, Hvidberg, Martin wrote: > I'm looking for at way to read (and later write) small simple .xml file from > Python. > > e.g. I would like to read the following?from a small ini.xml file into a > dictionary. > > > > > ?default > ?False > ?False > ?UBMlight > ?True > > > I would prefer a relative simple (not too much creating new classes) way to > do this. from xml.etree.ElementTree import ElementTree tree = ElementTree() tree.parse("ini.xml") as_dictionary = dict((child.tag, child.text) for child in tree.getchildren()) Writing is left as an exercise for another poster. Cheers, Chris -- http://blog.rebertia.com From philip at semanchuk.com Tue May 11 09:17:48 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 11 May 2010 09:17:48 -0400 Subject: reading xml from python In-Reply-To: References: Message-ID: <549D0765-9DD8-4816-BEE2-5C77101CB49C@semanchuk.com> On May 11, 2010, at 8:54 AM, Hvidberg, Martin wrote: > I'm looking for at way to read (and later write) small simple .xml > file from Python. > > e.g. I would like to read the following from a small ini.xml file > into a dictionary. > > > > default > False > False > UBMlight > True > > I would prefer a relative simple (not too much creating new classes) > way to do this. > > Any suggestions appreciated. Hej Martin, Did you look in the standard library? ElementTree in the XML section of the standard library will do what you want. There are several other choices there if you don't like that. bye Philip From dkgispam at gmail.com Tue May 11 09:22:29 2010 From: dkgispam at gmail.com (Dominik Gabi) Date: Tue, 11 May 2010 06:22:29 -0700 (PDT) Subject: urllib.urlopen blocking? Message-ID: Hi, I'm new to python and have been playing around with it for a few days now. So please forgive me if this is a stupid question :) I've tried writing a little application with pygtk and urllib. When a button is clicked I create a new thread that opens an URL with urllib. The new thread is running but as soon as I call urllib.urlopen("https://someurl", postdata) it blocks. It blocks until I do something in the interface (e.g. click another button). I've obviously missed something here. The interface should not interfere with anything that runs in an other thread!? Here are a few extracts from my code: def send_message(self, widget, data=None): # This is called when the button is clicked ... threading.Thread(target=message.send).start() ... def send(self): # This is executed in its own thread ... postdata = urllib.urlencode(data) # This line is the last one executed resp = urllib.urlopen('https://theurl', postdata) Regards, Dominik. From phlip2005 at gmail.com Tue May 11 09:27:18 2010 From: phlip2005 at gmail.com (Phlip) Date: Tue, 11 May 2010 06:27:18 -0700 (PDT) Subject: lame sphinx questions [Was: lame epydoc questions] References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> <4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com> <289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com> Message-ID: <656fab1f-2cb7-433e-84ba-ffebbc118dde@t26g2000prt.googlegroups.com> On May 11, 3:54?am, Jean-Michel Pichavant wrote: > I remember trying using Sphinx for auto documented APIs, but it was not > suitable at that time. You can include API docs generated from the code, > but you still need to write the docs around. > If I'm correct, ?Sphinx is one of the best tool to document public APIs. > However to build internal documentation with everything from interfaces > to implementations, epydoc is still the best, it builds everything with > no additional writing, just press the button. Ah, thanks. We are all about writing '''doc strings''', then ripping them to form documentation that we DO intend someone to READ and USE! Now the problem with epydoc is it uses a persnickety text markup language that... - throws a syntax error & reverts to
 when the wind blows
 - demands all kinds of extra markup, such as @param
 - uses >3 different kinds of escapes, @, L{}, & 
 - has no developer tests to speak of

I'm all about cross-linking and transcluding, and I wanted to upgrade
epydoc to do it, so I need to make sure that all those issues are
going to be either worth our time to fix or work around, and I didn't
overlook some better system.


From solipsis at pitrou.net  Tue May 11 09:54:57 2010
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Tue, 11 May 2010 15:54:57 +0200
Subject: urllib.urlopen blocking?
References: 
Message-ID: <20100511155457.2ecfa366@pitrou.net>

On Tue, 11 May 2010 06:22:29 -0700 (PDT)
Dominik Gabi  wrote:
> 
> I'm new to python and have been playing around with it for a few days
> now. So please forgive me if this is a stupid question :)
> 
> I've tried writing a little application with pygtk and urllib.

For the record, have you tried calling gobject.threads_init() at the
beginning of your application (just after importing all modules)?




From aahz at pythoncraft.com  Tue May 11 09:55:13 2010
From: aahz at pythoncraft.com (Aahz)
Date: 11 May 2010 06:55:13 -0700
Subject: Extract all words that begin with x
References: 
	
	
	
Message-ID: 

In article ,
Terry Reedy   wrote:
>On 5/10/2010 5:35 AM, James Mills wrote:
>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho  wrote:
>>> Have I missed something, or wouldn't this work just as well:
>>>
>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>> ['awes', 'asdgas']
>>
>> I would do this for completeness (just in case):
>>
>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>
>> Just guards against empty strings which may or may not be in the list.
>
>  ... word[0:1] does the same thing. All Python programmers should learn 
>to use slicing to extract a  char from a string that might be empty.
>The method call of .startswith() will be slower, I am sure.

And if it is slower, so what?  Using startswith() makes for faster
reading of the code for me, and I'm sure I'm not the only one.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From paul at boddie.org.uk  Tue May 11 10:00:16 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Tue, 11 May 2010 07:00:16 -0700 (PDT)
Subject: Picking a license
References: 
	<4be5bdcb$0$27798$c3e8da3@news.astraweb.com> 
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> 
	 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<4be95545$1@dnews.tpgi.com.au>
Message-ID: 

On 11 Mai, 15:00, Lie Ryan  wrote:
>
> Come on, 99% ?of the projects released under GPL did so because they
> don't want to learn much about the law; they just need to release it
> under a certain license so their users have some legal certainty.

Yes, this is frequently the case. And the GPL does offer some
certainty that various permissive licences do not.

> Most programmers are not lawyers and don't care about the law and don't care
> about the GPL; if a commercial programmer want to use the GPL-code in an
> incompatible licensed program, and he comes up asking, many would just
> be happy to say yes.

Yes, quite possibly. I did mention this myself elsewhere.

> Most people release their code in GPL just because it's popular, not for
> the exact clauses in it. Heck, many people that releases code in GPL
> might not actually have read the full license.

Yes, this is also probably the case for a number of people. Although
many probably understand the principles of the licence and feel that
it represents their wishes most accurately.

> Only big GPL projects have the resources to waste on a lawyer. And only
> very big projects have the resources to waste on enforcing the license
> they uses. The rest of us just don't care.

Well, that's always an option as well, but at the same time, there are
people willing to pursue licence violations, and these people have
done so successfully. There's no need to make an impassioned argument
for apathy, though. Some people do wish to dictate what others can do
with their work.

Or are you trying to make another point here? That people would choose
something other than the GPL if only they "knew better", perhaps?
Since the FSF goes out of its way to list lots of Free Software
licences, GPL-compatible or otherwise, and those other licences aren't
exactly secret anyway, I hardly think there's a conspiracy at work.

Paul


From jeanmichel at sequans.com  Tue May 11 10:04:19 2010
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Tue, 11 May 2010 16:04:19 +0200
Subject: lame sphinx questions [Was: lame epydoc questions]
In-Reply-To: <656fab1f-2cb7-433e-84ba-ffebbc118dde@t26g2000prt.googlegroups.com>
References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com>
		<4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com>	<289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com>
	
	<656fab1f-2cb7-433e-84ba-ffebbc118dde@t26g2000prt.googlegroups.com>
Message-ID: <4BE963E3.3040609@sequans.com>

Phlip wrote:
> On May 11, 3:54 am, Jean-Michel Pichavant 
> wrote:
>
>   
>> I remember trying using Sphinx for auto documented APIs, but it was not
>> suitable at that time. You can include API docs generated from the code,
>> but you still need to write the docs around.
>> If I'm correct,  Sphinx is one of the best tool to document public APIs.
>> However to build internal documentation with everything from interfaces
>> to implementations, epydoc is still the best, it builds everything with
>> no additional writing, just press the button.
>>     
>
> Ah, thanks. We are all about writing '''doc strings''', then ripping
> them to form documentation that we DO intend someone to READ and USE!
>   
> Now the problem with epydoc is it uses a persnickety text markup
> language that...
>
>  - throws a syntax error & reverts to 
 when the wind blows
>  - demands all kinds of extra markup, such as @param
>  - uses >3 different kinds of escapes, @, L{}, & 
>  - has no developer tests to speak of
>
> I'm all about cross-linking and transcluding, and I wanted to upgrade
> epydoc to do it, so I need to make sure that all those issues are
> going to be either worth our time to fix or work around, and I didn't
> overlook some better system.
>   
epydoc supports reStructured text markups. AFAIK it's still the best doc 
builder available for python code. Too bad it is not maintained since 2 
years and the 3.0 release.
If there was any effort to provide however, I think it would be on 
sphinx so it would allow building the complete doc from python code. As 
written in the doc, it's currently half-automated.

JM


From dkgispam at gmail.com  Tue May 11 10:35:52 2010
From: dkgispam at gmail.com (Dominik Gabi)
Date: Tue, 11 May 2010 07:35:52 -0700 (PDT)
Subject: urllib.urlopen blocking?
References: 
	
Message-ID: 

> For the record, have you tried calling gobject.threads_init() at the
> beginning of your application (just after importing all modules)?

I haven't... now it works, thanks :) Any tips on how to avoid mistakes
like that in the future? I'm somewhat confused as to how I was
supposed to get this out of the documentation...


From no.email at nospam.invalid  Tue May 11 10:36:30 2010
From: no.email at nospam.invalid (Paul Rubin)
Date: Tue, 11 May 2010 07:36:30 -0700
Subject: Is Python a functional programming language?
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
Message-ID: <7xvdau8pzl.fsf@ruckus.brouhaha.com>

Lawrence D'Oliveiro  writes:
> I thought the opposite of ?functional? was ?procedural?, not ?imperative?. 
> The opposite to the latter is ?declarative?. But (nearly) all procedural 
> languages also have declarative constructs, not just imperative ones 
> (certainly Python does). Presumably an ?imperative? language would not.

Offhand I can't tell that imperative and procedural mean something
different.  Both basically mean that the programmer specifies a series
of steps for the computer to carry out.  Functional languages are mostly
declarative; for example, an expression like
   x = 3
is called an "equation" rather than an "assignment".  It declares "x is
equal to 3", rather than directing x to be set to 3.  If someplace else
in the program you say "x = 4", that is an error, normally caught by
the compiler, since x cannot be equal to both 3 and 4.


From python at bdurham.com  Tue May 11 10:37:01 2010
From: python at bdurham.com (python at bdurham.com)
Date: Tue, 11 May 2010 10:37:01 -0400
Subject: Slice last char from string without raising exception on empty string
	(Re: Extract all words that begin with x)
In-Reply-To: 
References: 
	
Message-ID: <1273588621.1629.1374510539@webmail.messagingengine.com>

Terry,

>  ... word[0:1] does the same thing. All Python programmers should learn to use slicing to extract a char from a string that might be empty.

Is there an equivalent way to slice the last char from a string (similar
to an .endswith) that doesn't raise an exception when a string is empty?

Thanks,
Malcolm


From jim.vickroy at noaa.gov  Tue May 11 10:46:17 2010
From: jim.vickroy at noaa.gov (j vickroy)
Date: Tue, 11 May 2010 08:46:17 -0600
Subject: unable to get Hudson to run unit tests
In-Reply-To: 
References: 		<4BE80A78.2030502@noaa.gov>		<4BE828A2.2070106@noaa.gov>
	
Message-ID: <4BE96DB9.7040303@noaa.gov>

Thanks again, Stefan.  My comments are below.

Stefan Behnel wrote:
> j vickroy, 10.05.2010 17:39:
>> Unfortunately, when "Hudson Build now" is performed, the Hudson Console
>> output, for this job, is:
>>
>> ------------------------------------------------------------
>> Started by user anonymous
>> Updating svn://vm-svn/GOES data 
>> processing/trunk/GOES/13,14,15/SXI/level-1
>> At revision 3403
>> no change for svn://vm-svn/GOES data
>> processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build
>> [workspace] $ python.exe
>> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson5273111667332806239.sh
>> os.getcwd(): C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES
>> 13-15 SXI Level-1 Products Generation\workspace
>> os.listdir(os.getcwd()): ['level-1']
>> [workspace] $ cmd.exe -xe
>> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson991194264891924641.sh
>> Microsoft Windows XP [Version 5.1.2600]
>> (C) Copyright 1985-2001 Microsoft Corp.
>>
>> C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI
>> Level-1 Products Generation\workspace>Recording test results
>> No test report files were found. Configuration error?
>> Finished: FAILURE
>> ------------------------------------------------------------
>>
>> The second [workspace] section output (above) looks like cmd.exe is
>> being executed with no parameters (i.e., without the
>> "nosetests.exe --where=level-1 --with-xunit --verbose") parameter.
> 
> No, what Hudson actually does, is, it writes your command(s) into a text 
> file and runs it with the system's shell interpreter (which, unless 
> otherwise configured, is "cmd.exe" on Windows). 

This is not the behavior I am experiencing on my Windows XP Pro (Service 
Pack 3) workstation.

If I do not specify "C:\WINDOWS\system32\cmd.exe" for "Manage Hudson | 
Configuration System | Shell | Shell executable", the "Console output" 
after a "Build now" is:

-----------------------------------------------------
Started by user anonymous
Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1
At revision 3417
no change for svn://vm-svn/GOES data 
processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build
[workspace] $ sh -xe 
C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson869574722591302824.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: Cannot run program "sh" (in directory "C:\Documents 
and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI Level-1 Products 
Generation\workspace"): CreateProcess error=2, The system cannot find 
the file specified
	at java.lang.ProcessBuilder.start(Unknown Source)
	at hudson.Proc$LocalProc.(Proc.java:149)
	at hudson.Proc$LocalProc.(Proc.java:121)
	at hudson.Launcher$LocalLauncher.launch(Launcher.java:636)
	at hudson.Launcher$ProcStarter.start(Launcher.java:271)
	at hudson.Launcher$ProcStarter.join(Launcher.java:278)
	at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:83)
	at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:58)
	at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:19)
	at 
hudson.model.AbstractBuild$AbstractRunner.perform(AbstractBuild.java:584)
	at hudson.model.Build$RunnerImpl.build(Build.java:174)
	at hudson.model.Build$RunnerImpl.doRun(Build.java:138)
	at hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:416)
	at hudson.model.Run.run(Run.java:1244)
	at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
	at hudson.model.ResourceController.execute(ResourceController.java:88)
	at hudson.model.Executor.run(Executor.java:122)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot 
find the file specified
	at java.lang.ProcessImpl.create(Native Method)
	at java.lang.ProcessImpl.(Unknown Source)
	at java.lang.ProcessImpl.start(Unknown Source)
	... 17 more
Recording test results
Finished: FAILURE
-----------------------------------------------------

Note Hudson is looking for "sh".

This assures the highest
> possible compatibility with the executed script. You can even use the 
> shebang in Hudson's scripts that way, so that you can execute scripts in 
> basically any scripting language.
> 
> The likely reason why it doesn't find your test results is that you 
> didn't tell it where to look. 

Actually, Hudson is not finding the tests results because they are not 
being generated.  There is no "nosetests.xml" file anywhere on my hard 
drive (except in the Recycle Bin from my explicit executions of the 
"nosetests.exe --where=level-1 --with-xunit --verbose" command).  This 
is why I thought Hudson was not executing the above nosetests.exe 
command (specified in "*job* | Configure | Build | Execute shell | command".


Put a wildcard path into the unit test
> config box that finds the XML files that nosetest writes. It's also best 
> to tell nosetest where to put them explicitly using a command line option.
> 
> Stefan
> 

Thanks again for your continued interest.  I quickly got Hudson to 
retrieve job source from our subversion repository so I thought it would 
be equally easy to get Hudson to run the unit tests, but that has proven 
to be difficult, and so far I do not know how to diagnose this since it 
seems there is no way to prevent Hudson from immediately deleting the 
temporary scripts it generates.


From michele.simionato at gmail.com  Tue May 11 10:49:55 2010
From: michele.simionato at gmail.com (Michele Simionato)
Date: Tue, 11 May 2010 07:49:55 -0700 (PDT)
Subject: Is Python a functional programming language?
References:  
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
Message-ID: 

On May 10, 8:18?pm, a... at pythoncraft.com (Aahz) wrote:
> saying that functional features
> are "tacked on" understates the case. ?Consider how frequently people
> reach for list comps and gen exps. ?Function dispatch through dicts is
> the standard replacement for a switch statement. ?Lambda callbacks are
> common. ?Etc, etc, etc

Just to play devil's advocate, I will notice that list comps and gen
exps are not really
functional (a generator has a state that changes at each call of
next). A functional language
would use streams instead. Function dispatch through dicts is very
lame compared to pattern matching. Lambdas are restricted. There is no
tail call optimization. Definitively Python functional features are
"tacked on" with respect to a language defined to be functional.
Having said that, the functional features are still usable and one can
use a functional style
in Python if she wants to (module a few caveats).


From solipsis at pitrou.net  Tue May 11 10:55:43 2010
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Tue, 11 May 2010 16:55:43 +0200
Subject: urllib.urlopen blocking?
References: 
	
	
Message-ID: <20100511165543.4a1d64f4@pitrou.net>

On Tue, 11 May 2010 07:35:52 -0700 (PDT)
Dominik Gabi  wrote:

> > For the record, have you tried calling gobject.threads_init() at the
> > beginning of your application (just after importing all modules)?
> 
> I haven't... now it works, thanks :) Any tips on how to avoid mistakes
> like that in the future? I'm somewhat confused as to how I was
> supposed to get this out of the documentation...

I'm afraid I don't know the answer. I'm not a pygtk expert at all, I
just remember that I had to do that in one of my applications long ago,
otherwise pygtk doesn't support Python threads properly.

Regards

Antoine.




From utente at esempio.net  Tue May 11 11:03:58 2010
From: utente at esempio.net (superpollo)
Date: Tue, 11 May 2010 17:03:58 +0200
Subject: Extract all words that begin with x
In-Reply-To: 
References: 
	
	
	
	
Message-ID: <4be971de$0$18659$4fafbaef@reader3.news.tin.it>

Aahz ha scritto:
> In article ,
> Terry Reedy   wrote:
>> On 5/10/2010 5:35 AM, James Mills wrote:
>>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho  wrote:
>>>> Have I missed something, or wouldn't this work just as well:
>>>>
>>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>> ['awes', 'asdgas']
>>> I would do this for completeness (just in case):
>>>
>>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>> Just guards against empty strings which may or may not be in the list.
>>  ... word[0:1] does the same thing. All Python programmers should learn 
>> to use slicing to extract a  char from a string that might be empty.
>> The method call of .startswith() will be slower, I am sure.
> 
> And if it is slower, so what?  Using startswith() makes for faster
> reading of the code for me, and I'm sure I'm not the only one.

also, what if the OP intended "words that begin with x" with x a string 
(as opposed to a single character) ?

then startswith is the solution methinks...

bye


From eckhardt at satorlaser.com  Tue May 11 11:08:02 2010
From: eckhardt at satorlaser.com (Ulrich Eckhardt)
Date: Tue, 11 May 2010 17:08:02 +0200
Subject: Iterating over dict and removing some elements
Message-ID: 

Hi!

I wrote a simple loop like this:

  d = {}
  ...
  for k in d:
      if some_condition(d[k]):
          d.pop(k)

If I run this, Python complains that the dictionary size changed during
iteration. I understand that the iterator relies on the internal structure
not changing, but how would I structure this loop otherwise?

My first approach was to simply postpone removing the elements, but I was
wondering if there was a more elegant solution.

Thanks!

Uli

-- 
Sator Laser GmbH
Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932



From stefan_ml at behnel.de  Tue May 11 11:11:50 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Tue, 11 May 2010 17:11:50 +0200
Subject: unable to get Hudson to run unit tests
In-Reply-To: <4BE96DB9.7040303@noaa.gov>
References: 		<4BE80A78.2030502@noaa.gov>		<4BE828A2.2070106@noaa.gov>	
	<4BE96DB9.7040303@noaa.gov>
Message-ID: 

j vickroy, 11.05.2010 16:46:
 > Stefan Behnel wrote:
>> No, what Hudson actually does, is, it writes your command(s) into a
>> text file and runs it with the system's shell interpreter (which,
>> unless otherwise configured, is "cmd.exe" on Windows).
>
> This is not the behavior I am experiencing on my Windows XP Pro (Service
> Pack 3) workstation.

Then setting the "Shell executable" to "cmd.exe" will do the right thing here.


>> This assures the highest
>> possible compatibility with the executed script. You can even use the
>> shebang in Hudson's scripts that way, so that you can execute scripts
>> in basically any scripting language.

... although the shebang isn't really supported by cmd.exe, I guess ...


>> The likely reason why it doesn't find your test results is that you
>> didn't tell it where to look.
>
> Actually, Hudson is not finding the tests results because they are not
> being generated. There is no "nosetests.xml" file anywhere on my hard
> drive

That's why I told you to configure nosetest to use an specific output path 
for the unit test file.


> Thanks again for your continued interest. I quickly got Hudson to
> retrieve job source from our subversion repository so I thought it would
> be equally easy to get Hudson to run the unit tests, but that has proven
> to be difficult, and so far I do not know how to diagnose this since it
> seems there is no way to prevent Hudson from immediately deleting the
> temporary scripts it generates.

Which is ok, since it prints what it does during the script execution, and 
the scripts contain nothing more than what you typed in.

Does nosetest produce an XML file when you call it manually from the 
command line? Is nosetest.exe in your PATH, so that the cmd.exe that Hudson 
starts can find it?

Personally, I'd always step into the target directory before running a 
command, so I'd make the script

     cd level-1
     nosetest.exe ...

Stefan



From utente at esempio.net  Tue May 11 11:13:50 2010
From: utente at esempio.net (superpollo)
Date: Tue, 11 May 2010 17:13:50 +0200
Subject: Slice last char from string without raising exception on empty
	string (Re: Extract all words that begin with x)
In-Reply-To: 
References: 	
	
Message-ID: <4be9742f$0$18659$4fafbaef@reader3.news.tin.it>

python at bdurham.com ha scritto:
> Terry,
> 
>>  ... word[0:1] does the same thing. All Python programmers should learn to use slicing to extract a char from a string that might be empty.
> 
> Is there an equivalent way to slice the last char from a string (similar
> to an .endswith) that doesn't raise an exception when a string is empty?
> 

could it be:

word[len(word)-1:] ?


From utente at esempio.net  Tue May 11 11:16:31 2010
From: utente at esempio.net (superpollo)
Date: Tue, 11 May 2010 17:16:31 +0200
Subject: Iterating over dict and removing some elements
In-Reply-To: 
References: 
Message-ID: <4be974cf$0$18659$4fafbaef@reader3.news.tin.it>

Ulrich Eckhardt ha scritto:
> Hi!
> 
> I wrote a simple loop like this:
> 
>   d = {}
>   ...
>   for k in d:
>       if some_condition(d[k]):
>           d.pop(k)
> 
> If I run this, Python complains that the dictionary size changed during
> iteration. I understand that the iterator relies on the internal structure
> not changing, but how would I structure this loop otherwise?

my first thought (untested):

use a copy of d for the if clause, then pop from the original.

bye


From michele.simionato at gmail.com  Tue May 11 11:21:07 2010
From: michele.simionato at gmail.com (Michele Simionato)
Date: Tue, 11 May 2010 08:21:07 -0700 (PDT)
Subject: Iterating over dict and removing some elements
References: 
	<4be974cf$0$18659$4fafbaef@reader3.news.tin.it>
Message-ID: 

Or you copy the whole dictionary or you just copy the keys:

for k in d.keys():
    ...

or

for k in list(d):
    ...


From peter_peyman_puk at yahoo.ca  Tue May 11 11:21:56 2010
From: peter_peyman_puk at yahoo.ca (Peyman Askari)
Date: Tue, 11 May 2010 08:21:56 -0700 (PDT)
Subject: PyMPI comm.gather problem
Message-ID: <180709.12854.qm@web43407.mail.sp1.yahoo.com>

Hi

I have run into a serious problem with PyMPI (Python bindings for the Message Passing Interface). Unfortunately I can not provide any example code as it is a massive program (38,000+ lines) and it is very difficult to break the program down due to multiple inheritance.

When I run the program (on multiple nodes), there is a linear increase in time per iteration. Every 1,500 iterations, it gains a tenth of a second per iteration. I timed different regions of my code which were engaged in messaging (broadcasting and gathering) and I found the increase to be in a gather statement, much like so

IO_list=self.comm.gather(IO,root=0)

each iteration this single command requires more and more time to pass information. I checked the size of IO being sent from every node (including root node) and it always remains constant. I also checked the size of the IO_list, and it too is always constant. Furthermore, I added a sleep(5) command before the line to make sure it was not a synchronization issue. 

Has anyone got any possible ideas as to what could possibly be going wrong? 

Cheers


Peyman Askari



-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From jim.vickroy at noaa.gov  Tue May 11 11:26:22 2010
From: jim.vickroy at noaa.gov (j vickroy)
Date: Tue, 11 May 2010 09:26:22 -0600
Subject: unable to get Hudson to run unit tests
In-Reply-To: 
References: 		<4BE80A78.2030502@noaa.gov>		<4BE828A2.2070106@noaa.gov>		<4BE96DB9.7040303@noaa.gov>
	
Message-ID: <4BE9771E.1040909@noaa.gov>

Stefan Behnel wrote:
> j vickroy, 11.05.2010 16:46:
>  > Stefan Behnel wrote:
>>> No, what Hudson actually does, is, it writes your command(s) into a
>>> text file and runs it with the system's shell interpreter (which,
>>> unless otherwise configured, is "cmd.exe" on Windows).
>>
>> This is not the behavior I am experiencing on my Windows XP Pro (Service
>> Pack 3) workstation.
> 
> Then setting the "Shell executable" to "cmd.exe" will do the right thing 
> here.
> 
> 
>>> This assures the highest
>>> possible compatibility with the executed script. You can even use the
>>> shebang in Hudson's scripts that way, so that you can execute scripts
>>> in basically any scripting language.
> 
> ... although the shebang isn't really supported by cmd.exe, I guess ...
> 
> 
>>> The likely reason why it doesn't find your test results is that you
>>> didn't tell it where to look.
>>
>> Actually, Hudson is not finding the tests results because they are not
>> being generated. There is no "nosetests.xml" file anywhere on my hard
>> drive
> 
> That's why I told you to configure nosetest to use an specific output 
> path for the unit test file.

OK, I will do this and report back.

> 
> 
>> Thanks again for your continued interest. I quickly got Hudson to
>> retrieve job source from our subversion repository so I thought it would
>> be equally easy to get Hudson to run the unit tests, but that has proven
>> to be difficult, and so far I do not know how to diagnose this since it
>> seems there is no way to prevent Hudson from immediately deleting the
>> temporary scripts it generates.
> 
> Which is ok, since it prints what it does during the script execution, 
> and the scripts contain nothing more than what you typed in.

Yes, and I am not seeing the nosetests.exe command listed anywhere in 
the Hudson console output.  This is why I do not think Hudson is 
executing it.

> 
> Does nosetest produce an XML file when you call it manually from the 
> command line? 

Yes it does.  The exact same command (specified for the Hudson job) 
works perfectly from a Windows console.

Is nosetest.exe in your PATH, so that the cmd.exe that
> Hudson starts can find it?

Yes, it is.  "C:\Python26\Scripts" is in PATH and that is where 
"nosetests.exe" is.
> 
> Personally, I'd always step into the target directory before running a 
> command, so I'd make the script
> 
>     cd level-1
>     nosetest.exe ...

OK, I will try this.

> 
> Stefan
> 


From utente at esempio.net  Tue May 11 11:26:29 2010
From: utente at esempio.net (superpollo)
Date: Tue, 11 May 2010 17:26:29 +0200
Subject: Iterating over dict and removing some elements
In-Reply-To: <4be974cf$0$18659$4fafbaef@reader3.news.tin.it>
References: 
	<4be974cf$0$18659$4fafbaef@reader3.news.tin.it>
Message-ID: <4be97725$0$18655$4fafbaef@reader3.news.tin.it>

superpollo ha scritto:
> Ulrich Eckhardt ha scritto:
>> Hi!
>>
>> I wrote a simple loop like this:
>>
>>   d = {}
>>   ...
>>   for k in d:
>>       if some_condition(d[k]):
>>           d.pop(k)
>>
>> If I run this, Python complains that the dictionary size changed during
>> iteration. I understand that the iterator relies on the internal 
>> structure
>> not changing, but how would I structure this loop otherwise?
> 
> my first thought (untested):
> 
> use a copy of d for the if clause, then pop from the original.
> 
> bye

i mean:

 >>> d = {"name":"max","surname":"zanardi","nick":"zanna"}
 >>> dc = copy.copy(d)
 >>> dc
{'nick': 'zanna', 'surname': 'zanardi', 'name': 'max'}
 >>> for k in dc:
...     if dc[k].startswith("z"):
...         d.pop(k)
...
'zanna'
'zanardi'
 >>> d
{'name': 'max'}
 >>> dc
{'nick': 'zanna', 'surname': 'zanardi', 'name': 'max'}
 >>>

bye


From malaclypse2 at gmail.com  Tue May 11 11:29:34 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Tue, 11 May 2010 11:29:34 -0400
Subject: Iterating over dict and removing some elements
In-Reply-To: 
References: 
Message-ID: 

On Tue, May 11, 2010 at 11:08 AM, Ulrich Eckhardt
 wrote:
> My first approach was to simply postpone removing the elements, but I was
> wondering if there was a more elegant solution.

Iterate over something other than the actual dictionary, like this:

d = {1: 'one', 2: 'two', 3: 'three'}

for k in d.keys():
    if d[k] == 'two':
        d.pop(k)


-- 
Jerry


From malaclypse2 at gmail.com  Tue May 11 11:32:22 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Tue, 11 May 2010 11:32:22 -0400
Subject: Slice last char from string without raising exception on empty 
	string (Re: Extract all words that begin with x)
In-Reply-To: <1273588621.1629.1374510539@webmail.messagingengine.com>
References: 
	
	
	
	
	<1273588621.1629.1374510539@webmail.messagingengine.com>
Message-ID: 

On Tue, May 11, 2010 at 10:37 AM,   wrote:
> Is there an equivalent way to slice the last char from a string (similar
> to an .endswith) that doesn't raise an exception when a string is empty?

If you use negative indexes in the slice, they refer to items from the
end of the sequence instead of the front.  So slicing the last
character from the string would be:

word[-1:]

-- 
Jerry


From jim.vickroy at noaa.gov  Tue May 11 11:42:55 2010
From: jim.vickroy at noaa.gov (j vickroy)
Date: Tue, 11 May 2010 09:42:55 -0600
Subject: unable to get Hudson to run unit tests
In-Reply-To: 
References: 		<4BE80A78.2030502@noaa.gov>		<4BE828A2.2070106@noaa.gov>		<4BE96DB9.7040303@noaa.gov>
	
Message-ID: <4BE97AFF.5080903@noaa.gov>

Stefan Behnel wrote:
> j vickroy, 11.05.2010 16:46:
>  > Stefan Behnel wrote:
>>> No, what Hudson actually does, is, it writes your command(s) into a
>>> text file and runs it with the system's shell interpreter (which,
>>> unless otherwise configured, is "cmd.exe" on Windows).
>>
>> This is not the behavior I am experiencing on my Windows XP Pro (Service
>> Pack 3) workstation.
> 
> Then setting the "Shell executable" to "cmd.exe" will do the right thing 
> here.
> 
> 
>>> This assures the highest
>>> possible compatibility with the executed script. You can even use the
>>> shebang in Hudson's scripts that way, so that you can execute scripts
>>> in basically any scripting language.
> 
> ... although the shebang isn't really supported by cmd.exe, I guess ...
> 
> 
>>> The likely reason why it doesn't find your test results is that you
>>> didn't tell it where to look.
>>
>> Actually, Hudson is not finding the tests results because they are not
>> being generated. There is no "nosetests.xml" file anywhere on my hard
>> drive
> 
> That's why I told you to configure nosetest to use an specific output 
> path for the unit test file.
> 
> 
>> Thanks again for your continued interest. I quickly got Hudson to
>> retrieve job source from our subversion repository so I thought it would
>> be equally easy to get Hudson to run the unit tests, but that has proven
>> to be difficult, and so far I do not know how to diagnose this since it
>> seems there is no way to prevent Hudson from immediately deleting the
>> temporary scripts it generates.
> 
> Which is ok, since it prints what it does during the script execution, 
> and the scripts contain nothing more than what you typed in.
> 
> Does nosetest produce an XML file when you call it manually from the 
> command line? Is nosetest.exe in your PATH, so that the cmd.exe that 
> Hudson starts can find it?
> 
> Personally, I'd always step into the target directory before running a 
> command, so I'd make the script
> 
>     cd level-1
>     nosetest.exe ...
> 
> Stefan
> 

Here are the Hudson job | Configure | Execute shell | Command inputs:

------------------------------------------------------------------
cd level-1
dir
nosetests.exe --with-xunit --xunit-file=nosetests.xml --verbose
------------------------------------------------------------------
#!python.exe
####print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO'
import os ; print 'os.getcwd():',os.getcwd(); print 
'os.listdir(os.getcwd()):',os.listdir(os.getcwd())
------------------------------------------------------------------


and here is the Hudson Console Output:

--------------------------------------------------------------------------------------
Started by user anonymous
Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1
At revision 3417
no change for svn://vm-svn/GOES data 
processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build
[workspace] $ C:\WINDOWS\system32\cmd.exe -xe 
C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2208088016039194869.sh
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI 
Level-1 Products Generation\workspace>[workspace] $ python.exe 
C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson6398132145818001258.sh
os.getcwd(): C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 
13-15 SXI Level-1 Products Generation\workspace
os.listdir(os.getcwd()): ['level-1']
Recording test results
No test report files were found. Configuration error?
Finished: FAILURE
--------------------------------------------------------------------------------------


There is no nosetests.xml file anywhere on my hard drive (except as 
previously noted in the Recycle Bin).

 From the above Console Output, I see no evidence that the nosetests.exe 
command was ever executed.


From python at bdurham.com  Tue May 11 12:01:38 2010
From: python at bdurham.com (python at bdurham.com)
Date: Tue, 11 May 2010 12:01:38 -0400
Subject: Slice last char from string without raising exception on empty 
	string (Re: Extract all words that begin with x)
In-Reply-To: <4be9742f$0$18659$4fafbaef@reader3.news.tin.it>
References: 
	
	<4be9742f$0$18659$4fafbaef@reader3.news.tin.it>
Message-ID: <1273593698.18399.1374527347@webmail.messagingengine.com>

Superpollo,

> word[len(word)-1:] 

Perfect! Thank you,

Malcolm


From python at bdurham.com  Tue May 11 12:05:48 2010
From: python at bdurham.com (python at bdurham.com)
Date: Tue, 11 May 2010 12:05:48 -0400
Subject: Slice last char from string without raising exception on empty 
	string (Re: Extract all words that begin with x)
In-Reply-To: 
References: <1273588621.1629.1374510539@webmail.messagingengine.com>
	
Message-ID: <1273593948.19179.1374528335@webmail.messagingengine.com>

Jerry,

> If you use negative indexes in the slice, they refer to items from the end of the sequence instead of the front. So slicing the last character from the string would be:
> 
> word[-1:]

Perfect! Thank you,

Malcolm


From cde3 at live.com  Tue May 11 12:08:45 2010
From: cde3 at live.com (Sandy Sandy)
Date: Tue, 11 May 2010 21:08:45 +0500
Subject: plot debugging problem
Message-ID: 


Hi friends

pls help with debugging problem

the mutter is:

during debugging the  debug processes stacks when fig is created

for example, in code



import random



import matplotlib.pyplot as plt

from pylab import *





x= 23;

y = 111111;

print(23456)

plt.plot(range(10))



plot([1,2,3])

show()



print(11111111)



a=888



it is impossible after show() to continue debug

as stated in

Beginning Python Visualization - Crafting Visual Transformation Scripts 
(2009)

page  187



Note If you?re not using matplotlib interactively in Python, be sure

to call the function show() after all

graphs have been generated, as it enters a user interface main loop

that will stop execution of the rest of

your code. The reason behind this behavior is that matplotlib is

designed to be embedded in a GUI as well.

In Windows, if you?re working from interactive Python, you need only

issue show() once; close the figures

(or figures) to return to the shell. Subsequent plots will be drawn

automatically without issuing show(), and

you?ll be able to plot graphs interactively.



Best Regards

Sandy 		 	   		  
_________________________________________________________________
Hotmail: Free, trusted and rich email service.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From cde3 at live.com  Tue May 11 12:26:13 2010
From: cde3 at live.com (Sandy Sandy)
Date: Tue, 11 May 2010 21:26:13 +0500
Subject: graphs in Python during debugging
Message-ID: 




Hi friends

Can you help pls  to find how to plot graphs in Python
during debugging without destroying figures to continue to debug

the mutter is:

during debugging the  debug processes stacks when fig is created

for example, in code

import random

import matplotlib.pyplot as plt

from pylab import *

x= 23;

y = 111111;

print(23456)

plt.plot(range(10))

plot([1,2,3])

show()

print(11111111)

a=888



it is impossible after show() to continue debug

as stated in

Beginning Python Visualization - Crafting Visual Transformation Scripts (2009)

page  187



Note If you?re not using matplotlib interactively in Python, be sure

to call the function show() after all

graphs have been generated, as it enters a user interface main loop

that will stop execution of the rest of

your code. The reason behind this behavior is that matplotlib is

designed to be embedded in a GUI as well.

In Windows, if you?re working from interactive Python, you need only

issue show() once; close the figures

(or figures) to return to the shell. Subsequent plots will be drawn

automatically without issuing show(), and

you?ll be able to plot graphs interactively.



Best Regards

Sandy

 		 	   		  
_________________________________________________________________
Your E-mail and More On-the-Go. Get Windows Live Hotmail Free.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From prologic at shortcircuit.net.au  Tue May 11 12:35:36 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Wed, 12 May 2010 02:35:36 +1000
Subject: Slice last char from string without raising exception on empty 
	string (Re: Extract all words that begin with x)
In-Reply-To: <1273593698.18399.1374527347@webmail.messagingengine.com>
References: 
	 
	 
	
	 
	
	<4be9742f$0$18659$4fafbaef@reader3.news.tin.it> 
	<1273593698.18399.1374527347@webmail.messagingengine.com>
Message-ID: 

On Wed, May 12, 2010 at 2:01 AM,   wrote:
>> word[len(word)-1:]

This works just as well:

>>> word[-1:]

cheers
James


From utente at esempio.net  Tue May 11 12:39:42 2010
From: utente at esempio.net (superpollo)
Date: Tue, 11 May 2010 18:39:42 +0200
Subject: Slice last char from string without raising exception on empty
	string (Re: Extract all words that begin with x)
In-Reply-To: 
References: 	
	
		
		<4be9742f$0$18659$4fafbaef@reader3.news.tin.it>
	<1273593698.18399.1374527347@webmail.messagingengine.com>
	
Message-ID: <4be9884f$0$18652$4fafbaef@reader3.news.tin.it>

James Mills ha scritto:
> On Wed, May 12, 2010 at 2:01 AM,   wrote:
>>> word[len(word)-1:]
> 
> This works just as well:
> 
>>>> word[-1:]

d'uh. ;-)


From stefan_ml at behnel.de  Tue May 11 12:46:37 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Tue, 11 May 2010 18:46:37 +0200
Subject: unable to get Hudson to run unit tests
In-Reply-To: <4BE97AFF.5080903@noaa.gov>
References: 		<4BE80A78.2030502@noaa.gov>		<4BE828A2.2070106@noaa.gov>		<4BE96DB9.7040303@noaa.gov>	
	<4BE97AFF.5080903@noaa.gov>
Message-ID: 

j vickroy, 11.05.2010 17:42:
> Here are the Hudson job | Configure | Execute shell | Command inputs:
>
> ------------------------------------------------------------------
> cd level-1
> dir
> nosetests.exe --with-xunit --xunit-file=nosetests.xml --verbose
> ------------------------------------------------------------------
> #!python.exe
> ####print 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO'
> import os ; print 'os.getcwd():',os.getcwd(); print
> 'os.listdir(os.getcwd()):',os.listdir(os.getcwd())
> ------------------------------------------------------------------
>
>
> and here is the Hudson Console Output:
>
> --------------------------------------------------------------------------------------
>
> Started by user anonymous
> Updating svn://vm-svn/GOES data processing/trunk/GOES/13,14,15/SXI/level-1
> At revision 3417
> no change for svn://vm-svn/GOES data
> processing/trunk/GOES/13,14,15/SXI/level-1 since the previous build
> [workspace] $ C:\WINDOWS\system32\cmd.exe -xe
> C:\DOCUME~1\JIM~1.VIC\LOCALS~1\Temp\hudson2208088016039194869.sh
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
>
> C:\Documents and Settings\jim.vickroy\.hudson\jobs\GOES 13-15 SXI
> Level-1 Products Generation\workspace>[workspace] $ python.exe

This is telling. It doesn't properly execute the cmd.exe shell. Maybe you 
have to configure the shell setup somehow to make it accept MS's cmd.exe? 
Note that cmd.exe isn't really what I'd call a "shell", so you may have to 
put some work into getting it to run your scripts.

You can also try to add a shebang "#!cmd.exe" to the script, it seems like 
Hudson interprets that by itself. Or execute nosetest from a Python script, 
just check what the nosetest main script is doing and do the same in a 
Python script.

Disclaimer: I never used Hudson on MS Windows, and I'm happy I don't have to.

Stefan



From amphioxus at yahoo.com  Tue May 11 12:57:01 2010
From: amphioxus at yahoo.com (Armin)
Date: Tue, 11 May 2010 09:57:01 -0700
Subject: Problem displaying jpgs in Tkinter via PIL
References: <2010051014011093749-amphioxus@yahoocom>
Message-ID: <2010051109570184033-amphioxus@yahoocom>

Never mind, I gave up on Tkinter and have switched to wxPython now. 
Getting jpg images to display in a wx frame worked like a charm... (As 
I said, I'm very new to Python, so I didn't really know what my options 
for GUI programming were.)

It seems like the ImageTk module on the Enthought distribution on my 
Mac is broken, but I can't figure out how to fix that. (I wiped my 
python installations and did a re-install, all to no avail.) As long as 
I don't need Tkinter for the GUI I'm envisioning, I don't really care 
however.



On 2010-05-10 14:01:10 -0700, Armin said:

> I'm new to Python and have been playing around with it using the 
> Enthought Python distribution for Mac OS X 10.6.3 (EPD academic 
> license, version 6.1 with python 2.6.4).
> 
> It's been great learning the basics, but I've started running into 
> problems when I'm trying to use the PIL library with Tkinter. All I'm 
> trying to do is display a JPG as a Tkinter label:
> 
> It all works fine when I'm just using GIF images through Tkinter's 
> photoimage object, but as soon as I'm trying to convert an image 
> through ImageTk, I get the following error:
> 
> ImportError: 
> dlopen(/Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/PIL/_imagingtk.so, 
> 2): Library not loaded: /System at rpath/Tcl Referenced from: 
> /Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/PIL/_imagingtk.so 
> Reason: image not found
> 
> I have no idea what that means, but I've always assumed the EPD 
> includes all the stuff that's needed to make Tkinter work with PIL.
> Any advice would be greatly appreciated. Thanks!




From solipsis at pitrou.net  Tue May 11 13:08:01 2010
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Tue, 11 May 2010 19:08:01 +0200
Subject: Problem displaying jpgs in Tkinter via PIL
References: <2010051014011093749-amphioxus@yahoocom>
	<2010051109570184033-amphioxus@yahoocom>
Message-ID: <20100511190801.51b8fdb4@pitrou.net>

On Tue, 11 May 2010 09:57:01 -0700
Armin  wrote:
> Never mind, I gave up on Tkinter and have switched to wxPython now. 
> Getting jpg images to display in a wx frame worked like a charm... (As 
> I said, I'm very new to Python, so I didn't really know what my options 
> for GUI programming were.)

You might also want to try PyQT, which is often considered more modern
than wxPython (I've never tried it, though).

Regards

Antoine.




From phlip2005 at gmail.com  Tue May 11 13:22:03 2010
From: phlip2005 at gmail.com (Phlip)
Date: Tue, 11 May 2010 10:22:03 -0700 (PDT)
Subject: lame sphinx questions [Was: lame epydoc questions]
References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com> 
	
	<4f11b7a0-1737-48d3-8dff-c7a9938ed1c5@32g2000prq.googlegroups.com>
	<289a3542-9e2f-46eb-b19b-e550ed16c244@34g2000prs.googlegroups.com> 
	
	<656fab1f-2cb7-433e-84ba-ffebbc118dde@t26g2000prt.googlegroups.com>
	
Message-ID: <8a7e019a-4606-417c-b7c7-c4ee14b5d172@r21g2000prr.googlegroups.com>

> epydoc supports reStructured text markups.

Oh, good. For a moment there, I thought I'd be stuck with a markup
language that was persnickety!


From landimatte at gmail.com  Tue May 11 13:46:27 2010
From: landimatte at gmail.com (Matteo Landi)
Date: Tue, 11 May 2010 19:46:27 +0200
Subject: plot debugging problem
In-Reply-To: 
References: 
Message-ID: 

I imagine you have to create a separate thread for it. Just thoughts.

On Tue, May 11, 2010 at 6:08 PM, Sandy Sandy  wrote:
> Hi friends
> pls help with debugging problem
> the mutter is:
> during debugging the ?debug processes stacks when fig is created
> for example, in code
>
> import random
>
> import matplotlib.pyplot as plt
> from pylab import *
>
>
> x= 23;
> y = 111111;
> print(23456)
> plt.plot(range(10))
>
> plot([1,2,3])
> show()
>
> print(11111111)
>
> a=888
>
> it is impossible after show() to continue debug
> as stated in
> Beginning Python Visualization - Crafting Visual Transformation Scripts
> (2009)
> page ?187
>
> Note If you?re not using matplotlib interactively in Python, be sure
> to call the function show() after all
> graphs have been generated, as it enters a user interface main loop
> that will stop execution of the rest of
> your code. The reason behind this behavior is that matplotlib is
> designed to be embedded in a GUI as well.
> In Windows, if you?re working from interactive Python, you need only
> issue show() once; close the figures
> (or figures) to return to the shell. Subsequent plots will be drawn
> automatically without issuing show(), and
> you?ll be able to plot graphs interactively.
>
> Best Regards
> Sandy
> ________________________________
> Hotmail: Free, trusted and rich email service. Get it now.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



-- 
Matteo Landi
http://www.matteolandi.net/


From dweimer at ORSCHELN.com  Tue May 11 14:02:00 2010
From: dweimer at ORSCHELN.com (Dean Weimer)
Date: Tue, 11 May 2010 13:02:00 -0500
Subject: Pythonw.exe randomly crashing
Message-ID: 

Hi, I have a python application I wrote that is randomly crashing, I was
wondering if anyone else has ran into this error, or if anyone has any
idea about how to fix it.  This is currently running under Windows
server 2008 R2 x64 in terminal services, with Python 2.6.4 x64
installed.  I ran into this problem with previous versions of Python on
windows 2003 server running under 32 bit.  I have been unable to
duplicate the error under a devolvement platform.  The application is a
simple GUI used for time clock stations on a shop floor; it has a
multithreaded GUI which displays some rotating informational images.  A
Text box that displays a constantly updating clock, and a text box that
accepts employee clock number input and one that displays results
returned from a background thread that runs a telnet session to a
server.  I can't really tell you where the error is occurring within the
actual code, as it takes days of the application running to happen.

Does anyone have any suggestions as to how I can get it to give me more
information about the crash?

 

Log Name:      Application

Source:        Application Error

Date:          5/6/2010 3:33:40 PM

Event ID:      1000

Task Category: (100)

Level:         Error

Keywords:      Classic

User:          N/A

Description:

Faulting application name: pythonw.exe, version: 0.0.0.0, time stamp:
0x4ba3b0d9

Faulting module name: tcl85.dll, version: 8.5.2.2, time stamp:
0x48515e43

Exception code: 0xc0000005

Fault offset: 0x000000000005863d

Faulting process id: 0xa98

Faulting application start time: 0x01cae87cff98c7c4

Faulting application path: C:\Python26\pythonw.exe

Faulting module path: C:\Python26\DLLs\tcl85.dll

Report Id: a7a18c68-594e-11df-b65f-005056b55389

 

 

Thanks,

     Dean Weimer

     Network Administrator

     Orscheln Management Co

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From tjreedy at udel.edu  Tue May 11 14:13:19 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 14:13:19 -0400
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 	<7xvdavd4bq.fsf@ruckus.brouhaha.com>
	
Message-ID: 

On 5/11/2010 7:11 AM, Lawrence D'Oliveiro wrote:
> In message<7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote:
>
>> Python is a pragmatic language from an imperative tradition ...
>
> I thought the opposite of ?functional? was ?procedural?, not ?imperative?.
> The opposite to the latter is ?declarative?. But (nearly) all procedural
> languages also have declarative constructs, not just imperative ones
> (certainly Python does).

Python has only two: 'global' and now 'nonlocal'.
There are also two meta-declarations: the coding cookie (which 
would/will go away in an entirely unicode world) and future imports 
(which are effectively temporarily gone in 3.x until needed again).

Newbies sometimes trip over def and class being imperative (executable) 
statments rather than declarations.

Terry Jan Reedy





From tjreedy at udel.edu  Tue May 11 14:16:50 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 14:16:50 -0400
Subject: inherit from data type
In-Reply-To: <201005111351.46892.richard.lamboj@bilcom.at>
References: 		<26lnb7-t6g.ln1@satorlaser.homedns.org>
	<201005111351.46892.richard.lamboj@bilcom.at>
Message-ID: 

On 5/11/2010 7:51 AM, Richard Lamboj wrote:

> I just want to test what is possible with python and what not. There is no
> problem that i need to solve.
>
> This is what i'am searching for:
> http://docs.python.org/reference/datamodel.html
>
> Last year i have stopped programming python, but now i'am back with a big
> black hole in my brain and i want to understand what the interpreter is doing
> in the background.

I suggest you (re)read and try examples in the Tutorial. It covers the 
basic syntax pretty well.



From alan.isaac at gmail.com  Tue May 11 14:33:12 2010
From: alan.isaac at gmail.com (Alan G Isaac)
Date: Tue, 11 May 2010 14:33:12 -0400
Subject: documentation bug? (format spec mini language)
Message-ID: 

The documentation at http://docs.python.org/py3k/library/string.html#format-specification-mini-language

         '<' Forces the field to be left-aligned within the available space (This is the default.)

The conflicting example::

         >>> format(3.2,'10.5f')
         '   3.20000'
         >>> format(3.2,'<10.5f')
         '3.20000   '

Am I somehow misreading the documentation?

Thanks,
Alan Isaac




From landimatte at gmail.com  Tue May 11 14:37:39 2010
From: landimatte at gmail.com (Matteo Landi)
Date: Tue, 11 May 2010 20:37:39 +0200
Subject: plot debugging problem
In-Reply-To: 
References: 
	 
	
Message-ID: 

Well, I cannot tell you how to do that in a precise way, but googling
a bit I found this (expecially the second example):

http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/

Take a look also at the Matplotlib cookbook:

http://www.scipy.org/Cookbook/Matplotlib

ps. when you answer back, remember to include the list, or the flow will be cut!

On Tue, May 11, 2010 at 7:49 PM, Sandy Sandy  wrote:
> great!!!
> how to do it?
>
> this way it is not working:
>
> from pylab import plot,show,close
> x = range(10)
> plot(x)
> from threading import Timer
> t = Timer(0, show)
> t.start()
>
> y = [2, 8, 3, 9, 4]
> plot(y)
> close()
>
> Best Regards
> Sandy
>
>
>
>
>
>
>
>
>
>
>
>
>
>> From: landimatte at gmail.com
>> Date: Tue, 11 May 2010 19:46:27 +0200
>> Subject: Re: plot debugging problem
>> To: cde3 at live.com
>> CC: python-list at python.org
>>
>> I imagine you have to create a separate thread for it. Just thoughts.
>>
>> On Tue, May 11, 2010 at 6:08 PM, Sandy Sandy  wrote:
>> > Hi friends
>> > pls help with debugging problem
>> > the mutter is:
>> > during debugging the ?debug processes stacks when fig is created
>> > for example, in code
>> >
>> > import random
>> >
>> > import matplotlib.pyplot as plt
>> > from pylab import *
>> >
>> >
>> > x= 23;
>> > y = 111111;
>> > print(23456)
>> > plt.plot(range(10))
>> >
>> > plot([1,2,3])
>> > show()
>> >
>> > print(11111111)
>> >
>> > a=888
>> >
>> > it is impossible after show() to continue debug
>> > as stated in
>> > Beginning Python Visualization - Crafting Visual Transformation Scripts
>> > (2009)
>> > page ?187
>> >
>> > Note If you?re not using matplotlib interactively in Python, be sure
>> > to call the function show() after all
>> > graphs have been generated, as it enters a user interface main loop
>> > that will stop execution of the rest of
>> > your code. The reason behind this behavior is that matplotlib is
>> > designed to be embedded in a GUI as well.
>> > In Windows, if you?re working from interactive Python, you need only
>> > issue show() once; close the figures
>> > (or figures) to return to the shell. Subsequent plots will be drawn
>> > automatically without issuing show(), and
>> > you?ll be able to plot graphs interactively.
>> >
>> > Best Regards
>> > Sandy
>> > ________________________________
>> > Hotmail: Free, trusted and rich email service. Get it now.
>> > --
>> > http://mail.python.org/mailman/listinfo/python-list
>> >
>> >
>>
>>
>>
>> --
>> Matteo Landi
>> http://www.matteolandi.net/
>
> ________________________________
> Hotmail: Powerful Free email with security by Microsoft. Get it now.



-- 
Matteo Landi
http://www.matteolandi.net/


From tjreedy at udel.edu  Tue May 11 14:42:00 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 14:42:00 -0400
Subject: How to make this doctest work?
In-Reply-To: 
References: 
Message-ID: 

On 5/11/2010 5:29 AM, Xie&Tian wrote:
> Hello
>
> I ran across this accidentally and wonders how to make the doctest in
> following code snippet work:
>
>
> import doctest
>
> def a():
>       """
>      >>>  a = '\\r\\n'
>      >>>  print a
>
>
>      No matter how many blank lines I add here, it just can't get enough -_-
>      """
>      pass
>
> doctest.testmod()
>
>
>
> ps: I want variable "a" to be '\r\n', but python kept telling me
>          ValueError: line 4 of the docstring has inconsistent leading
> whitespace: "'"
>      Why can't doctest module deal with statement "a='\r\n'"?

You should post (copy and paste) entire error messages.
The problem is with the print statement, not the assignment.
I would prefix the docstring with r instead doubling \s within it.
The point of doctest is to imitate what one would get with the 
interactive interpreter. However, literally entering what you have 
within the doc string does (3.1)

 >>> a = '\\r\\n'
 >>> print(a)
\r\n
 >>>

Terry Jan Reedy





From backgoodoo at gmail.com  Tue May 11 15:06:36 2010
From: backgoodoo at gmail.com (Back9)
Date: Tue, 11 May 2010 12:06:36 -0700 (PDT)
Subject: default argument
Message-ID: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>

Hi,

Is this grammer working in Python?

class test:
  self._value = 10
  def func(self, self._value)

When i try it, it complains about undefined self.

i don't know why.

TIA


From backgoodoo at gmail.com  Tue May 11 15:08:04 2010
From: backgoodoo at gmail.com (Back9)
Date: Tue, 11 May 2010 12:08:04 -0700 (PDT)
Subject: default argument
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
Message-ID: <7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>

On May 11, 3:06?pm, Back9  wrote:
> Hi,
>
> Is this grammer working in Python?
>
> class test:
> ? self._value = 10
> ? def func(self, self._value)
>
> When i try it, it complains about undefined self.
>
> i don't know why.
>
> TIA

Sorry
here is the what i meant
class test:
  self._value = 10
  def func(self, pos = self._value)



From landimatte at gmail.com  Tue May 11 15:11:06 2010
From: landimatte at gmail.com (Matteo Landi)
Date: Tue, 11 May 2010 21:11:06 +0200
Subject: plot debugging problem
In-Reply-To: 
References: 
	 
	
	 
	
Message-ID: 

On Tue, May 11, 2010 at 8:59 PM, Sandy Sandy  wrote:
>
> 1
>
> remember to include the list,
>
> what does it mean??

I mean that you are leaving out the mlist from your answers. Instead
of press _reply_, look for a _reply-to-all_ button.

>
> 2
>
> do you mean
>
> Pseudo Color Plots
>
> in
>
> http://www.scipy.org/Cookbook/Matplotlib
>
> ??
>
> 3
>
> could you pls clarify what to see in
>
> http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/
>
>
> http://www.scipy.org/Cookbook/Matplotlib
>

As I stated in the previous email, I have no experience with
matplotlib, but in the first link I posted there is an example on how
to integrate matplotlib within a wxpython application. You can start
from it, and look how to attach plot within a gui mailoop.

> S
>
> Well, I cannot tell you how to do that in a precise way, but googling
> a bit I found this (expecially the second example):
>
> http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/
>
> Take a look also at the Matplotlib cookbook:
>
> http://www.scipy.org/Cookbook/Matplotlib
>
> ps. when you answer back, remember to include the list, or the flow will be
> cut!
>
> On Tue, May 11, 2010 at 7:49 PM, Sandy Sandy  wrote:
>> great!!!
>> how to do it?
>>
>> this way it is not working:
>>
>> from pylab import plot,show,close
>> x = range(10)
>> plot(x)
>> from threading import Timer
>> t = Timer(0, show)
>> t.start()
>>
>> y = [2, 8, 3, 9, 4]
>> plot(y)
>> close()
>>
>> Best Regards
>> Sandy
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>> From: landimatte at gmail.com
>>> Date: Tue, 11 May 2010 19:46:27 +0200
>>> Subject: Re: plot debugging problem
>>> To: cde3 at live.com
>>> CC: python-list at python.org
>>>
>>> I imagine you have to create a separate thread for it. Just thoughts.
>>>
>>> On Tue, May 11, 2010 at 6:08 PM, Sandy Sandy  wrote:
>>> > Hi friends
>>> > pls help with debugging problem
>>> > the mutter is:
>>> > during debugging the ?debug processes stacks when fig is created
>>> > for example, in code
>>> >
>>> > import random
>>> >
>>> > import matplotlib.pyplot as plt
>>> > from pylab import *
>>> >
>>> >
>>> > x= 23;
>>> > y = 111111;
>>> > print(23456)
>>> > plt.plot(range(10))
>>> >
>>> > plot([1,2,3])
>>> > show()
>>> >
>>> > print(11111111)
>>> >
>>> > a=888
>>> >
>>> > it is impossible after show() to continue debug
>>> > as stated in
>>> > Beginning Python Visualization - Crafting Visual Transformation Scripts
>>> > (2009)
>>> > page ?187
>>> >
>>> > Note If you?re not using matplotlib interactively in Python, be sure
>>> > to call the function show() after all
>>> > graphs have been generated, as it enters a user interface main loop
>>> > that will stop execution of the rest of
>>> > your code. The reason behind this behavior is that matplotlib is
>>> > designed to be embedded in a GUI as well.
>>> > In Windows, if you?re working from interactive Python, you need only
>>> > issue show() once; close the figures
>>> > (or figures) to return to the shell. Subsequent plots will be drawn
>>> > automatically without issuing show(), and
>>> > you?ll be able to plot graphs interactively.
>>> >
>>> > Best Regards
>>> > Sandy
>>> > ________________________________
>>> > Hotmail: Free, trusted and rich email service. Get it now.
>>> > --
>>> > http://mail.python.org/mailman/listinfo/python-list
>>> >
>>> >
>>>
>>>
>>>
>>> --
>>> Matteo Landi
>>> http://www.matteolandi.net/
>>
>> ________________________________
>> Hotmail: Powerful Free email with security by Microsoft. Get it now.
>
>
>
> --
> Matteo Landi
> http://www.matteolandi.net/
>
>
>> From: landimatte at gmail.com
>> Date: Tue, 11 May 2010 20:37:39 +0200
>> Subject: Re: plot debugging problem
>> To: cde3 at live.com
>> CC: python-list at python.org
>>
>> Well, I cannot tell you how to do that in a precise way, but googling
>> a bit I found this (expecially the second example):
>>
>> http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/
>>
>> Take a look also at the Matplotlib cookbook:
>>
>> http://www.scipy.org/Cookbook/Matplotlib
>>
>> ps. when you answer back, remember to include the list, or the flow will
>> be cut!
>>
>> On Tue, May 11, 2010 at 7:49 PM, Sandy Sandy  wrote:
>> > great!!!
>> > how to do it?
>> >
>> > this way it is not working:
>> >
>> > from pylab import plot,show,close
>> > x = range(10)
>> > plot(x)
>> > from threading import Timer
>> > t = Timer(0, show)
>> > t.start()
>> >
>> > y = [2, 8, 3, 9, 4]
>> > plot(y)
>> > close()
>> >
>> > Best Regards
>> > Sandy
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> >> From: landimatte at gmail.com
>> >> Date: Tue, 11 May 2010 19:46:27 +0200
>> >> Subject: Re: plot debugging problem
>> >> To: cde3 at live.com
>> >> CC: python-list at python.org
>> >>
>> >> I imagine you have to create a separate thread for it. Just thoughts.
>> >>
>> >> On Tue, May 11, 2010 at 6:08 PM, Sandy Sandy  wrote:
>> >> > Hi friends
>> >> > pls help with debugging problem
>> >> > the mutter is:
>> >> > during debugging the ?debug processes stacks when fig is created
>> >> > for example, in code
>> >> >
>> >> > import random
>> >> >
>> >> > import matplotlib.pyplot as plt
>> >> > from pylab import *
>> >> >
>> >> >
>> >> > x= 23;
>> >> > y = 111111;
>> >> > print(23456)
>> >> > plt.plot(range(10))
>> >> >
>> >> > plot([1,2,3])
>> >> > show()
>> >> >
>> >> > print(11111111)
>> >> >
>> >> > a=888
>> >> >
>> >> > it is impossible after show() to continue debug
>> >> > as stated in
>> >> > Beginning Python Visualization - Crafting Visual Transformation
>> >> > Scripts
>> >> > (2009)
>> >> > page ?187
>> >> >
>> >> > Note If you?re not using matplotlib interactively in Python, be sure
>> >> > to call the function show() after all
>> >> > graphs have been generated, as it enters a user interface main loop
>> >> > that will stop execution of the rest of
>> >> > your code. The reason behind this behavior is that matplotlib is
>> >> > designed to be embedded in a GUI as well.
>> >> > In Windows, if you?re working from interactive Python, you need only
>> >> > issue show() once; close the figures
>> >> > (or figures) to return to the shell. Subsequent plots will be drawn
>> >> > automatically without issuing show(), and
>> >> > you?ll be able to plot graphs interactively.
>> >> >
>> >> > Best Regards
>> >> > Sandy
>> >> > ________________________________
>> >> > Hotmail: Free, trusted and rich email service. Get it now.
>> >> > --
>> >> > http://mail.python.org/mailman/listinfo/python-list
>> >> >
>> >> >
>> >>
>> >>
>> >>
>> >> --
>> >> Matteo Landi
>> >> http://www.matteolandi.net/
>> >
>> > ________________________________
>> > Hotmail: Powerful Free email with security by Microsoft. Get it now.
>>
>>
>>
>> --
>> Matteo Landi
>> http://www.matteolandi.net/
>
> ________________________________
> Hotmail: Powerful Free email with security by Microsoft. Get it now.



-- 
Matteo Landi
http://www.matteolandi.net/


From python at mrabarnett.plus.com  Tue May 11 15:19:53 2010
From: python at mrabarnett.plus.com (MRAB)
Date: Tue, 11 May 2010 20:19:53 +0100
Subject: documentation bug? (format spec mini language)
In-Reply-To: 
References: 
Message-ID: <4BE9ADD9.9030901@mrabarnett.plus.com>

Alan G Isaac wrote:
> The documentation at 
> http://docs.python.org/py3k/library/string.html#format-specification-mini-language 
> 
> 
>         '<' Forces the field to be left-aligned within the available 
> space (This is the default.)
> 
> The conflicting example::
> 
>         >>> format(3.2,'10.5f')
>         '   3.20000'
>         >>> format(3.2,'<10.5f')
>         '3.20000   '
> 
> Am I somehow misreading the documentation?
> 
It does look misleading. Numbers default to right-aligned, as you
discovered.

You usually want numbers to be right-aligned so that the decimal points
line up when writing a columns of them.


From clp2 at rebertia.com  Tue May 11 15:20:26 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Tue, 11 May 2010 12:20:26 -0700
Subject: default argument
In-Reply-To: <7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
	<7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>
Message-ID: 

On Tue, May 11, 2010 at 12:08 PM, Back9  wrote:
> On May 11, 3:06?pm, Back9  wrote:

>> When i try it, it complains about undefined self.
>>
>> i don't know why.
>>
>> TIA
>
> Sorry
> here is the what i meant
> class test:
> ?self._value = 10
> ?def func(self, pos = self._value)

You're still defining the class, so how could there possibly be an
instance of it to refer to as "self" yet (outside of a method body)?
Also, just so you know, default argument values are only evaluated
once, at the time the function/method is defined, so `pos =
self._value` is never going to work.

Do you mean for self._value to be a class variable (Java lingo: static
variable), or an instance variable?

Cheers,
Chris
--
http://blog.rebertia.com


From clp2 at rebertia.com  Tue May 11 15:25:11 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Tue, 11 May 2010 12:25:11 -0700
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
	
Message-ID: 

On Tue, May 11, 2010 at 11:13 AM, Terry Reedy  wrote:
> On 5/11/2010 7:11 AM, Lawrence D'Oliveiro wrote:
>> In message<7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote:
>>
>>> Python is a pragmatic language from an imperative tradition ...
>>
>> I thought the opposite of ?functional? was ?procedural?, not ?imperative?.
>> The opposite to the latter is ?declarative?. But (nearly) all procedural
>> languages also have declarative constructs, not just imperative ones
>> (certainly Python does).
>
> Python has only two: 'global' and now 'nonlocal'.
> There are also two meta-declarations: the coding cookie (which would/will go
> away in an entirely unicode world) and future imports (which are effectively
> temporarily gone in 3.x until needed again).
>
> Newbies sometimes trip over def and class being imperative (executable)
> statments rather than declarations.

Er, declarative programming has nothing to do with variable declarations.
http://en.wikipedia.org/wiki/Declarative_programming

Cheers,
Chris
--
http://blog.rebertia.com


From tjreedy at udel.edu  Tue May 11 15:25:43 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 15:25:43 -0400
Subject: how to import a module for global use in a library package ?
In-Reply-To: <577270.86860.qm@web23105.mail.ird.yahoo.com>
References: <577270.86860.qm@web23105.mail.ird.yahoo.com>
Message-ID: 

On 5/11/2010 8:04 AM, Aur? Gourrier wrote:
> Dear all,
>
> I am building a library package of the form:
>
> rootlib
> ---__init__
> ---subpackage1
> ------__init__
> ------sub1module1
> ------sub1module2
> ------...
> ---subpackage2
> ------ __init__
> ------sub2module1
> ------sub2module2
> ------...
>
> My rootlib.__init__ file contains:
>
> __name__        = ...
> __version__     = ...
> __author__      = ...
> __author_email__= ...
> __url__         = ...
> __description__ = ...
>
> import subpackage1
> import subpackage2
>
> __all__ = []
> __all__.extend(['subpackage1','subpackage2'])
>
> My question is the following: I need to import an external package,
say numpy, for use in various submodules. So far, I simply do an import
numpy as _numpy where needed, say sub1module1 and sub2module2. This
means that I import this package a number of times which doesn't seem to
be a logical thing to do (?). In the end, I would like to make this
module a "global" module for my library.

I have a similar package structure and after writing a few submodules, I 
developed a template that includes common text, including a couple of 
imports that are usually needed. I also made a backup copy of the 
template in case I open the template and forget to 'save as 
' before just 'save'ing ;-).

If I had several such imports, and thought the list might expand, I 
might make one submodule for imports and then do 'from rootlib.util 
import importmod as m' in the template. But I have no need now for such.

Terry Jan Reedy




From bookexplorer at msisinc.com  Tue May 11 15:28:00 2010
From: bookexplorer at msisinc.com (Donna Lane)
Date: Tue, 11 May 2010 13:28:00 -0600
Subject: First Timer
Message-ID: <002c01caf140$11a0eb00$34e2c100$@com>

I have downloaded Python and I'm a beginner in every sense.  What I want to
know now is when I am in Idle and have made a syntax error how do I repair?
After the error I can't type in

anything and I get this bing noise.  Usually I just start idle over again.

Thanks to anyone out there who responds.

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From backgoodoo at gmail.com  Tue May 11 15:41:48 2010
From: backgoodoo at gmail.com (Back9)
Date: Tue, 11 May 2010 12:41:48 -0700 (PDT)
Subject: default argument
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
	<7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com> 
	
Message-ID: <439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>

On May 11, 3:20?pm, Chris Rebert  wrote:
> On Tue, May 11, 2010 at 12:08 PM, Back9  wrote:
> > On May 11, 3:06?pm, Back9  wrote:
> 
> >> When i try it, it complains about undefined self.
>
> >> i don't know why.
>
> >> TIA
>
> > Sorry
> > here is the what i meant
> > class test:
> > ?self._value = 10
> > ?def func(self, pos = self._value)
>
> You're still defining the class, so how could there possibly be an
> instance of it to refer to as "self" yet (outside of a method body)?
> Also, just so you know, default argument values are only evaluated
> once, at the time the function/method is defined, so `pos =
> self._value` is never going to work.
>
> Do you mean for self._value to be a class variable (Java lingo: static
> variable), or an instance variable?
>
> Cheers,
> Chris
> --http://blog.rebertia.com

self._value will be instance variable


From tjreedy at udel.edu  Tue May 11 15:45:05 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 15:45:05 -0400
Subject: Iterating over dict and removing some elements
In-Reply-To: 
References: 
	
Message-ID: 

On 5/11/2010 11:29 AM, Jerry Hill wrote:
> On Tue, May 11, 2010 at 11:08 AM, Ulrich Eckhardt
>   wrote:
>> My first approach was to simply postpone removing the elements, but I was
>> wondering if there was a more elegant solution.
>
> Iterate over something other than the actual dictionary, like this:
>
> d = {1: 'one', 2: 'two', 3: 'three'}
>
> for k in d.keys():
>      if d[k] == 'two':
>          d.pop(k)

This, as written, does not work in 3.1, where d.keys is a view of the 
dict. Nor does

for k in filter(lambda k: d[k] == 'two', d):
         d.pop(k)

But these do

for k in list(filter(lambda k: d[k] == 'two', d)):
         d.pop(k)

for k in [k for k in d if d[k] == 'two']:
         d.pop(k)

Rather than make an external list of *all* keys, one only needs to make 
a list of keys to be removed, which often  will be much smaller.

Terry Jan Reedy



From nobody at nowhere.com  Tue May 11 15:46:33 2010
From: nobody at nowhere.com (Nobody)
Date: Tue, 11 May 2010 20:46:33 +0100
Subject: fast regex
References: 
	
Message-ID: 

On Tue, 11 May 2010 17:48:41 +1200, Lawrence D'Oliveiro wrote:

>> I was working with regex on a very large text, really large but I have
>> time constrained.
> 
> ?Fast regex? is a contradiction in terms.

Not at all. A properly-written regexp engine will be limited only by
memory bandwidth, provided that the state table fits into the primary
cache.

> You use regexes when you
> want ease of definition and application, not speed.

Other way around.

> For speed, consider hand-coding your own state machine. Preferably in a
> compiled language like C.

Or use a decent regexp library.

Even if you want to use non-regular expressions (e.g. backreferences), a
decent engine will still use a DFA, bactracking only where strictly
necessary.



From richard.lamboj at bilcom.at  Tue May 11 15:48:38 2010
From: richard.lamboj at bilcom.at (Richard Lamboj)
Date: Tue, 11 May 2010 21:48:38 +0200
Subject: inherit from data type
In-Reply-To: 
References: 
	<201005111351.46892.richard.lamboj@bilcom.at>
	
Message-ID: <201005112148.39057.richard.lamboj@bilcom.at>


Am Tuesday 11 May 2010 20:16:50 schrieb Terry Reedy:
> On 5/11/2010 7:51 AM, Richard Lamboj wrote:
> > I just want to test what is possible with python and what not. There is
> > no problem that i need to solve.
> >
> > This is what i'am searching for:
> > http://docs.python.org/reference/datamodel.html
> >
> > Last year i have stopped programming python, but now i'am back with a big
> > black hole in my brain and i want to understand what the interpreter is
> > doing in the background.
>
> I suggest you (re)read and try examples in the Tutorial. It covers the
> basic syntax pretty well.

There are many programming languages, so i have forgotten that python data 
types are objects and not a "wrapper". So its a little bit confusing 
that "self" returns the value of the datatype and not something 
like "self.value". But who cares about logical mistakes in my brain.


From no.email at please.post  Tue May 11 15:49:53 2010
From: no.email at please.post (kj)
Date: Tue, 11 May 2010 19:49:53 +0000 (UTC)
Subject: Limitation of os.walk
Message-ID: 




I want implement a function that walks through a directory tree
and performs an analsysis of all the subdirectories found.  The
task has two essential requirements that, AFAICT, make it impossible
to use os.walk for this:

1. I need to be able to prune certain directories from being visited.

2. The analysis on each directory can be performed only after it
   has been performed on all its subdirectories.

Unless I'm missing something, to do (1), os.walk must be run with
topdown=True, whereas to do (2) it must be run with topdown=False.

Is there a work around that I'm missing?

TIA!

~K

PS: I never understood why os.walk does not support hooks for key
events during such a tree traversal.


From clp2 at rebertia.com  Tue May 11 15:52:43 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Tue, 11 May 2010 12:52:43 -0700
Subject: default argument
In-Reply-To: <439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
	<7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>
	
	<439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
Message-ID: 

On Tue, May 11, 2010 at 12:41 PM, Back9  wrote:
> On May 11, 3:20?pm, Chris Rebert  wrote:
>> On Tue, May 11, 2010 at 12:08 PM, Back9  wrote:
>> > On May 11, 3:06?pm, Back9  wrote:
>> 
>> >> When i try it, it complains about undefined self.
>>
>> >> i don't know why.
>>
>> >> TIA
>>
>> > Sorry
>> > here is the what i meant
>> > class test:
>> > ?self._value = 10
>> > ?def func(self, pos = self._value)
>>
>> You're still defining the class, so how could there possibly be an
>> instance of it to refer to as "self" yet (outside of a method body)?
>> Also, just so you know, default argument values are only evaluated
>> once, at the time the function/method is defined, so `pos =
>> self._value` is never going to work.
>>
>> Do you mean for self._value to be a class variable (Java lingo: static
>> variable), or an instance variable?
>
> self._value will be instance variable

class Test(object):
    def __init__(self):
        self._value = 10
    def func(self, pos=None):
        if pos is None:
            pos = self._value
        #do whatever

Using None like this is the idiomatic way to have non-constant or
mutable default argument values in Python.

I recommend you read the part of the Python tutorial on
object-oriented programming:
http://docs.python.org/tutorial/classes.html

Cheers,
Chris
--
http://blog.rebertia.com


From jim.vickroy at noaa.gov  Tue May 11 15:59:36 2010
From: jim.vickroy at noaa.gov (j vickroy)
Date: Tue, 11 May 2010 13:59:36 -0600
Subject: default argument
In-Reply-To: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>
Message-ID: <4BE9B728.8070602@noaa.gov>

Back9 wrote:
> Hi,
> 
> Is this grammer working in Python?
> 
> class test:
>   self._value = 10
>   def func(self, self._value)
> 
> When i try it, it complains about undefined self.
> 
> i don't know why.
> 
> TIA

... not exactly; try:

class Test:
    _value = 10
    def func(self):
       print id(self._value), self._value
       print id(Test._value), Test._value

t = Test()
t.func()


From lie.1296 at gmail.com  Tue May 11 15:59:50 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 12 May 2010 05:59:50 +1000
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 	<7xvdavd4bq.fsf@ruckus.brouhaha.com>
		
	
Message-ID: <4be9b795$1@dnews.tpgi.com.au>

On 05/12/10 05:25, Chris Rebert wrote:
> On Tue, May 11, 2010 at 11:13 AM, Terry Reedy  wrote:
>> On 5/11/2010 7:11 AM, Lawrence D'Oliveiro wrote:
>>> In message<7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote:
>>>
>>>> Python is a pragmatic language from an imperative tradition ...
>>>
>>> I thought the opposite of ?functional? was ?procedural?, not ?imperative?.
>>> The opposite to the latter is ?declarative?. But (nearly) all procedural
>>> languages also have declarative constructs, not just imperative ones
>>> (certainly Python does).
>>
>> Python has only two: 'global' and now 'nonlocal'.
>> There are also two meta-declarations: the coding cookie (which would/will go
>> away in an entirely unicode world) and future imports (which are effectively
>> temporarily gone in 3.x until needed again).
>>
>> Newbies sometimes trip over def and class being imperative (executable)
>> statments rather than declarations.
> 
> Er, declarative programming has nothing to do with variable declarations.
> http://en.wikipedia.org/wiki/Declarative_programming
> 

Variable declarations have everything to do with declarative programming.

An imperative way to create a variable is to allocate the memory
yourself and instead of "variables" you have just registers and the
memory; fortunately all popular imperative languages (wisely) picks up
declarative syntax from the declarative paradigm. In Python, the regular
def/class is a pseudo-declaration, but it is also possible to
*imperatively/procedurally* create a class by calling type() and a
function by passing a __call__() to type()'s __dict__ argument.

A fully declarative language just turn everything into declarations
including the "business logic" of the application (and of course,
variable declaration).


From tjreedy at udel.edu  Tue May 11 16:00:48 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 16:00:48 -0400
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 	<7xvdavd4bq.fsf@ruckus.brouhaha.com>
		
	
Message-ID: 

On 5/11/2010 3:25 PM, Chris Rebert wrote:
> On Tue, May 11, 2010 at 11:13 AM, Terry Reedy  wrote:
>> On 5/11/2010 7:11 AM, Lawrence D'Oliveiro wrote:
>>> In message<7xvdavd4bq.fsf at ruckus.brouhaha.com>, Paul Rubin wrote:
>>>
>>>> Python is a pragmatic language from an imperative tradition ...
>>>
>>> I thought the opposite of ?functional? was ?procedural?, not ?imperative?.
>>> The opposite to the latter is ?declarative?. But (nearly) all procedural
>>> languages also have declarative constructs, not just imperative ones
>>> (certainly Python does).
>>
>> Python has only two: 'global' and now 'nonlocal'.
>> There are also two meta-declarations: the coding cookie (which would/will go
>> away in an entirely unicode world) and future imports (which are effectively
>> temporarily gone in 3.x until needed again).
>>
>> Newbies sometimes trip over def and class being imperative (executable)
>> statments rather than declarations.
>
> Er, declarative programming has nothing to do with variable declarations.
> http://en.wikipedia.org/wiki/Declarative_programming

I found it hard to get much from the vague description. I will leave it 
to Lawrence to list what *he* thinks are 'declarative constructs' in Python.




From nobody at nowhere.com  Tue May 11 16:03:35 2010
From: nobody at nowhere.com (Nobody)
Date: Tue, 11 May 2010 21:03:35 +0100
Subject: Is Python a functional programming language?
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
	<7xvdau8pzl.fsf@ruckus.brouhaha.com>
Message-ID: 

On Tue, 11 May 2010 07:36:30 -0700, Paul Rubin wrote:

> Offhand I can't tell that imperative and procedural mean something
> different.  Both basically mean that the programmer specifies a series of
> steps for the computer to carry out.  Functional languages are mostly
> declarative; for example, an expression like
>    x = 3
> is called an "equation" rather than an "assignment".  It declares "x is
> equal to 3", rather than directing x to be set to 3.  If someplace else in
> the program you say "x = 4", that is an error, normally caught by the
> compiler, since x cannot be equal to both 3 and 4.

In both ML and Haskell, bindings are explicitly scoped, i.e.

	let x = 3 in ... end	(ML)
	let x = 3 in ...	(Haskell)

If you bind a variable which is already bound, it introduces a new binding
which "overrides" the existing binding. It won't generate an error.

The key point is that a variable has a fixed (constant) value at any
specific point in the program. The value depends upon which bindings are
in scope at that point, and not on the "state" of the variable at a
particular point in time.

E.g. (Haskell):

	test y = let x = 3
	         in let f y = x + y
	            in let x = 5
	               in f y
	test 5
	8

x has the value 3 at the point that f is defined, so that's the value
which is used when f is used.



From clp2 at rebertia.com  Tue May 11 16:03:41 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Tue, 11 May 2010 13:03:41 -0700
Subject: First Timer
In-Reply-To: <002c01caf140$11a0eb00$34e2c100$@com>
References: <002c01caf140$11a0eb00$34e2c100$@com>
Message-ID: 

On Tue, May 11, 2010 at 12:28 PM, Donna Lane  wrote:
> I have downloaded Python and I'm a beginner in every sense.? What I want to
> know now is when I am in Idle and have made a syntax error how do I repair?
> After the error I can't type in
>
> anything and I get this bing noise.? Usually I just start idle over again.

You re-type or copy-paste and then fix the line(s) after the new >>>
prompt that appears after the SyntaxError message. You can't edit
lines you've already run.

Also, you can compose an entire file of code and then run the file,
rather than working directly at the interactive interpreter (aka
shell). File->New Window makes an empty file you can work in; pressing
F5 in the file editor window will run the file.

Cheers,
Chris
--
http://blog.rebertia.com


From nobody at nowhere.com  Tue May 11 16:07:30 2010
From: nobody at nowhere.com (Nobody)
Date: Tue, 11 May 2010 21:07:30 +0100
Subject: Is Python a functional programming language?
References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com>
	
	
Message-ID: 

On Tue, 11 May 2010 23:13:10 +1200, Lawrence D'Oliveiro wrote:

>> But the beauty is that Python is multi-paradigm ...
> 
> The trouble with ?multi-paradigm? is that it offends the zealots on
> all sides.

Is that how you view people who like languages to exhibit a degree of
consistency? Some people would prefer to have a manageable set of rules
rather than having to remember the results of all of the possible
combinations of interactions between language features.



From alan.isaac at gmail.com  Tue May 11 16:23:51 2010
From: alan.isaac at gmail.com (Alan G Isaac)
Date: Tue, 11 May 2010 16:23:51 -0400
Subject: documentation bug? (format spec mini language)
In-Reply-To: 
References: 
	
Message-ID: 

On 5/11/2010 3:19 PM, MRAB wrote:
> You usually want numbers to be right-aligned so that the decimal points
> line up when writing a columns of them.


Yes.  I'm not questioning the wisdom of the implementation,
just the documentation of it.

Thanks,
Alan



From pmaupin at gmail.com  Tue May 11 16:39:48 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Tue, 11 May 2010 13:39:48 -0700 (PDT)
Subject: Picking a license
References: 
	
	<4be5bdcb$0$27798$c3e8da3@news.astraweb.com>
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com>
	 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com>
Message-ID: <151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com>

On May 11, 5:24?am, Paul Boddie  wrote:
> On 10 Mai, 17:01, Patrick Maupin  wrote:
>
> > I'll be charitable and assume the fact that you can make that
> > statement without apparent guile merely means that you haven't read
> > the post I was referring to:
>
> >http://www.gnu.org/philosophy/why-not-lgpl.html
>
> Of course I have read it, and not just recently either. But this is a
> position paper by the author of the licence, and it doesn't mean that
> someone who has written a GPL-licensed library completely agrees with
> that position. And anyway, it's a case of "take it or leave it" - it's
> not like the author or the FSF are sneaking stuff into every product
> and every corner of the market and then telling you that you can't
> "unchoose" their stuff.

OK.  Now I'm REALLY confused.  I said "Certainly RMS
carefully lays out that the LGPL should be used sparingly in his "Why
you shouldn't use the Lesser GPL for your next library" post.  (Hint:
he's not suggesting a permissive license instead.)"

to which you replied:

"Sure, but all he's asking you to do is to make the software available
under a GPL-compatible licence."

and then I tried to politely show that you were wrong about RMS's
intentions, but now, but you're saying "oh, of course, he'd say that
-- he wrote the license"  which is basically what I've been saying all
along.  But if you have read it like you say, then it appears you were
being very disingenuous in your original reply!

> Although it seems quite unfair, the e-mail discussion about the
> licence does show that Stallman was not initially convinced that works
> should be affected in such a way (with regard to the Objective-C
> compiler developed by NeXT), and that Haible was not strongly opposed
> to changing the licence. You can argue that Stallman overreached by
> demanding a licence change and that consideration of such matters has
> progressed since that time, but Haible always had the option of not
> using or supporting readline - only the latter is contentious,

"was not strongly opposed to changing the license"  As I already
mentioned, he was more interested in doing useful stuff than worrying
about the license.  Yes, readline was the hook that sucked him into
using the GPL, but IMHO RMS was flat out wrong about the licensing
implications.  As I mentioned, though, the morality and the legality
are probably different animals.

> and the
> obligation of GPL-compatible licensing (as opposed to GPL-licensing)
> now diminishes how contentious this is today.

NO.  If you are building an application, and distributing GPLed stuff
as part of it, the FSF still maintains that the license is such that
the entire application must be GPLed.  You keep acting like this isn't
true, but it absolutely is if you're distributing the entire
application.

> > I think that, legally, they probably don't have a leg to stand on for
> > some of their overarching claims (e.g. about shipping proprietary
> > software that could link to readline, without even shipping
> > readline). ?But morally -- well, they've made their position
> > reasonably clear and I try to abide by it. ?That still doesn't make it
> > "not really FUD." ?I'd call this sort of badgering "copyright misuse"
> > myself.
>
> Again, you have to consider the intent of the licensing: that some
> software which links to readline results in a software system that
> should offer the "four freedoms", because that's the price of linking
> to readline whose licence has promised that any system which builds
> upon it shall offer those privileges.

But I did consider the intent, and as I have made clear, I think
that's a bullying tactic that fragments the software world
unnecessarily.  Obviously YMMV.

> > > As for rst2pdf, what your modifications would mean is that the
> > > software would need to be redistributed under a GPL-compatible
> > > licence.

NO.  You're still not paying attention.  The FSF's clear position is
that if you actually *redistribute* software under the GPL as *part of
a system* then the full package must be licensed *under the GPL*.

> Once again, I refer you to the intent of the licensing: if someone has
> the software in front of them which uses svglib, then they need to
> have the privileges granted to them by the GPL. Yes, if the software
> also uses some component with a GPL-incompatible licence, then this
> causes a problem.

It appears that the FSF's position is the ability to link to svglib
would require software to be licensed under the GPL.  I don't believe
that, but I do believe that if rst2pdf distributed svglib (or even
patches to svglib which were clearly derivative works) then yes,
rst2pdf would have to be distributed under the GPL.  This kind of
bullshit is only acceptable to people who only think a single license
is acceptable.

> [...]
>
> >http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystem
>
> > "A system incorporating a GPL-covered program is an extended version
> > of that program. The GPL says that any extended version of the program
> > must be released under the GPL if it is released at all."
>
> > This makes it clear that the overall work must be GPLed. ?Now, all of
> > a sudden, downstream users cannot do some things they could have done
> > before. ?Can you not see that taking a preexisting MIT-licensed
> > project and adding code to make it GPL could negatively affect some of
> > its users and that that is not necessarily an unalloyed good?
>
> Well, I have referred several times to WebKit without you taking the
> hint,

OK, I don't work with webkit.  I knew you were hinting at something,
but why the games, I don't know.  I guess it's all about mystique and
games.

> but that provides a specific case of a project which is LGPL-
> licensed despite being based on (in GPLv3 terminology) libraries which
> were distributed under the GPL and combined with that software.

What other libraries?  I don't know it's history.  I give you specific
examples at problems; you hint around at things you claim are not
problems and then still don't give specifics.

> Similarly, the effort to ensure that CPython's licence was GPL-
> compatible had a lot to do with the right to redistribute with GPL-
> licensed code (actually readline, if I remember correctly).

Yes, but the Python project doesn't actually distribute readline, and
(as I mentioned) people are more informed now, and it would be
difficult for RMS to bully Python into relicensing.  But if the Python
distribution *included* GNU Readline, then RMS would be on firmer
ground, and the license would probably have to be changed.  This is
*exactly* the situation I was describing with svglib -- can you still
not see that it is a problem to just toss unsupported free software
out there with a GPL license?  Unsupported Apache or MIT is fine --
fix it or ignore.  Unsupported GPL is an attractive nuisance.


> Is readline trivial? Was readline trivial in 1992?

Again, you could have neural net prediction and other fancy
technologies, but in general, yes, the concept is pretty trivial and
there were many systems that already had such things back then.

> Does it even
> matter, because the author is more or less saying that they don't want
> their code incorporated in a proprietary system?

Yes it matters because as others have pointed out, sometimes people
use stuff which is purported to be "free" without a full understanding
of all the implications.  But this gets back to my general complaint
about co-opting the word "free" which you don't think is a problem
because you have chosen to use other words.

> It's interesting to
> see that GPLv3 doesn't talk about derived works or derivatives (at
> least not as much as GPLv2), but instead talks about things being
> "based on" other things, but as I've already said, at the point of
> someone running a bunch of software components together, the intent of
> copyleft licences is to say that the user should be able to take that
> (or part of it, in the case of "weak copyleft" licences) and change,
> recompile and distribute its sources, modified or not.

Trust me, I know the intent, and could even consider it a noble goal.
But I think a lot of the means employed in getting to this end are
simply wrong.

Regards,
Pat


From davea at ieee.org  Tue May 11 16:42:35 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 May 2010 16:42:35 -0400
Subject: default argument
In-Reply-To: <439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>	<7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>
	
	<439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
Message-ID: <4BE9C13B.3020503@ieee.org>



Back9 wrote:
> On May 11, 3:20 pm, Chris Rebert  wrote:
>   
>> On Tue, May 11, 2010 at 12:08 PM, Back9  wrote:
>>     
>>> On May 11, 3:06 pm, Back9  wrote:
>>>       
>> 
>>     
>>>> When i try it, it complains about undefined self.
>>>>         
>>>> i don't know why.
>>>>         
>>>> TIA
>>>>         
>>> Sorry
>>> here is the what i meant
>>> class test:
>>>  self._value =0
>>>  def func(self, pos =elf._value)
>>>       
>> You're still defining the class, so how could there possibly be an
>> instance of it to refer to as "self" yet (outside of a method body)?
>> Also, just so you know, default argument values are only evaluated
>> once, at the time the function/method is defined, so `pos > self._value` is never going to work.
>>
>> Do you mean for self._value to be a class variable (Java lingo: static
>> variable), or an instance variable?
>>
>> Cheers,
>> Chris
>> --http://blog.rebertia.com
>>     
>
> self._value will be instance variable
>
>   
If you want an instance value to be your default, you'll need to us an 
indirect approach.  There are no instances at the time the class is 
defined.  So you want to create such a value in the __init__() method.
Something like the following (untested):

class  Test(object):
     def __init__(self, initvalue):
         self.value = initvalue
     def func(self, pos = None):
          if pos=None:   pos = self.value
          etc.

x = Test(44)
x.func(91)          #uses 91 for pos
x.func()              #uses 44 for pos


DaveA


From pmaupin at gmail.com  Tue May 11 16:50:41 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Tue, 11 May 2010 13:50:41 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	
Message-ID: 

On May 11, 5:34?am, Paul Boddie  wrote:
> On 10 Mai, 20:36, Patrick Maupin  wrote:

> > I've addressed this before. ?Aahz used a word in an accurate, but to
> > you, inflammatory, sense, but it's still accurate -- the man *would*
> > force you to pay for the chocolate if you took it.
>
> Yes, *if* you took it. He isn't forcing you to take it, though, is he?

No,  but he said a lot of words that I didn't immediately understand
about what it meant to be free and that it was free, and then after I
bit into it he told me he owned my soul now.

> > You're making it sound like whining, but Aahz was simply trying to state a fact.
>
> It is whining if someone says, "I really want that chocolate, but that
> nasty man is going to make me pay for it!"

But that's not what happened.  I mean, he just told me that I might
have to give some of it to others later.  He didn't mention that if I
spread peanut butter on mine before I ate it that I'd have to give
people Reese's Peanut Butter cups.

>
> >?The fact is, I know the man would force me to pay for the chocolate, so in
> > some cases that enters into the equation and keeps me from wanting the
> > chocolate.
>
> If the man said, "please take the chocolate, but I want you to share
> it with your friends", and you refused to do so because you couldn't
> accept that condition, would it be right to say, "that man is forcing
> me to share chocolate with my friends"?

But the thing is, he's *not* making me share the chocolate with any of
my friends.  He's not even making me share my special peanut butter
and chocolate.  What he's making me do is, if I give my peanut butter
and chocolate to one of my friends, he's making me make *that* friend
promise to share.  I try not to impose obligations like that on my
friends, so obviously the "nice" man with the chocolate isn't my
friend!

> > ?This isn't whining; just a common-sense description of
> > reality. ?Personally, I think this use of the word "force" is much
> > less inflammatory than the deliberate act of co-opting the word
> > "freedom" to mean "if you think you can take this software and do
> > anything you want with it, you're going to find out differently when
> > we sue you."
>
> The word "freedom" means a number of things. If you don't like the way
> Messrs Finney and Stallman use the term, please take it up with them.
> But to say that someone entering a voluntary agreement is "forced" to
> do something, when they weren't forced into that agreement in the
> first place, is just nonsense. It's like saying that the shopkeeper is
> some kind of Darth Vader character who is coercing people to take the
> chocolate and then saddling them with obligations against their will.

I explained this very carefully before multiple times.  Let me give
concrete examples -- (1) I have told my children before "if we take
that candy, then they will make us pay for it" and (2) if we included
(GPLed software) in this (MIT-licensed software) then we will have to
change the license.  In both these cases, once the decision has been
made, then yes, force enters into it.  And no, I don't think the
average shop keeper is nearly as evil as Darth, or even RMS.

Regards,
Pat


From pmaupin at gmail.com  Tue May 11 17:02:06 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Tue, 11 May 2010 14:02:06 -0700 (PDT)
Subject: Picking a license
References: 
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com>
	 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<4be95545$1@dnews.tpgi.com.au>
	
Message-ID: 

On May 11, 9:00?am, Paul Boddie  wrote:
> On 11 Mai, 15:00, Lie Ryan  wrote:
> > Come on, 99% ?of the projects released under GPL did so because they
> > don't want to learn much about the law; they just need to release it
> > under a certain license so their users have some legal certainty.
>
> Yes, this is frequently the case. And the GPL does offer some
> certainty that various permissive licences do not.

Huh? Permissive licenses offer much better certainty for someone
attempting a creative mash-up.  Different versions of the Apache
license don't conflict with each other.  If I use an MIT-licensed
component, it doesn't attempt to make me offer my whole work under
MIT.

[..]
>
> Well, that's always an option as well, but at the same time, there are
> people willing to pursue licence violations, and these people have
> done so successfully. There's no need to make an impassioned argument
> for apathy, though. Some people do wish to dictate what others can do
> with their work.

Oh, I get it.  You were discussing the certainty that an author can
control what downstream users do with the software to some extent.
Yes, I fully agree.  The GPL is for angry idealists who have an easily
outraged sense of justice, who don't have enough real problems to work
on.

BTW, I'm here to make an impassioned argument for apathy.  For
example, I think the world needs fewer suicide bombers, and the more
apathy we can get.

Regards,
Pat


From pmaupin at gmail.com  Tue May 11 17:03:08 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Tue, 11 May 2010 14:03:08 -0700 (PDT)
Subject: Picking a license
References: 
	
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	<4be93cee$0$27837$c3e8da3@news.astraweb.com>
Message-ID: <35e2b804-2e96-437e-8a72-325dc2b06c57@a39g2000prb.googlegroups.com>

On May 11, 6:18?am, Steven D'Aprano  wrote:
> Last time I came home with chocolate, I tried that excuse on my wife. She
> didn't believe it for a second.
>
> Next time, I'll try claiming that I was obliged to eat the chocolate
> because of the GPL.

Good luck with that.  Women can always see right through bad
analogies, especially where chocolate is concerned!

Regards,
Pat


From tjreedy at udel.edu  Tue May 11 17:05:19 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 17:05:19 -0400
Subject: documentation bug? (format spec mini language)
In-Reply-To: <4BE9ADD9.9030901@mrabarnett.plus.com>
References: 
	<4BE9ADD9.9030901@mrabarnett.plus.com>
Message-ID: 

On 5/11/2010 3:19 PM, MRAB wrote:
> Alan G Isaac wrote:
>> The documentation at
>> http://docs.python.org/py3k/library/string.html#format-specification-mini-language
>>
>>
>> '<' Forces the field to be left-aligned within the available space
>> (This is the default.)
>>
>> The conflicting example::
>>
>> >>> format(3.2,'10.5f')
>> ' 3.20000'
>> >>> format(3.2,'<10.5f')
>> '3.20000 '
>>
>> Am I somehow misreading the documentation?
>>
> It does look misleading. Numbers default to right-aligned, as you
> discovered.
>
> You usually want numbers to be right-aligned so that the decimal points
> line up when writing a columns of them.

http://bugs.python.org/issue8691



From martin at v.loewis.de  Tue May 11 17:13:55 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Tue, 11 May 2010 23:13:55 +0200
Subject: Upgrade Python 2.6.4 to 2.6.5
In-Reply-To: 
References: 	<4BE86BC1.8040102@v.loewis.de>
	
Message-ID: <4BE9C893.1070104@v.loewis.de>

> When will it install into system32?

When you install "for all users".

>> Did the upgrade inform you that it was an upgrade, or did it warn you
>> that you would overwrite the previous installation?
>>    
> It warned me that there is a previous installation.

Hmm. You don't remember the exact message, do you?
I guess it was a popup saying "[TARGETDIR] exists. Are you sure you want
to overwrite existing files?", and that it was not
a red text saying "This update will replace your existing [ProductLine]
installation."

Please confirm.

If so, you now have two Python installations in the same location; one
for all users, and the older one just for you (or vice versa).

I recommend to uninstall them both, and start over.

Regards,
Martin


From tjreedy at udel.edu  Tue May 11 17:19:50 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 17:19:50 -0400
Subject: default argument
In-Reply-To: <439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
References: <20a88cfd-9c18-4e2d-94bf-b7031114338a@e1g2000yqe.googlegroups.com>	<7d9f6a50-c234-4e74-b092-b6e0f1f1b2ab@r11g2000yqa.googlegroups.com>
	
	<439584b6-61c6-4fff-a3b4-a1cbbb0b4926@n15g2000yqf.googlegroups.com>
Message-ID: 

On 5/11/2010 3:41 PM, Back9 wrote:

>
> self._value will be instance variable

Then set it in the __init__ method. Read the tutorial and ref manual on 
Python class statements, which are a bit different from what you might 
be used to.




From python at bdurham.com  Tue May 11 17:27:03 2010
From: python at bdurham.com (python at bdurham.com)
Date: Tue, 11 May 2010 17:27:03 -0400
Subject: Upgrade Python 2.6.4 to 2.6.5
In-Reply-To: <4BE9C893.1070104@v.loewis.de>
References: 
	<4BE86BC1.8040102@v.loewis.de>
	<4BE9C893.1070104@v.loewis.de>
Message-ID: <1273613223.8700.1374581741@webmail.messagingengine.com>

Martin,

If we install over an existing version of Python 2.6.5, will our PTH
files and site-packages be preserved?

Or do we need to back out our 3rd party packages, install Python 2.6.5
and then manually restore our 3rd party packages?

Thank you,
Malcolm


From tjreedy at udel.edu  Tue May 11 17:37:53 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 17:37:53 -0400
Subject: First Timer
In-Reply-To: <002c01caf140$11a0eb00$34e2c100$@com>
References: <002c01caf140$11a0eb00$34e2c100$@com>
Message-ID: 

On 5/11/2010 3:28 PM, Donna Lane wrote:
> I have downloaded Python and I'm a beginner in every sense.

Welcome. I hope you enjoy Python too.

 > What I want to
> know now is when I am in Idle and have made a syntax error how do I repair?
> After the error I can't type in anything and I get this bing noise.
 > Usually I just start idle over again.

You cannot directly repair a line already ed. You must enter a 
new line. In the command line interpreter, you should be able to hit up 
arrow and have the line above copied to the current entry line for 
correction. In IDLE, this does not yet work, so copy and paste or retype.

For anything too complicated for either of those (more than one line), I 
use (and reuse) a temporary edit file in an edit window. Just make sure 
the file is named .py rather than just . You save 
and run the file with F5. If there is a syntax error, IDLE will say so 
and reopen the cursor window with the cursor at (or after) the location 
of the error. Fix and hit F5 again. Very fast.

The main thing to watch is that you must say 'print(x)' rather than just 
'x' to print. File/Recent files lets one easily reopen the tem file (or 
any other of the 20 most recently edited files).

I use the tem file when I copy and paste more than a single line of code 
from, say, a post here.

Terry Jan Reedy




From debatem1 at gmail.com  Tue May 11 17:40:36 2010
From: debatem1 at gmail.com (geremy condra)
Date: Tue, 11 May 2010 17:40:36 -0400
Subject: open(False) in python3
Message-ID: 

I'm unsure if this qualifies as a bug (it is also clearly user error) but I just
ran into a situation where open() was inadvertantly called on a False,
and I was somewhat surprised to see that this didn't bail horribly, but
rather hung forever. Here's some example sessions for python3.x and
python2.x:

@:~$ python3
Python 3.1.2 (r312:79147, Apr 15 2010, 12:35:07)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open(False)
>>> f.read()
^CTraceback (most recent call last):
  File "", line 1, in 
KeyboardInterrupt
>>>
@:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open(False)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: coercing to Unicode: need string or buffer, bool found
>>>

Should I chalk this up to stupid coder syndrome or file a bug report?

Geremy Condra


From vinay_sajip at yahoo.co.uk  Tue May 11 17:43:07 2010
From: vinay_sajip at yahoo.co.uk (Vinay Sajip)
Date: Tue, 11 May 2010 14:43:07 -0700 (PDT)
Subject: Version 0.3.9 of the Python config module has been released.
Message-ID: 

Version 0.3.9 of the Python config module has been released.

What Does It Do?
================
The config module allows you to implement a hierarchical configuration
scheme with support for mappings and sequences, cross-references
between one part of the configuration and another, the ability to
flexibly access real Python objects, facilities for configurations to
include and cross-reference one another, simple expression evaluation
and the ability to change, save, cascade and merge configurations. You
can easily integrate with command line options using optparse.

This module has been developed on python 2.3 but should work on
version 2.2 or greater. A test suite using unittest is included in the
distribution.

A very simple configuration file (simple.cfg):

# starts here
message: Hello, world!
#ends here

a very simple program to use it:

from config import Config

cfg = Config(file('simple.cfg'))
print cfg.message

results in:

Hello, world!

Configuration files are key-value pairs, but the values can be
containers that contain further values.

A simple example - with the example configuration file:

messages:
[
  {
    stream : `sys.stderr`
    message: 'Welcome'
    name: 'Harry'
  }
  {
    stream : `sys.stdout`
    message: 'Welkom'
    name: 'Ruud'
  }
  {
    stream : $messages[0].stream
    message: 'Bienvenue'
    name: Yves
  }
]

a program to read the configuration would be:

from config import Config

f = file('simple.cfg')
cfg = Config(f)
for m in cfg.messages:
    s = '%s, %s' % (m.message, m.name)
    try:
        print >> m.stream, s
    except IOError, e:
        print e

which, when run, would yield the console output:

Welcome, Harry
Welkom, Ruud
Bienvenue, Yves

The above example just scratches the surface. There's more information
about this module available at

http://www.red-dove.com/config-doc/

Comprehensive API documentation is available at

http://www.red-dove.com/config/index.html

As always, your feedback is most welcome (especially bug reports,
patches and suggestions for improvement). Enjoy!

Cheers

Vinay Sajip
Red Dove Consultants Ltd.

Changes since the last release posted on comp.lang.python[.announce]:
=====================================================
Fix bug in parsing numbers with exponents (reported
by Philip S?eberg).


From inq1ltd at inqvista.com  Tue May 11 17:49:43 2010
From: inq1ltd at inqvista.com (jim-on-linux)
Date: Tue, 11 May 2010 17:49:43 -0400
Subject: py2exe help
In-Reply-To: 
References: 
	
	
Message-ID: <201005111749.43342.inq1ltd@inqvista.com>

python help,

I'm open for suggestions.

I'm using py2exe to compile a working program.

The program runs and prints fine until I compile it with py2exe. 

After compiling the program, it runs fine until it tries to import 
the win32ui module, v2.6214.0. 

Then, I get a windows error message:

ImportError: Dll load failed:  
This application has failed to start because 
the application configuration is incorrect.
Reinstalling the application may fix this problem.


Anyone have the same problem with this?.

jim-on linux


From python.list at tim.thechases.com  Tue May 11 17:53:48 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Tue, 11 May 2010 16:53:48 -0500
Subject: Limitation of os.walk
In-Reply-To: 
References: 
Message-ID: <4BE9D1EC.8040500@tim.thechases.com>

On 05/11/2010 02:49 PM, kj wrote:
> I want implement a function that walks through a directory tree
> and performs an analsysis of all the subdirectories found.  The
> task has two essential requirements that, AFAICT, make it impossible
> to use os.walk for this:
>
> 1. I need to be able to prune certain directories from being visited.
>
> 2. The analysis on each directory can be performed only after it
>     has been performed on all its subdirectories.
>
> Unless I'm missing something, to do (1), os.walk must be run with
> topdown=True, whereas to do (2) it must be run with topdown=False.

I don't think there's a way to coerce os.walk into doing what you 
want.  That said, the core source for os.walk() is a whole 23 
lines of code, it's easy enough to just clone it and add what you 
need...

> PS: I never understood why os.walk does not support hooks for key
> events during such a tree traversal.

including hooks for calling pre/post hooks.

-tkc




From bryanjugglercryptographer at yahoo.com  Tue May 11 18:01:44 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Tue, 11 May 2010 15:01:44 -0700 (PDT)
Subject: Extract all words that begin with x
References: 
	 
	 
	
	
Message-ID: <1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com>

Tycho Andersen wrote:
> Terry Reedy wrote:
> > ?... word[0:1] does the same thing. All Python programmers should learn to
> > use slicing to extract a ?char from a string that might be empty.
> > The method call of .startswith() will be slower, I am sure.
>
> Why? Isn't slicing just sugar for a method call?

Yes, but finding the method doesn't require looking it up by name at
run-time, and startswith is built to work for startings of any length.

Let's timeit:

# -----
from timeit import Timer
from random import choice
from string import ascii_lowercase as letters

strs = [''.join([choice(letters) for _ in range(5)])
        for _ in range(5000)]

way1 = "[s for s in strs if s.startswith('a')]"
way2 = "[s for s in strs if s[:1] == 'a']"

assert eval(way1) == eval(way2)

for way in [way1, way2]:
    t = Timer(way, 'from __main__ import strs')
    print(way, ' took: ', t.timeit(1000))

# -----

On my particular box, I get:

[s for s in strs if s.startswith('a')]  took:  5.43566498797
[s for s in strs if s[:1] == 'a']  took:  3.20704924968

So Terry Reedy was right: startswith() is slower. I would,
nevertheless, use startswith(). Later, if users want my program to run
faster and my profiling shows a lot of the run-time is spent finding
words that start with 'a', I might switch.

--
--Bryan


From rtw at rtw.me.uk  Tue May 11 18:25:10 2010
From: rtw at rtw.me.uk (Rob Williscroft)
Date: Tue, 11 May 2010 17:25:10 -0500
Subject: py2exe help
References: 
	
	
	
Message-ID: 

jim-on-linux wrote in news:mailman.74.1273614703.32709.python-list at python.org 
in comp.lang.python:

> python help,
> 
> I'm open for suggestions.
> 
> I'm using py2exe to compile a working program.
> 
> The program runs and prints fine until I compile it with py2exe. 
> 
> After compiling the program, it runs fine until it tries to import 
> the win32ui module, v2.6214.0. 
> 
> Then, I get a windows error message:
> 
> ImportError: Dll load failed:  
> This application has failed to start because 
> the application configuration is incorrect.
> Reinstalling the application may fix this problem.
> 
> 
> Anyone have the same problem with this?.

http://www.py2exe.org/index.cgi/Py2exeAndWin32ui

Rob.


From gagsl-py2 at yahoo.com.ar  Tue May 11 18:27:37 2010
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Tue, 11 May 2010 19:27:37 -0300
Subject: open(False) in python3
References: 
Message-ID: 

En Tue, 11 May 2010 18:40:36 -0300, geremy condra   
escribi?:

> I'm unsure if this qualifies as a bug (it is also clearly user error)  
> but I just
> ran into a situation where open() was inadvertantly called on a False,
> and I was somewhat surprised to see that this didn't bail horribly, but
> rather hung forever. Here's some example sessions for python3.x and
> python2.x:
>
> @:~$ python3
> Python 3.1.2 (r312:79147, Apr 15 2010, 12:35:07)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> f = open(False)
>>>> f.read()
> ^CTraceback (most recent call last):
>   File "", line 1, in 
> KeyboardInterrupt

open() in Python 3 does a lot of things; it's like a mix of codecs.open()  
+ builtin open() + os.fdopen() from 2.x all merged together. It does  
different things depending on the type and quantity of its arguments, and  
even returns objects of different types.

In particular, open(some_integer) assumes some_integer is a file  
descriptor and return some variant of file object using the given file  
descriptor.

Now, False is an instance of bool, a subclass of int, and is numerically  
equal to 0:

p3> isinstance(False, int)
True
p3> False==0
True

so open(False) is the same as open(0), and 0 is the file descriptor  
associated to standard input. The program isn't hung, it's just waiting  
for you to type some text:

p3> f = open(False)
p3> f.read()
Type some text
^Z
^Z
'Type some text\n'
p3>


> Should I chalk this up to stupid coder syndrome or file a bug report?

Uhm, perhaps the bug is, bool should not inherit from int in Python 3, but  
it's way too late to change that.

-- 
Gabriel Genellina



From mensanator at aol.com  Tue May 11 19:03:37 2010
From: mensanator at aol.com (Mensanator)
Date: Tue, 11 May 2010 16:03:37 -0700 (PDT)
Subject: First Timer
References: <002c01caf140$11a0eb00$34e2c100$@com>
	
Message-ID: 

On May 11, 4:37?pm, Terry Reedy  wrote:
> On 5/11/2010 3:28 PM, Donna Lane wrote:
>
> > I have downloaded Python and I'm a beginner in every sense.
>
> Welcome. I hope you enjoy Python too.
>
> ?> What I want to> know now is when I am in Idle and have made a syntax error how do I repair?
> > After the error I can't type in anything and I get this bing noise.
>
> ?> Usually I just start idle over again.
>
> You cannot directly repair a line already ed.

Ok.

> You must enter a new line.

Huh?! I suppose it depends on what you mean by "enter".

> In the command line interpreter, you should be able to hit up
> arrow and have the line above copied to the current entry line for
> correction. In IDLE, this does not yet work,

It doesn't have to. Simply place the cursor on the line you originally
entered and hit .

> so copy and paste or retype.

The line will be repeated as a new line which you can edit
and make corrections.

>
> For anything too complicated for either of those (more than one line), I
> use (and reuse) a temporary edit file in an edit window. Just make sure
> the file is named .py rather than just . You save
> and run the file with F5. If there is a syntax error, IDLE will say so
> and reopen the cursor window with the cursor at (or after) the location
> of the error. Fix and hit F5 again. Very fast.

Sounds like you're making a mountain out of a molehill. You deserve
a medal if you've been using IDLE without knowing how to edit.

>
> The main thing to watch is that you must say 'print(x)' rather than just
> 'x' to print. File/Recent files lets one easily reopen the tem file (or
> any other of the 20 most recently edited files).
>
> I use the tem file when I copy and paste more than a single line of code
> from, say, a post here.
>
> Terry Jan Reedy



From no.email at please.post  Tue May 11 19:49:04 2010
From: no.email at please.post (kj)
Date: Tue, 11 May 2010 23:49:04 +0000 (UTC)
Subject: Limitation of os.walk
References: 
	
Message-ID: 

In  Tim Chase  writes:

>That said, the core source for os.walk() is a whole 23 
>lines of code, it's easy enough to just clone it and add what you 
>need...

Thanks, that was a good idea.

~K


From inq1ltd at inqvista.com  Tue May 11 21:24:12 2010
From: inq1ltd at inqvista.com (jim-on-linux)
Date: Tue, 11 May 2010 21:24:12 -0400
Subject: py2exe help
In-Reply-To: 
References: 
	
	
Message-ID: <201005112124.12663.inq1ltd@inqvista.com>



I appreciate the help, it's working.

jim-on-linux


> jim-on-linux wrote in
>  news:mailman.74.1273614703.32709.python-list at python.org
> 
> in comp.lang.python:
> > python help,
> >
> > I'm open for suggestions.
> >
> > I'm using py2exe to compile a working program.
> >
> > The program runs and prints fine until I compile it with 
py2exe.
> >
> > After compiling the program, it runs fine until it tries to 
import
> > the win32ui module, v2.6214.0.
> >
> > Then, I get a windows error message:
> >
> > ImportError: Dll load failed:
> > This application has failed to start because
> > the application configuration is incorrect.
> > Reinstalling the application may fix this problem.
> >
> >
> > Anyone have the same problem with this?.
> 
> http://www.py2exe.org/index.cgi/Py2exeAndWin32ui
> 
> Rob.
> 


From no.email at nospam.invalid  Tue May 11 21:31:03 2010
From: no.email at nospam.invalid (Paul Rubin)
Date: Tue, 11 May 2010 18:31:03 -0700
Subject: Is Python a functional programming language?
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
	<7xvdau8pzl.fsf@ruckus.brouhaha.com>
	
Message-ID: <7xr5lhaotk.fsf@ruckus.brouhaha.com>

Nobody  writes:
>> is called an "equation" rather than an "assignment".  It declares "x is
>> equal to 3", rather than directing x to be set to 3.  If someplace else in
>> the program you say "x = 4", that is an error, normally caught by the
>> compiler, since x cannot be equal to both 3 and 4.
>
> In both ML and Haskell, bindings are explicitly scoped, i.e.
> 	let x = 3 in ...	(Haskell)

I'm not talking about nested bindings.  I'm talking about two different
bindings of the same symbol in the same scope:

    $ cat meow.hs
    x = 3
    x = 4
    $ ghc meow.hs

    meow.hs:2:0:
        Multiple declarations of `Main.x'
        Declared at: meow.hs:1:0
                     meow.hs:2:0


From tjreedy at udel.edu  Tue May 11 21:50:02 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 21:50:02 -0400
Subject: Upgrade Python 2.6.4 to 2.6.5
In-Reply-To: <1273613223.8700.1374581741@webmail.messagingengine.com>
References: 	<4BE86BC1.8040102@v.loewis.de>	<4BE9C893.1070104@v.loewis.de>
	<1273613223.8700.1374581741@webmail.messagingengine.com>
Message-ID: 

On 5/11/2010 5:27 PM, python at bdurham.com wrote:
> Martin,
>
> If we install over an existing version of Python 2.6.5, will our PTH
> files and site-packages be preserved?
>
> Or do we need to back out our 3rd party packages, install Python 2.6.5
> and then manually restore our 3rd party packages?

In my experience on WinXP, installing x.y.z+1 over x.y.z nicely leaves 
sitepackages alone as well as any other directories I have added under 
the pythonxy directory. An uninstall and reinstall should also leave 
user stuff alone.

Installing x.y+1 create and install in a new pythonx directory, 
leaving one to copy from pythonxy subdirs as desired.

It appears that the OP confused things by switching between one and all 
user installs.

Terry Jan Reedy





From zhenhua.zhang at intel.com  Tue May 11 21:59:52 2010
From: zhenhua.zhang at intel.com (Zhang, Zhenhua)
Date: Wed, 12 May 2010 09:59:52 +0800
Subject: How to pass file descriptor through dbus call in python
Message-ID: <33AB447FBD802F4E932063B962385B351E79F6EB@shsmsx501.ccr.corp.intel.com>

Hi,
Hi,

DBus 1.3 supports passing file descriptor through dbus method call. So I am writing a python test case to verify my interface. Can someone answer my question: how to pass a file descriptor through python-dbus call? For example:

	import os
	
	m, s = os.openpty()
	
	bus = dbus.SystemBus()
	obj = dbus.Interface(bus.get_object('org.xxx', '/', interface)
	obj.Create(m)

Python tells me that: org.freedesktop.DBus.Error.UnknowMethod: Method 'Create' with signature "i" on interface 'xxx' doesn't exist. Obviously it interprets 'm' as 'i' instead of 'h'.

Regards,
Zhenhua
 

From tjreedy at udel.edu  Tue May 11 22:07:35 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 22:07:35 -0400
Subject: Limitation of os.walk
In-Reply-To: 
References: 
Message-ID: 

On 5/11/2010 3:49 PM, kj wrote:
>
>
>
> I want implement a function that walks through a directory tree
> and performs an analsysis of all the subdirectories found.  The
> task has two essential requirements that, AFAICT, make it impossible
> to use os.walk for this:
>
> 1. I need to be able to prune certain directories from being visited.
>
> 2. The analysis on each directory can be performed only after it
>     has been performed on all its subdirectories.
>
> Unless I'm missing something, to do (1), os.walk must be run with
> topdown=True, whereas to do (2) it must be run with topdown=False.
>
> Is there a work around that I'm missing?

(I was going to say, 'Copy the code from os.py and revise to suit' -- 
but I see this has been posted since I wrote it ;-)

> PS: I never understood why os.walk does not support hooks for key
> events during such a tree traversal.

Either 1) it is intentionally simple, with the expectation that people 
would write there own code for more complicated uses or 2) no one has 
submitted a 'full-featured' version or 3) both.

If os.walk were rewritten, it should be as an iterator (generator). 
Directory entry and exit functions could still be added as params.

Terry Jan Reedy






From tjreedy at udel.edu  Tue May 11 22:21:08 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 22:21:08 -0400
Subject: Extract all words that begin with x
In-Reply-To: <1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com>
References: 	
	
		
	<1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com>
Message-ID: 

On 5/11/2010 6:01 PM, Bryan wrote:
> Tycho Andersen wrote:
>> Terry Reedy wrote:
>>>   ... word[0:1] does the same thing. All Python programmers should learn to
>>> use slicing to extract a  char from a string that might be empty.
>>> The method call of .startswith() will be slower, I am sure.
>>
>> Why? Isn't slicing just sugar for a method call?
>
> Yes, but finding the method doesn't require looking it up by name at
> run-time, and startswith is built to work for startings of any length.
>
> Let's timeit:
>
> # -----
> from timeit import Timer
> from random import choice
> from string import ascii_lowercase as letters
>
> strs = [''.join([choice(letters) for _ in range(5)])
>          for _ in range(5000)]
>
> way1 = "[s for s in strs if s.startswith('a')]"
> way2 = "[s for s in strs if s[:1] == 'a']"
>
> assert eval(way1) == eval(way2)
>
> for way in [way1, way2]:
>      t = Timer(way, 'from __main__ import strs')
>      print(way, ' took: ', t.timeit(1000))
>
> # -----
>
> On my particular box, I get:
>
> [s for s in strs if s.startswith('a')]  took:  5.43566498797
> [s for s in strs if s[:1] == 'a']  took:  3.20704924968
>
> So Terry Reedy was right: startswith() is slower. I would,
> nevertheless, use startswith(). Later, if users want my program to run
> faster and my profiling shows a lot of the run-time is spent finding
> words that start with 'a', I might switch.

Thank you for that timing report.

My main point is that there are two ways to fetch a char, the difference 
being the error return -- exception IndexError versus error value ''. 
This is an example of out-of-band versus in-band error/exception 
signaling, which programmers, especially of Python, should understand.

The fact that in Python syntax tends to be faster than calls was 
secondary, though good to know on occasion.

.startswith and .endswith are methods that wrap the special cases of 
slice at an end and compare to one value. There are not necessary, and 
save no keystrokes, but Guido obviously thought they added enough to 
more than balance the slight expansion of the language. They were added 
after I learned Python and I thought the tradeoff to be a toss-up, but I 
will consider using the methods when writing didactic code meant to be 
read by others.

Terry Jan Reedy



From ldo at geek-central.gen.new_zealand  Tue May 11 22:31:04 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Wed, 12 May 2010 14:31:04 +1200
Subject: virtualenvwrapper for Windows (Powershell)
References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com>
	
	<973ca0fa-4a2f-4e3b-91b9-e38917885c0f@d27g2000yqc.googlegroups.com>
Message-ID: 

In message
<973ca0fa-4a2f-4e3b-91b9-e38917885c0f at d27g2000yqc.googlegroups.com>, 
Guillermo wrote:

> On May 11, 7:43 am, Lawrence D'Oliveiro 
> wrote:
>
>> In message
>> <22cf35af-44d1-43fe-8b90-07f2c6545... at i10g2000yqh.googlegroups.com>,
>>
>> Guillermo wrote:
>>
>>> If you've ever missed it on Windows and you can use Powershell ...
>>
>> I thought the whole point of Windows was to get away from this
>> command-line stuff. Not such a good idea after all?
> 
> I suppose it depends.

On the way it?s implemented? Microsoft seems to have botched that as well.


From tjreedy at udel.edu  Tue May 11 22:32:22 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Tue, 11 May 2010 22:32:22 -0400
Subject: First Timer
In-Reply-To: 
References: <002c01caf140$11a0eb00$34e2c100$@com>	
	
Message-ID: 

On 5/11/2010 7:03 PM, Mensanator wrote:
> On May 11, 4:37 pm, Terry Reedy  wrote:
>
>> In the command line interpreter, you should be able to hit up
>> arrow and have the line above copied to the current entry line for
>> correction. In IDLE, this does not yet work,
>
> It doesn't have to. Simply place the cursor on the line you originally
> entered and hit.
>
>> so copy and paste or retype.
>
> The line will be repeated as a new line which you can edit
> and make corrections.

Thank you for the information. I obviously have never seen that written 
anywhere and never thought to try it. It will save me time.

>> For anything too complicated for either of those (more than one line), I
>> use (and reuse) a temporary edit file in an edit window. Just make sure
>> the file is named.py rather than just. You save
>> and run the file with F5. If there is a syntax error, IDLE will say so
>> and reopen the cursor window with the cursor at (or after) the location
>> of the error. Fix and hit F5 again. Very fast.
>
> Sounds like you're making a mountain out of a molehill. You deserve
> a medal if you've been using IDLE without knowing how to edit.

Huh? I was explaining, perhaps clumbsily, how to easily edit, run, 
re-edit, and re-run multiple statements, in an editor window meant for 
that job, which cannot so easily be done in the shell, if at all.

Unlike the raw interpreter window, IDLE does not allow pasting of 
multiple statements in its simulated shell (well it does, but it ignores 
any after the first). So using an editor window in that case also is 
necessary.

Terry Jan Reedy



From python.list at tim.thechases.com  Tue May 11 22:38:02 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Tue, 11 May 2010 21:38:02 -0500
Subject: Limitation of os.walk
In-Reply-To: 
References:  
Message-ID: <4BEA148A.7020800@tim.thechases.com>

  05/11/2010 09:07 PM, Terry Reedy wrote:
>> PS: I never understood why os.walk does not support hooks for key
>> events during such a tree traversal.
>
> Either 1) it is intentionally simple, with the expectation that people
> would write there own code for more complicated uses or 2) no one has
> submitted a 'full-featured' version or 3) both.
>
> If os.walk were rewritten, it should be as an iterator (generator).
> Directory entry and exit functions could still be added as params.

It *is* an iterator/generator.  However, I suspect you mean that 
it should slurp the dirs/files iteratively instead of using 
listdir() as was discussed on c.l.p a few months back.

The patch to os.py would be fairly simple, something like
--------------------------------------------
--- /usr/lib/python2.5/os.py
+++ ~/tmp/os.py
@@ -220,7 +220,7 @@

  __all__.extend(["makedirs", "removedirs", "renames"])

-def walk(top, topdown=True, onerror=None):
+def walk(top, topdown=True, onerror=None, pre=None, post=None):
      """Directory tree generator.

      For each directory in the directory tree rooted at top 
(including top
@@ -296,15 +296,19 @@
          else:
              nondirs.append(name)

+    if pre is not None:
+        top, dirs, nondirs = pre(top, dirs, nondirs)
      if topdown:
          yield top, dirs, nondirs
      for name in dirs:
          path = join(top, name)
          if not islink(path):
-            for x in walk(path, topdown, onerror):
+            for x in walk(path, topdown, onerror, pre=pre, 
post=post):
                  yield x
      if not topdown:
          yield top, dirs, nondirs
+    if post is not None:
+        post(top, dirs, nondirs)

--------------------------------------------

which would allow you to do things like

   def pre(top, dirs, nondirs):
       dirs = [d for d in dirs
               if d not in ('RCS', '.svn', '.hg', '.git')]
       return top, dirs, nondirs
   def post(top, dirs, nondirs):
       complex_process(top)
   for top, dirs, nondirs in my.walk(PATH, pre=pre, post=post):
       do_stuff(...)

I suspect if I thought about it much longer, only one would 
really be needed, the other accommodated by the "topdown" parameter.

-tkc





From lie.1296 at gmail.com  Tue May 11 23:06:53 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 12 May 2010 13:06:53 +1000
Subject: Picking a license
In-Reply-To: 
References: 
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com>
	
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com>
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com>
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com>
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com>
	
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com>
	<4be95545$1@dnews.tpgi.com.au>
	
	
Message-ID: <4bea1bac$1@dnews.tpgi.com.au>

On 05/12/10 07:02, Patrick Maupin wrote:
> On May 11, 9:00 am, Paul Boddie  wrote:
>> On 11 Mai, 15:00, Lie Ryan  wrote:
>>> Come on, 99%  of the projects released under GPL did so because they
>>> don't want to learn much about the law; they just need to release it
>>> under a certain license so their users have some legal certainty.
>>
>> Yes, this is frequently the case. And the GPL does offer some
>> certainty that various permissive licences do not.
> 
> Huh? Permissive licenses offer much better certainty for someone
> attempting a creative mash-up.  Different versions of the Apache
> license don't conflict with each other.  If I use an MIT-licensed
> component, it doesn't attempt to make me offer my whole work under
> MIT.

Legal certainty as in, imagine if you released a piece of code, and use
this as the license:

"Feel free to use the code"

Then some other programmers see it, and use it in their project. The
original author then sued them because he actually intended the code to
be linked to, not copied pasted into another code base.

Then he modified the license to sound:

"Feel free to link, include, or use the code"

Then some other programmers see the code, and modified it to fit their
purpose. The original author then sued them because he only intended the
code to be "used unchanged" not "modified".


"Feel free to link, include, use, or modify the code"

Then some other programmers see the code, and used it in some commercial
project. The original author then sued them because he only intended the
code to be used in open source projects.


Lather, Rinse, Repeat and you get twenty page long license like GPL or
OWL[*]. By this time, the other programmer have learnt not to use code
with such uncertain license and the original author would either have
taken a law degree or learn to use a well-known licenses (GPL or
whatever) instead of writing his own.

The other programmer would always find a loophole in such ad-hoc
license, inadvertantly or otherwise. If  the original author used GPL
(or OWL), the other programmer knows exactly when their use case is
protected by GPL/OWL (i.e. even if the original author later found that
he disagrees with a certain clause in the license he choose, it then
becomes his fault for choosing it; the other programmer's use case is
protected by the license and thus he have the legal certainty).

[*] OWL: other well-known license

As a plus, using a well-known license means the other programmer also
don't need to hire a lawyer to determine whether he can use your code.
The other programmer sees GPL and remembers that FSF listed the license
he's using as GPL-compatible, he knows immediately he can use the code
without reading the full text of GPL. The other programmer sees some
Apache and he remembers previously he had used another Apache-licensed
code and knows immediately that he can use this other Apache project. If
everyone writes their own license, then this knowledge reuse wouldn't be
possible.

>> Well, that's always an option as well, but at the same time, there are
>> people willing to pursue licence violations, and these people have
>> done so successfully. There's no need to make an impassioned argument
>> for apathy, though. Some people do wish to dictate what others can do
>> with their work.
> 
> Oh, I get it.  You were discussing the certainty that an author can
> control what downstream users do with the software to some extent.
> Yes, I fully agree.  The GPL is for angry idealists who have an easily
> outraged sense of justice, who don't have enough real problems to work
> on.

The point is, GPL (and OWL) is for programmers who just don't care about
the legal stuffs and would want to spend more time writing code than
writing license.


From kushal.kumaran+python at gmail.com  Tue May 11 23:13:29 2010
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Wed, 12 May 2010 08:43:29 +0530
Subject: HTTP Post Request
In-Reply-To: <2b94f35e-b3a0-49db-a66a-9ee1bf104a41@h20g2000prn.googlegroups.com>
References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com>
	
	<06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com>
	
	<95e73ff4-abe5-4874-8652-647818ed224a@k29g2000yqh.googlegroups.com>
	<2b94f35e-b3a0-49db-a66a-9ee1bf104a41@h20g2000prn.googlegroups.com>
Message-ID: 

On Tue, May 11, 2010 at 3:59 PM, kaklis at gmail.com  wrote:
> On May 11, 10:56?am, "kak... at gmail.com"  wrote:
>> On May 11, 5:06?am, Kushal Kumaran 
>> wrote:
>>
>>
>>
>> > On Mon, May 10, 2010 at 8:26 PM, kak... at gmail.com  wrote:
>> > > On May 10, 10:22?am, Kushal Kumaran 
>> > > wrote:
>> > >> On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com  wrote:
>> > >> > Hi to all, i want to ask you a question, concerning the best way to do
>> > >> > the following as a POST request:
>> > >> > There is server-servlet that accepts xml commands
>> > >> > It had the following HTTP request headers:
>>
>> > >> > ? ? ? ? ? ?Host: somehost.com
>> > >> > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient
>> > >> > ? ? ? ? ? ?Content-Type: text/xml
>> > >> > ? ? ? ? ? ?Content-Length: 415
>>
>> > >> > and the following request body (reformatted here for clarity):
>>
>> > >> > ? ? ? ? ? ?
>> > >> > ? ? ? ? ? ?
>> > >> > ? ? ? ? ? ? ?search
>> > >> > ? ? ? ? ? ?
>> > >> > How can i send the above to the Listener Servlet?
>> > >> > Thanks in advance
>>
>> > >> Use the xmlrpclib module.
>>
>> > > OK, sending headers with xmlrpclib,
>> > > but how do i send the XML message?
>>
>> > Your XML message is an XML RPC message. ?You will use xmlrpclib like this:
>>
>> > server_proxy = xmlrpclib.ServerProxy(('somehost.com', 80))
>> > result = server_proxy.search()
>>
>> > The call to server_proxy.search will result in an actual XML RPC
>> > message being sent.
>>
>> > Read up on the xmlrpclib documentation here:http://docs.python.org/library/xmlrpclib.html, and the XMLRPC spec
>> > here:http://www.xmlrpc.com/spec
>>
>>
>> Ok I got it!
>> Thank you!!!
>>
>> A.K
>
> Apparently the server i'm trying to connect accepts only POST
> connections. So xmlrpclib is useless.
> I think I need the httplib library module.
>
> Any hints?
>

I don't understand.  xmlrpclib sends POST requests only.  Are you
getting an exception?  If so, please post the entire stack trace.

If you want to send the data "by hand", use the httplib module.  you
can pass your XML to the HTTPConnection.request method as the "body"
argument.

-- 
regards,
kushal


From martin at v.loewis.de  Wed May 12 00:03:55 2010
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Wed, 12 May 2010 06:03:55 +0200
Subject: Upgrade Python 2.6.4 to 2.6.5
In-Reply-To: <1273613223.8700.1374581741@webmail.messagingengine.com>
References: 
	<4BE86BC1.8040102@v.loewis.de>
	<4BE9C893.1070104@v.loewis.de>
	<1273613223.8700.1374581741@webmail.messagingengine.com>
Message-ID: <4BEA28AB.6050505@v.loewis.de>

> If we install over an existing version of Python 2.6.5, will our PTH
> files and site-packages be preserved?
> 
> Or do we need to back out our 3rd party packages, install Python 2.6.5
> and then manually restore our 3rd party packages?

An upgrade installation will only replace the Python files, and leave
all other files alone.

Regards,
Martin


From python.leojay at gmail.com  Wed May 12 00:04:41 2010
From: python.leojay at gmail.com (Leo Jay)
Date: Wed, 12 May 2010 12:04:41 +0800
Subject: Why the inconsistent of those two base64 methods?
Message-ID: 

I'd like to encode a string in base64, but I found a inconsistent of
two methods:

>>> 'aaa'.encode('base64')
'YWFh\n'
>>> import base64
>>> base64.b64encode('aaa')
'YWFh'
>>>


as you can see, the result of
'aaa'.encode('base64')
has a '\n' at the end, but the other method doesn't.

Why the inconsistent?
Thanks.

-- 
Best Regards,
Leo Jay


From dasacc22 at gmail.com  Wed May 12 00:10:46 2010
From: dasacc22 at gmail.com (dasacc22)
Date: Tue, 11 May 2010 21:10:46 -0700 (PDT)
Subject: Fastest way to calculate leading whitespace
References: <60089b4f-0513-400e-96bd-489711283b74@l31g2000yqm.googlegroups.com>
	
	
Message-ID: <7e14423c-95e0-4b2d-93b3-504a282e5f53@p2g2000yqh.googlegroups.com>

On May 10, 2:25?am, Stefan Behnel  wrote:
> Stefan Behnel, 10.05.2010 08:54:
>
>
>
>
>
> > dasacc22, 08.05.2010 19:19:
> >> This is a simple question. I'm looking for the fastest way to
> >> calculate the leading whitespace (as a string, ie ' ').
>
> > Here is an (untested) Cython 0.13 solution:
>
> > ? ? from cpython.unicode cimport Py_UNICODE_ISSPACE
>
> > ? ? def leading_whitespace(unicode ustring):
> > ? ? ? ? cdef Py_ssize_t i
> > ? ? ? ? cdef Py_UNICODE uchar
>
> > ? ? ? ? for i, uchar in enumerate(ustring):
> > ? ? ? ? ? ? if not Py_UNICODE_ISSPACE(uchar):
> > ? ? ? ? ? ? ? ? return ustring[:i]
> > ? ? ? ? return ustring
>
> > Cython compiles this to the obvious C code, so this should be impossible
> > to beat in plain Python code.
>
> ... and it is. For a simple string like
>
> ? ? ?u = u" ? abcdefg" + u"fsdf"*20
>
> timeit gives me this for "s=u.lstrip(); u[:-len(s)]":
>
> 1000000 loops, best of 3: 0.404 usec per loop
>
> and this for "leading_whitespace(u)":
>
> 10000000 loops, best of 3: 0.0901 usec per loop
>
> It's closer for the extreme case of an all whitespace string like " "*60,
> where I get this for the lstrip variant:
>
> 1000000 loops, best of 3: 0.277 usec per loop
>
> and this for the Cython code:
>
> 10000000 loops, best of 3: 0.177 usec per loop
>
> But I doubt that this is the main use case of the OP.
>
> Stefan

indeed, actually ive been going back and forth on the idea to use
cython for some more intensive portions. That bit of code looks really
simple so I think I'll give cython a shot. Only deal is I need to be
able to use w/e the latest cython is available via easy_install, but
this should prove an interesting experience.


From hnassrat at gmail.com  Wed May 12 00:38:47 2010
From: hnassrat at gmail.com (Hatem Nassrat)
Date: Wed, 12 May 2010 01:38:47 -0300
Subject: PEP 3119 ABC - And how I learned to love the Abstract Bomb
Message-ID: 

Today I was doing a major re-write of a library I called yajl-py that
wraps the json 'sax-like' c-parser yajl, and decided I should look
into absract base classes since I knew they had been added to py26.
Truthfully, I was surprised when I found out that the BDFL accepted
this PEP, but hey were in 2010 :p.

So I was getting around to using it when I realised that I cannot make
my class as abstract as can be. Here is my?dilemma / requirements:

1. To create a YajlContentHandler class that forces all sub-classers
to implement a certain set of methods. (Great, thats what ABC is for)

There is a certain set of mutually exclusive callbacks, i.e. if you
implement the first set you need not implement the second, and vice
versa, so my second requirement is:

2. Conditional Abstractness! if certain methods are not implemented
then be able to require some method to be implemented.

Python is more flexible than Java, so having Conditional Meta Abstract
Base Classes seems only natural :P, maybe someone should write a PEP.
This only reminds me of the following tweet:
http://twitter.com/bos31337/status/13349058839

--
Hatem Nassrat


From aahz at pythoncraft.com  Wed May 12 01:18:25 2010
From: aahz at pythoncraft.com (Aahz)
Date: 11 May 2010 22:18:25 -0700
Subject: Extract all words that begin with x
References: 
	
	<1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com>
	
Message-ID: 

In article ,
Terry Reedy   wrote:
>
>.startswith and .endswith are methods that wrap the special cases of 
>slice at an end and compare to one value. There are not necessary, and 
>save no keystrokes, but Guido obviously thought they added enough to 
>more than balance the slight expansion of the language. They were added 
>after I learned Python and I thought the tradeoff to be a toss-up, but I 
>will consider using the methods when writing didactic code meant to be 
>read by others.

They were also added after I learned Python, and I think they're great!
Using them signals that you're doing simple string checking rather than
some more arcane slicing.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From gagsl-py2 at yahoo.com.ar  Wed May 12 01:29:01 2010
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 12 May 2010 02:29:01 -0300
Subject: PEP 3119 ABC - And how I learned to love the Abstract Bomb
References: 
Message-ID: 

En Wed, 12 May 2010 01:38:47 -0300, Hatem Nassrat   
escribi?:

> 1. To create a YajlContentHandler class that forces all sub-classers
> to implement a certain set of methods. (Great, thats what ABC is for)
>
> There is a certain set of mutually exclusive callbacks, i.e. if you
> implement the first set you need not implement the second, and vice
> versa, so my second requirement is:
>
> 2. Conditional Abstractness! if certain methods are not implemented
> then be able to require some method to be implemented.

Mmm, can't you use two separate ABCs? Perhaps inheriting from a common  
base.

-- 
Gabriel Genellina



From mensanator at aol.com  Wed May 12 01:56:51 2010
From: mensanator at aol.com (Mensanator)
Date: Tue, 11 May 2010 22:56:51 -0700 (PDT)
Subject: First Timer
References: <002c01caf140$11a0eb00$34e2c100$@com>
	 
	 
	
Message-ID: 

On May 11, 9:32?pm, Terry Reedy  wrote:
> On 5/11/2010 7:03 PM, Mensanator wrote:
>
> > On May 11, 4:37 pm, Terry Reedy ?wrote:
>
> >> In the command line interpreter, you should be able to hit up
> >> arrow and have the line above copied to the current entry line for
> >> correction. In IDLE, this does not yet work,
>
> > It doesn't have to. Simply place the cursor on the line you originally
> > entered and hit.
>
> >> so copy and paste or retype.
>
> > The line will be repeated as a new line which you can edit
> > and make corrections.
>
> Thank you for the information. I obviously have never seen that written
> anywhere and never thought to try it. It will save me time.
>
> >> For anything too complicated for either of those (more than one line), I
> >> use (and reuse) a temporary edit file in an edit window. Just make sure
> >> the file is named.py rather than just. You save
> >> and run the file with F5. If there is a syntax error, IDLE will say so
> >> and reopen the cursor window with the cursor at (or after) the location
> >> of the error. Fix and hit F5 again. Very fast.
>
> > Sounds like you're making a mountain out of a molehill. You deserve
> > a medal if you've been using IDLE without knowing how to edit.
>
> Huh? I was explaining, perhaps clumbsily, how to easily edit, run,
> re-edit, and re-run multiple statements, in an editor window meant for
> that job, which cannot so easily be done in the shell, if at all.
>
> Unlike the raw interpreter window, IDLE does not allow pasting of
> multiple statements in its simulated shell (well it does, but it ignores
> any after the first).

Really? Touche, I didn't know that.

Because it would never occur to me. The only time I would need
multiple
lines is in a def situation. And placing the cursor on the def line
repeats
the ENTIRE definition, spanning as many lines as needed, all of which
can be
edited.

Sure, I'll open an edit window when things get messy or need to be
saved.
But often the IDLE prompt is all I need

> So using an editor window in that case also is
> necessary.
>
> Terry Jan Reedy



From bryanjugglercryptographer at yahoo.com  Wed May 12 02:55:39 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Tue, 11 May 2010 23:55:39 -0700 (PDT)
Subject: Extract all words that begin with x
References: 
	 
	 
	
	 
	<1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com> 
	
Message-ID: <1295fd82-39ba-4edc-ad01-ee5f9fd8dc19@a39g2000prb.googlegroups.com>

Terry Reedy wrote:
> Thank you for that timing report.

Enjoyed doing it, and more on that below.

> My main point is that there are two ways to fetch a char, the difference
> being the error return -- exception IndexError versus error value ''.
> This is an example of out-of-band versus in-band error/exception
> signaling, which programmers, especially of Python, should understand.

Sure. I think your posts and the bits of Python code they contain are
great. Slicing is amazingly useful, and it helps that slices don't
barf just because 'start' or 'stop' falls outside the index range.

My main point was to show off how Python and its standard library make
answering the which-is-faster question easy. I think that's another
thing Python programmers should understand, even though I just learned
how today.

Now back to the arguably-interesting issue of speed in the particular
problem here: 'Superpollo' had suggested another variant, which I
appended to my timeit targets, resulting in:

[s for s in strs if s.startswith('a')]  took:  5.68393977159
[s for s in strs if s[:1] == 'a']  took:  3.31676491502
[s for s in strs if s and s[0] == 'a']  took:  2.29392950076

Superpollo's condition -- s and s[0] == 'a' -- is the fastest of the
three.

What's more, in my timeit script the strings in the list are all of
length 5, so the 'and' never gets to short-circuit. If a major portion
of the strings are in fact empty superpollo's condition should do even
better. But I didn't test and time that. Yet.

-Bryan Olson


# ----- timeit code -----

from random import choice
from string import ascii_lowercase as letters
from timeit import Timer

strs = [''.join([choice(letters) for _ in range(5)])
        for _ in range(5000)]

way1 = "[s for s in strs if s.startswith('a')]"
way2 = "[s for s in strs if s[:1] == 'a']"
way3 = "[s for s in strs if s and s[0] == 'a']"

assert eval(way1) == eval(way2) == eval(way3)

for way in [way1, way2, way3]:
    t = Timer(way, 'from __main__ import strs')
    print(way, ' took: ', t.timeit(1000))


From bryanjugglercryptographer at yahoo.com  Wed May 12 02:59:29 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Tue, 11 May 2010 23:59:29 -0700 (PDT)
Subject: Iterating over dict and removing some elements
References: 
	 
	
Message-ID: 

Terry Reedy wrote:
[...]
> for k in [k for k in d if d[k] == 'two']:
> ? ? ? ? ?d.pop(k)

We have a winner.


--
--Bryan




From puntabluda at gmail.com  Wed May 12 02:59:44 2010
From: puntabluda at gmail.com (Rebelo)
Date: Wed, 12 May 2010 08:59:44 +0200
Subject: Iterating over dict and removing some elements
In-Reply-To: 
References: 
Message-ID: 

On 05/11/2010 05:08 PM, Ulrich Eckhardt wrote:
> Hi!
>
> I wrote a simple loop like this:
>
>    d = {}
>    ...
>    for k in d:
>        if some_condition(d[k]):
>            d.pop(k)
>
> If I run this, Python complains that the dictionary size changed during
> iteration. I understand that the iterator relies on the internal structure
> not changing, but how would I structure this loop otherwise?
>
> My first approach was to simply postpone removing the elements, but I was
> wondering if there was a more elegant solution.
>
> Thanks!
>
> Uli
>


i am wondering why not like this:

 >>> d = {1: 'one', 2: 'two', 3: 'three'}
 >>> for k,v in d.items():
...     if k==1:
...          del d[k]
...
 >>> d
{2: 'two', 3: 'three'}
 >>>



From mhv at dmu.dk  Wed May 12 03:08:49 2010
From: mhv at dmu.dk (Hvidberg, Martin)
Date: Wed, 12 May 2010 09:08:49 +0200
Subject: Re.: reading xml from python - Sum-up
Message-ID: 

Thanks to all - Just to give a positive feed back.
The following solution works for me:


from xml.etree.ElementTree import ElementTree

tree = ElementTree()

tree.parse('inifile.xml')

dicIni = dict((child.tag, child.text) for child in tree.getroot().getchildren())

:-) Martin



This email is made of 100% recycled bytes ...


________________________________
From: Hvidberg, Martin
Sent: Tuesday, May 11, 2010 2:54 PM
To: 'python-list at python.org'
Subject: reading xml from python

I'm looking for at way to read (and later write) small simple .xml file from Python.

e.g. I would like to read the following from a small ini.xml file into a dictionary.



 default
 False
 False
 UBMlight
 True

I would prefer a relative simple (not too much creating new classes) way to do this.

Any suggestions appreciated.

:-) Martin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From lie.1296 at gmail.com  Wed May 12 03:19:26 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 12 May 2010 17:19:26 +1000
Subject: Picking a license
In-Reply-To: 
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
Message-ID: <4bea56dd$1@dnews.tpgi.com.au>

On 05/12/10 06:50, Patrick Maupin wrote:
> On May 11, 5:34 am, Paul Boddie  wrote:
>> On 10 Mai, 20:36, Patrick Maupin  wrote:
>>>  The fact is, I know the man would force me to pay for the chocolate, so in
>>> some cases that enters into the equation and keeps me from wanting the
>>> chocolate.
>>
>> If the man said, "please take the chocolate, but I want you to share
>> it with your friends", and you refused to do so because you couldn't
>> accept that condition, would it be right to say, "that man is forcing
>> me to share chocolate with my friends"?
> 
> But the thing is, he's *not* making me share the chocolate with any of
> my friends.  He's not even making me share my special peanut butter
> and chocolate.  What he's making me do is, if I give my peanut butter
> and chocolate to one of my friends, he's making me make *that* friend
> promise to share.  I try not to impose obligations like that on my
> friends, so obviously the "nice" man with the chocolate isn't my
> friend!

The analogy breaks here; unlike chocolate, the value of software/source
code, if shared, doesn't decrease (in fact, many software increases its
value when shared liberally, e.g. p2p apps).

There might be certain cases where the software contains some trade
secret whose value decreases the more people knows about it; but sharing
does not decrease the value of the software, at least not directly, it
is the value of the secret that decreases because of the sharing.


From werner.bruhin at free.fr  Wed May 12 03:24:49 2010
From: werner.bruhin at free.fr (Werner F. Bruhin)
Date: Wed, 12 May 2010 09:24:49 +0200
Subject: Upgrade Python 2.6.4 to 2.6.5
In-Reply-To: <4BE9C893.1070104@v.loewis.de>
References: 	<4BE86BC1.8040102@v.loewis.de>
	
	<4BE9C893.1070104@v.loewis.de>
Message-ID: <4BEA57C1.7080005@free.fr>

On 11/05/2010 23:13, Martin v. Loewis wrote:
>> When will it install into system32?
>>      
> When you install "for all users".
>
>    
>>> Did the upgrade inform you that it was an upgrade, or did it warn you
>>> that you would overwrite the previous installation?
>>>
>>>        
>> It warned me that there is a previous installation.
>>      
> Hmm. You don't remember the exact message, do you?
> I guess it was a popup saying "[TARGETDIR] exists. Are you sure you want
> to overwrite existing files?", and that it was not
> a red text saying "This update will replace your existing [ProductLine]
> installation."
>
> Please confirm.
>    
Correct that was it.
> If so, you now have two Python installations in the same location; one
> for all users, and the older one just for you (or vice versa).
>    
Yes, that is what I did ages ago.
> I recommend to uninstall them both, and start over.
>    
O.K., will do that.

Thanks for your help
Werner



From bruno.42.desthuilliers at websiteburo.invalid  Wed May 12 03:25:23 2010
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Wed, 12 May 2010 09:25:23 +0200
Subject: accessing superclass methods from subclass
In-Reply-To: 
References: <4f8532ab-1ee1-4920-996b-b83697a1ca04@q32g2000yqb.googlegroups.com>		
	
Message-ID: <4bea57d7$0$20587$426a74cc@news.free.fr>

Chris Rebert a ?crit :
(snip)
> Here is how I would rewrite your example:
> 
> class Shape(object):
>     def __init__(self, x=0, y=0):
>         self.x = x
>         self.y = y
> 
>     @property
>     def location(self):
>         return (self.x, self.y)
> 
>     @location.setter
>     def location(self, val):
>        self.x, self.y = val

Not necessary but helps documenting the expected interface:

       def draw(self):
           raise NotImplementedError("Abstract method")

> class Square(Shape):
>    def __init__(self,size):
>        super(Square, self).__init__()
>        self.size = size

Why can't I specify a Square location ??? This looks rather inconsistant 
and inconveniant to me...

     def __init__(self, x=0, y=0, size=0):
         super(Square, self).__init__(x, y)
         self.size = size
	

>    def draw(self):
>        x, y = self.location
>        # code to draw shape from location[0],location[1] at size size
>        # etc...
> 


From varahalu2400 at yahoo.co.in  Wed May 12 03:27:16 2010
From: varahalu2400 at yahoo.co.in (varahalu 2400)
Date: Wed, 12 May 2010 12:57:16 +0530 (IST)
Subject: Python-list Digest, Vol 80, Issue 108
In-Reply-To: 
References: 
Message-ID: <483577.5422.qm@web8706.mail.in.yahoo.com>

please dont send mails




________________________________
From: "python-list-request at python.org" 
To: python-list at python.org
Sent: Wed, 12 May, 2010 12:00:02 AM
Subject: Python-list Digest, Vol 80, Issue 108

Note: Forwarded message is attached.

Send Python-list mailing list submissions to
    python-list at python.org

To subscribe or unsubscribe via the World Wide Web, visit
    http://mail.python.org/mailman/listinfo/python-list
or, via email, send a message with subject or body 'help' to
    python-list-request at python.org

You can reach the person managing the list at
    python-list-owner at python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Python-list digest..."
Today's Topics:

   1. Re: HTTP Post Request (Kushal Kumaran)
   2. Re: Picking a license (Lie Ryan)
   3. Re: Upgrade Python 2.6.4 to 2.6.5 (Martin v. L?wis)
   4. Why the inconsistent of those two base64 methods? (Leo Jay)
   5. Re: Fastest way to calculate leading whitespace (dasacc22)
   6. PEP 3119 ABC - And how I learned to love the Abstract Bomb
      (Hatem Nassrat)
   7. Re: Extract all words that begin with x (Aahz)
   8. Re: PEP 3119 ABC - And how I learned to love the Abstract
      Bomb (Gabriel Genellina)
   9. Re: First Timer (Mensanator)
  10. Re: Extract all words that begin with x (Bryan)
-- 
http://mail.python.org/mailman/listinfo/python-list

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From bryanjugglercryptographer at yahoo.com  Wed May 12 03:28:43 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Wed, 12 May 2010 00:28:43 -0700 (PDT)
Subject: Iterating over dict and removing some elements
References: 
	
Message-ID: <8465ce4b-8ddb-4bfb-ba31-25ad1c0924a0@s13g2000prc.googlegroups.com>

Rebelo wrote:
> i am wondering why not like this:
>
> ?>>> d = {1: 'one', 2: 'two', 3: 'three'}
> ?>>> for k,v in d.items():
> ... ? ? if k==1:
> ... ? ? ? ? ?del d[k]
> ...
> ?>>> d
> {2: 'two', 3: 'three'}
> ?>>>

Mostly because there's no reason to get 'v' if you're not going to use
it. That may be just because you simplified the example, and if you
are working in Python 2.x and the real test for whether to delete
involves the value and not just the key, that's a reasonable solution.

On subtler issues, it constucts an unnecessarily long temporary list
in current Python 2.X, and fails in Python 3.x, as Terry Ready
explained.


--
--Bryan


From kaklis at gmail.com  Wed May 12 03:38:32 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Wed, 12 May 2010 00:38:32 -0700 (PDT)
Subject: HTTP Post Request
References: <0de340e6-e7d0-4659-b18f-b6c6df44c9b4@i9g2000yqi.googlegroups.com>
	
	<06743e3b-f792-43f6-bd0b-fe10a457d223@p2g2000yqh.googlegroups.com>
	
	<95e73ff4-abe5-4874-8652-647818ed224a@k29g2000yqh.googlegroups.com>
	<2b94f35e-b3a0-49db-a66a-9ee1bf104a41@h20g2000prn.googlegroups.com> 
	
Message-ID: <4325e3d2-d684-4c75-b02c-8b78f38da6c9@d39g2000yqa.googlegroups.com>

On May 12, 6:13?am, Kushal Kumaran 
wrote:
> On Tue, May 11, 2010 at 3:59 PM, kak... at gmail.com  wrote:
> > On May 11, 10:56?am, "kak... at gmail.com"  wrote:
> >> On May 11, 5:06?am, Kushal Kumaran 
> >> wrote:
>
> >> > On Mon, May 10, 2010 at 8:26 PM, kak... at gmail.com  wrote:
> >> > > On May 10, 10:22?am, Kushal Kumaran 
> >> > > wrote:
> >> > >> On Mon, May 10, 2010 at 7:30 PM, kak... at gmail.com  wrote:
> >> > >> > Hi to all, i want to ask you a question, concerning the best way to do
> >> > >> > the following as a POST request:
> >> > >> > There is server-servlet that accepts xml commands
> >> > >> > It had the following HTTP request headers:
>
> >> > >> > ? ? ? ? ? ?Host: somehost.com
> >> > >> > ? ? ? ? ? ?User-Agent: Jakarta Commons-HttpClient
> >> > >> > ? ? ? ? ? ?Content-Type: text/xml
> >> > >> > ? ? ? ? ? ?Content-Length: 415
>
> >> > >> > and the following request body (reformatted here for clarity):
>
> >> > >> > ? ? ? ? ? ?
> >> > >> > ? ? ? ? ? ?
> >> > >> > ? ? ? ? ? ? ?search
> >> > >> > ? ? ? ? ? ?
> >> > >> > How can i send the above to the Listener Servlet?
> >> > >> > Thanks in advance
>
> >> > >> Use the xmlrpclib module.
>
> >> > > OK, sending headers with xmlrpclib,
> >> > > but how do i send the XML message?
>
> >> > Your XML message is an XML RPC message. ?You will use xmlrpclib like this:
>
> >> > server_proxy = xmlrpclib.ServerProxy(('somehost.com', 80))
> >> > result = server_proxy.search()
>
> >> > The call to server_proxy.search will result in an actual XML RPC
> >> > message being sent.
>
> >> > Read up on the xmlrpclib documentation here:http://docs.python.org/library/xmlrpclib.html, and the XMLRPC spec
> >> > here:http://www.xmlrpc.com/spec
>
> >> Ok I got it!
> >> Thank you!!!
>
> >> A.K
>
> > Apparently the server i'm trying to connect accepts only POST
> > connections. So xmlrpclib is useless.
> > I think I need the httplib library module.
>
> > Any hints?
>
> I don't understand. ?xmlrpclib sends POST requests only. ?Are you
> getting an exception? ?If so, please post the entire stack trace.
>
> If you want to send the data "by hand", use the httplib module. ?you
> can pass your XML to the HTTPConnection.request method as the "body"
> argument.
>
> --
> regards,
> kushal

Ok i found it. I sent the xml by hand with httplib module.
i use the last example of http://docs.python.org/library/httplib.html
and it worked.
Thank you very much for your response.

A.K.


From alia_khouri at yahoo.com  Wed May 12 04:01:03 2010
From: alia_khouri at yahoo.com (Alia Khouri)
Date: Wed, 12 May 2010 01:01:03 -0700 (PDT)
Subject: Is Python a functional programming language?
References:  
	<06f5541f-ccbe-427a-83ad-176fcb947d29@e35g2000yqm.googlegroups.com> 
	<7xzl06ewl1.fsf@ruckus.brouhaha.com>
Message-ID: <5b00fbd7-24e0-4fbc-bdbf-4538b897680e@a34g2000yqn.googlegroups.com>

Paul Rubin:

> I like learnyouahaskell.com if you want to get some exposure to Haskell,
> probably the archetypal functional language these days. ?I've been
> fooling with it on and off for the past couple years. ?I'm still not
> convinced that it's that good a vehicle for practical general purpose
> software development, but there are some specific areas where it works
> out just beautifully. ?And in terms of the challenges it presents and
> the amount I've learned from it, it's one of the most interesting things
> I've done as a programmer in as long as I can remember. ?It really is
> mind altering.

Completely agree with you. Learnyouahaskell.com is as good as it gets
to learn haskell: haven't had so much fun learning a language since I
picked up python :-)

For similarly mind-altering pleasure, have a look at pure-lang [http://
code.google.com/p/pure-lang/] which describes itself as:

"Pure is a modern-style functional programming language based on term
rewriting. It offers equational definitions with pattern matching,
full symbolic rewriting capabilities, dynamic typing, eager and lazy
evaluation, lexical closures, built-in list and matrix support and an
easy-to-use C interface. The interpreter uses LLVM as a backend to JIT-
compile Pure programs to fast native code."

Enjoy!

AK


From johan at forberg.se  Wed May 12 04:05:33 2010
From: johan at forberg.se (Johan =?iso-8859-1?q?F=F6rberg?=)
Date: Wed, 12 May 2010 08:05:33 +0000 (UTC)
Subject: open(False) in python3
References: 
	
Message-ID: 

On Tue, 11 May 2010 19:27:37 -0300, Gabriel Genellina wrote:

> so open(False) is the same as open(0), and 0 is the file descriptor
> associated to standard input. The program isn't hung, it's just waiting
> for you to type some text

That's interesting. Are there any more numbered pseudofiles? I suppose 
its mainly an excellent way to confuse people when you open(0).read(), 
but it would be interesting to know.

Johan F?rberg


From DugmoreB at Nedbankcapital.co.za  Wed May 12 04:07:35 2010
From: DugmoreB at Nedbankcapital.co.za (Biyana, D. (Dugmore))
Date: Wed, 12 May 2010 10:07:35 +0200
Subject: python list digest
Message-ID: <7C6068ED9BBEAE4CAC7A3F4C9781AD7F043E7DC9@EXVS135RC101.africa.nedcor.net>

Hi All!

I have a huge file and I want to extract subtext starting with "{1:" and
ending with "-}" inclusive. This subtext recurs in many places in the
file and I want the resultant to be in some output file. Any suggestions
about the best way forward. 


********************
Nedbank Limited Reg No 1951/000009/06. The following link displays
the names of the Nedbank Board of Directors and Company Secretary.
[ http://www.nedbank.co.za/terms/DirectorsNedbank.htm ]
This email is confidential and is intended for the addressee only.
The following link will take you to Nedbank's legal notice.
[ http://www.nedbank.co.za/terms/EmailDisclaimer.htm ]
********************
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From guillermo.listas at googlemail.com  Wed May 12 04:15:06 2010
From: guillermo.listas at googlemail.com (Guillermo)
Date: Wed, 12 May 2010 01:15:06 -0700 (PDT)
Subject: virtualenvwrapper for Windows (Powershell)
References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com>
	
	<973ca0fa-4a2f-4e3b-91b9-e38917885c0f@d27g2000yqc.googlegroups.com>
	
Message-ID: 

On May 12, 4:31?am, Lawrence D'Oliveiro  wrote:
> In message
> <973ca0fa-4a2f-4e3b-91b9-e38917885... at d27g2000yqc.googlegroups.com>,
>
> Guillermo wrote:
> > On May 11, 7:43 am, Lawrence D'Oliveiro 
> > wrote:
>
> >> In message
> >> <22cf35af-44d1-43fe-8b90-07f2c6545... at i10g2000yqh.googlegroups.com>,
>
> >> Guillermo wrote:
>
> >>> If you've ever missed it on Windows and you can use Powershell ...
>
> >> I thought the whole point of Windows was to get away from this
> >> command-line stuff. Not such a good idea after all?
>
> > I suppose it depends.
>
> On the way it?s implemented? Microsoft seems to have botched that as well.

File a bug then. It works here. But I think you're getting a wee bit
off-topic.


From jeanmichel at sequans.com  Wed May 12 04:26:33 2010
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Wed, 12 May 2010 10:26:33 +0200
Subject: how to import a module for global use in a library package ?
In-Reply-To: 
References: <577270.86860.qm@web23105.mail.ird.yahoo.com>
	
Message-ID: <4BEA6639.1060704@sequans.com>

Terry Reedy wrote:
> On 5/11/2010 8:04 AM, Aur? Gourrier wrote:
> I might make one submodule for imports and then do 'from rootlib.util 
> import importmod as m' in the template. But I have no need now for such.
>
> Terry Jan Reedy
>
>
We did that, and we so regret it. After 5 years of intensive dev on that 
application (with more than 10 different guys committing in the repos) 
this module is now nothing but a real mess.
As soon as someone is writing twice the same import: "Oh I should put 
this module into the auto import, it will save 4 sec of my time".

This module is now an inconsistent bunch of imports and global 
assignements  :( .

JM



From stefan_ml at behnel.de  Wed May 12 04:29:23 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 12 May 2010 10:29:23 +0200
Subject: Extract all words that begin with x
In-Reply-To: <1295fd82-39ba-4edc-ad01-ee5f9fd8dc19@a39g2000prb.googlegroups.com>
References: 	
	
		
	<1b25230a-e584-4a89-b371-389d058aa586@g1g2000pro.googlegroups.com>
	
	<1295fd82-39ba-4edc-ad01-ee5f9fd8dc19@a39g2000prb.googlegroups.com>
Message-ID: 

Bryan, 12.05.2010 08:55:
> Now back to the arguably-interesting issue of speed in the particular
> problem here: 'Superpollo' had suggested another variant, which I
> appended to my timeit targets, resulting in:
>
> [s for s in strs if s.startswith('a')]  took:  5.68393977159
> [s for s in strs if s[:1] == 'a']  took:  3.31676491502
> [s for s in strs if s and s[0] == 'a']  took:  2.29392950076
>
> Superpollo's condition -- s and s[0] == 'a' -- is the fastest of the
> three.

Just out of curiosity, I ran the same code in the latest Cython pre-0.13 
and added some optimised Cython implementations. Here's the code:

def cython_way0(l):
     return [ s for s in l if s.startswith(u'a') ]

def cython_way1(list l):
     cdef unicode s
     return [ s for s in l if s.startswith(u'a') ]

def cython_way2(list l):
     cdef unicode s
     return [ s for s in l if s[:1] == u'a' ]

def cython_way3(list l):
     cdef unicode s
     return [ s for s in l if s[0] == u'a' ]

def cython_way4(list l):
     cdef unicode s
     return [ s for s in l if s and s[0] == u'a' ]

def cython_way5(list l):
     cdef unicode s
     return [ s for s in l if (s[0]) == u'a' ]

def cython_way6(list l):
     cdef unicode s
     return [ s for s in l if s and (s[0]) == u'a' ]


And here are the numbers (plain Python 2.6.5 first):

[s for s in strs if s.startswith(u'a')] took: 1.04618620872
[s for s in strs if s[:1] == u'a'] took: 0.518909931183
[s for s in strs if s and s[0] == u'a'] took: 0.617404937744

cython_way0(strs) took: 0.769457817078
cython_way1(strs) took: 0.0861849784851
cython_way2(strs) took: 0.208586931229
cython_way3(strs) took: 0.18615603447
cython_way4(strs) took: 0.190477132797
cython_way5(strs) took: 0.0366449356079
cython_way6(strs) took: 0.0368368625641

Personally, I think the cast to Py_UNICODE in the last two implementations 
shouldn't be required, that should happen automatically, so that way3/4 
runs equally fast as way5/6. I'll add that when I get to it.

Note that unicode.startswith() is optimised in Cython, so it's a pretty 
fast option, too. Also note that the best speed-up here is only a factor of 
14, so plain Python is quite competitive, unless the list is huge and this 
is really a bottleneck in an application.

Stefan



From ldo at geek-central.gen.new_zealand  Wed May 12 04:29:50 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Wed, 12 May 2010 20:29:50 +1200
Subject: virtualenvwrapper for Windows (Powershell)
References: <22cf35af-44d1-43fe-8b90-07f2c6545f63@i10g2000yqh.googlegroups.com>
	
	<973ca0fa-4a2f-4e3b-91b9-e38917885c0f@d27g2000yqc.googlegroups.com>
	
	
Message-ID: 

In message
, 
Guillermo wrote:

> On May 12, 4:31 am, Lawrence D'Oliveiro 
> wrote:
>
>> In message
>> <973ca0fa-4a2f-4e3b-91b9-e38917885... at d27g2000yqc.googlegroups.com>,
>>
>> Guillermo wrote:
>> > On May 11, 7:43 am, Lawrence D'Oliveiro
>> >  wrote:
>>
>> >> In message
>> >> <22cf35af-44d1-43fe-8b90-07f2c6545... at i10g2000yqh.googlegroups.com>,
>>
>> >> Guillermo wrote:
>>
>> >>> If you've ever missed it on Windows and you can use Powershell ...
>>
>> >> I thought the whole point of Windows was to get away from this
>> >> command-line stuff. Not such a good idea after all?
>>
>> > I suppose it depends.
>>
>> On the way it?s implemented? Microsoft seems to have botched that as
>> well.
> 
> But I think you're getting a wee bit off-topic.

Hey, you were the one who brought it up.


From stefan_ml at behnel.de  Wed May 12 04:36:27 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 12 May 2010 10:36:27 +0200
Subject: open(False) in python3
In-Reply-To: 
References: 	
	
Message-ID: 

Johan F?rberg, 12.05.2010 10:05:
> On Tue, 11 May 2010 19:27:37 -0300, Gabriel Genellina wrote:
>
>> so open(False) is the same as open(0), and 0 is the file descriptor
>> associated to standard input. The program isn't hung, it's just waiting
>> for you to type some text
>
> That's interesting. Are there any more numbered pseudofiles? I suppose
> its mainly an excellent way to confuse people when you open(0).read(),
> but it would be interesting to know.

Standard Unix behaviour dictates that 0 is stdin, 1 is stdout, and 2 is 
stderr. So you can only read() from 0.

Stefan



From lists at cheimes.de  Wed May 12 04:42:41 2010
From: lists at cheimes.de (Christian Heimes)
Date: Wed, 12 May 2010 10:42:41 +0200
Subject: open(False) in python3
In-Reply-To: 
References: 	
	
Message-ID: 

Johan F?rberg every:
> That's interesting. Are there any more numbered pseudofiles? I suppose
> its mainly an excellent way to confuse people when you open(0).read(),
> but it would be interesting to know.

All opened files (and on Unix even network sockets, epoll queues, 
inotify handlers etc) have a number. It's called a file descriptor. By 
default stdin, stdout and stderr have the file descriptors 0, 1 and 2. 
The concept of file descriptors is much older than Python and not Python 
specific. Even shells use the numbers, e.g. "cmd >logfile 2>&1" means 
"write stdout to logfile, redirect and combine stderr stream with stdout".



From mbnoimi at gmx.com  Wed May 12 04:43:27 2010
From: mbnoimi at gmx.com (M. Bashir Al-Noimi)
Date: Wed, 12 May 2010 10:43:27 +0200
Subject: encoding issue (cp720)
Message-ID: <4BEA6A2F.5020905@gmx.com>

Hi All,

I'm still a newbie in Python (I started learn it yesterday)  and I faced 
a huge problem cuz python always crashes because of encoding issue!

> Fatal Python error: Py_Initialize: can't initialize sys standard streams
> LookupError: unknown encoding: cp720
>    

so I filed a bug report 
 
about it but I couldn't find a solution for this problem so could you 
please help me to run python correctly?

*Note:*

    * I'm using: Windows XP SP3 32Bit, Python 3.1.2
    * I tried to copy cp720.py
      
      to Python31\Lib\encodings but it didn't fix the issue and gives me
      an error message (see attachment plz)

-- 
Best Regards
Muhammad Bashir Al-Noimi
My Blog: http://mbnoimi.net

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: error-message.txt
URL: 

From stefan_ml at behnel.de  Wed May 12 04:43:39 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 12 May 2010 10:43:39 +0200
Subject: Extract all words that begin with x
In-Reply-To: <4be971de$0$18659$4fafbaef@reader3.news.tin.it>
References: 				
	<4be971de$0$18659$4fafbaef@reader3.news.tin.it>
Message-ID: 

superpollo, 11.05.2010 17:03:
> Aahz ha scritto:
>> In article ,
>> Terry Reedy  wrote:
>>> On 5/10/2010 5:35 AM, James Mills wrote:
>>>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho wrote:
>>>>> Have I missed something, or wouldn't this work just as well:
>>>>>
>>>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>>> ['awes', 'asdgas']
>>>> I would do this for completeness (just in case):
>>>>
>>>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>>> Just guards against empty strings which may or may not be in the list.
>>> ... word[0:1] does the same thing. All Python programmers should
>>> learn to use slicing to extract a char from a string that might be
>>> empty.
>>> The method call of .startswith() will be slower, I am sure.
>>
>> And if it is slower, so what? Using startswith() makes for faster
>> reading of the code for me, and I'm sure I'm not the only one.
>
> also, what if the OP intended "words that begin with x" with x a string
> (as opposed to a single character) ?

     word[:len(x)] == x

will work in that case.

Stefan



From utente at esempio.net  Wed May 12 04:48:00 2010
From: utente at esempio.net (superpollo)
Date: Wed, 12 May 2010 10:48:00 +0200
Subject: Extract all words that begin with x
In-Reply-To: 
References: 					<4be971de$0$18659$4fafbaef@reader3.news.tin.it>
	
Message-ID: <4bea6b40$0$40293$4fafbaef@reader2.news.tin.it>

Stefan Behnel ha scritto:
> superpollo, 11.05.2010 17:03:
>> Aahz ha scritto:
>>> In article ,
>>> Terry Reedy  wrote:
>>>> On 5/10/2010 5:35 AM, James Mills wrote:
>>>>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho 
>>>>> wrote:
>>>>>> Have I missed something, or wouldn't this work just as well:
>>>>>>
>>>>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>>>> ['awes', 'asdgas']
>>>>> I would do this for completeness (just in case):
>>>>>
>>>>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>>>> Just guards against empty strings which may or may not be in the list.
>>>> ... word[0:1] does the same thing. All Python programmers should
>>>> learn to use slicing to extract a char from a string that might be
>>>> empty.
>>>> The method call of .startswith() will be slower, I am sure.
>>>
>>> And if it is slower, so what? Using startswith() makes for faster
>>> reading of the code for me, and I'm sure I'm not the only one.
>>
>> also, what if the OP intended "words that begin with x" with x a string
>> (as opposed to a single character) ?
> 
>     word[:len(x)] == x
> 
> will work in that case.

yes ... thanks.


From news1234 at free.fr  Wed May 12 04:48:16 2010
From: news1234 at free.fr (News123)
Date: Wed, 12 May 2010 10:48:16 +0200
Subject: client to upload big files via https and get progress info
Message-ID: <4bea6b50$0$8925$426a74cc@news.free.fr>

Hi,

I'd like to perform huge file uploads via https.
I'd like to make sure,
- that I can obtain upload progress info (sometimes the nw is very slow)
- that (if the file exceeds a certain size) I don't have to
  read the entire file into RAM.

I found Active states recipe 146306, which constructs the whole
multipart message first in RAM and sends it then in one chunk.


I found a server side solutions, that will write out the data file chunk
wise ( http://webpython.codepoint.net/mod_python_publisher_big_file_upload
)



If I just wanted to have progress info, then I could probably
just split line 16 of Active State's recipe ( h.send(body) )
into multiple send, right?

chunksize = 1024
for i in range(0,len(body),chunksize):
    h.send(body[i:i+chunksize])
    show_progressinfo()


But how could I create body step by step?
I wouldn't know the content-length up front?

thanks in advance



N







From maarten.sneep at knmi.nl  Wed May 12 05:20:11 2010
From: maarten.sneep at knmi.nl (Maarten)
Date: Wed, 12 May 2010 02:20:11 -0700 (PDT)
Subject: Why the inconsistent of those two base64 methods?
References: 
Message-ID: 

On May 12, 6:04 am, Leo Jay  wrote:
> I'd like to encode a string in base64, but I found a inconsistent of
> two methods:
>
> >>> 'aaa'.encode('base64')
> 'YWFh\n'
> >>> import base64
> >>> base64.b64encode('aaa')
> 'YWFh'
>
> as you can see, the result of
> 'aaa'.encode('base64')
> has a '\n' at the end, but the other method doesn't.
>
> Why the inconsistent?

Don't know. Does it matter?

>>> import base64
>>> base64.decodestring(base64.b64encode('aaa'))
'aaa'

>>> 'aaa'.encode('base64').decode('base64')
'aaa'

(so far so good, and as expected)

>>> base64.decodestring('aaa'.encode('base64'))
'aaa'

>>> base64.b64encode('aaa').decode('base64')
'aaa'

(As far as I can see, both methods are completely consistent)

Maarten


From lie.1296 at gmail.com  Wed May 12 06:14:53 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 12 May 2010 20:14:53 +1000
Subject: encoding issue (cp720)
In-Reply-To: 
References: 
Message-ID: <4bea7ffc$1@dnews.tpgi.com.au>

On 05/12/10 18:43, M. Bashir Al-Noimi wrote:
> Hi All,
> 
> I'm still a newbie in Python (I started learn it yesterday)  and I faced
> a huge problem cuz python always crashes because of encoding issue!
> 
>> Fatal Python error: Py_Initialize: can't initialize sys standard streams
>> LookupError: unknown encoding: cp720
> 
> so I filed a bug report
> 
> about it but I couldn't find a solution for this problem so could you
> please help me to run python correctly?

This is partly a locale issue; your terminal (command prompt) is using a
locale yet unsupported by python. You can use 'chcp' to switch to
different terminal code page (e.g. use chcp 1250). You won't be able to
'print' arabic characters, but at least python should run.

> *Note:*
> 
>    * I'm using: Windows XP SP3 32Bit, Python 3.1.2
>    * I tried to copy cp720.py
>      
>      to Python31\Lib\encodings but it didn't fix the issue and gives me
>      an error message (see attachment plz)

You're using Python 3.1, the cp720.py file you copied is for Python 2.7
(trunk); there are some backward incompatible between python 2 and
python 3 (specifically in your case, unicode string is now default in
python 3, so unicode literal is no longer supported). Try using the
cp720.py from py3k branch:
http://svn.python.org/view/python/branches/py3k/Lib/encodings/cp720.py?view=markup


From albert at spenarnc.xs4all.nl  Wed May 12 07:25:28 2010
From: albert at spenarnc.xs4all.nl (Albert van der Horst)
Date: 12 May 2010 11:25:28 GMT
Subject: strange interaction between open and cwd
References: <4BDEDC73.1020301@ftml.net>
	
	
Message-ID: 

In article ,
Grant Edwards   wrote:

>
>Still, at the time, it _seemed_ like a good way to share a directory
>of source code amongst multiple projects.  I don't remember why
>symlinks wouldn't accomplish the task -- something to do with RCS...

Must be deep. I use RCS in combination with symlinks all the time.
Like symlinks to a directory tree on a mounted volume, where
one is not supposed to check out.
Or symlinking  happyd.sco,v to HAPPYD.SCO,v effectively making
file names case-insensitive.

>
>--
>Grant
>

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst



From paul at boddie.org.uk  Wed May 12 08:10:27 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 05:10:27 -0700 (PDT)
Subject: Picking a license
References: 
	<4be5bdcb$0$27798$c3e8da3@news.astraweb.com> 
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com> 
	 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com>
Message-ID: 

On 11 Mai, 22:39, Patrick Maupin  wrote:
>
> OK. ?Now I'm REALLY confused. ?I said "Certainly RMS
> carefully lays out that the LGPL should be used sparingly in his "Why
> you shouldn't use the Lesser GPL for your next library" post. ?(Hint:
> he's not suggesting a permissive license instead.)"
>
> to which you replied:
>
> "Sure, but all he's asking you to do is to make the software available
> under a GPL-compatible licence."

Alright, then, all he's asking you to do is to make *your* software
available under a GPL-compatible licence. That's what I meant in the
context of the discussion. Usually, people complain about how the GPL
dictates a single licence, forbidding all others, that is then
inseparable from their work ("It's my work but they make me GPL it! I
can't even control my own work any more! The FSF owns it!" and such
nonsense), but I've already given examples of this not being the case
at all.

> and then I tried to politely show that you were wrong about RMS's
> intentions, but now, but you're saying "oh, of course, he'd say that
> -- he wrote the license" ?which is basically what I've been saying all
> along. ?But if you have read it like you say, then it appears you were
> being very disingenuous in your original reply!

What the licence asks you to do and what the author of the licence
wants you to do are two separate things.

[...]

> NO. ?If you are building an application, and distributing GPLed stuff
> as part of it, the FSF still maintains that the license is such that
> the entire application must be GPLed. ?You keep acting like this isn't
> true, but it absolutely is if you're distributing the entire
> application.

I wrote "the software" above when I meant "your software", but I have
not pretended that the whole system need not be available under the
GPL. Otherwise the following text would be logically inconsistent with
such claims:

[...]

> On May 11, 5:24 am, Paul Boddie  wrote:
> > Again, you have to consider the intent of the licensing: that some
> > software which links to readline results in a software system that
> > should offer the "four freedoms", because that's the price of linking
> > to readline whose licence has promised that any system which builds
> > upon it shall offer those privileges.
>
> But I did consider the intent, and as I have made clear, I think
> that's a bullying tactic that fragments the software world
> unnecessarily. ?Obviously YMMV.

More loaded terms to replace the last set, I see.

> > > > As for rst2pdf, what your modifications would mean is that the
> > > > software would need to be redistributed under a GPL-compatible
> > > > licence.
>
> NO. ?You're still not paying attention. ?The FSF's clear position is
> that if you actually *redistribute* software under the GPL as *part of
> a system* then the full package must be licensed *under the GPL*.

Again, what I meant was "your software", not the whole software
system. As I more or less state below...

> > Once again, I refer you to the intent of the licensing: if someone has
> > the software in front of them which uses svglib, then they need to
> > have the privileges granted to them by the GPL. Yes, if the software
> > also uses some component with a GPL-incompatible licence, then this
> > causes a problem.
>
> It appears that the FSF's position is the ability to link to svglib
> would require software to be licensed under the GPL.

It would require the resulting system to be licensed under the GPL. As
it stands by itself, rst2pdf would need to be licensed compatibly with
the GPL.

> I don't believe
> that, but I do believe that if rst2pdf distributed svglib (or even
> patches to svglib which were clearly derivative works) then yes,
> rst2pdf would have to be distributed under the GPL. ?This kind of
> bullshit is only acceptable to people who only think a single license
> is acceptable.

Take it or leave it, then.

[...]

> > Well, I have referred several times to WebKit without you taking the
> > hint,
>
> OK, I don't work with webkit. ?I knew you were hinting at something,
> but why the games, I don't know. ?I guess it's all about mystique and
> games.

You mentioned WebKit as a non-GPL-licensed project which attracted
contributions from hard-nosed business. WebKit started life as KHTML
and was (and still is) LGPL-licensed, but for all practical purposes,
KHTML was only ever experienced by KDE users whilst linked to the Qt
framework, then available under the GPL. Now, given that WebKit now
works with other GUI frameworks, yet is still LGPL-licensed (and this
has nothing to do with recent Qt licensing developments, since this
applies to the period before those changes), it is clear that any
assertion that WebKit "was made GPL-only", which is what a lot of
people claim, is incorrect.

> > but that provides a specific case of a project which is LGPL-
> > licensed despite being based on (in GPLv3 terminology) libraries which
> > were distributed under the GPL and combined with that software.
>
> What other libraries? ?I don't know it's history. ?I give you specific
> examples at problems; you hint around at things you claim are not
> problems and then still don't give specifics.

I've now given you the specifics.

> > Similarly, the effort to ensure that CPython's licence was GPL-
> > compatible had a lot to do with the right to redistribute with GPL-
> > licensed code (actually readline, if I remember correctly).
>
> Yes, but the Python project doesn't actually distribute readline, and
> (as I mentioned) people are more informed now, and it would be
> difficult for RMS to bully Python into relicensing.

All RMS and the FSF's lawyers wanted was that the CNRI licences be GPL-
compatible. There are actually various aspects of GPL-compatibility
that are beneficial, even if you don't like the copyleft-style
clauses, so I don't think it was to the detriment of the Python
project.

> But if the Python
> distribution *included* GNU Readline, then RMS would be on firmer
> ground, and the license would probably have to be changed. ?This is
> *exactly* the situation I was describing with svglib -- can you still
> not see that it is a problem to just toss unsupported free software
> out there with a GPL license? ?Unsupported Apache or MIT is fine --
> fix it or ignore. ?Unsupported GPL is an attractive nuisance.

Well, if you're planning to release code and just walk away from it,
then choosing a permissive licence might be acceptable, but not all
code "found" by people on the Internet is abandoned, even if it is
apparently mere fodder for their super-important project.

> > Is readline trivial? Was readline trivial in 1992?
>
> Again, you could have neural net prediction and other fancy
> technologies, but in general, yes, the concept is pretty trivial and
> there were many systems that already had such things back then.

Well, that may not be a judgement shared by the authors. There are
numerous tools and components which do dull jobs and whose maintenance
is tedious and generally unrewarding, but that doesn't mean that such
investment is worth nothing in the face of someone else's so-very-
topical high-profile project.

> > Does it even
> > matter, because the author is more or less saying that they don't want
> > their code incorporated in a proprietary system?
>
> Yes it matters because as others have pointed out, sometimes people
> use stuff which is purported to be "free" without a full understanding
> of all the implications. ?But this gets back to my general complaint
> about co-opting the word "free" which you don't think is a problem
> because you have chosen to use other words.

Well, if people are making use of "some good code found for free on
the Internet", particularly if they are corporations like Cisco, and
they choose not to understand things like copyright and licensing, or
they think "all rights reserved" is just a catchy slogan, then they
probably shouldn't be building larger works and redistributing them.
This may seem unfair to you, but there are plenty of other
organisations who are much less charitable about copyright
infringement than the FSF or the average Free Software developer.

But if you're more or less saying that the intentions of an author can
(or should) be disregarded if the desire to use that author's work is
great enough, well, that's certainly interesting to learn.

Paul


From adi at digitaltrowel.com  Wed May 12 08:13:05 2010
From: adi at digitaltrowel.com (Adi Eyal)
Date: Wed, 12 May 2010 14:13:05 +0200
Subject: Iterating over dict and removing some elements
Message-ID: 

> ---------- Forwarded message ----------
> From:?Bryan 
> To:?python-list at python.org
> Date:?Tue, 11 May 2010 23:59:29 -0700 (PDT)
> Subject:?Re: Iterating over dict and removing some elements
> Terry Reedy wrote:
> [...]
>> for k in [k for k in d if d[k] == 'two']:
>> ? ? ? ? ?d.pop(k)
>
> We have a winner.
>

also

foo = lambda k, d : d[k] == "two"
d = dict([(k, d[k]) for k in d.keys() if not foo(k, d)])

incidentally, this is marginally slower than pops and dels but has the
benefit of not modifying the original dict if that's what you need.

Adi


From paul at boddie.org.uk  Wed May 12 08:26:22 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 05:26:22 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<4be95545$1@dnews.tpgi.com.au>
	
	
Message-ID: <1d32b5bf-3445-454e-bbb5-172435741fa1@q30g2000yqd.googlegroups.com>

On 11 Mai, 23:02, Patrick Maupin  wrote:
>
> Huh? Permissive licenses offer much better certainty for someone
> attempting a creative mash-up. ?Different versions of the Apache
> license don't conflict with each other. ?If I use an MIT-licensed
> component, it doesn't attempt to make me offer my whole work under
> MIT.

What certainty does the MIT licence give contributors to a project
against patent infringement claims initiated by another contributor?

[...]

> Oh, I get it. ?You were discussing the certainty that an author can
> control what downstream users do with the software to some extent.
> Yes, I fully agree. ?The GPL is for angry idealists who have an easily
> outraged sense of justice, who don't have enough real problems to work
> on.

Again, the author does not exercise control when people must
voluntarily choose to use that author's work and thereby agree to
adhere to that author's set of terms.

Paul


From mbnoimi at gmx.com  Wed May 12 08:33:09 2010
From: mbnoimi at gmx.com (M. Bashir Al-Noimi)
Date: Wed, 12 May 2010 14:33:09 +0200
Subject: [SOLVED] encoding issue (cp720)
In-Reply-To: <4bea7ffc$1@dnews.tpgi.com.au>
References: 
	<4bea7ffc$1@dnews.tpgi.com.au>
Message-ID: <4BEAA005.8050601@gmx.com>

Hi Lie,

On 12/05/2010 12:14 ?, Lie Ryan wrote:
> On 05/12/10 18:43, M. Bashir Al-Noimi wrote:
>    
>> Hi All,
>>
>> I'm still a newbie in Python (I started learn it yesterday)  and I faced
>> a huge problem cuz python always crashes because of encoding issue!
>>
>>      
>>> Fatal Python error: Py_Initialize: can't initialize sys standard streams
>>> LookupError: unknown encoding: cp720
>>>        
>> so I filed a bug report
>> 
>> about it but I couldn't find a solution for this problem so could you
>> please help me to run python correctly?
>>      
> This is partly a locale issue; your terminal (command prompt) is using a
> locale yet unsupported by python. You can use 'chcp' to switch to
> different terminal code page (e.g. use chcp 1250). You won't be able to
> 'print' arabic characters, but at least python should run.
>    
Actually I tried to run chcp (some one mentioned it in bug report) but 
it didn't fix the issue.

>> *Note:*
>>
>>     * I'm using: Windows XP SP3 32Bit, Python 3.1.2
>>     * I tried to copy cp720.py
>>       
>>       to Python31\Lib\encodings but it didn't fix the issue and gives me
>>       an error message (see attachment plz)
>>      
> You're using Python 3.1, the cp720.py file you copied is for Python 2.7
> (trunk); there are some backward incompatible between python 2 and
> python 3 (specifically in your case, unicode string is now default in
> python 3, so unicode literal is no longer supported). Try using the
> cp720.py from py3k branch:
> http://svn.python.org/view/python/branches/py3k/Lib/encodings/cp720.py?view=markup
>    
Thanks a lot python currently works this is the right file.

-- 
Best Regards
Muhammad Bashir Al-Noimi
My Blog: http://mbnoimi.net



From paul at boddie.org.uk  Wed May 12 08:43:19 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 05:43:19 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	
Message-ID: <1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>

On 11 Mai, 22:50, Patrick Maupin  wrote:
> On May 11, 5:34?am, Paul Boddie  wrote:
>
> > Yes, *if* you took it. He isn't forcing you to take it, though, is he?
>
> No, ?but he said a lot of words that I didn't immediately understand
> about what it meant to be free and that it was free, and then after I
> bit into it he told me he owned my soul now.

Thus, "owned my soul" joins "holy war" and "Bin Laden" on the list.
That rhetorical toolbox is looking pretty empty at this point.

[...]

> > It is whining if someone says, "I really want that chocolate, but that
> > nasty man is going to make me pay for it!"
>
> But that's not what happened. ?I mean, he just told me that I might
> have to give some of it to others later. ?He didn't mention that if I
> spread peanut butter on mine before I ate it that I'd have to give
> people Reese's Peanut Butter cups.

He isn't, though. He's telling you that you can't force other people
to lick the chocolate off whatever "Reese's Peanut Butter cups" are,
rather than actually eating the combination of the two, when you offer
such a combination to someone else. Is the Creative Commons share-
alike clause just as objectionable to you, because it's that principle
we're talking about here?

[...]

> > If the man said, "please take the chocolate, but I want you to share
> > it with your friends", and you refused to do so because you couldn't
> > accept that condition, would it be right to say, "that man is forcing
> > me to share chocolate with my friends"?
>
> But the thing is, he's *not* making me share the chocolate with any of
> my friends. ?He's not even making me share my special peanut butter
> and chocolate. ?What he's making me do is, if I give my peanut butter
> and chocolate to one of my friends, he's making me make *that* friend
> promise to share. ?I try not to impose obligations like that on my
> friends, so obviously the "nice" man with the chocolate isn't my
> friend!

Yes, he's making everyone commit to sharing, and yes, it's like a
snowball effect once people agree to join in. But unless you hide that
commitment, no-one imposes anything on anyone. They can get their
chocolate elsewhere. They join in; they are not conscripted.

[...]

> I explained this very carefully before multiple times. ?Let me give
> concrete examples -- (1) I have told my children before "if we take
> that candy, then they will make us pay for it" and (2) if we included
> (GPLed software) in this (MIT-licensed software) then we will have to
> change the license. ?In both these cases, once the decision has been
> made, then yes, force enters into it. ?And no, I don't think the
> average shop keeper is nearly as evil as Darth, or even RMS.

Entering an agreement voluntarily does not mean that you are forced to
enter that agreement, even if the agreement then involves obligations
(as agreements inevitably do).

Paul


From czg0002 at gmail.com  Wed May 12 09:40:34 2010
From: czg0002 at gmail.com (chen zeguang)
Date: Wed, 12 May 2010 21:40:34 +0800
Subject: How to add callbacks that is the same function with different 
	argument in Tkinter python26?
Message-ID: 

code is in the end.
I want to print different number when pressing different button.
Yet the program outputs 8 no matter which button is pressed.
I guess it's because the callback function is not established untill the
button is pressed, and i has already reached to 8.

then How to add callbacks that is the same function with different argument?

CODE:
from Tkinter import *
root = Tk()
def func(x):
    print x
    return

func_en=[]
for i in range(9):
    func_en.append(lambda:func(i))
for i in range(9):
    func_en[i]()
for i in range(9):
    Button(root, text='%d'%i, command=func_en[i]).pack()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From jeanmichel at sequans.com  Wed May 12 10:09:05 2010
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Wed, 12 May 2010 16:09:05 +0200
Subject: How to add callbacks that is the same function with different
	argument in Tkinter python26?
In-Reply-To: 
References: 
Message-ID: <4BEAB681.9060108@sequans.com>

chen zeguang wrote:
> code is in the end.
> I want to print different number when pressing different button.
> Yet the program outputs 8 no matter which button is pressed.
> I guess it's because the callback function is not established untill 
> the button is pressed, and i has already reached to 8.
>
> then How to add callbacks that is the same function with different 
> argument?
>
> CODE:
> from Tkinter import *
> root = Tk()
> def func(x):
>     print x
>     return
>
> func_en=[]
> for i in range(9):
>     func_en.append(lambda:func(i))
> for i in range(9):
>     func_en[i]()
> for i in range(9):
>     Button(root, text='%d'%i, command=func_en[i]).pack()
from Tkinter import *
root = Tk()

def func(x):
    def _printme():
        print x
    return _printme

for i in range(9):
    Button(root, text='%d'%i, command=func(i)).pack()

Surely someone will explain why your code was not working, I can't 
'cause I don't use lambda, it brings more problems than it solves (maybe 
I'm not talented enough).
Above is how I would have written the code, I tested it, looks like it's 
working.

JM


From pmaupin at gmail.com  Wed May 12 10:10:52 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 07:10:52 -0700 (PDT)
Subject: Picking a license
References: 
	<888943a3-e4c0-4fba-9ee8-7e0a452c68a2@e35g2000yqm.googlegroups.com>
	 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	
Message-ID: <3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com>

On May 12, 7:10?am, Paul Boddie  wrote:
> On 11 Mai, 22:39, Patrick Maupin  wrote:
>
>
>
> > OK. ?Now I'm REALLY confused. ?I said "Certainly RMS
> > carefully lays out that the LGPL should be used sparingly in his "Why
> > you shouldn't use the Lesser GPL for your next library" post. ?(Hint:
> > he's not suggesting a permissive license instead.)"
>
> > to which you replied:
>
> > "Sure, but all he's asking you to do is to make the software available
> > under a GPL-compatible licence."
>
> Alright, then, all he's asking you to do is to make *your* software
> available under a GPL-compatible licence. That's what I meant in the
> context of the discussion. Usually, people complain about how the GPL
> dictates a single licence, forbidding all others, that is then
> inseparable from their work ("It's my work but they make me GPL it! I
> can't even control my own work any more! The FSF owns it!" and such
> nonsense), but I've already given examples of this not being the case
> at all.

In that post, specifically, RMS says to use the GPL in some cases,
rather than the LGPL, for libraries.  Any other interpretation of
*that post* is disingenuous.

> > and then I tried to politely show that you were wrong about RMS's
> > intentions, but now, but you're saying "oh, of course, he'd say that
> > -- he wrote the license" ?which is basically what I've been saying all
> > along. ?But if you have read it like you say, then it appears you were
> > being very disingenuous in your original reply!
>
> What the licence asks you to do and what the author of the licence
> wants you to do are two separate things.

But the whole context was about what RMS wanted me to do and you
disagreed!

>
> > NO. ?If you are building an application, and distributing GPLed stuff
> > as part of it, the FSF still maintains that the license is such that
> > the entire application must be GPLed. ?You keep acting like this isn't
> > true, but it absolutely is if you're distributing the entire
> > application.
>
> I wrote "the software" above when I meant "your software", but I have
> not pretended that the whole system need not be available under the
> GPL.

You say you "have not pretended" but you've never mentioned that it
would or even acknowledged the correctness of my assertions about this
until now, just claiming that what I said was false.

> > On May 11, 5:24 am, Paul Boddie  wrote:
> > > Again, you have to consider the intent of the licensing: that some
> > > software which links to readline results in a software system that
> > > should offer the "four freedoms", because that's the price of linking
> > > to readline whose licence has promised that any system which builds
> > > upon it shall offer those privileges.
>
> > But I did consider the intent, and as I have made clear, I think
> > that's a bullying tactic that fragments the software world
> > unnecessarily. ?Obviously YMMV.
>
> More loaded terms to replace the last set, I see.

IMO "Bullying" is the correct term for some of Stallman's actions,
including in the clisp debacle.  I knew you wouldn't agree -- that's
why YMMV.  And I'm not "replacing" any set of terms -- part of the
"bullying" is the "forcing."

> > > > > As for rst2pdf, what your modifications would mean is that the
> > > > > software would need to be redistributed under a GPL-compatible
> > > > > licence.
>
> > NO. ?You're still not paying attention. ?The FSF's clear position is
> > that if you actually *redistribute* software under the GPL as *part of
> > a system* then the full package must be licensed *under the GPL*.
>
> Again, what I meant was "your software", not the whole software
> system. As I more or less state below...

BUT THAT DOESN'T MATTER.  Once the whole package is licensed under the
GPL, for someone downstream to try to scrape the GPL off and get to
just the underlying non-GPL parts is harder than scraping bubblegum
off your shoe on a hot Texas day.

> > > Once again, I refer you to the intent of the licensing: if someone has
> > > the software in front of them which uses svglib, then they need to
> > > have the privileges granted to them by the GPL. Yes, if the software
> > > also uses some component with a GPL-incompatible licence, then this
> > > causes a problem.
>
> > It appears that the FSF's position is the ability to link to svglib
> > would require software to be licensed under the GPL.
>
> It would require the resulting system to be licensed under the GPL. As
> it stands by itself, rst2pdf would need to be licensed compatibly with
> the GPL.

They've softened their stance considerably over the last few years,
and don't overreach nearly as much as they used to, I agree.

[...]

> You mentioned WebKit as a non-GPL-licensed project which attracted
> contributions from hard-nosed business. WebKit started life as KHTML
> and was (and still is) LGPL-licensed, but for all practical purposes,
> KHTML was only ever experienced by KDE users whilst linked to the Qt
> framework, then available under the GPL. Now, given that WebKit now
> works with other GUI frameworks, yet is still LGPL-licensed (and this
> has nothing to do with recent Qt licensing developments, since this
> applies to the period before those changes), it is clear that any
> assertion that WebKit "was made GPL-only", which is what a lot of
> people claim, is incorrect.

I didn't make that claim and have never heard of that claim, and I'm
not at all sure of the relevance of whatever you're trying to explain
to the licensing of an overall program, rather than a library.

> > > but that provides a specific case of a project which is LGPL-
> > > licensed despite being based on (in GPLv3 terminology) libraries which
> > > were distributed under the GPL and combined with that software.
>
> > What other libraries? ?I don't know it's history. ?I give you specific
> > examples at problems; you hint around at things you claim are not
> > problems and then still don't give specifics.
>
> I've now given you the specifics.

And now that I know the specifics, I think they are completely
irrelevant to any points I was trying to make in this discussion.

> > > Similarly, the effort to ensure that CPython's licence was GPL-
> > > compatible had a lot to do with the right to redistribute with GPL-
> > > licensed code (actually readline, if I remember correctly).
>
> > Yes, but the Python project doesn't actually distribute readline, and
> > (as I mentioned) people are more informed now, and it would be
> > difficult for RMS to bully Python into relicensing.
>
> All RMS and the FSF's lawyers wanted was that the CNRI licences be GPL-
> compatible. There are actually various aspects of GPL-compatibility
> that are beneficial, even if you don't like the copyleft-style
> clauses, so I don't think it was to the detriment of the Python
> project.

And I don't have a problem with that.  Honestly I don't.  But as far
as I'm concerned, although you finally admitted it, a lot of the
dancing around appeared to be an attempt to disprove my valid
assertion that a combined work would have to be distributed under the
GPL, and that no other free software license claims sovereignty over
the entire work.

> > But if the Python
> > distribution *included* GNU Readline, then RMS would be on firmer
> > ground, and the license would probably have to be changed. ?This is
> > *exactly* the situation I was describing with svglib -- can you still
> > not see that it is a problem to just toss unsupported free software
> > out there with a GPL license? ?Unsupported Apache or MIT is fine --
> > fix it or ignore. ?Unsupported GPL is an attractive nuisance.
>
> Well, if you're planning to release code and just walk away from it,
> then choosing a permissive licence might be acceptable, but not all
> code "found" by people on the Internet is abandoned, even if it is
> apparently mere fodder for their super-important project.

Code doesn't have to be abandoned to be an attractive nuisance.

> > > Is readline trivial? Was readline trivial in 1992?
>
> > Again, you could have neural net prediction and other fancy
> > technologies, but in general, yes, the concept is pretty trivial and
> > there were many systems that already had such things back then.
>
> Well, that may not be a judgement shared by the authors. There are
> numerous tools and components which do dull jobs and whose maintenance
> is tedious and generally unrewarding, but that doesn't mean that such
> investment is worth nothing in the face of someone else's so-very-
> topical high-profile project.

OK, so what you're saying is that readline is so dull and unrewarding
that the only reason to bother writing it is to reel people in to the
GPL?

> > > Does it even
> > > matter, because the author is more or less saying that they don't want
> > > their code incorporated in a proprietary system?
>
> > Yes it matters because as others have pointed out, sometimes people
> > use stuff which is purported to be "free" without a full understanding
> > of all the implications. ?But this gets back to my general complaint
> > about co-opting the word "free" which you don't think is a problem
> > because you have chosen to use other words.
>
> Well, if people are making use of "some good code found for free on
> the Internet", particularly if they are corporations like Cisco, and

I'm not talking about Cisco.  I'm talking about people like the author
of clisp, and you well know it.

> they choose not to understand things like copyright and licensing, or
> they think "all rights reserved" is just a catchy slogan, then they
> probably shouldn't be building larger works and redistributing them.

Well, the FSF seems to have softened its stance, but at the time,
clisp wasn't even distributing readline.  That's why I use terms like
"bullying".  The bully now knows it's harder to get away with that
particular lie, but he's still scheming about how to reel more people
in.

> This may seem unfair to you, but there are plenty of other
> organisations who are much less charitable about copyright
> infringement than the FSF or the average Free Software developer.

None of those claim that their software is "Free Software" (all
caps).  You apparently think it's fine that that's just a catchy
slogan.

> But if you're more or less saying that the intentions of an author can
> (or should) be disregarded if the desire to use that author's work is
> great enough, well, that's certainly interesting to learn.

I never said that and you know it.  I have explicitly gone out of my
way to indicate that I won't use GPLed software in cases where my
doing so might violate the author's wishes, even if it would be legal
to do so, and I have always said people should be able to use whatever
license they want.  But the intentions of an author, as viewed
through, e.g., the MIT license, are much easier to discern and much
more liberal for downstream users than the GPL, which is exceedingly
long and requires a huge FAQ to even begin to fathom.

Regards,
Pat


From pmaupin at gmail.com  Wed May 12 10:12:36 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 07:12:36 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<4be95545$1@dnews.tpgi.com.au>
	
	 
	<4bea1bac$1@dnews.tpgi.com.au>
Message-ID: <2f547c51-3779-4141-9f6a-d3ca938d7fbb@a21g2000yqn.googlegroups.com>

On May 11, 10:06?pm, Lie Ryan  wrote:

> The point is, GPL (and OWL) is for programmers who just don't care about
> the legal stuffs and would want to spend more time writing code than
> writing license.

Absolutely.  When I wrote "permissive license" I was not trying to
imply that everybody should roll their own.

Regards,
Pat


From pmaupin at gmail.com  Wed May 12 10:20:25 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 07:20:25 -0700 (PDT)
Subject: Picking a license
References: 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com>
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<4be95545$1@dnews.tpgi.com.au>
	
	 
	<1d32b5bf-3445-454e-bbb5-172435741fa1@q30g2000yqd.googlegroups.com>
Message-ID: <6c5ed669-96bb-4e4c-a203-03c478165dbe@24g2000yqy.googlegroups.com>

On May 12, 7:26?am, Paul Boddie  wrote:
> On 11 Mai, 23:02, Patrick Maupin  wrote:
> > Huh? Permissive licenses offer much better certainty for someone
> > attempting a creative mash-up. ?Different versions of the Apache
> > license don't conflict with each other. ?If I use an MIT-licensed
> > component, it doesn't attempt to make me offer my whole work under
> > MIT.
>
> What certainty does the MIT licence give contributors to a project
> against patent infringement claims initiated by another contributor?

None.  If I was worried about that, I'd probably use the Apache
license instead.

> > Oh, I get it. ?You were discussing the certainty that an author can
> > control what downstream users do with the software to some extent.
> > Yes, I fully agree. ?The GPL is for angry idealists who have an easily
> > outraged sense of justice, who don't have enough real problems to work
> > on.
>
> Again, the author does not exercise control when people must
> voluntarily choose to use that author's work and thereby agree to
> adhere to that author's set of terms.

So you're saying that Microsoft doesn't exercise control about keeping
me from using a copy of Windows on more than one machine -- it's not
"control" because I agreed to it up front.   Sorry, my mileage
varies.  In fact, I would (and do) say that Microsoft forces me to buy
one copy of Windows for every machine I want to run it on.

Regards,
Pat


From matt at tplus1.com  Wed May 12 10:23:29 2010
From: matt at tplus1.com (Matthew Wilson)
Date: Wed, 12 May 2010 14:23:29 +0000 (UTC)
Subject: Need help using callables and setup in timeit.Timer
Message-ID: 

I want to time some code that depends on some setup.  The setup code
looks a little like this:

    >>> b = range(1, 1001)

And the code I want to time looks vaguely like this:

    >>> sorted(b)

Except my code uses a different function than sorted.  But that ain't
important right now.

Anyhow, I know how to time this code as long as I pass in strings to timeit:

    >>> import timeit
    >>> t = timeit.Timer("sorted(b)", "b = range(1, 1001)")
    >>> min(t.repeat(3, 100))

How do I use a setup callable and have it put stuff into the namespace
that the stmt callable can access?

In other words, I want to do the same thing as above, but using
callables as the parameters to timeit.Timer, not strings of python code.

Here's my long-run goal.  I want to reuse code from my unit tests to
test performance:

    import unittest
    class TestSorting(unittest.TestCase):

        def setUp(self):
            self.b = range(1, 1001)

        def test_sorted(self):
            sorted(self.b)

I expect to have to do a little work.  The timeit setup will need to
make an instance of TestSorting and somehow the stmt code will have to
use that particular instance.

Once I understand how to have the timeit setup put stuff into the same
namespace as the timeit stmt, I'll attack how to translate
unittest.TestCase instances into something that can feed right into
timeit.Timer.

Matt





From pmaupin at gmail.com  Wed May 12 10:45:04 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 07:45:04 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
Message-ID: <5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>

On May 12, 7:43?am, Paul Boddie  wrote:
> On 11 Mai, 22:50, Patrick Maupin  wrote:
>
> > On May 11, 5:34?am, Paul Boddie  wrote:
>
> > > Yes, *if* you took it. He isn't forcing you to take it, though, is he?
>
> > No, ?but he said a lot of words that I didn't immediately understand
> > about what it meant to be free and that it was free, and then after I
> > bit into it he told me he owned my soul now.
>
> Thus, "owned my soul" joins "holy war" and "Bin Laden" on the list.
> That rhetorical toolbox is looking pretty empty at this point.

Not emptier than you analogy toolbox.  This is really a pretty stupid
analogy, but I guess my lame attempts at showing that are wasted.

> > > It is whining if someone says, "I really want that chocolate, but that
> > > nasty man is going to make me pay for it!"
>
> > But that's not what happened. ?I mean, he just told me that I might
> > have to give some of it to others later. ?He didn't mention that if I
> > spread peanut butter on mine before I ate it that I'd have to give
> > people Reese's Peanut Butter cups.
>
> He isn't, though. He's telling you that you can't force other people
> to lick the chocolate off whatever "Reese's Peanut Butter cups" are,
> rather than actually eating the combination of the two, when you offer
> such a combination to someone else.

No.  That's not what is happening, and you've now officially stretched
the analogy way past the breaking point.  In any case, he's telling me
I have to give the recipe for my homemade peanut butter.

> Is the Creative Commons share-
> alike clause just as objectionable to you, because it's that principle
> we're talking about here?

I have explained that, in some cases, I will use GPL software, and in
other cases I won't, and tried to explain why and what the difference
is.  Anybody can re-read my posts and figure out that the same might
apply to the various Creative Commons licenses.

> > > If the man said, "please take the chocolate, but I want you to share
> > > it with your friends", and you refused to do so because you couldn't
> > > accept that condition, would it be right to say, "that man is forcing
> > > me to share chocolate with my friends"?
>
> > But the thing is, he's *not* making me share the chocolate with any of
> > my friends. ?He's not even making me share my special peanut butter
> > and chocolate. ?What he's making me do is, if I give my peanut butter
> > and chocolate to one of my friends, he's making me make *that* friend
> > promise to share. ?I try not to impose obligations like that on my
> > friends, so obviously the "nice" man with the chocolate isn't my
> > friend!
>
> Yes, he's making everyone commit to sharing, and yes, it's like a
> snowball effect once people agree to join in.

Sorry, I sometimes have a hard time distinguishing the semantic
difference between "make" and "force".  Could you elucidate?

> But unless you hide that
> commitment, no-one imposes anything on anyone. They can get their
> chocolate elsewhere. They join in; they are not conscripted.

And I've already explained why, in some cases, someone might refuse
the tastiest chocolate in the world to not join in.

> > I explained this very carefully before multiple times. ?Let me give
> > concrete examples -- (1) I have told my children before "if we take
> > that candy, then they will make us pay for it" and (2) if we included
> > (GPLed software) in this (MIT-licensed software) then we will have to
> > change the license. ?In both these cases, once the decision has been
> > made, then yes, force enters into it. ?And no, I don't think the
> > average shop keeper is nearly as evil as Darth, or even RMS.
>
> Entering an agreement voluntarily does not mean that you are forced to
> enter that agreement, even if the agreement then involves obligations
> (as agreements inevitably do).

No, but copyright licenses are funny things, not like contracts where
there is a meeting of the minds up front.  For example, while the
Ciscos of the world have no excuse, I bet a lot of people who download
Ubuntu and make copies for their friends are unaware of this section
of the GPL FAQ:

"I downloaded just the binary from the net. If I distribute copies, do
I have to get the source and distribute that too?   Yes. The general
rule is, if you distribute binaries, you must distribute the complete
corresponding source code too. The exception for the case where you
received a written offer for source code is quite limited."

Regards,
Pat


From enleverLesX_XXmcX at XmclavXeauX.com.invalid  Wed May 12 10:51:27 2010
From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP)
Date: Wed, 12 May 2010 16:51:27 +0200
Subject: Upgrade Python 2.6.4 to 2.6.5
References: 
Message-ID: <4beac072$0$27583$ba4acef3@reader.news.orange.fr>

Hi! 

If you are under Vista, or Windows 7, have you unactivate UAC, before
the update?

@+

MCI


From pmaupin at gmail.com  Wed May 12 10:53:40 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 07:53:40 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<4bea56dd$1@dnews.tpgi.com.au>
Message-ID: <56c7788a-898f-4993-9b6f-e8d6723b573d@e2g2000yqn.googlegroups.com>

On May 12, 2:19?am, Lie Ryan  wrote:
> On 05/12/10 06:50, Patrick Maupin wrote:
>
>
>
> > On May 11, 5:34 am, Paul Boddie  wrote:
> >> On 10 Mai, 20:36, Patrick Maupin  wrote:
> >>> ?The fact is, I know the man would force me to pay for the chocolate, so in
> >>> some cases that enters into the equation and keeps me from wanting the
> >>> chocolate.
>
> >> If the man said, "please take the chocolate, but I want you to share
> >> it with your friends", and you refused to do so because you couldn't
> >> accept that condition, would it be right to say, "that man is forcing
> >> me to share chocolate with my friends"?
>
> > But the thing is, he's *not* making me share the chocolate with any of
> > my friends. ?He's not even making me share my special peanut butter
> > and chocolate. ?What he's making me do is, if I give my peanut butter
> > and chocolate to one of my friends, he's making me make *that* friend
> > promise to share. ?I try not to impose obligations like that on my
> > friends, so obviously the "nice" man with the chocolate isn't my
> > friend!
>
> The analogy breaks here; unlike chocolate, the value of software/source
> code, if shared, doesn't decrease (in fact, many software increases its
> value when shared liberally, e.g. p2p apps).

Absolutely true. Actually, the analogy was really pretty broken to
start with.  It wasn't my analogy -- I was just trying to play
along :-)

> There might be certain cases where the software contains some trade
> secret whose value decreases the more people knows about it; but sharing
> does not decrease the value of the software, at least not directly, it
> is the value of the secret that decreases because of the sharing.

Sure.  But in general, people will share, often even when doing so is
legally questionable.  Just look at the RIAA's woes if you don't
believe me.  The only real question here is whether the marginal value
achieved by adding constraints to force people to share (which most
would have done anyway) outweighs the costs to people who, for
whatever reason (perhaps a trade secret obligation) *can't* share.

The answer to that question may well vary depending on several
factors.  The fact that GPL and Apache and MIT and BSD are available
is a good thing -- whichever license an author feels best fits his
project is definitely the one he should use.

Regards,
Pat


From davea at ieee.org  Wed May 12 11:09:45 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 May 2010 11:09:45 -0400
Subject: How to add callbacks that is the same function with different
	argument in Tkinter python26?
In-Reply-To: <4BEAB681.9060108@sequans.com>
References: 
	<4BEAB681.9060108@sequans.com>
Message-ID: <4BEAC4B9.2070103@ieee.org>

Jean-Michel Pichavant wrote:
> chen zeguang wrote:
>> code is in the end.
>> I want to print different number when pressing different button.
>> Yet the program outputs 8 no matter which button is pressed.
>> I guess it's because the callback function is not established untill 
>> the button is pressed, and i has already reached to 8.
>>
>> then How to add callbacks that is the same function with different 
>> argument?
>>
>> CODE:
>> from Tkinter import *
>> root = Tk()
>> def func(x):
>>     print x
>>     return
>>
>> func_en=[]
>> for i in range(9):
>>     func_en.append(lambda:func(i))
>> for i in range(9):
>>     func_en[i]()
>> for i in range(9):
>>     Button(root, text='%d'%i, command=func_en[i]).pack()
> from Tkinter import *
> root = Tk()
>
> def func(x):
>    def _printme():
>        print x
>    return _printme
>
> for i in range(9):
>    Button(root, text='%d'%i, command=func(i)).pack()
>
> Surely someone will explain why your code was not working, I can't 
> 'cause I don't use lambda, it brings more problems than it solves 
> (maybe I'm not talented enough).
> Above is how I would have written the code, I tested it, looks like 
> it's working.
>
> JM
This solution works because of the nested function.  Chen could do the 
same with nested lambdas, or by using default arguments in the lambda.

The trick is just that you need separate instances of x for each 
callback, so they don't all get incremented in the loop.

DaveA


From aahz at pythoncraft.com  Wed May 12 11:33:49 2010
From: aahz at pythoncraft.com (Aahz)
Date: 12 May 2010 08:33:49 -0700
Subject: Extract all words that begin with x
References: 
	
	<4be971de$0$18659$4fafbaef@reader3.news.tin.it>
	
Message-ID: 

In article ,
Stefan Behnel   wrote:
>superpollo, 11.05.2010 17:03:
>> Aahz ha scritto:
>>> In article ,
>>> Terry Reedy  wrote:
>>>> On 5/10/2010 5:35 AM, James Mills wrote:
>>>>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho wrote:
>>>>>> Have I missed something, or wouldn't this work just as well:
>>>>>>
>>>>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>>>> ['awes', 'asdgas']
>>>>> I would do this for completeness (just in case):
>>>>>
>>>>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>>>> Just guards against empty strings which may or may not be in the list.
>>>> ... word[0:1] does the same thing. All Python programmers should
>>>> learn to use slicing to extract a char from a string that might be
>>>> empty.
>>>> The method call of .startswith() will be slower, I am sure.
>>>
>>> And if it is slower, so what? Using startswith() makes for faster
>>> reading of the code for me, and I'm sure I'm not the only one.
>>
>> also, what if the OP intended "words that begin with x" with x a string
>> (as opposed to a single character) ?
>
>     word[:len(x)] == x
>
>will work in that case.

But that's now going to be slower.  ;-)  (Unless one makes the obvious
optimization to hoist len(x) out of the loop.)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From stefan_ml at behnel.de  Wed May 12 12:15:48 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 12 May 2010 18:15:48 +0200
Subject: Extract all words that begin with x
In-Reply-To: 
References: 		<4be971de$0$18659$4fafbaef@reader3.news.tin.it>	
	
Message-ID: 

Aahz, 12.05.2010 17:33:
> Stefan Behnel  wrote:
>> superpollo, 11.05.2010 17:03:
>>> Aahz ha scritto:
>>>> In article,
>>>> Terry Reedy  wrote:
>>>>> On 5/10/2010 5:35 AM, James Mills wrote:
>>>>>> On Mon, May 10, 2010 at 6:50 PM, Xavier Ho  wrote:
>>>>>>> Have I missed something, or wouldn't this work just as well:
>>>>>>>
>>>>>>>>>> list_of_strings = ['2', 'awes', '3465sdg', 'dbsdf', 'asdgas']
>>>>>>>>>> [word for word in list_of_strings if word[0] == 'a']
>>>>>>> ['awes', 'asdgas']
>>>>>> I would do this for completeness (just in case):
>>>>>>
>>>>>>>>>> [word for word in list_of_strings if word and word[0] == 'a']
>>>>>> Just guards against empty strings which may or may not be in the list.
>>>>> ... word[0:1] does the same thing. All Python programmers should
>>>>> learn to use slicing to extract a char from a string that might be
>>>>> empty.
>>>>> The method call of .startswith() will be slower, I am sure.
>>>>
>>>> And if it is slower, so what? Using startswith() makes for faster
>>>> reading of the code for me, and I'm sure I'm not the only one.
>>>
>>> also, what if the OP intended "words that begin with x" with x a string
>>> (as opposed to a single character) ?
>>
>>      word[:len(x)] == x
>>
>> will work in that case.
>
> But that's now going to be slower.  ;-)  (Unless one makes the obvious
> optimization to hoist len(x) out of the loop.)

Right, I forgot to mention that I left that as an exercise to the reader.

Stefan



From tjreedy at udel.edu  Wed May 12 12:32:38 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Wed, 12 May 2010 12:32:38 -0400
Subject: Extract all words that begin with x
In-Reply-To: 
References: 		<4be971de$0$18659$4fafbaef@reader3.news.tin.it>	
	
Message-ID: 

On 5/12/2010 11:33 AM, Aahz wrote:

>>> also, what if the OP intended "words that begin with x" with x a string
>>> (as opposed to a single character) ?
>>
>>      word[:len(x)] == x
>>
>> will work in that case.
>
> But that's now going to be slower.  ;-)  (Unless one makes the obvious
> optimization to hoist len(x) out of the loop.)

If x were a known literal, then len(x) could be replaced by the actual 
size. But I admit that that is a nuisance and point of failure. I think 
comparing start/end strings of variable length or length greater than 
one is the real justification for the new methods, not the OP's trivial 
single-char case.

Terry Jan Reedy





From debatem1 at gmail.com  Wed May 12 12:53:18 2010
From: debatem1 at gmail.com (geremy condra)
Date: Wed, 12 May 2010 09:53:18 -0700
Subject: open(False) in python3
In-Reply-To: 
References: 
	
	
	
Message-ID: 

On Wed, May 12, 2010 at 1:36 AM, Stefan Behnel  wrote:
> Johan F?rberg, 12.05.2010 10:05:
>>
>> On Tue, 11 May 2010 19:27:37 -0300, Gabriel Genellina wrote:
>>
>>> so open(False) is the same as open(0), and 0 is the file descriptor
>>> associated to standard input. The program isn't hung, it's just waiting
>>> for you to type some text
>>
>> That's interesting. Are there any more numbered pseudofiles? I suppose
>> its mainly an excellent way to confuse people when you open(0).read(),
>> but it would be interesting to know.
>
> Standard Unix behaviour dictates that 0 is stdin, 1 is stdout, and 2 is
> stderr. So you can only read() from 0.
>
> Stefan

Nitpicking, but open(1).read() and open(2).read() both succeed
(for small values of success) the same way that open(0).read()
does.

Thanks for the advice, everybody.

Geremy Condra


From mensanator at aol.com  Wed May 12 13:12:06 2010
From: mensanator at aol.com (Mensanator)
Date: Wed, 12 May 2010 10:12:06 -0700 (PDT)
Subject: Why the inconsistent of those two base64 methods?
References:  
	
Message-ID: 

On May 12, 4:20?am, Maarten  wrote:
> On May 12, 6:04 am, Leo Jay  wrote:
>
> > I'd like to encode a string in base64, but I found a inconsistent of
> > two methods:
>
> > >>> 'aaa'.encode('base64')
> > 'YWFh\n'
> > >>> import base64
> > >>> base64.b64encode('aaa')
> > 'YWFh'
>
> > as you can see, the result of
> > 'aaa'.encode('base64')
> > has a '\n' at the end, but the other method doesn't.
>
> > Why the inconsistent?
>
> Don't know. Does it matter?

Yeah...

>>> import base64
>>> a = 'aaa'.encode('base64')
>>> aa = base64.b64encode('aaa')
>>> a == aa
False


>
> >>> import base64
> >>> base64.decodestring(base64.b64encode('aaa'))
>
> 'aaa'
>
> >>> 'aaa'.encode('base64').decode('base64')
>
> 'aaa'
>
> (so far so good, and as expected)
>
> >>> base64.decodestring('aaa'.encode('base64'))
>
> 'aaa'
>
> >>> base64.b64encode('aaa').decode('base64')
>
> 'aaa'
>
> (As far as I can see, both methods are completely consistent)

Your notion of 'consistency' is wanting.

>
> Maarten



From paul at boddie.org.uk  Wed May 12 13:17:18 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 10:17:18 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
Message-ID: <75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>

On 12 Mai, 16:45, Patrick Maupin  wrote:
> On May 12, 7:43?am, Paul Boddie  wrote:
> > Thus, "owned my soul" joins "holy war" and "Bin Laden" on the list.
> > That rhetorical toolbox is looking pretty empty at this point.
>
> Not emptier than you analogy toolbox. ?This is really a pretty stupid
> analogy, but I guess my lame attempts at showing that are wasted.

Yes they are. The analogy was to point out that someone can really
want something, but if they are not prepared to accept the "price" of
acquiring it, then there is no point in them whining about someone
withholding that thing from them, or whining about someone "forcing"
them to do stuff, especially when there is clearly no "force" involved
at all.

[...]

> > He isn't, though. He's telling you that you can't force other people
> > to lick the chocolate off whatever "Reese's Peanut Butter cups" are,
> > rather than actually eating the combination of the two, when you offer
> > such a combination to someone else.
>
> No. ?That's not what is happening, and you've now officially stretched
> the analogy way past the breaking point. ?In any case, he's telling me
> I have to give the recipe for my homemade peanut butter.

If you want to redefine the basis of the analogy, then you can talk
about the recipe all you like, yes. Otherwise, no: the analogy was
only about people whining about not being able to get stuff with no
strings attached. I could swap that analogy with one that has someone
really wanting a ride on a bus, or wanting to go to the moon, where
they don't like it when someone tells them that they can't get do that
stuff without agreeing to something or other first. Feel free to start
discussing the shape of the bus ticket or who pays for spacesuits if
you want, but to say, "I really want to use that thing, but that nasty
man has licensed it under the GPL" is whining in precisely the same
way as featured in the analogy.

> > Is the Creative Commons share-
> > alike clause just as objectionable to you, because it's that principle
> > we're talking about here?
>
> I have explained that, in some cases, I will use GPL software, and in
> other cases I won't, and tried to explain why and what the difference
> is. ?Anybody can re-read my posts and figure out that the same might
> apply to the various Creative Commons licenses.

So it is objectionable to you as well, then.

[...]

> > Yes, he's making everyone commit to sharing, and yes, it's like a
> > snowball effect once people agree to join in.
>
> Sorry, I sometimes have a hard time distinguishing the semantic
> difference between "make" and "force". ?Could you elucidate?

Yes: once they've agreed to join in, they "have to" go along with the
whole scheme.

> > But unless you hide that
> > commitment, no-one imposes anything on anyone. They can get their
> > chocolate elsewhere. They join in; they are not conscripted.
>
> And I've already explained why, in some cases, someone might refuse
> the tastiest chocolate in the world to not join in.

Well, great for them. I thought they were "forced" to join in. I guess
not.

[...]

> No, but copyright licenses are funny things, not like contracts where
> there is a meeting of the minds up front. ?For example, while the
> Ciscos of the world have no excuse, I bet a lot of people who download
> Ubuntu and make copies for their friends are unaware of this section
> of the GPL FAQ:
>
> "I downloaded just the binary from the net. If I distribute copies, do
> I have to get the source and distribute that too? ? Yes. The general
> rule is, if you distribute binaries, you must distribute the complete
> corresponding source code too. The exception for the case where you
> received a written offer for source code is quite limited."

Yes, and that's why, when Mepis Linux were found not to be
distributing the sources, they had to go along with the above section.
And that's also why version 3 of the GPL has a clause about nominating
a party that will honour the obligation to provide source. But what's
your problem exactly? The GPL applies to redistribution, and the
default state of a copyrighted work is that you don't have permission
to redistribute it, so before someone shares something they have to
know whether they are able to do so or not.

The various clauses are all there for their own reasons. If you don't
like them, don't use GPL-licensed software.

Paul


From g.rodola at gmail.com  Wed May 12 13:26:58 2010
From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=)
Date: Wed, 12 May 2010 19:26:58 +0200
Subject: open(False) in python3
In-Reply-To: 
References: 
	
Message-ID: 

2010/5/12 Gabriel Genellina :
> open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
> builtin open() + os.fdopen() from 2.x all merged together. It does different
> things depending on the type and quantity of its arguments, and even returns
> objects of different types.
>
> In particular, open(some_integer) assumes some_integer is a file descriptor
> and return some variant of file object using the given file descriptor.

Interesting. I wasn't aware of this.
Is it documented somewhere?


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil


From zapwireDASHgroups at yahoo.com  Wed May 12 13:42:31 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 10:42:31 -0700
Subject: Do any debuggers support "edit and continue?"
Message-ID: 

Just curious... in Microsoft's Visual Studio (and I would presume some other 
tools), for many languages (both interpreted and compiled!) there's an "edit 
and conitnue" option that, when you hit a breakpoint, allows you to modify a 
line of code before it's actually executed.

Does any Python debugger support this feature?  Being an interpreted language 
it doesn't seem like it would necessarily be too onerous to support?  It'd be 
quite handy in that, especially if you hit a breakpoint due to the interpreter 
throwing an error, you could fix just the line in question and keep going, 
rather than having to stop the entire program, fix the line, and then run 
again and potentially kill a bunch of time getting the program back into the 
same "state."

Thanks,
---Joel Koltner



From cde3 at live.com  Wed May 12 13:56:38 2010
From: cde3 at live.com (Sandy Sandy)
Date: Wed, 12 May 2010 22:56:38 +0500
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: 


good question
I also looking for debugging tools like Matlab in Python

do you know how to stop in breakpoint investigate the variables by using graphics in  figures and continue
the
mutter is:

during debugging the  debug processes stacks when fig is created

for example, in code

import random

import matplotlib.pyplot as plt

from pylab import *

x= 23;

y = 111111;

print(23456)

plt.plot(range(10))

plot([1,2,3])

show()

print(11111111)

a=888



it is impossible after show() to continue debug

as stated in

Beginning Python Visualization - Crafting Visual Transformation Scripts (2009)

page  187



Note If you?re not using matplotlib interactively in Python, be sure

to call the function show() after all

graphs have been generated, as it enters a user interface main loop

that will stop execution of the rest of

your code. The reason behind this behavior is that matplotlib is

designed to be embedded in a GUI as well.

In Windows, if you?re working from interactive Python, you need only

issue show() once; close the figures

(or figures) to return to the shell. Subsequent plots will be drawn

automatically without issuing show(), and

you?ll be able to plot graphs interactively.




the problem is that after show() the debugger stacks

the decision can be to use threads like this 

from pylab import plot,show,ion
ion()
x = range(10)
plot(x)
from threading import Timer
t = Timer(0, show)
t.start()

a = 1222233
y = [2, 8, 3, 9, 4]
plot(y)

zz= 12346
print(44444)




but it is not working, bug??

Sandy
  

> From: zapwireDASHgroups at yahoo.com
> Subject: Do any debuggers support "edit and continue?"
> Date: Wed, 12 May 2010 10:42:31 -0700
> To: python-list at python.org
> 
> Just curious... in Microsoft's Visual Studio (and I would presume some other 
> tools), for many languages (both interpreted and compiled!) there's an "edit 
> and conitnue" option that, when you hit a breakpoint, allows you to modify a 
> line of code before it's actually executed.
> 
> Does any Python debugger support this feature?  Being an interpreted language 
> it doesn't seem like it would necessarily be too onerous to support?  It'd be 
> quite handy in that, especially if you hit a breakpoint due to the interpreter 
> throwing an error, you could fix just the line in question and keep going, 
> rather than having to stop the entire program, fix the line, and then run 
> again and potentially kill a bunch of time getting the program back into the 
> same "state."
> 
> Thanks,
> ---Joel Koltner
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
 		 	   		  
_________________________________________________________________
Hotmail: Trusted email with Microsoft?s powerful SPAM protection.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From paul at boddie.org.uk  Wed May 12 14:00:09 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 11:00:09 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com> 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com>
Message-ID: <0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com>

On 12 Mai, 16:10, Patrick Maupin  wrote:
> On May 12, 7:10?am, Paul Boddie  wrote:
> > What the licence asks you to do and what the author of the licence
> > wants you to do are two separate things.
>
> But the whole context was about what RMS wanted me to do and you
> disagreed!

What RMS as an activist wants is that everyone releases GPL-licensed
code, except where permissively licensed code might encourage open
standards proliferation. What RMS the licence author requests is that
your work is licensed in a way which is compatible with the GPL.

[...]

> > I wrote "the software" above when I meant "your software", but I have
> > not pretended that the whole system need not be available under the
> > GPL.
>
> You say you "have not pretended" but you've never mentioned that it
> would or even acknowledged the correctness of my assertions about this
> until now, just claiming that what I said was false.

Well, excuse me! I think we both know that combining something with a
GPL-licensed work and redistributing it means that the "four freedoms"
must apply, and that recipients get the work under the GPL. You can
insist that I said something else, but I spell it out in this post:

http://groups.google.com/group/comp.lang.python/msg/034fbc8289a4d555

Specifically the part...

"Not least because people are only obliged to make their work
available under a GPL-compatible licence so that people who are using
the combined work may redistribute it under
the GPL."

In case you don't find this satisfactory, "their work" means "their
own work".

[...]

> > More loaded terms to replace the last set, I see.
>
> IMO "Bullying" is the correct term for some of Stallman's actions,
> including in the clisp debacle. ?I knew you wouldn't agree -- that's
> why YMMV. ?And I'm not "replacing" any set of terms -- part of the
> "bullying" is the "forcing."

Stallman gave Haible the choice to not use readline. Maybe that wasn't
very nice, and maybe Haible didn't believe that using readline would
incur any consequences, but that's what you get when you use a
copyrighted work. Your language is all about portraying the FSF as
operating in some kind of illegal or unethical way. I guess you
believe that if you throw enough mud, some of it will stick.

> > Again, what I meant was "your software", not the whole software
> > system. As I more or less state below...
>
> BUT THAT DOESN'T MATTER. ?Once the whole package is licensed under the
> GPL, for someone downstream to try to scrape the GPL off and get to
> just the underlying non-GPL parts is harder than scraping bubblegum
> off your shoe on a hot Texas day.

Big deal. If a project wants to avoid even looking at GPL-licensed
code for the reason that someone might end up getting the code under
the GPL, and that they're so bothered that the opportunity to not
grant such recipients the privileges of modification and
redistribution disappears because of the GPL, then that's their
problem.

[WebKit is LGPL-licensed but KHTML linked to GPL-licensed code,
shouldn't WebKit be GPL-licensed?]

> I didn't make that claim and have never heard of that claim, and I'm
> not at all sure of the relevance of whatever you're trying to explain
> to the licensing of an overall program, rather than a library.

The point is precisely the one you concede about a project needing to
be licensed compatibly with the GPL, even though to use the combined
work, the result will be GPL-licensed.

[...]

> > All RMS and the FSF's lawyers wanted was that the CNRI licences be GPL-
> > compatible. There are actually various aspects of GPL-compatibility
> > that are beneficial, even if you don't like the copyleft-style
> > clauses, so I don't think it was to the detriment of the Python
> > project.
>
> And I don't have a problem with that. ?Honestly I don't. ?But as far
> as I'm concerned, although you finally admitted it, a lot of the
> dancing around appeared to be an attempt to disprove my valid
> assertion that a combined work would have to be distributed under the
> GPL, and that no other free software license claims sovereignty over
> the entire work.

I never denied that the GPL would apply to the combined work! Read the
stuff I quote above. Your *own* stuff (for example, the WebKit stuff)
can be licensed compatibly with the GPL (for example, the LGPL), but
the *whole* thing as it lands in the user's lap will be GPL-licensed.

[...]

> > Well, that may not be a judgement shared by the authors. There are
> > numerous tools and components which do dull jobs and whose maintenance
> > is tedious and generally unrewarding, but that doesn't mean that such
> > investment is worth nothing in the face of someone else's so-very-
> > topical high-profile project.
>
> OK, so what you're saying is that readline is so dull and unrewarding
> that the only reason to bother writing it is to reel people in to the
> GPL?

No, what I am saying is that a fair amount of work might have gone
into making readline, even though it may not be shiny enough by some
people's standards, but that doesn't mean you can disregard the
authors' wishes by insisting that is it "trivial" or unimportant,
whereas your own software somehow is important. As soon as you go down
that road, everyone can start belittling the works of others purely so
that they can start disregarding the terms which regulate those works,
and then it's a free-for-all.

[...]

> > Well, if people are making use of "some good code found for free on
> > the Internet", particularly if they are corporations like Cisco, and
>
> I'm not talking about Cisco. ?I'm talking about people like the author
> of clisp, and you well know it.

Well, Cisco seemed to have a bit of a problem. Maybe they thought that
this "free stuff" was just a commodity, too.

> > they choose not to understand things like copyright and licensing, or
> > they think "all rights reserved" is just a catchy slogan, then they
> > probably shouldn't be building larger works and redistributing them.
>
> Well, the FSF seems to have softened its stance, but at the time,
> clisp wasn't even distributing readline. ?That's why I use terms like
> "bullying". ?The bully now knows it's harder to get away with that
> particular lie, but he's still scheming about how to reel more people
> in.

What the FSF did was regrettable if the author didn't feel he had a
choice. I have no idea what went on beyond what the public mailing
list record can reveal.

Paul


From kushal.kumaran+python at gmail.com  Wed May 12 14:05:37 2010
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Wed, 12 May 2010 23:35:37 +0530
Subject: open(False) in python3
In-Reply-To: 
References:  
	
	
Message-ID: 

On Wed, May 12, 2010 at 10:56 PM, Giampaolo Rodol?  wrote:
> 2010/5/12 Gabriel Genellina :
>> open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
>> builtin open() + os.fdopen() from 2.x all merged together. It does different
>> things depending on the type and quantity of its arguments, and even returns
>> objects of different types.
>>
>> In particular, open(some_integer) assumes some_integer is a file descriptor
>> and return some variant of file object using the given file descriptor.
>
> Interesting. I wasn't aware of this.
> Is it documented somewhere?
>

http://docs.python.org/py3k/library/functions.html#open

-- 
regards,
kushal


From rbrt.somerville at gmail.com  Wed May 12 14:10:20 2010
From: rbrt.somerville at gmail.com (robert somerville)
Date: Wed, 12 May 2010 11:10:20 -0700
Subject: How to test whether bit is set within a flag with Python ?
Message-ID: 

I am trying to determine how to test whether variors bits are set within a
byte (or larger flag) , the python 'and' and 'or' do not seem to be doing
what i want .. does anybody have some sample code showing how to do it ??

e.g. (in "C")

unsigned char a = 6;

is 3rd bit set ??

a & 4 =,  true in this case ....

thanks
Robert Somerville
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From phlip2005 at gmail.com  Wed May 12 14:23:42 2010
From: phlip2005 at gmail.com (Phlip)
Date: Wed, 12 May 2010 11:23:42 -0700 (PDT)
Subject: How to? epydoc --top=README
References: <1e380352-d6b0-416a-8110-80b32afd83b5@6g2000prg.googlegroups.com>
Message-ID: 

On May 10, 1:29?pm, Phlip  wrote:
> Pythonistas:
>
> I have a question to epydoc-devel, but it might be languishing:
>
> http://sourceforge.net/mailarchive/forum.php?thread_name=l2n860c114f1...
>
> How do you populate the index.html output with your (insanely clever)
> contents of your README file?
>
> When I try the obvious notations, such as --top=README or --
> top=README.html, I get:
>
> Warning: Identifier 'README' looks suspicious; using it anyway.
> Warning: Could not find top page 'README'; using module-tree.html
> instead
>
> And, yes, the README is included in the input list, and yes I get a
> script-README-module.html
>
> ----8<------------------------------------------
>
> The question for the rest of Python-Land: Should I be using a better
> documentation extractor? (pydoc is too mundane so far.) Or should I be
> using a better forum for epydoc users questions?

Regardless of the advocacy, does anyone have an actual answer for
this?

>
> --
> ? yes-I-know-topicality-ly-yrs
> ? Phlip
> ?http://c2.com/cgi/wiki?ZeekLand



From tjreedy at udel.edu  Wed May 12 14:26:54 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Wed, 12 May 2010 14:26:54 -0400
Subject: open(False) in python3
In-Reply-To: 
References: 	
	
Message-ID: 

On 5/12/2010 1:26 PM, Giampaolo Rodol? wrote:
> 2010/5/12 Gabriel Genellina:
>> open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
>> builtin open() + os.fdopen() from 2.x all merged together. It does different
>> things depending on the type and quantity of its arguments, and even returns
>> objects of different types.

The change actually happened, according to 'What's new', in 2.6 when 
'open' was made a synonym for the new io.open.

>> In particular, open(some_integer) assumes some_integer is a file descriptor
>> and return some variant of file object using the given file descriptor.
>
> Interesting. I wasn't aware of this.
> Is it documented somewhere?

Right where it should be, in the entry for 'open' under 'built-in 
functions': "file is either ... or an integer file descriptor of the 
file to be wrapped"




From pmaupin at gmail.com  Wed May 12 14:29:38 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 11:29:38 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
Message-ID: <039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>

On May 12, 12:17?pm, Paul Boddie  wrote:
> On 12 Mai, 16:45, Patrick Maupin  wrote:
>
> > On May 12, 7:43?am, Paul Boddie  wrote:
> > > Thus, "owned my soul" joins "holy war" and "Bin Laden" on the list.
> > > That rhetorical toolbox is looking pretty empty at this point.
>
> > Not emptier than you analogy toolbox. ?This is really a pretty stupid
> > analogy, but I guess my lame attempts at showing that are wasted.
>
> Yes they are. The analogy was to point out that someone can really
> want something, but if they are not prepared to accept the "price" of
> acquiring it, then there is no point in them whining about someone
> withholding that thing from them, or whining about someone "forcing"
> them to do stuff, especially when there is clearly no "force" involved
> at all.

But nobody's whining about the strings attached to the software.  Just
pointing out why they sometimes won't use a particular piece of
software, and pointing out that some other people (e.g. random Ubuntu
users) might not understand the full cost of the software, and that
that is because the cost of the software has been deliberately
obscured by using unqualified terms like all-caps "Free Software."

> > > He isn't, though. He's telling you that you can't force other people
> > > to lick the chocolate off whatever "Reese's Peanut Butter cups" are,
> > > rather than actually eating the combination of the two, when you offer
> > > such a combination to someone else.
>
> > No. ?That's not what is happening, and you've now officially stretched
> > the analogy way past the breaking point. ?In any case, he's telling me
> > I have to give the recipe for my homemade peanut butter.
>
> If you want to redefine the basis of the analogy, then you can talk
> about the recipe all you like, yes. Otherwise, no: the analogy was
> only about people whining about not being able to get stuff with no
> strings attached. I could swap that analogy with one that has someone
> really wanting a ride on a bus, or wanting to go to the moon, where
> they don't like it when someone tells them that they can't get do that
> stuff without agreeing to something or other first. Feel free to start
> discussing the shape of the bus ticket or who pays for spacesuits if
> you want, but to say, "I really want to use that thing, but that nasty
> man has licensed it under the GPL" is whining in precisely the same
> way as featured in the analogy.

Oh, no wonder I didn't understand what you were getting at with the
analogy.  I'm not whining about people licensing stuff under the GPL,
just about its apologists pretending there are never any negative
consequences from it.

> > > Is the Creative Commons share-
> > > alike clause just as objectionable to you, because it's that principle
> > > we're talking about here?
>
> > I have explained that, in some cases, I will use GPL software, and in
> > other cases I won't, and tried to explain why and what the difference
> > is. ?Anybody can re-read my posts and figure out that the same might
> > apply to the various Creative Commons licenses.
>
> So it is objectionable to you as well, then.

I somehow knew that is how you would read my posts, but no.  It's
people like you putting words in my month that is objectionable.

> [...]
>
> > > Yes, he's making everyone commit to sharing, and yes, it's like a
> > > snowball effect once people agree to join in.
>
> > Sorry, I sometimes have a hard time distinguishing the semantic
> > difference between "make" and "force". ?Could you elucidate?
>
> Yes: once they've agreed to join in, they "have to" go along with the
> whole scheme.

Sorry, that is absolutely no different than what I originally said
when I was first defending Aahz's use of the word "force" to Ben
Finney back on the 7th:

"Perhaps you feel "forces" is too loaded of a word.  There is no
question, however, that a copyright license can require that if you do
"X" with some code, you must also do "Y".  There is also no question
that the GPL uses this capability in copyright law to require anybody
who distributes a derivative work to provide the source.  Thus,
"forced to contribute back any changes" is definitely what happens
once the decision is made to distribute said changes in object form."

Both your "make" and my "force" mean "to compel."  We've come full
circle.  The English language makes no real distinction between
"making everyone commit" and "forcing everyone [to] commit".


> > > But unless you hide that
> > > commitment, no-one imposes anything on anyone. They can get their
> > > chocolate elsewhere. They join in; they are not conscripted.
>
> > And I've already explained why, in some cases, someone might refuse
> > the tastiest chocolate in the world to not join in.
>
> Well, great for them. I thought they were "forced" to join in. I guess
> not.

That's because you use selective quoting of "forced" and deliberately
ignore the context it was used in.

> > No, but copyright licenses are funny things, not like contracts where
> > there is a meeting of the minds up front. ?For example, while the
> > Ciscos of the world have no excuse, I bet a lot of people who download
> > Ubuntu and make copies for their friends are unaware of this section
> > of the GPL FAQ:
>
> > "I downloaded just the binary from the net. If I distribute copies, do
> > I have to get the source and distribute that too? ? Yes. The general
> > rule is, if you distribute binaries, you must distribute the complete
> > corresponding source code too. The exception for the case where you
> > received a written offer for source code is quite limited."
>
> Yes, and that's why, when Mepis Linux were found not to be
> distributing the sources, they had to go along with the above section.
> And that's also why version 3 of the GPL has a clause about nominating
> a party that will honour the obligation to provide source. But what's
> your problem exactly?

My problem, exactly, is that bothering Mepis, yet not bothering Joe
Blow when he gives a copy to his friend, is exactly the kind of
selective enforcement of copyright rights that Microsoft is accused of
when they turn a blind eye to piracy in third-world countries.

>The GPL applies to redistribution, and the
> default state of a copyrighted work is that you don't have permission
> to redistribute it, so before someone shares something they have to
> know whether they are able to do so or not.

And Joe Blow assumes that something that says "Free Software" means
it.  Sure he *should* read the copyright license, but you've already
admitted he probably won't bother, and might not understand it if he
does.

> The various clauses are all there for their own reasons. If you don't
> like them, don't use GPL-licensed software.

I've already explained very carefully multiple times:

1) I often use GPL software, and don't have any problem with the
license at all *as a user*.
2) I very seldom create stuff under the GPL because I don't like
imposing those sorts of restrictions on software I am giving away; and
3) For stuff  I create which is not under the GPL, to make sure that I
can give it away without restrictions, I need to make sure that I am
not incorporating any GPL software.

Despite your opinion, there is nothing legally or morally wrong with
me using GPL software (and not redistributing it) just because I
happen to feel that (a) for my purposes, for most stuff I write, it
happens to be the wrong license, (b) (especially historically) some of
the practices used to insure proliferation of the GPL are ethically
questionable, and (c) whenever these ethically questionable practices
are discussed, quasi-religious apologists will take these questionable
practices to the next level, by selective quoting and bad analogies
and hinting at things without actually coming out and saying them, and
all sorts of other debate tactics designed to confuse rather than
enlighten.

Regards,
Pat


From davea at ieee.org  Wed May 12 14:36:28 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 May 2010 14:36:28 -0400
Subject: open(False) in python3
In-Reply-To: 
References: 	
	
Message-ID: <4BEAF52C.70504@ieee.org>



Giampaolo Rodol? wrote:
> 2010/5/12 Gabriel Genellina :
>   
>> open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
>> builtin open() + os.fdopen() from 2.x all merged together. It does different
>> things depending on the type and quantity of its arguments, and even returns
>> objects of different types.
>>
>> In particular, open(some_integer) assumes some_integer is a file descriptor
>> and return some variant of file object using the given file descriptor.
>>     
>
> Interesting. I wasn't aware of this.
> Is it documented somewhere?
>
>
>   
http://docs.python.org/py3k/library/functions.html#open

   .... or an integer file descriptor of the file to be wrapped.....




From python at mrabarnett.plus.com  Wed May 12 14:40:59 2010
From: python at mrabarnett.plus.com (MRAB)
Date: Wed, 12 May 2010 19:40:59 +0100
Subject: How to test whether bit is set within a flag with Python ?
In-Reply-To: 
References: 
Message-ID: <4BEAF63B.3020409@mrabarnett.plus.com>

robert somerville wrote:
> I am trying to determine how to test whether variors bits are set within 
> a byte (or larger flag) , the python 'and' and 'or' do not seem to be 
> doing what i want .. does anybody have some sample code showing how to 
> do it ??
> 
> e.g. (in "C")
> 
> unsigned char a = 6;
> 
> is 3rd bit set ??
> 
> a & 4 =,  true in this case ....
> 
'and', 'or' and 'not' are Boolean.

Python borrows its bitwise operators from C:

     &     bitwise and
     |     bitwise or
     ^     bitwise xor
     ~     bitwise not (ones' complement)
     <<    shift left
     >>    shift right

You also need to remember that Python's integers are of (virtually)
unlimited length.


From stef.mientki at gmail.com  Wed May 12 14:43:50 2010
From: stef.mientki at gmail.com (Stef Mientki)
Date: Wed, 12 May 2010 20:43:50 +0200
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: <4BEAF6E6.6020303@gmail.com>

On 12-05-2010 19:42, Joel Koltner wrote:
> Just curious... in Microsoft's Visual Studio (and I would presume some
> other tools), for many languages (both interpreted and compiled!)
> there's an "edit and conitnue" option that, when you hit a breakpoint,
> allows you to modify a line of code before it's actually executed.
>
> Does any Python debugger support this feature?  Being an interpreted
> language it doesn't seem like it would necessarily be too onerous to
> support?  It'd be quite handy in that, especially if you hit a
> breakpoint due to the interpreter throwing an error, you could fix
> just the line in question and keep going, rather than having to stop
> the entire program, fix the line, and then run again and potentially
> kill a bunch of time getting the program back into the same "state."
>
> Thanks,
> ---Joel Koltner
>
winpdb perhaps ?

Stef
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From tjreedy at udel.edu  Wed May 12 14:46:53 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Wed, 12 May 2010 14:46:53 -0400
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: 

On 5/12/2010 1:42 PM, Joel Koltner wrote:
> Just curious... in Microsoft's Visual Studio (and I would presume some
> other tools), for many languages (both interpreted and compiled!)
> there's an "edit and conitnue" option that, when you hit a breakpoint,
> allows you to modify a line of code before it's actually executed.
>
> Does any Python debugger support this feature? Being an interpreted
> language it doesn't seem like it would necessarily be too onerous to
> support? It'd be quite handy in that, especially if you hit a breakpoint
> due to the interpreter throwing an error, you could fix just the line in

CPython compiles Python code (a sequence of statements) to its private 
bytecode (a sequence of codes and operands) and then interprets the 
bytecode. So 'edit and continue' would have to recompile the statement 
and patch the result into the bytecode. Since function compilation 
depends on global analysis of the function, functions would have to be 
recompiled as a whole.

Another problem is recovery of state. If an exception is raised in the 
middle of a statememt, there would need to be a means to roll back the 
state of objects and namespaces to what they were before execution of 
the statement started. So the interpreter would need to act like a 
transactional database, which is not trivial. This would also slow 
normal execution, so it would have to be optional.

> question and keep going, rather than having to stop the entire program,
> fix the line, and then run again and potentially kill a bunch of time
> getting the program back into the same "state."

If would definitely be nice. Perhaps $500,000 in funding would do the trick.

Terry Jan Reedy



From lie.1296 at gmail.com  Wed May 12 14:49:24 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Thu, 13 May 2010 04:49:24 +1000
Subject: Picking a license
In-Reply-To: <56c7788a-898f-4993-9b6f-e8d6723b573d@e2g2000yqn.googlegroups.com>
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
	<4bea56dd$1@dnews.tpgi.com.au>
	<56c7788a-898f-4993-9b6f-e8d6723b573d@e2g2000yqn.googlegroups.com>
Message-ID: <4beaf893$1@dnews.tpgi.com.au>

On 05/13/10 00:53, Patrick Maupin wrote:
> On May 12, 2:19 am, Lie Ryan  wrote:
>> On 05/12/10 06:50, Patrick Maupin wrote:
>>
>>
>>
>>> On May 11, 5:34 am, Paul Boddie  wrote:
>>>> On 10 Mai, 20:36, Patrick Maupin  wrote:
>>>>>  The fact is, I know the man would force me to pay for the chocolate, so in
>>>>> some cases that enters into the equation and keeps me from wanting the
>>>>> chocolate.
>>
>>>> If the man said, "please take the chocolate, but I want you to share
>>>> it with your friends", and you refused to do so because you couldn't
>>>> accept that condition, would it be right to say, "that man is forcing
>>>> me to share chocolate with my friends"?
>>
>>> But the thing is, he's *not* making me share the chocolate with any of
>>> my friends.  He's not even making me share my special peanut butter
>>> and chocolate.  What he's making me do is, if I give my peanut butter
>>> and chocolate to one of my friends, he's making me make *that* friend
>>> promise to share.  I try not to impose obligations like that on my
>>> friends, so obviously the "nice" man with the chocolate isn't my
>>> friend!
>>
>> The analogy breaks here; unlike chocolate, the value of software/source
>> code, if shared, doesn't decrease (in fact, many software increases its
>> value when shared liberally, e.g. p2p apps).
> 
> Absolutely true. Actually, the analogy was really pretty broken to
> start with.  It wasn't my analogy -- I was just trying to play
> along :-)

All analogy is broken, except if the analogy is the exact situation; but
then again, if the analogy is the exact situation, then it's not an
analogy :-)


From no.email at please.post  Wed May 12 14:52:41 2010
From: no.email at please.post (kj)
Date: Wed, 12 May 2010 18:52:41 +0000 (UTC)
Subject: Limitation of os.walk
References:  
	
Message-ID: 

In  Tim Chase writes:
>  05/11/2010 09:07 PM, Terry Reedy wrote:
>> If os.walk were rewritten, it should be as an iterator (generator).
>> Directory entry and exit functions could still be added as params.

>It *is* an iterator/generator.  However, I suspect you mean that 
>it should slurp the dirs/files iteratively instead of using 
>listdir() as was discussed on c.l.p a few months back.

Thanks for mentioning this thread.  Very interesting stuff.  Apropos
the implementability of an iterative listdir, I wonder if some
variation of glob.iglob() would fit the bill.  (Maybe it's too
slow, though.)

>I suspect if I thought about it much longer, only one would 
>really be needed, the other accommodated by the "topdown" parameter.

Yeah, I think one only needs a post hook.  The fact that it's a
generator obviates need for a pre hook, since the yield returns
control to the calling function right around where the pre-hook
would run anyway.  For the same reason, the post hook is needed
only for the case topdown=True.

Another useful callback would be one that replaced listdir in the
generation of the current directory's contents.

~K


From zapwireDASHgroups at yahoo.com  Wed May 12 14:54:30 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 11:54:30 -0700
Subject: Do any debuggers support "edit and continue?"
References: 
	
Message-ID: 

"Terry Reedy"  wrote in message 
news:mailman.119.1273690025.32709.python-list at python.org...
> CPython compiles Python code (a sequence of statements) to its private 
> bytecode (a sequence of codes and operands) and then interprets the 
> bytecode. So 'edit and continue' would have to recompile the statement and 
> patch the result into the bytecode.

I believe this is what, e.g., Visual Studio does with, e.g., C++ code -- it 
compiles the modified code and then patches the binary to call the new code as 
a subroutine or somesuch.

> Another problem is recovery of state. If an exception is raised in the 
> middle of a statememt, there would need to be a means to roll back the state 
> of objects and namespaces to what they were before execution of the 
> statement started. So the interpreter would need to act like a transactional 
> database, which is not trivial.

Yeah, I can see this being challenging.  I think it's pretty cool how some 
Python debuggers will allow you to use a shell with the context set to the 
current function or any of the calling functions higher up the call stack 
hierarchy as well.

> This would also slow normal execution, so it would have to be optional.

That'd be a small price to pay. :-)  (Visual Studio only lets you do this with 
unoptimized code...)

> If would definitely be nice. Perhaps $500,000 in funding would do the trick.

Cool, if I win the lottery and add it to the "worty causes" list! :-)

Thanks for the information,
---Joel



From cjw at ncf.ca  Wed May 12 14:55:09 2010
From: cjw at ncf.ca (cjw)
Date: Wed, 12 May 2010 14:55:09 -0400
Subject: How to test whether bit is set within a flag with Python ?
In-Reply-To: 
References: 
	
Message-ID: 

On 12-May-10 14:40 PM, MRAB wrote:
> robert somerville wrote:
>> I am trying to determine how to test whether variors bits are set
>> within a byte (or larger flag) , the python 'and' and 'or' do not seem
>> to be doing what i want .. does anybody have some sample code showing
>> how to do it ??
>>
>> e.g. (in "C")
>>
>> unsigned char a = 6;
>>
>> is 3rd bit set ??
>>
>> a & 4 =, true in this case ....
>>
> 'and', 'or' and 'not' are Boolean.
>
> Python borrows its bitwise operators from C:
>
> & bitwise and
> | bitwise or
> ^ bitwise xor
> ~ bitwise not (ones' complement)
> << shift left
>  >> shift right
>
> You also need to remember that Python's integers are of (virtually)
> unlimited length.

a= 6
if a & 2:
   print 'hit'
else:
   print 'miss'

This hits.

Colin W.



From pmaupin at gmail.com  Wed May 12 15:02:07 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 12:02:07 -0700 (PDT)
Subject: Picking a license
References: 
	<30aff350-169a-4cbf-977a-7947f531008e@r34g2000yqj.googlegroups.com>
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com> 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com> 
	<0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com>
Message-ID: <356d235e-63e3-4d36-bb7e-e436d9279f27@l28g2000yqd.googlegroups.com>

On May 12, 1:00?pm, Paul Boddie  wrote:
> On 12 Mai, 16:10, Patrick Maupin  wrote:
>
> > On May 12, 7:10?am, Paul Boddie  wrote:
> > > What the licence asks you to do and what the author of the licence
> > > wants you to do are two separate things.
>
> > But the whole context was about what RMS wanted me to do and you
> > disagreed!
>
> What RMS as an activist wants is that everyone releases GPL-licensed
> code, except where permissively licensed code might encourage open
> standards proliferation. What RMS the licence author requests is that
> your work is licensed in a way which is compatible with the GPL.

Sorry, didn't know they were twins.

>
> [...]
>
> > > I wrote "the software" above when I meant "your software", but I have
> > > not pretended that the whole system need not be available under the
> > > GPL.
>
> > You say you "have not pretended" but you've never mentioned that it
> > would or even acknowledged the correctness of my assertions about this
> > until now, just claiming that what I said was false.
>
> Well, excuse me! I think we both know that combining something with a
> GPL-licensed work and redistributing it means that the "four freedoms"
> must apply, and that recipients get the work under the GPL. You can
> insist that I said something else, but I spell it out in this post:
>
> http://groups.google.com/group/comp.lang.python/msg/034fbc8289a4d555
>
> Specifically the part...
>
> "Not least because people are only obliged to make their work
> available under a GPL-compatible licence so that people who are using
> the combined work may redistribute it under
> the GPL."
>
> In case you don't find this satisfactory, "their work" means "their
> own work".

OK, but in the last several threads on this sub-part, you kept
contradicting me for some supposed technicality (how was I to know
there were two RMS's?) when I was trying to make the same point.

>
> [...]
>
> > > More loaded terms to replace the last set, I see.
>
> > IMO "Bullying" is the correct term for some of Stallman's actions,
> > including in the clisp debacle. ?I knew you wouldn't agree -- that's
> > why YMMV. ?And I'm not "replacing" any set of terms -- part of the
> > "bullying" is the "forcing."
>
> Stallman gave Haible the choice to not use readline. Maybe that wasn't
> very nice,

It wasn't even legally correct.  At that point, Stallman had access to
counsel, etc. and should have known better.

> and maybe Haible didn't believe that using readline would
> incur any consequences,

He wasn't distributing it!  It didn't incur any legal consequences;
only the consequence due to not realizing that using readline placed
him squarely inside RMS's chess game.

> but that's what you get when you use a
> copyrighted work.

No.  That's what you get when you use a copyrighted work authored by
an idealist who is trying to spread his choice of license.

> Your language is all about portraying the FSF as
> operating in some kind of illegal or unethical way.

Sorry, didn't mean to be that subtle.  RMS and others at the FSF have,
on multiple occasions, made statements about how licenses work which
are legally false.  This is not illegal, but it is, in my opinion,
unethical.  Some of these claims appear to not be made so boldly any
more, so perhaps they are catching on that others have caught on.

> I guess you
> believe that if you throw enough mud, some of it will stick.

I don't care about mud or sticking.  I am happy to see that the
current wording of the FAQ probably means that another clisp/readline
scenario won't happen, and like to believe that the public outcry over
this sort of thing, and reminders of it in this sort of discussion,
help to remind the FSF that others are watching them.

> > > Again, what I meant was "your software", not the whole software
> > > system. As I more or less state below...
>
> > BUT THAT DOESN'T MATTER. ?Once the whole package is licensed under the
> > GPL, for someone downstream to try to scrape the GPL off and get to
> > just the underlying non-GPL parts is harder than scraping bubblegum
> > off your shoe on a hot Texas day.
>
> Big deal. If a project wants to avoid even looking at GPL-licensed
> code for the reason that someone might end up getting the code under
> the GPL, and that they're so bothered that the opportunity to not
> grant such recipients the privileges of modification and
> redistribution disappears because of the GPL, then that's their
> problem.

Yes, I understand it's no big deal to you.  However, what you have
said is not quite right.  If I license something under the MIT
license, I cannot guarantee that no one will ever get it under the
GPL, because it could be redistributed downstream under the GPL (but
then I don't care to in any case).  However, I *can* guarantee that
the code I write (and all the underlying code it relies on) will
remain freely available from me for people who need the ability to,
for example, link with proprietary code.

Despite this not being a very big deal to you, the whole tempest in a
teacup here is about this very issue.  Yes, I understand it is a
problem for me, or any other author who wants to provide code that can
be used freely by people who download it.  And, as has been pointed
out in this discussion, many people don't read licenses very
carefully, so someone who doesn't want to restrict other people from
linking his library with third party proprietary code should think
twice about using the GPL.

> [WebKit is LGPL-licensed but KHTML linked to GPL-licensed code,
> shouldn't WebKit be GPL-licensed?]
>
> > I didn't make that claim and have never heard of that claim, and I'm
> > not at all sure of the relevance of whatever you're trying to explain
> > to the licensing of an overall program, rather than a library.
>
> The point is precisely the one you concede about a project needing to
> be licensed compatibly with the GPL, even though to use the combined
> work, the result will be GPL-licensed.

You keep spinning around on what you're trying to argue or prove.  I
don't know what I'm supposed to have "conceded" -- I was only stating
the obvious about how if I incorporate GPL licensed code in a project,
the entire project has to be GPL licensed.

>
> > > All RMS and the FSF's lawyers wanted was that the CNRI licences be GPL-
> > > compatible. There are actually various aspects of GPL-compatibility
> > > that are beneficial, even if you don't like the copyleft-style
> > > clauses, so I don't think it was to the detriment of the Python
> > > project.
>
> > And I don't have a problem with that. ?Honestly I don't. ?But as far
> > as I'm concerned, although you finally admitted it, a lot of the
> > dancing around appeared to be an attempt to disprove my valid
> > assertion that a combined work would have to be distributed under the
> > GPL, and that no other free software license claims sovereignty over
> > the entire work.
>
> I never denied that the GPL would apply to the combined work! Read the
> stuff I quote above. Your *own* stuff (for example, the WebKit stuff)
> can be licensed compatibly with the GPL (for example, the LGPL), but
> the *whole* thing as it lands in the user's lap will be GPL-licensed.

Yes, but at the outset, I was talking about incorporating (at least to
the point of redistributing) GPL-licensed code.  That forces the
license.

> No, what I am saying is that a fair amount of work might have gone
> into making readline, even though it may not be shiny enough by some
> people's standards, but that doesn't mean you can disregard the
> authors' wishes by insisting that is it "trivial" or unimportant,
> whereas your own software somehow is important. As soon as you go down
> that road, everyone can start belittling the works of others purely so
> that they can start disregarding the terms which regulate those works,
> and then it's a free-for-all.

Ahh, well done.  You've sucked me into a meaningless side debate.  If
I'm not distributing readline, then legally the license distribution
terms don't apply to me.  End of story.  (Morally, now we might get
into how trivial it is or isn't.)

> > > Well, if people are making use of "some good code found for free on
> > > the Internet", particularly if they are corporations like Cisco, and
>
> > I'm not talking about Cisco. ?I'm talking about people like the author
> > of clisp, and you well know it.
>
> Well, Cisco seemed to have a bit of a problem. Maybe they thought that
> this "free stuff" was just a commodity, too.

Well, that's the problem with an "attractive nuisance."  It's
attractive, or people wouldn't use it, and it's a nuisance -- either
you have to have the lawyers look at all this paperwork, or you can
just ignore it and hope for the best and be bothered by the nuisance
later.  And before you start talking about how the license isn't any
worse than Microsoft, etc.  -- just remember that, for Cisco, part of
what makes it attractive is the availability of source.

> > > they choose not to understand things like copyright and licensing, or
> > > they think "all rights reserved" is just a catchy slogan, then they
> > > probably shouldn't be building larger works and redistributing them.
>
> > Well, the FSF seems to have softened its stance, but at the time,
> > clisp wasn't even distributing readline. ?That's why I use terms like
> > "bullying". ?The bully now knows it's harder to get away with that
> > particular lie, but he's still scheming about how to reel more people
> > in.
>
> What the FSF did was regrettable if the author didn't feel he had a
> choice. I have no idea what went on beyond what the public mailing
> list record can reveal.

But you don't need to know anything else.  RMS claimed clisp was a
derivative work of readline, even though readline wasn't even
distributed with clisp.  That's just plain copyright misuse, and if it
had gone to court with good lawyers, RMS might have lost the copyright
protections for readline.

Regards,
Pat


From no.email at please.post  Wed May 12 15:04:47 2010
From: no.email at please.post (kj)
Date: Wed, 12 May 2010 19:04:47 +0000 (UTC)
Subject: Limitation of os.walk
References: 
	
Message-ID: 

In  Terry Reedy  writes:

>On 5/11/2010 3:49 PM, kj wrote:
>> PS: I never understood why os.walk does not support hooks for key
>> events during such a tree traversal.

>Either 1) it is intentionally simple, with the expectation that people 
>would write there own code for more complicated uses or 2) no one has 
>submitted a 'full-featured' version or 3) both.

I hope it's not (1): I want the language I use to include more
"batteries" not fewer.

It seems that a similar "simplicity argument" was invoked
to strip the cmp option from sort in Python 3.  Grrrr.  Simplicity
is great, but when the drive for it starts causing useful functionality
to be thrown out, then it is going too far.  Yes, I know that it
is possible to do everything that sort's cmp option does through
clever tricks with key, but grokking and coding this maneuver
requires a *lot* more Python-fu than cmp did, which makes this
functionality a lot less accessible to beginners that the intrinsic
complexity of the problem warrants.  And for what?  To get rid of
an *option* that could be easily disregarded by anyone who found
it too "complex"? It makes no sense to me.


From lie.1296 at gmail.com  Wed May 12 15:05:45 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Thu, 13 May 2010 05:05:45 +1000
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: <4beafc68$1@dnews.tpgi.com.au>

On 05/13/10 03:42, Joel Koltner wrote:
> Just curious... in Microsoft's Visual Studio (and I would presume some
> other tools), for many languages (both interpreted and compiled!)
> there's an "edit and conitnue" option that, when you hit a breakpoint,
> allows you to modify a line of code before it's actually executed.
> 
> Does any Python debugger support this feature?  Being an interpreted
> language it doesn't seem like it would necessarily be too onerous to
> support?  It'd be quite handy in that, especially if you hit a
> breakpoint due to the interpreter throwing an error, you could fix just
> the line in question and keep going, rather than having to stop the
> entire program, fix the line, and then run again and potentially kill a
> bunch of time getting the program back into the same "state."
> 

Using pdb, if you step through a function, you can execute arbitrary
python function in the break and then 'jump' to the line after the next,
effectively simulating "edit and continue". I don't know if there's any
GUI interface to pdb that uses them though.


From phlip2005 at gmail.com  Wed May 12 15:33:18 2010
From: phlip2005 at gmail.com (Phlip)
Date: Wed, 12 May 2010 12:33:18 -0700 (PDT)
Subject: Do any debuggers support "edit and continue?"
References: 
Message-ID: 

On May 12, 10:42?am, "Joel Koltner" 
wrote:

> Does any Python debugger support this feature?

I have worked for >3 years by now in Python and have never once
debugged.

People who need "edit and continue" probably need developer tests
instead. You typically edit the test a little, run all the code, edit
the code a little, run all the code, and integrate whenever the code's
a little better and all the tests pass.

To avoid debugging, if the tests fail unexpectedly or mysteriously,
you just 'git reset --hard HEAD'. Your bug disappears. Better than a
debugger!


From zapwireDASHgroups at yahoo.com  Wed May 12 15:44:06 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 12:44:06 -0700
Subject: Do any debuggers support "edit and continue?"
References: 
	
Message-ID: 

"Phlip"  wrote in message 
news:d580dece-bd42-4753-a0c6-783ce69b5a81 at m31g2000pre.googlegroups.com...
> People who need "edit and continue" probably need developer tests
> instead. You typically edit the test a little, run all the code, edit
> the code a little, run all the code, and integrate whenever the code's
> a little better and all the tests pass.

I find myself making mistakes in typing the name of classes and/or methods 
when I'm first getting started with them (there are some thousands of them 
after all, and even of commonly used classes/methods you're probably talking 
upwards of a hundred), *particularly* when using libraries such as wxWidgets 
that use "fancy" imports that aren't correctly picked up by the "code 
intelligence" analyzers in, e.g., Komodo or Wing.



From martin at v.loewis.de  Wed May 12 16:24:09 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Wed, 12 May 2010 22:24:09 +0200
Subject: open(False) in python3
In-Reply-To: 
References: 			
	
Message-ID: <4BEB0E69.8080506@v.loewis.de>

geremy condra wrote:
> On Wed, May 12, 2010 at 1:36 AM, Stefan Behnel  wrote:
>> Johan F?rberg, 12.05.2010 10:05:
>>> On Tue, 11 May 2010 19:27:37 -0300, Gabriel Genellina wrote:
>>>
>>>> so open(False) is the same as open(0), and 0 is the file descriptor
>>>> associated to standard input. The program isn't hung, it's just waiting
>>>> for you to type some text
>>> That's interesting. Are there any more numbered pseudofiles? I suppose
>>> its mainly an excellent way to confuse people when you open(0).read(),
>>> but it would be interesting to know.
>> Standard Unix behaviour dictates that 0 is stdin, 1 is stdout, and 2 is
>> stderr. So you can only read() from 0.
>>
>> Stefan
> 
> Nitpicking, but open(1).read() and open(2).read() both succeed
> (for small values of success) the same way that open(0).read()
> does.

That's because your operating system made that so. Try a different
operating system, and you may get different results.

Regards,
Martin


From phlip2005 at gmail.com  Wed May 12 16:31:05 2010
From: phlip2005 at gmail.com (Phlip)
Date: Wed, 12 May 2010 13:31:05 -0700 (PDT)
Subject: Do any debuggers support "edit and continue?"
References:  
	 
	
Message-ID: <75c050d2-365e-4b08-8716-884ed5473572@k25g2000prh.googlegroups.com>

On May 12, 12:44?pm, "Joel Koltner" 
wrote:

> I find myself making mistakes in typing the name of classes and/or methods
> when I'm first getting started with them (there are some thousands of them
> after all, and even of commonly used classes/methods you're probably talking
> upwards of a hundred), *particularly* when using libraries such as wxWidgets
> that use "fancy" imports that aren't correctly picked up by the "code
> intelligence" analyzers in, e.g., Komodo or Wing.

Are you implying that you then run the code, and - after a handful of
higher-level calls - control flow gets down to the lines you just
typed, and the run fails because they are misspelled? The only fix is
decoupling, and _expecting_ your first few debugger or test runs to
fail.

Other than that, lolwut?


From zapwireDASHgroups at yahoo.com  Wed May 12 16:38:25 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 13:38:25 -0700
Subject: Do any debuggers support "edit and continue?"
References: 
	
	
	<75c050d2-365e-4b08-8716-884ed5473572@k25g2000prh.googlegroups.com>
Message-ID: <7lEGn.122365$iG7.15555@en-nntp-12.dc1.easynews.com>

"Phlip"  wrote in message 
news:75c050d2-365e-4b08-8716-884ed5473572 at k25g2000prh.googlegroups.com...
On May 12, 12:44 pm, "Joel Koltner" 
wrote:
>Are you implying that you then run the code, and - after a handful of
>higher-level calls - control flow gets down to the lines you just
>typed, and the run fails because they are misspelled?

Correct.

>The only fix is
>decoupling, and _expecting_ your first few debugger or test runs to
>fail.

Well, sure, that is the current fix... but an "edit and continue" feature 
would make for a much faster fix. :-)



From phlip2005 at gmail.com  Wed May 12 16:40:53 2010
From: phlip2005 at gmail.com (Phlip)
Date: Wed, 12 May 2010 13:40:53 -0700 (PDT)
Subject: Do any debuggers support "edit and continue?"
References:  
	 
	
	<75c050d2-365e-4b08-8716-884ed5473572@k25g2000prh.googlegroups.com>
	<7lEGn.122365$iG7.15555@en-nntp-12.dc1.easynews.com>
Message-ID: 

On May 12, 1:38?pm, "Joel Koltner" 
wrote:

> Well, sure, that is the current fix... but an "edit and continue" feature
> would make for a much faster fix. :-)

Are you implying, after an edit, you need to start a program again,
then enter several user inputs, to navigate back to the place where
you hit the syntax error? (WxWidgets noted - props!)


From cde3 at live.com  Wed May 12 17:01:37 2010
From: cde3 at live.com (Sandy Sandy)
Date: Thu, 13 May 2010 02:01:37 +0500
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: 



maybe ipython?


http://showmedo.com/videos/video?name=1000020&fromSeriesID=100



> From: zapwireDASHgroups at yahoo.com
> Subject: Do any debuggers support "edit and continue?"
> Date: Wed, 12 May 2010 10:42:31 -0700
> To: python-list at python.org
> 
> Just curious... in Microsoft's Visual Studio (and I would presume some other 
> tools), for many languages (both interpreted and compiled!) there's an "edit 
> and conitnue" option that, when you hit a breakpoint, allows you to modify a 
> line of code before it's actually executed.
> 
> Does any Python debugger support this feature?  Being an interpreted language 
> it doesn't seem like it would necessarily be too onerous to support?  It'd be 
> quite handy in that, especially if you hit a breakpoint due to the interpreter 
> throwing an error, you could fix just the line in question and keep going, 
> rather than having to stop the entire program, fix the line, and then run 
> again and potentially kill a bunch of time getting the program back into the 
> same "state."
> 
> Thanks,
> ---Joel Koltner
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
 		 	   		  
_________________________________________________________________
Hotmail: Powerful Free email with security by Microsoft.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nagle at animats.com  Wed May 12 17:18:53 2010
From: nagle at animats.com (John Nagle)
Date: Wed, 12 May 2010 14:18:53 -0700
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 
Message-ID: <4beb15c5$0$1634$742ec2ed@news.sonic.net>

Joel Koltner wrote:
> Just curious... in Microsoft's Visual Studio (and I would presume some 
> other tools), for many languages (both interpreted and compiled!) 
> there's an "edit and conitnue" option that, when you hit a breakpoint, 
> allows you to modify a line of code before it's actually executed.
> 
> Does any Python debugger support this feature?  Being an interpreted 
> language it doesn't seem like it would necessarily be too onerous to 
> support?  It'd be quite handy in that, especially if you hit a 
> breakpoint due to the interpreter throwing an error, you could fix just 
> the line in question and keep going, rather than having to stop the 
> entire program, fix the line, and then run again and potentially kill a 
> bunch of time getting the program back into the same "state."

    Having actually used LISP systems with "edit and continue", it's a good
thing that Python doesn't have it.  It encourages a "patch" mentality, and
the resulting code is usually disappointing.

    What the original poster seems to need is a global analysis
tool that insures that all names used are defined.  Like "pylint".

					John Nagle


From joax.spec at gmail.com  Wed May 12 17:21:22 2010
From: joax.spec at gmail.com (Joax Spec)
Date: Wed, 12 May 2010 16:21:22 -0500
Subject: fails to call python from jython for types, functools, csv modules
Message-ID: 

Hello I'm very new to python/jython, and trying yo *call a program from
jython*, which works very good in python.
I got some issues which resolve as I expose here, but I think these are
unsatisfactory solutions.
If you want to reply please do it to my address.

thanks,
Jx

PD. both are great projects!!!

1. FIRST Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 1, in 
  File "C:\Python26\lib\re.py", line 283, in 
    import copy_reg
  File "C:\Python26\lib\copy_reg.py", line 7, in 
    from types import ClassType as _ClassType
  File "C:\Python26\lib\types.py", line 36, in 
    BufferType = buffer
NameError: name 'buffer' is not defined

*Solution --> comment in types.py   #BufferType = buffer (line 37)*

2. SECOND Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 3, in 
  File "C:\Python26\lib\csv.py", line 7, in 
    from functools import reduce
  File "C:\Python26\lib\functools.py", line 10, in 
    from _functools import partial, reduce
ImportError: cannot import name reduce

*Solution --> comment in functools.py   #, reduce (line 10)
Problem --> IDLE for windows doesn't work anymore, I mean I can lauch the
GUI, but I can still use python from command line*

3. THIRD Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 3, in 
  File "C:\Python26\lib\csv.py", line 7, in 
    from functools import reduce
ImportError: cannot import name reduce

*Solution --> comment in csv.py  #@fieldnames.setter (line 96)*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From zapwireDASHgroups at yahoo.com  Wed May 12 18:03:36 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 15:03:36 -0700
Subject: Do any debuggers support "edit and continue?"
References: 
	
	
	<75c050d2-365e-4b08-8716-884ed5473572@k25g2000prh.googlegroups.com>
	<7lEGn.122365$iG7.15555@en-nntp-12.dc1.easynews.com>
	
Message-ID: 

"Phlip"  wrote in message 
news:c014ae9f-99d8-4857-a3f7-e6ac16e45250 at e34g2000pra.googlegroups.com...
>Are you implying, after an edit, you need to start a program again,
>then enter several user inputs, to navigate back to the place where
>you hit the syntax error? (WxWidgets noted - props!)

Pretty much, yeah... Realistically, we're probably talking less than a minute 
each time, so objectively it's not really a big deal -- it's just different 
than what I'm used to so I'm noticing it more. :-)

I guess what I'm realizing here is that one of the upsides of compiled 
languages is that they'll (usually) catch most typos before your program even 
runs!



From zapwireDASHgroups at yahoo.com  Wed May 12 18:07:37 2010
From: zapwireDASHgroups at yahoo.com (Joel Koltner)
Date: Wed, 12 May 2010 15:07:37 -0700
Subject: Do any debuggers support "edit and continue?"
References: 
	<4beb15c5$0$1634$742ec2ed@news.sonic.net>
Message-ID: 

"John Nagle"  wrote in message 
news:4beb15c5$0$1634$742ec2ed at news.sonic.net...
>    Having actually used LISP systems with "edit and continue", it's a good
> thing that Python doesn't have it.  It encourages a "patch" mentality, and
> the resulting code is usually disappointing.

Hey, a lot of people would argue that Python's lack of strong typing and 
data/member protection (from one class to another) encourages sloppy 
programming too. :-)  (Some people even figure that automatic garbage 
collection does so!)

>    What the original poster seems to need is a global analysis
> tool that insures that all names used are defined.  Like "pylint".

Sounds intriguing... I'll check it out; thanks!

---Joel



From phlip2005 at gmail.com  Wed May 12 18:13:50 2010
From: phlip2005 at gmail.com (Phlip)
Date: Wed, 12 May 2010 15:13:50 -0700 (PDT)
Subject: Do any debuggers support "edit and continue?"
References:  
	 
	
	<75c050d2-365e-4b08-8716-884ed5473572@k25g2000prh.googlegroups.com>
	<7lEGn.122365$iG7.15555@en-nntp-12.dc1.easynews.com>
	
	
Message-ID: 

On May 12, 3:03?pm, "Joel Koltner" 
wrote:

> Pretty much, yeah... Realistically, we're probably talking less than a minute
> each time, so objectively it's not really a big deal -- it's just different
> than what I'm used to so I'm noticing it more. :-)
>
> I guess what I'm realizing here is that one of the upsides of compiled
> languages is that they'll (usually) catch most typos before your program even
> runs!

When you write developer tests ("unit tests"), you edit the code for a
while, hit a test button, and get instant feedback - syntax errors,
assertion failures, or a green bar. Then you edit a little more. This
allows you to learn to make the smallest possible edits that
constantly return you to a testworthy state.

Each test case does everything you did, manually. It sets up various
inputs and runs them thru a system. Better, it sets up inputs for each
specific method, not just for the whole app. That helps decouple the
specific methods, so they don't accidentally depend on everything.


From pmaupin at gmail.com  Wed May 12 18:26:23 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 15:26:23 -0700 (PDT)
Subject: Limitation of os.walk
References: 
	 
	
Message-ID: <970bdae6-2436-4e3a-95b2-6bdaf67a3218@d27g2000yqc.googlegroups.com>

On May 12, 2:04?pm, kj  wrote:
> It seems that a similar "simplicity argument" was invoked
> to strip the cmp option from sort in Python 3. ?Grrrr. ?Simplicity
> is great, but when the drive for it starts causing useful functionality
> to be thrown out, then it is going too far. ?Yes, I know that it
> is possible to do everything that sort's cmp option does through
> clever tricks with key, but grokking and coding this maneuver
> requires a *lot* more Python-fu than cmp did, which makes this
> functionality a lot less accessible to beginners that the intrinsic
> complexity of the problem warrants. ?And for what? ?To get rid of
> an *option* that could be easily disregarded by anyone who found
> it too "complex"? It makes no sense to me.

I didn't follow the discussion on cmp and Python 3, but I would assume
one reason it was removed was for performance.  cmp is very slow
compared to key, and if there should be one obvious way to do it, it
should probably be the way that runs faster.  Also, while in many
cases cmp can be easier to use than key, it would be possible for a
naive person with a complicated data structure to come up with a cmp
function that, e.g. sorted A > B, B > C, and C > A.  It's impossible
to come up with a key function that will break sort in that fashion.
So, while I understand the frustration of having a favorite tool
removed, I have no trouble believing that there were good reasons for
the removal.

Regards,
Pat


From paul at boddie.org.uk  Wed May 12 18:41:42 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 15:41:42 -0700 (PDT)
Subject: Picking a license
References: 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com>
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com> 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com> 
	<0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com> 
	<356d235e-63e3-4d36-bb7e-e436d9279f27@l28g2000yqd.googlegroups.com>
Message-ID: <845fc53a-5940-44fc-9189-a5a8ff56a95d@n15g2000yqf.googlegroups.com>

On 12 Mai, 21:02, Patrick Maupin  wrote:
> On May 12, 1:00?pm, Paul Boddie  wrote:

[Quoting himself...]

> > "Not least because people are only obliged to make their work
> > available under a GPL-compatible licence so that people who are using
> > the combined work may redistribute it under
> > the GPL."
>
> > In case you don't find this satisfactory, "their work" means "their
> > own work".
>
> OK, but in the last several threads on this sub-part, you kept
> contradicting me for some supposed technicality (how was I to know
> there were two RMS's?) when I was trying to make the same point.

We both agree that any combining a work with a GPL-licensed work means
that the result has to be distributable under the GPL. I was also
merely pointing out that the non-GPL-licensed work has to be licensed
compatibly if the possibility of combination with GPL-licensed works
exists, but you still get to choose the licence. You even acknowledged
this:

"In practice, what it really means is that the combination (e.g. the
whole program) would effectively be GPL-licensed.  This then means
that downstream users would have to double-check that they are not
combining the whole work with licenses which are GPL-incompatible,
even if they are not using the svg feature."

And for the last time, Stallman's opinion on what you should or should
not do is a distinct matter from the actual use of these licences.

[Haible and readline]

> He wasn't distributing it! ?It didn't incur any legal consequences;
> only the consequence due to not realizing that using readline placed
> him squarely inside RMS's chess game.

Really, what Stallman did in 1992 is a matter for Stallman to defend.
Whether a bunch of people use the GPL to license their work or not is
a separate matter. All I can say is that Stallman's reasoning was
probably driven by the possibility that someone could license their
work in a fashion that is incompatible with readline, but deliberately
be able to make use of it technically, and then when a user combines
that work and readline, the user is told that although readline is
used in that combined work, the licensing terms do not now apply.

[...]

> No. ?That's what you get when you use a copyrighted work authored by
> an idealist who is trying to spread his choice of license.

Well, take it up with Stallman, then. It's a separate issue from the
use of the FSF's licences and even how the FSF functions today.

[...]

> Yes, I understand it's no big deal to you. ?However, what you have
> said is not quite right. ?If I license something under the MIT
> license, I cannot guarantee that no one will ever get it under the
> GPL, because it could be redistributed downstream under the GPL (but
> then I don't care to in any case). ?However, I *can* guarantee that
> the code I write (and all the underlying code it relies on) will
> remain freely available from me for people who need the ability to,
> for example, link with proprietary code.

Yes, and as I said, in the context of a program landing in a user's
lap, there is no guarantee that such a program will offer users any
privileges other than to run the program, and then maybe only under
certain conditions. Which is how this discussion began.

> Despite this not being a very big deal to you, the whole tempest in a
> teacup here is about this very issue. ?Yes, I understand it is a
> problem for me, or any other author who wants to provide code that can
> be used freely by people who download it. ?And, as has been pointed
> out in this discussion, many people don't read licenses very
> carefully, so someone who doesn't want to restrict other people from
> linking his library with third party proprietary code should think
> twice about using the GPL.

Sure, the permissive licences declare fewer restrictions or
obligations on immediate recipients, but what kicked this discussion
off was the remark about end-user privileges, not what certain
recipients (but not others) are able to do with the code.

[...]

> > No, what I am saying is that a fair amount of work might have gone
> > into making readline, even though it may not be shiny enough by some
> > people's standards, but that doesn't mean you can disregard the
> > authors' wishes by insisting that is it "trivial" or unimportant,
> > whereas your own software somehow is important. As soon as you go down
> > that road, everyone can start belittling the works of others purely so
> > that they can start disregarding the terms which regulate those works,
> > and then it's a free-for-all.
>
> Ahh, well done. ?You've sucked me into a meaningless side debate. ?If
> I'm not distributing readline, then legally the license distribution
> terms don't apply to me. ?End of story. ?(Morally, now we might get
> into how trivial it is or isn't.)

According to the FSF, whose opinions you don't trust, it doesn't
matter if you do distribute readline or not:

http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPL
http://www.gnu.org/licenses/gpl-faq.html#IfLibraryIsGPL

>From version 3 of the GPL:

"For example, Corresponding Source includes interface definition files
associated with source files for the work, and the source code for
shared libraries and dynamically linked subprograms that the work is
specifically designed to require, such as by intimate data
communication or control flow between those subprograms and other
parts of the work."

You may beg to differ. I would advise against doing so in a courtroom.

[...]

> But you don't need to know anything else. ?RMS claimed clisp was a
> derivative work of readline, even though readline wasn't even
> distributed with clisp. ?That's just plain copyright misuse, and if it
> had gone to court with good lawyers, RMS might have lost the copyright
> protections for readline.

Now that *is* a ridiculous statement. Just because a decision is made
that one work is not derived from another does not mean that the
claimed original work is no longer subject to copyright.

Paul


From mensanator at aol.com  Wed May 12 18:56:45 2010
From: mensanator at aol.com (Mensanator)
Date: Wed, 12 May 2010 15:56:45 -0700 (PDT)
Subject: How to test whether bit is set within a flag with Python ?
References:  
	
Message-ID: 

On May 12, 1:40?pm, MRAB  wrote:
> robert somerville wrote:
> > I am trying to determine how to test whether variors bits are set within
> > a byte (or larger flag) , the python 'and' and 'or' do not seem to be
> > doing what i want .. does anybody have some sample code showing how to
> > do it ??
>
> > e.g. (in "C")
>
> > unsigned char a = 6;
>
> > is 3rd bit set ??
>
> > a & 4 =, ?true in this case ....
>
> 'and', 'or' and 'not' are Boolean.
>
> Python borrows its bitwise operators from C:
>
> ? ? ?& ? ? bitwise and
> ? ? ?| ? ? bitwise or
> ? ? ?^ ? ? bitwise xor
> ? ? ?~ ? ? bitwise not (ones' complement)
> ? ? ?<< ? ?shift left
> ? ? ?>> ? ?shift right
>
> You also need to remember that Python's integers are of (virtually)
> unlimited length.

The gmpy module has a wonderful set of functions tailored to the
bit twiddler:

FUNCTIONS
    bit_length(...)
        bit_length(x): returns length of string representing x in base
2

>>> gmpy.bit_length(275)
9

    digits(...)
        digits(x[,base]): returns Python string representing x in the
        given base (2 to 36, default 10 if omitted or 0); leading '-'
        present if x<0, but no leading '+' if x>=0. x must be an mpz,
        or else gets coerced into one.

>>> gmpy.digits(275,2)
'100010011'

    hamdist(...)
        hamdist(x,y): returns the Hamming distance (number of bit-
positions
        where the bits differ) between x and y.  x and y must be mpz,
or else
        get coerced to mpz.

>>> a = 275    # '100010011'
>>> b = 333    # '101001101'
               #    x xxxx
>>> gmpy.hamdist(a,b)
5

    lowbits(...)
        lowbits(x,n): returns the n lowest bits of x; n must be an
        ordinary Python int, >0; x must be an mpz, or else gets
        coerced to one.

>>> gmpy.digits(gmpy.lowbits(333,8),2)
'1001101' # (bit 7 was a 0)

    numdigits(...)
        numdigits(x[,base]): returns length of string representing x
in
        the given base (2 to 36, default 10 if omitted or 0); the
value
        returned may sometimes be 1 more than necessary; no provision
        for any 'sign' character, nor leading '0' or '0x' decoration,
        is made in the returned length.  x must be an mpz, or else
gets
        coerced into one.

>>> import collatz_functions
>>> c = collatz_functions.Type12MH(6,1)
>>> gmpy.numdigits(c,2)
177149

    popcount(...)
        popcount(x): returns the number of 1-bits set in x; note that
        this is 'infinite' if x<0, and in that case, -1 is returned.
        x must be an mpz, or else gets coerced to one.

>>> gmpy.popcount(3**33)
34
>>> gmpy.digits(3**33,2)
'10011101111111110111110100110010110101011101110000011'

    scan0(...)
        scan0(x, n=0): returns the bit-index of the first 0-bit of x
(that
        is at least n); n must be an ordinary Python int, >=0.  If no
more
        0-bits are in x at or above bit-index n (which can only happen
for
        x<0, notionally extended with infinite 1-bits), None is
returned.
        x must be an mpz, or else gets coerced to one.

>>> gmpy.scan0(3**33,4) # find first 0 bit starting at bit4
4
'10011101111111110111110100110010110101011101110000011'
                                                 x
    scan1(...)
        scan1(x, n=0): returns the bit-index of the first 1-bit of x
(that
        is at least n); n must be an ordinary Python int, >=0.  If no
more
        1-bits are in x at or above bit-index n (which can only happen
for
        x>=0, notionally extended with infinite 0-bits), None is
returned.
        x must be an mpz, or else gets coerced to one.

>>> gmpy.scan1(3**33,4) # find first 1 bit starting at bit4
7
'10011101111111110111110100110010110101011101110000011'
                                              x

    setbit(...)
        setbit(x,n,v=1): returns a copy of the value of x, with bit n
set
        to value v; n must be an ordinary Python int, >=0; v, 0 or !
=0;
        x must be an mpz, or else gets coerced to one.

>>> a = 2**24+1
>>> gmpy.digits(a,2)
'1000000000000000000000001'
>>> a = gmpy.setbit(a,12,1)
>>> gmpy.digits(a,2)
'1000000000001000000000001'


From zuo at chopin.edu.pl  Wed May 12 19:07:15 2010
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Thu, 13 May 2010 01:07:15 +0200
Subject: open(False) in python3
In-Reply-To: 
References: 
	
	
	
Message-ID: <20100512230714.GA8407@chopin.edu.pl>

Terry Reedy dixit (2010-05-12, 14:26):

> On 5/12/2010 1:26 PM, Giampaolo Rodol? wrote:
> >2010/5/12 Gabriel Genellina:
> >>open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
> >>builtin open() + os.fdopen() from 2.x all merged together. It does different
> >>things depending on the type and quantity of its arguments, and even returns
> >>objects of different types.
> 
> The change actually happened, according to 'What's new', in 2.6 when
> 'open' was made a synonym for the new io.open.

It did happened in 3.0, not in 2.6.

Regards,
*j


From paul at boddie.org.uk  Wed May 12 19:15:16 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 16:15:16 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
Message-ID: <26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>

On 12 Mai, 20:29, Patrick Maupin  wrote:
>
> But nobody's whining about the strings attached to the software. ?Just
> pointing out why they sometimes won't use a particular piece of
> software, and pointing out that some other people (e.g. random Ubuntu
> users) might not understand the full cost of the software, and that
> that is because the cost of the software has been deliberately
> obscured by using unqualified terms like all-caps "Free Software."

Right. The "full cost" of software that probably cost them nothing
monetarily and which comes with all the sources, some through a chain
of distribution and improvement which could have led to proprietary
software had the earliest stages in the chain involved permissive
licensing. And that they can't sell a binary-only Ubuntu derivative.

[...]

> Oh, no wonder I didn't understand what you were getting at with the
> analogy. ?I'm not whining about people licensing stuff under the GPL,
> just about its apologists pretending there are never any negative
> consequences from it.

So, the "negative consequences" are that people can't make proprietary
editions of some software. When that's a deliberate choice in the
design of a licence, there's no pretending that the consequences
aren't there, just that they aren't perceived by everyone to be
negative.

[Sharing alike]

> I somehow knew that is how you would read my posts, but no. ?It's
> people like you putting words in my month that is objectionable.

Well, you effectively said that you didn't like being asked to "share
alike", which is what the GPL achieves, so why should I not assume
that you generally object to other, more obviously labelled licences
like the CC-*-SA licences which make it clear what is expected of that
hapless recipient of a work who doesn't bother reading the licence?

[Obligations after joining a scheme]

> Sorry, that is absolutely no different than what I originally said
> when I was first defending Aahz's use of the word "force" to Ben
> Finney back on the 7th:
>
> "Perhaps you feel "forces" is too loaded of a word. ?There is no
> question, however, that a copyright license can require that if you do
> "X" with some code, you must also do "Y". ?There is also no question
> that the GPL uses this capability in copyright law to require anybody
> who distributes a derivative work to provide the source. ?Thus,
> "forced to contribute back any changes" is definitely what happens
> once the decision is made to distribute said changes in object form."
>
> Both your "make" and my "force" mean "to compel." ?We've come full
> circle. ?The English language makes no real distinction between
> "making everyone commit" and "forcing everyone [to] commit".

Yes, but you have to choose to do something ("X") to start with. Which
is actually what you wrote later in that exchange:

"Again, the force is applied once you choose to do a particular thing
with the software -- is is really that hard to understand that
concept?"

But you're virtually claiming that people stumble into a situation
where they have to do something they don't like or didn't anticipate,
when in fact they've actually entered into an agreement.

[...]

> My problem, exactly, is that bothering Mepis, yet not bothering Joe
> Blow when he gives a copy to his friend, is exactly the kind of
> selective enforcement of copyright rights that Microsoft is accused of
> when they turn a blind eye to piracy in third-world countries.

Nonsense. If anything, it's a matter of priorities, and completely
absurd to claim that the FSF and all the other copyright holders for
GPL-licensed software on Ubuntu installation media are all conspiring
together to "seed" the planet with "unlicensed wares" in order to reap
some kind of monetary reward afterwards, which is what Microsoft has
been accused of.

[...]

> Despite your opinion, there is nothing legally or morally wrong with
> me using GPL software (and not redistributing it) just because I

I never said there was. I said that if you don't like the licence,
don't incorporate works which use it into your own projects. But don't
say that it's not fair that people are releasing stuff under terms you
don't like, or say that they're being "pathetic" or petty or
ridiculous by doing so, or are imposing their agenda on you.

> happen to feel that (a) for my purposes, for most stuff I write, it
> happens to be the wrong license, (b) (especially historically) some of
> the practices used to insure proliferation of the GPL are ethically
> questionable, and (c) whenever these ethically questionable practices
> are discussed, quasi-religious apologists will take these questionable
> practices to the next level, by selective quoting and bad analogies
> and hinting at things without actually coming out and saying them, and
> all sorts of other debate tactics designed to confuse rather than
> enlighten.

More name-calling and finger-pointing. Great stuff, there. Anything
else?

Paul


From paul at boddie.org.uk  Wed May 12 19:32:47 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 May 2010 16:32:47 -0700 (PDT)
Subject: Picking a license
References: 
Message-ID: 

On 11 Mai, 14:12, Ed Keith  wrote:
> --- On Mon, 5/10/10, Ben Finney  wrote:
>
> > So I object to muddying the issue by misrepresenting the source of that
> > force. Whatever force there is in copyright comes from law, not any free
> > software license.
>
> You are the one muddying the waters. It does not mater whether you break my
> kneecaps, or hire someone else to break my kneecaps, either way my kneecaps
> are broken.

Nice analogy. In fact, the "force" mentioned above is nothing more
than the thing which makes these licensing agreements binding. All the
talk about the GPL "forcing" people to do stuff, when the stuff is
actually one side of a bargain or the obligations of a party in an
agreement, is great theatre but nothing more.

> You can use any license you want, but the simple fact is that if there are
> fewer restrictions in the license then the user has more freedom in how he
> uses the licensed code.

Yes, the recipient of that code as issued by you has fewer
restrictions on their actions and thus more privileges. However,
recipients of the extended work may be denied any or nearly all of
these privileges.

> If there are more restrictions he/she has less freedom in how he/she uses
> the licensed code.

Yes, that recipient does not get to exercise certain privileges.
However, recipients of the extended work retain the same set of
privileges. As do recipients of the work upon subsequent
redistribution.

> We can debate which is better (whether a man should be free to sell
> himself into slavery) but to claim that putting more restrictions on
> someone give them more freedom is pure Orwellian double speak.

It may provide fewer privileges for initial recipients but may grant
those privileges more widely.

> Sophistry is the last resort of those who have run out of good
> arguments. The more you engage in it the weaker you make your position.

Then I challenge you to dispute the statements of my last three
paragraphs without introducing a specific notion of "freedom" in order
to make your case.

> This thread is generating more heat than light, and probably should be dropped.

On this I don't necessarily disagree.

Paul


From pmaupin at gmail.com  Wed May 12 19:36:57 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 16:36:57 -0700 (PDT)
Subject: Picking a license
References: 
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g2000yqa.googlegroups.com>
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com> 
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com> 
	<0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com> 
	<356d235e-63e3-4d36-bb7e-e436d9279f27@l28g2000yqd.googlegroups.com> 
	<845fc53a-5940-44fc-9189-a5a8ff56a95d@n15g2000yqf.googlegroups.com>
Message-ID: <5c1c0cce-f9f9-469b-ba3b-3eb9280c2bc9@g21g2000yqk.googlegroups.com>

On May 12, 5:41?pm, Paul Boddie  wrote:
> > Ahh, well done. ?You've sucked me into a meaningless side debate. ?If
> > I'm not distributing readline, then legally the license distribution
> > terms don't apply to me. ?End of story. ?(Morally, now we might get
> > into how trivial it is or isn't.)
>
> According to the FSF, whose opinions you don't trust, it doesn't
> matter if you do distribute readline or not:
>
> http://www.gnu.org/licenses/gpl-faq.html#LinkingWithGPLhttp://www.gnu.org/licenses/gpl-faq.html#IfLibraryIsGPL
>
> From version 3 of the GPL:
>
> "For example, Corresponding Source includes interface definition files
> associated with source files for the work, and the source code for
> shared libraries and dynamically linked subprograms that the work is
> specifically designed to require, such as by intimate data
> communication or control flow between those subprograms and other
> parts of the work."
>
> You may beg to differ. I would advise against doing so in a courtroom.

Well, it's unlikely anybody will get a chance in a courtroom, because
nobody's going to bring suit.

>
> > But you don't need to know anything else. ?RMS claimed clisp was a
> > derivative work of readline, even though readline wasn't even
> > distributed with clisp. ?That's just plain copyright misuse, and if it
> > had gone to court with good lawyers, RMS might have lost the copyright
> > protections for readline.
>
> Now that *is* a ridiculous statement. Just because a decision is made
> that one work is not derived from another does not mean that the
> claimed original work is no longer subject to copyright.

Well, it won't come to court because the FSF is just going to posture
on this issue, but never really sue anybody (certainly not any open
source project), because they would lose both in court and in public
opinion.  But if they did decide to sue, a few prior cases like Sega v
Accolade and Galoob v Nintendo, as well as the court's use of the
abstraction, filtration and comparison tests to strip functionality
away from copyrightable subject matter, would probably be dispositive
in determining that a substantial program like clisp that didn't
include readline, but which could use readline, is not, in fact, a
derivative of readline.

Once the court reaches that conclusion, it would only be a tiny step
to find that the FSF's attempt to claim that clisp infringes the
readline copyright to be a misuse of that same readline copyright.
See, e.g. LaserComb v Reynolds, where the defendant (IMHO) acted much
more egregiously than anybody who is delivering free software like
clisp is acting, and nevertheless won on that issue.

Regards,
Pat


From pmaupin at gmail.com  Wed May 12 19:58:15 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 16:58:15 -0700 (PDT)
Subject: Picking a license
References: 
	
	<30aff350-
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com>
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
Message-ID: <1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>

On May 12, 6:15?pm, Paul Boddie  wrote:
> On 12 Mai, 20:29, Patrick Maupin  wrote:
>
>
>
> > But nobody's whining about the strings attached to the software. ?Just
> > pointing out why they sometimes won't use a particular piece of
> > software, and pointing out that some other people (e.g. random Ubuntu
> > users) might not understand the full cost of the software, and that
> > that is because the cost of the software has been deliberately
> > obscured by using unqualified terms like all-caps "Free Software."
>
> Right. The "full cost" of software that probably cost them nothing
> monetarily and which comes with all the sources, some through a chain
> of distribution and improvement which could have led to proprietary
> software had the earliest stages in the chain involved permissive
> licensing. And that they can't sell a binary-only Ubuntu derivative.

Who's talking about selling a binary-only version -- there is a good
chance they can't even give away a binary CD without violating
copyright.

> [...]
>
> > Oh, no wonder I didn't understand what you were getting at with the
> > analogy. ?I'm not whining about people licensing stuff under the GPL,
> > just about its apologists pretending there are never any negative
> > consequences from it.
>
> So, the "negative consequences" are that people can't make proprietary
> editions of some software. When that's a deliberate choice in the
> design of a licence, there's no pretending that the consequences
> aren't there, just that they aren't perceived by everyone to be
> negative.

I gave an example earlier of svglib and rst2pdf.  Negative
consequences.  Nothing proprietary involved.

> > I somehow knew that is how you would read my posts, but no. ?It's
> > people like you putting words in my month that is objectionable.
>
> Well, you effectively said that you didn't like being asked to "share
> alike", which is what the GPL achieves.

I give away lots of software.  Free to all comers.  Come and get some.

> so why should I not assume
> that you generally object to other, more obviously labelled licences
> like the CC-*-SA licences which make it clear what is expected of that
> hapless recipient of a work who doesn't bother reading the licence?

Your assumptions are so far away from reality that there is really no
good reason why you shouldn't assume that I'm a 10 foot tall purple
monster.

> > Sorry, that is absolutely no different than what I originally said
> > when I was first defending Aahz's use of the word "force" to Ben
> > Finney back on the 7th:
>
> > "Perhaps you feel "forces" is too loaded of a word. ?There is no
> > question, however, that a copyright license can require that if you do
> > "X" with some code, you must also do "Y". ?There is also no question
> > that the GPL uses this capability in copyright law to require anybody
> > who distributes a derivative work to provide the source. ?Thus,
> > "forced to contribute back any changes" is definitely what happens
> > once the decision is made to distribute said changes in object form."
>
> > Both your "make" and my "force" mean "to compel." ?We've come full
> > circle. ?The English language makes no real distinction between
> > "making everyone commit" and "forcing everyone [to] commit".
>
> Yes, but you have to choose to do something ("X") to start with. Which
> is actually what you wrote later in that exchange:
>
> "Again, the force is applied once you choose to do a particular thing
> with the software -- is is really that hard to understand that
> concept?"

I didn't just write that later.  I wrote it in my very first post,
which you just quoted a few lines up, apparently without even
bothering to read it closely.  I agree with that.  But you only
grudgingly agree with that, if at all, and when you do you make it
look like I'm the one trying desperately not to agree with it, because
in order to agree with it, you have to agree that, in the limited
context that I used the word "force", it is accurate, and you really
don't want to do that.

> But you're virtually claiming that people stumble into a situation
> where they have to do something they don't like or didn't anticipate,
> when in fact they've actually entered into an agreement.

Some people (end users of Ubuntu) do stumble into a situation.  Some
people see and decide not to enter into an agreement and attempt to
warn others that there may be consequences -- that if they enter into
the agreement they will be "forced" to live with those consequences.
This latter group of people always winds up arguing with those who
think the GPL is always good and none of the consequences are ever
negative, and forced is a loaded word.

> > My problem, exactly, is that bothering Mepis, yet not bothering Joe
> > Blow when he gives a copy to his friend, is exactly the kind of
> > selective enforcement of copyright rights that Microsoft is accused of
> > when they turn a blind eye to piracy in third-world countries.
>
> Nonsense. If anything, it's a matter of priorities, and completely
> absurd to claim that the FSF and all the other copyright holders for
> GPL-licensed software on Ubuntu installation media are all conspiring
> together to "seed" the planet with "unlicensed wares" in order to reap
> some kind of monetary reward afterwards, which is what Microsoft has
> been accused of.

So, the FSF, which so carefully provides the most legalese-ish license
on the planet, which was in development for god-knows-how-long, which
maintains a carefully parsed FAQ of what you can and can't do, which
engages in all sorts of advocacy, can't find the time to explain to
Ubuntu that they really ought to explain how the licensing works on
their download page?  What have you been smoking and where can I get
some?

> > Despite your opinion, there is nothing legally or morally wrong with
> > me using GPL software (and not redistributing it) just because I
>
> I never said there was. I said that if you don't like the licence,
> don't incorporate works which use it into your own projects.

No, you said "If you don't like them, don't use GPL-licensed
software."

> But don't
> say that it's not fair that people are releasing stuff under terms you
> don't like, or say that they're being "pathetic" or petty or
> ridiculous by doing so, or are imposing their agenda on you.

The only time I mentioned pathetic and petty were for really small
libraries, which probably wouldn't merit copyright protection in any
case.

>
> More name-calling and finger-pointing. Great stuff, there. Anything
> else?

Yes, just that you keep selectively quoting both of us, and twisting
what we both said to meet your agenda.  But I'm done.  I think there
are enough pointers to original material here for others to go and do
whatever level of research they deem appropriate for their own
situations.

Regards,
Pat


From ldo at geek-central.gen.new_zealand  Wed May 12 20:29:08 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Thu, 13 May 2010 12:29:08 +1200
Subject: Is Python a functional programming language?
References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com>
	
	
	
Message-ID: 

In message , Nobody wrote:

> On Tue, 11 May 2010 23:13:10 +1200, Lawrence D'Oliveiro wrote:
> 
>>> But the beauty is that Python is multi-paradigm ...
>> 
>> The trouble with ?multi-paradigm? is that it offends the zealots on
>> all sides.
> 
> Is that how you view people who like languages to exhibit a degree of
> consistency?

Interesting, I never knew ?consistency? was a synonym for ?faith?...

> Some people would prefer to have a manageable set of rules
> rather than having to remember the results of all of the possible
> combinations of interactions between language features.

What are you accusing Python of, exactly?


From alan.isaac at gmail.com  Wed May 12 21:51:23 2010
From: alan.isaac at gmail.com (Alan G Isaac)
Date: Wed, 12 May 2010 21:51:23 -0400
Subject: documentation bug? (format spec mini language)
In-Reply-To: 
References: 	<4BE9ADD9.9030901@mrabarnett.plus.com>
	
Message-ID: <1Yidnfk7UJi8xnbWnZ2dnUVZ_h6dnZ2d@rcn.net>

On 5/11/2010 5:05 PM, Terry Reedy wrote:  
> http://bugs.python.org/issue8691

Thanks!

Alan




From Jess-198700987 at hotmail.com  Wed May 12 22:23:34 2010
From: Jess-198700987 at hotmail.com (Jess)
Date: Thu, 13 May 2010 10:23:34 +0800
Subject: How to test whether bit is set within a flag with Python ?
References: 
	
Message-ID: 

Cheap Chanel Watches for sale at: http://www.luxuryowner.net/

Chanel Watches collection: 
http://www.luxuryowner.net/replica-chanel-watches.html

Chanel J12 Automatic Watches: 
http://www.luxuryowner.net/Chanel-J12-Automatic-Watches.html

Chanel J12 Quartz Watches: 
http://www.luxuryowner.net/Chanel-J12-Quartz-Watches.html


"MRAB"  
??????:mailman.117.1273689672.32709.python-list at python.org...
> robert somerville wrote:
>> I am trying to determine how to test whether variors bits are set within 
>> a byte (or larger flag) , the python 'and' and 'or' do not seem to be 
>> doing what i want .. does anybody have some sample code showing how to do 
>> it ??
>>
>> e.g. (in "C")
>>
>> unsigned char a = 6;
>>
>> is 3rd bit set ??
>>
>> a & 4 =,  true in this case ....
>>
> 'and', 'or' and 'not' are Boolean.
>
> Python borrows its bitwise operators from C:
>
>     &     bitwise and
>     |     bitwise or
>     ^     bitwise xor
>     ~     bitwise not (ones' complement)
>     <<    shift left
>     >>    shift right
>
> You also need to remember that Python's integers are of (virtually)
> unlimited length. 




From Jess-198700987 at hotmail.com  Wed May 12 22:24:12 2010
From: Jess-198700987 at hotmail.com (Jess)
Date: Thu, 13 May 2010 10:24:12 +0800
Subject: Do any debuggers support "edit and continue?"
References: 
Message-ID: 

Cheap Chanel Watches for sale at: http://www.luxuryowner.net/

Chanel Watches collection: 
http://www.luxuryowner.net/replica-chanel-watches.html

Chanel J12 Automatic Watches: 
http://www.luxuryowner.net/Chanel-J12-Automatic-Watches.html

Chanel J12 Quartz Watches: 
http://www.luxuryowner.net/Chanel-J12-Quartz-Watches.html


"Joel Koltner"  
??????:cMBGn.281180$Up1.207371 at en-nntp-09.dc1.easynews.com...
> Just curious... in Microsoft's Visual Studio (and I would presume some 
> other tools), for many languages (both interpreted and compiled!) there's 
> an "edit and conitnue" option that, when you hit a breakpoint, allows you 
> to modify a line of code before it's actually executed.
>
> Does any Python debugger support this feature?  Being an interpreted 
> language it doesn't seem like it would necessarily be too onerous to 
> support?  It'd be quite handy in that, especially if you hit a breakpoint 
> due to the interpreter throwing an error, you could fix just the line in 
> question and keep going, rather than having to stop the entire program, 
> fix the line, and then run again and potentially kill a bunch of time 
> getting the program back into the same "state."
>
> Thanks,
> ---Joel Koltner
> 




From googler.1.webmaster at spamgourmet.com  Wed May 12 22:33:42 2010
From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3)
Date: Wed, 12 May 2010 19:33:42 -0700 (PDT)
Subject: buffer objects (C-API)
Message-ID: 

Hi at all,

is it possible that a buffer object deallocates the memory when the
object is destroyed? I want to wrap the buffer object around some
memory. Or is there any chance that the buffer object copies the
memory so it will be responsible when it will be destroyed?

Thanks in advance, bye.

moerchendiser2k3


From tjreedy at udel.edu  Wed May 12 23:04:41 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Wed, 12 May 2010 23:04:41 -0400
Subject: open(False) in python3
In-Reply-To: <20100512230714.GA8407@chopin.edu.pl>
References: 			
	<20100512230714.GA8407@chopin.edu.pl>
Message-ID: 

On 5/12/2010 7:07 PM, Jan Kaliszewski wrote:
> Terry Reedy dixit (2010-05-12, 14:26):
>
>> On 5/12/2010 1:26 PM, Giampaolo Rodol? wrote:
>>> 2010/5/12 Gabriel Genellina:
>>>> open() in Python 3 does a lot of things; it's like a mix of codecs.open() +
>>>> builtin open() + os.fdopen() from 2.x all merged together. It does different
>>>> things depending on the type and quantity of its arguments, and even returns
>>>> objects of different types.
>>
>> The change actually happened, according to 'What's new', in 2.6 when
>> 'open' was made a synonym for the new io.open.
>
> It did happened in 3.0, not in 2.6.

I do not have 2.6 loaded to test and was judging from

What's New in Python 3.0 has a section

Changes Already Present In Python 2.6 which has an entry

"PEP 3116: New I/O Library. The io module is now the standard way of 
doing file I/O, and the initial values of sys.stdin, sys.stdout and 
sys.stderr are now instances of io.TextIOBase. The builtin open() 
function is now an alias for io.open() "

The 2.6.5 doc says
"io.open(file[, mode[, buffering[, encoding[, errors[, newline[, 
closefd=True]]]]]])?

     Open file and return a stream. If the file cannot be opened, an 
IOError is raised.

     file is either a string giving the name (and the path if the file 
isn?t in the current working directory) of the file to be opened or a 
file descriptor of the file to be opened. "

If you are right, then "The builtin open() function is now an alias for 
io.open() " is misleading and does not apply to 2.6 even though it 
appears in an entry on things backported to 2.6. I do not really care.

tjr









From pavlovevidence at gmail.com  Wed May 12 23:26:59 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Wed, 12 May 2010 20:26:59 -0700 (PDT)
Subject: buffer objects (C-API)
References: 
Message-ID: <5eebecfb-b76f-4101-b9de-02574f49f3fc@r11g2000yqa.googlegroups.com>

On May 12, 7:33?pm, moerchendiser2k3  wrote:
> Hi at all,
>
> is it possible that a buffer object deallocates the memory when the
> object is destroyed? I want to wrap the buffer object around some
> memory. Or is there any chance that the buffer object copies the
> memory so it will be responsible when it will be destroyed?


Objects that support the buffer protocol will only deallocate their
memory if they're programmed to.

If you're writing your own buffer type you can be assured the memory
won't be deallocated unless you do it yourself.

If you're referring to the Python 2.x "buffer" object, no it won't
deallocate the memory.  You should also be aware that it's deprecated
in 2.x and removed in 3.x.

Generally speaking, objects that allocate their own memory should also
deallocate it; objects that are passed pointers to existing memory
should leave it alone.  Most built-in types in Python that support
buffer protocol do allocate their own memory, so they also deallocate
it.  "buffer" doesn't, so it doesn't.

One other thing to consider is numpy, especially if your buffer is
numeric.  It might even have the operations you need already.
numpy.ndarray can allocate its own memory or accept a pointer (or
other buffer object), and will only delete the buffer if it allocated
it itself.


Carl Banks


From steven at REMOVE.THIS.cybersource.com.au  Wed May 12 23:29:00 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 13 May 2010 03:29:00 GMT
Subject: Limitation of os.walk
References: 
	
	
Message-ID: 

On Wed, 12 May 2010 19:04:47 +0000, kj wrote:

> In  Terry Reedy
>  writes:
> 
>>On 5/11/2010 3:49 PM, kj wrote:
>>> PS: I never understood why os.walk does not support hooks for key
>>> events during such a tree traversal.
> 
>>Either 1) it is intentionally simple, with the expectation that people
>>would write there own code for more complicated uses or 2) no one has
>>submitted a 'full-featured' version or 3) both.
> 
> I hope it's not (1): I want the language I use to include more
> "batteries" not fewer.

How many more? Ten? Twenty? A hundred? Ten thousand? Ten million? Where 
do you draw the line?

Every extra battery is (say) a hundred extra lines of code, which means 
fifty thousand more potential bugs. It means more burden on the 
maintainers, and more burden on people learning the language. More 
batteries can make it more, not less, difficult to code:

# Python 1.1
"I need a collection of values, should I use a list, a tuple or a dict?"

vs

# Python 5000:
"I need a collection of values, should I use a list, a tuple, a dict, an 
array, a bag, a SortedBag, a table, a SortedTable, a NamedTuple, a 
Record, a stack, a queue, a deque, a linked list, a HashTable, a doubly-
linked list, a set, a frozenset, a skip list, a jump list, a binary tree, 
a  B tree, a B+ tree, a SortedList, a red-black tree, an A* tree, a B* 
tree, a SortedList, a StringList, a CaseInsensitiveSortedStringList, a 
CaseInsensitiveRedBlackTree, a HashSet, a CaseInsensitiveHashSet, an 
ArrayList, a ConcurrentQueue, a ConcurrentStack, a KeyedCollection, an 
EnumerableBag, a MultiSet, a StringMultiSet, a SortedSet, a 
DoubleEndedQueue, a Buffer, a CircularQueue, a heap, a binary search 
tree, an AssociatedArray, a Vector, a SparseArray, an XOR-linked list, a 
weight-balanced tree, a RandomizedBinarySearchTree, a ThreadedBinaryTree, 
an AVL tree, a splay tree, a rope, a binomial heap, a fibonacci heap, a 
trie, a B-trie, a judy array, an and/or tree, an enfilade, a treap, a 
dancing tree, a queap, or a fusion tree?" (Whew!)


There's nothing wrong with the existence of all these data structures. If 
you need one, you can use it. But they don't all need to be included in 
the standard library. That just increases the cognitive load on 
programmers without really adding that much benefit. I've seen people 
stress over the choice of a tuple or a list.



> It seems that a similar "simplicity argument" was invoked to
> strip the cmp option from sort in Python 3.  Grrrr.  Simplicity is
> great, but when the drive for it starts causing useful functionality to
> be thrown out, then it is going too far.  Yes, I know that it is
> possible to do everything that sort's cmp option does through clever
> tricks with key, 

Not that clever. In general, key-based sorting is simpler than cmp-based 
sorting. In addition, the use of a key function is a basic technique 
which every coder should have in their mental toolbox, and it is 
applicable to more than just sorting. E.g. max() and min() also support 
key functions in Python 2.6 and better. On the other hand a cmp function 
is specific to sorting, and nothing but sorting.



> but grokking and coding this maneuver requires a *lot*
> more Python-fu than cmp did, which makes this functionality a lot less
> accessible to beginners that the intrinsic complexity of the problem
> warrants.

I disagree that key-based sorting requires any more Python-fu than cmp 
sorting. I believe they're equivalent. There are cmp functions you can 
write which aren't (easily?) convertible to key, but most of them (all?) 
aren't useful or sensible. E.g. they rely on side-effects, don't define a 
sensible sort order, or break stability of sorting:

>>> text = "here is a number of words in some order".split()
>>>
>>> sorted(text, cmp=lambda a,b: cmp(a.upper(), b.lower()))
['order', 'some', 'in', 'words', 'of', 'number', 'a', 'is', 'here']
>>>
>>> sorted(text[2:] + text[:2], cmp=lambda a,b: cmp(a.upper(), b.lower()))
['is', 'here', 'order', 'some', 'in', 'words', 'of', 'number', 'a']


Key-based sorting doesn't let you do this, but since I can't think of any 
application where you want the sort order to be dependent on the initial 
order, I believe this is a good thing. It is much harder to write buggy 
sorts using key than with cmp.



> And for what?  To get rid of an *option* that could be easily
> disregarded by anyone who found it too "complex"? It makes no sense to
> me.


It's not that cmp is too complex, but that it's mere existence adds 
complexity to the list data type, it is usually slow and inefficient, and 
it can introduce subtle sorting bugs.


In the past, I've suggested that if people really believe that there is a 
use-case for sorting with a comparison function, they should fork it from 
the built-in list object and release it on PyPI as a third-party package. 
I still believe this.



-- 
Steven


From tjreedy at udel.edu  Wed May 12 23:29:11 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Wed, 12 May 2010 23:29:11 -0400
Subject: Limitation of os.walk
In-Reply-To: 
References: 
		
	
Message-ID: 

On 5/12/2010 2:52 PM, kj wrote:
> In  Tim Chase writes:
>>   05/11/2010 09:07 PM, Terry Reedy wrote:
>>> If os.walk were rewritten, it should be as an iterator (generator).
>>> Directory entry and exit functions could still be added as params.
>
>> It *is* an iterator/generator.  However, I suspect you mean that
>> it should slurp the dirs/files iteratively instead of using
>> listdir() as was discussed on c.l.p a few months back.

Yes, I was thinking of that thread.
>
> Thanks for mentioning this thread.  Very interesting stuff.  Apropos
> the implementability of an iterative listdir, I wonder if some
> variation of glob.iglob() would fit the bill.  (Maybe it's too
> slow, though.)
>
>> I suspect if I thought about it much longer, only one would
>> really be needed, the other accommodated by the "topdown" parameter.
>
> Yeah, I think one only needs a post hook.  The fact that it's a
> generator obviates need for a pre hook, since the yield returns
> control to the calling function right around where the pre-hook
> would run anyway.  For the same reason, the post hook is needed
> only for the case topdown=True.

Once you have determined and tested the minimal needed change for 
greater functionality, you could either
a) post a suggestion and the revised os.walk to python-ideas
b) submit a feature request to the tracker and attach the revised 
function and, if possible, a diff patch
c) both.

I have no idea of the response.

Terry Jan Reedy



From ldo at geek-central.gen.new_zealand  Wed May 12 23:48:24 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Thu, 13 May 2010 15:48:24 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> ... but to claim that putting more restrictions on someone give them more
> freedom is pure Orwellian double speak.

What about the freedom to take away other people?s freedom? What tuple of 
speak would that be?


From timr at probo.com  Thu May 13 00:04:25 2010
From: timr at probo.com (Tim Roberts)
Date: Wed, 12 May 2010 21:04:25 -0700
Subject: win32com sql update problem
References: 
Message-ID: <18umu5dpt177lnr8t9hsfu3jd47mddnk9l@4ax.com>

Mark Carter  wrote:
>
>Consider the following snippet of code:
>
>import win32com.client
>
>DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=M:\\Finance\\camel\
>\camel.mdb;'
>conn.Open(DSN)
>cursor = conn.Execute("UPDATE tblInvoice SET InvComments='Python'
>WHERE InvBillingPeriod = 'April 2010' AND InvJobCode = '2169'")
>rows = cursor.Affected_Rows()
>print rows
>conn.Close()
>
>I am using Python 2.6.5, and pywin32. If I try to run it, I get the
>response:
>Traceback (most recent call last):
>  File "C:/Users/mcarter/tacc/pypms/post.py", line 79, in 
>    AdjustPms(d)
>  File "C:/Users/mcarter/tacc/pypms/post.py", line 64, in AdjustPms
>    cursor = conn.Execute("UPDATE tblInvoice SET InvComments='Python'
>WHERE InvBillingPeriod = 'April 2010' AND InvJobCode = '2169'")

Well, that's not the EXACT code, because that's clearly not line 64 in the
script above.  Do you actually have the file path hardcoded, as in your
example?  Or are you building it up from strings?

Does the net share exist at the time you run this?

You might print conn.ConnectionString just before the Execute.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.


From aahz at pythoncraft.com  Thu May 13 00:35:54 2010
From: aahz at pythoncraft.com (Aahz)
Date: 12 May 2010 21:35:54 -0700
Subject: Use of cmp() (was Re: Limitation of os.walk)
References: 
	
	
	
Message-ID: 

[nitpicking one specific point]

In article ,
Steven D'Aprano   wrote:
>
>On the other hand a cmp function is specific to sorting, and nothing
>but sorting.

Not quite.  cmp() is useful any time you have an expensive comparison
operation and you need to take three different codepaths depending on
the comparison result.  I don't know what the current code does, but I
used it in the first cut Decimal() class.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From pmaupin at gmail.com  Thu May 13 01:16:29 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Wed, 12 May 2010 22:16:29 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: <155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>

On May 12, 10:48?pm, Lawrence D'Oliveiro  wrote:
> In message , Ed Keith
> wrote:
>
> > ... but to claim that putting more restrictions on someone give them more
> > freedom is pure Orwellian double speak.
>
> What about the freedom to take away other people?s freedom?

The freedom to take away other people's freedom is a very serious
power that should only be used sparingly.

> What tuple of speak would that be?

Well, if my friend has a slow internet connection, so I give him a
Linux CD which lets him get out of Windows hell (me taking advantage
of RMS's "freedom 2", and my friend taking advantage of RMS's "freedom
0"), and I don't give my friend all the source code (or a written
offer) because, frankly, he wouldn't know what to do with the source
anyway, and it doesn't fit on the CD, and I didn't even bother
downloading the source, at that point I would apparently be in
violation of the GPL license on hundreds of programs, because I would
be violating what the FSF calls "freedom 1".  Or more pedantically, I
would be in violation of section 6 of the GPL v3 license for those
programs on the CD licensed under v3, and in violation of section 3 of
the GPL v2 for those programs on the CD licensed under v2.  In the
case of GPL v3, for example, Ubuntu lets me download code under 6d, so
if I download it and burn it, I would have to use 6a or 6b; if I had
actually received a CD from Ubuntu, I might be able to use 6c, but not
if I downloaded it.

Now I know none of us would ever violate the license like this, but
if, hypothetically speaking, I had made such a CD for my friend, and
then someone came along and explained to me that, by helping wean my
friend from MS Windows in this fashion, I had taken away his freedom
(specifically RMS's "freedom 1"), I would probably conclude that the
person making this accusation was a moron, and that his words were so
meaningless that the only tuple that could possibly represent them was
the empty tuple.

Regards,
Pat


From joax.spec at gmail.com  Thu May 13 02:34:30 2010
From: joax.spec at gmail.com (Joax Spec)
Date: Thu, 13 May 2010 01:34:30 -0500
Subject: Fwd: fails to call python from jython for types, functools, csv 
	modules
In-Reply-To: 
References: 
Message-ID: 

Hello I'm very new to python/jython, and trying yo *call a program from
jython*, which works very good in python.
I got some issues which resolve as I expose here, but I think these are
unsatisfactory solutions.
If you want to reply please do it to my address.

thanks,
Jx

PD. both are great projects!!!

1. FIRST Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 1, in 
  File "C:\Python26\lib\re.py", line 283, in 
    import copy_reg
  File "C:\Python26\lib\copy_reg.py", line 7, in 
    from types import ClassType as _ClassType
  File "C:\Python26\lib\types.py", line 36, in 
    BufferType = buffer
NameError: name 'buffer' is not defined

*Solution --> comment in types.py   #BufferType = buffer (line 37)*

2. SECOND Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 3, in 
  File "C:\Python26\lib\csv.py", line 7, in 
    from functools import reduce
  File "C:\Python26\lib\functools.py", line 10, in 
    from _functools import partial, reduce
ImportError: cannot import name reduce

*Solution --> comment in functools.py   #, reduce (line 10)
Problem --> IDLE for windows doesn't work anymore, I mean I can lauch the
GUI, but I can still use python from command line*

3. THIRD Error

Error !Traceback (most recent call last):
  File "", line 1, in 
  File "__pyclasspath__/parserJoax.py", line 3, in 
  File "C:\Python26\lib\csv.py", line 7, in 
    from functools import reduce
ImportError: cannot import name reduce

*Solution --> comment in csv.py  #@fieldnames.setter (line 96)*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steven at REMOVE.THIS.cybersource.com.au  Thu May 13 03:58:34 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 13 May 2010 07:58:34 GMT
Subject: Picking a license
References: 
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
Message-ID: 

On Wed, 12 May 2010 22:16:29 -0700, Patrick Maupin wrote:

> On May 12, 10:48?pm, Lawrence D'Oliveiro  central.gen.new_zealand> wrote:
>> In message , Ed
>> Keith wrote:
>>
>> > ... but to claim that putting more restrictions on someone give them
>> > more freedom is pure Orwellian double speak.
>>
>> What about the freedom to take away other people?s freedom?
> 
> The freedom to take away other people's freedom is a very serious power
> that should only be used sparingly.
> 
>> What tuple of speak would that be?
> 
> Well, if my friend has a slow internet connection, so I give him a Linux
> CD which lets him get out of Windows hell (me taking advantage of RMS's
> "freedom 2", and my friend taking advantage of RMS's "freedom 0"), and I
> don't give my friend all the source code (or a written offer) because,
> frankly, he wouldn't know what to do with the source anyway, and it
> doesn't fit on the CD, and I didn't even bother downloading the source,
> at that point I would apparently be in violation of the GPL license on
> hundreds of programs, because I would be violating what the FSF calls
> "freedom 1". 

If you used an existing Linux distribution, then the offer to provide 
source code will already be there.

If you compiled the CD yourself, and failed to provide a written offer on 
the CD, then yes absolutely you would be in violation of the licence 
terms, and shame on you.

The GPL doesn't require you to force source code on those who don't want 
it, but it does require you to make it available if they ask, and for you 
to notify them appropriately of this fact. You don't even have to 
explicitly tell your friend he can have the source code. You just have to 
make sure that the written offer is available on the disk you give him.


> Now I know none of us would ever violate the license like this, but if,
> hypothetically speaking, I had made such a CD for my friend, and then
> someone came along and explained to me that, by helping wean my friend
> from MS Windows in this fashion, I had taken away his freedom
> (specifically RMS's "freedom 1"), I would probably conclude that the
> person making this accusation was a moron


Well, yes, you probably would draw that conclusion. Doesn't mean that you 
are right to do so, because quite frankly you would have taken away your 
friend's freedom (albeit in a very small fashion). Access to the source 
code is a freedom that the GPLed software on the disk *explicitly* grants 
to your friend, and by failing to pass the offer on, you have taken away 
that freedom in a very real sense.

We are talking about a small technical violation of the licence terms 
here, but imagine if everyone did it, if Red Hat and Debian and Ubuntu 
etc didn't bother passing on the source code (or a written offer). Only a 
tiny proportion of people would discover by their own efforts that the 
source code was available, and only a proportion of them would learn 
where it was available from. The result in practical terms would be a 
major decrease in the number of people granted the freedom to modify the 
source code, and a correspondingly larger decrease in the number of 
people both free and able to modify the source code.

It's not enough to be granted freedom to modify source code in theory, if 
you know about it, if you can find some hard-to-locate website which may 
or may not be running. The practicalities are equally important. In 
theoretical terms, everyone has the freedom to legally modify and 
distribute the source code to Microsoft Windows. All you have to do is 
buy 51% of the stock so as to become majority shareholder, then make 
sufficient changes to the board of directors so that the new board grants 
you a licence to do so, then fight off the lawsuits from the rest of the 
shareholders. Anyone could do it! Not.

Another, more practical example: here in Australia our government is hell-
bent on introducing an ineffective and expensive Internet censorship 
scheme. It seems that under Australian law, it will be completely legal 
to circumvent the filter, but our government is investigating ways to 
make it illegal to tell anyone how to circumvent it. In other words, 
Australians will have permission to circumvent the nanny filter, but 
since few people will know this, or know how to do so, it will be a 
meaningless freedom.

The GPL concerns itself with the *practical* freedom to gain access to 
source code, not merely the theoretical freedom represented by permission 
without opportunity. Failure to pass on the offer to provide source code 
impacts that freedom in a very real sense.

If you can't understand this, you have the freedom to think I'm a moron, 
and I have the freedom to be sure you are one too *wink*



-- 
Steven


From pavlovevidence at gmail.com  Thu May 13 04:10:09 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Thu, 13 May 2010 01:10:09 -0700 (PDT)
Subject: Queue.Queue() AttributeError exception
References: <201005101040516097598@ucweb.com>
	
Message-ID: 

On May 12, 11:50?pm, Dennis Lee Bieber  wrote:
> On Mon, 10 May 2010 10:40:51 +0800, "??????" 
> declaimed the following in gmane.comp.python.general:
>
> > I have a multi-thread program work with Queue.Queue(), sometimes put request to the work queue, but throw an exception as below traceback information, it will always throw the exception until restart program, cound please have any experience, your help will be greatly appreciated!
>
> > ? File "/usr/local/lib/python2.4/Queue.py", line 71, in put
> > ? ? self.not_full.acquire()
> > AttributeError: '_Condition' object has no attribute 'acquire'
>
> ? ? ? ? Off hand -- I'd wonder if somewhere in the code there may be a
> faulty/erroneous rebinding of the "not_full" attribute...

My impression too, that or _Condition.


Carl Banks


From motoom at xs4all.nl  Thu May 13 07:31:21 2010
From: motoom at xs4all.nl (Michiel Overtoom)
Date: Thu, 13 May 2010 13:31:21 +0200
Subject: Do any debuggers support "edit and continue?"
In-Reply-To: 
References: 	<4beb15c5$0$1634$742ec2ed@news.sonic.net>
	
Message-ID: <4BEBE309.7090503@xs4all.nl>

On 2010-05-13 00:07, Joel Koltner wrote:

> Hey, a lot of people would argue that Python's lack of strong typing and
> data/member protection (from one class to another) encourages sloppy
> programming too.  :-)

You're being ironic, aren't you?

Python does have strong typing (many people confuse that with static 
typing), see http://www.artima.com/weblogs/viewpost.jsp?thread=7590

And for data member protection, there is the 'consenting adult' rule. 
Touch instance variables which start with an underscore on your own risk.

Greetings,

-- 
"Open-source projects are run by people who are self-selected to actually
care about the software, as opposed to resentful wage slaves for
whom control over their work product is minimal and development is
just another stretch of cubicle time." - ESR, http://esr.ibiblio.org


From ldo at geek-central.gen.new_zealand  Thu May 13 08:25:41 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:25:41 +1200
Subject: Picking a license
References: 
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
Message-ID: 

In message
<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5 at g21g2000yqk.googlegroups.com>, Patrick 
Maupin wrote:

> On May 12, 10:48 pm, Lawrence D'Oliveiro
>  wrote:
>
>> In message , Ed
>> Keith wrote:
>>
>> > ... but to claim that putting more restrictions on someone give them
>> > more freedom is pure Orwellian double speak.
>>
>> What about the freedom to take away other people?s freedom?
> 
> The freedom to take away other people's freedom is a very serious
> power that should only be used sparingly.

Given that the GPL restricts that power, then it must be all right.


From ldo at geek-central.gen.new_zealand  Thu May 13 08:30:50 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:30:50 +1200
Subject: PEP 3119 ABC - And how I learned to love the Abstract Bomb
References: 
Message-ID: 

In message , Hatem 
Nassrat wrote:

> 1. To create a YajlContentHandler class that forces all sub-classers
> to implement a certain set of methods. (Great, thats what ABC is for)
> 
> 2. Conditional Abstractness! if certain methods are not implemented
> then be able to require some method to be implemented.

You?re looking at it wrong. If you want to force people to do things in a 
certain way, use Java. Python is about enabling things, not forcing them.

Don?t use subclassing. Instead, let the caller pass you a duck-typed object 
that implements the methods you need.


From ldo at geek-central.gen.new_zealand  Thu May 13 08:35:01 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:35:01 +1200
Subject: Django as exemplary design
References: <2010050312243328275-tomfsessile@gmailcom>
	
	<2010050415342385304-tomfsessile@gmailcom>
	<746e8b47-bb35-47a1-9832-2babe0fec044@o8g2000yqo.googlegroups.com>
	<1273191529.196773.7.camel@paska>
	
Message-ID: 

In message , MRAB 
wrote:

> Albert Hopkins wrote:
>
>> On Thu, 2010-05-06 at 16:38 -0700, Patrick Maupin wrote:
>>
>>> I don't know how this applies to reading other peoples' code, but
>>> recent research shows we learn more from success than failure
>> 
>> That's good to learn, because for years I have been intentionally
>> failing in order to learn from it and become successful, and it hasn't
>> really worked out for me :|
>> 
> Failure just teaches you what you shouldn't do, not what you should...

But there are more different ways to fail than to succeed, therefore more to 
learn.


From ldo at geek-central.gen.new_zealand  Thu May 13 08:37:33 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:37:33 +1200
Subject: Django as exemplary design
References: <2010050312243328275-tomfsessile@gmailcom>
	
	<2010050619481239450-tomfsessile@gmailcom>
	
Message-ID: 

In message , Aahz wrote:

> My suspicion is that very very few medium/large systems are truly
> "well-designed".

Conway?s law applies: the product of any human endeavour reflects the 
organizational structure that produced it. If the individuals/groups writing 
the different parts of the software were in regular communication, and 
working towards a common goal rather than at odds with each other, that will 
be reflected in the way their contributions interact.


From ldo at geek-central.gen.new_zealand  Thu May 13 08:38:17 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:38:17 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> If, on the other hand you are releasing a library, to be incorporated into
> other products, If you release it under the GPL I will not take the time
> to learn it. I do not want to have to think about what took I can legally
> use for what job. Libraries with permissive licenses can be used in any
> project. Many contracts prohibit the use of GPL or LGPL code. So I do not
> waist my time learning to use libraries covered by restrictive licenses.
> So if you want me to even consider using your library do not use GPL, or
> LGPL.

What have you got against LGPL for this purpose?


From ldo at geek-central.gen.new_zealand  Thu May 13 08:41:19 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:41:19 +1200
Subject: Broken pipe
References: 
	
Message-ID: 

In message , Chris 
Rebert wrote:

> Also, please don't use semicolons in your code. It's bad style.

Wonder why they?re allowed, then.


From faltet at gmail.com  Thu May 13 08:48:38 2010
From: faltet at gmail.com (Francesc)
Date: Thu, 13 May 2010 05:48:38 -0700 (PDT)
Subject: Invoking setup.py in sub-packages
Message-ID: <6332d1a6-8f78-485b-a6cf-a9613d6be25d@b18g2000yqb.googlegroups.com>

Hi,

I'd like to setup a package that is make of other sub-packages,
modules and other extensions.  What I have is something like (this is
very simplified indeed):

/
    __init__.py
    setup.py
    foo1/
        __init__.py
        foo1.c
        [...]
    foo2/
        setup.py
        __init__.py
        foo2.c
        [...]

Now, I'd like to make a setup.py for package 'foo' that is able to
compile the 'foo1' extension directly, but invoke 'foo2/setup.py' in
order to generate the 'foo2' sub-package (which contains an extension
itself).

I'm currently trying:

setup(name = "foo",
      ...
      ext_modules = [ Extension( "foo.foo1", sources=["foo1.c"] ) ],
      packages = ["foo.foo1", "foo.foo2"],
      ...
      )

Of course, the foo2 package is not made at all.  Is there a way to get
the 'foo2/setup.py' invoked automagically and generate the desired
extensions?  Or all the instructions to generate the extension in
sub-packages have to be hard-wired in main 'foo/setup.py'?

Thanks!


From ldo at geek-central.gen.new_zealand  Thu May 13 08:50:44 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 00:50:44 +1200
Subject: Is there a better way to set a system clock in Python (on a Linux
	system)
References: 
Message-ID: 

In message , J wrote:

> Like I said, it works well, I just wonder if there is a cleaner way of
> setting the local clock to a different time in python without having
> to do all this.

How about one line in Bash:

    date -s $(date --rfc-3339=date -d "+1 hour")



From e_d_k at yahoo.com  Thu May 13 09:04:37 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 06:04:37 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <855698.98996.qm@web58704.mail.re1.yahoo.com>

--- On Wed, 5/12/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Wednesday, May 12, 2010, 11:48 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > ... but to claim that putting more restrictions on
> someone give them more
> > freedom is pure Orwellian double speak.
> 
> What about the freedom to take away other people?s
> freedom? What tuple of 
> speak would that be?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Assertion I:
   If person A is free to do more than person B, then person A has 
   more freedom then person B.

Assertion II:
   If person A is free do perform an action person B is not free to 
   perform then person A is free to do more than person B.

Assertion III:
  If person B is restricted in some way that person A is not them Person A 
  is free to do something Person B is not free to do.

Conclusion:
  If person B is more resticted than Peston A, Person A has mor freedom
  than person B.

Which step in this reasoning do you disagree with?

     -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From mrkafk at gmail.com  Thu May 13 09:14:09 2010
From: mrkafk at gmail.com (mk)
Date: Thu, 13 May 2010 15:14:09 +0200
Subject: Loading C extension from memory
Message-ID: 

Hello,

I wonder if there is a way to load C extension from in-memory object, 
not from the file on the disk?

I'm asking bc I would like to download C extensions over network and 
load them into Python interpreter (without storing the C extension in 
file on the disk).

I googled for this but there appear only methods of loading compiled 
Python (bytecode) modules.

Regards,
mk



From e_d_k at yahoo.com  Thu May 13 09:21:10 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 06:21:10 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <479178.94015.qm@web58705.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 8:25 AM
> In message
> <155f1683-9bfd-4a83-b63f-7fb0fc2f51c5 at g21g2000yqk.googlegroups.com>,
> Patrick 
> Maupin wrote:
> 
> > On May 12, 10:48 pm, Lawrence D'Oliveiro
> > 
> wrote:
> >
> >> In message ,
> Ed
> >> Keith wrote:
> >>
> >> > ... but to claim that putting more
> restrictions on someone give them
> >> > more freedom is pure Orwellian double speak.
> >>
> >> What about the freedom to take away other
> people?s freedom?
> > 
> > The freedom to take away other people's freedom is a
> very serious
> > power that should only be used sparingly.
> 
> Given that the GPL restricts that power, then it must be
> all right.
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

I do not think anyone is claiming it is not 'all right'. The claim is being made that it restricts freedom.

You are free to put any restrictions you want on your software. If you use the GPL on a library I will not use it because I need to make a living. I do not dispute your right to use the GPL. I just dispute your claim that you use it to give me 'more freedom'.

I do not know what your reason for using the GPL is, but most of the people I know who use it do so so that can charge a license fee to people who want to use the code with out the restrictions of the GPL. They do this so they can make a living, which is their right, and I do not hold it against them. If I ever develop a library I think people would be willing to pay to license, I'd to the same.

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Thu May 13 09:24:04 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 06:24:04 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <495778.64465.qm@web58702.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 8:38 AM
> In message ,
> Ed Keith 
> wrote:
> 
> > If, on the other hand you are releasing a library, to
> be incorporated into
> > other products, If you release it under the GPL I will
> not take the time
> > to learn it. I do not want to have to think about what
> took I can legally
> > use for what job. Libraries with permissive licenses
> can be used in any
> > project. Many contracts prohibit the use of GPL or
> LGPL code. So I do not
> > waist my time learning to use libraries covered by
> restrictive licenses.
> > So if you want me to even consider using your library
> do not use GPL, or
> > LGPL.
> 
> What have you got against LGPL for this purpose?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Most of my clients would not know how to relink a program if their life depended on it. And I do not want to put then in DLL hell. So I avoid the LGPL.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From jerome.delachienne at googlemail.com  Thu May 13 10:19:39 2010
From: jerome.delachienne at googlemail.com (jerome delachienne)
Date: Thu, 13 May 2010 07:19:39 -0700 (PDT)
Subject: jython and emacs on windows
Message-ID: <8b9b6ef9-4f7e-49a5-aaff-8d1edb181ba3@r11g2000yqa.googlegroups.com>

Hello,

i am trying to start a jython interpreter from emacs on windows from
several days and did not managed to do it.
I managed to start the jython interpreter from emacs on linux
I managed to start the python interpreter from emacs on windows.
with jython on windows i have the following problem: i can execute a
python script with the option -m but i can not interact with the
interpreter.
When i start from an eshell jython without the -i  option, nothing
happens as expected (like python)
When I start from an eshell the jython interpreter with -i option,  I
receive the "welcome" information and the prompt:
c:/Users/jerome $ jython -i
Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.6.0_20
Type "help", "copyright", "credits" or "license" for more information.
>>>
but then the interpreter does not react to any inputs
on the process explorer i can see that emacs has started a child
process cmd /c c:\jython2.5.1\jython.bat -i. this child process
started itself the jython interpreter which runs.but it seems that the
inputs are not passed from emacs to the jython interpreter.

has anyone an idea how i could solve this problem? Thanks for your
help !

jython 2.5.1
Jdk 1.6.0_20
emacs 22.3 and 21.3
windows xp and 7


From oxfordenergyservices at googlemail.com  Thu May 13 10:36:58 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 07:36:58 -0700 (PDT)
Subject: indexing lists/arrays question
Message-ID: 

this must be easy but its taken me a couple of hours already

i have

a=[2,3,3,4,5,6]

i want to know the indices where a==3 (ie 1 and 2)

then i want to reference these in a

ie what i would do in IDL is

b=where(a eq 3)
a1=a(b)

any ideas?

Thanks



From stefan_ml at behnel.de  Thu May 13 10:47:27 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Thu, 13 May 2010 16:47:27 +0200
Subject: indexing lists/arrays question
In-Reply-To: 
References: 
Message-ID: 

a, 13.05.2010 16:36:
> this must be easy but its taken me a couple of hours already
>
> i have
>
> a=[2,3,3,4,5,6]
>
> i want to know the indices where a==3 (ie 1 and 2)

   indices = [ i for i,item in enumerate(a) if item == 3 ]


> then i want to reference these in a

   print [ a[i] for i in indices ]

Stefan



From paul at boddie.org.uk  Thu May 13 10:53:10 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Thu, 13 May 2010 07:53:10 -0700 (PDT)
Subject: Picking a license
References: 
	<40daef8c-ca33-4840-ac14-37455347143e@a34g2000yqn.googlegroups.com>
	 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com> 
	<0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com> 
	<356d235e-63e3-4d36-bb7e-e436d9279f27@l28g2000yqd.googlegroups.com> 
	<845fc53a-5940-44fc-9189-a5a8ff56a95d@n15g2000yqf.googlegroups.com> 
	<5c1c0cce-f9f9-469b-ba3b-3eb9280c2bc9@g21g2000yqk.googlegroups.com>
Message-ID: <4f1c4723-a1c9-4b3d-aee3-d6475733066d@a34g2000yqn.googlegroups.com>

On 13 Mai, 01:36, Patrick Maupin  wrote:
>
> Once the court reaches that conclusion, it would only be a tiny step
> to find that the FSF's attempt to claim that clisp infringes the
> readline copyright to be a misuse of that same readline copyright.
> See, e.g. LaserComb v Reynolds, where the defendant (IMHO) acted much
> more egregiously than anybody who is delivering free software like
> clisp is acting, and nevertheless won on that issue.

In that very case you mention, LaserComb did not lose the copyright
protection on their work, were "free to bring an infringement suit
once it had cured the misuse" [1], and the clause which led to a
defence based on "copyright misuse" was one which forbade licensees
from making competing products.

Paul

[1] http://itlaw.wikia.com/wiki/Lasercomb_America_v._Reynolds#cite_ref-2


From matt at tplus1.com  Thu May 13 11:01:08 2010
From: matt at tplus1.com (Matthew Wilson)
Date: Thu, 13 May 2010 15:01:08 +0000 (UTC)
Subject: indexing lists/arrays question
References: 
Message-ID: 

On Thu 13 May 2010 10:36:58 AM EDT, a wrote:
> this must be easy but its taken me a couple of hours already
>
> i have
>
> a=[2,3,3,4,5,6]
>
> i want to know the indices where a==3 (ie 1 and 2)
>
> then i want to reference these in a
>
> ie what i would do in IDL is
>
> b=where(a eq 3)
> a1=a(b)


There's several solutions.  Here's one:

It is a recipe for madness to use a list of integers and then talk
about the position of those integers, so I renamed your list to use
strings.

    >>> a = ['two', 'three', 'three', 'four','five', 'six']

Now I'll use the enumerate function to iterate through each element and
get its position::

    >>> for position, element in enumerate(a):
    ...     print position, element
    ...
    0 two
    1 three
    2 three
    3 four
    4 five
    5 six

And now filter:

    >>> for position, element in enumerate(a):
    ...    if element == 'three':
    ...        print position, element

    1 three
    2 three

And now do something different besides printing:

    >>> b = []
    >>> for position, element in enumerate(a):
    ...     if element == 'three':
    ...         b.append(position)

And now we can rewrite the whole thing from scratch to use a list
comprehension:

    >>> [position for (position, element) in enumerate(a) if element == 'three']
    [1, 2]

HTH

Matt



From neilc at norwich.edu  Thu May 13 11:05:46 2010
From: neilc at norwich.edu (Neil Cerutti)
Date: 13 May 2010 15:05:46 GMT
Subject: indexing lists/arrays question
References: 
Message-ID: <852iqaFdj6U1@mid.individual.net>

On 2010-05-13, a  wrote:
> this must be easy but its taken me a couple of hours already
>
> i have
>
> a=[2,3,3,4,5,6]
>
> i want to know the indices where a==3 (ie 1 and 2)
>
> then i want to reference these in a
>
> ie what i would do in IDL is
>
> b=where(a eq 3)
> a1=a(b)
>
> any ideas?

For a sorted sequence the bisect module is a good start.

>>> start = bisect.bisect_left(a, 3)
>>> end = bisect.bisect_right(a, 3, bs)
>>> b = list(range(start, end))
>>> b
[1, 2]

If the list isn't necessarily sorted, try filter and enumerate.

>>> b = [a for a,b in filter(lambda x: x[1]==3, enumerate(a))]
>>> b
[1, 2]

-- 
Neil Cerutti
*** Your child was bitten by a Bat-Lizard. ***


From pmaupin at gmail.com  Thu May 13 11:06:52 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 08:06:52 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
Message-ID: <72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>

On May 13, 2:58?am, Steven D'Aprano
 wrote:
> On Wed, 12 May 2010 22:16:29 -0700, Patrick Maupin wrote:
> > On May 12, 10:48?pm, Lawrence D'Oliveiro  > central.gen.new_zealand> wrote:
> >> In message , Ed
> >> Keith wrote:
>
> >> > ... but to claim that putting more restrictions on someone give them
> >> > more freedom is pure Orwellian double speak.
>
> >> What about the freedom to take away other people?s freedom?
>
> > The freedom to take away other people's freedom is a very serious power
> > that should only be used sparingly.
>
> >> What tuple of speak would that be?
>
> > Well, if my friend has a slow internet connection, so I give him a Linux
> > CD which lets him get out of Windows hell (me taking advantage of RMS's
> > "freedom 2", and my friend taking advantage of RMS's "freedom 0"), and I
> > don't give my friend all the source code (or a written offer) because,
> > frankly, he wouldn't know what to do with the source anyway, and it
> > doesn't fit on the CD, and I didn't even bother downloading the source,
> > at that point I would apparently be in violation of the GPL license on
> > hundreds of programs, because I would be violating what the FSF calls
> > "freedom 1".
>
> If you used an existing Linux distribution, then the offer to provide
> source code will already be there.

No, there is no written offer, e.g. with Ubuntu, simply because they
take advantage of the ability to provide a download of the source from
the same place as a download of the object.  If I download an Ubuntu
ISO, burn it and give it away (let's say I give away 100 copies, just
to remove the fair use defense), then I have violated the GPL.  I
provided chapter and verse on this; go look it up.

> If you compiled the CD yourself, and failed to provide a written offer on
> the CD, then yes absolutely you would be in violation of the licence
> terms, and shame on you.

Not relevant.

> The GPL doesn't require you to force source code on those who don't want
> it, but it does require you to make it available if they ask, and for you
> to notify them appropriately of this fact. You don't even have to
> explicitly tell your friend he can have the source code. You just have to
> make sure that the written offer is available on the disk you give him.

There is no written offer on the disk, because I burned it from
Ubuntu's repository.  It really is that simple -- if I give away
copies I've made of Ubuntu, I've violated the GPL.  Unless you can
cite some authority that tells me I'm wrong and gives real reasons.  I
actually quoted chapter and verse from the license, but you chose to
ignore that and make unsubstantiated claims.

> > Now I know none of us would ever violate the license like this, but if,
> > hypothetically speaking, I had made such a CD for my friend, and then
> > someone came along and explained to me that, by helping wean my friend
> > from MS Windows in this fashion, I had taken away his freedom
> > (specifically RMS's "freedom 1"), I would probably conclude that the
> > person making this accusation was a moron
>
> Well, yes, you probably would draw that conclusion. Doesn't mean that you
> are right to do so, because quite frankly you would have taken away your
> friend's freedom (albeit in a very small fashion). Access to the source
> code is a freedom that the GPLed software on the disk *explicitly* grants
> to your friend, and by failing to pass the offer on, you have taken away
> that freedom in a very real sense.

I was going to say "moron" but you're obviously not, so I'll change my
opinion to "brainwashed." :-)

> We are talking about a small technical violation of the licence terms
> here.

No.  It's fundamental.  The license deliberately makes not sharing the
source *the* principal way to violate it.

> but imagine if everyone did it, if Red Hat and Debian and Ubuntu
> etc didn't bother passing on the source code (or a written offer).

Then somebody else would.  How does Apache work?

> Only a
> tiny proportion of people would discover by their own efforts that the
> source code was available

No, I tell my friends that source is available, and they can come and
see me if they want to know more.  This may have been a viable
argument in 1989 (doubtful) but it's extremely silly today.

>, and only a proportion of them would learn
> where it was available from. The result in practical terms would be a
> major decrease in the number of people granted the freedom to modify the
> source code, and a correspondingly larger decrease in the number of
> people both free and able to modify the source code.

I sincerely doubt your dystopian vision, which, like the GPL and many
laws, is predicated on some outmoded views about how humans interact.

The reason some people say that the GPL protects the "freedom of the
code" is because the GPL assumes that code needs to be nurtured,
instead of taking the viewpoint that, while there may be some
freeloaders, sharing code is obviously so valuable to most of humanity
that it will just happen.  We don't live in medieval Europe any more
where the rules of glassmaking are so secret that you'll be hunted
down like a dog if you try to leave.  We live in a world where "co-
opetition" has been shown to be so valuable we had to make up a word
for it, and even for those secrets that people are willing to kill to
keep, we have wikileaks.

Let's face it -- a software freeloader is not the most evil thing in
the world.  But whenever people assume that stopping bad behavior 'x'
is paramount, they have to make so many rules that everybody is in
violation of them all the time.  People love to share, but in general
people don't share things that others aren't interested in.  People
with source code will share with people who care about it.  Perhaps
making a special case for modified source code would be sufficient, if
you really care about what Linus calls "tit-for-tat."

> It's not enough to be granted freedom to modify source code in theory, if
> you know about it, if you can find some hard-to-locate website which may
> or may not be running. The practicalities are equally important.

That's another thing.  Even if I downloaded all the source from
Ubuntu, what assurances do I really have that I have all the source?
I could be in technical violation of the GPL without even knowing it,
even after wasting an extra two days grabbing the source.  Best to use
Gentoo to be sure, and even then, I need to build it twice running
strace just to make sure that I really built everything.

> In
> theoretical terms, everyone has the freedom to legally modify and
> distribute the source code to Microsoft Windows. All you have to do is
> buy 51% of the stock so as to become majority shareholder, then make
> sufficient changes to the board of directors so that the new board grants
> you a licence to do so, then fight off the lawsuits from the rest of the
> shareholders. Anyone could do it! Not.

So "everyone" could own 51% of Microsoft?  That means 100% of the
shares would be around 350,000,000,000%.  Wait, that can't be right,
what? :-)  Can you come up with a sillier analogy?

> Another, more practical example: here in Australia our government is hell-
> bent on introducing an ineffective and expensive Internet censorship
> scheme. It seems that under Australian law, it will be completely legal
> to circumvent the filter, but our government is investigating ways to
> make it illegal to tell anyone how to circumvent it. In other words,
> Australians will have permission to circumvent the nanny filter, but
> since few people will know this, or know how to do so, it will be a
> meaningless freedom.

Yes, that's basically how the DMCA works, and that's evil, and that's
one of the reasons I sometimes give money to the EFF.  But, you can't
seriously be comparing making speech a crime and making not speaking a
crime (or a copyright violation), can you?  Maybe you *did* manage to
come up with a sillier analogy...

> The GPL concerns itself with the *practical* freedom to gain access to
> source code, not merely the theoretical freedom represented by permission
> without opportunity.

No, the GPL is ideologically opposed to anything related to
practicality (although in practice, its adherents have to bend a bit
to avoid being made irrelevant, and Linux, the shining success, is led
by someone who arguably cares not one whit for GPL ideological
purity).

> Failure to pass on the offer to provide source code
> impacts that freedom in a very real sense.

The thing is, there is an offer.  It's just not written, and it may
not be that I will later be able to download the exact same source.
It doesn't meet the letter of the license.  Nonetheless, the offer is
*even better* than the one mandated by the GPL, because it comes with
an offer to teach.

But the GPL wording required to enforce what you call a practical
freedom imposes so many impractical costs that there are probably
millions of people in the world who have violated this license, in the
good-faith attempt to spread free software around.  As I mentioned to
Mr. Boddie, IMHO, the failure to bring any of these to justice is
deliberate, because suing someone who installed Ubuntu on his
grandmother's computer would give Free Software a huge public black
eye.

So the practicality is not in the *license*, but in the *selective
enforcement* of the license.  I view this sort of nod to practicality
to be exactly the same as Microsoft's implicit encouragement of piracy
in third-world countries.

Well, maybe not *exactly* the same, but to conclude that they are at
all different is to admit that *eventual* access to the source code is
moral enough and that enforced distribution of source code to
*everybody* is not really the best way to make the world a better
place.

> If you can't understand this, you have the freedom to think I'm a moron,
> and I have the freedom to be sure you are one too *wink*

Well, I don't think you are a moron, but I find some of your beliefs
not only ill-founded, but very negative -- based on the belief that so
few people will do the right thing absent onerous controls that the
only way to proceed is to impose those onerous controls and then look
the other way when the violation is not *too* egregious.

Also, it is obvious that you did not adequately research the legal
obligations of someone who downloads an Ubuntu ISO and make a few
copies to hand out, because you made completely unsupported statements
about how that works.

Regards,
Pat


From neilc at norwich.edu  Thu May 13 11:08:44 2010
From: neilc at norwich.edu (Neil Cerutti)
Date: 13 May 2010 15:08:44 GMT
Subject: indexing lists/arrays question
References: 
	
Message-ID: <852ivsFdj6U2@mid.individual.net>

On 2010-05-13, Stefan Behnel  wrote:
> a, 13.05.2010 16:36:
>> this must be easy but its taken me a couple of hours already
>>
>> i have
>>
>> a=[2,3,3,4,5,6]
>>
>> i want to know the indices where a==3 (ie 1 and 2)
>
>    indices = [ i for i,item in enumerate(a) if item == 3 ]

That form of list comprehension is preferable to my use of filter
posted elsewhere, but it didn't occur to me. Oops!

-- 
Neil Cerutti
*** Your child was bitten by a Bat-Lizard. ***


From oxfordenergyservices at googlemail.com  Thu May 13 11:15:30 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 08:15:30 -0700 (PDT)
Subject: indexing lists/arrays question
References: 
	
Message-ID: <91dbd493-bf48-443c-a2cf-93269baa25a8@24g2000yqy.googlegroups.com>

On 13 May, 15:47, Stefan Behnel  wrote:
> a, 13.05.2010 16:36:
>
> > this must be easy but its taken me a couple of hours already
>
> > i have
>
> > a=[2,3,3,4,5,6]
>
> > i want to know the indices where a==3 (ie 1 and 2)
>
> ? ?indices = [ i for i,item in enumerate(a) if item == 3 ]
>
> > then i want to reference these in a
>
> ? ?print [ a[i] for i in indices ]
>
> Stefan

thanks Stefan.  very useful.  I didn't get this from the python
documentation!


From e_d_k at yahoo.com  Thu May 13 11:18:25 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 08:18:25 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <495778.64465.qm@web58702.mail.re1.yahoo.com>
Message-ID: <929861.91577.qm@web58708.mail.re1.yahoo.com>

Consider the following scenario:

Three programmers, call them A, B & C, independently develop three different algorithms to perform a O(ln(n)) search. Each decide to release it for 'free'.

A decides to make it 'free', by publishing compiled object code for all major platforms and putting them in the public domain.

B decides to make it 'free' by publishing the source code under the GPL.

C decides to make it 'free' by publishing the source code under the Boost license.

Which library should be incorporated into the next Python release?, and why?

I vote for C, but would like to hear any arguments for another position.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From pmaupin at gmail.com  Thu May 13 11:18:52 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 08:18:52 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
Message-ID: <5c618134-bad9-456c-ace9-22bb082bc12d@i10g2000yqh.googlegroups.com>

On May 13, 7:25?am, Lawrence D'Oliveiro  wrote:
> In message
> <155f1683-9bfd-4a83-b63f-7fb0fc2f5... at g21g2000yqk.googlegroups.com>, Patrick
>
> Maupin wrote:
> > On May 12, 10:48 pm, Lawrence D'Oliveiro
> >  wrote:
>
> >> In message , Ed
> >> Keith wrote:
>
> >> > ... but to claim that putting more restrictions on someone give them
> >> > more freedom is pure Orwellian double speak.
>
> >> What about the freedom to take away other people?s freedom?
>
> > The freedom to take away other people's freedom is a very serious
> > power that should only be used sparingly.
>
> Given that the GPL restricts that power, then it must be all right.

But the freedom to take away other people's freedom to take away other
people's freedom is an even *more* serious power (as many communities
which have straight-jacketed their law enforcement officers have found
out), that should be used *very sparingly*, so your conclusion doesn't
necessarily follow.

Regards,
Pat



From python.list at tim.thechases.com  Thu May 13 11:19:05 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Thu, 13 May 2010 10:19:05 -0500
Subject: indexing lists/arrays question
In-Reply-To: 
References: 
Message-ID: <4BEC1869.1060204@tim.thechases.com>

On 05/13/2010 09:36 AM, a wrote:
> this must be easy but its taken me a couple of hours already
>
> i have
>
> a=[2,3,3,4,5,6]
>
> i want to know the indices where a==3 (ie 1 and 2)

indexes = [i for (i, v) in enumerate(a) where v==3]

> then i want to reference these in a

In a _what_?  You can then do things like

   for i in indexes:
     print a[i]

(but you already know these are "3", so it's not very exciting...)

-tkc




From aahz at pythoncraft.com  Thu May 13 11:27:27 2010
From: aahz at pythoncraft.com (Aahz)
Date: 13 May 2010 08:27:27 -0700
Subject: client to upload big files via https and get progress info
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
Message-ID: 

In article <4bea6b50$0$8925$426a74cc at news.free.fr>,
News123   wrote:
>
>I'd like to perform huge file uploads via https.
>I'd like to make sure,
>- that I can obtain upload progress info (sometimes the nw is very slow)
>- that (if the file exceeds a certain size) I don't have to
>  read the entire file into RAM.

Based on my experience with this, you really need to send multiple
requests (i.e. "chunking").  There are ways around this (you can look
into curl's resumable uploads), but you will need to maintain state no
matter what, and I think that chunking is the best/simplest.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From oxfordenergyservices at googlemail.com  Thu May 13 11:45:54 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 08:45:54 -0700 (PDT)
Subject: indexing lists/arrays question
References: 
	
Message-ID: 

On 13 May, 16:19, Tim Chase  wrote:
> On 05/13/2010 09:36 AM, a wrote:
>
> > this must be easy but its taken me a couple of hours already
>
> > i have
>
> > a=[2,3,3,4,5,6]
>
> > i want to know the indices where a==3 (ie 1 and 2)
>
> indexes = [i for (i, v) in enumerate(a) where v==3]
>
> > then i want to reference these in a
>
> In a _what_? ?You can then do things like
>
> ? ?for i in indexes:
> ? ? ?print a[i]
>
> (but you already know these are "3", so it's not very exciting...)
>
> -tkc

really its to get the indexes in 1 array where something equals
something then reference these in another array.


From pmaupin at gmail.com  Thu May 13 11:59:45 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 08:59:45 -0700 (PDT)
Subject: Picking a license
References: 
	
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	 
	<3ac0b2d2-7c14-4865-878c-c91473d7e71d@j35g2000yqm.googlegroups.com> 
	<151af4f3-8b32-4010-865c-c0041b636255@e2g2000yqn.googlegroups.com> 
	 
	<3dd1e80d-9979-41da-a332-66054e1eb309@i10g2000yqh.googlegroups.com> 
	<0c573cdc-5e6f-4747-b0df-84e338adcd89@e1g2000yqe.googlegroups.com> 
	<356d235e-63e3-4d36-bb7e-e436d9279f27@l28g2000yqd.googlegroups.com> 
	<845fc53a-5940-44fc-9189-a5a8ff56a95d@n15g2000yqf.googlegroups.com> 
	<5c1c0cce-f9f9-469b-ba3b-3eb9280c2bc9@g21g2000yqk.googlegroups.com> 
	<4f1c4723-a1c9-4b3d-aee3-d6475733066d@a34g2000yqn.googlegroups.com>
Message-ID: 

On May 13, 9:53?am, Paul Boddie  wrote:
> On 13 Mai, 01:36, Patrick Maupin  wrote:
>
>
>
> > Once the court reaches that conclusion, it would only be a tiny step
> > to find that the FSF's attempt to claim that clisp infringes the
> > readline copyright to be a misuse of that same readline copyright.
> > See, e.g. LaserComb v Reynolds, where the defendant (IMHO) acted much
> > more egregiously than anybody who is delivering free software like
> > clisp is acting, and nevertheless won on that issue.
>
> In that very case you mention, LaserComb did not lose the copyright
> protection on their work, were "free to bring an infringement suit
> once it had cured the misuse" [1], and the clause which led to a
> defence based on "copyright misuse" was one which forbade licensees
> from making competing products.

Yes.  You make 3 points here, which I will address in order

1) They did not lose the copyright protection on their work.

To be clear, what I meant by losing copyright protection is not at all
the same as losing the copyright itself.  The loss of protections
simply means that you can't necessarily prevail in a lawsuit for
infringement against people who infringed while you were misusing the
copyright.  This could be true, even if while the copyright was being
misused, RMS attempted to sue someone else, and even if he had a solid
case.  From Lasercomb:  "However, again analogizing to patent misuse,
the defense of copyright misuse is available even if the defendants
themselves have not been injured by the misuse."  So, during the time
of the misuse, yes, they lost their copyright protections, but the
loss was only temporary and could be cured going forward by not
overreaching in their license agreement.

2) "Were free to bring an infringement suit once they cured the
misuse."

Yes, if you read the actual footnote you are referencing, it cites
United States Gypsum Co. v National Gypsum Co., which was a patent
case.  In that case, there was a price-fixing cartel based on patents,
and the cartel lost its ability to use the patents until they changed
their illegal patent licensing scheme.  Once they changed how they
licensed their patents to the court's satisfaction, they were then
free to go after patent infringers.  BUT, only for infringements that
occurred *after* they cured the infringement.  Curing the infringement
is not a magic wand that allows you a mulligan for your original cause
of action, otherwise the patent/copyright misuse defense would be
meaningless.

3) and the clause which led to a defence based on "copyright misuse"
was one which forbade licensees from making competing products.

Yes, but if you read the reasoning in the decision, almost any attempt
to stretch a copyright (or patent) to cover things it doesn't really
cover could be viewed as a misuse.  So, to the extent that the GPL
claims that the distribution of something that links to readline
violates readline's copyright by being a derivative work, if a court
finds this to be untrue, it could also find that the readline
copyright was being misused, at least until the license were modified
to make it clear that distributing a program that could use readline
(without distributing readline) did not impose any specific licensing
requirements on the readline-using program.

To follow this logic, all you have to do is to read the LaserComb
decision very carefully (it analogizes copyright misuse to patent
misuse), and then read the myriad ways it is possible to misuse
patents.

Regards,
Pat


From prologic at shortcircuit.net.au  Thu May 13 12:02:24 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 14 May 2010 02:02:24 +1000
Subject: client to upload big files via https and get progress info
In-Reply-To: <4bea6b50$0$8925$426a74cc@news.free.fr>
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
Message-ID: 

On Wed, May 12, 2010 at 6:48 PM, News123  wrote:
> Hi,
>
> I'd like to perform huge file uploads via https.
> I'd like to make sure,
> - that I can obtain upload progress info (sometimes the nw is very slow)
> - that (if the file exceeds a certain size) I don't have to
> ?read the entire file into RAM.
>
> I found Active states recipe 146306, which constructs the whole
> multipart message first in RAM and sends it then in one chunk.
>
>
> I found a server side solutions, that will write out the data file chunk
> wise ( http://webpython.codepoint.net/mod_python_publisher_big_file_upload
> )
>
>
>
> If I just wanted to have progress info, then I could probably
> just split line 16 of Active State's recipe ( h.send(body) )
> into multiple send, right?
>
> chunksize = 1024
> for i in range(0,len(body),chunksize):
> ? ?h.send(body[i:i+chunksize])
> ? ?show_progressinfo()
>
>
> But how could I create body step by step?
> I wouldn't know the content-length up front?
>
> thanks in advance

My suggestion is to find some tools that can
send multiple chucks of data. A non-blocking
i/o library/tool might be useful here (eg: twisted or similar).

cheers
James


From paul at boddie.org.uk  Thu May 13 12:19:25 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Thu, 13 May 2010 09:19:25 -0700 (PDT)
Subject: Picking a license
References:  <30aff350- 
	<074b412a-c2f4-4090-a52c-4d69edb29a22@d39g2000yqa.googlegroups.com> 
	
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
Message-ID: <2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>

On 13 Mai, 01:58, Patrick Maupin  wrote:
> On May 12, 6:15?pm, Paul Boddie  wrote:
> > Right. The "full cost" of software that probably cost them nothing
> > monetarily and which comes with all the sources, some through a chain
> > of distribution and improvement which could have led to proprietary
> > software had the earliest stages in the chain involved permissive
> > licensing. And that they can't sell a binary-only Ubuntu derivative.
>
> Who's talking about selling a binary-only version -- there is a good
> chance they can't even give away a binary CD without violating
> copyright.

People only have to honour requests for the corresponding source if
asked for it. They are not violating copyright by default. If you
think Ubuntu are exposing people to legal peril by advocating that
people make copies of Ubuntu for their friends, why don't you tell
Mark Shuttleworth about it?

[...]

> > So, the "negative consequences" are that people can't make proprietary
> > editions of some software. When that's a deliberate choice in the
> > design of a licence, there's no pretending that the consequences
> > aren't there, just that they aren't perceived by everyone to be
> > negative.
>
> I gave an example earlier of svglib and rst2pdf. ?Negative
> consequences. ?Nothing proprietary involved.

Negative consequences for people who don't want to touch GPL-licensed
software and who reserve the right to make proprietary versions of
rst2pdf.

[...]

> > Well, you effectively said that you didn't like being asked to "share
> > alike", which is what the GPL achieves.
>
> I give away lots of software. ?Free to all comers. ?Come and get some.

Yes, but you don't insist that people "share alike". I don't demand
that you insist that, either, but you clearly object to other people
putting that condition on their own works.

> > so why should I not assume
> > that you generally object to other, more obviously labelled licences
> > like the CC-*-SA licences which make it clear what is expected of that
> > hapless recipient of a work who doesn't bother reading the licence?
>
> Your assumptions are so far away from reality that there is really no
> good reason why you shouldn't assume that I'm a 10 foot tall purple
> monster.

Then you've done a very bad job communicating them. Laying off the
bizarre imagery might help remedy that somewhat.

[...]

> > Yes, but you have to choose to do something ("X") to start with. Which
> > is actually what you wrote later in that exchange:
>
> > "Again, the force is applied once you choose to do a particular thing
> > with the software -- is is really that hard to understand that
> > concept?"
>
> I didn't just write that later. ?I wrote it in my very first post,
> which you just quoted a few lines up, apparently without even
> bothering to read it closely.

I did read it closely. Now read your own comment closely and take
particular notice of the word "choose".

[...]

> So, the FSF, which so carefully provides the most legalese-ish license
> on the planet, which was in development for god-knows-how-long, which

Have you read the Mozilla Public License? Have you read through Sun's
JDK licence? You were complaining about Microsoft licensing earlier:
have you read those licences through to the end? (There are people who
refuse to accept them, incidentally, and are then refused any kind of
refund for the product. Next you'll be claiming that the FSF's
indiscretions are on the same level as this particular Microsoft-plus-
vendor scam, and yet accuse me of a lack of a sense of perspective.)

> maintains a carefully parsed FAQ of what you can and can't do, which
> engages in all sorts of advocacy, can't find the time to explain to
> Ubuntu that they really ought to explain how the licensing works on
> their download page?

I think Ubuntu can maybe see the case for moving their notice on their
"legal" page to the download page if you can make it successfully. Or
is your point that people have to be "warned" about that inconvenient
GPL licence?

>?What have you been smoking and where can I get some?

Yes, always ready with a pertinent response, I see.

[...]

> > I never said there was. I said that if you don't like the licence,
> > don't incorporate works which use it into your own projects.
>
> No, you said "If you don't like them, don't use GPL-licensed
> software."

In the context of developing and redistributing it. If you hate the
GPL so much, you might not feel comfortable even using the software,
either, but that's up to you. You're the one with the problem with the
GPL.

> > But don't
> > say that it's not fair that people are releasing stuff under terms you
> > don't like, or say that they're being "pathetic" or petty or
> > ridiculous by doing so, or are imposing their agenda on you.
>
> The only time I mentioned pathetic and petty were for really small
> libraries, which probably wouldn't merit copyright protection in any
> case.

And for you, libraries like readline are apparently not really worth
anything, either. It's always interesting to see the case made for
incorporating something into another system because it apparently has
little value relative to the entire system, but should the request be
made that the incorporated work be dropped and replaced by something
rewritten to do the same job, it is suddenly far too much work.

> > More name-calling and finger-pointing. Great stuff, there. Anything
> > else?
>
> Yes, just that you keep selectively quoting both of us, and twisting
> what we both said to meet your agenda. ?But I'm done. ?I think there
> are enough pointers to original material here for others to go and do
> whatever level of research they deem appropriate for their own
> situations.

All my position has ever been is this:

A copyrighted work denies recipients virtually all rights to do stuff
with that work, such as modify and redistribute it. Copyleft licences
grant some privileges and uphold some obligations in order to ensure
that these privileges are universally maintained in all forms and
extensions of the work. Permissive licences grant more privileges to
immediate recipients but do not uphold as many obligations.

You rejected the suggestion that people using permissive licences
afford users fewer privileges than those using copyleft licences, yet
on balance when considering all forms and extensions of the work, they
do. And the only such privilege that the copyleft licences withholds
from recipients is that of withholding any other privilege from others
who receive the work.

You objected to the suggestion that people using permissive licences
do not care about maintaining such privileges ("an uncaring bunch"),
yet it can be said that they surely do not actively care about the
matter of such privileges being maintained: I have encountered
proprietary variants of Apache technologies, and proprietary editions
of Python have been released from some vendors. If they had considered
it important enough, they would not have chosen licences which
permitted the delivery of their work (or extended versions thereof) to
people where many of the privileges normally afforded to users have
been withheld.

You made the point that some people don't want to touch GPL-licensed
software because it might affect the permissively licensed software
that they are writing. Since the only effect of combining both forms
of software occurs when offering that to a user, and that effect is to
uphold the copyleft obligations and maintain the corresponding set of
privileges, withholding only the privilege to deny recipients the
other privileges, this means that it becomes impossible to make the
combined work a proprietary one. You then tried to sow uncertainty
about the validity and effectiveness of the GPL to achieve its
objectives.

I can see why some people don't like the GPL. When the only notable
privilege it withholds is precisely that of taking the work of others
and making a proprietary product from it, all the claims about
coercion and ideology should be considered against this very function
of the licence. Then, the motivations of a number of its critics are
plain for all to see.

That some of those critics appeal to public outrage by using
references to terrorists, criminals and fundamentalists should hardly
be surprising, and I have come to expect no better in discussions of
this kind. Anything to accuse others of having an agenda - even better
if that agenda can be blended in the popular imagination with those
aforementioned kinds of undesirable people - while doing as much as
they can to conceal their own.

Paul


From lie.1296 at gmail.com  Thu May 13 12:35:09 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Fri, 14 May 2010 02:35:09 +1000
Subject: Broken pipe
In-Reply-To: 
References: 
	
	
Message-ID: <4bec2a9a$1@dnews.tpgi.com.au>

On 05/13/10 22:41, Lawrence D'Oliveiro wrote:
> In message , Chris 
> Rebert wrote:
> 
>> Also, please don't use semicolons in your code. It's bad style.
> 
> Wonder why they?re allowed, then.

they're there for line continuation, e.g.:

a = 40; foo(a)

but in many cases, putting two statements in a single line reduces
readability so use the semicolons extremely conservatively. But the
worst is the abuse of semicolons for end-of-line markers.


From news1234 at free.fr  Thu May 13 12:39:37 2010
From: news1234 at free.fr (News123)
Date: Thu, 13 May 2010 18:39:37 +0200
Subject: client to upload big files via https and get progress info
In-Reply-To: 
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	
Message-ID: <4BEC2B49.7060007@free.fr>

Hi Aaaz,

Aahz wrote:
> In article <4bea6b50$0$8925$426a74cc at news.free.fr>,
> News123   wrote:
>> I'd like to perform huge file uploads via https.
>> I'd like to make sure,
>> - that I can obtain upload progress info (sometimes the nw is very slow)
>> - that (if the file exceeds a certain size) I don't have to
>>  read the entire file into RAM.
> 
> Based on my experience with this, you really need to send multiple
> requests (i.e. "chunking").  There are ways around this (you can look
> into curl's resumable uploads), but you will need to maintain state no
> matter what, and I think that chunking is the best/simplest.
I agree I need  chunking. (the question is just on which level of the
protocol)

I just don't know how to make a chunkwise file upload or what library is
best.

Can you recommend any libraries or do you have a link to an example?


I'd like to avoid to make separate https post requests for the chunks
(at least if the underlying module does NOT support keep-alive connections)


I made some tests with high level chunking (separate sequential https
post requests).
What I noticed is a rather high penalty in data throughput.
The reason is probably, that each request makes its own https connection
and that either the NW driver or the TCP/IP stack doesn't allocate
enough band width to my request.

Therefore I'd like to do the chunking on a 'lower' level.
One option would be to have a https module, which supports keep-alive,

the other would be  to have a library, which creates a http post body
chunk by chunk.


What do others do for huge file uploads
The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )

N


From carey.tilden at gmail.com  Thu May 13 12:41:46 2010
From: carey.tilden at gmail.com (Carey Tilden)
Date: Thu, 13 May 2010 09:41:46 -0700
Subject: indexing lists/arrays question
In-Reply-To: 
References: 
	
	
Message-ID: 

On Thu, May 13, 2010 at 8:45 AM, a  wrote:
> On 13 May, 16:19, Tim Chase  wrote:
>> On 05/13/2010 09:36 AM, a wrote:
>>
>> > this must be easy but its taken me a couple of hours already
>>
>> > i have
>>
>> > a=[2,3,3,4,5,6]
>>
>> > i want to know the indices where a==3 (ie 1 and 2)
>>
>> indexes = [i for (i, v) in enumerate(a) where v==3]
>>
>> > then i want to reference these in a
>>
>> In a _what_? ?You can then do things like
>>
>> ? ?for i in indexes:
>> ? ? ?print a[i]
>>
>> (but you already know these are "3", so it's not very exciting...)
>>
>> -tkc
>
> really its to get the indexes in 1 array where something equals
> something then reference these in another array.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Out of curiosity, why are you using two arrays?  Have you considered a
dict?  There are of course good reasons not to use a dict in this
situation, but you haven't said one way or another.

Carey


From python.list at tim.thechases.com  Thu May 13 13:18:39 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Thu, 13 May 2010 12:18:39 -0500
Subject: indexing lists/arrays question
In-Reply-To: 
References: 	
	
Message-ID: <4BEC346F.3020901@tim.thechases.com>

On 05/13/2010 10:45 AM, a wrote:
>>> a=[2,3,3,4,5,6]
>>
>>> i want to know the indices where a==3 (ie 1 and 2)
>>
>> indexes = [i for (i, v) in enumerate(a) where v==3]
>>
>>> then i want to reference these in a
>>
>> In a _what_?  You can then do things like
>>
>>     for i in indexes:
>>       print a[i]
>>
>> (but you already know these are "3", so it's not very exciting...)
>>
>> -tkc
>
> really its to get the indexes in 1 array where something equals
> something then reference these in another array.

If your two arrays are of the same length, you can do things like

   a = [2,3,3,4,5,6]
   b = ['a', 'b', 'c', 'd', 'e', 'f']

   print [m for (n,m) in zip(a,b) if n == 3]

and skip the indexes altogether.

-tkc






From oxfordenergyservices at googlemail.com  Thu May 13 13:48:42 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 10:48:42 -0700 (PDT)
Subject: indexing lists/arrays question
References: 
	
	
	
Message-ID: <47754dc9-dcfa-4a3b-b171-3a342f42e5fe@o14g2000yqb.googlegroups.com>

On 13 May, 17:41, Carey Tilden  wrote:
> On Thu, May 13, 2010 at 8:45 AM, a  wrote:
> > On 13 May, 16:19, Tim Chase  wrote:
> >> On 05/13/2010 09:36 AM, a wrote:
>
> >> > this must be easy but its taken me a couple of hours already
>
> >> > i have
>
> >> > a=[2,3,3,4,5,6]
>
> >> > i want to know the indices where a==3 (ie 1 and 2)
>
> >> indexes = [i for (i, v) in enumerate(a) where v==3]
>
> >> > then i want to reference these in a
>
> >> In a _what_? ?You can then do things like
>
> >> ? ?for i in indexes:
> >> ? ? ?print a[i]
>
> >> (but you already know these are "3", so it's not very exciting...)
>
> >> -tkc
>
> > really its to get the indexes in 1 array where something equals
> > something then reference these in another array.
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Out of curiosity, why are you using two arrays? ?Have you considered a
> dict? ?There are of course good reasons not to use a dict in this
> situation, but you haven't said one way or another.
>
> Carey

i am reading a 2,n array from one website, column1=times,
column2=values
then another 2,n array from another website, column1=times,
column2=values

the times are different but may (or may not) coincide in places

i need to make a 3rd array, 2,n where the first column are column2
values from array1 and the second column are column2 values from array
2 #where the timestamps agree#

i'm an idl programmer and doing this would be second nature but i need
to make an application which does something along the lines of the
above then plots column2 vs column2 for the above array3 (plus some
other maths).  needs to be non-proprietary and work on different
platforms.  i just started with python, not even sure if it's the best
thing.  the plotting routines seem not to come wrapped with standard
python which is a bit of a pain.

the routine i use most in idl is 'where' and though i managed to write
a def which worked, i couldn't then dereference the list of those
indexes.  i'm a bit old to be learning new languages

thanks for your help!



From oxfordenergyservices at googlemail.com  Thu May 13 13:51:13 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 10:51:13 -0700 (PDT)
Subject: indexing lists/arrays question
References: 
	
	
	
Message-ID: <994e3852-637d-4bfd-96db-dd2e74c12cd2@e2g2000yqn.googlegroups.com>

On 13 May, 18:18, Tim Chase  wrote:
> On 05/13/2010 10:45 AM, a wrote:
>
>
>
>
>
> >>> a=[2,3,3,4,5,6]
>
> >>> i want to know the indices where a==3 (ie 1 and 2)
>
> >> indexes = [i for (i, v) in enumerate(a) where v==3]
>
> >>> then i want to reference these in a
>
> >> In a _what_? ?You can then do things like
>
> >> ? ? for i in indexes:
> >> ? ? ? print a[i]
>
> >> (but you already know these are "3", so it's not very exciting...)
>
> >> -tkc
>
> > really its to get the indexes in 1 array where something equals
> > something then reference these in another array.
>
> If your two arrays are of the same length, you can do things like
>
> ? ?a = [2,3,3,4,5,6]
> ? ?b = ['a', 'b', 'c', 'd', 'e', 'f']
>
> ? ?print [m for (n,m) in zip(a,b) if n == 3]
>
> and skip the indexes altogether.
>
> -tkc

mmm, that's clever, thanks.  although i don't know why it works yet.
at least i found a good user group!


From albertkao3 at gmail.com  Thu May 13 13:58:44 2010
From: albertkao3 at gmail.com (albert kao)
Date: Thu, 13 May 2010 10:58:44 -0700 (PDT)
Subject: walk directory & ignore all files/directories begin with '.'
Message-ID: 

I want to walk a directory and ignore all the files or directories
which names begin in '.' (e.g. '.svn').
Then I will process all the files.
My test program walknodot.py does not do the job yet.
Python version is 3.1 on windows XP.
Please help.

[code]
#!c:/Python31/python.exe -u
import os
import re

path = "C:\\test\\com.comp.hw.prod.proj.war\\bin"
for dirpath, dirs, files in os.walk(path):
    print ("dirpath " + dirpath)
    p = re.compile('\\\.(\w)+$')
    if p.match(dirpath):
        continue
    print ("dirpath " + dirpath)
    for dir in dirs:
        print ("dir " + dir)
        if dir.startswith('.'):
            continue

        print (files)
        for filename in files:
            print ("filename " + filename)
            if filename.startswith('.'):
                continue
            print ("dirpath filename " + dirpath + "\\" + filename)
    	    # process the files here
[/code]

C:\python>walknodot.py
dirpath C:\test\com.comp.hw.prod.proj.war\bin
dirpath C:\test\com.comp.hw.prod.proj.war\bin
dir .svn
dir com
[]
dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
...

I do not expect C:\test\com.comp.hw.prod.proj.war\bin\.svn to appear
twice.
Please help.


From python at mrabarnett.plus.com  Thu May 13 15:10:52 2010
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 13 May 2010 20:10:52 +0100
Subject: walk directory & ignore all files/directories begin with '.'
In-Reply-To: 
References: 
Message-ID: <4BEC4EBC.7010107@mrabarnett.plus.com>

albert kao wrote:
> I want to walk a directory and ignore all the files or directories
> which names begin in '.' (e.g. '.svn').
> Then I will process all the files.
> My test program walknodot.py does not do the job yet.
> Python version is 3.1 on windows XP.
> Please help.
> 
> [code]
> #!c:/Python31/python.exe -u
> import os
> import re
> 
> path = "C:\\test\\com.comp.hw.prod.proj.war\\bin"
> for dirpath, dirs, files in os.walk(path):
>     print ("dirpath " + dirpath)
>     p = re.compile('\\\.(\w)+$')
>     if p.match(dirpath):
>         continue
>     print ("dirpath " + dirpath)
>     for dir in dirs:
>         print ("dir " + dir)
>         if dir.startswith('.'):
>             continue
> 
>         print (files)
>         for filename in files:
>             print ("filename " + filename)
>             if filename.startswith('.'):
>                 continue
>             print ("dirpath filename " + dirpath + "\\" + filename)
>     	    # process the files here
> [/code]
> 
> C:\python>walknodot.py
> dirpath C:\test\com.comp.hw.prod.proj.war\bin
> dirpath C:\test\com.comp.hw.prod.proj.war\bin
> dir .svn
> dir com
> []
> dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> ...
> 
> I do not expect C:\test\com.comp.hw.prod.proj.war\bin\.svn to appear
> twice.
> Please help.

The problem is with your use of the 'match' method, which will look for 
a match only at the start of the string. You need to use the 'search'
method instead.

The regular expression is also incorrect. The string literal:

     '\\\.(\w)+$'

passes the characters:

     \\.(\w)+$

to the re module as the regular expression, which will match a
backslash, then any character, then a word, then the end of the string.
What you want is:

     \\\.\w+$

(you don't need the parentheses) which is best expressed as the 'raw'
string literal:

     r'\\\.\w+$'


From pmaupin at gmail.com  Thu May 13 16:10:04 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 13:10:04 -0700 (PDT)
Subject: Picking a license
References: 
	 
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com> 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
Message-ID: <7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>

On May 13, 11:19?am, Paul Boddie  wrote:
> People only have to honour requests for the corresponding source if
> asked for it. They are not violating copyright by default.

Well, the gospel according to the FSF says otherwise:

http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary

> If you
> think Ubuntu are exposing people to legal peril by advocating that
> people make copies of Ubuntu for their friends, why don't you tell
> Mark Shuttleworth about it?

Because I don't really think the peril is real -- a) nobody's going to
sue because of the negative PR consequences; and b) fair use would nip
the lawsuit in the bud.  In fact, the very *lack* of warning on the
Ubuntu site would help the end user in the lawsuit.

> Negative consequences for people who don't want to touch GPL-licensed
> software and who reserve the right to make proprietary versions of
> rst2pdf.

Negative consequences for people who don't want to tell other people
what to do.

> > > Well, you effectively said that you didn't like being asked to "share
> > > alike", which is what the GPL achieves.
>
> > I give away lots of software. ?Free to all comers. ?Come and get some.
>
> Yes, but you don't insist that people "share alike". I don't demand
> that you insist that, either, but you clearly object to other people
> putting that condition on their own works.

You're still not paying attention.  I think it's fine if people want
to do that, but I still think there is "force" involved, and that it
is not the best solution for all situations.  I also believe that
legally, the GPL license tries to overreach in its control of other
people's software, but that morally that may not matter, because the
intentions of the license's author are clear.

> > Your assumptions are so far away from reality that there is really no
> > good reason why you shouldn't assume that I'm a 10 foot tall purple
> > monster.
>
> Then you've done a very bad job communicating them. Laying off the
> bizarre imagery might help remedy that somewhat.

I didn't start off with bizarre imagery.  That only came about when
people started trying to use really lame excuses about why my initial
statement was wrong.
>
> [...]
>
> > > Yes, but you have to choose to do something ("X") to start with. Which
> > > is actually what you wrote later in that exchange:
>
> > > "Again, the force is applied once you choose to do a particular thing
> > > with the software -- is is really that hard to understand that
> > > concept?"
>
> > I didn't just write that later. ?I wrote it in my very first post,
> > which you just quoted a few lines up, apparently without even
> > bothering to read it closely.
>
> I did read it closely. Now read your own comment closely and take
> particular notice of the word "choose".

In my initial post, I mentioned that the force kicks in "once the
decision is made..."  That implies a choice.  Knowingly or not, you
have finally acknowledged that my initial post on this issue is
reasonably accurate, but even in so doing, you keep pointing to
specific words there to try to show that I'm contradicting myself.
Which, if I am, is only because I'm overreaching to try to combat the
overreaching on the other side.  I fully stand by my first post on
this issue, and most of the posting since then has been to correct
misunderstandings and apparently willful misinterpretations of that.

> I think Ubuntu can maybe see the case for moving their notice on their
> "legal" page to the download page if you can make it successfully.

The point, which I have made in another post, is that a fairly normal
way of acquiring Ubuntu -- giving a friend a CD -- violates the GPL as
written, and this is by design.  The goal is to get more free software
users even if they are abusing the license, and only punish those who
are abusing the license in particular ways.  BTW, there is nothing
even on Ubuntu's legal page warning about this possible consequence
for sharing a CD, or at least not in a very clear fashion.

> Or
> is your point that people have to be "warned" about that inconvenient
> GPL licence?

I don't think that would be a bad idea at all.  Say what you want
about Microsoft; if you install Windows, their software is quick to
explain all the licensing terms in gory detail.  Mind you, even that's
not really in English, but they get more points for the attempt than
Ubuntu.

> >?What have you been smoking and where can I get some?
>
> Yes, always ready with a pertinent response, I see.

I am ready with pertinent responses to well thought-out arguments, and
with impertinent responses to silly arguments.  From a practical
perspective, Microsoft turning a blind eye to increase market share,
and GPL authors turning a blind eye to increase market share and/or
goodwill are identical.  The fact that money is involved in one
instance and not in the other is immaterial.  The fact that you
believe in the goals of one and not the goals of the other is
immaterial.  The true fact is that, in both cases, copyright law in
conjunction with the license would allow the author to go after
several individuals for license violations, and (IMHO) a deliberate
decision has been made not to do so.  There have been numerous well-
publicized instances of people giving away copies they burned of
Ubuntu without corresponding source or a written offer, and no
negative consequences that I can see.

> [...]
>
> > > I never said there was. I said that if you don't like the licence,
> > > don't incorporate works which use it into your own projects.
>
> > No, you said "If you don't like them, don't use GPL-licensed
> > software."
>
> In the context of developing and redistributing it. If you hate the
> GPL so much, you might not feel comfortable even using the software,
> either, but that's up to you. You're the one with the problem with the
> GPL.

The context was right after talking about Mepis getting slapped, and
how all the clauses of the GPL were there for a reason, and if you
don't like the clauses, don't use the software.  I did not read it
with the contextual limitations you are now claiming for it.  You,
either deliberately or carelessly, have written several thing like
this that could easily be misconstrued, and this sometimes exasperates
me to the point where I write impertinent responses.

> > > But don't
> > > say that it's not fair that people are releasing stuff under terms you
> > > don't like, or say that they're being "pathetic" or petty or
> > > ridiculous by doing so, or are imposing their agenda on you.
>
> > The only time I mentioned pathetic and petty were for really small
> > libraries, which probably wouldn't merit copyright protection in any
> > case.
>
> And for you, libraries like readline are apparently not really worth
> anything, either. It's always interesting to see the case made for
> incorporating something into another system because it apparently has
> little value relative to the entire system, but should the request be
> made that the incorporated work be dropped and replaced by something
> rewritten to do the same job, it is suddenly far too much work.

No, you are absolutely misreading.  The case is for *not*
incorporating something into another system, because it's really *not*
that much work, even though the replicated effort is a bit of a shame
in some cases.

> > > More name-calling and finger-pointing. Great stuff, there. Anything
> > > else?
>
> > Yes, just that you keep selectively quoting both of us, and twisting
> > what we both said to meet your agenda. ?But I'm done. ?I think there
> > are enough pointers to original material here for others to go and do
> > whatever level of research they deem appropriate for their own
> > situations.
>
> All my position has ever been is this:
>
> A copyrighted work denies recipients virtually all rights to do stuff
> with that work, such as modify and redistribute it.

Translation:  Copyright law gives the author a monopoly on
distribution and derivative works,  and absent an explicit license to
make a derivative work or distribute a copy, the author can sue you
for making the derivative work or distributing the copy.  Nobody
forces the author to do that; it is his choice alone, but if he makes
it, government might back him up in his attempt to damage you.  Also,
in choosing a commercial license such as the GPL, the author is making
clear his intent to assert his rights, so you should take this very
seriously.

> Copyleft licences
> grant some privileges and uphold some obligations in order to ensure
> that these privileges are universally maintained in all forms and
> extensions of the work.

Translation:

Copyleft licences are a way for the author to communicate that he will
not sue you for making a derivative work or distributing a copy as
long as you distribute source code.  In reality, the author probably
will not sue you even if you don't distribute source code with that
Ubuntu CD, but you really can't be sure about that, because he has
made it clear that he *really* wants you to give out the source code.
In fact, on the FSF website, they make it clear in several places that
the author really wants you to give away your *own* source code if it
could interoperate with the author's source code, *even if* you're not
actually giving away the author's source code.

> Permissive licences grant more privileges to
> immediate recipients but do not uphold as many obligations.

Translation:

Software with a permissive license is more of a gift.  No quid-pro-quo
required, and the license does not attempt to claim rights over
anything except the actual licensed work.

> You rejected the suggestion that people using permissive licences
> afford users fewer privileges than those using copyleft licences,

That is correct.  All "privileges" as you put it are merely things
that a user can do with the code without fear of a lawsuit by the
author, and when an author uses a permissive license, he indicates
that the things that he could possibly find egregious enough to sue
over are very few.  For example, if you give an Ubuntu CD to your
friend without giving source code or a written offer of source code,
you have violated the license on quite a few of the programs on the
CD, but not, for example, on Python or Apache, because these licenses
do not attempt to forbid you from doing this.

> yet on balance when considering all forms and
> extensions of the work, they do.

Translation:

An author using the GPL is using the threat of lawsuits against *other
authors* to force the other authors to make their work also available
under the GPL.  Some authors attempt use this threat even against the
authors of works which a user could conveniently link against a GPLed
work, even when the authors of these other works have not copied or
distributed the GPL work themselves.  Some people, including Mr.
Boddie, feel that the public benefits of this license pyramid scheme
greatly outweigh any negative consequences of this scheme, in part by
equating the scheme itself with freedom and morality, and then using
the tautological logic that anybody who feels the negative
consequences must be immorally against freedom.

> And the only such privilege that the copyleft licences withholds
> from recipients is that of withholding any other privilege from others
> who receive the work.

Translation:

We really are serious about suing people who violate the license in
some cases.  Even though the stated purpose of the license is to
encourage sharing, the only really safe thing to do is to not share
that Ubuntu CD, because if you don't give out the exact source to the
exact object on the CD to everybody you give the CD to, you could be a
target.  Well, not really.  That would be bad PR.  But to protect your
rights, we have to design the license in such a way that we do reserve
the right to sue you under these conditions.  Just so you know.

> You objected to the suggestion that people using permissive licences
> do not care about maintaining such privileges ("an uncaring bunch"),
> yet it can be said that they surely do not actively care about the
> matter of such privileges being maintained:

Oh?  They take down their source archives on a whim?

> I have encountered
> proprietary variants of Apache technologies, and proprietary editions
> of Python have been released from some vendors.

Oh, I see.  Once someone releases a proprietary version of Python,
it's game over -- the PSF people realize they're outnumbered and
that's when take down their repository, so that's how privileges
disappear.

Seriously, to the extent there is nothing new in the proprietary
version, it's no big deal -- get it from the original source (probably
fewer viruses anyway).  To the extent there are additional features in
the proprietary version, guess what?  They were written by somebody
else and they don't belong to the PSF people.  To the extent there are
bug fixes in the proprietary version that aren't in the mainline
Python distribution -- hah!  that's extremely unlikely.

> If they had considered
> it important enough, they would not have chosen licences which
> permitted the delivery of their work (or extended versions thereof) to
> people where many of the privileges normally afforded to users have
> been withheld.

"Normally afforded to users."  Normalcy, in the software world, is
what Microsoft does.  Sure, that's changing, and that's good, but I
don't think that word means what you think it does.  But in any case,
you're right -- they didn't consider it important enough.  Hint:  that
doesn't make them uncaring.

> You made the point that some people don't want to touch GPL-licensed
> software because it might affect the permissively licensed software
> that they are writing.

Correct.

> Since the only effect of combining both forms
> of software occurs when offering that to a user,

No, according to the FSF, the effect can happen even before the
software is combined, when non-GPLed software is offered to the user,
if that non-GPLed software can interact in certain ways with GPLed
software.

> and that effect is to
> uphold the copyleft obligations and maintain the corresponding set of
> privileges, withholding only the privilege to deny recipients the
> other privileges,

Translation:

The effect is to try to force licensing terms on software that the
author didn't write.

> this means that it becomes impossible to make the
> combined work a proprietary one.

That's obviously the strongly desired effect.

> You then tried to sow uncertainty
> about the validity and effectiveness of the GPL to achieve its
> objectives.

The GPL is certainly effective in achieving some of its objectives.  I
disagree how useful some of those are to society, sure.  In terms of
the validity of the license, I believe that the selective enforcement
of the GPL will only target those actors who everybody can agree is
bad, but that the literal writing of the GPL and, especially the FSF's
FAQ about the GPL, is unsupportably overbroad.  For example, a literal
reading really does require you to give grandma source or a written
offer if you install Ubuntu on her computer, but fair use would
decimate that claim in a heartbeat.  Nonetheless, on a few of the
overbroad claims, the FSF prefers to promulgate FUD about how, for
example, it would not be possible for a proprietary program to
dynamically link to readline.  The wouldn't actually file a lawsuit on
that issue, because the possibility they would lose is too great.

> I can see why some people don't like the GPL.

Yes, you see, but you don't understand.

> When the only notable
> privilege it withholds is precisely that of taking the work of others
> and making a proprietary product from it.

No, it theoretically keeps me from burning a Ubuntu CD and then
putting it on my grandmother's computer without also downloading a
bunch of source code.  A literal reading of the license shows that the
restrictions really are that onerous.

> all the claims about
> coercion and ideology should be considered against this very function
> of the licence. Then, the motivations of a number of its critics are
> plain for all to see.

Here, we absolutely agree.  Just want to be sure that we also agree
that the GPL license is *so* picky about how it goes about its
business that you can't even link GPL v2-only code with GPL v3 code
without incurring a license violation.  It's really tough to innovate
on licensing when one of the major functions of the license is to
propagate exact copies of itself.

> That some of those critics appeal to public outrage by using
> references to terrorists, criminals and fundamentalists should hardly
> be surprising, and I have come to expect no better in discussions of
> this kind.

When the leader of your religion bandies terms like "freedom" and
"evil" about, what do you expect?  Seriously?

> Anything to accuse others of having an agenda

So now you're claiming RMS doesn't have an agenda?  That's really
interesting.  I think even he would disagree.

> - even better
> if that agenda can be blended in the popular imagination with those
> aforementioned kinds of undesirable people - while doing as much as
> they can to conceal their own.

My primary agenda is to explain that RMS does, in fact, have an
agenda, and the GPL was designed as a tool in furtherance of that
agenda, and that while the agenda does have some arguably noble goals,
before using the GPL people should understand its consequences both
for good and bad, and make their own determination about whether it's
the right license for their project.

Regards,
Pat


From albertkao3 at gmail.com  Thu May 13 16:10:30 2010
From: albertkao3 at gmail.com (albert kao)
Date: Thu, 13 May 2010 13:10:30 -0700 (PDT)
Subject: walk directory & ignore all files/directories begin with '.'
References: 
	
Message-ID: <6069b900-88a5-4cc7-ab82-bfe8ccabd68b@d27g2000yqc.googlegroups.com>

On May 13, 3:10?pm, MRAB  wrote:
> albert kao wrote:
> > I want to walk a directory and ignore all the files or directories
> > which names begin in '.' (e.g. '.svn').
> > Then I will process all the files.
> > My test program walknodot.py does not do the job yet.
> > Python version is 3.1 on windows XP.
> > Please help.
>
> > [code]
> > #!c:/Python31/python.exe -u
> > import os
> > import re
>
> > path = "C:\\test\\com.comp.hw.prod.proj.war\\bin"
> > for dirpath, dirs, files in os.walk(path):
> > ? ? print ("dirpath " + dirpath)
> > ? ? p = re.compile('\\\.(\w)+$')
> > ? ? if p.match(dirpath):
> > ? ? ? ? continue
> > ? ? print ("dirpath " + dirpath)
> > ? ? for dir in dirs:
> > ? ? ? ? print ("dir " + dir)
> > ? ? ? ? if dir.startswith('.'):
> > ? ? ? ? ? ? continue
>
> > ? ? ? ? print (files)
> > ? ? ? ? for filename in files:
> > ? ? ? ? ? ? print ("filename " + filename)
> > ? ? ? ? ? ? if filename.startswith('.'):
> > ? ? ? ? ? ? ? ? continue
> > ? ? ? ? ? ? print ("dirpath filename " + dirpath + "\\" + filename)
> > ? ? ? ? ? ? ? ?# process the files here
> > [/code]
>
> > C:\python>walknodot.py
> > dirpath C:\test\com.comp.hw.prod.proj.war\bin
> > dirpath C:\test\com.comp.hw.prod.proj.war\bin
> > dir .svn
> > dir com
> > []
> > dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> > dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> > ...
>
> > I do not expect C:\test\com.comp.hw.prod.proj.war\bin\.svn to appear
> > twice.
> > Please help.
>
> The problem is with your use of the 'match' method, which will look for
> a match only at the start of the string. You need to use the 'search'
> method instead.
>
> The regular expression is also incorrect. The string literal:
>
> ? ? ?'\\\.(\w)+$'
>
> passes the characters:
>
> ? ? ?\\.(\w)+$
>
> to the re module as the regular expression, which will match a
> backslash, then any character, then a word, then the end of the string.
> What you want is:
>
> ? ? ?\\\.\w+$
>
> (you don't need the parentheses) which is best expressed as the 'raw'
> string literal:
>
> ? ? ?r'\\\.\w+$'
Following your advice and add the case for C:\test
\com.comp.hw.prod.proj.war\bin\.svn\tmp
    p = re.compile(r'\\\.\w+$')
    if p.search(dirpath):
        continue
    p = re.compile(r'\\\.\w+\\')
    if p.search(dirpath):
        continue

Problem is solved.
Thanks.


From albertkao3 at gmail.com  Thu May 13 16:12:40 2010
From: albertkao3 at gmail.com (albert kao)
Date: Thu, 13 May 2010 13:12:40 -0700 (PDT)
Subject: use only files but ignore directories on Windows
Message-ID: <1f3324a2-009b-4fac-b900-ffbfedae3d9a@24g2000yqy.googlegroups.com>

My program plan to use only files but ignore directories on Windows.
I google but do not find some functions like
bool isFile(string)
bool isDirectory(string)
Please help.


From malaclypse2 at gmail.com  Thu May 13 16:30:47 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Thu, 13 May 2010 16:30:47 -0400
Subject: use only files but ignore directories on Windows
In-Reply-To: <1f3324a2-009b-4fac-b900-ffbfedae3d9a@24g2000yqy.googlegroups.com>
References: <1f3324a2-009b-4fac-b900-ffbfedae3d9a@24g2000yqy.googlegroups.com>
Message-ID: 

On Thu, May 13, 2010 at 4:12 PM, albert kao  wrote:
> My program plan to use only files but ignore directories on Windows.
> I google but do not find some functions like
> bool isFile(string)
> bool isDirectory(string)
> Please help.

You're looking for the functions os.path.isfile() and os.path.isdir()

See http://docs.python.org/library/os.path.html for details.

-- 
Jerry


From prologic at shortcircuit.net.au  Thu May 13 16:30:51 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 14 May 2010 06:30:51 +1000
Subject: use only files but ignore directories on Windows
In-Reply-To: <1f3324a2-009b-4fac-b900-ffbfedae3d9a@24g2000yqy.googlegroups.com>
References: <1f3324a2-009b-4fac-b900-ffbfedae3d9a@24g2000yqy.googlegroups.com>
Message-ID: 

On Fri, May 14, 2010 at 6:12 AM, albert kao  wrote:
> My program plan to use only files but ignore directories on Windows.
> I google but do not find some functions like
> bool isFile(string)
> bool isDirectory(string)
> Please help.

Try looking up the os module.

cheers
James


From oxfordenergyservices at googlemail.com  Thu May 13 17:00:02 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Thu, 13 May 2010 14:00:02 -0700 (PDT)
Subject: stopping execution window on error - newbie
Message-ID: <101459d0-92cb-40d4-ad6d-6f82a70b167d@l31g2000yqm.googlegroups.com>

I'm coding on an old windows laptop

i write the code and double click the icon.  it runs the program and
writes results to a window.

when the code finishes, the window closes, i do a time.sleep(10) to
see what has happened.

unfortunately when there is an error it just closes the window.
anyway of seeing the error messages?

thanks

a


From landimatte at gmail.com  Thu May 13 17:12:00 2010
From: landimatte at gmail.com (Matteo Landi)
Date: Thu, 13 May 2010 23:12:00 +0200
Subject: stopping execution window on error - newbie
In-Reply-To: <101459d0-92cb-40d4-ad6d-6f82a70b167d@l31g2000yqm.googlegroups.com>
References: <101459d0-92cb-40d4-ad6d-6f82a70b167d@l31g2000yqm.googlegroups.com>
Message-ID: 

Place a try .. except surrounding the body of your program, and finally call
the input() function.

On Thu, May 13, 2010 at 11:00 PM, a wrote:

> I'm coding on an old windows laptop
>
> i write the code and double click the icon.  it runs the program and
> writes results to a window.
>
> when the code finishes, the window closes, i do a time.sleep(10) to
> see what has happened.
>
> unfortunately when there is an error it just closes the window.
> anyway of seeing the error messages?
>
> thanks
>
> a
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From mark.engelberg at gmail.com  Thu May 13 18:19:41 2010
From: mark.engelberg at gmail.com (puzzler)
Date: Thu, 13 May 2010 15:19:41 -0700 (PDT)
Subject: Tkinter - paste from clipboard not working
Message-ID: 

I have written a very simple GUI in Python / Tkinter, running under
Python 2.5.4 on Windows.

The GUI is essentially a big Tix.ScrolledText area, where you can
enter some text, and a button underneath to process the text.  (The
button causes the text to be looked up in a SQLite database, and some
stats are generated and displayed in a web browser).

One of my users is reporting to me that intermittently, he loses the
ability to paste text into the Tix.ScrolledText area.  He says that
copy and paste works in all his other applications, but suddenly it
will not work in my app's text widget.  Even weirder, he says that
once the ability to paste goes away, it will not work *until he
reboots his computer*.

Even if there's some sort of bug with my app, I can't think of any way
that this problem could persist across stopping and starting the
program.  Seems like restarting the program should put things back
into a pristine state.  So I'm beginning to wonder if there's some
sort of deeper bug with Tkinter or Tix?  How could this bug persist
until a reboot?  Does Python run some background service to handle Tk
calls that remains running across Python instantiations?

Any ideas or suggestions would be most appreciated.  Thanks!


From mensanator at aol.com  Thu May 13 19:14:32 2010
From: mensanator at aol.com (Mensanator)
Date: Thu, 13 May 2010 16:14:32 -0700 (PDT)
Subject: stopping execution window on error - newbie
References: <101459d0-92cb-40d4-ad6d-6f82a70b167d@l31g2000yqm.googlegroups.com>
Message-ID: <3fd705f1-2b3b-4b2b-b48d-06a6700a76be@g21g2000yqk.googlegroups.com>

On May 13, 4:00?pm, a  wrote:
> I'm coding on an old windows laptop
>
> i write the code and double click the icon. ?

Don't do that.

> it runs the program and
> writes results to a window.
>
> when the code finishes, the window closes, i do a time.sleep(10) to
> see what has happened.
>
> unfortunately when there is an error it just closes the window.
> anyway of seeing the error messages?

Go to the windows [Start] button. Select [Run...] and in the popup
box,
type "cmd" as the program to run. This will open a DOS shell window (a
text window.)

Then you can run your Python script from the window prompt and it
won't
close until you manually close it, even if the program crashes.

For example, once I open the DOS shell...


Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

H:\>C:

C:\>cd python31\user\lotto

C:\Python31\user\lotto>dir
 Volume in drive C has no label.
 Volume Serial Number is 06DE-55B4

 Directory of C:\Python31\user\lotto

05/13/2010  05:53 PM              .
05/13/2010  05:53 PM              ..
08/19/2009  07:08 PM             3,334 lotto.py
05/13/2010  05:56 PM             6,068 lotto_2010.py
               2 File(s)          9,402 bytes
               2 Dir(s)  102,247,440,384 bytes free

C:\Python31\user\lotto>..\..\python lotto_2010.py

{1: 2, 2: 3, 3: 2, 4: 1, 5: 2, 6: 1, 7: 2, 8: 1, 9: 1, 10: 2, 11: 2,
13: 1, 14: 2, 17: 1, 18: 2, 19: 1, 20: 1, 21: 1, 22: 1, 24: 1, 25: 1,
26: 3, 27: 1, 28: 2, 29: 2, 30: 1, 31: 1, 32: 1, 34: 1, 35: 1, 37: 2,
38: 2, 39: 2, 40: 1, 42: 2, 43: 1, 44: 2, 46: 2, 47: 1, 48: 1, 50: 1,
51: 2, 52: 3}

 1  2 **
 2  3 ***
 3  2 **
 4  1 *
 5  2 **
 6  1 *
 7  2 **
 8  1 *
 9  1 *
10  2 **
11  2 **
12
13  1 *
14  2 **
15
16
17  1 *
18  2 **
19  1 *
20  1 *
21  1 *
22  1 *
23
24  1 *
25  1 *
26  3 ***
27  1 *
28  2 **
29  2 **
30  1 *
31  1 *
32  1 *
33
34  1 *
35  1 *
36
37  2 **
38  2 **
39  2 **
40  1 *
41
42  2 **
43  1 *
44  2 **
45
46  2 **
47  1 *
48  1 *
49
50  1 *
51  2 **
52  3 ***


(7, 21, 50, 36, 26, 3)
(7, 21, 50, 36, 26, 17)
(7, 21, 50, 36, 26, 52)
(7, 21, 50, 36, 3, 17)
(7, 21, 50, 36, 3, 52)
(7, 21, 50, 36, 17, 52)
(7, 21, 50, 26, 3, 17)
(7, 21, 50, 26, 3, 52)
(7, 21, 50, 26, 17, 52)
(7, 21, 50, 3, 17, 52)
(7, 21, 36, 26, 3, 17)
(7, 21, 36, 26, 3, 52)
(7, 21, 36, 26, 17, 52)
(7, 21, 36, 3, 17, 52)
(7, 21, 26, 3, 17, 52)
(7, 50, 36, 26, 3, 17)
(7, 50, 36, 26, 3, 52)
(7, 50, 36, 26, 17, 52)
(7, 50, 36, 3, 17, 52)
(7, 50, 26, 3, 17, 52)
(7, 36, 26, 3, 17, 52)
(21, 50, 36, 26, 3, 17)
(21, 50, 36, 26, 3, 52)
(21, 50, 36, 26, 17, 52)
(21, 50, 36, 3, 17, 52)
(21, 50, 26, 3, 17, 52)
(21, 36, 26, 3, 17, 52)
(50, 36, 26, 3, 17, 52)


 8  9 32 38 40 48
13 22 28 39 42 43
 1  2  5 11 18 52 +
 2  3 26 44 51 52 +++
 4  7 14 26 35 52 +++
 2  7 10 19 42 47 +
 5 20 31 34 50 51 +
 1 28 29 37 39 46
10 11 27 37 38 46
 6 21 24 29 30 44 +
 3 14 17 18 25 26 +++
 7 10 39 42 45 46 +
15 17 23 36 38 44 ++
16 19 23 27 41 49
15 25 32 36 44 47 +
16 19 24 29 38 41
 3  4  8 13 43 49 +
 2 11 17 19 22 50 ++
14 21 22 28 30 45 +
 4 15 21 34 47 49 +
19 34 38 39 40 48
 4 16 24 33 37 48
 8 16 17 18 39 40 +
 1 24 27 30 31 47
 1  7 11 21 30 43 ++
 1  8 13 18 32 36 +
 5 10 12 16 20 21 +
 7 11 23 24 26 35 ++
 7  8 11 13 42 49 +
 1  8 17 34 40 50 ++
 1 24 29 35 41 45
15 17 24 32 44 52 ++
 4 12 21 26 33 38 ++
 2 13 15 41 48 50 +
 2  7  9 27 45 52 ++
24 25 35 36 39 42 +
 8 22 39 40 42 48
16 18 29 30 34 43
 7 21 28 36 45 50 ++++
 4  8 30 35 39 42
 2 11 15 23 40 51
 2  7 14 18 23 34 +
 1 11 22 37 41 50 +
 4 34 40 44 50 52 ++
12 28 33 39 40 52 +
14 18 25 36 38 39 +
 4 11 16 17 27 37 +
 1 11 16 28 31 36 +
 8 16 31 34 36 52 ++
 7 10 15 21 35 36 +++
 2  9 21 23 29 30 +
15 29 33 41 46 47
 2  5 18 34 36 39 +
 7 15 21 31 45 50 +++
12 17 20 28 39 51 +
 3  7 22 26 50 52 +++++
 1  5 21 27 31 39 +
 2  8 10 23 34 50 +
 1 11 24 26 32 52 ++
 1 18 20 38 41 42
12 33 36 42 45 48 +
 1  6 21 28 37 39 +
16 18 19 22 33 35
 2  7 17 27 29 47 ++
15 19 20 25 42 45
 2  6 17 19 20 41 +
 1 13 34 42 43 46
16 29 30 31 34 47
 5  7 26 29 36 46 +++
 1 27 28 30 31 49
 8 17 19 47 49 52 ++
 5 23 32 41 42 45
11 13 22 29 40 46
16 17 18 20 41 43 +
 3 17 26 38 45 52 ++++
13 18 21 38 39 41 +
14 19 28 40 44 51
 4  8  9 36 43 47 +
 1  9 15 24 36 39 +
 4 31 37 41 42 43
 7 12 18 27 36 42 ++
 3  4 26 27 35 51 ++
 7 12 19 23 26 45 ++
19 28 36 39 42 52 ++
 8 17 21 44 46 51 ++
 2  4 18 19 36 49 +
 1  4 11 16 22 35
13 14 17 18 41 46 +
 8 16 23 29 43 48
 1  8 25 36 37 44 +
 7 20 21 23 36 50 ++++
 3  7 23 27 39 43 ++
 4 10 21 37 38 48 +
 6 18 30 35 36 42 +
 3 14 23 43 46 48 +
10 11 19 26 42 46 +
 1  5 27 34 42 45
 1 16 29 33 40 46
32 41 43 45 48 51
 1 13 23 24 46 49
24 25 28 30 32 40
 8 14 20 33 50 52 ++
 2 16 27 28 33 39
13 17 19 32 43 52 ++
10 11 16 43 45 49
 2  4 20 22 35 44
 1 12 18 36 37 40 +
 8 10 16 22 35 47
 8 11 16 31 45 46
11 13 22 25 26 27 +
 3 17 25 26 29 40 +++
 7 10 27 37 46 47 +
 3  5  7 27 33 40 ++
 4 14 28 37 40 44
18 22 25 33 43 48
11 19 26 30 44 50 ++
 3 11 22 42 46 51 +
 7  8 21 26 30 50 ++++
 6 13 15 23 37 39
12 17 31 37 43 47 +
 2  7 11 21 33 42 ++
 2 21 26 37 39 50 +++
 6 26 37 38 42 46 +
18 19 24 34 40 49
 2  9 12 17 31 42 +
 5 14 30 32 34 49
 7 14 29 41 49 50 ++
 3  7 43 45 46 47 ++
12 22 31 37 40 51
 1  3  5 11 28 46 +
 6  7 12 22 30 32 +
13 18 20 25 26 49 +
14 19 22 41 49 50 +
 3  4 12 20 39 42 +
 9 18 31 44 46 49
 9 20 24 27 41 45
 6  8 27 31 45 52 +
22 34 35 40 41 42
 1  8 15 37 38 45
 6  9 13 16 35 51
 6 14 17 30 33 52 ++
14 27 31 34 40 51
 2 11 21 34 36 46 ++
 1  3 12 15 47 51 +
 4  5 26 30 32 37 +
 4 10 18 29 37 51
 8 33 35 36 39 43 +
 9 17 22 23 40 52 ++
 3 31 34 38 47 50 ++
21 26 27 33 41 50 +++
 1 10 15 26 40 43 +
 9 15 17 25 40 42 +
 6 11 23 26 30 45 +
 1  5  9 33 44 51
13 15 20 22 27 48
 3  5 10 11 17 32 ++

C:\Python31\user\lotto>


Now I can study the output for as long as I want.

Also, I could have done this:

    C:\Python31\user\lotto>..\..\python lotto_2010.py >
lotto_output.txt

and directed the output to a file for editing and/or printing.

>
> thanks
>
> a



From 007brendan at gmail.com  Thu May 13 19:30:35 2010
From: 007brendan at gmail.com (Brendan Abel)
Date: Thu, 13 May 2010 16:30:35 -0700 (PDT)
Subject: Picking a license
References: 
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
Message-ID: <7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>

While I think most of the disagreement in this long thread results
from different beliefs in what "freedom" means, I wanted to add, that
most of the responses that argue that the MIT license permits the user
more freedom than the GPL, suffer from the broken window fallacy.
This fallacy results from the short-sided-ness of the user base, as it
is only considering the first generation of derivative works.

I agree, that under an MIT license, the first generation of derivative
works have more freedom.  But any extra freedom gained here comes at
the direct expense of all future generations of derivative software.

Under a GPL license, it is true that the first generation will have
less freedom to distribute their software as they would like.  But it
also ensures that all subsequent generations of derivative works have
the freedom to access all previous derivative works.

I also want to add that I think the GPL v3 has exceeded this
fundamental concept.  GPL v2 really embodies this meaning of "freedom".


From steven at REMOVE.THIS.cybersource.com.au  Thu May 13 19:39:42 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 13 May 2010 23:39:42 GMT
Subject: Picking a license
References: 
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
Message-ID: 

On Thu, 13 May 2010 08:06:52 -0700, Patrick Maupin wrote:

> If I download an Ubuntu
> ISO, burn it and give it away (let's say I give away 100 copies, just to
> remove the fair use defense), then I have violated the GPL.  I provided
> chapter and verse on this; go look it up.

I'm sorry, I can't see where you have provided "chapter and verse", or 
even a URL.


>> If you compiled the CD yourself, and failed to provide a written offer
>> on the CD, then yes absolutely you would be in violation of the licence
>> terms, and shame on you.
> 
> Not relevant.

You didn't specify whether the "Linux CD" you were distributing was a 
mere copy of an existing CD , or one you created yourself, so you will 
pardon me for covering both possibilities.


>> The GPL doesn't require you to force source code on those who don't
>> want it, but it does require you to make it available if they ask, and
>> for you to notify them appropriately of this fact. You don't even have
>> to explicitly tell your friend he can have the source code. You just
>> have to make sure that the written offer is available on the disk you
>> give him.
> 
> There is no written offer on the disk, because I burned it from Ubuntu's
> repository.  It really is that simple -- if I give away copies I've made
> of Ubuntu, I've violated the GPL.

No, I think this use-case would count as "propagation without conveying", 
since you are merely acting as a mechanical proxy between your friend(s) 
and Ubuntu.

I will admit that the GPL FAQs are not as clear about this matter as they 
should be.



> Unless you can cite some authority
> that tells me I'm wrong and gives real reasons.  I actually quoted
> chapter and verse from the license, but you chose to ignore that and
> make unsubstantiated claims.

I'm sorry, I can't find where you have quoted "chapter and verse" from 
the licence, so I can't comment.



[snip]
>> but imagine if everyone did it, if Red Hat and Debian and Ubuntu etc
>> didn't bother passing on the source code (or a written offer).
> 
> Then somebody else would.  How does Apache work?

Apache is niche software, and sadly its popularity is falling 
significantly. (~200 million webservers is a large niche, but it's still 
a niche.) The scales on the Netcraft graph are useless, so I can't read 
accurate numbers, but it looks like it has fallen from approximately a 
75% market share to under 55%.

http://news.netcraft.com/archives/web_server_survey.html

Perhaps the Apache model doesn't work quite as well as you think?

As far as not-so-niche software goes, the GPLed Linux OS is far more 
popular on the desktop than FreeBSD and OpenBSD together, and about equal 
in popularity to Mac OS. I'm not suggesting that the popularity of an OS 
is *entirely* dependent on the licence, but it may be a factor.



>> Only a
>> tiny proportion of people would discover by their own efforts that the
>> source code was available
> 
> No, I tell my friends that source is available, and they can come and
> see me if they want to know more.

That doesn't scale to distributing hundreds of copies of the CD, let 
alone tens of thousands. If you're handing over a single copy to a friend 
(which is the example you gave earlier) then a verbal offer works well, 
and is only a technical breach of the GPL. If you're distributing 
hundreds of copies, I don't believe any such verbal offer is practical.


> This may have been a viable argument
> in 1989 (doubtful) but it's extremely silly today.

So you say.


>>, and only a proportion of them would learn
>> where it was available from. The result in practical terms would be a
>> major decrease in the number of people granted the freedom to modify
>> the source code, and a correspondingly larger decrease in the number of
>> people both free and able to modify the source code.
> 
> I sincerely doubt your dystopian vision, which, like the GPL and many
> laws, is predicated on some outmoded views about how humans interact.
> 
> The reason some people say that the GPL protects the "freedom of the
> code" is because the GPL assumes that code needs to be nurtured, instead
> of taking the viewpoint that, while there may be some freeloaders,
> sharing code is obviously so valuable to most of humanity that it will
> just happen.  We don't live in medieval Europe any more where the rules
> of glassmaking are so secret that you'll be hunted down like a dog if
> you try to leave.  We live in a world where "co- opetition" has been
> shown to be so valuable we had to make up a word for it, and even for
> those secrets that people are willing to kill to keep, we have
> wikileaks.

I admire your optimism, but don't share it.


> Let's face it -- a software freeloader is not the most evil thing in the
> world.  

*A* software freeloader certainly isn't a big problem. Cutting down *a* 
tree is no big deal either, but consider what happened to the people of 
Easter Island, Ethiopia and Haiti when *everyone* did so. The terms of 
the GPL exist to discourage freeloaders, lest everyone does so. The 
obligations it imposes are not onerous by any stretch of the exaggeration.


>> It's not enough to be granted freedom to modify source code in theory,
>> if you know about it, if you can find some hard-to-locate website which
>> may or may not be running. The practicalities are equally important.
> 
> That's another thing.  Even if I downloaded all the source from Ubuntu,
> what assurances do I really have that I have all the source? I could be
> in technical violation of the GPL without even knowing it, even after
> wasting an extra two days grabbing the source.  Best to use Gentoo to be
> sure, and even then, I need to build it twice running strace just to
> make sure that I really built everything.

That's a silly objection to the GPL. When you include an MIT-licenced 
library in your project, you can't be sure that the library wasn't stolen 
from Microsoft and you've therefore accidentally infringed Microsoft's 
copyright. This isn't an argument against the MIT licence any more than 
your hypothetical is an argument against the GPL.



>> In
>> theoretical terms, everyone has the freedom to legally modify and
>> distribute the source code to Microsoft Windows. All you have to do is
>> buy 51% of the stock so as to become majority shareholder, then make
>> sufficient changes to the board of directors so that the new board
>> grants you a licence to do so, then fight off the lawsuits from the
>> rest of the shareholders. Anyone could do it! Not.
> 
> So "everyone" could own 51% of Microsoft?  That means 100% of the shares
> would be around 350,000,000,000%.  Wait, that can't be right, what? :-) 

Obviously not all at once, silly. But "in theory", everyone could become 
the majority shareholder -- there is no law or physical law of nature 
that says "Patrick Maupin is prohibited from being majority shareholder 
of Microsoft".

Anti-competition laws or similar may prevent a person from becoming 
majority shareholder unless they (e.g.) gave up their shares in another 
company, but again, there's nothing stopping them from doing so, if they 
wished.


> Can you come up with a sillier analogy?

I'm sure I could, but you seem to have entirely missed the point that 
such theoretical "freedom" is entirely illusionary, since *in practice* 
very few people actually can partake in it.

 
>> Another, more practical example: here in Australia our government is
>> hell- bent on introducing an ineffective and expensive Internet
>> censorship scheme. It seems that under Australian law, it will be
>> completely legal to circumvent the filter, but our government is
>> investigating ways to make it illegal to tell anyone how to circumvent
>> it. In other words, Australians will have permission to circumvent the
>> nanny filter, but since few people will know this, or know how to do
>> so, it will be a meaningless freedom.
> 
> Yes, that's basically how the DMCA works, and that's evil, and that's
> one of the reasons I sometimes give money to the EFF.  But, you can't
> seriously be comparing making speech a crime and making not speaking a
> crime (or a copyright violation), can you?  Maybe you *did* manage to
> come up with a sillier analogy...

There are situations where not speaking is a crime. If you witness a 
crime, and fail to report it, there are circumstances where you may be 
liable to be persecuted for aiding and abetting.



>> The GPL concerns itself with the *practical* freedom to gain access to
>> source code, not merely the theoretical freedom represented by
>> permission without opportunity.
> 
> No, the GPL is ideologically opposed to anything related to practicality
> (although in practice, its adherents have to bend a bit to avoid being
> made irrelevant, and Linux, the shining success, is led by someone who
> arguably cares not one whit for GPL ideological purity).

And yet Linux is distributed under the GPL, which pretty much sinks your 
argument.


[...]
> But the GPL wording required to enforce what you call a practical
> freedom imposes so many impractical costs that there are probably
> millions of people in the world who have violated this license, in the
> good-faith attempt to spread free software around.

As I admitted earlier, there is an apparent grey area there, at least 
according to the FAQs, but I don't think it is anywhere near as obvious 
as you claim that it is a licence violation.




-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Thu May 13 19:41:47 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 13 May 2010 23:41:47 GMT
Subject: Picking a license
References: 
Message-ID: 

On Thu, 13 May 2010 06:24:04 -0700, Ed Keith wrote:

> --- On Thu, 5/13/10, Lawrence D'Oliveiro
>  wrote:
>>
>> What have you got against LGPL for this purpose? --
>> 
> Most of my clients would not know how to relink a program if their life
> depended on it. And I do not want to put then in DLL hell. So I avoid
> the LGPL.


Are you implying that by distributing your libraries under the MIT or 
Apache licence, no linking is required? That's a cool trick, can you 
explain how it works please?



-- 
Steven


From ethan at stoneleaf.us  Thu May 13 20:12:48 2010
From: ethan at stoneleaf.us (Ethan Furman)
Date: Thu, 13 May 2010 17:12:48 -0700
Subject: Picking a license
In-Reply-To: 
References: 
	
Message-ID: <4BEC9580.1030900@stoneleaf.us>

Steven D'Aprano wrote:
> On Thu, 13 May 2010 06:24:04 -0700, Ed Keith wrote:
> 
>> --- On Thu, 5/13/10, Lawrence D'Oliveiro
>>  wrote:
>>> What have you got against LGPL for this purpose? --
>>>
>> Most of my clients would not know how to relink a program if their life
>> depended on it. And I do not want to put then in DLL hell. So I avoid
>> the LGPL.
> 
> 
> Are you implying that by distributing your libraries under the MIT or 
> Apache licence, no linking is required? That's a cool trick, can you 
> explain how it works please?

I believe he is implying that with MIT or Apache, he is able to do all 
the compiling/linking/generating himself, thus saving his customers the 
effort.

You're a smart man, Steven, surely you could have figured that out?  ;)

~Ethan~


From ethan at stoneleaf.us  Thu May 13 20:12:54 2010
From: ethan at stoneleaf.us (Ethan Furman)
Date: Thu, 13 May 2010 17:12:54 -0700
Subject: Picking a license
In-Reply-To: <7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
References: 	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
Message-ID: <4BEC9586.3070302@stoneleaf.us>

Brendan Abel wrote:
> While I think most of the disagreement in this long thread results
> from different beliefs in what "freedom" means, I wanted to add, that
> most of the responses that argue that the MIT license permits the user
> more freedom than the GPL, suffer from the broken window fallacy.
> This fallacy results from the short-sided-ness of the user base, as it
> is only considering the first generation of derivative works.
> 
> I agree, that under an MIT license, the first generation of derivative
> works have more freedom.  But any extra freedom gained here comes at
> the direct expense of all future generations of derivative software.

You are assuming that _all_ future generations become propriety, then? 
How pessimistic.


> Under a GPL license, it is true that the first generation will have
> less freedom to distribute their software as they would like.  But it
> also ensures that all subsequent generations of derivative works have
> the freedom to access all previous derivative works.

Just because you have the code for the _current_ version of something, 
doesn't mean you have the code for that something three versions ago... 
after all, it may have been modified.


~Ethan~


From info at wingware.com  Thu May 13 20:17:40 2010
From: info at wingware.com (Wingware)
Date: Thu, 13 May 2010 20:17:40 -0400
Subject: ANN: Wing IDE 3.2.7 released
Message-ID: <4BEC96A4.2040905@wingware.com>

Hi,

Wingware has released version 3.2.7 of Wing IDE, an integrated development
environment designed specifically for the Python programming language.

Wing IDE is a cross-platform Python IDE that provides a professional code
editor with vi, emacs, and other key bindings, auto-completion, call tips,
a powerful graphical debugger, version control, unit testing, search, and
many other features.

This release includes the following minor features and improvements:

* Added preference to control mini-search case sensitivity
* Added Debug to Here editor context menu item and Alt-F5 binding
* Fixed parsing of "from package.module import *" statements
* Fixed shared perspectives
* Improved default extension set in Windows file dialogs
* Several VI mode improvements (details in change log)
* Several Templates tool fixes (details in change log)
* Confirm close of Feedback and Bug Report windows
* Fix up and down arrow keys in Debug I/O tool
* Several other minor bug fixes

See the change log at http://wingware.com/pub/wingide/3.2.7/CHANGELOG.txt
for details

*Downloads*

Wing IDE Professional and Wing IDE Personal are commercial software and
require a license to run.  A free trial license can be obtained directly 
from
the product when launched.  Wing IDE 101 can be used free of charge.

Wing IDE Pro 3.2.7        http://wingware.com/downloads/wingide/3.2

Wing IDE Personal 3.2.7   http://wingware.com/downloads/wingide-personal/3.2

Wing IDE 101 3.2.7        http://wingware.com/downloads/wingide-101/3.2

*About Wing IDE*

Wing IDE is an integrated development environment designed specifically for
the Python programming language. It provides powerful editing, testing, and
debugging features that help reduce development and debugging time, cut down
on coding errors, and make it easier to understand and navigate Python code.
Wing IDE can be used to develop Python code for web, GUI, and embedded
scripting applications.

Wing IDE is available in three product levels:  Wing IDE Professional is
the full-featured Python IDE, Wing IDE Personal offers a reduced feature
set at a low price, and Wing IDE 101 is a free simplified version designed
for teaching entry level programming courses with Python.

Version 3.2 of Wing IDE Professional includes the following major features:

* Professional quality code editor with vi, emacs, and other keyboard 
personalities
* Code intelligence for Python:  Auto-completion, call tips, 
goto-definition,
  error indicators, smart indent and rewrapping, and source navigation
* Advanced multi-threaded debugger with graphical UI, command line 
interaction,
  conditional breakpoints, data value tooltips over code, watch tool, and
  externally launched and remote debugging
* Powerful search and replace options including keyboard driven and 
graphical
  UIs, multi-file, wild card, and regular expression search and replace
* Version control integration for Subversion, CVS, Bazaar, git, 
Mercurial, and
  Perforce
* Integrated unit testing with unittest, nose, and doctest frameworks
* Many other features including project manager, bookmarks, code snippets,
  OS command integration, indentation manager, PyLint integration, and 
perspectives
* Extremely configurable and may be extended with Python scripts

Please refer to the feature list at http://wingware.com/wingide/features for
a detailed listing of features by product level.

System requirements are Windows 2000 or later, OS X 10.3.9 or later for 
PPC or
Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit).
Wing IDE supports Python versions 2.0.x through 3.1.x and Stackless Python.

For more information, see http://wingware.com/products

*Purchasing and Upgrading*

Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Version 2.x
licenses cost 1/2 the normal price to upgrade.

Upgrade a 2.x license:     https://wingware.com/store/upgrade

Purchase a 3.x license:    https://wingware.com/store/purchase

-- 

The Wingware Team
Wingware | Python IDE
Advancing Software Development

www.wingware.com



From python.list at tim.thechases.com  Thu May 13 20:18:16 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Thu, 13 May 2010 19:18:16 -0500
Subject: indexing lists/arrays question
In-Reply-To: <994e3852-637d-4bfd-96db-dd2e74c12cd2@e2g2000yqn.googlegroups.com>
References: 			
	<994e3852-637d-4bfd-96db-dd2e74c12cd2@e2g2000yqn.googlegroups.com>
Message-ID: <4BEC96C7.2010602@tim.thechases.com>

On 05/13/2010 12:51 PM, a wrote:
>> If your two arrays are of the same length, you can do things like
>>
>>     a = [2,3,3,4,5,6]
>>     b = ['a', 'b', 'c', 'd', 'e', 'f']
>>
>>     print [m for (n,m) in zip(a,b) if n == 3]
>>
>> and skip the indexes altogether.
>
> mmm, that's clever, thanks.  although i don't know why it works yet.
> at least i found a good user group!

the zip() function takes its parameters and returns a list 
containing paired items from each list:

 >>> print zip(a,b) # using the above-defined a/b
[(2, 'a'), (3, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f')]

The list comprehension then iterates over the elements of that 
list, assigned as (n,m), testing "n" (the numeric value you want 
to test) and returning "m" (the corresponding value in "b")

-tkc





From pavlovevidence at gmail.com  Thu May 13 20:18:47 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Thu, 13 May 2010 17:18:47 -0700 (PDT)
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
Message-ID: <59194ade-46dc-4178-8b76-36038808109b@k2g2000yqe.googlegroups.com>

On May 13, 4:30?pm, Brendan Abel <007bren... at gmail.com> wrote:
> While I think most of the disagreement in this long thread results
> from different beliefs in what "freedom" means, I wanted to add, that
> most of the responses that argue that the MIT license permits the user
> more freedom than the GPL, suffer from the broken window fallacy.
> This fallacy results from the short-sided-ness of the user base, as it
> is only considering the first generation of derivative works.
>
> I agree, that under an MIT license, the first generation of derivative
> works have more freedom. ?But any extra freedom gained here comes at
> the direct expense of all future generations of derivative software.
>
> Under a GPL license, it is true that the first generation will have
> less freedom to distribute their software as they would like. ?But it
> also ensures that all subsequent generations of derivative works have
> the freedom to access all previous derivative works.

I believe the you have the fallacy backwards.

The thing you GPL fanbois refuse to understand or accept is that, in
the real world, a person or company who doesn't want to open source
their "derivative work" will only rarely be forced to by the GPL.
They'll work around it instead, vast majority of the time.  They
could:

1. Derive their work from a project with a license that grants the
user more freedom
2. Reimplment the functionality seperately (*cough* PySide)
3. Ignore the license

And no, a small number of anecdotal counterexamples is not any strong
evidence to the contrary.

On the other hand, those who intended to release their work as open
source are going to do it even if the license is permissive.  The way
some of you GPL fanbois talk you'd think the MIT license prohibitied
open source derivatives.

So, you see, the rights given to users of first generation works (as
you say) are far more important than requiring people who create
"derivatives" to also offer those rights.  Those who intend to do that
will anyways, those who don't intend to will find a way not to.


Carl Banks

PS The word "derivative" is quoted throught because the GPL's
definition of "derivative" is ludicrous and not in accordance any
common defintion of the word.


From python.list at tim.thechases.com  Thu May 13 20:35:59 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Thu, 13 May 2010 19:35:59 -0500
Subject: walk directory & ignore all files/directories begin with '.'
In-Reply-To: 
References: 
Message-ID: <4BEC9AEF.1080907@tim.thechases.com>

On 05/13/2010 12:58 PM, albert kao wrote:
> I want to walk a directory and ignore all the files or directories
> which names begin in '.' (e.g. '.svn').
> Then I will process all the files.
> My test program walknodot.py does not do the job yet.
> Python version is 3.1 on windows XP.
> Please help.
>
> [code]
> #!c:/Python31/python.exe -u
> import os
> import re
>
> path = "C:\\test\\com.comp.hw.prod.proj.war\\bin"
> for dirpath, dirs, files in os.walk(path):
>      print ("dirpath " + dirpath)
>      p = re.compile('\\\.(\w)+$')
>      if p.match(dirpath):
>          continue
>      print ("dirpath " + dirpath)
>      for dir in dirs:
>          print ("dir " + dir)
>          if dir.startswith('.'):
>              continue
>
>          print (files)
>          for filename in files:
>              print ("filename " + filename)
>              if filename.startswith('.'):
>                  continue
>              print ("dirpath filename " + dirpath + "\\" + filename)
>      	    # process the files here
> [/code]
>
> C:\python>walknodot.py
> dirpath C:\test\com.comp.hw.prod.proj.war\bin
> dirpath C:\test\com.comp.hw.prod.proj.war\bin
> dir .svn
> dir com
> []
> dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> dirpath C:\test\com.comp.hw.prod.proj.war\bin\.svn
> ...
>
> I do not expect C:\test\com.comp.hw.prod.proj.war\bin\.svn to appear
> twice.

Note that the first time .svn appears, it's as "dir .svn" while 
the second time it appears, it's via "dirpath ...\.svn"

If you don't modify the list of dirs in place, os.walk will 
descend into all the dirs by default.  (Also, you shouldn't mask 
the built-in dir() function by naming your variables "dir")

While it can be detected with regexps, I like the clarity of just 
using ".startswith()" on the strings, producing something like:

   for curdir, dirs, files in os.walk(root):
     # modify "dirs" in place to prevent
     # future code in os.walk from seeing those
     # that start with "."
     dirs[:] = [d for d in dirs if not d.startswith('.')]

     print curdir
     for f in files:
       if f.startswith('.'): continue
       print (os.path.join(curdir, f))

-tkc





From e_d_k at yahoo.com  Thu May 13 21:26:17 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 18:26:17 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <737293.15031.qm@web58702.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Steven D'Aprano  wrote:

> From: Steven D'Aprano 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 7:41 PM
> On Thu, 13 May 2010 06:24:04 -0700,
> Ed Keith wrote:
> 
> > --- On Thu, 5/13/10, Lawrence D'Oliveiro
> > 
> wrote:
> >>
> >> What have you got against LGPL for this purpose?
> --
> >> 
> > Most of my clients would not know how to relink a
> program if their life
> > depended on it. And I do not want to put then in DLL
> hell. So I avoid
> > the LGPL.
> 
> 
> Are you implying that by distributing your libraries under
> the MIT or 
> Apache licence, no linking is required? That's a cool
> trick, can you 
> explain how it works please?
> 
> 
> 
> -- 
> Steven
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Normally I link it for them. As I read the LGPL, if I use any LGPLed code I need to teach the client how to link the software against any possible future version of the LGPLed library. 

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Thu May 13 21:32:31 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 18:32:31 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <59194ade-46dc-4178-8b76-36038808109b@k2g2000yqe.googlegroups.com>
Message-ID: <444360.64811.qm@web58705.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Carl Banks  wrote:

> 
> The thing you GPL fanbois refuse to understand or accept is
> that, in
> the real world, a person or company who doesn't want to
> open source
> their "derivative work" will only rarely be forced to by
> the GPL.
> They'll work around it instead, vast majority of the
> time.? They
> could:
> 
> 1. Derive their work from a project with a license that
> grants the
> user more freedom
> 2. Reimplment the functionality seperately (*cough*
> PySide)
> 3. Ignore the license

I think you have over looked the most common, keep the software in house and not let anyone else use it. This way you are in full compliance with the GPL. If you let someone else use the software that you need to talk to a lawyer, or GPL your software.

> 
> And no, a small number of anecdotal counterexamples is not
> any strong
> evidence to the contrary.
> 
> On the other hand, those who intended to release their work
> as open
> source are going to do it even if the license is
> permissive.? The way
> some of you GPL fanbois talk you'd think the MIT license
> prohibitied
> open source derivatives.

If I use MIT licensed code, I can give someone else access to the program with out binding them to the legal restrictions of the GPL. 

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com


 


      


From e_d_k at yahoo.com  Thu May 13 21:37:31 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Thu, 13 May 2010 18:37:31 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
Message-ID: <925552.63628.qm@web58705.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Brendan Abel <007brendan at gmail.com> wrote:

> From: Brendan Abel <007brendan at gmail.com>
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 7:30 PM
> While I think most of the
> disagreement in this long thread results
> from different beliefs in what "freedom" means, I wanted to
> add, that
> most of the responses that argue that the MIT license
> permits the user
> more freedom than the GPL, suffer from the broken window
> fallacy.
> This fallacy results from the short-sided-ness of the user
> base, as it
> is only considering the first generation of derivative
> works.
> 
> I agree, that under an MIT license, the first generation of
> derivative
> works have more freedom.? But any extra freedom gained
> here comes at
> the direct expense of all future generations of derivative
> software.
> 
> Under a GPL license, it is true that the first generation
> will have
> less freedom to distribute their software as they would
> like.? But it
> also ensures that all subsequent generations of derivative
> works have
> the freedom to access all previous derivative works.
> 
> I also want to add that I think the GPL v3 has exceeded
> this
> fundamental concept.? GPL v2 really embodies this
> meaning of "freedom".
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I ALWAYS give my client my source code. But I do not want to bind them to the requirements of the GPL, I want them to be free do do what they want with the program, so I never incorporate any GPLed code in my projects.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From aahz at pythoncraft.com  Thu May 13 21:56:28 2010
From: aahz at pythoncraft.com (Aahz)
Date: 13 May 2010 18:56:28 -0700
Subject: Picking a license
References: 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-b
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
Message-ID: 

In article <2d625c61-7a94-4c71-8953-69c3b3c76d07 at k29g2000yqh.googlegroups.com>,
Paul Boddie   wrote:
>
>All my position has ever been is this:
>
>A copyrighted work denies recipients virtually all rights to do stuff
>with that work, such as modify and redistribute it. Copyleft licences
>grant some privileges and uphold some obligations in order to ensure
>that these privileges are universally maintained in all forms and
>extensions of the work. Permissive licences grant more privileges to
>immediate recipients but do not uphold as many obligations.
>
>You rejected the suggestion that people using permissive licences
>afford users fewer privileges than those using copyleft licences, yet
>on balance when considering all forms and extensions of the work, they
>do. And the only such privilege that the copyleft licences withholds
>from recipients is that of withholding any other privilege from others
>who receive the work.

IMO this only makes sense if one agrees that people should not be allowed
to sell software for money.  Absent that agreement, your argument about
freedom seems rather limited.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From pmaupin at gmail.com  Thu May 13 22:10:09 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 19:10:09 -0700 (PDT)
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
Message-ID: 

On May 13, 6:30?pm, Brendan Abel <007bren... at gmail.com> wrote:
> While I think most of the disagreement in this long thread results
> from different beliefs in what "freedom" means, I wanted to add, that
> most of the responses that argue that the MIT license permits the user
> more freedom than the GPL, suffer from the broken window fallacy.
> This fallacy results from the short-sided-ness of the user base, as it
> is only considering the first generation of derivative works.

The broken window fallacy is about labor that could have been spent
elsewhere if someone else had done something differently.  The only
time that comes into play in my programming life is when I have to
recode something that is nominally available under the GPL, so I'm not
sure this is really making the point you think it is.

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 22:12:29 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 19:12:29 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
Message-ID: 

On May 13, 6:39 pm, Steven D'Aprano
 wrote:
> On Thu, 13 May 2010 08:06:52 -0700, Patrick Maupin wrote:
> > If I download an Ubuntu
> > ISO, burn it and give it away (let's say I give away 100 copies, just to
> > remove the fair use defense), then I have violated the GPL.  I provided
> > chapter and verse on this; go look it up.
>
> I'm sorry, I can't see where you have provided "chapter and verse", or
> even a URL.

In the original message, I wrote "In the case of GPL v3, for example,
Ubuntu lets me download code under 6d, so if I download it and burn
it, I would have to use 6a or 6b; if I had actually received a CD from
Ubuntu, I might be able to use 6c, but not if I downloaded it."  I
thought it was clear those were references to the license clauses.

> >> If you compiled the CD yourself, and failed to provide a written offer
> >> on the CD, then yes absolutely you would be in violation of the licence
> >> terms, and shame on you.
>
> > Not relevant.
>
> You didn't specify whether the "Linux CD" you were distributing was a
> mere copy of an existing CD , or one you created yourself, so you will
> pardon me for covering both possibilities.

Well, in the section I just quoted, I did mention "Ubuntu"...

> >> The GPL doesn't require you to force source code on those who don't
> >> want it, but it does require you to make it available if they ask, and
> >> for you to notify them appropriately of this fact. You don't even have
> >> to explicitly tell your friend he can have the source code. You just
> >> have to make sure that the written offer is available on the disk you
> >> give him.
>
> > There is no written offer on the disk, because I burned it from Ubuntu's
> > repository.  It really is that simple -- if I give away copies I've made
> > of Ubuntu, I've violated the GPL.
>
> No, I think this use-case would count as "propagation without conveying",
> since you are merely acting as a mechanical proxy between your friend(s)
> and Ubuntu.

No, I'm actually creating a copy and distributing it (in GPL v3
terminology, conveying it), especially since my friends don't
specifically ask for Ubuntu, and I'm foisting it off on them
(especially if I burn 10 CDs at a time so I have one if I need it).
GPL v2 also has similar rules, and there's lots of v2 licensed
software on the Ubuntu CD.

> I will admit that the GPL FAQs are not as clear about this matter as they
> should be.

I think it's quite clear, although a bit of a tedious slog.  But since
you want a URL, try this:  http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary

> > Unless you can cite some authority
> > that tells me I'm wrong and gives real reasons.  I actually quoted
> > chapter and verse from the license, but you chose to ignore that and
> > make unsubstantiated claims.
>
> I'm sorry, I can't find where you have quoted "chapter and verse" from
> the licence, so I can't comment.

Well, I just re-copied what I posted, and added a URL from the FAQ.

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 22:49:33 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 19:49:33 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
Message-ID: <89297458-28f7-4324-a804-8d2897477ee9@k2g2000yqe.googlegroups.com>

On May 13, 6:39 pm, Steven D'Aprano
 wrote:
> On Thu, 13 May 2010 08:06:52 -0700, Patrick Maupin wrote:

[...]

> >> Only a
> >> tiny proportion of people would discover by their own efforts that the
> >> source code was available
>
> > No, I tell my friends that source is available, and they can come and
> > see me if they want to know more.
>
> That doesn't scale to distributing hundreds of copies of the CD, let
> alone tens of thousands.

Sure it does.  Each one of those CD distributions is friend-to-
friend.  And if my friend gives a CD to someone interested in
programming, I might wind up with a new friend.

> If you're handing over a single copy to a friend
> (which is the example you gave earlier) then a verbal offer works well,
> and is only a technical breach of the GPL. If you're distributing
> hundreds of copies, I don't believe any such verbal offer is practical.

Right.  And lots of Linux Users Groups are in breach of the GPL on
many software packages.  But guess what?  It really doesn't matter,
because the source is sitting there on the internet, for the taking.

> > This may have been a viable argument
> > in 1989 (doubtful) but it's extremely silly today.
>
> So you say.

Yes, that what's I believe.  More anon.

>
> >>, and only a proportion of them would learn
> >> where it was available from. The result in practical terms would be a
> >> major decrease in the number of people granted the freedom to modify
> >> the source code, and a correspondingly larger decrease in the number of
> >> people both free and able to modify the source code.
>
> > I sincerely doubt your dystopian vision, which, like the GPL and many
> > laws, is predicated on some outmoded views about how humans interact.
>
> > The reason some people say that the GPL protects the "freedom of the
> > code" is because the GPL assumes that code needs to be nurtured, instead
> > of taking the viewpoint that, while there may be some freeloaders,
> > sharing code is obviously so valuable to most of humanity that it will
> > just happen.  We don't live in medieval Europe any more where the rules
> > of glassmaking are so secret that you'll be hunted down like a dog if
> > you try to leave.  We live in a world where "co- opetition" has been
> > shown to be so valuable we had to make up a word for it, and even for
> > those secrets that people are willing to kill to keep, we have
> > wikileaks.
>
> I admire your optimism, but don't share it.

I understand that.  There are a lot of people out there who will
attempt to profit off of other peoples' labor without any value-add.
But it's getting more difficult to do that.  A key element in any kind
of arbitrage is imperfect communications, and the internet is rapidly
perfecting almost all communications.

> > Let's face it -- a software freeloader is not the most evil thing in the
> > world.
>
> *A* software freeloader certainly isn't a big problem. Cutting down *a*
> tree is no big deal either, but consider what happened to the people of
> Easter Island, Ethiopia and Haiti when *everyone* did so.

In a different context, you would probably be arguing about how
software is not like physical goods, and nobody is made poorer if I
make my own copy of it.

> The terms of
> the GPL exist to discourage freeloaders, lest everyone does so. The
> obligations it imposes are not onerous by any stretch of the exaggeration.

Well, you still don't believe that if I download a CD and give it to a
friend I legally have to download a DVD's worth of source to go with
it :-)  (Mind you, I don't believe for a minute anybody would be
stupid enough to try to sue over that, or that copying a few CDs
wouldn't be covered by fair use, but I *do* believe that the license
attempts to require the source to be distributed.)

> >> It's not enough to be granted freedom to modify source code in theory,
> >> if you know about it, if you can find some hard-to-locate website which
> >> may or may not be running. The practicalities are equally important.
>
> > That's another thing.  Even if I downloaded all the source from Ubuntu,
> > what assurances do I really have that I have all the source? I could be
> > in technical violation of the GPL without even knowing it, even after
> > wasting an extra two days grabbing the source.  Best to use Gentoo to be
> > sure, and even then, I need to build it twice running strace just to
> > make sure that I really built everything.
>
> That's a silly objection to the GPL. When you include an MIT-licenced
> library in your project, you can't be sure that the library wasn't stolen
> from Microsoft and you've therefore accidentally infringed Microsoft's
> copyright. This isn't an argument against the MIT licence any more than
> your hypothetical is an argument against the GPL.

Well, OK, it's a bit silly, but not really the same as your example,
and certainly much more likely.  I have never downloaded any FOSS that
had any licensing issues I know of (and trust me, SCO tried really
hard on that front :-), but I have often downloaded .deb files and
tried to build something, but the dependencies were foobar.  All I'm
saying is that, to follow the letter of the license I'm handed (not
some theoretical other license that someone upstream violated) along
with the code is easy with MIT, but might be technically practically
impossible with a binary distribution of GPLed code, as with Ubuntu.

>
> >> In
> >> theoretical terms, everyone has the freedom to legally modify and
> >> distribute the source code to Microsoft Windows. All you have to do is
> >> buy 51% of the stock so as to become majority shareholder, then make
> >> sufficient changes to the board of directors so that the new board
> >> grants you a licence to do so, then fight off the lawsuits from the
> >> rest of the shareholders. Anyone could do it! Not.
>
> > So "everyone" could own 51% of Microsoft?  That means 100% of the shares
> > would be around 350,000,000,000%.  Wait, that can't be right, what? :-)
>
> Obviously not all at once, silly. But "in theory", everyone could become
> the majority shareholder -- there is no law or physical law of nature
> that says "Patrick Maupin is prohibited from being majority shareholder
> of Microsoft".

Yeah, but I think if I put my lonely little projects out there, that
practically speaking, everybody has a better chance of being able to
download the code to those, no matter what the license, than I have a
chance of coming up with the scratch to buy Microsoft :-)

> Anti-competition laws or similar may prevent a person from becoming
> majority shareholder unless they (e.g.) gave up their shares in another
> company, but again, there's nothing stopping them from doing so, if they
> wished.
>
> > Can you come up with a sillier analogy?
>
> I'm sure I could, but you seem to have entirely missed the point that
> such theoretical "freedom" is entirely illusionary, since *in practice*
> very few people actually can partake in it.

No, I saw your point, and completely disagree with it.  My code is out
there.  Sure, people can wrap *their* proprietary stuff around it, but
other people can still get *my* stuff, so I really, truly, don't see
the problem here.  Again, it would be different if *my* stuff were so
fantastically important that I was going to make a mint off of it, but
frankly if I don't see that it is, but someone else sees some
intrinsic value and manages to make a mint off it, perhaps the world
is a better place.

> >> Another, more practical example: here in Australia our government is
> >> hell- bent on introducing an ineffective and expensive Internet
> >> censorship scheme. It seems that under Australian law, it will be
> >> completely legal to circumvent the filter, but our government is
> >> investigating ways to make it illegal to tell anyone how to circumvent
> >> it. In other words, Australians will have permission to circumvent the
> >> nanny filter, but since few people will know this, or know how to do
> >> so, it will be a meaningless freedom.
>
> > Yes, that's basically how the DMCA works, and that's evil, and that's
> > one of the reasons I sometimes give money to the EFF.  But, you can't
> > seriously be comparing making speech a crime and making not speaking a
> > crime (or a copyright violation), can you?  Maybe you *did* manage to
> > come up with a sillier analogy...
>
> There are situations where not speaking is a crime. If you witness a
> crime, and fail to report it, there are circumstances where you may be
> liable to be persecuted for aiding and abetting.

Usually, you have to take active measures to conceal the crime, not
just "not speak" about it:  http://en.wikipedia.org/wiki/Misprision_of_felony

> >> The GPL concerns itself with the *practical* freedom to gain access to
> >> source code, not merely the theoretical freedom represented by
> >> permission without opportunity.
>
> > No, the GPL is ideologically opposed to anything related to practicality
> > (although in practice, its adherents have to bend a bit to avoid being
> > made irrelevant, and Linux, the shining success, is led by someone who
> > arguably cares not one whit for GPL ideological purity).
>
> And yet Linux is distributed under the GPL, which pretty much sinks your
> argument.

Not sure how you come to that conclusion.  For example, while Linux is
arguably strong enough to start kicking out binary drivers now, at the
beginning that would have been its death-knell, and that's probably
how RMS would have proceeded.  The point is, Torvalds views the
license as a good starting point for a set of behaviors, but he made
very clear the kind of behaviors he was interested in enforcing.  See,
for example:  http://www.linuxfordevices.com/c/a/News/Torvalds-quashes-binary-kernel-module-revolt/

Interestingly, one of the problems with Linux that has more to do with
the size of the project and pace of development than anything else, is
that people are more worried that their contributions aren't going to
make it into the kernel, rather than that they have to give them back
to the kernel.

>
> [...]
>
> > But the GPL wording required to enforce what you call a practical
> > freedom imposes so many impractical costs that there are probably
> > millions of people in the world who have violated this license, in the
> > good-faith attempt to spread free software around.
>
> As I admitted earlier, there is an apparent grey area there, at least
> according to the FAQs, but I don't think it is anywhere near as obvious
> as you claim that it is a licence violation.

Well, take another look.  I would be interested in any evidence you
can find that shows otherwise.

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 22:58:16 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 19:58:16 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
Message-ID: <84a26d03-03b3-47d9-a1f9-107470b87c75@k2g2000yqe.googlegroups.com>

On May 13, 6:39 pm, Steven D'Aprano
 wrote:
> On Thu, 13 May 2010 08:06:52 -0700, Patrick Maupin wrote:

> Perhaps the Apache model doesn't work quite as well as you think?

Apparently it's 66 percent of the web servers for the million busiest
sites,  and presumably 65 for the next million, etc...

When I look at the netcraft graphs, the only thing that seemed to
cause a decline before last year was Microsoft and their marketing
muscle.  For example, they incentivize godaddy and others to run all
the parked sites on IIS.

In the graphs, there was a sudden spike in "other" at the beginning of
last year. My gut tells me this is ROR, django, and other similarly
permissively licensed software.  In any case, back when GPL take-up
was quite small, RMS was very dismissive of market numbers, but I
really have to ask:  where are all the GPL-licensed web servers?

> As far as not-so-niche software goes, the GPLed Linux OS is far more
> popular on the desktop than FreeBSD and OpenBSD together, and about equal
> in popularity to Mac OS. I'm not suggesting that the popularity of an OS
> is *entirely* dependent on the licence, but it may be a factor.

Well, despite what others have said here, I think the lingering
effects of the Unix lawsuit helped give Linux a push.  Torvalds
himself was a huge factor, and I'm willing to concede that the GPL
didn't hinder the quest for contributors.

The fact is that, in reality (Darwinian competition to determine the
best architecture aside) it's very nice to have a single primary point
of focus for an OS, and Unix was perceived to be hopelessly fragmented
by many would-be contributors who wouldn't know where to start.

I also firmly believe, as I have stated before, that the GPL is a much
more commercial license.  If you want to make money off something,
then, no doubt, GPL keeps your competitors from being able to take
what you wrote and redistribute it as closed source.  But, frankly I
view that as more of a business issue than a moral issue.

In any case, if you want to look, as a marketer would, at TAM (Total
Available Market), free software is completely floundering in the OS
space, and permissively licensed software owns the serious web server
space.

Regards,
Pat


From ldo at geek-central.gen.new_zealand  Thu May 13 23:03:32 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 15:03:32 +1200
Subject: Picking a license
References: 
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
Message-ID: 

In message <72888d2c-4b1a-4b08-a3aa-
f4021d2ed646 at e2g2000yqn.googlegroups.com>, Patrick Maupin wrote:

> If I download an Ubuntu ISO, burn it and give it away (let's say I give
> away 100 copies, just to remove the fair use defense), then I have
> violated the GPL.  I provided chapter and verse on this; go look it up.

I have looked it up , and sections 
3b or 3c would seem to apply. Or alternatively 
, 6b or 6c. If the source you got it 
from didn?t violate the GPL, then obviously you didn?t either.


From ldo at geek-central.gen.new_zealand  Thu May 13 23:04:57 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 15:04:57 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> The claim is being made that [the GPL] restricts freedom.

What about the ?freedom? to restrict other people?s freedom? Should that be 
restricted or not?


From ldo at geek-central.gen.new_zealand  Thu May 13 23:06:08 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 15:06:08 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> Assertion I:
>    If person A is free to do more than person B, then person A has
>    more freedom then person B.
> 
> Assertion II:
>    If person A is free do perform an action person B is not free to
>    perform then person A is free to do more than person B.
> 
> Assertion III:
>   If person B is restricted in some way that person A is not them Person A
>   is free to do something Person B is not free to do.
> 
> Conclusion:
>   If person B is more resticted than Peston A, Person A has mor freedom
>   than person B.
> 
> Which step in this reasoning do you disagree with?

Under the GPL, everybody has exactly the same freedoms. So which of your 
assertions is supposedly a criticism of the GPL?


From ldo at geek-central.gen.new_zealand  Thu May 13 23:07:26 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 15:07:26 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> On Thu, 5/13/10, Lawrence D'Oliveiro
>  wrote:
> 
>> In message ,
>> Ed Keith wrote:
>> 
>>> So if you want me to even consider using your library
>>> do not use GPL, or LGPL.
>> 
>> What have you got against LGPL for this purpose?
> 
> Most of my clients would not know how to relink a program if their life
> depended on it. And I do not want to put then in DLL hell. So I avoid the
> LGPL.

How exactly does the LGPL lead to a requirement to ?relink??


From pmaupin at gmail.com  Thu May 13 23:35:25 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 20:35:25 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: <1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>

On May 13, 10:07?pm, Lawrence D'Oliveiro  wrote:

> How exactly does the LGPL lead to a requirement to ?relink??

I think this might be a misconception, but I'm not 100% sure.  Since
Ed gives his customers full source code, there may not be the
requirement to directly provide the ability to relink, because "The
?Corresponding Application Code? for a Combined Work means the object
code and/or source code for the Application." and section 4d0 requires
you to "permit the user to recombine or relink" where "recombine"
isn't defined directly (perhaps in the underlying GPL?)

Nonetheless, all the dotting of i's and crossing of t's to satisfy
section 4 and the underlying GPL probably require a lawyer to check
your source code distribution.  For example, what is "prominent
notice"?

And I love the gem at 4e:  "Provide Installation Information, but only
if you would otherwise be required to provide such information under
section 6 of the GNU GPL, and only to the extent that such information
is necessary to install and execute a modified version of the Combined
Work produced by recombining or relinking the Application with a
modified version of the Linked Version. (If you use option 4d0, the
Installation Information must accompany the Minimal Corresponding
Source and Corresponding Application Code. If you use option 4d1, you
must provide the Installation Information in the manner specified by
section 6 of the GNU GPL for conveying Corresponding Source.)"

I mean, it's in English and very technically precise, but if you
follow all the references, you quickly come to realize that the
license is a "patch" to the GPL.  It was deliberately made in patch
format to make it smaller, but as we all know, reading source code and
the accompanying patch is almost always more difficult than reading
the patched source.

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 23:39:54 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 20:39:54 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
Message-ID: 

On May 13, 10:03?pm, Lawrence D'Oliveiro  wrote:
> In message <72888d2c-4b1a-4b08-a3aa-
>
> f4021d2ed... at e2g2000yqn.googlegroups.com>, Patrick Maupin wrote:
> > If I download an Ubuntu ISO, burn it and give it away (let's say I give
> > away 100 copies, just to remove the fair use defense), then I have
> > violated the GPL. ?I provided chapter and verse on this; go look it up.
>
> I have looked it up , and sections
> 3b or 3c would seem to apply. Or alternatively
> , 6b or 6c. If the source you got it
> from didn?t violate the GPL, then obviously you didn?t either.

I don't think that's necessarily true.  As I've posted before:  "In
the
case of GPL v3, for example, Ubuntu lets me download code under 6d, so
if I download it and burn it, I would have to use 6a or 6b; if I had
actually received a CD from Ubuntu, I might be able to use 6c, but not
if I downloaded it."

That's because to use 6c, the initial underlying distribution had to
be done with 6b, not 6d.  Also the FAQ is very clear:
http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 23:43:44 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 20:43:44 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: <2ff3643b-6ef1-4471-8438-dcba0dc93c24@a21g2000yqn.googlegroups.com>

On May 13, 10:04?pm, Lawrence D'Oliveiro  wrote:
> In message , Ed Keith
> wrote:
>
> > The claim is being made that [the GPL] restricts freedom.
>
> What about the ?freedom? to restrict other people?s freedom? Should that be
> restricted or not?

It's interesting that some people don't like the comparison of the
Free Software movement to a religion, yet the main argument of the
movement, and the deliberate co-opting of words like "Free" and "Free
Software" are done in an attempt to guilt others into accepting RMS's
vision of morality.

He's perfectly welcome have that vision.  But I don't let it affect my
own moral compass -- I reject it as just another post-modern religion,
AKA cult.

Regards,
Pat


From pmaupin at gmail.com  Thu May 13 23:45:07 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Thu, 13 May 2010 20:45:07 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: <2b17ee77-0e49-4a97-994c-7582f86c0ba9@r34g2000yqj.googlegroups.com>

On May 13, 10:06?pm, Lawrence D'Oliveiro  wrote:
> In message , Ed Keith
> wrote:
>
>
>
> > Assertion I:
> > ? ?If person A is free to do more than person B, then person A has
> > ? ?more freedom then person B.
>
> > Assertion II:
> > ? ?If person A is free do perform an action person B is not free to
> > ? ?perform then person A is free to do more than person B.
>
> > Assertion III:
> > ? If person B is restricted in some way that person A is not them Person A
> > ? is free to do something Person B is not free to do.
>
> > Conclusion:
> > ? If person B is more resticted than Peston A, Person A has mor freedom
> > ? than person B.
>
> > Which step in this reasoning do you disagree with?
>
> Under the GPL, everybody has exactly the same freedoms. So which of your
> assertions is supposedly a criticism of the GPL?

That's absolutely not true.  For a start, the original author can dual-
license.  This is not a theoretical issue -- it is a multi-million
dollar issue.

Regards,
Pat


From half.italian at gmail.com  Fri May 14 00:54:11 2010
From: half.italian at gmail.com (Sean DiZazzo)
Date: Thu, 13 May 2010 21:54:11 -0700 (PDT)
Subject: client to upload big files via https and get progress info
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	 <4BEC2B49.7060007@free.fr>
Message-ID: <4cbd946d-5b24-46dd-acdc-d19414fa7ffc@11g2000prw.googlegroups.com>

On May 13, 9:39?am, News123  wrote:
> Hi Aaaz,
>
> Aahz wrote:
> > In article <4bea6b50$0$8925$426a7... at news.free.fr>,
> > News123 ? wrote:
> >> I'd like to perform huge file uploads via https.
> >> I'd like to make sure,
> >> - that I can obtain upload progress info (sometimes the nw is very slow)
> >> - that (if the file exceeds a certain size) I don't have to
> >> ?read the entire file into RAM.
>
> > Based on my experience with this, you really need to send multiple
> > requests (i.e. "chunking"). ?There are ways around this (you can look
> > into curl's resumable uploads), but you will need to maintain state no
> > matter what, and I think that chunking is the best/simplest.
>
> I agree I need ?chunking. (the question is just on which level of the
> protocol)
>
> I just don't know how to make a chunkwise file upload or what library is
> best.
>
> Can you recommend any libraries or do you have a link to an example?
>
> I'd like to avoid to make separate https post requests for the chunks
> (at least if the underlying module does NOT support keep-alive connections)
>
> I made some tests with high level chunking (separate sequential https
> post requests).
> What I noticed is a rather high penalty in data throughput.
> The reason is probably, that each request makes its own https connection
> and that either the NW driver or the TCP/IP stack doesn't allocate
> enough band width to my request.
>
> Therefore I'd like to do the chunking on a 'lower' level.
> One option would be to have a https module, which supports keep-alive,
>
> the other would be ?to have a library, which creates a http post body
> chunk by chunk.
>
> What do others do for huge file uploads
> The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )
>
> N

You could also just send the file in one big chunk and give yourself
another avenue to read the size of the file on the server.  Maybe a
webservice that you call with the name of the file that returns it's
percent complete, or it could just return bytes on disk and you do the
math on the client side.  Then you just forget about the transfer and
query the file size whenever you want to know...or on a schedule.

~Sean


From half.italian at gmail.com  Fri May 14 01:01:55 2010
From: half.italian at gmail.com (Sean DiZazzo)
Date: Thu, 13 May 2010 22:01:55 -0700 (PDT)
Subject: client to upload big files via https and get progress info
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	 <4BEC2B49.7060007@free.fr>
	<4cbd946d-5b24-46dd-acdc-d19414fa7ffc@11g2000prw.googlegroups.com>
Message-ID: 

On May 13, 9:54?pm, Sean DiZazzo  wrote:
> On May 13, 9:39?am, News123  wrote:
>
>
>
> > Hi Aaaz,
>
> > Aahz wrote:
> > > In article <4bea6b50$0$8925$426a7... at news.free.fr>,
> > > News123 ? wrote:
> > >> I'd like to perform huge file uploads via https.
> > >> I'd like to make sure,
> > >> - that I can obtain upload progress info (sometimes the nw is very slow)
> > >> - that (if the file exceeds a certain size) I don't have to
> > >> ?read the entire file into RAM.
>
> > > Based on my experience with this, you really need to send multiple
> > > requests (i.e. "chunking"). ?There are ways around this (you can look
> > > into curl's resumable uploads), but you will need to maintain state no
> > > matter what, and I think that chunking is the best/simplest.
>
> > I agree I need ?chunking. (the question is just on which level of the
> > protocol)
>
> > I just don't know how to make a chunkwise file upload or what library is
> > best.
>
> > Can you recommend any libraries or do you have a link to an example?
>
> > I'd like to avoid to make separate https post requests for the chunks
> > (at least if the underlying module does NOT support keep-alive connections)
>
> > I made some tests with high level chunking (separate sequential https
> > post requests).
> > What I noticed is a rather high penalty in data throughput.
> > The reason is probably, that each request makes its own https connection
> > and that either the NW driver or the TCP/IP stack doesn't allocate
> > enough band width to my request.
>
> > Therefore I'd like to do the chunking on a 'lower' level.
> > One option would be to have a https module, which supports keep-alive,
>
> > the other would be ?to have a library, which creates a http post body
> > chunk by chunk.
>
> > What do others do for huge file uploads
> > The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )
>
> > N
>
> You could also just send the file in one big chunk and give yourself
> another avenue to read the size of the file on the server. ?Maybe a
> webservice that you call with the name of the file that returns it's
> percent complete, or it could just return bytes on disk and you do the
> math on the client side. ?Then you just forget about the transfer and
> query the file size whenever you want to know...or on a schedule.
>
> ~Sean

oops...that doesn't help with the other requirements.  My suggestion
is to not use https.  I don't think it was created to move around
large pieces of data.  Lots of small pieces rather.  SFTP?


From user at example.net  Fri May 14 01:37:38 2010
From: user at example.net (J.O. Aho)
Date: Fri, 14 May 2010 07:37:38 +0200
Subject: client to upload big files via https and get progress info
In-Reply-To: <4BEC2B49.7060007@free.fr>
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	 <4BEC2B49.7060007@free.fr>
Message-ID: <8545t3F8mtU1@mid.individual.net>

News123   wrote:

> What do others do for huge file uploads
> The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )

Those cases where I have had to move big files it's been scp on those cases
where you just have to push a new file, in cases where it's a question of
keeping two directories synced, then it's rsync over ssh.
The later one I have never done in python.


-- 

  //Aho


From steve at REMOVE-THIS-cybersource.com.au  Fri May 14 01:59:04 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 14 May 2010 05:59:04 GMT
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
	<59194ade-46dc-4178-8b76-36038808109b@k2g2000yqe.googlegroups.com>
Message-ID: <4bece6a8$0$8761$c3e8da3@news.astraweb.com>

On Thu, 13 May 2010 17:18:47 -0700, Carl Banks wrote:

> The thing you GPL fanbois refuse to understand or accept is that, in the
> real world, a person or company who doesn't want to open source their
> "derivative work" will only rarely be forced to by the GPL. They'll work
> around it instead, vast majority of the time.  They could:
> 
> 1. Derive their work from a project with a license that grants the user
> more freedom
> 2. Reimplment the functionality seperately (*cough* PySide) 

Yes. So what? In what possible way is this an argument against the GPL?

If I offer to mow your lawn for $20, and you refuse, I don't have to 
force my services onto you. You can mow your lawn yourself, or find 
somebody who will do it for $10, or find some kind generous soul who will 
do it for free under an MIT licence.

If you don't want the obligations of the GPL, nobody is going to force 
you to distribute or derive from the GPLed software. If you're not 
willing to meet my conditions to use my software, then I don't want you 
using my software. Go write your own, or find somebody else who will do 
it for a fee, or for free. What you see as a disadvantage of the GPL is a 
feature, not a bug.

You seem to be under the impression that the only public good developers 
should care about is maximising the number of people who create 
derivative works from your project. That's obviously not so in the real 
world, where vast numbers of developers release software under closed-
source licences, or don't release it to the public at all, and it's 
certainly not the case for people who use the GPL. The FSF even has a FAQ 
about that exact point.



> 3. Ignore the license

This is a crime under copyright law, and there have been many instances 
of companies who thought they could ignore the GPL learning different.


-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Fri May 14 02:08:30 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 14 May 2010 06:08:30 GMT
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
	
Message-ID: <4bece8de$0$8761$c3e8da3@news.astraweb.com>

On Thu, 13 May 2010 19:10:09 -0700, Patrick Maupin wrote:

> The broken window fallacy is about labor that could have been spent
> elsewhere if someone else had done something differently.  The only time
> that comes into play in my programming life is when I have to recode
> something that is nominally available under the GPL, so I'm not sure
> this is really making the point you think it is.

You've never had to recode something because it was nominally available 
under a proprietary licence that you (or your client) was unwilling to 
use? Lucky you!

The GPL ensures that once software has entered the commons (and therefore 
available for all), it can never be removed from the commons. The MIT 
licence does not. Now, you might argue that in practice once software is 
released under an MIT licence, it is unlikely to ever disappear from the 
commons. Well, perhaps, but if so, that's despite and not because of the 
licence.

In practice, I believe most MIT-licenced code never even makes it into 
the commons in the first place. I'm willing to predict that the majority 
of code you've written for paying customers (as opposed to specifically 
for open source projects) has disappeared into their code base, never to 
be seen by anyone outside of the company. Am I right?


-- 
Steven


From pavlovevidence at gmail.com  Fri May 14 03:08:06 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 14 May 2010 00:08:06 -0700 (PDT)
Subject: Picking a license
References: 
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com> 
	<59194ade-46dc-4178-8b76-36038808109b@k2g2000yqe.googlegroups.com> 
	<4bece6a8$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <804512fb-e9ac-4284-a577-84e609531e06@s4g2000prh.googlegroups.com>

On May 13, 10:59?pm, Steven D'Aprano  wrote:
> On Thu, 13 May 2010 17:18:47 -0700, Carl Banks wrote:
> > The thing you GPL fanbois refuse to understand or accept is that, in the
> > real world, a person or company who doesn't want to open source their
> > "derivative work" will only rarely be forced to by the GPL. They'll work
> > around it instead, vast majority of the time. ?They could:
>
> > 1. Derive their work from a project with a license that grants the user
> > more freedom
> > 2. Reimplment the functionality seperately (*cough* PySide)
>
> Yes. So what? In what possible way is this an argument against the GPL?

[snip a bunch of crap I don't care about]


It's not.  It's an argument that the GPL doesn't do much good.

Arguments against the GPL are found elsewhere in this thread, I don't
need to repeat them here.


Carl Banks


From news1234 at free.fr  Fri May 14 03:19:20 2010
From: news1234 at free.fr (News123)
Date: Fri, 14 May 2010 09:19:20 +0200
Subject: client to upload big files via https and get progress info
In-Reply-To: 
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	 <4BEC2B49.7060007@free.fr>
	<4cbd946d-5b24-46dd-acdc-d19414fa7ffc@11g2000prw.googlegroups.com>
	
Message-ID: <4becf979$0$2854$426a34cc@news.free.fr>

Hi Sean,




Sean DiZazzo wrote:
> On May 13, 9:54 pm, Sean DiZazzo  wrote:
>> On May 13, 9:39 am, News123  wrote:
>>
>>
>>
>>> Hi Aaaz,
>>> Aahz wrote:
>>>> In article <4bea6b50$0$8925$426a7... at news.free.fr>,
>>>> News123   wrote:
>>>>> I'd like to perform huge file uploads via https.
>>>>> I'd like to make sure,

> 
> oops...that doesn't help with the other requirements.  My suggestion
> is to not use https.  I don't think it was created to move around
> large pieces of data.  Lots of small pieces rather.  SFTP?


I had to check, but I guess sftp is not exactly suitable for my usecase.

My problem
- the whole communication is to be intended to work like a drop box.
  - one can upload files
  - one can not see, what one has uploaded before
  - no way to accidentally overwrite a previous upload, etc.
- I don't know enough about sftp servers to know how I could configure
it to act as a drop box.


That's much easier to hide behind an https server than behind an out of
the box sftp server.



N


From news1234 at free.fr  Fri May 14 03:22:01 2010
From: news1234 at free.fr (News123)
Date: Fri, 14 May 2010 09:22:01 +0200
Subject: client to upload big files via https and get progress info
In-Reply-To: 
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	
Message-ID: <4becfa19$0$2854$426a34cc@news.free.fr>

Hi James,

James Mills wrote:
> On Wed, May 12, 2010 at 6:48 PM, News123  wrote:
>> Hi,
>>
>> I'd like to perform huge file uploads via https.
>> I'd like to make sure,
>> - that I can obtain upload progress info (sometimes the nw is very slow)
>> - that (if the file exceeds a certain size) I don't have to
>>  read the entire file into RAM.
>>
> 
> My suggestion is to find some tools that can
> send multiple chucks of data. A non-blocking
> i/o library/tool might be useful here (eg: twisted or similar).
> 

I never used twisted so far.
Perhaps the time to look at it.


bye


N


From news1234 at free.fr  Fri May 14 03:23:59 2010
From: news1234 at free.fr (News123)
Date: Fri, 14 May 2010 09:23:59 +0200
Subject: client to upload big files via https and get progress info
In-Reply-To: <8545t3F8mtU1@mid.individual.net>
References: <4bea6b50$0$8925$426a74cc@news.free.fr>
	 <4BEC2B49.7060007@free.fr>
	<8545t3F8mtU1@mid.individual.net>
Message-ID: <4becfa8f$0$2854$426a34cc@news.free.fr>

Hi J,


J.O. Aho wrote:
> News123   wrote:
> 
>> What do others do for huge file uploads
>> The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )
> 
> Those cases where I have had to move big files it's been scp on those cases
> where you just have to push a new file, in cases where it's a question of
> keeping two directories synced, then it's rsync over ssh.
> The later one I have never done in python.


I agree. From home this is also what I do.
scp / rsync.


However I'd like to use https, as http/https are the two ports, that are
almost everywhere accessible (eve with proxies / firewalls, etc.)



N


From hkiridis at yahoo.com.au  Fri May 14 04:19:24 2010
From: hkiridis at yahoo.com.au (harry k)
Date: Fri, 14 May 2010 08:19:24 -0000
Subject: help need to write a python spell checker
Message-ID: 

Write a spell checking tool that will identify all misspelled word in a text file using a provided dictionary.


The program will accept either one or two command line parameters.
1.	The first command line parameter is the name of the text file that will be checked.
2.	The optional second command line parameter is the name of the dictionary file ? a file of words with one word per line.  The default dictionary file is ref.txt.
The program will write out the misspelled words, one per line, in alphabetical order.

Extend the spell checking tool so that as well as identifying all misspelled words,  the program will list the line numbers in the file where the incorrect spelling occurs.

The program will write out the misspelled words (one per line, in alphabetical order), followed by a tab character, followed by the list of line numbers that word is misspelled in,in ascending order, on the same line, separated by a single space.


Extend the spell-checking tool so that the program will also print out a list of possible correct spellings for the words.

The program will write out the misspelled words (one per line, in alphabetic order), followed (on the same line) by a single space, followed by the list of line numbers in ascending order, each separated by a single space, followed by a single space, then the list of possible correct spellings, each separated by a single space.

Find the alternate spellings by considering:
a.	Words in the dictionary that are the same length but:
a.	Have a pair of characters interchanged
b.	Differ by one character from the misspelled word
b.	Words that are one character longer or one character shorter, but otherwise match the misspelled word.



From oxfordenergyservices at googlemail.com  Fri May 14 04:23:40 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Fri, 14 May 2010 01:23:40 -0700 (PDT)
Subject: stopping execution window on error - newbie
References: <101459d0-92cb-40d4-ad6d-6f82a70b167d@l31g2000yqm.googlegroups.com>
	<3fd705f1-2b3b-4b2b-b48d-06a6700a76be@g21g2000yqk.googlegroups.com>
Message-ID: 

On 14 May, 00:14, Mensanator  wrote:
> On May 13, 4:00?pm, a  wrote:
>
> > I'm coding on an old windows laptop
>
> > i write the code and double click the icon. ?
>
> Don't do that.
>
> > it runs the program and
> > writes results to a window.
>
> > when the code finishes, the window closes, i do a time.sleep(10) to
> > see what has happened.
>
> > unfortunately when there is an error it just closes the window.
> > anyway of seeing the error messages?
>
> Go to the windows [Start] button. Select [Run...] and in the popup
> box,
> type "cmd" as the program to run. This will open a DOS shell window (a
> text window.)
>
> Then you can run your Python script from the window prompt and it
> won't
> close until you manually close it, even if the program crashes.
>
> For example, once I open the DOS shell...
>
> 
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
>
> H:\>C:
>
> C:\>cd python31\user\lotto
>
> C:\Python31\user\lotto>dir
> ?Volume in drive C has no label.
> ?Volume Serial Number is 06DE-55B4
>
> ?Directory of C:\Python31\user\lotto
>
> 05/13/2010 ?05:53 PM ? ? ? ? ? ? ?.
> 05/13/2010 ?05:53 PM ? ? ? ? ? ? ?..
> 08/19/2009 ?07:08 PM ? ? ? ? ? ? 3,334 lotto.py
> 05/13/2010 ?05:56 PM ? ? ? ? ? ? 6,068 lotto_2010.py
> ? ? ? ? ? ? ? ?2 File(s) ? ? ? ? ?9,402 bytes
> ? ? ? ? ? ? ? ?2 Dir(s) ?102,247,440,384 bytes free
>
> C:\Python31\user\lotto>..\..\python lotto_2010.py
>
> {1: 2, 2: 3, 3: 2, 4: 1, 5: 2, 6: 1, 7: 2, 8: 1, 9: 1, 10: 2, 11: 2,
> 13: 1, 14: 2, 17: 1, 18: 2, 19: 1, 20: 1, 21: 1, 22: 1, 24: 1, 25: 1,
> 26: 3, 27: 1, 28: 2, 29: 2, 30: 1, 31: 1, 32: 1, 34: 1, 35: 1, 37: 2,
> 38: 2, 39: 2, 40: 1, 42: 2, 43: 1, 44: 2, 46: 2, 47: 1, 48: 1, 50: 1,
> 51: 2, 52: 3}
>
> ?1 ?2 **
> ?2 ?3 ***
> ?3 ?2 **
> ?4 ?1 *
> ?5 ?2 **
> ?6 ?1 *
> ?7 ?2 **
> ?8 ?1 *
> ?9 ?1 *
> 10 ?2 **
> 11 ?2 **
> 12
> 13 ?1 *
> 14 ?2 **
> 15
> 16
> 17 ?1 *
> 18 ?2 **
> 19 ?1 *
> 20 ?1 *
> 21 ?1 *
> 22 ?1 *
> 23
> 24 ?1 *
> 25 ?1 *
> 26 ?3 ***
> 27 ?1 *
> 28 ?2 **
> 29 ?2 **
> 30 ?1 *
> 31 ?1 *
> 32 ?1 *
> 33
> 34 ?1 *
> 35 ?1 *
> 36
> 37 ?2 **
> 38 ?2 **
> 39 ?2 **
> 40 ?1 *
> 41
> 42 ?2 **
> 43 ?1 *
> 44 ?2 **
> 45
> 46 ?2 **
> 47 ?1 *
> 48 ?1 *
> 49
> 50 ?1 *
> 51 ?2 **
> 52 ?3 ***
>
> (7, 21, 50, 36, 26, 3)
> (7, 21, 50, 36, 26, 17)
> (7, 21, 50, 36, 26, 52)
> (7, 21, 50, 36, 3, 17)
> (7, 21, 50, 36, 3, 52)
> (7, 21, 50, 36, 17, 52)
> (7, 21, 50, 26, 3, 17)
> (7, 21, 50, 26, 3, 52)
> (7, 21, 50, 26, 17, 52)
> (7, 21, 50, 3, 17, 52)
> (7, 21, 36, 26, 3, 17)
> (7, 21, 36, 26, 3, 52)
> (7, 21, 36, 26, 17, 52)
> (7, 21, 36, 3, 17, 52)
> (7, 21, 26, 3, 17, 52)
> (7, 50, 36, 26, 3, 17)
> (7, 50, 36, 26, 3, 52)
> (7, 50, 36, 26, 17, 52)
> (7, 50, 36, 3, 17, 52)
> (7, 50, 26, 3, 17, 52)
> (7, 36, 26, 3, 17, 52)
> (21, 50, 36, 26, 3, 17)
> (21, 50, 36, 26, 3, 52)
> (21, 50, 36, 26, 17, 52)
> (21, 50, 36, 3, 17, 52)
> (21, 50, 26, 3, 17, 52)
> (21, 36, 26, 3, 17, 52)
> (50, 36, 26, 3, 17, 52)
>
> ?8 ?9 32 38 40 48
> 13 22 28 39 42 43
> ?1 ?2 ?5 11 18 52 +
> ?2 ?3 26 44 51 52 +++
> ?4 ?7 14 26 35 52 +++
> ?2 ?7 10 19 42 47 +
> ?5 20 31 34 50 51 +
> ?1 28 29 37 39 46
> 10 11 27 37 38 46
> ?6 21 24 29 30 44 +
> ?3 14 17 18 25 26 +++
> ?7 10 39 42 45 46 +
> 15 17 23 36 38 44 ++
> 16 19 23 27 41 49
> 15 25 32 36 44 47 +
> 16 19 24 29 38 41
> ?3 ?4 ?8 13 43 49 +
> ?2 11 17 19 22 50 ++
> 14 21 22 28 30 45 +
> ?4 15 21 34 47 49 +
> 19 34 38 39 40 48
> ?4 16 24 33 37 48
> ?8 16 17 18 39 40 +
> ?1 24 27 30 31 47
> ?1 ?7 11 21 30 43 ++
> ?1 ?8 13 18 32 36 +
> ?5 10 12 16 20 21 +
> ?7 11 23 24 26 35 ++
> ?7 ?8 11 13 42 49 +
> ?1 ?8 17 34 40 50 ++
> ?1 24 29 35 41 45
> 15 17 24 32 44 52 ++
> ?4 12 21 26 33 38 ++
> ?2 13 15 41 48 50 +
> ?2 ?7 ?9 27 45 52 ++
> 24 25 35 36 39 42 +
> ?8 22 39 40 42 48
> 16 18 29 30 34 43
> ?7 21 28 36 45 50 ++++
> ?4 ?8 30 35 39 42
> ?2 11 15 23 40 51
> ?2 ?7 14 18 23 34 +
> ?1 11 22 37 41 50 +
> ?4 34 40 44 50 52 ++
> 12 28 33 39 40 52 +
> 14 18 25 36 38 39 +
> ?4 11 16 17 27 37 +
> ?1 11 16 28 31 36 +
> ?8 16 31 34 36 52 ++
> ?7 10 15 21 35 36 +++
> ?2 ?9 21 23 29 30 +
> 15 29 33 41 46 47
> ?2 ?5 18 34 36 39 +
> ?7 15 21 31 45 50 +++
> 12 17 20 28 39 51 +
> ?3 ?7 22 26 50 52 +++++
> ?1 ?5 21 27 31 39 +
> ?2 ?8 10 23 34 50 +
> ?1 11 24 26 32 52 ++
> ?1 18 20 38 41 42
> 12 33 36 42 45 48 +
> ?1 ?6 21 28 37 39 +
> 16 18 19 22 33 35
> ?2 ?7 17 27 29 47 ++
> 15 19 20 25 42 45
> ?2 ?6 17 19 20 41 +
> ?1 13 34 42 43 46
> 16 29 30 31 34 47
> ?5 ?7 26 29 36 46 +++
> ?1 27 28 30 31 49
> ?8 17 19 47 49 52 ++
> ?5 23 32 41 42 45
> 11 13 22 29 40 46
> 16 17 18 20 41 43 +
> ?3 17 26 38 45 52 ++++
> 13 18 21 38 39 41 +
> 14 19 28 40 44 51
> ?4 ?8 ?9 36 43 47 +
> ?1 ?9 15 24 36 39 +
> ?4 31 37 41 42 43
> ?7 12 18 27 36 42 ++
> ?3 ?4 26 27 35 51 ++
> ?7 12 19 23 26 45 ++
> 19 28 36 39 42 52 ++
> ?8 17 21 44 46 51 ++
> ?2 ?4 18 19 36 49 +
> ?1 ?4 11 16 22 35
> 13 14 17 18 41 46 +
> ?8 16 23 29 43 48
> ?1 ?8 25 36 37 44 +
> ?7 20 21 23 36 50 ++++
> ?3 ?7 23 27 39 43 ++
> ?4 10 21 37 38 48 +
> ?6 18 30 35 36 42 +
> ?3 14 23 43 46 48 +
> 10 11 19 26 42 46 +
> ?1 ?5 27 34 42 45
> ?1 16 29 33 40 46
> 32 41 43 45 48 51
> ?1 13 23 24 46 49
> 24 25 28 30 32 40
> ?8 14 20 33 50 52 ++
> ?2 16 27 28 33 39
> 13 17 19 32 43 52 ++
> 10 11 16 43 45 49
> ?2 ?4 20 22 35 44
> ?1 12 18 36 37 40 +
> ?8 10 16 22 35 47
> ?8 11 16 31 45 46
> 11 13 22 25 26 27 +
> ?3 17 25 26 29 40 +++
> ?7 10 27 37 46 47 +
> ?3 ?5 ?7 27 33 40 ++
> ?4 14 28 37 40 44
> 18 22 25 33 43 48
> 11 19 26 30 44 50 ++
> ?3 11 22 42 46 51 +
> ?7 ?8 21 26 30 50 ++++
> ?6 13 15 23 37 39
> 12 17 31 37 43 47 +
> ?2 ?7 11 21 33 42 ++
> ?2 21 26 37 39 50 +++
> ?6 26 37 38 42 46 +
> 18 19 24 34 40 49
> ?2 ?9 12 17 31 42 +
> ?5 14 30 32 34 49
> ?7 14 29 41 49 50 ++
> ?3 ?7 43 45 46 47 ++
> 12 22 31 37 40 51
> ?1 ?3 ?5 11 28 46 +
> ?6 ?7 12 22 30 32 +
> 13 18 20 25 26 49 +
> 14 19 22 41 49 50 +
> ?3 ?4 12 20 39 42 +
> ?9 18 31 44 46 49
> ?9 20 24 27 41 45
> ?6 ?8 27 31 45 52 +
> 22 34 35 40 41 42
> ?1 ?8 15 37 38 45
> ?6 ?9 13 16 35 51
> ?6 14 17 30 33 52 ++
> 14 27 31 34 40 51
> ?2 11 21 34 36 46 ++
> ?1 ?3 12 15 47 51 +
> ?4 ?5 26 30 32 37 +
> ?4 10 18 29 37 51
> ?8 33 35 36 39 43 +
> ?9 17 22 23 40 52 ++
> ?3 31 34 38 47 50 ++
> 21 26 27 33 41 50 +++
> ?1 10 15 26 40 43 +
> ?9 15 17 25 40 42 +
> ?6 11 23 26 30 45 +
> ?1 ?5 ?9 33 44 51
> 13 15 20 22 27 48
> ?3 ?5 10 11 17 32 ++
>
> C:\Python31\user\lotto>
> 
>
> Now I can study the output for as long as I want.
>
> Also, I could have done this:
>
> ? ? C:\Python31\user\lotto>..\..\python lotto_2010.py >
> lotto_output.txt
>
> and directed the output to a file for editing and/or printing.
>
Thanks!


From darragh.ssa at gmail.com  Fri May 14 05:33:23 2010
From: darragh.ssa at gmail.com (darragh)
Date: Fri, 14 May 2010 02:33:23 -0700 (PDT)
Subject: d-cm Controll Manager
Message-ID: 

Hey,
I'm developing d-cm, it's a program for web-developers that often need
a text-editor,file-manager,sql-manager,ftp-manager.  d-cm combines all
of them in one easy to use program.

i'm looking for people that would like to help developing or to test
the program.
http://code.google.com/p/d-cm


From jackie.space at gmail.com  Fri May 14 05:40:40 2010
From: jackie.space at gmail.com (Jackie Lee)
Date: Fri, 14 May 2010 02:40:40 -0700 (PDT)
Subject: write a 20GB file
Message-ID: 

Hello there,

I have a 22 GB binary file, a want to change values of specific
positions. Because of the volume of the file, I doubt my code a
efficient one:

#! /usr/bin/env python
#coding=utf-8
import sys
import struct

try:
        f=open(sys.argv[1],'rb+')
except (IOError,Exception):
    print '''usage:
        scriptname segyfilename
'''
    sys.exit(1)

#skip EBCDIC header
try:
    f.seek(3200)
except Exception:
    print 'Oops! your file is broken..'

#read binary header
binhead = f.read(400)
ns = struct.unpack('>h',binhead[20:22])[0]
if ns < 0:
    print 'file read error'
    sys.exit(1)

#read trace header
while True:
    f.seek(28,1)
    f.write(struct.pack('>h',1))
    f.seek(212,1)
    f.seek(ns*4,1)

f.close()


From bruno.42.desthuilliers at websiteburo.invalid  Fri May 14 06:14:57 2010
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Fri, 14 May 2010 12:14:57 +0200
Subject: How to add callbacks that is the same function with different
	argument in Tkinter python26?
In-Reply-To: 
References: 
	
Message-ID: <4bed22a1$0$9131$426a34cc@news.free.fr>

Jean-Michel Pichavant a ?crit :
> chen zeguang wrote:
>> code is in the end.
>> I want to print different number when pressing different button.
>> Yet the program outputs 8 no matter which button is pressed.
>> I guess it's because the callback function is not established untill 
>> the button is pressed, and i has already reached to 8.

[answering to the op]
The key here is that the current value of 'i' is not captured when the 
lambda function is created. To make it work, you'd have to capture the 
current value of 'i', which is usually done using a default argument ie:

for i in range(9):
     func_en.append(lambda i=i:func(i))

Now there are other solutions...

> 
> def func(x):
>    def _printme():
>        print x
>    return _printme
> 
> for i in range(9):
>    Button(root, text='%d'%i, command=func(i)).pack()
> 
> Surely someone will explain why your code was not working,

done !-)

> I can't 
> 'cause I don't use lambda, it brings more problems than it solves (maybe 
> I'm not talented enough).
> Above is how I would have written the code, I tested it, looks like it's 
> working.

FWIW, there's now (since 2.5 IIRC) a stdlib way to solve this kind of 
problems:

from functools import partial

def printme(x):
     print x

for i in range(9):
    Button(root, text='%d'%i, command=partial(printme,i)).pack()

HTH


From kaklis at gmail.com  Fri May 14 06:46:13 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Fri, 14 May 2010 03:46:13 -0700 (PDT)
Subject: cmd app and xml
Message-ID: <5363cc2f-04c7-469e-a3d3-a21813c48bbb@i10g2000yqh.googlegroups.com>

Hi there,
i'm writing a console app using the cmd library. I also use
xml.dom.minidom to parse an xml file that i get as a response to an
HTTP Post request.
with
data = response.read()
i get the xml response from the server.
i then feed the parser with that data.
myDoc = parse(data)
but it doesn't work.
To make it work i open an xml file and the save the data to that file.
myDoc = parse('test.xml')
that worked.
But i don't want to use the local xml file?
What am i doing wrong?

Thanks in advance
A.


From davea at ieee.org  Fri May 14 07:04:37 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 14 May 2010 07:04:37 -0400
Subject: write a 20GB file
In-Reply-To: 
References: 
Message-ID: <4BED2E45.6060301@ieee.org>

Jackie Lee wrote:
> Hello there,
>
> I have a 22 GB binary file, a want to change values of specific
> positions. Because of the volume of the file, I doubt my code a
> efficient one:
>
> #! /usr/bin/env python
> #coding=utf-8
> import sys
> import struct
>
> try:
>         f=open(sys.argv[1],'rb+')
> except (IOError,Exception):
>     print '''usage:
>         scriptname segyfilename
> '''
>     sys.exit(1)
>
> #skip EBCDIC header
> try:
>     f.seek(3200)
> except Exception:
>     print 'Oops! your file is broken..'
>
> #read binary header
> binhead = f.read(400)
> ns = struct.unpack('>h',binhead[20:22])[0]
> if ns < 0:
>     print 'file read error'
>     sys.exit(1)
>
> #read trace header
> while True:
>     f.seek(28,1)
>     f.write(struct.pack('>h',1))
>     f.seek(212,1)
>     f.seek(ns*4,1)
>
> f.close()
>
>   
I don't see a question anywhere.  So perhaps you just want comments on 
your code.

1) How do you plan to test this?
2) Consider doing a lot more checking to see that you have in fact a 
file of the right type.
3) Fix indentation - perhaps you've accidentally used a tab in the source.
4) Provide a termination condition for the while True loop, which 
currently will (I think) go forever, or perhaps until the disk fills up.
5) Depending on the purpose of this file, you should consider making the 
changes on a copy, then deleting and renaming.  As it stands, if the 
program gets aborted part way through, there's no way to know how far it 
got.  Since it's just clobbering bytes, it would be safe to rerun the 
same program again, but many times that's not the case.  And this 
program clearly isn't finished yet, so perhaps it's not true here either.
6) I don't see anything inefficient about it.  The nature of the problem 
is going to be very slow (for small values of ns), but I don't know what 
your code could do to speed it up.  Perhaps make sure the file is on a 
fast drive, and not RAID 5.

DaveA



From stefan_ml at behnel.de  Fri May 14 07:10:50 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 14 May 2010 13:10:50 +0200
Subject: cmd app and xml
In-Reply-To: <5363cc2f-04c7-469e-a3d3-a21813c48bbb@i10g2000yqh.googlegroups.com>
References: <5363cc2f-04c7-469e-a3d3-a21813c48bbb@i10g2000yqh.googlegroups.com>
Message-ID: 

kaklis at gmail.com, 14.05.2010 12:46:
> Hi there,
> i'm writing a console app using the cmd library. I also use
> xml.dom.minidom to parse an xml file that i get as a response to an
> HTTP Post request.
> with
> data = response.read()
> i get the xml response from the server.
> i then feed the parser with that data.
> myDoc = parse(data)
> but it doesn't work.

Note that "it doesn't work" is not a very complete description of the 
actual problem.


> To make it work i open an xml file and the save the data to that file.
> myDoc = parse('test.xml')
> that worked.
> But i don't want to use the local xml file?
> What am i doing wrong?

Not reading the docs?

http://docs.python.org/library/xml.dom.minidom.html

There is a parseString() function that does what you want.

Stefan



From ldo at geek-central.gen.new_zealand  Fri May 14 07:12:37 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 23:12:37 +1200
Subject: Picking a license
References: 
	
	<2ff3643b-6ef1-4471-8438-dcba0dc93c24@a21g2000yqn.googlegroups.com>
Message-ID: 

In message <2ff3643b-6ef1-4471-8438-
dcba0dc93c24 at a21g2000yqn.googlegroups.com>, Patrick Maupin wrote:

> On May 13, 10:04 pm, Lawrence D'Oliveiro
>  wrote:
>
>> In message , Ed
>> Keith wrote:
>>
>>> The claim is being made that [the GPL] restricts freedom.
>>
>> What about the ?freedom? to restrict other people?s freedom? Should that
>> be restricted or not?
> 
> It's interesting that some people don't like the comparison of the
> Free Software movement to a religion, yet the main argument of the
> movement, and the deliberate co-opting of words like "Free" and "Free
> Software" ...

Haven?t you ?co-opted? those words yourself?


From ldo at geek-central.gen.new_zealand  Fri May 14 07:13:32 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Fri, 14 May 2010 23:13:32 +1200
Subject: Picking a license
References: 
	
	<2b17ee77-0e49-4a97-994c-7582f86c0ba9@r34g2000yqj.googlegroups.com>
Message-ID: 

In message 
<2b17ee77-0e49-4a97-994c-7582f86c0ba9 at r34g2000yqj.googlegroups.com>, Patrick 
Maupin wrote:

> On May 13, 10:06 pm, Lawrence D'Oliveiro
>  wrote:
>
>> Under the GPL, everybody has exactly the same freedoms.
> 
> That's absolutely not true.  For a start, the original author can dual-
> license.

That?s nothing to do with the GPL.


From jackie.space at gmail.com  Fri May 14 07:32:15 2010
From: jackie.space at gmail.com (Jackie Lee)
Date: Fri, 14 May 2010 18:32:15 +0700
Subject: write a 20GB file
In-Reply-To: <4BED2E45.6060301@ieee.org>
References: 
	<4BED2E45.6060301@ieee.org>
Message-ID: 

Thx, Dave,

The code works fine. I just don't know how f.write works. It says that
file.write won't write the file until file.close or file.flush. So I
don't know if the following one is more efficient (sorry I forget to
add condition to break the loop):

#! /usr/bin/env python
#coding=utf-8
import sys
import struct

try:
        f=open(sys.argv[1],'rb+')
except (IOError,Exception):
    print '''usage:
        scriptname segyfilename
'''
    sys.exit(1)

#skip EBCDIC header
try:
    f.seek(3200)
except Exception:
    print 'Oops! your file is broken..'

#read binary header
binhead = f.read(400)
ns = struct.unpack('>h',binhead[20:22])[0]
if ns < 0:
    print 'file read error'
    sys.exit(1)

#read trace header
while True:
    f.seek(28,1)
    if f.read(2) == '':
        break
    f.seek(-2,1)
    f.write(struct.pack('>h',1))
    f.seek(210,1)
    f.seek(ns*4,1)

f.close()


On Fri, May 14, 2010 at 6:04 PM, Dave Angel  wrote:
> Jackie Lee wrote:
>>
>> Hello there,
>>
>> I have a 22 GB binary file, a want to change values of specific
>> positions. Because of the volume of the file, I doubt my code a
>> efficient one:
>>
>> #! /usr/bin/env python
>> #coding=utf-8
>> import sys
>> import struct
>>
>> try:
>> ? ? ? ?f=open(sys.argv[1],'rb+')
>> except (IOError,Exception):
>> ? ?print '''usage:
>> ? ? ? ?scriptname segyfilename
>> '''
>> ? ?sys.exit(1)
>>
>> #skip EBCDIC header
>> try:
>> ? ?f.seek(3200)
>> except Exception:
>> ? ?print 'Oops! your file is broken..'
>>
>> #read binary header
>> binhead = f.read(400)
>> ns = struct.unpack('>h',binhead[20:22])[0]
>> if ns < 0:
>> ? ?print 'file read error'
>> ? ?sys.exit(1)
>>
>> #read trace header
>> while True:
>> ? ?f.seek(28,1)
>> ? ?f.write(struct.pack('>h',1))
>> ? ?f.seek(212,1)
>> ? ?f.seek(ns*4,1)
>>
>> f.close()
>>
>>
>
> I don't see a question anywhere. ?So perhaps you just want comments on your
> code.
>
> 1) How do you plan to test this?
> 2) Consider doing a lot more checking to see that you have in fact a file of
> the right type.
> 3) Fix indentation - perhaps you've accidentally used a tab in the source.
> 4) Provide a termination condition for the while True loop, which currently
> will (I think) go forever, or perhaps until the disk fills up.
> 5) Depending on the purpose of this file, you should consider making the
> changes on a copy, then deleting and renaming. ?As it stands, if the program
> gets aborted part way through, there's no way to know how far it got. ?Since
> it's just clobbering bytes, it would be safe to rerun the same program
> again, but many times that's not the case. ?And this program clearly isn't
> finished yet, so perhaps it's not true here either.
> 6) I don't see anything inefficient about it. ?The nature of the problem is
> going to be very slow (for small values of ns), but I don't know what your
> code could do to speed it up. ?Perhaps make sure the file is on a fast
> drive, and not RAID 5.
>
> DaveA
>
>



-- 
Jackie


From kaklis at gmail.com  Fri May 14 08:14:00 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Fri, 14 May 2010 05:14:00 -0700 (PDT)
Subject: cmd app and xml
References: <5363cc2f-04c7-469e-a3d3-a21813c48bbb@i10g2000yqh.googlegroups.com>
	
Message-ID: <41cb09f0-f603-4d83-8315-965bfc2d58f2@j35g2000yqm.googlegroups.com>

On May 14, 7:10?am, Stefan Behnel  wrote:
> kak... at gmail.com, 14.05.2010 12:46:
>
> > Hi there,
> > i'm writing a console app using the cmd library. I also use
> > xml.dom.minidom to parse an xml file that i get as a response to an
> > HTTP Post request.
> > with
> > data = response.read()
> > i get the xml response from the server.
> > i then feed the parser with that data.
> > myDoc = parse(data)
> > but it doesn't work.
>
> Note that "it doesn't work" is not a very complete description of the
> actual problem.
>
> > To make it work i open an xml file and the save the data to that file.
> > myDoc = parse('test.xml')
> > that worked.
> > But i don't want to use the local xml file?
> > What am i doing wrong?
>
> Not reading the docs?
>
> http://docs.python.org/library/xml.dom.minidom.html
>
> There is a parseString() function that does what you want.
>
> Stefan

ok, i missed that function.
Thank you so much!!
Antonis


From ethan at stoneleaf.us  Fri May 14 09:04:52 2010
From: ethan at stoneleaf.us (Ethan Furman)
Date: Fri, 14 May 2010 06:04:52 -0700
Subject: Picking a license
In-Reply-To: <4bece8de$0$8761$c3e8da3@news.astraweb.com>
References: 	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>			<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>	
	<4bece8de$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <4BED4A74.6060203@stoneleaf.us>

Steven D'Aprano wrote:
> On Thu, 13 May 2010 19:10:09 -0700, Patrick Maupin wrote:
>>The only time
>>that comes into play in my programming life is *when I have to recode*
>>something that is nominally available under the GPL,
> 
> You've never had to recode something because it was nominally available 
> under a proprietary licence that you (or your client) was unwilling to 
> use? Lucky you!

Steven, did you actually read what he wrote?  If you did, why would you 
say something so stupid?

~Ethan~


From saharabear at gmail.com  Fri May 14 09:18:28 2010
From: saharabear at gmail.com (Haulyn Jason)
Date: Fri, 14 May 2010 21:18:28 +0800
Subject: Data store solution need help
Message-ID: <4BED4DA4.8050604@gmail.com>

Hi, all:

I am a Java programmer, now I am working on a Python program. At the 
moment, I need to store some data from user's input, no database, no 
xml, no txt(we can not make users open the data file by vim or other 
text editor).

Any suggestions or reference url? Is there a lib should do this or I 
need to implement it myself?

PS: if I want to implement it myself, which part of python document I 
need to learn? I know how to write txt files now, but not further for me.

-- 
Thanks!

VVThumb Microproduction

Location:Room 807,QiLuRuanJianDaSha Qilu Software Park
          No. 1 Shunhua Rd High-Tech Development Zone
          Jinan, China 250101
Website: http://www.haulynjason.net/haulyn
Mobile: +86 15854103759

Haulyn Jason



From paul at boddie.org.uk  Fri May 14 09:26:14 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 06:26:14 -0700 (PDT)
Subject: Picking a license
References: 
	<9c5518c4-fe99-4f7b-8c39-c0e6929b730c@q30g2000yqd.googlegroups.com>
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com> 
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
Message-ID: 

On 13 Mai, 22:10, Patrick Maupin  wrote:
>

[...]

Just to deal with your Ubuntu "high horse" situation first, you should
take a look at the following for what people regard to be the best
practices around GPL-licensed software distribution:

http://www.softwarefreedom.org/resources/2008/compliance-guide.html

If you still think Ubuntu are violating the GPL or encouraging others
to do so, feel free to contact their lawyers who I'm sure will be very
interested to hear from you.

> When the leader of your religion bandies terms like "freedom" and
> "evil" about, what do you expect? ?Seriously?

I thought you were "done". I guess you are: again, we have the usual
courting of public outrage by labelling stuff you don't like as
"religion" - presumably not the "right one", either - when it is no
such thing.

[...]

> My primary agenda is to explain that RMS does, in fact, have an
> agenda, and the GPL was designed as a tool in furtherance of that
> agenda, and that while the agenda does have some arguably noble goals,
> before using the GPL people should understand its consequences both
> for good and bad, and make their own determination about whether it's
> the right license for their project.

Reading through your "translations" of what are effectively honest
summaries, one gets the impression that you have quite a chip on your
shoulder about the FSF and RMS. Referring to the GPL as a "commercial"
licence and stating that it (as opposed to any other licence or even
the word "copyright" followed by a name) is a threat to sue people,
presumably appealing to the libertarian crowd with a judicious mention
of "government" just to fan the flames of supposed injustice, really
does triangulate where you are coming from. So, yes, we're now rather
more aware of what your agenda is, I think.

And I don't think it improves any argument you may have by projecting
notions of "morality" or "immorality" onto what I have written,
especially when I have deliberately chosen to use other terms which
avoid involving such notions, or by equating the copyleft licences
with criminal enterprises ("pyramid scheme"), or by suggesting that I
endorse criminal endeavours. But if that's what you have left to say
at this point, then I think you probably are "done".

Paul


From paul at boddie.org.uk  Fri May 14 09:35:16 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 06:35:16 -0700 (PDT)
Subject: Picking a license
References: 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-b
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	
Message-ID: 

On 14 Mai, 03:56, a... at pythoncraft.com (Aahz) wrote:
>
> IMO this only makes sense if one agrees that people should not be allowed
> to sell software for money. ?Absent that agreement, your argument about
> freedom seems rather limited.

You'll have to explain this to me because I don't quite follow your
assertion. You can sell copyleft-licensed software, although I accept
that you can't set an arbitrarily high price on the sources for
someone who has already acquired a binary distribution.

Paul


From e_d_k at yahoo.com  Fri May 14 09:39:05 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 06:39:05 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <779006.76311.qm@web58707.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 11:06 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > Assertion I:
> >? ? If person A is free to do more than
> person B, then person A has
> >? ? more freedom then person B.
> > 
> > Assertion II:
> >? ? If person A is free do perform an action
> person B is not free to
> >? ? perform then person A is free to do more
> than person B.
> > 
> > Assertion III:
> >???If person B is restricted in some way
> that person A is not them Person A
> >???is free to do something Person B is
> not free to do.
> > 
> > Conclusion:
> >???If person B is more resticted than
> Peston A, Person A has mor freedom
> >???than person B.
> > 
> > Which step in this reasoning do you disagree with?
> 
> Under the GPL, everybody has exactly the same freedoms. So
> which of your 
> assertions is supposedly a criticism of the GPL?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Yes, under the GPL every one has one set of freedoms, under the MIT or Boost license every one has more freedoms. Under other licenses they have fewer freedoms. 

None of my point criticize the GPL, they merely defend my claim that a more permissive license grants more freedom. You claimed the contrary. 

Are you withdrawing your previous claim, or will you directly refute my arguments?

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From bruno.42.desthuilliers at websiteburo.invalid  Fri May 14 09:42:00 2010
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Fri, 14 May 2010 15:42:00 +0200
Subject: Data store solution need help
In-Reply-To: 
References: 
Message-ID: <4bed5326$0$27708$426a74cc@news.free.fr>

Haulyn Jason a ?crit :
> Hi, all:
> 
> I am a Java programmer, now I am working on a Python program. At the 
> moment, I need to store some data from user's input, no database, no 
> xml, no txt(we can not make users open the data file by vim or other 
> text editor).
> 
> Any suggestions or reference url? Is there a lib should do this or I 
> need to implement it myself?
> 
> PS: if I want to implement it myself, which part of python document I 
> need to learn? I know how to write txt files now, but not further for me.
> 

Not sure I really understand whether you want to store your data in just 
any format or if it need to be a "binary" format or else... And you 
don't tell much about how your data structure and how it will be used.

Anyway: two possible solutions are csv or serialization.

For the first option, see the csv module
http://docs.python.org/library/csv.html#module-csv

For the second, look at pickle and shelve modules:
http://docs.python.org/library/pickle.html#module-pickle
http://docs.python.org/library/shelve.html#module-shelve


If none of this fits your needs, please provide more details !-)
HTH


From e_d_k at yahoo.com  Fri May 14 09:42:31 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 06:42:31 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <440135.15702.qm@web58708.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 11:07 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > On Thu, 5/13/10, Lawrence D'Oliveiro
> > 
> wrote:
> > 
> >> In message ,
> >> Ed Keith wrote:
> >> 
> >>> So if you want me to even consider using your
> library
> >>> do not use GPL, or LGPL.
> >> 
> >> What have you got against LGPL for this purpose?
> > 
> > Most of my clients would not know how to relink a
> program if their life
> > depended on it. And I do not want to put then in DLL
> hell. So I avoid the
> > LGPL.
> 
> How exactly does the LGPL lead to a requirement to
> ?relink??
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

I am not a lawyer, but as I understand the LGPL, If I give someone something that used any LGPLed code I must give them the ability to relink it with any future releases of the LGPLed code. I think that means that I need to give them a linker and teach them how to use it, and I do not want to go there.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From e_d_k at yahoo.com  Fri May 14 09:47:11 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 06:47:11 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <2b17ee77-0e49-4a97-994c-7582f86c0ba9@r34g2000yqj.googlegroups.com>
Message-ID: <125692.28959.qm@web58703.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Patrick Maupin  wrote:

> From: Patrick Maupin 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 11:45 PM
> On May 13, 10:06?pm, Lawrence
> D'Oliveiro  central.gen.new_zealand> wrote:
> > In message ,
> Ed Keith
> > wrote:
> >
> >
> >
> > > Assertion I:
> > > ? ?If person A is free to do more than person
> B, then person A has
> > > ? ?more freedom then person B.
> >
> > > Assertion II:
> > > ? ?If person A is free do perform an action
> person B is not free to
> > > ? ?perform then person A is free to do more
> than person B.
> >
> > > Assertion III:
> > > ? If person B is restricted in some way that
> person A is not them Person A
> > > ? is free to do something Person B is not free
> to do.
> >
> > > Conclusion:
> > > ? If person B is more resticted than Peston A,
> Person A has mor freedom
> > > ? than person B.
> >
> > > Which step in this reasoning do you disagree
> with?
> >
> > Under the GPL, everybody has exactly the same
> freedoms. So which of your
> > assertions is supposedly a criticism of the GPL?
> 
> That's absolutely not true.? For a start, the original
> author can dual-
> license.? This is not a theoretical issue -- it is a
> multi-million
> dollar issue.
> 
> Regards,
> Pat
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Everyone I personally know who has released code under the GPL either dual-licenses, or hopes to.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From python.list at tim.thechases.com  Fri May 14 09:47:13 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Fri, 14 May 2010 08:47:13 -0500
Subject: Data store solution need help
In-Reply-To: <4BED4DA4.8050604@gmail.com>
References: <4BED4DA4.8050604@gmail.com>
Message-ID: <4BED5461.9010806@tim.thechases.com>

On 05/14/2010 08:18 AM, Haulyn Jason wrote:
> I am a Java programmer, now I am working on a Python program. At the
> moment, I need to store some data from user's input, no database, no
> xml, no txt(we can not make users open the data file by vim or other
> text editor).

You don't mention what type of data you want to store?  Is it a 
single string?  Multiple strings?  Complex nested data?

And how do you want to access it?

Python provides you any number of options:

- you can use standard Python file objects to read/write content 
in a file format of your own definition

- you can use the ConfigParser module to read/write an old-school 
.INI style file (which can also be edited in a text editor, but 
doesn't have to be)

- you can use the "anydbm" module to store key/value pairs of 
strings with an internal user-interface much like a dictionary

- you can use the "pickle" module to persist Python objects into 
files

- you can use the "shelve" module to combine the "pickle" 
persistence with the DBM layer

- you can use the built-in (as of Python2.5) "sqlite3" module for 
a single-file database with full SQL capabilities without the 
need to install a SQL server (MySQL, PostgreSQL, MS SQL Server, etc)

- you can persist to cloud storage or to your own web-server 
using the urllib/urllib2 modules


But without knowing what you want to store or how you want to 
access it, it's hard to offer more concrete advice.

-tkc








From paul at boddie.org.uk  Fri May 14 09:47:30 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 06:47:30 -0700 (PDT)
Subject: Picking a license
References:  
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
Message-ID: <9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com>

On 14 Mai, 05:35, Patrick Maupin  wrote:
>
> I mean, it's in English and very technically precise, but if you
> follow all the references, you quickly come to realize that the
> license is a "patch" to the GPL.

It is a set of exceptions applied to version 3 of the GPL, done this
way so that the exceptions machinery of the GPL can be used to remove
them if desired, as opposed to getting into the business of allowing
people to relicense works from the LGPL to the GPL, as was the case
with previous versions of these licences. You don't even have to read
as far as the first clause of the LGPL terms to be told this, but I
guess there's more "sport" in taking cheap shots at the authors than
reading three lines down from the top of the text.

Paul


From e_d_k at yahoo.com  Fri May 14 09:53:54 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 06:53:54 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <4bece8de$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <967692.89720.qm@web58707.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Steven D'Aprano  wrote:
> 
> The GPL ensures that once software has entered the commons
> (and therefore 
> available for all), it can never be removed from the
> commons. The MIT 
> licence does not. Now, you might argue that in practice
> once software is 
> released under an MIT licence, it is unlikely to ever
> disappear from the 
> commons. Well, perhaps, but if so, that's despite and not
> because of the 
> licence.

Why is MIT licensed code any more likely to dispersal from the common that GPLed code? Does using the GPL somehow grantee that my server will never crash?


> 
> In practice, I believe most MIT-licenced code never even
> makes it into 
> the commons in the first place. I'm willing to predict that
> the majority 
> of code you've written for paying customers (as opposed to
> specifically 
> for open source projects) has disappeared into their code
> base, never to 
> be seen by anyone outside of the company. Am I right?

Yes, but it was licensed to the client, and never enter into the commons, That which never enters into the commons can never be removed.

Any MIT licensed code that I may have used is still in the common. My using it did not reomove it from the common. 

Has the fact that Python has been used for many commercial/propitiatory projects reduced your ability to make use of it? If so how?

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From mehgcap at gmail.com  Fri May 14 09:56:02 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Fri, 14 May 2010 09:56:02 -0400
Subject: Data store solution need help
In-Reply-To: <4bed5326$0$27708$426a74cc@news.free.fr>
References: 
	<4bed5326$0$27708$426a74cc@news.free.fr>
Message-ID: 

An important question is: will you need this input stored across
multiple runs of the program? What I mean is, do you want the user to
set the data, then have those same settings even after closing and
re-opening the program?

On 5/14/10, Bruno Desthuilliers
 wrote:
> Haulyn Jason a ?crit :
>> Hi, all:
>>
>> I am a Java programmer, now I am working on a Python program. At the
>> moment, I need to store some data from user's input, no database, no
>> xml, no txt(we can not make users open the data file by vim or other
>> text editor).
>>
>> Any suggestions or reference url? Is there a lib should do this or I
>> need to implement it myself?
>>
>> PS: if I want to implement it myself, which part of python document I
>> need to learn? I know how to write txt files now, but not further for me.
>>
>
> Not sure I really understand whether you want to store your data in just
> any format or if it need to be a "binary" format or else... And you
> don't tell much about how your data structure and how it will be used.
>
> Anyway: two possible solutions are csv or serialization.
>
> For the first option, see the csv module
> http://docs.python.org/library/csv.html#module-csv
>
> For the second, look at pickle and shelve modules:
> http://docs.python.org/library/pickle.html#module-pickle
> http://docs.python.org/library/shelve.html#module-shelve
>
>
> If none of this fits your needs, please provide more details !-)
> HTH
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


From utente at esempio.net  Fri May 14 10:02:19 2010
From: utente at esempio.net (superpollo)
Date: Fri, 14 May 2010 16:02:19 +0200
Subject: Data store solution need help
In-Reply-To: 
References: 
Message-ID: <4bed57ec$0$18997$4fafbaef@reader5.news.tin.it>

Haulyn Jason ha scritto:
> Hi, all:
> 
> I am a Java programmer, now I am working on a Python program. At the 
> moment, I need to store some data from user's input, no database, no 
> xml, no txt(we can not make users open the data file by vim or other 
> text editor).

security thru obscurity? mmmhhh...


From e_d_k at yahoo.com  Fri May 14 10:10:50 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 07:10:50 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
Message-ID: <375036.32165.qm@web58706.mail.re1.yahoo.com>

--- On Thu, 5/13/10, Patrick Maupin  wrote:

> From: Patrick Maupin 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Thursday, May 13, 2010, 11:35 PM
> On May 13, 10:07?pm, Lawrence
> D'Oliveiro  central.gen.new_zealand> wrote:
> 
> > How exactly does the LGPL lead to a requirement to
> ?relink??
> 
> I think this might be a misconception, but I'm not 100%
> sure.? Since
> Ed gives his customers full source code, there may not be
> the
> requirement to directly provide the ability to relink,
> because "The
> ?Corresponding Application Code? for a Combined Work
> means the object
> code and/or source code for the Application." and section
> 4d0 requires
> you to "permit the user to recombine or relink" where
> "recombine"
> isn't defined directly (perhaps in the underlying GPL?)

But if my client give someone else a copy of the binary I gave them, they are now in violation. I do not want to put my client in this position. 

When using the GPL or LGPL you can do anything you want as long as you do not let anyone else use your work, but if you let someone else have a copy of you work you are putting them in a position where that can easily/inadvertently violate the law. I do not want to put clients in legal jeopardy, so I do not use GPL, or LGPLed code.

I do not claim that using the GLP is immoral, nor deny others right to use it. I just feel the risks out way the benefits for me.

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Fri May 14 10:28:06 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 07:28:06 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <4bece8de$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <157842.21043.qm@web58707.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Steven D'Aprano  wrote:

> The GPL ensures that once software has entered the commons
> (and therefore 
> available for all), it can never be removed from the
> commons. The MIT 
> licence does not. Now, you might argue that in practice
> once software is 
> released under an MIT licence, it is unlikely to ever
> disappear from the 
> commons. Well, perhaps, but if so, that's despite and not
> because of the 
> licence.


Several years ago I released a C++ library under the Boost license. I put it up on a small free server. Later my hard drive crashed, both my backup copies were corrupted, and when I went to retrieve it from the site I found it no longer existed.

I am recreating the code, and it will be MUCH better this time, and it is on three web sites, but are you telling me that of I have used the GPL instead of Boost I would not have had this problem?

I use the Boost Libraries (http://www.boost.org/) in most of my code. Do you believe they are likely to disappear because they are not covered by the GPL?

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From aonlazio at gmail.com  Fri May 14 10:32:39 2010
From: aonlazio at gmail.com (AON LAZIO)
Date: Fri, 14 May 2010 10:32:39 -0400
Subject: Setup global variables settings for the entire applications
Message-ID: 

Hi,
   Say I have an application which requires a global settings for the user.
When the user finishes setting those global variables for the app. Any class
can use that variables (which are the same for all), something like that.
What is the suitable mechanism for this solution?
   Thanks in advance

Aonlazio

-- 
Passion is my style
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From dreadpiratejeff at gmail.com  Fri May 14 10:50:49 2010
From: dreadpiratejeff at gmail.com (J)
Date: Fri, 14 May 2010 10:50:49 -0400
Subject: write a 20GB file
In-Reply-To: 
References: 
	<4BED2E45.6060301@ieee.org>
	
Message-ID: 

On Fri, May 14, 2010 at 07:32, Jackie Lee  wrote:
> Thx, Dave,
>
> The code works fine. I just don't know how f.write works. It says that
> file.write won't write the file until file.close or file.flush. So I
> don't know if the following one is more efficient (sorry I forget to
> add condition to break the loop):

someone smarter than me can correct me, but file.write() will write
when it's buffer is filled, or close() or flush() are called.
I don't know what the default buffer size for file.write() is though.
close() flushes the buffer before closing the file, and flush()
flushes the buffer and leaves the file open for further writing.

> try:
> ? ? ? ?f=open(sys.argv[1],'rb+')
> except (IOError,Exception):
> ? ?print '''usage:
> ? ? ? ?scriptname segyfilename
> '''

You can just add a f.flush() every time you write to the file, but, I
tend to open files with 0 buffer size like this:

f = open(filename,"rb+",0)

Then again, I don't deal with files of that size, so there could be a
problem with my way once you start scaling up to the 20GB or larger
that you're working with.

Again, I could be wrong about all of that, so if so, I hope someone
will correct me and fix my understanding...

Cheers,

Jeff


From albertkao3 at gmail.com  Fri May 14 10:53:18 2010
From: albertkao3 at gmail.com (albert kao)
Date: Fri, 14 May 2010 07:53:18 -0700 (PDT)
Subject: recursively remove all the directories and files which begin with '.'
Message-ID: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>

How do I recursively remove all the directories and files which begin
with '.'?
My test program rmdir.py does not do the job yet.
Please help.
[code]
#!c:/Python31/python.exe -u
import os
from shutil import *

root = "C:\\test\\com.comp.hw.prod.proj.war\\bin"

for curdir, dirs, files in os.walk(root):
  print (curdir)
  print (dirs)
  for d in dirs:
    print ("d " + d)
    if d.startswith('.'):
      print ("dotd " + os.path.join(curdir, d))
      rmtree(os.path.join(curdir, d))
[/code]

C:\python>rmdir.py
C:\test\com.comp.hw.prod.proj.war\bin
['.svn', 'com']
d .svn
dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
Traceback (most recent call last):
  File "C:\python\rmdir.py", line 14, in 
    rmtree(os.path.join(curdir, d))
  File "C:\Python31\lib\shutil.py", line 235, in rmtree
    onerror(os.remove, fullname, sys.exc_info())
  File "C:\Python31\lib\shutil.py", line 233, in rmtree
    os.remove(fullname)
WindowsError: [Error 5] Access is denied: 'C:\\test\
\com.comp.hw.prod.proj.war\\bin\\.svn\\entries'



From pmaupin at gmail.com  Fri May 14 10:56:09 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 07:56:09 -0700 (PDT)
Subject: Picking a license
References:  
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
	<9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com>
Message-ID: <548024fc-dd56-48b9-907d-3aa6a722b43c@l31g2000yqm.googlegroups.com>

On May 14, 8:47?am, Paul Boddie  wrote:
> On 14 Mai, 05:35, Patrick Maupin  wrote:
>
>
>
> > I mean, it's in English and very technically precise, but if you
> > follow all the references, you quickly come to realize that the
> > license is a "patch" to the GPL.
>
> It is a set of exceptions applied to version 3 of the GPL, done this
> way so that the exceptions machinery of the GPL can be used to remove
> them if desired, as opposed to getting into the business of allowing
> people to relicense works from the LGPL to the GPL, as was the case
> with previous versions of these licences. You don't even have to read
> as far as the first clause of the LGPL terms to be told this, but I
> guess there's more "sport" in taking cheap shots at the authors than
> reading three lines down from the top of the text.
>
> Paul

That's not a cheap shot.  It's a (programmer) technical description of
how the licenses interact, along with an opinion that it would be
easier to read otherwise, along with a quoted snippet that shows (at
least to me) that these are really quite complicated licenses.  The
confusion that some are showing in this thread about whether source
must be distributed certainly helps to show that as well.  Now, it may
well be, and probably is, that the licenses are as simple as they can
be for the desired effect, but that doesn't make them simple.

Regards,
Pat


From pmaupin at gmail.com  Fri May 14 10:57:25 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 07:57:25 -0700 (PDT)
Subject: Picking a license
References: 
Message-ID: <578ec00e-86ac-46d3-8ae9-d26d43068652@r11g2000yqa.googlegroups.com>

On May 14, 9:10?am, Ed Keith  wrote:
> --- On Thu, 5/13/10, Patrick Maupin  wrote:
>
>
>
> > From: Patrick Maupin 
> > Subject: Re: Picking a license
> > To: python-l... at python.org
> > Date: Thursday, May 13, 2010, 11:35 PM
> > On May 13, 10:07?pm, Lawrence
> > D'Oliveiro  > central.gen.new_zealand> wrote:
>
> > > How exactly does the LGPL lead to a requirement to
> > ?relink??
>
> > I think this might be a misconception, but I'm not 100%
> > sure.? Since
> > Ed gives his customers full source code, there may not be
> > the
> > requirement to directly provide the ability to relink,
> > because "The
> > ?Corresponding Application Code? for a Combined Work
> > means the object
> > code and/or source code for the Application." and section
> > 4d0 requires
> > you to "permit the user to recombine or relink" where
> > "recombine"
> > isn't defined directly (perhaps in the underlying GPL?)
>
> But if my client give someone else a copy of the binary I gave them, they are now in violation. I do not want to put my client in this position.
>
> When using the GPL or LGPL you can do anything you want as long as you do not let anyone else use your work, but if you let someone else have a copy of you work you are putting them in a position where that can easily/inadvertently violate the law. I do not want to put clients in legal jeopardy, so I do not use GPL, or LGPLed code.

Good point.  I guess I haven't distributed something linked in a while
(really just Python), so I tend to forget that aspect of it.

Regards,
Pat



From kaklis at gmail.com  Fri May 14 10:57:48 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Fri, 14 May 2010 07:57:48 -0700 (PDT)
Subject: parsing XML
Message-ID: 

Hi to all, let's say we have the following Xml

  
    17.1
    6.4
  
  
    15.5
    7.8
  


How can i get the players name, age and height?
DOM or SAX and how

Thanks
Antonis


From dreadpiratejeff at gmail.com  Fri May 14 11:01:22 2010
From: dreadpiratejeff at gmail.com (J)
Date: Fri, 14 May 2010 11:01:22 -0400
Subject: recursively remove all the directories and files which begin with
	'.'
In-Reply-To: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>
References: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>
Message-ID: 

On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>
> C:\python>rmdir.py
> C:\test\com.comp.hw.prod.proj.war\bin
> ['.svn', 'com']
> d .svn
> dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
> Traceback (most recent call last):
> ?File "C:\python\rmdir.py", line 14, in 
> ? ?rmtree(os.path.join(curdir, d))
> ?File "C:\Python31\lib\shutil.py", line 235, in rmtree
> ? ?onerror(os.remove, fullname, sys.exc_info())
> ?File "C:\Python31\lib\shutil.py", line 233, in rmtree
> ? ?os.remove(fullname)
> WindowsError: [Error 5] Access is denied: 'C:\\test\
> \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

You don't have permissions to remove the subdir or file entries in the
.svn directory...

Maybe that file is still open, or still has a lock attached to it?


From pmaupin at gmail.com  Fri May 14 11:04:53 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 08:04:53 -0700 (PDT)
Subject: Picking a license
References: 
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com> 
	 
	<4bece8de$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <79811fa0-f8bb-4ec8-acc3-a4a1727a8e78@k42g2000yqb.googlegroups.com>

On May 14, 1:08?am, Steven D'Aprano  wrote:
> On Thu, 13 May 2010 19:10:09 -0700, Patrick Maupin wrote:
> > The broken window fallacy is about labor that could have been spent
> > elsewhere if someone else had done something differently. ?The only time
> > that comes into play in my programming life is when I have to recode
> > something that is nominally available under the GPL, so I'm not sure
> > this is really making the point you think it is.
>
> You've never had to recode something because it was nominally available
> under a proprietary licence that you (or your client) was unwilling to
> use? Lucky you!

Don't be silly.  That's why I started writing open source software in
the first place.  But if I start writing stuff to put in the commons
with strings removed, why would I bother with a license that just adds
some strings back?

> The GPL ensures that once software has entered the commons (and therefore
> available for all), it can never be removed from the commons.

No it doesn't.  It just insures that if people actually *distribute*
the software to others, they have to distribute the source.  In any
case, for software to remain in the commons, it has to be available
where people can get to it.  Somebody has to care enough to maintain a
repository, or it has to be good enough for people to distribute.

> The MIT licence does not.

The only difference is that somebody has to care enough to maintain a
repository, or it has to be good enough for people to distribute
*along with source*.

> Now, you might argue that in practice once software is
> released under an MIT licence, it is unlikely to ever disappear from the
> commons.

Depends on the software.  See above.

> Well, perhaps, but if so, that's despite and not because of the
> licence.

Same thing for GPLed software.  See above.

> In practice, I believe most MIT-licenced code never even makes it into
> the commons in the first place.

Interesting assertion.

> I'm willing to predict that the majority
> of code you've written for paying customers (as opposed to specifically
> for open source projects) has disappeared into their code base, never to
> be seen by anyone outside of the company. Am I right?

That's true, but what on earth does that have to do with the MIT
license?

Regards,
Pat


From martin at v.loewis.de  Fri May 14 11:07:01 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Fri, 14 May 2010 17:07:01 +0200
Subject: write a 20GB file
In-Reply-To: 
References: 	<4BED2E45.6060301@ieee.org>
	
Message-ID: <4BED6715.1000106@v.loewis.de>

> The code works fine. I just don't know how f.write works. It says that
> file.write won't write the file until file.close or file.flush.

You are misinterpreting the documentation. It certainly won't keep the
entire file in memory. Instead, it has a fixed-size buffer (something
like 8kiB or 32kiB) in which it writes and which it flushes when that
buffer is full.

The comment about flush and close merely refers to the problem that some
data may still be in the buffer at any point in time, unless you just
called close or flush.

HTH,
Martin


From martin at v.loewis.de  Fri May 14 11:07:01 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Fri, 14 May 2010 17:07:01 +0200
Subject: write a 20GB file
In-Reply-To: 
References: 	<4BED2E45.6060301@ieee.org>
	
Message-ID: <4BED6715.1000106@v.loewis.de>

> The code works fine. I just don't know how f.write works. It says that
> file.write won't write the file until file.close or file.flush.

You are misinterpreting the documentation. It certainly won't keep the
entire file in memory. Instead, it has a fixed-size buffer (something
like 8kiB or 32kiB) in which it writes and which it flushes when that
buffer is full.

The comment about flush and close merely refers to the problem that some
data may still be in the buffer at any point in time, unless you just
called close or flush.

HTH,
Martin


From martin at v.loewis.de  Fri May 14 11:15:07 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Fri, 14 May 2010 17:15:07 +0200
Subject: parsing XML
In-Reply-To: 
References: 
Message-ID: 

kaklis at gmail.com wrote:
> Hi to all, let's say we have the following Xml
> 
>   
>     17.1
>     6.4
>   
>   
>     15.5
>     7.8
>   
> 
> 
> How can i get the players name, age and height?
> DOM or SAX and how

Homework?

Martin


From paul at boddie.org.uk  Fri May 14 11:20:06 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 08:20:06 -0700 (PDT)
Subject: Picking a license
References: 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com> 
	<59194ade-46dc-4178-8b76-36038808109b@k2g2000yqe.googlegroups.com> 
	<4bece6a8$0$8761$c3e8da3@news.astraweb.com>
	<804512fb-e9ac-4284-a577-84e609531e06@s4g2000prh.googlegroups.com>
Message-ID: 

On 14 Mai, 09:08, Carl Banks  wrote:
> On May 13, 10:59?pm, Steven D'Aprano  wrote:
> > On Thu, 13 May 2010 17:18:47 -0700, Carl Banks wrote:
> > > 2. Reimplment the functionality seperately (*cough* PySide)
>
> > Yes. So what? In what possible way is this an argument against the GPL?

[...]

> It's not. ?It's an argument that the GPL doesn't do much good.

Right. So nobody got the benefit from Qt under the GPL or PyQt under
the GPL? Even the PySide developers seem hell-bent on picking over the
work of the PyQt developers for ideas, although they obviously won't
touch the code. Nokia seem to have accrued tremendous benefit from the
existence of PyQt because I rather doubt that anyone would have
bothered rolling a set of mature, usable Python bindings for Qt now
had some not existed already and proved that dynamic languages are
worth supporting.

> Arguments against the GPL are found elsewhere in this thread, I don't
> need to repeat them here.

Yes, don't bother. They fit in rather well with the comment you made
above.

Paul


From stefan_ml at behnel.de  Fri May 14 11:22:47 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 14 May 2010 17:22:47 +0200
Subject: parsing XML
In-Reply-To: 
References: 
Message-ID: 

kaklis at gmail.com, 14.05.2010 16:57:
> Hi to all, let's say we have the following Xml
> 
>    
>      17.1
>      6.4
>    
>    
>      15.5
>      7.8
>    
> 
>
> How can i get the players name, age and height?

Here's an overly complicated solution, but I thought that an object 
oriented design would help here.


   import xml.etree.ElementTree as ET

   class Player(object):
      def __init__(self, name, age, height):
          self.name, self.age, self.height = name, age, height

   attributes = ['name', 'age', 'height']

   players = []
   for _, element in ET.iterparse("teamfile.xml"):
       if element.tag == 'player':
           players.append(
               Player(*[ element.get(attr) for attr in attributes ]))

   for player in players:
       print player.name, player.age, player.height


Stefan



From gberbeglia at gmail.com  Fri May 14 11:24:24 2010
From: gberbeglia at gmail.com (gerardob)
Date: Fri, 14 May 2010 08:24:24 -0700 (PDT)
Subject: an element from a set
Message-ID: <28560792.post@talk.nabble.com>


Hello, let S be a python set which is not empty
(http://docs.python.org/library/sets.html)

i would like to obtain one element (anyone, it doesn't matter which one) and
assign it to a variable.

How can i do this? 

Thanks.

-- 
View this message in context: http://old.nabble.com/an-element-from-a-set-tp28560792p28560792.html
Sent from the Python - python-list mailing list archive at Nabble.com.



From albertkao3 at gmail.com  Fri May 14 11:27:50 2010
From: albertkao3 at gmail.com (albert kao)
Date: Fri, 14 May 2010 08:27:50 -0700 (PDT)
Subject: recursively remove all the directories and files which begin with
	'.'
References: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>
	
Message-ID: <67827508-ddda-44e8-8b88-aae4f78e23da@o8g2000yqo.googlegroups.com>

On May 14, 11:01?am, J  wrote:
> On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>
> > C:\python>rmdir.py
> > C:\test\com.comp.hw.prod.proj.war\bin
> > ['.svn', 'com']
> > d .svn
> > dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
> > Traceback (most recent call last):
> > ?File "C:\python\rmdir.py", line 14, in 
> > ? ?rmtree(os.path.join(curdir, d))
> > ?File "C:\Python31\lib\shutil.py", line 235, in rmtree
> > ? ?onerror(os.remove, fullname, sys.exc_info())
> > ?File "C:\Python31\lib\shutil.py", line 233, in rmtree
> > ? ?os.remove(fullname)
> > WindowsError: [Error 5] Access is denied: 'C:\\test\
> > \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> You don't have permissions to remove the subdir or file entries in the
> .svn directory...
>
> Maybe that file is still open, or still has a lock attached to it?

I reboot my windows computer and run this script as administrator.
Do my script has a bug?


From pmaupin at gmail.com  Fri May 14 11:37:14 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 08:37:14 -0700 (PDT)
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	 
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	
Message-ID: <94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com>

On May 14, 8:26?am, Paul Boddie  wrote:
> On 13 Mai, 22:10, Patrick Maupin  wrote:
> Just to deal with your Ubuntu "high horse" situation first, you should
> take a look at the following for what people regard to be the best
> practices around GPL-licensed software distribution:
>
> http://www.softwarefreedom.org/resources/2008/compliance-guide.html

Before, you were busy pointing me at the GPL FAQ as authoritative.
When I show where the FAQ says that you should distribute source if
you give somebody a CD, you point me at a document which is obviously
designed for the Ciscos of the world.

> If you still think Ubuntu are violating the GPL or encouraging others
> to do so, feel free to contact their lawyers who I'm sure will be very
> interested to hear from you.

Did I *ever* say that Ubuntu was violating the GPL.  No.  Do I believe
that the practices of any binary Linux distribution that fits on a
single CD make it easy for the downloader/burner to violate the GPL.
Yes.
>
> > When the leader of your religion bandies terms like "freedom" and
> > "evil" about, what do you expect? ?Seriously?
>
> I thought you were "done". I guess you are: again, we have the usual
> courting of public outrage by labelling stuff you don't like as
> "religion" - presumably not the "right one", either - when it is no
> such thing.

Well, you conveniently ignore sections of your bible (for example, the
part of the FAQ where it says you should distribute source with
binary) and reach for more obscure scrolls whenever the real world
gets in the way of your fantasy.  Even here, you don't bother to quote
what you wrote, which would show I am just responding to your outrage.

> > My primary agenda is to explain that RMS does, in fact, have an
> > agenda, and the GPL was designed as a tool in furtherance of that
> > agenda, and that while the agenda does have some arguably noble goals,
> > before using the GPL people should understand its consequences both
> > for good and bad, and make their own determination about whether it's
> > the right license for their project.
>
> Reading through your "translations" of what are effectively honest
> summaries.

There are multiple sides to every discussion, and everybody comes to
the table with biases.  If you honestly think that you are not biased,
then you are deluding yourself.  If you realize that you are biased,
then you will also come to realize that my translations are equally
honest.

> one gets the impression that you have quite a chip on your
> shoulder about the FSF and RMS.

I can take them or leave them until they and their followers start
spouting damaging nonsense.  Many businesses were scared to death of
FOSS for many years, and I lay the blame squarely on RMS's shoulders.
You see only the good he has done; it is tempered by quite a bit of
bad.

> Referring to the GPL as a "commercial"
> licence and stating that it (as opposed to any other licence or even
> the word "copyright" followed by a name) is a threat to sue people,
> presumably appealing to the libertarian crowd with a judicious mention
> of "government" just to fan the flames of supposed injustice, really
> does triangulate where you are coming from. So, yes, we're now rather
> more aware of what your agenda is, I think.

I'm not the one who keeps spouting that it "gives" freedoms (or even
privileges) that copyright would have taken away.  That's complete
bullshit.  As I said, copyright *allows* the author to control various
aspects of his work ("take away freedoms" in GPL-speak), and all
licenses (including the GPL) explicitly state which aspects the author
plans to control.  The only way the author can really exert control is
to sue or credibly threaten to sue.  I can actually point to multiple
instances of GPL authors suing, and people like you crowing about how
great it is that the GPL stands up in court, but I don't actually
recall any suits about violations of the MIT or Apache licenses.  So,
yes, I firmly believe that when somebody slaps a GPL license on their
software (and especially if they sign the copyrights over to the FSF)
they are trying to signal that they are willing to go to court to
protect their rights.  This is no different than when Microsoft sues
an infringer, and is not an evil thing, but it is definitely something
to be aware of.  The easiest way to not get tangled in that kind of
lawsuit is to just make sure that you never distribute any software
with a commercial-type license on it (including the GPL).

> And I don't think it improves any argument you may have by projecting
> notions of "morality" or "immorality" onto what I have written,

But you're arguing from a moral standpoint.

> especially when I have deliberately chosen to use other terms which
> avoid involving such notions

Yes, but you're making exactly the same arguments as others, just
changing the name.

> or by equating the copyleft licences
> with criminal enterprises ("pyramid scheme"),

Well, that may be a bit OTT.  What I really should say is that the GPL
license has a "selfish gene."  It tries really hard to propagate
itself, at the expense of the genes of other licenses.

> or by suggesting that I
> endorse criminal endeavours.

Hmmm, don't recall doing that.  If I did, I certainly apologize.

> But if that's what you have left to say
> at this point, then I think you probably are "done".

Well, I thought I was before, but then the discussion about
downloading an ISO and burning it and giving it to a friend came up.
This may be technically allowable under the license, but nothing you
or anybody else has written has yet proved that to me.

Regards,
Pat



From pmaupin at gmail.com  Fri May 14 11:42:56 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 08:42:56 -0700 (PDT)
Subject: Picking a license
References:  
	
	<2ff3643b-6ef1-4471-8438-dcba0dc93c24@a21g2000yqn.googlegroups.com>
	
Message-ID: 

On May 14, 6:12?am, Lawrence D'Oliveiro  wrote:
> In message <2ff3643b-6ef1-4471-8438-
>
>
>
> dcba0dc93... at a21g2000yqn.googlegroups.com>, Patrick Maupin wrote:
> > On May 13, 10:04 pm, Lawrence D'Oliveiro
> >  wrote:
>
> >> In message , Ed
> >> Keith wrote:
>
> >>> The claim is being made that [the GPL] restricts freedom.
>
> >> What about the ?freedom? to restrict other people?s freedom? Should that
> >> be restricted or not?
>
> > It's interesting that some people don't like the comparison of the
> > Free Software movement to a religion, yet the main argument of the
> > movement, and the deliberate co-opting of words like "Free" and "Free
> > Software" ...
>
> Haven?t you ?co-opted? those words yourself?

Only in response.  But hey, it's not just me; even Stallman says that
MIT-licensed software is "free software", just not "Free Software".

Regards,
Pat


From pmaupin at gmail.com  Fri May 14 11:47:53 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 08:47:53 -0700 (PDT)
Subject: Picking a license
References:  
	
	<2b17ee77-0e49-4a97-994c-7582f86c0ba9@r34g2000yqj.googlegroups.com>
	
Message-ID: <5e719bcd-5405-4c34-870b-13e64ef1f818@k29g2000yqh.googlegroups.com>

On May 14, 6:13?am, Lawrence D'Oliveiro  wrote:
> In message
> <2b17ee77-0e49-4a97-994c-7582f86c0... at r34g2000yqj.googlegroups.com>, Patrick
>
> Maupin wrote:
> > On May 13, 10:06 pm, Lawrence D'Oliveiro
> >  wrote:
>
> >> Under the GPL, everybody has exactly the same freedoms.
>
> > That's absolutely not true. ?For a start, the original author can dual-
> > license.
>
> That?s nothing to do with the GPL.

If you mean "that's out of the control of the GPL" I agree.  But the
whole point of the discussion has been about how people can't take GPL
licensed code proprietary, making enhancements, etc. and I'm just
pointing out that this doesn't apply to the original author.  Someone
can decide they aren't making enough money under the GPL and stop
distributing that way, and make all their enhancements proprietary, if
they are the original author.

Regards,
Pat


From mrkafk at gmail.com  Fri May 14 11:52:34 2010
From: mrkafk at gmail.com (mk)
Date: Fri, 14 May 2010 17:52:34 +0200
Subject: Picking a license
In-Reply-To: 
References: 
	
Message-ID: 

Steven D'Aprano wrote:
> Are you implying that by distributing your libraries under the MIT or 
> Apache licence, no linking is required? That's a cool trick, can you 
> explain how it works please?

Err.. Linking statically with library in question? Which excludes LGPL 
for legal reasons and doesn't exclude MIT/Apache license for legal reasons?

(this is obviously orthogonal to a technical question why static linking 
should be used sparringly if at all)


Regards,
mk



From toby at rcsreg.com  Fri May 14 11:59:38 2010
From: toby at rcsreg.com (Tobiah)
Date: Fri, 14 May 2010 15:59:38 GMT
Subject: Picking a license
References: 
Message-ID: 


> Assertion II:
>    If person A is free do perform an action person B is not free to
>    perform then person A is free to do more than person B.

This does not hold water.  Let's say there are only 10 activities
available.  Person A can do number 1 and person B can not.  Person
B can do activities 2 through 10, while person A can not.  Therefore,
Person A is indeed free to perform an action that person B is not
free to perform, but person a is *not* free to do more than person B.

Tobiah


From e_d_k at yahoo.com  Fri May 14 12:18:09 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 09:18:09 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <5e719bcd-5405-4c34-870b-13e64ef1f818@k29g2000yqh.googlegroups.com>
Message-ID: <966161.19793.qm@web58707.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Patrick Maupin  wrote:

> From: Patrick Maupin 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 11:47 AM
> On May 14, 6:13?am, Lawrence
> D'Oliveiro  central.gen.new_zealand> wrote:
> > In message
> > <2b17ee77-0e49-4a97-994c-7582f86c0... at r34g2000yqj.googlegroups.com>,
> Patrick
> >
> > Maupin wrote:
> > > On May 13, 10:06 pm, Lawrence D'Oliveiro
> > > 
> wrote:
> >
> > >> Under the GPL, everybody has exactly the same
> freedoms.
> >
> > > That's absolutely not true. ?For a start, the
> original author can dual-
> > > license.
> >
> > That?s nothing to do with the GPL.
> 
> If you mean "that's out of the control of the GPL" I
> agree.? But the
> whole point of the discussion has been about how people
> can't take GPL
> licensed code proprietary, making enhancements, etc. and
> I'm just
> pointing out that this doesn't apply to the original
> author.? Someone
> can decide they aren't making enough money under the GPL
> and stop
> distributing that way, and make all their enhancements
> proprietary, if
> they are the original author.
> 

That is one good reason for choosing to use the GPL, instead of a less 
restrictive license. You can license it, for a fee, to someone who wants to use it in some way that is not allowed under the GPL. If you use a less 
restrictive license that is not an option. Of course you still could put 
restrictions on future enhancements, but the the original code cannot have 
new restrictions put on it, only taken off. If I release code under the GPL today, I can change my mind and release the same code under the Boost 
license tomorrow. But if I release it with the Boost license, while 
technically I can release it with the GPL tomorrow, in practice everyone 
will use the previously released Boost licensed version.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Fri May 14 12:28:30 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 09:28:30 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <980293.99579.qm@web58702.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Tobiah  wrote:

> From: Tobiah 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 11:59 AM
> 
> > Assertion II:
> >? ? If person A is free do perform an action
> person B is not free to
> >? ? perform then person A is free to do more
> than person B.
> 
> This does not hold water.? Let's say there are only 10
> activities
> available.? Person A can do number 1 and person B can
> not.? Person
> B can do activities 2 through 10, while person A can
> not.? Therefore,
> Person A is indeed free to perform an action that person B
> is not
> free to perform, but person a is *not* free to do more than
> person B.

THat argument is valid if and only if the rights of B are not a strict subset of the rights of A. As far as I can tell, the rights granted by the GPL are a strict subset of the right granted by the Boost license. So your argument does not work.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From bryanjugglercryptographer at yahoo.com  Fri May 14 12:33:10 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Fri, 14 May 2010 09:33:10 -0700 (PDT)
Subject: Iterating over dict and removing some elements
References: 
Message-ID: <1e19af7b-226a-4cae-a407-e6285344a28c@6g2000prg.googlegroups.com>

Adi Eyal  wrote:
> > Bryan:
> > Terry Reedy wrote:
> > [...]
> >> for k in [k for k in d if d[k] == 'two']:
> >> ? ? ? ? ?d.pop(k)
>
> > We have a winner.
>
> also
>
> foo = lambda k, d : d[k] == "two"
> d = dict([(k, d[k]) for k in d.keys() if not foo(k, d)])
>
> incidentally, this is marginally slower than pops and dels but has the
> benefit of not modifying the original dict if that's what you need.

Well, I guess, sure. The original problem in this tread was about
modifying the dict over which we are iterating. If you create a new
dict instead, that problem just goes away.

In Python 3.X, and in Python 2.X starting with 2.4, you can drop the
square brackets and avoid creating an extra temporary list:

d = dict((k, d[k]) for k in d.keys() if not foo(k, d))

You can also drop .keys() in Python 3.X or current Python 2.X:

d = dict((k, d[k]) for k in d if not foo(k, d))

Passing the dict to foo() seems inelegant. You could use:

foo = lambda val: val == "two"
d = dict((k, d[k]) for k in d if not foo(d[k]))

I'm sticking with my call of Terry Reedy's last solution as winner. It
solves the originally-stated problem, works correctly and efficiently
in both Python 3.X and current Python 2.X, and there is not a bracket
in it that does not need to be there.

--
--Bryan


From tjreedy at udel.edu  Fri May 14 12:39:43 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Fri, 14 May 2010 12:39:43 -0400
Subject: an element from a set
In-Reply-To: <28560792.post@talk.nabble.com>
References: <28560792.post@talk.nabble.com>
Message-ID: 

On 5/14/2010 11:24 AM, gerardob wrote:
>
> Hello, let S be a python set which is not empty
> (http://docs.python.org/library/sets.html)
>
> i would like to obtain one element (anyone, it doesn't matter which one) and
> assign it to a variable.
>
> How can i do this?

Depends on whether or not you want the element removed from the set

#3.1
 >>> s=set(range(10))
 >>> s
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
 >>> x=next(iter(s))
 >>> x
0
 >>> s
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
 >>> x = s.pop()
 >>> x
0
 >>> s
{1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed

The choice of 0 is an implementation artifact. It could have been any 
member.

Terry Jan Reedy





From paul at boddie.org.uk  Fri May 14 12:48:59 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 09:48:59 -0700 (PDT)
Subject: Picking a license
References: 
	
	 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com>
Message-ID: <3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com>

On 14 Mai, 17:37, Patrick Maupin  wrote:
>
> Before, you were busy pointing me at the GPL FAQ as authoritative.

No, the licence is the authority, although the FAQ would probably be
useful to clarify the licence author's intent in a litigation
environment.

[Fast-forward through the usual tirade, this time featuring words like
"bible", "moral", "evil"...]

> Well, I thought I was before, but then the discussion about
> downloading an ISO and burning it and giving it to a friend came up.
> This may be technically allowable under the license, but nothing you
> or anybody else has written has yet proved that to me.

Section 3 of GPLv2 (and section 6(d) of GPLv3 reads similarly): "If
distribution of executable or object code is made by offering access
to copy from a designated place, then offering equivalent access to
copy the source code from the same place counts as distribution of the
source code, even though third parties are not compelled to copy the
source along with the object code."

And here's that FAQ entry which clarifies the intent:

http://www.gnu.org/licenses/gpl-faq.html#DistributeWithSourceOnInternet

Like I said, if you really have a problem with Ubuntu shipping CDs and
exposing others to copyright infringement litigation - or even
themselves, since they (and all major distributions) are actively
distributing binaries but not necessarily sources in the very same
download or on the very same disc - then maybe you should take it up
with them.

Paul


From pmaupin at gmail.com  Fri May 14 13:00:47 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 10:00:47 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com
Message-ID: 

On May 14, 10:20?am, Paul Boddie  wrote:
> On 14 Mai, 09:08, Carl Banks  wrote:
>
> > On May 13, 10:59?pm, Steven D'Aprano  wrote:
> > > On Thu, 13 May 2010 17:18:47 -0700, Carl Banks wrote:
> > > > 2. Reimplment the functionality seperately (*cough* PySide)
>
> > > Yes. So what? In what possible way is this an argument against the GPL?
>
> [...]
>
> > It's not. ?It's an argument that the GPL doesn't do much good.
>
> Right. So nobody got the benefit from Qt under the GPL or PyQt under
> the GPL? Even the PySide developers seem hell-bent on picking over the
> work of the PyQt developers for ideas, although they obviously won't
> touch the code. Nokia seem to have accrued tremendous benefit from the
> existence of PyQt because I rather doubt that anyone would have
> bothered rolling a set of mature, usable Python bindings for Qt now
> had some not existed already and proved that dynamic languages are
> worth supporting.

Perhaps he should have said "the GPL doesn't do any more good than any
other commercial license."

After all, lots of software ideas proved their worth in proprietary
systems, and then were later cloned by FOSS developers.  In many
cases, these clones are, functionally, almost exact copies.  That's
why all the really proprietary people are hell-bent on trying to get
or maintain patent protection -- copyright doesn't protect
"inventions".

Would you have agreed had he had said that "MatLab's license doesn't
do much good" and assigned the same sort of meaning to that statement,
namely that the MatLab license prevented enough motivated people from
freely using MatLab in ways that were important to them?  Obviously,
it was important enough to enough people that they went and built the
GPLed Octave software, which now emulates MatLab very closely.  As I
think both Ed and I have said before, the GPL can be a great license
for a full-blown *program* (like Octave) that people can just download
and use, but is not always so great for program *pieces* that are
designed to be used in the programmatic equivalent of a "mash-up",
like PyQt/PySide, so the cloning of PyQt into PySide is as inevitable
as the cloning of MatLab into Octave, or Unix/Minix into Linux.  As
far as your comments about PyQt proving out the concept, well duh!
Just as there are a lot of proprietary programs that are relatively
useless and *won't* have any GPLed versions written, nobody's going to
waste time rewriting a marginally useful GPLed library just to put a
permissive license on it, either.  They are either going to write
something completely different in the hopes that their vision is
correct, or are going to copy at least some parts of the design and/or
vision of something that is popular and useful.  And that's a great
thing.  It would have been horribly unproductive if the Linux API
weren't at least reasonably close to the Unix API, for example.

It's an interesting tension between the licenses.  Nobody rewrites
permissively licensed software as GPL simply because the license is
unacceptable, but just as people will rewrite proprietary programs and
libraries as GPL because the license is unacceptable, so will some
rewrite GPLed libraries as permissive because the license is
unacceptable.

Regards,
Pat


From switch2mathan at gmail.com  Fri May 14 13:15:36 2010
From: switch2mathan at gmail.com (MathanK)
Date: Fri, 14 May 2010 05:15:36 -1200
Subject: Alternate string object type for PyStringObject(available Python
	2.x) in python 3.x?
Message-ID: <12897d06413.515885629628951451.7220101516557890617@gmail.com>

What is the replacement in python 3.x for PyStringObject which is available in python 2.x?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From pmaupin at gmail.com  Fri May 14 13:15:51 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 10:15:51 -0700 (PDT)
Subject: Picking a license
References: 
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com>
Message-ID: <29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com>

On May 14, 11:48?am, Paul Boddie  wrote:
> On 14 Mai, 17:37, Patrick Maupin  wrote:
>
>
>
> > Before, you were busy pointing me at the GPL FAQ as authoritative.
>
> No, the licence is the authority, although the FAQ would probably be
> useful to clarify the licence author's intent in a litigation
> environment.

Agreed.

> Section 3 of GPLv2 (and section 6(d) of GPLv3 reads similarly): "If
> distribution of executable or object code is made by offering access
> to copy from a designated place, then offering equivalent access to
> copy the source code from the same place counts as distribution of the
> source code, even though third parties are not compelled to copy the
> source along with the object code."
>
> And here's that FAQ entry which clarifies the intent:
>
> http://www.gnu.org/licenses/gpl-faq.html#DistributeWithSourceOnInternet

That entry, along with the written offer, certainly covers Ubuntu when
they distribute a CD.

But if I *download* an ISO, burn it on a CD, and give it away, *I* am
the one distributing the physical copy, not Ubuntu, and I am not going
to put up an FTP server just so my friend can get source from it.  And
as section 6 of GPL v3 makes clear, I am not allowed to piggyback on
Ubuntu's source offer.  My situation *really is* covered by the FAQ
entry I referred you to:

http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary

> Like I said, if you really have a problem with Ubuntu shipping CDs and
> exposing others to copyright infringement litigation.

So, deliberately or not, you're trying to change the discussion
again.  I *never* discussed Ubuntu shipping a physical CD, and never
intimated that that was a problem.  My discussion was *always* about
an individual *downloading* an ISO and *burning* a CD himself, then
*distributing* the CD to someone else.

> - or even
> themselves, since they (and all major distributions) are actively
> distributing binaries but not necessarily sources in the very same
> download or on the very same disc - then maybe you should take it up
> with them.

Again, I never intimated this.  Please read more carefully in the
future before you reply, and then perhaps you will actually make
cogent replies that address my points, and then I won't be so
frustrated that I make snide comments you take offense at, OK?  This
has happened on at least 4 separate occasions in this thread, and
sometimes a single misunderstanding goes on for quite a few posts, so
I'm starting to wonder if it's deliberate.

Regards,
Pat


From mannu_0523 at rediffmail.com  Fri May 14 13:22:37 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 14 May 2010 17:22:37 -0000
Subject: =?utf-8?B?am9pbmluZyB0d28gY29sdW1u?=
Message-ID: <20100514172237.23776.qmail@f4mail-235-238.rediffmail.com>

Hi,

I have two different file 

file1:

a1 a2
a3 a4
a5 a6
a7 a8
 
file2:

b1 b2
b3 b4 
b5 b6
b7 b8

and I want to join them so the output should look like this:

a1 a2 b1 b2
a3 a4 b3 b4
a5 a6 b5 b6
a7 a8 b7 b8

how to do that?




-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From albert at spenarnc.xs4all.nl  Fri May 14 13:36:20 2010
From: albert at spenarnc.xs4all.nl (Albert van der Horst)
Date: 14 May 2010 17:36:20 GMT
Subject: Picking a license
References: 
	<4a2021e7-a229-4cb6-9386-15a937a98b9a@b7g2000yqk.googlegroups.com>
	<4dbe2b0f-8fe0-4df5-a9d8-7f102e71962e@r11g20
	<4be95545$1@dnews.tpgi.com.au>
Message-ID: 

In article <4be95545$1 at dnews.tpgi.com.au>,
Lie Ryan   wrote:



>
>Come on, 99%  of the projects released under GPL did so because they
>don't want to learn much about the law; they just need to release it
>under a certain license so their users have some legal certainty. Most
>programmers are not lawyers and don't care about the law and don't care
>about the GPL; if a commercial programmer want to use the GPL-code in an
>incompatible licensed program, and he comes up asking, many would just
>be happy to say yes.

This is a big reason for me to release everything (see my website,
it is a *lot*) under GPL. If someone wants to use it they can,
if someone wants to use it commercially, they can too, as long
as they pay me a little bit too. Really, I'm reasonable.

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst



From prologic at shortcircuit.net.au  Fri May 14 13:55:38 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sat, 15 May 2010 03:55:38 +1000
Subject: joining two column
In-Reply-To: <20100514172237.23776.qmail@f4mail-235-238.rediffmail.com>
References: <20100514172237.23776.qmail@f4mail-235-238.rediffmail.com>
Message-ID: 

On Sat, May 15, 2010 at 3:22 AM, mannu jha  wrote:
> Hi,
>
> I have two different file
>
> file1:
>
> a1 a2
> a3 a4
> a5 a6
> a7 a8
>
> file2:
>
> b1 b2
> b3 b4
> b5 b6
> b7 b8
>
> and I want to join them so the output should look like this:
>
> a1 a2 b1 b2
> a3 a4 b3 b4
> a5 a6 b5 b6
> a7 a8 b7 b8
>
> how to do that?

This is completely untested, but this "should" (tm) work:

from itertools import chain

input1 = open("input1.txt", "r").readlines()
input2 = open("input2.txt", "r").readlines()
open("output.txt", "w").write("".join(chain(input1, input2)))

cheers
James


From paul at boddie.org.uk  Fri May 14 14:07:38 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 11:07:38 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
Message-ID: 

On 14 Mai, 19:00, Patrick Maupin  wrote:
>
> Would you have agreed had he had said that "MatLab's license doesn't
> do much good" and assigned the same sort of meaning to that statement,
> namely that the MatLab license prevented enough motivated people from
> freely using MatLab in ways that were important to them? ?Obviously,
> it was important enough to enough people that they went and built the
> GPLed Octave software, which now emulates MatLab very closely.

I don't need to answer your question. It's obvious that the licence
doesn't do much good when people seek to create a platform which is
genuinely and irrevocably open as a response. That they have done so
using the GPL pretty much sinks the previous ridiculous statement
about the GPL, too, unless Octave is somehow a bad thing (which is
what a certain vendor of proprietary statistics software would have
you believe about a certain widely-used statistical analysis tool).
Although people can argue that usage of the GPL prevents people from
potentially contributing because they would not be able to sell
proprietary versions of the software, it has been in no way
demonstrated to be universally true that such contributors would
contribute more than those who do so because of the copyleft
licensing. The creators of Octave are obviously not willing to create
(or help create) another system with all the proprietary limitations
of MatLab, and why should they be willing? The production of a
different "proprietary flavour" of MatLab wouldn't be beneficial to
them at all - it might even be detrimental to their project - and
might only be marginally beneficial, at best, to existing MatLab
customers.

[PySide]

> Just as there are a lot of proprietary programs that are relatively
> useless and *won't* have any GPLed versions written, nobody's going to
> waste time rewriting a marginally useful GPLed library just to put a
> permissive license on it, either.

Unless they really want to release (or encourage the creation of)
proprietary software, which is precisely what PySide is all about.
(And PyQt is not "marginally useful" - it is a widely-used and widely
well-regarded library.) And this apparent overriding need to support
proprietary solutions results in different strategies, such as with
the Chandler project: because the OSAF wanted to be able to sell
proprietary solutions but didn't own all the code, they decided to
pick only permissively licensed software for the components of the
solution, resulting in a lot of extra effort expended in getting their
user interface toolkit up to scratch. You can make your own mind up
about whether that was a sensible strategy.

Usually, however, most people wanting to write proprietary software
cannot be bothered to do the work to replicate an existing GPL-
licensed solution (or even to significantly improve permissively
licensed solutions). They instead appeal to people to release already-
mature permissively licensed software, typically waiting for someone
with enough money or manpower to do most of the work for them. Again,
this is precisely why PySide appeals to a certain audience.

Paul


From e_d_k at yahoo.com  Fri May 14 14:11:27 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 11:11:27 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <82399.84016.qm@web58705.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Albert van der Horst  wrote:
 
> This is a big reason for me to release everything (see my
> website,
> it is a *lot*) under GPL. If someone wants to use it they
> can,
> if someone wants to use it commercially, they can too, as
> long
> as they pay me a little bit too. Really, I'm reasonable.

I have no problem with that. 

I have played with your forth assembler a bit. It is good work, and the 
best part is that I can read the source and learn from it. Putting it out 
under GPL allows me to learn from it, and you to profit from it, a real 
win/win. Thank you very much for making it available.

I'm working on an assembler myself. I may steal your ideas, but I will not 
steal your code. I'm writing it in ocaml, your forth code would not be 
easy to translate. When/if I finish I'll publish it under a less restrictive open source license, because I do not think I would be able to 
persuade anyone else to pay for a commercial license. But I do not fault 
you if you think you can. 

If I did use your code I would either publish under the GPL or not publish 
at all depending on the exact circumstances. I have been know, on rare occasions, to use GPLed code in my own work (mostly plug-ins for GPLed applications). I just refuse to use it in any code for a client, because I do not want to require someone who does not know source code from Morse code code to figure out what they need to do to avoid violating the license. When I deliver my code to the client they are always free to do whatever they want with it. 

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com



      


From kaklis at gmail.com  Fri May 14 14:23:52 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Fri, 14 May 2010 11:23:52 -0700 (PDT)
Subject: parsing XML
References: 
	
Message-ID: <620efb1b-9c7c-46dc-8bfb-477daa67692c@o14g2000yqb.googlegroups.com>

On May 14, 6:22?pm, Stefan Behnel  wrote:
> kak... at gmail.com, 14.05.2010 16:57:
>
> > Hi to all, let's say we have the following Xml
> > 
> > ? ?
> > ? ? ?17.1
> > ? ? ?6.4
> > ? ?
> > ? ?
> > ? ? ?15.5
> > ? ? ?7.8
> > ? ?
> > 
>
> > How can i get the players name, age and height?
>
> Here's an overly complicated solution, but I thought that an object
> oriented design would help here.
>
> ? ?import xml.etree.ElementTree as ET
>
> ? ?class Player(object):
> ? ? ? def __init__(self, name, age, height):
> ? ? ? ? ? self.name, self.age, self.height = name, age, height
>
> ? ?attributes = ['name', 'age', 'height']
>
> ? ?players = []
> ? ?for _, element in ET.iterparse("teamfile.xml"):
> ? ? ? ?if element.tag == 'player':
> ? ? ? ? ? ?players.append(
> ? ? ? ? ? ? ? ?Player(*[ element.get(attr) for attr in attributes ]))
>
> ? ?for player in players:
> ? ? ? ?print player.name, player.age, player.height
>
> Stefan

Thanks stefan!

A.K.


From pmaupin at gmail.com  Fri May 14 14:36:54 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 11:36:54 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
	
Message-ID: 

On May 14, 1:07?pm, Paul Boddie  wrote:
> On 14 Mai, 19:00, Patrick Maupin  wrote:

> > Would you have agreed had he had said that "MatLab's license doesn't
> > do much good" and assigned the same sort of meaning to that statement,
> > namely that the MatLab license prevented enough motivated people from
> > freely using MatLab in ways that were important to them? ?Obviously,
> > it was important enough to enough people that they went and built the
> > GPLed Octave software, which now emulates MatLab very closely.
>
> I don't need to answer your question. It's obvious that the licence
> doesn't do much good when people seek to create a platform which is
> genuinely and irrevocably open as a response. That they have done so
> using the GPL pretty much sinks the previous ridiculous statement
> about the GPL, too.

That statement was made in the context of why Carl doesn't use GPL-
licensed *libraries*.  He and I have both explained the difference
between libraries and programs multiple times, not that you care.

> unless Octave is somehow a bad thing (which is
> what a certain vendor of proprietary statistics software would have
> you believe about a certain widely-used statistical analysis tool).
> Although people can argue that usage of the GPL prevents people from
> potentially contributing because they would not be able to sell
> proprietary versions of the software, it has been in no way
> demonstrated to be universally true that such contributors would
> contribute more than those who do so because of the copyleft
> licensing.

As I have said before, the availability of multiple (but not too
many!) licenses is a great thing, because each contributor can decide
how he wants to license his creation.  Finding the right license to
contribute under can only enhance the commons.

> The creators of Octave are obviously not willing to create
> (or help create) another system with all the proprietary limitations
> of MatLab, and why should they be willing?

I don't presume to know their motivations, or how the license got
chosen.  However, once it was under the GPL and there were multiple
contributors, it would certainly be difficult to relicense any other
way.

> The production of a
> different "proprietary flavour" of MatLab wouldn't be beneficial to
> them at all - it might even be detrimental to their project - and
> might only be marginally beneficial, at best, to existing MatLab
> customers.

I personally can't see any realistic chance of detriment.  How could a
proprietary clone hope to compete against free software on one side
and real matlab on the other side?  That's a no-win position, so I
wouldn't expect to see any proprietary clones.

> [PySide]
>
> > Just as there are a lot of proprietary programs that are relatively
> > useless and *won't* have any GPLed versions written, nobody's going to
> > waste time rewriting a marginally useful GPLed library just to put a
> > permissive license on it, either.
>
> Unless they really want to release (or encourage the creation of)
> proprietary software.

How does recreating something marginally useful encourage proprietary
software?  That's very confusing.

> which is precisely what PySide is all about.

No, PySide is about non-GPL software, and is released under a license
that even RMS recognizes as "free", and it is certainly not of
marginal utility.

> (And PyQt is not "marginally useful" - it is a widely-used and widely
> well-regarded library.)

Well, we agree on that.  But I don't know why you're trying to claim I
said PyQt was only marginally useful.

> And this apparent overriding need to support
> proprietary solutions results in different strategies, such as with
> the Chandler project: because the OSAF wanted to be able to sell
> proprietary solutions but didn't own all the code, they decided to
> pick only permissively licensed software for the components of the
> solution, resulting in a lot of extra effort expended in getting their
> user interface toolkit up to scratch. You can make your own mind up
> about whether that was a sensible strategy.

Large, high-risk projects are often going to fail and there will
always be some decisions that are easy to second-guess, correctly or
not.  In any case, if the goal was a particular method to get a ROI,
it may have been that they wouldn't have been able to do that at all
with the GPL, either.

> Usually, however, most people wanting to write proprietary software
> cannot be bothered to do the work to replicate an existing GPL-
> licensed solution (or even to significantly improve permissively
> licensed solutions).

Usually, most people wanting to write software can't be bothered to do
the work.  That's nothing new.  Yet occasionally people do some work,
and some projects make progress.

> They instead appeal to people to release already-
> mature permissively licensed software, typically waiting for someone
> with enough money or manpower to do most of the work for them.

Well, personally, I'm still waiting for someone to finish the Hurd,
but I've always been led to believe that laziness is a virtue in a
programmer.

> Again,
> this is precisely why PySide appeals to a certain audience.

Certainly, the audience for a library is going to be people who both
find it interesting and find that it meets their licensing
requirements.  Nothing new about that.

Regards,
Pat


From paul at boddie.org.uk  Fri May 14 14:38:07 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 11:38:07 -0700 (PDT)
Subject: Picking a license
References: 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com>
Message-ID: 

On 14 Mai, 19:15, Patrick Maupin  wrote:
> On May 14, 11:48?am, Paul Boddie  wrote:
> > Section 3 of GPLv2 (and section 6(d) of GPLv3 reads similarly): "If
> > distribution of executable or object code is made by offering access
> > to copy from a designated place, then offering equivalent access to
> > copy the source code from the same place counts as distribution of the
> > source code, even though third parties are not compelled to copy the
> > source along with the object code."
>
> > And here's that FAQ entry which clarifies the intent:
>
> >http://www.gnu.org/licenses/gpl-faq.html#DistributeWithSourceOnInternet

[...]

> http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary

We're all aware of the obligation to provide source code. You've spent
the last few days complaining about it.

> > Like I said, if you really have a problem with Ubuntu shipping CDs and
> > exposing others to copyright infringement litigation.
>
> So, deliberately or not, you're trying to change the discussion
> again. ?I *never* discussed Ubuntu shipping a physical CD, and never
> intimated that that was a problem. ?My discussion was *always* about
> an individual *downloading* an ISO and *burning* a CD himself, then
> *distributing* the CD to someone else.

I am not changing the discussion at all. You are describing a
situation where someone gets the binaries but not the sources, but
according to the licence they should get both of those things
(ignoring written offers and the like), and this does apply to Ubuntu
since precisely this act of distribution (to use the older term) is
performed by them. That you then pass on the binaries without the
sources is an equivalent situation, ignoring for the moment that you
do not yourself have the sources either.

So, what are you supposed to do when the recipient "calls" you on the
lack of sources? (And, yes, clearly the FSF anticipates that not
everyone will request the sources because it is written in that very
excerpt I provide above.) If the recipient is strict about exact
compliance, you will have to provide the sources on CD to them. And
this makes sense: if they can only make use of the binaries if
provided on CD (and not, say, on an FTP site because they don't have
an Internet connection, for example), then they will need to receive
the sources in the same manner. Of course, the recipient may only
demand certain sources, not wishing to avail themself of the sources
for all copyleft-licensed packages in the binary distribution.

Now we return to the matter of getting the Ubuntu sources. If you
ordered a CD from Ubuntu via their ShipIt service, it is at this point
that you can demand a CD of corresponding sources. If they cannot
provide one, then obviously it poses a problem for your compliance
(and theirs, and you should see once again why Ubuntu's activities do
matter), but naturally Ubuntu provide parallel binary and source
repositories for all their packages. So, even if they were found not
to be in compliance according to the strictest interpretation of the
licence, it is technically possible for you to acquire the
corresponding sources and make them available to the person who was
given the CD. If you downloaded an ISO file, Ubuntu could (and do)
obviously provide source packages from the same location: their Web
site and various mirrors.

Really, if at this point you think I'm playing games with you, then
you really need to stop taking score and formulate the exact problem
you have with the distribution of Ubuntu-style media, because I'm
starting to think that the only real problem here is the one you have
with people using copyleft-style licences for their works. Since we've
had to hear about that over several days, I don't think that
articulating that particular problem once again really brings anything
more to the discussion.

Paul


From python.list at tim.thechases.com  Fri May 14 14:46:55 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Fri, 14 May 2010 13:46:55 -0500
Subject: joining two column
In-Reply-To: 
References: <20100514172237.23776.qmail@f4mail-235-238.rediffmail.com>
	
Message-ID: <4BED9A9F.5040708@tim.thechases.com>

On 05/14/2010 12:55 PM, James Mills wrote:
>> file1:
>> a1 a2
>> a3 a4
>> a5 a6
>> a7 a8
>>
>> file2:
>> b1 b2
>> b3 b4
>> b5 b6
>> b7 b8
>>
>> and I want to join them so the output should look like this:
>>
>> a1 a2 b1 b2
>> a3 a4 b3 b4
>> a5 a6 b5 b6
>> a7 a8 b7 b8
>
> This is completely untested, but this "should" (tm) work:
>
> from itertools import chain
>
> input1 = open("input1.txt", "r").readlines()
> input2 = open("input2.txt", "r").readlines()
> open("output.txt", "w").write("".join(chain(input1, input2)))

I think you meant izip() instead of chain() ... the OP wanted to 
be able to join the two lines together, so I suspect it would 
look something like

   # OPTIONAL_DELIMITER = " "
   f1 = file("input1.txt")
   f2 = file("input2.txt")
   out = open("output.txt", 'w')
   for left, right in itertools.izip(f1, f2):
     out.write(left.rstrip('\r\n'))
     # out.write(OPTIONAL_DELIMITER)
     out.write(right)
   out.close()

This only works if the two files are the same length, or (if 
they're of differing lengths) you want the shorter version.  The 
itertools lib also includes an izip_longest() function with 
optional fill, as of Python2.6 which you could use instead if you 
need all the lines

-tkc






From nobody at nowhere.com  Fri May 14 15:08:52 2010
From: nobody at nowhere.com (Nobody)
Date: Fri, 14 May 2010 20:08:52 +0100
Subject: Is Python a functional programming language?
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
	<7xvdau8pzl.fsf@ruckus.brouhaha.com>
	
	<7xr5lhaotk.fsf@ruckus.brouhaha.com>
Message-ID: 

On Tue, 11 May 2010 18:31:03 -0700, Paul Rubin wrote:

>>> is called an "equation" rather than an "assignment".  It declares "x is
>>> equal to 3", rather than directing x to be set to 3.  If someplace else
>>> in the program you say "x = 4", that is an error, normally caught by
>>> the compiler, since x cannot be equal to both 3 and 4.
>>
>> In both ML and Haskell, bindings are explicitly scoped, i.e.
>> 	let x = 3 in ...	(Haskell)
> 
> I'm not talking about nested bindings.  I'm talking about two different
> bindings of the same symbol in the same scope:
> 
>     $ cat meow.hs
>     x = 3
>     x = 4
>     $ ghc meow.hs
> 
>     meow.hs:2:0:
>         Multiple declarations of `Main.x'
>         Declared at: meow.hs:1:0
>                      meow.hs:2:0

It may be worth noting the interactive behaviour:

	$ ghci
	GHCi, version 6.8.2: http://www.haskell.org/ghc/  :? for help
	Loading package base ... linking ... done.
	Prelude> let x = 7
	Prelude> let f y = x + y
	Prelude> f 3
	10
	Prelude> let x = 5
	Prelude> f 3
	10

The main point is that variables aren't mutable state.

An important secondary point is that, unlike Python, free (global)
variables in a function body are substituted when the function is defined,
not when it's called.



From pmaupin at gmail.com  Fri May 14 15:14:18 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 12:14:18 -0700 (PDT)
Subject: Picking a license
References: 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com> 
	
Message-ID: <41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com>

On May 14, 1:38?pm, Paul Boddie  wrote:
> On 14 Mai, 19:15, Patrick Maupin  wrote:
>
> > On May 14, 11:48?am, Paul Boddie  wrote:
> > > Section 3 of GPLv2 (and section 6(d) of GPLv3 reads similarly): "If
> > > distribution of executable or object code is made by offering access
> > > to copy from a designated place, then offering equivalent access to
> > > copy the source code from the same place counts as distribution of the
> > > source code, even though third parties are not compelled to copy the
> > > source along with the object code."
>
> > > And here's that FAQ entry which clarifies the intent:
>
> > >http://www.gnu.org/licenses/gpl-faq.html#DistributeWithSourceOnInternet
>
> [...]
>
> >http://www.gnu.org/licenses/gpl-faq.html#UnchangedJustBinary
>
> We're all aware of the obligation to provide source code. You've spent
> the last few days complaining about it.
>
> > > Like I said, if you really have a problem with Ubuntu shipping CDs and
> > > exposing others to copyright infringement litigation.
>
> > So, deliberately or not, you're trying to change the discussion
> > again. ?I *never* discussed Ubuntu shipping a physical CD, and never
> > intimated that that was a problem. ?My discussion was *always* about
> > an individual *downloading* an ISO and *burning* a CD himself, then
> > *distributing* the CD to someone else.
>
> I am not changing the discussion at all. You are describing a
> situation where someone gets the binaries but not the sources, but
> according to the licence they should get both of those things
> (ignoring written offers and the like), and this does apply to Ubuntu
> since precisely this act of distribution (to use the older term) is
> performed by them. That you then pass on the binaries without the
> sources is an equivalent situation, ignoring for the moment that you
> do not yourself have the sources either.

If Joe downloads and burns a CD for his friend, he may not have the
sources and may not have any intention of getting them, and probably
didn't provide a "written offer."  What you're "ignoring for the
moment" is my whole point, that unlike Ubuntu, Joe is now in violation
of the GPL license, because he provided neither a written offer nor
source on CD, nor his own download site.

> So, what are you supposed to do when the recipient "calls" you on the
> lack of sources?

There is possibly no "calling".  Since no source and no written offer
was delivered, Joe's friend may not know about the issue.  Even Joe
himself just saw it was "free software" and didn't read the fine
print, so he may not have a clue how to get the source.


>(And, yes, clearly the FSF anticipates that not
> everyone will request the sources because it is written in that very
> excerpt I provide above.)

Which Joe doesn't know about and didn't adhere to in any case.

> If the recipient is strict about exact
> compliance, you will have to provide the sources on CD to them.

That could be a year later, and Joe, who doesn't really even know
anything about source, is really going to have a hard time figuring
out exactly which sources went into the CD he downloaded that long
ago.

> And
> this makes sense: if they can only make use of the binaries if
> provided on CD (and not, say, on an FTP site because they don't have
> an Internet connection, for example), then they will need to receive
> the sources in the same manner.

To an extent it makes sense.  That's why I explained that I thought it
would be nice of Ubuntu to put a warning to Joe on their site
explaining the consequences of helping his friend out.  Of course,
since the warning would only serve to decrease object downloads, and
since Joe's friend doesn't really want the source anyway, there is no
real point.  That doesn't alter the fact that Joe is immediately in
violation of the GPL once he delivers the CD to his friend without the
written offer.

> Of course, the recipient may only
> demand certain sources, not wishing to avail themself of the sources
> for all copyleft-licensed packages in the binary distribution.

[ Stuff about ShipIt snipped because I was never discussing that.]

> Really, if at this point you think I'm playing games with you.

I don't know what to think about that.  Even after I've explicitly
said multiple times I'm not discussing when Ubuntu ships a CD, you
still felt compelled to include a big paragraph about ShipIt.  Is it
to confuse?  Or because have OCD?  I don't really know.

> then
> you really need to stop taking score and formulate the exact problem
> you have with the distribution of Ubuntu-style media,

I explained it fully multiple times.

> because I'm
> starting to think that the only real problem here is the one you have
> with people using copyleft-style licences for their works.

Well, as I have tried to explain, there are tradeoffs with any
license, including the GPL.  With the GPL, you can easily adhere to
the letter of the license by shipping source with object.  But
sometimes the source is so huge, people take shortcuts to get around
that.  The license allows this, via a requirement to provide source
later, that could actually fall on people who really don't understand
that that is required of them (perhaps not very often in practice, but
certainly in theory).

> Since we've
> had to hear about that over several days, I don't think that
> articulating that particular problem once again really brings anything
> more to the discussion.

Probably not, but you've still never addressed how easy it is for a
complete neophyte to go to, e.g. the Ubuntu site, be told do a
download, try it out, get excited, burn CDs for his friends, and then
be in violation of the GPL.  As I have said, I don't view this as a
*practical* issue, but it is an example of how those in the GPL
community turn a blind eye to innocent infringement, just like
Microsoft.

After all, the Ubuntu download page says "When the CD is ready, simply
put it in your CD drive, restart your computer and follow the
instructions that will appear on your screen. Don't forget that you
can create more copies and pass the CD to as many people as you like."
without mentioning *anything* about source code.

Regards,
Pat


From clp2 at rebertia.com  Fri May 14 15:15:32 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Fri, 14 May 2010 12:15:32 -0700
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 
	<7xvdavd4bq.fsf@ruckus.brouhaha.com> 
	<7xvdau8pzl.fsf@ruckus.brouhaha.com>
	
	<7xr5lhaotk.fsf@ruckus.brouhaha.com>
	
Message-ID: 

On Fri, May 14, 2010 at 12:08 PM, Nobody  wrote:
> On Tue, 11 May 2010 18:31:03 -0700, Paul Rubin wrote:
>>>> is called an "equation" rather than an "assignment". ?It declares "x is
>>>> equal to 3", rather than directing x to be set to 3. ?If someplace else
>>>> in the program you say "x = 4", that is an error, normally caught by
>>>> the compiler, since x cannot be equal to both 3 and 4.
>>>
>>> In both ML and Haskell, bindings are explicitly scoped, i.e.
>>> ? ? ?let x = 3 in ... ? ? ? ?(Haskell)
>>
>> I'm not talking about nested bindings. ?I'm talking about two different
>> bindings of the same symbol in the same scope:
>>
>> ? ? $ cat meow.hs
>> ? ? x = 3
>> ? ? x = 4
>> ? ? $ ghc meow.hs
>>
>> ? ? meow.hs:2:0:
>> ? ? ? ? Multiple declarations of `Main.x'
>> ? ? ? ? Declared at: meow.hs:1:0
>> ? ? ? ? ? ? ? ? ? ? ?meow.hs:2:0
>
> It may be worth noting the interactive behaviour:
>
> ? ? ? ?$ ghci
> ? ? ? ?GHCi, version 6.8.2: http://www.haskell.org/ghc/ ?:? for help
> ? ? ? ?Loading package base ... linking ... done.
> ? ? ? ?Prelude> let x = 7
> ? ? ? ?Prelude> let f y = x + y
> ? ? ? ?Prelude> f 3
> ? ? ? ?10
> ? ? ? ?Prelude> let x = 5
> ? ? ? ?Prelude> f 3
> ? ? ? ?10

Ahem (emphasis mine):
"""
==This syntax is *ghci-specific*==
The syntax for 'let' that ghci accepts is not the same as we would use
at the ?top level? of a normal Haskell program.
"""
-- http://book.realworldhaskell.org/read/getting-started.html

Cheers,
Chris
--
http://blog.rebertia.com


From nobody at nowhere.com  Fri May 14 15:16:36 2010
From: nobody at nowhere.com (Nobody)
Date: Fri, 14 May 2010 20:16:36 +0100
Subject: Is Python a functional programming language?
References: <34569B97-164F-48A9-842D-3F296166E88A@gmail.com>
	
	
	
	
Message-ID: 

On Thu, 13 May 2010 12:29:08 +1200, Lawrence D'Oliveiro wrote:

>> Some people would prefer to have a manageable set of rules rather than
>> having to remember the results of all of the possible combinations of
>> interactions between language features.
> 
> What are you accusing Python of, exactly?

I'm not accusing it of anything, exactly. I'm just pointing out that there
are entirely pragmatic reasons for disliking "multi-paradigm" languages.



From e_d_k at yahoo.com  Fri May 14 15:18:43 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 12:18:43 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <391086.53182.qm@web58702.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Paul Boddie  wrote:


<<< lots of stuff snipped >>>

> > > Like I said, if you really have a problem with
> Ubuntu shipping CDs and
> > > exposing others to copyright infringement
> litigation.


<<< A lot more stuff snipped >>>

Everyone is assuming a certain degree of computer savvy.

I have not installed Ubuntu, but I understand that they strive for ease of 
use, so I assume that if ant now, at some time in the near future, my 
farther, who knows very little about computers, could install it if I gave 
him a CD with it on it (He would never be able to burn it himself).

Supposes download the ISO image and burn a CD and give it to my father. 
(As I understand it I am now in violation of the GPL, but I may not be). 
My father installs it. He likes it, he gives it to a friend. 

Now suppose, just for the sake of argument, that Ubuntu forgets to renew 
their domain name and it gets taken over by a porn site (It happens to Web 
mechanic, it could happen to anyone). If my father's friend's teenage son 
wants the source code, he can not get it from his father, who does not 
even know what source code is. He does not know that I exist, because his 
father forgot where he got the disk. He can not get the source from the 
porn site. 

Clearly someone has violated the GPL, but I'm not sure who, I think it was me, but I may be wrong. If not me who? My father for giving the disk I gave him to a friend? My father's friend for not keeping track of who gave him the disk? Ubuntu, for not including the source in the ISO image I downloaded? or for allowing a porn site to take over their domain name?

It is questions like this that make me steer clear of the GPL. If I give 
my father a CD of Microsoft software, I know I'm breaking the law. If I 
give my father a CD of BSD software licensed software I'm on firm legal 
ground. If I give my father a CD of GPLed software, I'm on shaky ground 
unless I include all the source, which he has no use for, on a second 
disk. And if he give his friend the binary disk, but not the source disk 
(which is of no value to him or his friend), then he is in violation of 
the law, and he cannot even understand why.

The GPL is fine when all parties concern understand what source code is 
and what to do with it. But when you add people like my father to the loop 
if gets very ugly very fast.

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com



      


From nobody at nowhere.com  Fri May 14 15:23:51 2010
From: nobody at nowhere.com (Nobody)
Date: Fri, 14 May 2010 20:23:51 +0100
Subject: write a 20GB file
References: 
	<4BED2E45.6060301@ieee.org>
	
	
Message-ID: 

On Fri, 14 May 2010 10:50:49 -0400, J wrote:

> someone smarter than me can correct me, but file.write() will write when
> it's buffer is filled, or close() or flush() are called.

And, in all probability, seek() will either flush it immediately or cause
the next write() to flush it before writing anything.




From paul at boddie.org.uk  Fri May 14 15:26:34 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 12:26:34 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
	 
	
Message-ID: 

On 14 Mai, 20:36, Patrick Maupin  wrote:
>
> That statement was made in the context of why Carl doesn't use GPL-
> licensed *libraries*. ?He and I have both explained the difference
> between libraries and programs multiple times, not that you care.

Saying that GPL-licensed applications are acceptable is a minor
concession to the use of copyleft licensing if one advocates
permissive licensing for all things which are not perceived to be
finished products: things that one isn't looking to re-use somehow.
Saying that one likes Octave and that it uses the GPL, too, is really
damning it with faint praise if one were then to say that its parts
should be permissively licensed so that one can incorporate its
functionality into something else. No, I don't care if you have a
problem with GPL-licensed libraries because it is, as we have
established repeatedly, your problem not mine.

[...]

> > The production of a
> > different "proprietary flavour" of MatLab wouldn't be beneficial to
> > them at all - it might even be detrimental to their project - and
> > might only be marginally beneficial, at best, to existing MatLab
> > customers.
>
> I personally can't see any realistic chance of detriment. ?How could a
> proprietary clone hope to compete against free software on one side
> and real matlab on the other side? ?That's a no-win position, so I
> wouldn't expect to see any proprietary clones.

Well, only permissively licensed software would encourage such clones.
At that point, there are incentives for people to develop
functionality for proprietary deployment instead of for the upstream
project.

[PySide and proprietary software]

> No, PySide is about non-GPL software, and is released under a license
> that even RMS recognizes as "free", and it is certainly not of
> marginal utility.

No, PySide is about permitting the development of proprietary
applications by providing a solution to the all-important "ISVs" which
lets them develop and deploy proprietary software. Do you really think
a platform vendor whose "ISVs" routinely ship proprietary software on
their platform and on other platforms, and who will demand the ability
to continue to do so, now expects all these "ISVs" to provide their
applications under the modified BSD licence? Sure, other developers
can use the software - even people releasing GPL-licensed software -
but that is highly unlikely to be the primary business motivation. If
you think the mobile telephony vendors are a bunch of fluffy bunny
rabbits playing with each other in sugary meadows of niceness, I don't
want to be present when someone directly and finally disabuses you of
this belief. It's all about people selling stuff to "consumers" over
and over again, preferably with the "consumers" rarely if ever being
able to opt-out and do things their own way.

> > (And PyQt is not "marginally useful" - it is a widely-used and widely
> > well-regarded library.)
>
> Well, we agree on that. ?But I don't know why you're trying to claim I
> said PyQt was only marginally useful.

Because you followed on from writing about PyQt by introducing the
topic of "marginally useful" libraries, thus giving the impression
that you regarded PyQt as "marginally useful".

Paul


From aaron.hildebrandt at gmail.com  Fri May 14 15:27:02 2010
From: aaron.hildebrandt at gmail.com (Aaron Scott)
Date: Fri, 14 May 2010 12:27:02 -0700 (PDT)
Subject: Including a remote file -- permission denied?
Message-ID: 

I have a Python script running on the default OSX webserver, stored
in /Library/WebServer/CGI-Executables. That script spits out a list of
files on a network drive, a la "os.listdir('/Volumes/code/
directory/')". If I just execute this from the terminal, it works as
expected, but when I try to access it through a browser
(computer.local/cgi-bin/test.py), I get a permissions error (: [Errno 13] Permission denied: '/Volumes/code/
directory').

Is there any way to give the script permission to access the network
when accessed via CGI?


From prologic at shortcircuit.net.au  Fri May 14 15:28:46 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sat, 15 May 2010 05:28:46 +1000
Subject: joining two column
In-Reply-To: <4BED9A9F.5040708@tim.thechases.com>
References: <20100514172237.23776.qmail@f4mail-235-238.rediffmail.com> 
	 
	<4BED9A9F.5040708@tim.thechases.com>
Message-ID: 

On Sat, May 15, 2010 at 4:46 AM, Tim Chase
 wrote:
> I think you meant izip() instead of chain() ... the OP wanted to be able to
> join the two lines together, so I suspect it would look something like

You're quite right! My mistake :)

--James


From e_d_k at yahoo.com  Fri May 14 16:05:59 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 13:05:59 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <994222.78014.qm@web58703.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Paul Boddie  wrote:


<<<>>
> 
> No, PySide is about permitting the development of
> proprietary
> applications by providing a solution to the all-important
> "ISVs" which
> lets them develop and deploy proprietary software. Do you
> really think
> a platform vendor whose "ISVs" routinely ship proprietary
> software on
> their platform and on other platforms, and who will demand
> the ability
> to continue to do so, now expects all these "ISVs" to
> provide their
> applications under the modified BSD licence? Sure, other
> developers
> can use the software - even people releasing GPL-licensed
> software -
> but that is highly unlikely to be the primary business
> motivation. If
> you think the mobile telephony vendors are a bunch of
> fluffy bunny
> rabbits playing with each other in sugary meadows of
> niceness, I don't
> want to be present when someone directly and finally
> disabuses you of
> this belief. It's all about people selling stuff to
> "consumers" over
> and over again, preferably with the "consumers" rarely if
> ever being
> able to opt-out and do things their own way.

Do you feel the same way about Python? It is released under a 
nonrestrictive license, since you are on this list I assume you use it.

If you want, I think you could use the existing Python code base to create 
a GPLed version of Python, I think the license is permissive enough to 
allow that. If you did, do you think more people would use the GPLed 
version? 

Personally, I would use the version with the more permissive license, unless the GPLed version offered a significant advantage of some kind.

     -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From pmaupin at gmail.com  Fri May 14 16:12:41 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 13:12:41 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
	 
	 
	
Message-ID: 

On May 14, 2:26?pm, Paul Boddie  wrote:
> On 14 Mai, 20:36, Patrick Maupin  wrote:
>
>
>
> > That statement was made in the context of why Carl doesn't use GPL-
> > licensed *libraries*. ?He and I have both explained the difference
> > between libraries and programs multiple times, not that you care.
>
> Saying that GPL-licensed applications are acceptable is a minor
> concession to the use of copyleft licensing if one advocates
> permissive licensing for all things which are not perceived to be
> finished products: things that one isn't looking to re-use somehow.

I am only "advocating" to the extent of explaining why I license stuff
permissively, and why, whenever I incorporate other stuff, it has to
be licensed permissively as well.  How you license your stuff is your
business.

> Saying that one likes Octave and that it uses the GPL

I don't recall saying I liked Octave.  I have no opinion.  I have
never used it.  Just threw it out there as an example of how people
rewrite proprietary software to counter your indignation that somebody
would rewrite PyQt.

> damning it with faint praise if one were then to say that its parts
> should be permissively licensed so that one can incorporate its
> functionality into something else.

I'm not operating a chop shop.  Never even had cause to look at the
source.  I really don't care about it.

> No, I don't care if you have a
> problem with GPL-licensed libraries because it is, as we have
> established repeatedly, your problem not mine.

Sure, the problems that I see with the GPL lead me to choose non-GPL
solutions for libraries.  And I never asked you to care.  I had a
brief moment of hope that you could see that my concerns were valid,
if personal, but apparently you can only concede that if you attribute
some sort of selfish ill-will to me.

> > I personally can't see any realistic chance of detriment. ?How could a
> > proprietary clone hope to compete against free software on one side
> > and real matlab on the other side? ?That's a no-win position, so I
> > wouldn't expect to see any proprietary clones.
>
> Well, only permissively licensed software would encourage such clones.

See, there you go with choice of language again.  Remember, we're both
biased with different viewpoints.  You say "encourage"; I say
"allow."  I further argued that it's immaterial that it's allowed,
nobody sane would do it.

> At that point, there are incentives for people to develop
> functionality for proprietary deployment instead of for the upstream
> project.

What incentives?  The incentives that the original matlab team will
keep outcompeting you from the top, or the incentives that the open
source octave team will keep outcompeting you from the bottom?

> [PySide and proprietary software]
>
> > No, PySide is about non-GPL software, and is released under a license
> > that even RMS recognizes as "free", and it is certainly not of
> > marginal utility.
>
> No, PySide is about permitting the development of proprietary
> applications by providing a solution to the all-important "ISVs" which
> lets them develop and deploy proprietary software.

That's an interesting viewpoint.  Originally, both Qt and PyQt were
available dual-licensed under the GPL or proprietary licenses.  For
anybody serious about proprietary development, the proprietary
licensed versions were actually quite reasonably priced.  Really the
major advantage I see in PySide licensing is for somebody like Ed or
Carl or me, who simply wants to be able to deliver programs with no
strings attached.  That was not possible under the GPL-licensed
version (because of the strings attaching to the customer that Ed has
talked about) or the commercial version (because then Ed couldn't even
give his customer the source to PyQt).  PySide is LGPL, which Ed still
might not touch, but at least any "linking" required between that and
code that uses it is really just an import statement, so then again,
he might be OK with that.

Of course, the fact that Qt and PySide are now both free of cost for
non-GPL customers certainly helps Nokia in their push to get people to
take them.

> Do you really think
> a platform vendor whose "ISVs" routinely ship proprietary software on
> their platform and on other platforms, and who will demand the ability
> to continue to do so, now expects all these "ISVs" to provide their
> applications under the modified BSD licence?

Not at all.  But they have now *enabled* ISVs to do that.  Before,
with QT and PyQt, it was GPL or proprietary.

> Sure, other developers
> can use the software - even people releasing GPL-licensed software -
> but that is highly unlikely to be the primary business motivation.

I think the motivation was to remove all impediments to using it on
the platform, and I see nothing wrong with that motivation.  They
already spent a lot on Qt, and they really want to leverage that.

> If
> you think the mobile telephony vendors are a bunch of fluffy bunny
> rabbits playing with each other in sugary meadows of niceness, I don't
> want to be present when someone directly and finally disabuses you of
> this belief.

I don't recall writing anything that would give you that impression,
but whatever.

> It's all about people selling stuff to "consumers" over
> and over again, preferably with the "consumers" rarely if ever being
> able to opt-out and do things their own way.

Nokia is locked in a tight battle with multiple players.  Developments
like Nokia using Qt and PyQt (which give small developers a chance to
play easily on that platform) and Google handing out Android to
whoever wants it are going to make the selling over-and-over
increasingly harder to do.  (Not that they won't do if if they can.  I
just think they are increasingly going to have a hard time playing
that game.)

>
> > > (And PyQt is not "marginally useful" - it is a widely-used and widely
> > > well-regarded library.)
>
> > Well, we agree on that. ?But I don't know why you're trying to claim I
> > said PyQt was only marginally useful.
>
> Because you followed on from writing about PyQt by introducing the
> topic of "marginally useful" libraries, thus giving the impression
> that you regarded PyQt as "marginally useful".

Well, it's pretty obvious to anyone paying attention that PySide was
written for the sole purpose of creating something with similar
functionality as PyQt, but under a permissive license, so when I wrote
"nobody's going to waste time rewriting a marginally useful GPLed
library just to put a permissive license on it, either." I *obviously*
was explaining that projects which *aren't* marginal, such as PyQt and
MatLab, are the *only* kinds of projects that would be rewritten for a
simple license change.  You really should slow down and read a bit
more carefully.

Regards,
Pat


From stefan_ml at behnel.de  Fri May 14 16:17:52 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 14 May 2010 22:17:52 +0200
Subject: parsing XML
In-Reply-To: 
References: 
	
Message-ID: 

Martin v. Loewis, 14.05.2010 17:15:
> kaklis at gmail.com wrote:
>> Hi to all, let's say we have the following Xml
>> 
>>    
>>      17.1
>>      6.4
>>    
>>    
>>      15.5
>>      7.8
>>    
>> 
>>
>> How can i get the players name, age and height?
>> DOM or SAX and how
>
> Homework?

I would hope that every school teacher who teaches Python is able to skip 
through c.l.py and the python-tutor list before accepting a homework result.

Stefan



From no.email at nospam.invalid  Fri May 14 16:19:59 2010
From: no.email at nospam.invalid (Paul Rubin)
Date: Fri, 14 May 2010 13:19:59 -0700
Subject: Iterating over dict and removing some elements
References: 
	<1e19af7b-226a-4cae-a407-e6285344a28c@6g2000prg.googlegroups.com>
Message-ID: <7xsk5u1bio.fsf@ruckus.brouhaha.com>

Bryan  writes:
> In Python 3.X, and in Python 2.X starting with 2.4, you can drop the
> square brackets and avoid creating an extra temporary list:
>
> d = dict((k, d[k]) for k in d.keys() if not foo(k, d))

In 2.x, I think you want d.iterkeys() rather than d.keys() to avoid
making a list with all the keys.  Or you can just say

  d = dict((k, d[k]) for k in d if not foo(k, d))


From awilliam at whitemice.org  Fri May 14 16:44:48 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Fri, 14 May 2010 16:44:48 -0400
Subject: parsing XML
In-Reply-To: 
References: 
	  
Message-ID: <1273869888.12194.11.camel@linux-yu4c.site>

On Fri, 2010-05-14 at 22:17 +0200, Stefan Behnel wrote:
> >> 
> >>    
> >>      17.1
> >>      6.4
> >>    
> >>    
> >>      15.5
> >>      7.8
> >>    
> >>  

from lxml import etree
handle = open('file', 'rb')
doc = etree.parse(handle)
handle.close()
players = [ ]
for player in doc.xpath('/team/player'):
  players.append({ 'name': player.xpath('./@name')[0],
                   'age': player.xpath('./@age')[0],
                   'height': player.xpath('./@height')[0] } )
print players
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba



From martin at v.loewis.de  Fri May 14 17:23:06 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Fri, 14 May 2010 23:23:06 +0200
Subject: Loading C extension from memory
In-Reply-To: 
References: 
Message-ID: <4BEDBF3A.3030906@v.loewis.de>


> I wonder if there is a way to load C extension from in-memory object,
> not from the file on the disk?
> 
> I'm asking bc I would like to download C extensions over network and
> load them into Python interpreter (without storing the C extension in
> file on the disk).
> 
> I googled for this but there appear only methods of loading compiled
> Python (bytecode) modules.

First, it depends on your operating system. None of the standard
operating systems supports loading shared libraries from memory; they
all need a file name.

Of course, your operating system may provide support for RAM disks. So
if you store the extension onto a RAM disk, you can load it from there -
from memory.

It may be possible to extend the Python interpreter to not rely on
shared libraries anymore for extension modules. Such an interpreter
likely wouldn't use standard shared libraries anymore, so you might
then have to recompile the extensions to make them loadable from memory.
However, it also might be possible to reimplement the shared library
loader of the operating system, in which case you could then run
regular extension modules directly from memory.

Regards,
Martin


From martin at v.loewis.de  Fri May 14 17:46:25 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Fri, 14 May 2010 23:46:25 +0200
Subject: parsing XML
In-Reply-To: 
References: 	
	
Message-ID: <4BEDC4B1.3080104@v.loewis.de>

>>> Hi to all, let's say we have the following Xml
>>> 
>>>    
>>>      17.1
>>>      6.4
>>>    
>>>    
>>>      15.5
>>>      7.8
>>>    
>>> 
>>>
>>> How can i get the players name, age and height?
>>> DOM or SAX and how
>>
>> Homework?
> 
> I would hope that every school teacher who teaches Python is able to
> skip through c.l.py and the python-tutor list before accepting a
> homework result.

If he uses your proposed solution, it probably wouldn't pass, anyway,
because it's neither DOM nor SAX. If he's really interested in a
solution to the original problem, then ElementTree is fine, of course.

As for teachers scanning relevant forums: that's often impractical.
For example, for an XML lecture, choice of programming language may be
to the student. You then have to search web forums, mailing lists, and
newsgroups for Java, Python, C#, Ruby, Scala, plus StackOverflow.

Solutions copied from the net often show a level of cuteness beyond
what you'd expect from a student (like your solution: who'd be using
reflection to access three attributes?). So you rather take these clues
as the starting point for an investigation (and then hope that Google
comes up with the specific source code).

Of course, it may also be that getting help is explicitly allowed.

Regards,
Martin


From dreadpiratejeff at gmail.com  Fri May 14 18:38:55 2010
From: dreadpiratejeff at gmail.com (J)
Date: Fri, 14 May 2010 18:38:55 -0400
Subject: write a 20GB file
In-Reply-To: 
References: 
	<4BED2E45.6060301@ieee.org>
	 
	
	
Message-ID: 

On Fri, May 14, 2010 at 15:23, Nobody  wrote:
> On Fri, 14 May 2010 10:50:49 -0400, J wrote:
>
>> someone smarter than me can correct me, but file.write() will write when
>> it's buffer is filled, or close() or flush() are called.
>
> And, in all probability, seek() will either flush it immediately or cause
> the next write() to flush it before writing anything.

Ahhh... I didn't know that... I thought seek() just moved the pointer
through the file a little further....

Cool.


From clp2 at rebertia.com  Fri May 14 19:02:11 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Fri, 14 May 2010 16:02:11 -0700
Subject: Alternate string object type for PyStringObject(available Python 
	2.x) in python 3.x?
In-Reply-To: <12897d06413.515885629628951451.7220101516557890617@gmail.com>
References: <12897d06413.515885629628951451.7220101516557890617@gmail.com>
Message-ID: 

On Fri, May 14, 2010 at 10:15 AM, MathanK  wrote:
> What is the replacement in python 3.x for PyStringObject which is available
> in python 2.x?

PyUnicodeObject or PyBytesObject depending on your use case.

Cheers,
Chris
--
http://blog.rebertia.com


From paul at boddie.org.uk  Fri May 14 19:42:34 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 16:42:34 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
	 
	 
	 
	
Message-ID: 

On 14 Mai, 22:12, Patrick Maupin  wrote:
>
> I *obviously*
> was explaining that projects which *aren't* marginal, such as PyQt and
> MatLab, are the *only* kinds of projects that would be rewritten for a
> simple license change.

"As far as your comments about PyQt proving out the concept, well duh!
Just as there are a lot of proprietary programs that are relatively
useless and *won't* have any GPLed versions written, nobody's going to
waste time rewriting a marginally useful GPLed library just to put a
permissive license on it, either."

This being the sudden introduction of this notion of a "marginally
useful" library. And for a long time no-one did rewrite PyQt for the
purpose of having a permissively licensed library, so it's quite
natural to assume that you're saying that until PySide came along, the
reasons for which I have already noted, PyQt was a "marginally useful"
library, not worth rewriting.

> You really should slow down and read a bit more carefully.

You might want to tone down the condescension.

Paul


From paul at boddie.org.uk  Fri May 14 19:52:28 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 16:52:28 -0700 (PDT)
Subject: Picking a license
References: 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com> 
	 
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com>
Message-ID: <47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com>

On 14 Mai, 21:14, Patrick Maupin  wrote:
>
> If Joe downloads and burns a CD for his friend, he may not have the
> sources and may not have any intention of getting them, and probably
> didn't provide a "written offer." ?What you're "ignoring for the
> moment" is my whole point, that unlike Ubuntu, Joe is now in violation
> of the GPL license, because he provided neither a written offer nor
> source on CD, nor his own download site.

Now, wait a moment! Your point is that just by giving the binary CD to
someone, you are now in violation of the licence. What I tried to
explain is that this situation is anticipated - that the FSF
acknowledges that the recipient won't have received the sources at the
same time in all situations - and that the same distributor is
responsible for providing the sources. As long as they don't deny the
recipient access to the sources, by the same means, they are not
violating the licence.

You have a point about recipients not being immediately and obviously
informed of the things they are entitled to, but that is a matter for
the distributing parties to remedy: that is arguably what happens
when, upon loud squealing about matters of "ideology", distributors
decide to de-emphasise the Free Software aspect of their
distributions. Nevertheless, it is my understanding that anyone
attempting to use or install such distributions do get to see a
summary of the licences; only people who pass on the software without
inspecting it (which would involve actually inserting the CD and
booting from it) will be unaware of its contents, and they could only
be held responsible as reasonably as one's Internet service provider
if that party were asked to provide source packages for "that Linux
distro I downloaded last year".

You also have a point about whether people are able to provide sources
at a later date, which might be troublesome if someone gave someone
else a CD with an old version of Ubuntu on it and then were asked to
provide the source packages. Naturally, the FSF have attempted to
address these points in version 3 of the GPL. I would be interested to
hear the opinion of the FSF and distributors on this matter, but I
think it's absurd to accuse the FSF as operating as you allege
Microsoft do, especially as the distributors are the ones who
encourage the sharing of the installation media.

Really, if you think distributions should do a better job at educating
their users and helping them uphold any obligations that may apply to
them, you should talk to them about it. But when I attempt to work
though the issues in a thorough manner in order to thrash out what it
is you really object to - and in practice, the only objections you can
seriously have lie in those two points I mention above (not this
"instant violation" situation, discussed in more detail elsewhere [*])
- and all you can do is suggest that other people are trying to
mislead you, I struggle to feel inclined to indulge you further.

And suggesting that people have behavioural disorders ("Or because
have OCD?") might be a source of amusement to you, or may be a neat
debating trick in certain circles you admire, but rest assured that I
am neither amused nor impressed, nor are others likely to be.

Paul

[*] http://www.mail-archive.com/debian-legal at lists.debian.org/msg31466.html


From paul at boddie.org.uk  Fri May 14 20:12:04 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Fri, 14 May 2010 17:12:04 -0700 (PDT)
Subject: Picking a license
References: 
Message-ID: <93d67bd9-6721-4759-a3de-412b95b29a93@c11g2000vbe.googlegroups.com>

On 14 Mai, 21:18, Ed Keith  wrote:
>
> The GPL is fine when all parties concern understand what source code is
> and what to do with it. But when you add people like my father to the loop
> if gets very ugly very fast.

Sure, and when I'm not otherwise being accused of pushing one
apparently rather unpopular man's agenda, I am interested in knowing
what the best practices should be and how they can be followed more
widely.

Although Bill Gates once apparently claimed that no-one needs the
source code for their word processor or office suite, there are still
benefits in people like your father having access to the sources, even
if this obviously means that he isn't going to recompile it himself:
he can get others to fix things, particularly if his favourite version
is no longer widely supported; if you were from a part of the planet
where you were comfortable with a widely-spoken "global" language but
your father could only converse in a less widely-spoken "minority"
language not generally supported by such software, someone (perhaps
you) could undertake the task of translating that software.

Whether or not one is comfortable with copyleft-style licences, there
clearly is a benefit in providing access to software governed by those
licences. Being able to do so responsibly is obviously a prerequisite
to feeling comfortable about it.

Paul


From ron.eggler at gmail.com  Fri May 14 20:14:02 2010
From: ron.eggler at gmail.com (cerr)
Date: Fri, 14 May 2010 17:14:02 -0700 (PDT)
Subject: huh??? weird problem
Message-ID: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>

Hi There,

I got following code:
start=time.time()
print 'warnTimeout '+str(WarnTimeout)
print 'critTimeout '+str(CritTimeout)
print 'start',str(start)
while wait:
    passed =  time.time()-start
    print 'passed ',str(passed)
    if passed >= WarnTimeout:
      print ' Warning!'
 ...
...
...
which basically means that the loops should go until the warning time
has been reached and then i want it to print 'warning!' and execute
some warning code. But weirdly enough i get following screen output:
warnTimeout 3
critTimeout 5
start 1273882010.43
passed  7.60555267334e-05
passed  0.998471975327
passed  1.99847102165
passed  2.9984691143
passed  3.99847006798
passed  4.998472929
...
...
any one a clue why after 3 seconds it doesn't go into the the if an
print 'Warning!'? That's odd... :o Crazy, what am i not seeing? :(


From tjreedy at udel.edu  Fri May 14 20:24:56 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Fri, 14 May 2010 20:24:56 -0400
Subject: Picking a license
In-Reply-To: <47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com>
References: 	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com>
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com>
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com>
	
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com>
	<47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com>
Message-ID: 

The following lines from

http://www.softwarefreedom.org/resources/2008/compliance-guide.html

seem to cover the case of someone who casually redistributes, for free, 
Ubuntu or whatever. Such can refer people back to the Ubuntu site. They 
should, perhaps, be familiar with the url, but I would expect that the 
binary Ubuntu distribution CDs have the appropriate offer and details on 
that disk. Someone who casually distributes, for free, a subset should 
also be covered. Under 4.1.2  Option (b): The Offer,

"The option to provide an offer for source rather than direct source 
distribution is a special benefit to companies equipped to handle a 
fulfillment process. GPLv2 ? 3(c) and GPLv3 ? 6(c) avoid burdening 
noncommercial, occasional redistributors with fulfillment request 
obligations by allowing them to pass along the offer for source as they 
received it.

Note that commercial redistributors cannot avail themselves of the 
option (c) exception, and so while your offer for source must be good to 
anyone who receives the offer (under v2) or the object code (under v3), 
it cannot extinguish the obligations of anyone who commercially 
redistributes your product. The license terms apply to anyone who 
distributes GPL?d software, "

Terry Jan Reedy




From awilliam at whitemice.org  Fri May 14 20:27:18 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Fri, 14 May 2010 20:27:18 -0400
Subject: Puzzled by code pages
Message-ID: <1273883238.3929.8.camel@linux-yu4c.site>

I'm trying to process OpenStep plist files in Python.  I have a parser
which works, but only for strict ASCII.  However plist files may contain
accented characters - equivalent to ISO-8859-2 (I believe).  For example
I read in the line:

>>> handle = open('file.txt', 'rb')
>>> data = handle.read()
>>> handle.close()
>>> data
'    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
NSFileName;\n'

What is the correct way to re-encode this data into UTF-8 so I can use
unicode strings, and then write the output back to ISO8859-?

I can read the file using codecs as ISO8859-2, but it still doesn't seem
correct.

>>> handle = codecs.open('file.txt', 'rb', encoding='iso8859-2')
>>> data = handle.read()
>>> handle.close()
>>> data
u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
NSFileName;\n'




From pavlovevidence at gmail.com  Fri May 14 20:28:57 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 14 May 2010 17:28:57 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com
Message-ID: <5cbfb2c3-6d39-4878-88a3-44c206a9ecdd@k25g2000prh.googlegroups.com>

On May 14, 8:20?am, Paul Boddie  wrote:
> On 14 Mai, 09:08, Carl Banks  wrote:
>
> > On May 13, 10:59?pm, Steven D'Aprano  wrote:
> > > On Thu, 13 May 2010 17:18:47 -0700, Carl Banks wrote:
> > > > 2. Reimplment the functionality seperately (*cough* PySide)
>
> > > Yes. So what? In what possible way is this an argument against the GPL?
>
> [...]
>
> > It's not. ?It's an argument that the GPL doesn't do much good.
>
> Right. So nobody got the benefit from Qt under the GPL or PyQt under
> the GPL?

[Snip a bunch of crap I don't care about]

The community as a whole benefited from PyQt because it was free, not
because it was GPL.  The community as whole suffered because it was
GPL instead of a more permissive license.

Now that we have PySide the community as a whole will benefit much,
much more than it could with only a GPLed PyQt.


Carl Banks


From clp2 at rebertia.com  Fri May 14 20:29:55 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Fri, 14 May 2010 17:29:55 -0700
Subject: huh??? weird problem
In-Reply-To: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
References: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
Message-ID: 

On Fri, May 14, 2010 at 5:14 PM, cerr  wrote:
> Hi There,
>
> I got following code:
> start=time.time()
> print 'warnTimeout '+str(WarnTimeout)
> print 'critTimeout '+str(CritTimeout)
> print 'start',str(start)
> while wait:
> ? ?passed = ?time.time()-start
> ? ?print 'passed ',str(passed)
> ? ?if passed >= WarnTimeout:
> ? ? ?print ' Warning!'
> ?...
> ...
> ...
> which basically means that the loops should go until the warning time
> has been reached and then i want it to print 'warning!' and execute
> some warning code. But weirdly enough i get following screen output:
> warnTimeout 3
> critTimeout 5
> start 1273882010.43
> passed ?7.60555267334e-05
> passed ?0.998471975327
> passed ?1.99847102165
> passed ?2.9984691143
> passed ?3.99847006798
> passed ?4.998472929
> ...
> ...
> any one a clue why after 3 seconds it doesn't go into the the if an
> print 'Warning!'? That's odd... :o Crazy, what am i not seeing? :(

print type(WarnTimeout)

I suspect it won't be numerical. Where is WarnTimeout assigned its value?
Note that in Python 2.x, comparisons between e.g. numbers and strings
were allowed, but the ordering was arbitrary.
Python 3.x fixes this and instead raises TypeError for such
nonsensical comparisons.

Cheers,
Chris
--
http://blog.rebertia.com


From pmaupin at gmail.com  Fri May 14 20:33:56 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 17:33:56 -0700 (PDT)
Subject: Picking a license
References: aa513b7d-8bff-42f4-ac29-6baf0416e2d5@e2g2000yqn.googlegroups.com 
	
	 
	 
	 
	 
	
Message-ID: <59713fd4-15a0-4b94-8fb0-c457ea27bf71@y12g2000vbg.googlegroups.com>

On May 14, 6:42?pm, Paul Boddie  wrote:

> > You really should slow down and read a bit more carefully.
>
> You might want to tone down the condescension.

I didn't start out condescending, and I agree I could have worded this
particular statement a bit more clearly, so I apologize for that, but
I can point to at least 5 or 6 occurrences of you misreading me when I
stated things very clearly.  It's really starting to get old.

Regards,
Pat


From mensanator at aol.com  Fri May 14 20:35:05 2010
From: mensanator at aol.com (Mensanator)
Date: Fri, 14 May 2010 17:35:05 -0700 (PDT)
Subject: huh??? weird problem
References: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
Message-ID: <289f06b9-aba0-4285-a29c-2ec676f63a2e@x1g2000vbo.googlegroups.com>

On May 14, 7:14?pm, cerr  wrote:
> Hi There,
>
> I got following code:
> start=time.time()
> print 'warnTimeout '+str(WarnTimeout)
> print 'critTimeout '+str(CritTimeout)
> print 'start',str(start)
> while wait:
> ? ? passed = ?time.time()-start
> ? ? print 'passed ',str(passed)
> ? ? if passed >= WarnTimeout:
> ? ? ? print ' Warning!'
> ?...
> ...
> ...
> which basically means that the loops should go until the warning time
> has been reached and then i want it to print 'warning!' and execute
> some warning code. But weirdly enough i get following screen output:
> warnTimeout 3
> critTimeout 5
> start 1273882010.43
> passed ?7.60555267334e-05
> passed ?0.998471975327
> passed ?1.99847102165
> passed ?2.9984691143
> passed ?3.99847006798
> passed ?4.998472929
> ...
> ...
> any one a clue why after 3 seconds it doesn't go into the the if an
> print 'Warning!'?

Works for me:

warnTimeout 3
critTimeout 5
start 1273883378.39
passed  1.0
passed  2.0
passed  3.0
 Warning!
passed  4.0
 Warning!
passed  5.0
 Warning!
passed  6.0
 Warning!
passed  7.0
 Warning!


> That's odd... :o Crazy, what am i not seeing? :(

Did you copy it right?



From awilliam at whitemice.org  Fri May 14 20:38:43 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Fri, 14 May 2010 20:38:43 -0400
Subject: Puzzled by code pages
In-Reply-To: <1273883238.3929.8.camel@linux-yu4c.site>
References: <1273883238.3929.8.camel@linux-yu4c.site>
Message-ID: <1273883923.3929.10.camel@linux-yu4c.site>

On Fri, 2010-05-14 at 20:27 -0400, Adam Tauno Williams wrote:
> I'm trying to process OpenStep plist files in Python.  I have a parser
> which works, but only for strict ASCII.  However plist files may contain
> accented characters - equivalent to ISO-8859-2 (I believe).  For example
> I read in the line:
> 
> >>> handle = open('file.txt', 'rb')
> >>> data = handle.read()
> >>> handle.close()
> >>> data
> '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
> NSFileName;\n'
> What is the correct way to re-encode this data into UTF-8 so I can use
> unicode strings, and then write the output back to ISO8859-?

Typical, 30 seconds after giving up and posting a message... I find the
problem.

Buried in the parser is a str(...) call.  Replacing that with
unicode(...) and now the OpenSTEP plist parser is working with Italian
plists.



From pmaupin at gmail.com  Fri May 14 20:51:35 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 17:51:35 -0700 (PDT)
Subject: Picking a license
References: 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com> 
	 
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com> 
	<47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com> 
	
Message-ID: <6fb754b4-20a9-4ab5-ae93-63571e6a119a@z17g2000vbd.googlegroups.com>

On May 14, 7:24?pm, Terry Reedy  wrote:
>
> "The option to provide an offer for source rather than direct source
> distribution is a special benefit to companies equipped to handle a
> fulfillment process. GPLv2 ? 3(c) and GPLv3 ? 6(c) avoid burdening
> noncommercial, occasional redistributors with fulfillment request
> obligations by allowing them to pass along the offer for source as they
> received it.

Paul Boddie already pointed out that document.  As I explained, that
document was written for the Ciscos of the world.  The FAQ, which was
written for you and me states very clearly "The general rule is, if
you distribute binaries, you must distribute the complete
corresponding source code too. The exception for the case where you
received a written offer for source code is quite limited." in answer
to the question "I downloaded just the binary from the net. If I
distribute copies, do I have to get the source and distribute that
too?"

As I have pointed out on at least 3 posts by now, this FAQ
interpretation derives directly from the actual license terms and
appears to reflect the terms correctly. If you actually *read* GPLv3 ?
6(c), it *only* applies if you received the object code in accordance
with GPLv3 ? 6(b).  But if you download an ISO from Ubuntu, that
happens under GPLv3 ? 6(d), *not* GPLv3 ? 6(b).

However, the distribution to your friend when you give him the CD that
you burned for him is under 6(b), so not only do you not have an
upstream to rely on, you are actually in violation of the license once
you give him the CD without your own written offer!  (At one level,
this makes sense -- if the 3 year window for source is to have any
teeth, then you can't give the poor guy a CD 2 years after you
downloaded it and expect Ubuntu to make good on the source 5 years
after you downloaded it.)

Now maybe there is some *other* way (besides the obvious ways I've
mentioned such as fair use and the fact that nobody's going to sue
because of the PR fallout from bothering some grandma for sharing a CD
that was advertised as "free") that this is not an issue, but nobody
on this thread has yet shown any credible evidence that the act of
just handing somebody a freshly burned Ubuntu CD with no written offer
is not a violation of the license.

As I have made clear, I do not view this as a direct practical
problem.  But I do view it as a huge problem that the license is so
complex that in a couple of days of conversing about it, several
people have asserted that there is no way my reading of the license is
correct, yet nobody has shown solid evidence that would back up an
alternate reading, and I also view it as the tip of the iceberg as far
as the issue of license compliance goes.

Regards,
Pat


From davea at ieee.org  Fri May 14 21:41:54 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 14 May 2010 21:41:54 -0400
Subject: huh??? weird problem
In-Reply-To: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
References: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
Message-ID: <4BEDFBE2.4090207@ieee.org>

cerr wrote:
> Hi There,
>
> I got following code:
> start=time.time()
> print 'warnTimeout '+str(WarnTimeout)
> print 'critTimeout '+str(CritTimeout)
> print 'start',str(start)
> while wait:
>     passed =  time.time()-start
>     print 'passed ',str(passed)
>     if passed >= WarnTimeout:
>       print ' Warning!'
>  ...
> ...
> ...
> which basically means that the loops should go until the warning time
> has been reached and then i want it to print 'warning!' and execute
> some warning code. But weirdly enough i get following screen output:
> warnTimeout 3
> critTimeout 5
> start 1273882010.43
> passed  7.60555267334e-05
> passed  0.998471975327
> passed  1.99847102165
> passed  2.9984691143
> passed  3.99847006798
> passed  4.998472929
> ...
> ...
> any one a clue why after 3 seconds it doesn't go into the the if an
> print 'Warning!'? That's odd... :o Crazy, what am i not seeing? :(
>
>   
we're not seeing all the relevant code.  While I can ignore the missing 
import, I don't see any creation of the variables WarnTimeout and 
CritTimeout.  Simplest explanation that fits your sample run is that 
they are not of type float.

DaveA



From pmaupin at gmail.com  Fri May 14 21:46:21 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 18:46:21 -0700 (PDT)
Subject: Picking a license
References: 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com> 
	 
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com> 
	<47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com>
Message-ID: 

On May 14, 6:52?pm, Paul Boddie  wrote:
> On 14 Mai, 21:14, Patrick Maupin  wrote:
>
> > If Joe downloads and burns a CD for his friend, he may not have the
> > sources and may not have any intention of getting them, and probably
> > didn't provide a "written offer." ?What you're "ignoring for the
> > moment" is my whole point, that unlike Ubuntu, Joe is now in violation
> > of the GPL license, because he provided neither a written offer nor
> > source on CD, nor his own download site.
>
> Now, wait a moment! Your point is that just by giving the binary CD to
> someone, you are now in violation of the licence.

Correct -- download an ISO, burn onto CD, hand CD to friend w/o
written offer = license violation.

> What I tried to
> explain is that this situation is anticipated - that the FSF
> acknowledges that the recipient won't have received the sources at the
> same time in all situations - and that the same distributor is
> responsible for providing the sources.

Right.  That distributor would be Joe.

> As long as they don't deny the
> recipient access to the sources, by the same means, they are not
> violating the licence.

But Joe didn't give a written offer, and he doesn't even know how to
download the source, and you still haven't showed why that's not a
problem for him.

> You have a point about recipients not being immediately and obviously
> informed of the things they are entitled to, but that is a matter for
> the distributing parties to remedy:

Well, Joe's the distributor to his friend.  He got the stuff from
Ubuntu, who will give him source and even have a legal page about it,
but Joe didn't bother reading all that stuff.

> that is arguably what happens
> when, upon loud squealing about matters of "ideology", distributors
> decide to de-emphasise the Free Software aspect of their
> distributions.

Yesterday, you were telling me I should inform Ubuntu that they didn't
have enough license information prominently available in the right
places.  Are you now claiming that that's simply because people like
me told Ubuntu that they were emphasizing the license information too
much?

In any case, Ubuntu prominently describes "The Ubuntu Promise" with a
link to more information from their front page.  Of course, the
download button is prominent as well.

> Nevertheless, it is my understanding that anyone
> attempting to use or install such distributions do get to see a
> summary of the licences;

Yes, and we all know that everybody has been trained to fully read and
understand every single license the click on when installing software.

> only people who pass on the software without
> inspecting it (which would involve actually inserting the CD and
> booting from it) will be unaware of its contents,

Well, to make what I said in my previous comment more clear, I believe
that Joe would have actually installed the software himself without
bothering to read the license.  This may be foolish of Joe, but he is
in excellent company -- in one recent unscientific yet (IMO) well-
constructed study, only 12% of users bothered to read the license at
all:

http://www.huffingtonpost.com/2010/04/17/gamestation-grabs-souls-o_n_541549.html

> and they could only
> be held responsible as reasonably as one's Internet service provider
> if that party were asked to provide source packages for "that Linux
> distro I downloaded last year".

You still haven't yet provided any credible evidence for this version
of the chain of responsibility.  But in any case, I suspect Joe would
have actually installed the software without bothering to read any
license information.

> You also have a point about whether people are able to provide sources
> at a later date, which might be troublesome if someone gave someone
> else a CD with an old version of Ubuntu on it and then were asked to
> provide the source packages.

Bingo!  My hypothetical Joe would be in serious hot water at this
point.

> Naturally, the FSF have attempted to
> address these points in version 3 of the GPL.

And I submit that they addressed the problem by making it really clear
that yes, it is Joe's responsibility, in section 6.

> I would be interested to
> hear the opinion of the FSF and distributors on this matter, but I
> think it's absurd to accuse the FSF as operating as you allege
> Microsoft do, especially as the distributors are the ones who
> encourage the sharing of the installation media.

Well, it's really the entire ecosystem. I have to believe that
everybody at the FSF knows how this works, and even though RMS is a
shrinking violet, I suspect that if he seriously cared about this, he
would work up the courage to address it publicly, much as it pains him
to share his opinions.

> Really, if you think distributions should do a better job at educating
> their users and helping them uphold any obligations that may apply to
> them, you should talk to them about it.

I seriously don't think they, or the FSF, are interested in this, and
I don't think they will harass Joe in any case.  My whole point is
that I believe they *could*, and if several people on this thread
can't either (1) understand and believe that; or (2) provide credible
reasons why I am mistaken, after umpteen posts on several days on this
issue, then the entire issue of actual compliance to the license in a
practical fashion (where I consider downloading and burning a DVD of
source to go along with every CD of object impractical) is really a
lot trickier than some people are making it out to be. This bolsters
my personal opinion that one rational response to this complexity is
to avoid the license when possible.

> But when I attempt to work
> though the issues in a thorough manner in order to thrash out what it
> is you really object to - and in practice, the only objections you can
> seriously have lie in those two points I mention above (not this
> "instant violation" situation, discussed in more detail elsewhere [*])

It's my opinion that the decision to let Joe off the hook is
strategic.  Nobody's going to bother Joe, but they *could*.  But
there's no percentage in it.  I don't actually object to the strategic
decision.  It's a marketing decision designed to increase the reach of
the software.  Yet instead of embracing the decision yourself, you not
only deny it, but accuse me of bad faith in even suggesting that it
could be a deliberate strategy.

> - and all you can do is suggest that other people are trying to
> mislead you, I struggle to feel inclined to indulge you further.

I'm suggesting that some other people should consider that perhaps my
viewpoint, while admittedly biased (as are all viewpoints) is not all
that inconsistent with reality.

> And suggesting that people have behavioural disorders ("Or because
> have OCD?") might be a source of amusement to you, or may be a neat
> debating trick in certain circles you admire, but rest assured that I
> am neither amused nor impressed, nor are others likely to be.

That was in an honest response to a question you asked "Really, if at
this point you think I'm playing games with you." where I explained
that I don't know what to think, because often, when you claimed to be
addressing my point, you would bring up other red herrings and spend
more time on those, and often assign positions to me that I never
took.  When I suggested maybe you don't read carefully enough, you
claimed that's not the root of the problem, so I really don't know
what it is, other than that maybe you need to calm down and reread
what I posted and what you are planning to respond with before pushing
"send".  It's really very annoying to be expected to defend positions
I didn't take and statements I didn't make and to have most of your
comments have a subtle dig at my motivations.  I honestly don't know
what makes you do that, but it certainly does not bring out the best
in me.  I will try to do better if you do too.  (BTW, IMO this was one
of your better posts in terms of tone and being on-point, etc., and I
appreciate that.)

Regards,
Pat


From ldo at geek-central.gen.new_zealand  Fri May 14 21:55:08 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 13:55:08 +1200
Subject: parsing XML
References: 
	
Message-ID: 

In message , Stefan 
Behnel wrote:

> Here's an overly complicated solution, but I thought that an object
> oriented design would help here.

How many times are you going to write the ?"name", "age", "height"? 
sequence? The next assignment question I would ask is: how easy would it be 
to add a fourth attribute?

>    attributes = ['name', 'age', 'height']

I would put this at the top.

Then this

>    class Player(object):
>       def __init__(self, name, age, height):
>           self.name, self.age, self.height = name, age, height

can become

    class Player(object):
       def __init__(self, **rest):
           for attr in attributes :
               setattr(self, attr, rest[attr])
           #end for
       #end __init__
    #end Player

and

>    for player in players:
>        print player.name, player.age, player.height

can become

    for player in players:
        print " ".join(getattr(player, attr) for attr in attributes)
    #end for



From ldo at geek-central.gen.new_zealand  Fri May 14 21:56:08 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 13:56:08 +1200
Subject: Broken pipe
References: 
	
	 <4bec2a9a$1@dnews.tpgi.com.au>
Message-ID: 

In message <4bec2a9a$1 at dnews.tpgi.com.au>, Lie Ryan wrote:

> On 05/13/10 22:41, Lawrence D'Oliveiro wrote:
>> In message , Chris
>> Rebert wrote:
>> 
>>> Also, please don't use semicolons in your code. It's bad style.
>> 
>> Wonder why they?re allowed, then.
> 
> they're there for line continuation, e.g.:
> 
> a = 40; foo(a)
> 
> but in many cases, putting two statements in a single line reduces
> readability so use the semicolons extremely conservatively. But the
> worst is the abuse of semicolons for end-of-line markers.

So why are they allowed, then?


From ldo at geek-central.gen.new_zealand  Fri May 14 21:57:58 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 13:57:58 +1200
Subject: Picking a license
References: 
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
	<84a26d03-03b3-47d9-a1f9-107470b87c75@k2g2000yqe.googlegroups.com>
Message-ID: 

In message <84a26d03-03b3-47d9-
a1f9-107470b87c75 at k2g2000yqe.googlegroups.com>, Patrick Maupin wrote:

> I also firmly believe, as I have stated before, that the GPL is a much
> more commercial license.  If you want to make money off something,
> then, no doubt, GPL keeps your competitors from being able to take
> what you wrote and redistribute it as closed source.  But, frankly I
> view that as more of a business issue than a moral issue.

Nevertheless, it?s probably a big factor in why the GPL has become the 
single most popular open-source licence.


From ldo at geek-central.gen.new_zealand  Fri May 14 21:58:48 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 13:58:48 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> Yes, under the GPL every one has one set of freedoms, under the MIT or
> Boost license every one has more freedoms. Under other licenses they have
> fewer freedoms.

But what about the ?freedom? to take away other people?s freedom? Is that 
really ?freedom??


From ldo at geek-central.gen.new_zealand  Fri May 14 22:02:07 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:02:07 +1200
Subject: Picking a license
References: 
	
	<2ff3643b-6ef1-4471-8438-dcba0dc93c24@a21g2000yqn.googlegroups.com>
	
	
Message-ID: 

In message
, Patrick 
Maupin wrote:

> On May 14, 6:12 am, Lawrence D'Oliveiro 
> wrote:
>
>> In message
>> <2ff3643b-6ef1-4471-8438-dcba0dc93... at a21g2000yqn.googlegroups.com>,
>> Patrick Maupin wrote:
>
>>> On May 13, 10:04 pm, Lawrence D'Oliveiro
>>>  wrote:
>>
>> >> In message , Ed
>> >> Keith wrote:
>>
>>>>> The claim is being made that [the GPL] restricts freedom.
>>>>
>>>> What about the ?freedom? to restrict other people?s freedom? Should
>>>> that be restricted or not?
>>
>>> It's interesting that some people don't like the comparison of the
>>> Free Software movement to a religion, yet the main argument of the
>>> movement, and the deliberate co-opting of words like "Free" and "Free
>>> Software" ...
>>
>> Haven?t you ?co-opted? those words yourself?
> 
> Only in response.

So it?s bad when others do it, but not when you do it?


From ldo at geek-central.gen.new_zealand  Fri May 14 22:04:05 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:04:05 +1200
Subject: Picking a license
References: 
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
	<9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com>
	<548024fc-dd56-48b9-907d-3aa6a722b43c@l31g2000yqm.googlegroups.com>
Message-ID: 

In message <548024fc-
dd56-48b9-907d-3aa6a722b43c at l31g2000yqm.googlegroups.com>, Patrick Maupin 
wrote:

> The confusion that some are showing in this thread about whether source
> must be distributed certainly helps to show that as well.

What ?confusion?? The GPL requires that source must always be offered in 
some form. Simple as that.


From ldo at geek-central.gen.new_zealand  Fri May 14 22:05:59 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:05:59 +1200
Subject: Picking a license
References: 
	
	<2b17ee77-0e49-4a97-994c-7582f86c0ba9@r34g2000yqj.googlegroups.com>
	
	<5e719bcd-5405-4c34-870b-13e64ef1f818@k29g2000yqh.googlegroups.com>
Message-ID: 

In message 
<5e719bcd-5405-4c34-870b-13e64ef1f818 at k29g2000yqh.googlegroups.com>, Patrick 
Maupin wrote:

> On May 14, 6:13 am, Lawrence D'Oliveiro  central.gen.new_zealand> wrote:
>
>> In message
>> <2b17ee77-0e49-4a97-994c-7582f86c0... at r34g2000yqj.googlegroups.com>,
>> Patrick Maupin wrote:
>>>
>>> On May 13, 10:06 pm, Lawrence D'Oliveiro
>>>  wrote:
>>
>>>> Under the GPL, everybody has exactly the same freedoms.
>>
>>> That's absolutely not true.  For a start, the original author can dual-
>>> license.
>>
>> That?s nothing to do with the GPL.
> 
> If you mean "that's out of the control of the GPL" I agree.  But the
> whole point of the discussion has been about how people can't take GPL
> licensed code proprietary, making enhancements, etc. and I'm just
> pointing out that this doesn't apply to the original author.  Someone
> can decide they aren't making enough money under the GPL and stop
> distributing that way, and make all their enhancements proprietary, if
> they are the original author.

That?s nothing to do with the GPL.


From ldo at geek-central.gen.new_zealand  Fri May 14 22:07:24 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:07:24 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> That is one good reason for choosing to use the GPL, instead of a less
> restrictive license. You can license it, for a fee, to someone who wants
> to use it in some way that is not allowed under the GPL.

Replace ?GPL? with ?? and your statement is no less (or more) 
true.

Funny how a lot of the arguments people keep trying to put forward about the 
GPL really have nothing to do with the GPL.


From pmaupin at gmail.com  Fri May 14 22:15:15 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:15:15 -0700 (PDT)
Subject: Picking a license
References:  
	
	<2ff3643b-6ef1-4471-8438-dcba0dc93c24@a21g2000yqn.googlegroups.com>
	
	
	
Message-ID: 

On May 14, 9:02?pm, Lawrence D'Oliveiro  wrote:
> In message
> , Patrick
>
>
>
> Maupin wrote:
> > On May 14, 6:12 am, Lawrence D'Oliveiro 
> > wrote:
>
> >> In message
> >> <2ff3643b-6ef1-4471-8438-dcba0dc93... at a21g2000yqn.googlegroups.com>,
> >> Patrick Maupin wrote:
>
> >>> On May 13, 10:04 pm, Lawrence D'Oliveiro
> >>>  wrote:
>
> >> >> In message , Ed
> >> >> Keith wrote:
>
> >>>>> The claim is being made that [the GPL] restricts freedom.
>
> >>>> What about the ?freedom? to restrict other people?s freedom? Should
> >>>> that be restricted or not?
>
> >>> It's interesting that some people don't like the comparison of the
> >>> Free Software movement to a religion, yet the main argument of the
> >>> movement, and the deliberate co-opting of words like "Free" and "Free
> >>> Software" ...
>
> >> Haven?t you ?co-opted? those words yourself?
>
> > Only in response.
>
> So it?s bad when others do it, but not when you do it?

I don't claim to have the vision that gave me the last word on
freedom, complete with the overarching power to enumerate all the
necessary freedoms on heaven and earth.  But even if I accept
Stallman's definitions of "freedom" it is apparently heretical of me
to point out that under other licenses, the original recipient of a
piece of software (for example, anybody who downloads any of my
software direct from google code) enjoys all four of the freedoms
relative to that particular piece of software, and has the additional
freedom of not having to worry too much about compliance.

BTW, RMS apparently stole "4 freedoms" from FDR.  But don't tell
anybody.

Regards,
Pat


From pmaupin at gmail.com  Fri May 14 22:17:20 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:17:20 -0700 (PDT)
Subject: Picking a license
References:  
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
	<9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com> 
	<548024fc-dd56-48b9-907d-3aa6a722b43c@l31g2000yqm.googlegroups.com> 
	
Message-ID: <6767a5ae-2aab-4532-8e18-8c445920624e@d3g2000vbr.googlegroups.com>

On May 14, 9:04?pm, Lawrence D'Oliveiro  wrote:
> In message <548024fc-
> dd56-48b9-907d-3aa6a722b... at l31g2000yqm.googlegroups.com>, Patrick Maupin
> wrote:
>
> > The confusion that some are showing in this thread about whether source
> > must be distributed certainly helps to show that as well.
>
> What ?confusion?? The GPL requires that source must always be offered in
> some form. Simple as that.

Right, but when I explained that that requirement also applies to Joe,
who downloaded an ISO from Ubuntu and burned a CD and gave it away, no
less than 3 people jumped in to "correct" me.

Regards,
Pat


From ldo at geek-central.gen.new_zealand  Fri May 14 22:17:23 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:17:23 +1200
Subject: Picking a license
References: 
Message-ID: 

In message
, Patrick 
Maupin wrote:

> After all, lots of software ideas proved their worth in proprietary
> systems, and then were later cloned by FOSS developers.

And vice versa. Everybody, whether working in closed or open environments, 
builds on the work of everybody else. Rsync pioneered the idea of doing 
transfers of incremental changes to a large file across a network without 
being able to have the two versions of the file on the same machine to do a 
direct side-by-side comparison; Microsoft copied the idea in more recent 
versions of its server software. Andrew Tridgell could easily have patented 
his idea, but he chose not to.

Apple pioneered the idea of using 3D graphics hardware to do window 
compositing on the desktop; the Compiz folks went on to figure out how to do 
this efficiently. Microsoft also copied the idea, but forgot the 
?efficiently? part.

Free Software also benefits from networking effects that are not available 
to proprietary developers. The resources available to proprietary developers 
are proportional to the size of the company they work for; typically they do 
not share software with competitors. Whereas the Free Software community is 
like one huge company in this regard, available to freely pass ideas and 
code back and forth. This has led to the creation of ideas that proprietary 
companies simply cannot match.


From ldo at geek-central.gen.new_zealand  Fri May 14 22:20:01 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:20:01 +1200
Subject: Picking a license
References: 
Message-ID: 

In message
, Paul 
Boddie wrote:

> Although people can argue that usage of the GPL prevents people from
> potentially contributing because they would not be able to sell
> proprietary versions of the software ...

It doesn?t prevent them from selling proprietary versions of their own 
contributions, any more than any other licence does.

The fact that their contribution may not be much use without the rest of 
that GPL?d code is entirely another matter. It was their choice to build on 
the work of others; they could have reinvented it from scratch themselves.


From ldo at geek-central.gen.new_zealand  Fri May 14 22:21:57 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:21:57 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> I just refuse to use [the GPL] in any code for a client, because I
> do not want to require someone who does not know source code from Morse
> code code to figure out what they need to do to avoid violating the
> license.

Why don?t you just put the source code on the same disc you send them, and 
tell them to pass copies of the entire disc to anyone they want?


From luxuryownerKelly at hotmail.com  Fri May 14 22:24:03 2010
From: luxuryownerKelly at hotmail.com (Kelly)
Date: Sat, 15 May 2010 10:24:03 +0800
Subject: Puzzled by code pages
References: 
Message-ID: 

Buy high quality TAG Heuer Tiger Woods Golf Watches at low price, you can 
not believe, but it is true.

There are two models on 
http://www.luxuryowner.net/Replica-TAG-Heuer-Tiger-Woods-Golf-Watches.html

White: Tag Heuer Tiger Woods Golf White Mens Watch WAE1112.FT6008:
http://www.luxuryowner.net/Replica-Tag-Heuer-Tiger-Woods-Golf-White-Mens-Watch-WAE1112.FT6008.html

Black: Tag Heuer Tiger Woods Golf Black Mens Watch WAE1111.FT6004
http://www.luxuryowner.net/Replica-Tag-Heuer-Tiger-Woods-Golf-Black-Mens-Watch-WAE1111.FT6004.html

More replica watches you can refer: http://www.luxuryowner.net/

"Adam Tauno Williams"  ????????????:mailman.193.1273883243.32709.python-list at python.org...
> I'm trying to process OpenStep plist files in Python.  I have a parser
> which works, but only for strict ASCII.  However plist files may contain
> accented characters - equivalent to ISO-8859-2 (I believe).  For example
> I read in the line:
>
>>>> handle = open('file.txt', 'rb')
>>>> data = handle.read()
>>>> handle.close()
>>>> data
> '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
> NSFileName;\n'
>
> What is the correct way to re-encode this data into UTF-8 so I can use
> unicode strings, and then write the output back to ISO8859-?
>
> I can read the file using codecs as ISO8859-2, but it still doesn't seem
> correct.
>
>>>> handle = codecs.open('file.txt', 'rb', encoding='iso8859-2')
>>>> data = handle.read()
>>>> handle.close()
>>>> data
> u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
> NSFileName;\n'
>
> 




From ldo at geek-central.gen.new_zealand  Fri May 14 22:30:55 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 14:30:55 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Paul Boddie wrote:

> If you think the mobile telephony vendors are a bunch of fluffy bunny
> rabbits playing with each other in sugary meadows of niceness, I don't
> want to be present when someone directly and finally disabuses you of
> this belief.

The rise to popularity of Free Software had nothing to do with meadows full 
of mobile bunny-meat, and everything to do with the hard realities of the 
marketplace. Vendors discovered that they could make hardware running a 
Linux kernel do more things than it could with proprietary alternatives. In 
the beginning they derided the GPL as ?business-unfriendly?, until they 
grudgingly accepted that, just as it prevented them from freeloading off 
their competitors, it stopped those same competitors from freeloading off 
them. The network effects translated into real profits.

> It's all about people selling stuff to "consumers" over
> and over again, preferably with the "consumers" rarely if ever being
> able to opt-out and do things their own way.

Interesting you should mention that. That is exactly how mobile phone 
networks have been operated right up until now. And Apple?s business model 
has fitted very well into that too, as witness the success of the iPhone.

But Google?s Android could represent a shift in that model. Yes, it does 
seem to be locked down in its way, but given that most of the source code is 
available, that hardly seems watertight. The phone networks may see it as 
just another phone platform that the plebs are happy to shell out their 
hard-earned for, but I think it could ultimately lead to a loss of their 
proprietary control.


From pmaupin at gmail.com  Fri May 14 22:31:21 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:31:21 -0700 (PDT)
Subject: Picking a license
References:  
	
	<155f1683-9bfd-4a83-b63f-7fb0fc2f51c5@g21g2000yqk.googlegroups.com>
	
	<72888d2c-4b1a-4b08-a3aa-f4021d2ed646@e2g2000yqn.googlegroups.com>
	
	<84a26d03-03b3-47d9-a1f9-107470b87c75@k2g2000yqe.googlegroups.com>
	
Message-ID: 

On May 14, 8:57?pm, Lawrence D'Oliveiro  wrote:
> In message <84a26d03-03b3-47d9-
>
> a1f9-107470b87... at k2g2000yqe.googlegroups.com>, Patrick Maupin wrote:
> > I also firmly believe, as I have stated before, that the GPL is a much
> > more commercial license. ?If you want to make money off something,
> > then, no doubt, GPL keeps your competitors from being able to take
> > what you wrote and redistribute it as closed source. ?But, frankly I
> > view that as more of a business issue than a moral issue.
>
> Nevertheless, it?s probably a big factor in why the GPL has become the
> single most popular open-source licence.

Possibly.  I think a bigger factor is that the GPL is *designed* to
win license competitions.  If you view the license as part of the DNA
of a piece of software, then whenever two packages "breed" (are
combined) the resultant package will always have the GPL if either of
the source packages did.  In attempting to draw a biological parallel,
many have equated the GPL to a virus, but this analogy fails
miserably.  The "selfish gene" analogy has much to recommend it,
however:

http://en.wikipedia.org/wiki/The_Selfish_Gene#.22Selfish.22_genes

It's an interesting exercise to extend the analogy to show how the GPL
gene mutated in a way to allow it to mate with even *more* licenses
(and always come out on top).  So now there are two incompatible
selfish gene FOSS licenses in the ecosystem.  The license genes always
propagate whenever the host software mates, but in order to have that
genetic advantage, they avoid allowing their host software to mate
whenever they couldn't be the dominant license gene of the resultant
package.  One side effect of this is that the two major GPL variants
are unable to mate with each other.

Regards,
Pat


From steve at REMOVE-THIS-cybersource.com.au  Fri May 14 22:32:24 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 02:32:24 GMT
Subject: Picking a license
References: 
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com>
	
	<4bece8de$0$8761$c3e8da3@news.astraweb.com>
	<79811fa0-f8bb-4ec8-acc3-a4a1727a8e78@k42g2000yqb.googlegroups.com>
Message-ID: <4bee07b7$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 08:04:53 -0700, Patrick Maupin wrote:

> On May 14, 1:08?am, Steven D'Aprano  cybersource.com.au> wrote:
>> On Thu, 13 May 2010 19:10:09 -0700, Patrick Maupin wrote:
>> > The broken window fallacy is about labor that could have been spent
>> > elsewhere if someone else had done something differently. ?The only
>> > time that comes into play in my programming life is when I have to
>> > recode something that is nominally available under the GPL, so I'm
>> > not sure this is really making the point you think it is.
>>
>> You've never had to recode something because it was nominally available
>> under a proprietary licence that you (or your client) was unwilling to
>> use? Lucky you!
> 
> Don't be silly.  That's why I started writing open source software in
> the first place.  But if I start writing stuff to put in the commons
> with strings removed, why would I bother with a license that just adds
> some strings back?

To maximise the likelihood of it staying in the commons, of course.


>> The GPL ensures that once software has entered the commons (and
>> therefore available for all), it can never be removed from the commons.
> 
> No it doesn't.  It just insures that if people actually *distribute* the
> software to others, they have to distribute the source.  In any case,
> for software to remain in the commons, it has to be available where
> people can get to it.  Somebody has to care enough to maintain a
> repository, or it has to be good enough for people to distribute.

The reality is that most software never gets very far. There are millions 
of packages and libraries and applications which have few than a dozen 
users, thousands with a few hundred, and only one Microsoft Windows. 
Since web sites shut down and people lose interest, move on or die, 
software can disappear. This is a fact of life, and if you're looking for 
any guarantees, neither the GPL nor MIT-style licence will give you one.

But consider the case of Ed Keith, who posted some Boost-licenced 
software to the commons. (See his message in this thread, about 30 
minutes before yours.) The website he posted it to has shut down and he 
has lost his original code.

Obviously no licence can guarantee that people will want to use your 
software. Unpopular software will remain unpopular no matter what licence 
you use. But it is precisely the viral nature of the GPL that means that, 
*if* your software is useful enough for people to want to distribute it, 
it will remain in the commons even if you, the original author, are hit 
by a bus, your web server crashes, and you lose the original sources.

Under a MIT-style licence, it is possible for you to put a work into the 
commons, somebody else to copy it and distribute it as a proprietary 
work, then the original to disappear. For all we know, Ed's software has 
made it into a thousand different proprietary applications. Nevertheless, 
it has been lost from the commons, at least until such time as he 
recreates it.

Under the GPL, of course work can be lost from the commons if nobody 
distributes it and the original is lost. But the viral nature is designed 
so that *if* the software propagates legally, it remains in the commons 
and not out of it. This is different from MIT-style licences, which are 
indifferent to whether the software propagates in the commons or not, and 
proprietary licences, which typically prohibit it.


[...]
>> In practice, I believe most MIT-licenced code never even makes it into
>> the commons in the first place.
> 
> Interesting assertion.

I think it is a safe one. So far in the discussion, you and Ed (and 
possibly others, I may have forgotten) have repeatedly declared that you 
use the MIT licence for work you write for clients. This implies two 
obvious business models:

(1) You write open source software, put it on the Internet, and wait for 
the donations to come flooding in.

(2) Clients pay you to write software for them, which you then use a non-
GPL open source licence so that they don't need to release the source 
code if/when they distribute it further.

Given that you're able to pay for an Internet connection, chances are 
that your model is closer to #2. This implies that most of the software 
you write is bespoke software for clients, which means they're probably 
not distributing it as open source, simply because most software is still 
proprietary.



>> I'm willing to predict that the majority of code you've written for
>> paying customers (as opposed to specifically for open source projects)
>> has disappeared into their code base, never to be seen by anyone
>> outside of the company. Am I right?
> 
> That's true, but what on earth does that have to do with the MIT
> license?


The motive behind the GPL is to maximise the amount of code in the 
commons. The motive behind the MIT is to maximise the convenience, 
regardless of whether people keep your code in the commons or not. Unless 
people understand that the *motives* behind the models are different, all 
this talk of "freedoms" is just talking at cross-purposes. To those who 
want to maximise code in the commons, allowing people to take code out of 
the commons isn't a desirable freedom at all; and to those who want to 
maximise convenience, obliging people to distribute source code isn't 
desirable either.


It's strictly irrelevant to this discussion, but I'm curious why you 
choose to licence your work to your clients rather than just working for 
hire and assigning copyright to them.



-- 
Steven


From pmaupin at gmail.com  Fri May 14 22:36:13 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:36:13 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: 

On May 14, 9:21?pm, Lawrence D'Oliveiro  wrote:
> In message , Ed Keith
> wrote:
>
> > I just refuse to use [the GPL] in any code for a client, because I
> > do not want to require someone who does not know source code from Morse
> > code code to figure out what they need to do to avoid violating the
> > license.
>
> Why don?t you just put the source code on the same disc you send them, and
> tell them to pass copies of the entire disc to anyone they want?

What you would really have to tell them is "don't pass along the
program *unless* you copy the whole disk."  That's no longer a
courtesy -- that's a mandate.  By not using the GPL, Ed avoids having
to mandate to his customer how to treat the software he has delivered
to them.

Regards,
Pat


From steve at REMOVE-THIS-cybersource.com.au  Fri May 14 22:37:46 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 02:37:46 GMT
Subject: Picking a license
References: 
Message-ID: <4bee08f9$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 06:42:31 -0700, Ed Keith wrote:

> I am not a lawyer, but as I understand the LGPL, If I give someone
> something that used any LGPLed code I must give them the ability to
> relink it with any future releases of the LGPLed code. I think that
> means that I need to give them a linker and teach them how to use it,
> and I do not want to go there.

Surely you're joking? 

Does this mean that if they lose their hands in an accident, you have to 
come sit at their computer and do their typing?

The LGPL and GPL don't grant people "the ability" to do anything, since 
that's not within our power to grant. Some people don't want to, or 
can't, program, or don't have time. It's not like the LGPL is the bite of 
a radioactive spider that can grant superpowers. It is a licence which 
grants *permissions*.

In that regard, that's absolutely no different to the MIT licence, or 
proprietary software licences, which also deal in permissions (and 
restrictions). If I go to my local computer retailer and buy a copy of 
Windows, Microsoft doesn't grant me the ability to run the software. If I 
say "I don't actually have a computer, and the electricity has been shut 
off, so you have to pay to have the power turned back on and give me a 
computer", you won't get anywhere. The licence permits you to run one 
copy of Windows on one machine. Everything else is up to you.


-- 
Steven


From jackie.space at gmail.com  Fri May 14 22:45:06 2010
From: jackie.space at gmail.com (Jackie Lee)
Date: Sat, 15 May 2010 09:45:06 +0700
Subject: write a 20GB file
In-Reply-To: <4BED6715.1000106@v.loewis.de>
References: 
	<4BED2E45.6060301@ieee.org>
	 
	<4BED6715.1000106@v.loewis.de>
Message-ID: 

Thanks to y'all. I should have be more careful reading the documentation.

Cheers

On Fri, May 14, 2010 at 10:07 PM, Martin v. Loewis  wrote:
>> The code works fine. I just don't know how f.write works. It says that
>> file.write won't write the file until file.close or file.flush.
>
> You are misinterpreting the documentation. It certainly won't keep the
> entire file in memory. Instead, it has a fixed-size buffer (something
> like 8kiB or 32kiB) in which it writes and which it flushes when that
> buffer is full.
>
> The comment about flush and close merely refers to the problem that some
> data may still be in the buffer at any point in time, unless you just
> called close or flush.
>
> HTH,
> Martin
>



-- 
Jackie


From e_d_k at yahoo.com  Fri May 14 22:47:36 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 19:47:36 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <286192.2146.qm@web58708.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 9:58 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > Yes, under the GPL every one has one set of freedoms,
> under the MIT or
> > Boost license every one has more freedoms. Under other
> licenses they have
> > fewer freedoms.
> 
> But what about the ?freedom? to take away other
> people?s freedom? Is that 
> really ?freedom??
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Yes.

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Fri May 14 22:55:39 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 19:55:39 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <509872.33107.qm@web58703.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 10:07 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > That is one good reason for choosing to use the GPL,
> instead of a less
> > restrictive license. You can license it, for a fee, to
> someone who wants
> > to use it in some way that is not allowed under the
> GPL.
> 
> Replace ?GPL? with ?? and your
> statement is no less (or more) 
> true.
> 
> Funny how a lot of the arguments people keep trying to put
> forward about the 
> GPL really have nothing to do with the GPL.
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

I can not imagine anyone being stupid enough to pay me for rights to use code I had already published under the Boost License, which grants then the rights to do anything they want with it without paying me anything.

  -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From pmaupin at gmail.com  Fri May 14 22:55:54 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:55:54 -0700 (PDT)
Subject: Picking a license
References: 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com> 
	 
	<4bece8de$0$8761$c3e8da3@news.astraweb.com>
	<79811fa0-f8bb-4ec8-acc3-a4a1727a8e78@k42g2000yqb.googlegroups.com>
	<4bee07b7$0$8761$c3e8da3@news.astraweb.com>
Message-ID: 

On May 14, 9:32?pm, Steven D'Aprano  wrote:
> > Don't be silly. ?That's why I started writing open source software in
> > the first place. ?But if I start writing stuff to put in the commons
> > with strings removed, why would I bother with a license that just adds
> > some strings back?
>
> To maximise the likelihood of it staying in the commons, of course.

Well, it's your opinion that it would do that, and you have some
reasonably good reasons for that opinion, but I don't personally buy
into all of them.

[...]

> Obviously no licence can guarantee that people will want to use your
> software. Unpopular software will remain unpopular no matter what licence
> you use. But it is precisely the viral nature of the GPL that means that,
> *if* your software is useful enough for people to want to distribute it,
> it will remain in the commons even if you, the original author, are hit
> by a bus, your web server crashes, and you lose the original sources.

Sure, there's an additional guarantee.  But I don't believe there is a
real distinction.  I believe, for example, that all the major Linux
distributions don't try to save bandwidth or disk space by
discriminating against non-GPL packages.  For example, the Ubuntu
policy clearly states that to be in "main" rather than "restricted" a
package "must include source code."

> Under the GPL, of course work can be lost from the commons if nobody
> distributes it and the original is lost. But the viral nature is designed
> so that *if* the software propagates legally, it remains in the commons
> and not out of it. This is different from MIT-style licences, which are
> indifferent to whether the software propagates in the commons or not, and
> proprietary licences, which typically prohibit it.

While that is a theoretical difference, I don't believe it is a
practical one.  I don't download all the source for my Linux distro,
but they make all the source available.

> >> In practice, I believe most MIT-licenced code never even makes it into
> >> the commons in the first place.
>
> > Interesting assertion.
>
> I think it is a safe one. So far in the discussion, you and Ed (and
> possibly others, I may have forgotten) have repeatedly declared that you
> use the MIT licence for work you write for clients.

I think there is a serious misunderstanding there.  For me, there are
usually 3 types of licenses involved:

1) proprietary license or work-for-hire agreement for the customer's
secret sauce
2) Stuff that the author has put under a permissive license before, or
gets the customer to agree is not part of the secret sauce, and the
customer agrees to allow the author to put under a permissive license
after he writes it
3) Stuff that somebody else wrote under a permissive license

For most of my career, I've been an employee with a work-for-hire
clause, so pretty much all my writing falls under (1) unless I can
make a compelling argument for (2), which is finally starting to
happen a bit more.

> This implies two
> obvious business models:
>
> (1) You write open source software, put it on the Internet, and wait for
> the donations to come flooding in.
>
> (2) Clients pay you to write software for them, which you then use a non-
> GPL open source licence so that they don't need to release the source
> code if/when they distribute it further.

The bulk of the code is probably (3) Customer dictates the license.

[Snipped a bunch of stuff predicated on a misunderstanding of the way
things work for me]

> It's strictly irrelevant to this discussion, but I'm curious why you
> choose to licence your work to your clients rather than just working for
> hire and assigning copyright to them.

In the past, work-for-hire was practically the rule (during the times
I've been an employee).  I've been trying to release open stuff from
the workplace from over a decade with little traction, but it's
finally happening a bit.  There are multiple good reasons to open-
source, including the hope for coopetition, and the building of a
resume.  Given that other people who might cooperate with me on an
open source project are often similarly situated (working for
proprietary employers who wouldn't necessarily want to worry about the
GPL), using a permissive license makes great sense.

Regards,
Pat


From pmaupin at gmail.com  Fri May 14 22:58:40 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 19:58:40 -0700 (PDT)
Subject: Picking a license
References:  
	
Message-ID: <882f0f61-0139-4c13-bb2c-94a03b86f8d4@k31g2000vbu.googlegroups.com>

On May 14, 8:58?pm, Lawrence D'Oliveiro  wrote:
> In message , Ed Keith
> wrote:
>
> > Yes, under the GPL every one has one set of freedoms, under the MIT or
> > Boost license every one has more freedoms. Under other licenses they have
> > fewer freedoms.
>
> But what about the ?freedom? to take away other people?s freedom? Is that
> really ?freedom??

Only if they love or fear you enough to not try to overthrow you.
Otherwise, you have to be always on your guard.  It's still probably a
pretty good life.


From steve at REMOVE-THIS-cybersource.com.au  Fri May 14 22:59:00 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 02:59:00 GMT
Subject: Picking a license
References: 
Message-ID: <4bee0df4$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 06:39:05 -0700, Ed Keith wrote:

> Yes, under the GPL every one has one set of freedoms, under the MIT or
> Boost license every one has more freedoms. Under other licenses they
> have fewer freedoms.

I think this talk about freedoms is dangerously incomplete, and is 
confusing the issue rather than shedding more light. Both licences grant 
the same positive freedoms (freedom to do something). MIT-style licences 
grant permission to:

* make copies of the work;
* make derivative works based on the work; and
* distribute those derivative works to others.

The GPL grants precisely the same three rights. There is no difference in 
the rights granted.

The MIT licence imposes an obligation on the licencee:

* you must include a copy of the licence and copyright notice with the 
work and/or any derivative works.


The GPL adds a further obligation:

* any derivative works must also be licenced under the GPL.


If we want to talk about "freedoms", rather than rights and obligations, 
we need to distinguish between positive freedoms (freedom to do 
something) and negative freedoms (freedoms from something) and not just 
blithely mix them up.


-- 
Steven


From pmaupin at gmail.com  Fri May 14 23:00:40 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 20:00:40 -0700 (PDT)
Subject: Picking a license
References: 
	
Message-ID: <65b24889-3f55-4802-b7ea-dac471714bd6@d3g2000vbr.googlegroups.com>

On May 14, 9:17?pm, Lawrence D'Oliveiro  wrote:
> In message
> , Patrick
>
> Maupin wrote:
> > After all, lots of software ideas proved their worth in proprietary
> > systems, and then were later cloned by FOSS developers.
>
> And vice versa. Everybody, whether working in closed or open environments,
> builds on the work of everybody else. Rsync pioneered the idea of doing
> transfers of incremental changes to a large file across a network without
> being able to have the two versions of the file on the same machine to do a
> direct side-by-side comparison; Microsoft copied the idea in more recent
> versions of its server software. Andrew Tridgell could easily have patented
> his idea, but he chose not to.
>
> Apple pioneered the idea of using 3D graphics hardware to do window
> compositing on the desktop; the Compiz folks went on to figure out how to do
> this efficiently. Microsoft also copied the idea, but forgot the
> ?efficiently? part.
>
> Free Software also benefits from networking effects that are not available
> to proprietary developers. The resources available to proprietary developers
> are proportional to the size of the company they work for; typically they do
> not share software with competitors. Whereas the Free Software community is
> like one huge company in this regard, available to freely pass ideas and
> code back and forth. This has led to the creation of ideas that proprietary
> companies simply cannot match.

Well said.

Pat


From e_d_k at yahoo.com  Fri May 14 23:08:33 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Fri, 14 May 2010 20:08:33 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <93d67bd9-6721-4759-a3de-412b95b29a93@c11g2000vbe.googlegroups.com>
Message-ID: <226966.24642.qm@web58705.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Paul Boddie  wrote:

> From: Paul Boddie 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 8:12 PM
> On 14 Mai, 21:18, Ed Keith 
> wrote:
> >
> > The GPL is fine when all parties concern understand
> what source code is
> > and what to do with it. But when you add people like
> my father to the loop
> > if gets very ugly very fast.
> 
> Sure, and when I'm not otherwise being accused of pushing
> one
> apparently rather unpopular man's agenda, I am interested
> in knowing
> what the best practices should be and how they can be
> followed more
> widely.
> 
> Although Bill Gates once apparently claimed that no-one
> needs the
> source code for their word processor or office suite, there
> are still
> benefits in people like your father having access to the
> sources, even
> if this obviously means that he isn't going to recompile it
> himself:
> he can get others to fix things, particularly if his
> favourite version
> is no longer widely supported; if you were from a part of
> the planet
> where you were comfortable with a widely-spoken "global"
> language but
> your father could only converse in a less widely-spoken
> "minority"
> language not generally supported by such software, someone
> (perhaps
> you) could undertake the task of translating that
> software.
> 
> Whether or not one is comfortable with copyleft-style
> licences, there
> clearly is a benefit in providing access to software
> governed by those
> licences. Being able to do so responsibly is obviously a
> prerequisite
> to feeling comfortable about it.
> 
> Paul
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

But if I license my software with a less restrictive license, like MIT, Boost or Apache, programmers can access the source code, and people like my father can give the executable to their friends without violating the law. IMHO that is better for everybody.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From aahz at pythoncraft.com  Fri May 14 23:55:14 2010
From: aahz at pythoncraft.com (Aahz)
Date: 14 May 2010 20:55:14 -0700
Subject: Picking a license
References: 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	
	
Message-ID: 

In article ,
Paul Boddie   wrote:
>On 14 Mai, 03:56, a... at pythoncraft.com (Aahz) wrote:
>>
>> IMO this only makes sense if one agrees that people should not be allowed
>> to sell software for money.  Absent that agreement, your argument about
>> freedom seems rather limited.
>
>You'll have to explain this to me because I don't quite follow your
>assertion. You can sell copyleft-licensed software, although I accept
>that you can't set an arbitrarily high price on the sources for
>someone who has already acquired a binary distribution.

You can't really sell Open Source software in any practical way; someone
will always undercut you once it's out in the wild.  You can only sell
support for the software, which is entirely different.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From aahz at pythoncraft.com  Sat May 15 00:00:53 2010
From: aahz at pythoncraft.com (Aahz)
Date: 14 May 2010 21:00:53 -0700
Subject: Picking a license
References: 
	<93d67bd9-6721-4759-a3de-412b95b29a93@c11g2000vbe.googlegroups.com>
Message-ID: 

In article <93d67bd9-6721-4759-a3de-412b95b29a93 at c11g2000vbe.googlegroups.com>,
Paul Boddie   wrote:
>
>Whether or not one is comfortable with copyleft-style licences, there
>clearly is a benefit in providing access to software governed by those
>licences. 

...and this newsgroup surely is evidence that there is benefit to Open
Source software that isn't copyleft.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From steve at REMOVE-THIS-cybersource.com.au  Sat May 15 00:19:33 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 04:19:33 GMT
Subject: Picking a license
References: 
Message-ID: <4bee20d5$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 07:10:50 -0700, Ed Keith wrote:

> But if my client give someone else a copy of the binary I gave them,
> they are now in violation. I do not want to put my client in this
> position.

If your client is distributing software without reading and obeying the 
licence terms, then they are either idiots, or unethical, or possibly 
both.

If you want to make life easier on them by reducing the consequences of 
such foolish and/or unethical behaviour, that of course is your right. 
There are good reasons for doing so, and equally good reasons for not. 
It's also their right to ask you to assign copyright to them, or to 
licence the work using the MIT licence (or similar), or to ask for an 
exclusive licence. Or even to ask you to sign a "no compete" agreement 
which prevents you from ever writing code again. It's your choice whether 
to say Yay or Nay, and if you agree, how much you will charge for it.


> When using the GPL or LGPL you can do anything you want as long as you
> do not let anyone else use your work, but if you let someone else have a
> copy of you work you are putting them in a position where that can
> easily/inadvertently violate the law. I do not want to put clients in
> legal jeopardy, so I do not use GPL, or LGPLed code.

You're not putting them in legal jeopardy, they are. It is their decision 
whether or not to violate the licence.


-- 
Steven


From pmaupin at gmail.com  Sat May 15 00:50:48 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 21:50:48 -0700 (PDT)
Subject: Picking a license
References:  
	<4bee0df4$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <7bfa5457-027d-4ee1-a54f-3c0baba45a55@e21g2000vbl.googlegroups.com>

On May 14, 9:59?pm, Steven D'Aprano  wrote:
> I think this talk about freedoms is dangerously incomplete, and is
> confusing the issue rather than shedding more light. Both licences grant
> the same positive freedoms (freedom to do something). MIT-style licences
> grant permission to:
>
> * make copies of the work;
> * make derivative works based on the work; and
> * distribute those derivative works to others.
>
> The GPL grants precisely the same three rights. There is no difference in
> the rights granted.
>
> The MIT licence imposes an obligation on the licencee:
>
> * you must include a copy of the licence and copyright notice with the
> work and/or any derivative works.
>
> The GPL adds a further obligation:
>
> * any derivative works must also be licenced under the GPL.
>
> If we want to talk about "freedoms", rather than rights and obligations,
> we need to distinguish between positive freedoms (freedom to do
> something) and negative freedoms (freedoms from something) and not just
> blithely mix them up.

That is well-put, and of course the whole purpose of the extra
obligation or "negative freedom" is to ensure the rights or "positive
freedoms" of downstream recipients of the software.

In theoretical terms, everybody who redistributes software under the
GPL has the same obligations imposed, but as I have shown in other
posts, this obligation is unevenly enforced, and probably by design.

In practical terms, the additional obligations of the GPL license are
imposed on those who distribute huge quantities of software (Ubuntu,
Red Hat) and those who distribute derivative works (by combining other
software with the GPLed software).

It is questionable whether distributors such as Ubuntu and Red Hat
truly see this as an obligation; certainly they also distribute source
for permissively-licensed programs, and certainly other parties
happily provide source for fully BSD-licensed distributions for free.
Nonetheless, some of the smaller derivative distributors undoubtedly
wind up paying for more bandwidth than they would like.

So, the bulk of the additional obligations fall squarely on people who
distribute derivative works.  This is by design.  It is what keeps the
Microsofts of this world from appropriating GPLed software.  As I have
said many times, for people who worry about this stuff, the GPL is
absolutely the right license, because any license that gets them
writing free software rather than worrying about freeloaders is a
great license.

But for someone (let's call him "Fred") who distributes derivative
works to a customer, the additional obligation you mention for the GPL
actually has 4 separate components:

1) Full source for the original program must be provided
2) Fred's own additional source code must also be provided
3) Fred can't link to any proprietary software at all.
4) Fred must be sure that his customer is OK with the resultant work
product being under the GPL.

Now, if Fred was going to provide source anyway, the only possible
sticking points are really #3 and #4.  But those can be very sticky.
Let's start with #3.

If the proprietary software that is being linked to is, for example,
Oracle, Fred can't legally use GPLed software.  Well, actually he
might be able to, if he writes the software as a work-for-hire (as a
contractor for the customer), because then there might not be a true
distribution of the final package.  So that might actually reduce the
amount of free software in the world -- if Fred writes it as work for
hire, he can't distribute it to anybody else, and the customer is not
about to make a distribution of any of the software, so this is a case
where, if Fred can find and leverage permissively licensed software
instead of GPLed software, the amount of free software available in
the world can actually go up.

Now for #4, where Fred just has to communicate with and educate the
customer.  Even if the customer is just going to use the software in-
house with no plans to ever distribute it, the act of merely *asking*
a customer if it is OK to use GPLed software in the solution can, in
some cases, mean the difference between being able to sign a contract
and get started right away, or needing a review by the lawyers that
won't conclude for a month and then being told "no" or, even worse,
that "business conditions have changed."

Obviously, if there were a GPLed solution already available that was
the best tool for the job, it might be a good tactic for Fred (if he
weren't too worried about the interminable lawyer review) to explain
that it will cost $X for a GPL solution, and $X+Y for a non-GPL
solution.  Or even a good tactic to precede that with a simple
question of if the customer ever uses GPL software, and if they
already do, do they have a policy.  (But that has to be asked in such
a way as to not provide an original research question for the lawyer.)

But if, starting out, there is no compelling GPLed solution, then
there is no good reason to even ask things like that of the customer
-- better to just start coding.  And if the climate is right to ask if
the customer minds if Fred reuses and shares the code, there is a good
chance that Fred will use a permissive license on any generic code, if
he wants to enable others like himself.

So, there are good reasons for both kinds of licenses, which I think
everybody on the pro-permissive side has been saying all along.  Of
course, "force" is a more inflammatory word that "obligation" in some
contexts, and that has been used in what I would admit on my part is a
knee-jerk reaction to my belief that "free" and "freedom" are more
inflammatory words than "rights" in the same contexts.

Regards,
Pat


From ben+python at benfinney.id.au  Sat May 15 00:57:35 2010
From: ben+python at benfinney.id.au (Ben Finney)
Date: Sat, 15 May 2010 14:57:35 +1000
Subject: Picking a license
References: 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	
	
	
Message-ID: <87r5ldbw3k.fsf@benfinney.id.au>

aahz at pythoncraft.com (Aahz) writes:

> You can't really sell Open Source software in any practical way;
> someone will always undercut you once it's out in the wild. You can
> only sell support for the software, which is entirely different.

Not at all. I've been selling all the software I write for clients for
the past ten years, and it's all free software. It's been very practical
for me and those I've worked with.

You can't sell free software like selling loaves of bread, but that's a
much more limited case and a far cry from your claim. Selling free
software is quite practical and a good way to fund development of
software that otherwise wouldn't be written as free software.

-- 
 \     ?Why am I an atheist? I ask you: Why is anybody not an atheist? |
  `\      Everyone starts out being an atheist.? ?Andy Rooney, _Boston |
_o__)                                                Globe_ 1982-05-30 |
Ben Finney


From stefan_ml at behnel.de  Sat May 15 01:17:47 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 15 May 2010 07:17:47 +0200
Subject: Picking a license
In-Reply-To: <87k4rgfutu.fsf@benfinney.id.au>
References: 		<4BE05D75.7030301@msn.com>
	 <87k4rgfutu.fsf@benfinney.id.au>
Message-ID: 

aahz at pythoncraft.com (Aahz) writes:
> Which license you use depends partly on your political philosophy.

Did they close down debian-legal, or why is this thread growing so long?

Ah, I forgot - Friday ...

Stefan



From pmaupin at gmail.com  Sat May 15 01:22:39 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 22:22:39 -0700 (PDT)
Subject: Picking a license
References:  
	<4bee20d5$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <8c45dd27-174d-495c-bf64-814f59fc6622@k31g2000vbu.googlegroups.com>

On May 14, 11:19?pm, Steven D'Aprano  wrote:
> On Fri, 14 May 2010 07:10:50 -0700, Ed Keith wrote:
> > But if my client give someone else a copy of the binary I gave them,
> > they are now in violation. I do not want to put my client in this
> > position.
>
> If your client is distributing software without reading and obeying the
> licence terms, then they are either idiots, or unethical, or possibly
> both.

How about just "ignorant."  Maybe even "blissfully ignorant" as in,
you just used permissively-licensed software, and since you're not
Microsoft and they paid you a fair amount of money for the software
and you both agreed on a handshake or a back of the napkin contract
that you could both do whatever you wanted with the software (except
stripping copyright notices), they go and do exactly that.

> If you want to make life easier on them by reducing the consequences of
> such foolish and/or unethical behaviour, that of course is your right.
> There are good reasons for doing so, and equally good reasons for not.

Well, for people who don't feel the imperative of the FSF's prime
directive, the only really good reason for "not" is if you found some
super-cool GPL-licensed software that will greatly reduce the cost of
the contract, *and* you can leverage some of the savings into your own
pocket.

> It's also their right to ask you to assign copyright to them, or to
> licence the work using the MIT licence (or similar), or to ask for an
> exclusive licence. Or even to ask you to sign a "no compete" agreement
> which prevents you from ever writing code again. It's your choice whether
> to say Yay or Nay, and if you agree, how much you will charge for it.

Sure, contracts can be made as simple or complex as the parties want.
In most cases, reuse of preexisting GPLed software certainly won't
simplify the negotiations, though.  In Texas, though, that particular
"no-compete" wouldn't fly.  I'll sign non-compete clauses like that in
the blink of an eye; it's the speciously more limited ones that you
have to watch out for because sometimes the courts will uphold at
least parts of those: http://www.texasnoncompetelaw.com/

> > When using the GPL or LGPL you can do anything you want as long as you
> > do not let anyone else use your work, but if you let someone else have a
> > copy of you work you are putting them in a position where that can
> > easily/inadvertently violate the law. I do not want to put clients in
> > legal jeopardy, so I do not use GPL, or LGPLed code.
>
> You're not putting them in legal jeopardy, they are. It is their decision
> whether or not to violate the licence.

Uh-huh.  If they're in legal jeopardy, you are too (at least in the
USA) because the first thing they are going to do is to cross-sue you
for failure to explain to them that you were using GPLed software.
Doesn't matter if it's not true.  Doesn't even matter if you have
signed contracts that prove it's not true.  It's still going to cost
you a pretty penny to get away from the lawsuit.

So, really, why go through all that unless it's going to save enough
on the contract to justify it?  Seriously, a software contract can be
less than half a page under some circumstances, and written so that
basically you and they can both do whatever you want, and neither is
going to sue the other.

Regards,
Pat


From steve at REMOVE-THIS-cybersource.com.au  Sat May 15 01:45:24 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 05:45:24 GMT
Subject: Picking a license
References: 
Message-ID: <4bee34f4$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 09:18:09 -0700, Ed Keith wrote:

> But if I release it with the Boost license, while technically I can
> release it with the GPL tomorrow, in practice everyone will use the
> previously released Boost licensed version.

That's a very interesting experiment to perform. Perhaps you should dual-
licence some library and see which gets more downloads and users?



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Sat May 15 01:50:57 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 05:50:57 GMT
Subject: Picking a license
References: 
	<7228bce1-5252-4b9e-a31f-691dc1ed34ce@b7g2000yqk.googlegroups.com>
	
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com>
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com>
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com>
Message-ID: <4bee3641$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 08:37:14 -0700, Patrick Maupin wrote:

> I don't actually
> recall any suits about violations of the MIT or Apache licenses.

The most obvious example was that the University of Berkley counter-sued 
Unix System Laboratories over USL's infringement of the BSD licence.

Admittedly this wasn't the MIT or Apache licence, and the circumstances 
were fairly special. It's a fairly safe bet that anyone who is 
distributing their software under such a licence is sending an implicit 
signal that they don't intend to sue. But it does demonstrate that MIT-
style licences aren't the same as public domain -- they do impose 
obligations on the recipient, even if those obligations are much lighter 
than those of the GPL.


-- 
Steven


From pmaupin at gmail.com  Sat May 15 01:56:37 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Fri, 14 May 2010 22:56:37 -0700 (PDT)
Subject: Picking a license
References: 
	
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com> 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<4bee3641$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <9eee39f5-fd58-4187-a3bb-4971382f5ec6@t15g2000vbo.googlegroups.com>

On May 15, 12:50?am, Steven D'Aprano  wrote:
> On Fri, 14 May 2010 08:37:14 -0700, Patrick Maupin wrote:

> The most obvious example was that the University of Berkley counter-sued
> Unix System Laboratories over USL's infringement of the BSD licence.

Well, I specifically excluded BSD for this reason.  But in any case,
I'd be willing to place a small wager that it's the *only* (rather
than merely the "most obvious") example you can find...

> Admittedly this wasn't the MIT or Apache licence, and the circumstances
> were fairly special. It's a fairly safe bet that anyone who is
> distributing their software under such a licence is sending an implicit
> signal that they don't intend to sue.

Right.

> But it does demonstrate that MIT-
> style licences aren't the same as public domain -- they do impose
> obligations on the recipient, even if those obligations are much lighter
> than those of the GPL.

And I certainly have never deliberately attempted to mislead on this
point.

Regards,
Pat


From pavlovevidence at gmail.com  Sat May 15 02:23:19 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 14 May 2010 23:23:19 -0700 (PDT)
Subject: an element from a set
References: <28560792.post@talk.nabble.com>
	
Message-ID: <213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>

On May 14, 9:39?am, Terry Reedy  wrote:
> On 5/14/2010 11:24 AM, gerardob wrote:
>
>
>
> > Hello, let S be a python set which is not empty
> > (http://docs.python.org/library/sets.html)
>
> > i would like to obtain one element (anyone, it doesn't matter which one) and
> > assign it to a variable.
>
> > How can i do this?
>
> Depends on whether or not you want the element removed from the set
>
> #3.1
> ?>>> s=set(range(10))
> ?>>> s
> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
> ?>>> x=next(iter(s))
> ?>>> x
> 0
> ?>>> s
> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
> ?>>> x = s.pop()
> ?>>> x
> 0
> ?>>> s
> {1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed
>
> The choice of 0 is an implementation artifact. It could have been any
> member.

Which brings up an interesting question: how do you get a random
element from a set?

random.choice(list(s))

is the most straightforward way and will work a lot of the time, but
how would you avoid creating the list?  I can't think of a way off
hand.


Carl Banks



From shashank.sunny.singh at gmail.com  Sat May 15 02:32:59 2010
From: shashank.sunny.singh at gmail.com (Shashank Singh)
Date: Sat, 15 May 2010 12:02:59 +0530
Subject: an element from a set
In-Reply-To: <213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
References: <28560792.post@talk.nabble.com>
	 
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
Message-ID: 

On Sat, May 15, 2010 at 11:53 AM, Carl Banks wrote:

> On May 14, 9:39 am, Terry Reedy  wrote:
> > On 5/14/2010 11:24 AM, gerardob wrote:
> >
> >
> >
> > > Hello, let S be a python set which is not empty
> > > (http://docs.python.org/library/sets.html)
> >
> > > i would like to obtain one element (anyone, it doesn't matter which
> one) and
> > > assign it to a variable.
> >
> > > How can i do this?
> >
> > Depends on whether or not you want the element removed from the set
> >
> > #3.1
> >  >>> s=set(range(10))
> >  >>> s
> > {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
> >  >>> x=next(iter(s))
> >  >>> x
> > 0
> >  >>> s
> > {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
> >  >>> x = s.pop()
> >  >>> x
> > 0
> >  >>> s
> > {1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed
> >
> > The choice of 0 is an implementation artifact. It could have been any
> > member.
>
> Which brings up an interesting question: how do you get a random
> element from a set?
>
> random.choice(list(s))
>
> is the most straightforward way and will work a lot of the time, but
> how would you avoid creating the list?  I can't think of a way off
> hand.
>
> How about random.sample(s, 1)[0]? Is it inefficient?

>
> Carl Banks
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regards
Shashank Singh
Senior Undergraduate, Department of Computer Science and Engineering
Indian Institute of Technology Bombay
shashank.sunny.singh at gmail.com
http://www.cse.iitb.ac.in/~shashanksingh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Sat May 15 02:34:42 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 15 May 2010 06:34:42 GMT
Subject: Picking a license
References: 
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
	<9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com>
	<548024fc-dd56-48b9-907d-3aa6a722b43c@l31g2000yqm.googlegroups.com>
	
	<6767a5ae-2aab-4532-8e18-8c445920624e@d3g2000vbr.googlegroups.com>
Message-ID: <4bee4081$0$8761$c3e8da3@news.astraweb.com>

On Fri, 14 May 2010 19:17:20 -0700, Patrick Maupin wrote:

> On May 14, 9:04?pm, Lawrence D'Oliveiro  central.gen.new_zealand> wrote:
>> In message <548024fc-
>> dd56-48b9-907d-3aa6a722b... at l31g2000yqm.googlegroups.com>, Patrick
>> Maupin wrote:
>>
>> > The confusion that some are showing in this thread about whether
>> > source must be distributed certainly helps to show that as well.
>>
>> What ?confusion?? The GPL requires that source must always be offered
>> in some form. Simple as that.
> 
> Right, but when I explained that that requirement also applies to Joe,
> who downloaded an ISO from Ubuntu and burned a CD and gave it away, no
> less than 3 people jumped in to "correct" me.

The confusion is over what form that offer may be, and what counts as 
distribution.

Your claim seems plausible, but whether it is correct or not is not so 
obvious. I would say that, given the lack of any lawsuits against 
individuals and Linux User Groups, the *intention* of the GPL is to allow 
individuals to act as a proxy between the end-user and the actual 
distributor (in this case, Ubuntu) without taking on the obligation to 
provide source code.

Looking at the FAQs, my comments in square brackets:

http://www.gnu.org/licenses/gpl-faq.html#WhatDoesWrittenOfferValid

    If you commercially distribute binaries not accompanied with 
    source code [e.g. as Canonical does with Ubuntu], the GPL says
    you must provide a written offer to distribute the source code 
    later. [This is available on their website.] When users non-
    commercially redistribute the binaries they received from you, 
    [e.g. I download the Ubuntu install DVD and make a copy for
    my friend] they must pass along a copy of this written offer. 
    [I am obliged to tell my friend they can get the Ubuntu written
    offer from Ubuntu's website, and pass it on directly if asked]
    This means that people who did not get the binaries directly 
    from you can still receive copies of the source code, along 
    with the written offer.

    The reason we require the offer to be valid for any third party 
    is so that people who receive the binaries indirectly in that way
    can order the source code from you. [In other words, if I give
    Fred a copy of Ubuntu, it is Canonical and not me who is responsible
    for providing the source code to Fred if he asks for it.]


Okay, it's not the licence itself, but the FAQ pretty much makes the 
intention clear. Merely handing over an Ubuntu DVD to a friend is not a 
violation of the GPL.



-- 
Steven


From prologic at shortcircuit.net.au  Sat May 15 02:40:46 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sat, 15 May 2010 16:40:46 +1000
Subject: an element from a set
In-Reply-To: <213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
References: <28560792.post@talk.nabble.com>
	 
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
Message-ID: 

On Sat, May 15, 2010 at 4:23 PM, Carl Banks  wrote:
> Which brings up an interesting question: how do you get a random
> element from a set?
>
> random.choice(list(s))
>
> is the most straightforward way and will work a lot of the time, but
> how would you avoid creating the list? ?I can't think of a way off
> hand.

random.choice(...) requires that the object passed to it supports "sequencing".

This means it must implement: __getitem__ (which a list does).

I don't think there is a way to retrieve a random element from a set without
first turning it into a sequence (list) unless the underlying data of
a set were exposed.

--James


From clp2 at rebertia.com  Sat May 15 02:52:38 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Fri, 14 May 2010 23:52:38 -0700
Subject: an element from a set
In-Reply-To: <213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
References: <28560792.post@talk.nabble.com>
	
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
Message-ID: 

On Fri, May 14, 2010 at 11:23 PM, Carl Banks  wrote:
> On May 14, 9:39?am, Terry Reedy  wrote:
>> On 5/14/2010 11:24 AM, gerardob wrote:
>> > Hello, let S be a python set which is not empty
>> > (http://docs.python.org/library/sets.html)
>>
>> > i would like to obtain one element (anyone, it doesn't matter which one) and
>> > assign it to a variable.
>>
>> > How can i do this?
>>
>> Depends on whether or not you want the element removed from the set
>>
>> #3.1
>> ?>>> s=set(range(10))
>> ?>>> s
>> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>> ?>>> x=next(iter(s))
>> ?>>> x
>> 0
>> ?>>> s
>> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
>> ?>>> x = s.pop()
>> ?>>> x
>> 0
>> ?>>> s
>> {1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed
>>
>> The choice of 0 is an implementation artifact. It could have been any
>> member.
>
> Which brings up an interesting question: how do you get a random
> element from a set?
>
> random.choice(list(s))
>
> is the most straightforward way and will work a lot of the time, but
> how would you avoid creating the list? ?I can't think of a way off
> hand.

def random_set_elem(s):
    iterator = iter(s)
    n = random.randint(0, len(s)-1)
    for i in xrange(n):
        next(iterator)
    return next(iterator)

Avoids creating the list, but it's still O(M). If you're gonna pick
multiple times from the same set, you're better off just converting it
to a list.

Cheers,
Chris
--
http://blog.rebertia.com


From pmaupin at gmail.com  Sat May 15 03:01:58 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 00:01:58 -0700 (PDT)
Subject: Picking a license
References:  
	
	<1c557d99-44d4-4287-be8b-08c31ae55027@q30g2000yqd.googlegroups.com>
	<9d9266a3-9f9b-4bdc-8c07-865cf7b70892@o14g2000yqb.googlegroups.com> 
	<548024fc-dd56-48b9-907d-3aa6a722b43c@l31g2000yqm.googlegroups.com> 
	
	<6767a5ae-2aab-4532-8e18-8c445920624e@d3g2000vbr.googlegroups.com>
	<4bee4081$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <2bb90c13-8f61-444d-8715-673da14bdad3@v18g2000vbc.googlegroups.com>

On May 15, 1:34?am, Steven D'Aprano  wrote:
> On Fri, 14 May 2010 19:17:20 -0700, Patrick Maupin wrote:
> > On May 14, 9:04?pm, Lawrence D'Oliveiro  > central.gen.new_zealand> wrote:
> >> In message <548024fc-
> >> dd56-48b9-907d-3aa6a722b... at l31g2000yqm.googlegroups.com>, Patrick
> >> Maupin wrote:
>
> >> > The confusion that some are showing in this thread about whether
> >> > source must be distributed certainly helps to show that as well.
>
> >> What ?confusion?? The GPL requires that source must always be offered
> >> in some form. Simple as that.
>
> > Right, but when I explained that that requirement also applies to Joe,
> > who downloaded an ISO from Ubuntu and burned a CD and gave it away, no
> > less than 3 people jumped in to "correct" me.
>
> The confusion is over what form that offer may be, and what counts as
> distribution.
>
> Your claim seems plausible, but whether it is correct or not is not so
> obvious.

Exactly.  And when people say it's obviously incorrect, they're
obviously incorrect, because if it were obvious, it would have been
answered correctly by now :-)

> I would say that, given the lack of any lawsuits against
> individuals and Linux User Groups, the *intention* of the GPL is to allow
> individuals to act as a proxy between the end-user and the actual
> distributor (in this case, Ubuntu) without taking on the obligation to
> provide source code.

Yes, and as I said, lawsuits against individuals would be bad for
business (as business is defined in the GPL world).

> Looking at the FAQs, my comments in square brackets:
>
> http://www.gnu.org/licenses/gpl-faq.html#WhatDoesWrittenOfferValid

Well, for one thing, that section is only *directly* relevant to GPL
v2.  For another thing, it is only directly relevant to Canonical's
obligations, not Joe's.

[Text snipped; part of d'Aprano interpretation left]

> ? ? [I am obliged to tell my friend they can get the Ubuntu written
> ? ? offer from Ubuntu's website, and pass it on directly if asked]

Sure, and that's *exactly* what I said isn't going to happen in a lot
of cases, because it takes a careful reading of the license and FAQ
for someone to realize that.  The download button at Ubuntu tells you
to make more copies (your "rights") without telling you about the
source code (your "obligations").  Which is perfectly legal, but
someone who isn't reading carefully could easily give a CD to a friend
without the offer of source.

> ? ? This means that people who did not get the binaries directly
> ? ? from you can still receive copies of the source code, along
> ? ? with the written offer.

More obligations on the part of Canonical;  note, however, that
Canonical's obligation to distribute source to a CD that you gave to a
friend may not even be long enough to cover 3 years after the time you
gave the CD to your friend.

> ? ? The reason we require the offer to be valid for any third party
> ? ? is so that people who receive the binaries indirectly in that way
> ? ? can order the source code from you. [In other words, if I give
> ? ? Fred a copy of Ubuntu, it is Canonical and not me who is responsible
> ? ? for providing the source code to Fred if he asks for it.]
>
> Okay, it's not the licence itself, but the FAQ pretty much makes the
> intention clear.

Yes, it does.  The FAQ part you quote is for Canonical and for v2.
The one for the user handing over the CD still says (for v3):

"I downloaded just the binary from the net. If I distribute copies, do
I have to get the source and distribute that too? Yes. The general
rule is, if you distribute binaries, you must distribute the complete
corresponding source code too. The exception for the case where you
received a written offer for source code is quite limited."

But, even if you fall under that limited exception, you *still* have
to make the written offer, and I stand by my assertion that even that
token act is not happening in lots of cases as we speak.

> Merely handing over an Ubuntu DVD to a friend is not a
> violation of the GPL.

... as long as you make the written offer.

Regards,
Pat


From contact at xavierho.com  Sat May 15 03:27:51 2010
From: contact at xavierho.com (Xavier Ho)
Date: Sat, 15 May 2010 17:27:51 +1000
Subject: help need to write a python spell checker
In-Reply-To: 
References: 
Message-ID: 

1) Welcome to Python-List!

2) Python-list doesn't like to do other people's homework.

3) What have you tried?

Cheers,
Xav

On Fri, May 14, 2010 at 6:19 PM, harry k  wrote:

> Write a spell checking tool that will identify all misspelled word in a
> text file using a provided dictionary.
>
>
> The program will accept either one or two command line parameters.
> 1.      The first command line parameter is the name of the text file that
> will be checked.
> 2.      The optional second command line parameter is the name of the
> dictionary file ? a file of words with one word per line.  The default
> dictionary file is ref.txt.
> The program will write out the misspelled words, one per line, in
> alphabetical order.
>
> Extend the spell checking tool so that as well as identifying all
> misspelled words,  the program will list the line numbers in the file where
> the incorrect spelling occurs.
>
> The program will write out the misspelled words (one per line, in
> alphabetical order), followed by a tab character, followed by the list of
> line numbers that word is misspelled in,in ascending order, on the same
> line, separated by a single space.
>
>
> Extend the spell-checking tool so that the program will also print out a
> list of possible correct spellings for the words.
>
> The program will write out the misspelled words (one per line, in
> alphabetic order), followed (on the same line) by a single space, followed
> by the list of line numbers in ascending order, each separated by a single
> space, followed by a single space, then the list of possible correct
> spellings, each separated by a single space.
>
> Find the alternate spellings by considering:
> a.      Words in the dictionary that are the same length but:
> a.      Have a pair of characters interchanged
> b.      Differ by one character from the misspelled word
> b.      Words that are one character longer or one character shorter, but
> otherwise match the misspelled word.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From prologic at shortcircuit.net.au  Sat May 15 03:30:09 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sat, 15 May 2010 17:30:09 +1000
Subject: help need to write a python spell checker
In-Reply-To: 
References: 
Message-ID: 

On Fri, May 14, 2010 at 6:19 PM, harry k  wrote:
> Write a spell checking tool that will identify all misspelled word in a text file using a provided dictionary.

Is this an assignment ? Sure looks like it!

I don't see a question anywhere.

--james


From lie.1296 at gmail.com  Sat May 15 03:33:16 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sat, 15 May 2010 17:33:16 +1000
Subject: Broken pipe
In-Reply-To: 
References: 
	
	 <4bec2a9a$1@dnews.tpgi.com.au>
	
Message-ID: <4bee4e98$1@dnews.tpgi.com.au>

On 05/15/10 11:56, Lawrence D'Oliveiro wrote:
> In message <4bec2a9a$1 at dnews.tpgi.com.au>, Lie Ryan wrote:
> 
>> On 05/13/10 22:41, Lawrence D'Oliveiro wrote:
>>> In message , Chris
>>> Rebert wrote:
>>>
>>>> Also, please don't use semicolons in your code. It's bad style.
>>>
>>> Wonder why they?re allowed, then.
>>
>> they're there for line continuation, e.g.:
>>
>> a = 40; foo(a)
>>
>> but in many cases, putting two statements in a single line reduces
>> readability so use the semicolons extremely conservatively. But the
>> worst is the abuse of semicolons for end-of-line markers.
> 
> So why are they allowed, then?

Convenience. I've sometimes, in the interactive interpreter, written
codes that looks like:

a = 0; ... other code ...

since I need to reset the variable 'a' every time 'other code' is run.
If there hasn't been the ;, then I'd have to press up, up, enter, up,
up, change, enter. Compare that to up, change, enter since I can "up"
two "lines" at once.

In the interactive interpreter these sort of conveniences is often useful.

Unless your "why are they allowed" is about why a blank continuation
(i.e. abusing ; as line ending) is allowed. In that case, I'd presume
it's just because conceptually:

foo();
bar

is just:

foo()

bar()


but probably you're right; maybe they should be strictly disallowed. But
it's too late for this kind of change, not until py4k.


From sumerc at gmail.com  Sat May 15 06:18:45 2010
From: sumerc at gmail.com (k3xji)
Date: Sat, 15 May 2010 03:18:45 -0700 (PDT)
Subject: yappi 0.51 released
Message-ID: <292fddf7-4cc4-4a2f-b10e-fc252fd47590@f14g2000vbn.googlegroups.com>

Hi all,

Yappi (Yet Another Python Profiler) 0.51 released. See the version
highlights:

    * OPTIMIZATION:Use per-pit cpc for better accuracy in different
timing_sample values. Now timing_sample is not linearly decreasing the
timing accuracy for most of the applications tested. We reduced the
runtime of the profiler from 3.2 secs to 0.7 by giving away ~%2 timing
accuracy. This means yappi can now run 4x-7x times faster than the
standart cProfile by increasing timing_sample values with very little
accuracy defect.
    * Python 2.6.5 gives import yappi Dll load failed error. This is
due to VC2008 compile. Unfortunately, we need to use VC Express Mingw
is not working because of MSVCR dll files on 2.6.5 on some machines.
    * Use snprintf for stat handling code. There may be some buffer
overflow situations. Use PyOS_snprintf for platform differences.
(Thanks to Dave Peticolas)
    * Format stat STRINGs from left, instead of right. (Thanks to Dave
Peticolas)
    * OPTIMIZATION:Move ctx calculation code to callback function.
Optimize call_XXX functions as much as possible.
    * Move timing calculation code from header to the C file.
    * MACRO defining code in setup.py is broken for some compilers,
use DEFINE_MACRO keyword.
    * OPTIMIZATION:Disable HASH table linked list swapping code, it is
not adapting to the profiler nature very well. Rollback to simple hash-
table-bucketing.

See below for more and download:
http://code.google.com/p/yappi/

Thanks,
twitter.com/sumercip


From lie.1296 at gmail.com  Sat May 15 06:30:31 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sat, 15 May 2010 20:30:31 +1000
Subject: Puzzled by code pages
In-Reply-To: 
References: 
Message-ID: <4bee7823$1@dnews.tpgi.com.au>

On 05/15/10 10:27, Adam Tauno Williams wrote:
> I'm trying to process OpenStep plist files in Python.  I have a parser
> which works, but only for strict ASCII.  However plist files may contain
> accented characters - equivalent to ISO-8859-2 (I believe).  For example
> I read in the line:
> 
>>>> handle = open('file.txt', 'rb')
>>>> data = handle.read()
>>>> handle.close()
>>>> data
> '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
> NSFileName;\n'

I presume you're using Python 2.x.

> What is the correct way to re-encode this data into UTF-8 so I can use
> unicode strings, and then write the output back to ISO8859-?
> 
> I can read the file using codecs as ISO8859-2, but it still doesn't seem
> correct.
> 
>>>> handle = codecs.open('file.txt', 'rb', encoding='iso8859-2')
>>>> data = handle.read()
>>>> handle.close()
>>>> data
> u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
> NSFileName;\n'

When printing in the interactive interpreter, python uses __repr__
representation by default. If you want to use __str__ representation use
"print data" (note, your terminal must support printing unicode
characters); either way, even though the string looks like '\u0102' when
printed on the terminal, the binary pattern inside the memory should
correctly represents the accented character.

f = codecs.open("in.txt", 'rb', encoding="iso8859-2")
f2 = codecs.open("out.txt", 'wb', encoding="utf-8")
s = f.read()
f2.write(s)
f.close()
f2.close()


From python.list at tim.thechases.com  Sat May 15 07:02:06 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Sat, 15 May 2010 06:02:06 -0500
Subject: help need to write a python spell checker
In-Reply-To: 
References: 
	
Message-ID: <4BEE7F2E.1020509@tim.thechases.com>

> 2) Python-list doesn't like to do other people's homework.


This could be fun... :)  For this problem, all you have to do is 
a big "if/elif/else" statement for every possible mis-spelling. 
If you want to get really fancy, you could put all the 
mis-spellings in a set() and then test the incoming word against 
the set for membership...For bonus points, you could use the 
anydbm module as a mapping from known-bad-spellings to the 
correct spelling so it can auto-correct for you...

Then you know if the word is mis-spelled.  The rest is pretty 
easy. ;-)

-tkc


(or maybe this only sounds amusing if you're sleep-deprived, up 
with your kid in the wee hours of the morning when you'd prefer 
to be snoozing)



From timoverbeek10 at gmail.com  Sat May 15 07:02:36 2010
From: timoverbeek10 at gmail.com (timo verbeek)
Date: Sat, 15 May 2010 04:02:36 -0700 (PDT)
Subject: Human word reader
Message-ID: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>

I'm planning to create a human word program
A human inputs a string
"Give me the weather for London please."
Then I will strip the string.
"weather for london"
Then I get the useful information.
what:"weather" where:"london"
After that I use the info.

I need help with getting the useful information how do I get the place
if I don't now how long the string is?


From contact at xavierho.com  Sat May 15 07:12:33 2010
From: contact at xavierho.com (Xavier Ho)
Date: Sat, 15 May 2010 21:12:33 +1000
Subject: Human word reader
In-Reply-To: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
Message-ID: 

On Sat, May 15, 2010 at 9:02 PM, timo verbeek wrote:

> I'm planning to create a human word program
>



>
> I need help with getting the useful information how do I get the place
> if I don't now how long the string is?
>
> Boy, that is a very hard problem. Are the inputs restricted to anything?
English only? Can the human user type in *anything*?

You need to have a very, very good set of heruistics and deterministic
functions to do that.

What have you got so far?

-

Otherwise,

"How do I get the position of a known word in a string if the length if
unknown?"

>>> input = 'Give me the weather for London please.'
>>> input.find('weather')
12

Cheers,
Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From contact at xavierho.com  Sat May 15 07:13:51 2010
From: contact at xavierho.com (Xavier Ho)
Date: Sat, 15 May 2010 21:13:51 +1000
Subject: Human word reader
In-Reply-To: 
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
Message-ID: 

On Sat, May 15, 2010 at 9:12 PM, Xavier Ho  wrote:

> You need to have a very, very good set of heruistics and deterministic
> functions to do that.
>
> "How do I get the position of a known word in a string if the length if
> unknown?"
>

And this is what I get for late night e-mailing.

is*

heuristic*

-Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From timoverbeek10 at gmail.com  Sat May 15 07:32:18 2010
From: timoverbeek10 at gmail.com (timo verbeek)
Date: Sat, 15 May 2010 04:32:18 -0700 (PDT)
Subject: Human word reader
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
Message-ID: 

On May 15, 1:02?pm, timo verbeek  wrote:
Place starts always with for



From e_d_k at yahoo.com  Sat May 15 07:40:43 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sat, 15 May 2010 04:40:43 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <4bee0df4$0$8761$c3e8da3@news.astraweb.com>
Message-ID: <815851.26625.qm@web58705.mail.re1.yahoo.com>

--- On Fri, 5/14/10, Steven D'Aprano  wrote:

> From: Steven D'Aprano 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Friday, May 14, 2010, 10:59 PM
> On Fri, 14 May 2010 06:39:05 -0700,
> Ed Keith wrote:
> 
> > Yes, under the GPL every one has one set of freedoms,
> under the MIT or
> > Boost license every one has more freedoms. Under other
> licenses they
> > have fewer freedoms.
> 
> I think this talk about freedoms is dangerously incomplete,
> and is 
> confusing the issue rather than shedding more light. Both
> licences grant 
> the same positive freedoms (freedom to do something).
> MIT-style licences 
> grant permission to:
> 
> * make copies of the work;
> * make derivative works based on the work; and
> * distribute those derivative works to others.
> 
> The GPL grants precisely the same three rights. There is no
> difference in 
> the rights granted.
> 
> The MIT licence imposes an obligation on the licencee:
> 
> * you must include a copy of the licence and copyright
> notice with the 
> work and/or any derivative works.
> 
> 
> The GPL adds a further obligation:
> 
> * any derivative works must also be licenced under the
> GPL.
> 
> 

That is why I prefer Boost, which adds very few obligations.



> If we want to talk about "freedoms", rather than rights and
> obligations, 
> we need to distinguish between positive freedoms (freedom
> to do 
> something) and negative freedoms (freedoms from something)
> and not just 
> blithely mix them up.
> 

Good point.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From ldo at geek-central.gen.new_zealand  Sat May 15 07:47:39 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sat, 15 May 2010 23:47:39 +1200
Subject: Do any debuggers support "edit and continue?"
References: 
Message-ID: 

In message , Joel 
Koltner wrote:

> Just curious... in Microsoft's Visual Studio (and I would presume some
> other tools), for many languages (both interpreted and compiled!) there's
> an "edit and conitnue" option that, when you hit a breakpoint, allows you
> to modify a line of code before it's actually executed.

Microsoft?s Visual Studio also has a reputation as a bloated and resource-
hungry study in software obesity.

Coincidence? Not if you can come up with a better example of the feature 
you?re touting as so wonderful...


From e_d_k at yahoo.com  Sat May 15 07:50:35 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sat, 15 May 2010 04:50:35 -0700 (PDT)
Subject: Picking a license
In-Reply-To: <87r5ldbw3k.fsf@benfinney.id.au>
Message-ID: <238275.9816.qm@web58702.mail.re1.yahoo.com>

--- On Sat, 5/15/10, Ben Finney  wrote:

> From: Ben Finney 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Saturday, May 15, 2010, 12:57 AM
> aahz at pythoncraft.com
> (Aahz) writes:
> 
> > You can't really sell Open Source software in any
> practical way;
> > someone will always undercut you once it's out in the
> wild. You can
> > only sell support for the software, which is entirely
> different.
> 
> Not at all. I've been selling all the software I write for
> clients for
> the past ten years, and it's all free software. It's been
> very practical
> for me and those I've worked with.
> 
> You can't sell free software like selling loaves of bread,
> but that's a
> much more limited case and a far cry from your claim.
> Selling free
> software is quite practical and a good way to fund
> development of
> software that otherwise wouldn't be written as free
> software.
> 
> -- 
>  \? ????Why am I an atheist? I ask
> you: Why is anybody not an atheist? |
> ? `\? ? ? Everyone starts out being an
> atheist.? ?Andy Rooney, _Boston |
> _o__)? ? ? ? ? ? ?
> ? ? ? ? ? ? ? ?
> ? ? ? ? ? ? ? ?
> ? Globe_ 1982-05-30 |
> Ben Finney
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Why don't your own customers under cut you? If you sell someone GPLed 
software they have the right to redistribute it for less than you are 
distributing it for. That dose not strike me as a viable business model.

How do you make it work?

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From utente at esempio.net  Sat May 15 08:35:04 2010
From: utente at esempio.net (superpollo)
Date: Sat, 15 May 2010 14:35:04 +0200
Subject: Human word reader
In-Reply-To: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
Message-ID: <4bee94f8$0$18652$4fafbaef@reader3.news.tin.it>

timo verbeek ha scritto:
> I'm planning to create a human word program
> A human inputs a string
> "Give me the weather for London please."
> Then I will strip the string.
> "weather for london"
> Then I get the useful information.
> what:"weather" where:"london"
> After that I use the info.
> 
> I need help with getting the useful information how do I get the place
> if I don't now how long the string is?


 >>> query = "Give me the weather for London please."
 >>> what = query.strip("Give me the ").split()[0]
 >>> where = query.strip("Give me the " + what + " for ").split()[0]
 >>> print what, where
weather London
 >>>


From contact at xavierho.com  Sat May 15 08:38:01 2010
From: contact at xavierho.com (Xavier Ho)
Date: Sat, 15 May 2010 22:38:01 +1000
Subject: Human word reader
In-Reply-To: 
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
Message-ID: 

On Sat, May 15, 2010 at 9:32 PM, timo verbeek wrote:

> On May 15, 1:02 pm, timo verbeek  wrote:
> Place starts always with for
>

Okay, much better.

Given that constraint, it looks like regular expression can do the job. I'm
not very experienced with regex, though.

\w* matches a whole word composed of letters and numbers by default.

>>> result = re.search('for \w*', 'Give me the weather for London please.')
>>> result.group()
'for London'
>>> result.group().split()[1]
'London'

Cheers,
Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From promptc2 at hotmail.com  Sat May 15 08:47:56 2010
From: promptc2 at hotmail.com (www.promptc.com)
Date: Sat, 15 May 2010 05:47:56 -0700 (PDT)
Subject: www.promptc.com (only $36,free shipping)for 2010 newest Adidas 
	shoes--Paypal
Message-ID: <768c36c4-ae14-4cfe-8561-e9ce57430d60@31g2000prc.googlegroups.com>

Dear my Lady or Gentleman,

Great day!

  welcome to visit online shopping website  www.Promptc.com

We are professional in supplying nike shox,nike air max,nike
jordan,basketball shoes,adidas shoes,MBT shoes,Vibram-Fivefingers
etc.We do long term business and have high reputation in USA and
Europe country!

Some links of the adidas shoes :
1)    http://www.promptc.com/index.php?main_page=index&cPath=363_364
2)   http://www.promptc.com/index.php?main_page=index&cPath=363_365&sort=20a&page=2
3)http://www.promptc.com/index.php?
main_page=product_info&cPath=363_365&products_id=9776

Basic information:
1)Payment:Paypal,WU,TT etc
2)Delivery time:3-7 days door to door delivery by DHL,TNT,EMS etc
3)quality condition:1:1
4) full size for men and women
5)can do drop-ship to your customers!
6)more order more discount ! ! !
7)we would send out your order within 24 hours once confirmed your
Pyament and then send you the tracking number via email for you to
track the status of the goods.

Please just enter the web site for more details or please fee free to
contact us for any questions! Waitting for your early reply.Hope to
start business with each other soon!

Your sincerity


Megan Li

Promptc Co.,Ltd
www.promptc.com
earphone & headphone, microphone, mp3 player, radio, earphone, bose,
in ear, wireless networking equipment speaker, mobile phone
accessories, mobile phone parts, telephones & parts, adidas shoes, t-
mac shoes, 35th shoes, y3 shoes, timberland shoes, puma shoes, bape
shoes, rift shoes, prada shoes, gucci shoes, ice cream shoes, lv
shoes, lacoste clothing, juicy clothing, evisu clothing, d&g clothing,
polo clothing, bape clothing, red monkey jeans, antik jeans, bape
jeans, evisu jeans, seven jeans, d&g jeans, tluerelgion, jeans,
repuplic jeans, lv bags, chanel bags, gucci bags, juicy bags, chloe
bags, fendi bags, caps and hats, glasses, watches, red monkey jeans,
d&g jeans, citizens of humanity jeans, antik denim jeans, red monkey,
miss sixty, evisu, bbc, citizens for humanity, d&g, rock&republic,
seven, taverniti so jeans, true religion, hermes, chanel, gucci,
prada, mulberry, fendi, chloe, coach, louis vuitton, bag, bags,
handbag, handbags, dior, wallet, purse, balenciage, leather wallets,
womens wallets, ipodlaptop, plasma tv, ipod, psp, ps3, xbox 360,
digital camera, mobile phone, apple, mp3, mp4, nokia, motorola,
samsung, usb, memory card, laptops, ps2, digital samsung, sony, canon,
olympus, ibm, powerbook, ipod nano, ipod video, reebok jersey,
champion jersey, jersey, jerseys, nba jerseys, xxxxx, nfl. shoes,
sports shoes, nike air jordan, nike air force, nike air max, womens
jeans, evisu jeans, womens swimwear, wig, hair pices, jordan 3 clear,
clear jordan 3, lacoste shirts, lacoste t-shirt, lacoste, jordan 21,
jordanjordan shoes, nike shoes, adidas shoes, shoes, jordan, nike,
puma shoes, pumas shoes, sport shoes, casual shoes, addidas shoes,
prada shoes, footwear shoes, nike nike, adidas adidas, puma puma,
prada prada, timberland shoes, timberland timberlan, footwear nike
jordan, air force max, air force one shoes, air force one sneakers,
air force one nikes, men's athletic shoes, shoes sports, women's
athletic shoes, mens athletic shoes, mens sport shoes, air max, air
force one, bape, nike shox, converse, adidas, polo gucci, jimmy choo,
christain dior, lv, replicas sandals mirror image, balenciaga, kooba,
marc jacobs, replicas bags, knock off hermes, womens wallets hermes,
replica bag, wholesale bag, wholesales bag, wholesale gucci bag,
wholesale chanel bag, wholesale hermes bag, wallet soccer shoes,
athletic shoes, clip-in hair, jordan xxi jordan shoes, knock off
hermes, wallet red monkey jeans, bape&bbc jeans, antic jeans, rocawear
jeans, sean john jeans, abercrombie fitch jeans, true religion jeans,
seven jeans, akademiks jeans, levis jeans, diesel jeans, d gjeans, men
sunglasses, sport sunglasses, designer sunglasses, fashion sunglasses,
men black sunglasses, cool sunglasses, dolce gabbana sunglasses, dg
sunglasses, chanel handbag, tiffany jewelry, gucci sun glasses, new
rolex watch, sterling silver necklace, fendi handbag, tiffany
bracelet, wholesale gucci, womens watch, silver necklace pendant,
necklace, nfl.soccer shoes, silver neck, soccer shoes, jordan jordan
shoes, necklace pendant, fashion jewelry necklace, luggage silver tag,
jewel, watch, watches, watches rolex, gold rolex watches, watches
women, gift watches, brand watches, branded watches, women watches,
female watches, rolex, cartier, bvlgari, omega, gucci watch, longines,
soccer shoes, athletic shoes, sports shoes, nike air jordan, nike air
force, nike air max, womens jean jersey nfl, authentic jersey nfl,
jersey nfl youth, football jersey nfl, jersey nfl throwback, cheap
jersey nfl, jersey nfl replica, jersey nfl personalized, jersey kid
nfl, custom jersey nfl, jersey nfl womens, authentic cheap jersey nfl,
jersey nfl replica youth, discount jersey nfl, authentic jersey nfl,
jersey man nfl replica, custom football jersey, college football
jersey, nfl football jersey, nba jersey, mlb jersey, nhl jersey, nike
sneakers, jordan sneakers jersey nfl, authentic jersey nfl, jersey nfl
youth, football jersey nfl, jersey nfl throwback, cheap jersey nfl,
jersey nfl replica, jersey nfl personalized, jersey kid nfl, custom
jersey nfl, jersey nfl womens, authentic cheap jersey nfl, jersey nfl
replica youth, discount jersey nfl, authentic jersey nfl, jersey man
nfl replica, nokia mobile phone, cell phone, cellular phone, cdma,
vertu phone, business phone, vertu signature cell phone, samsung
mobile phone, original phone, telephone, used mobile phone, oem mobile
phone, nokia n series, samsung d900, nokia n75, nokia8800, ipod nano
3rd, ipods, ipod video, apple ipod video, wholesale apple ipod touch,
ipod classic, vertu, verpu, vx, apple ipod shuffle, n71, 72, n90, n91,
n92, n93, n76, motorol] nokia vertu, nokia 8800 sirocco, nokia 8600
luna, nokia 8800, nokia e90, nokia n800, nokia n80, nokia n83, nokia
n76, nokia n72, nokia n90, nokia n92, nokia n91, nokia n82, nokia
5700, motorola a1200, motorola z3, v3, v3i, v3x, v3xx, handphone]
mobile phone, cell phone, anthentic phone, real phone, copy phone,
apple iphone, nokia n95, motorola, samsung, sony, unlocked phone,
memory cards, bluetooth, charger, battery, headphones n95, n80, e90,
8800, n70, n72, n73, n75, n77, iphone, ipod nano 2, mp3, mp4, iphone,
dvd computer, mobile phone, cell phone, shoes, clothing, nike, jordan,
nokia, sony, ps3, psp, wii, xbox, nokia, nokia n95, nokia mobile,
nokia n95 mobile, wholesale nokia, wholesale nokia n95, wholesale
nokia mobile, nokia whole sale, nokia n95 whole sale, nokia mobile
whole sale, nokia wholesalers, nokia n93 wholesalers, nokia mobile
wholesalers, nokia n91 mobile wholesalers, nokia suppliers, nokia 95
suppliers, nokia n80 mobile suppliers, nokia mobile suppliers, nokia
exporters, motorola nokia mobilemotorola phone, samsung mobile, nokia
nseries, nokia 8800, nokia vertu, nokia n95, n93, n91, n80 n73, n72,
n71, n70, nokia 6300, motorola v3, motorola v3i, samsung d900, apple
macbook, iphone ipod, mp3 mp4, 60g video, dual sim card, lg mobile
phone, laptop, gps, sonyericosson pad, blackberry, nokia8800sirocco
gold, edition apple iphone, nokia n95, sumsung moto, crafts lithium
batteries, nickel hydride batteries, mobile phone batteries, mobile
phone chargers, lithium batteries, nickel hydride batteries, mobile
phone batteries, mobile phone accessories, mobile phone parts, mobile
phones, ipod, ps3, psp, apple, sony, clothes, apparel, jeans, shirts,
t-shirts, wallet, rolex, bape, bbc, lrg, hoody, jacket, nike air
jordans, air jordan 9, xxxxx, capping, handbag, ipod, shoes, silver
jewelry, jewellery, nike shoes, jordan, replicas, mp3, xbox, mobile
phone, ipod nano, lacoste, nokia, mp4, textile accessories, mobile
phones, mp3 player, adidas, footwear, mp3 player, bag, jordan 13,
jordan shoes, nokia 8800, profiles, nike tn, gucci, handbags, sport
shoes, used shoes, phone, air force one, watches, air jordan, jeanst
shirt, sock holders, bluetooth, fashion, xbox 360 premium, sony psp,
mp4 player, jordan 21, sell, airforce 1, air max, puma, air force 1,
sports shoes, nike jordan, air, chanel, jacket, pradareplica, bamboo,
louis vuitton, air force ones, air max plus, pu shoes, belt, nike shox
r4, nike air max, jordan 10, jordan 14, xbox360, jordans, for
footwear, jordan 5, sunglasses, brand, shirt, jordan 21 shoes,
garment, textile, nike jordan 21, digital camera, footwear shoes, nike
shox tl, t shirts, nike shox nz, dunk, leather shoes, samsung d600,
air max 90, rolex, max tn, jordan 4, air max 97, cell phones, jordan
11, nike af1, nike af1, caps, nike shox shoes, playstation 3, nike
jordan shoes, air ones, shox r4, air jordan shoes, jordan 1 21jordan
19, jordan 4.5, ice cream, jordan 6, jordan 18, ipod nano 4gb, nike
air force one, jordan 15, jordan 2, nike air force 1, shox nz, jordan
3, polypropylene, bape, brand new, tapioca, nike;shox, air jordan 7,
shoes, tn r4 nz nike, tn timberland, nike pu, jordan 7, clear jordan,
clear jordan 7, jordan nike, jordan 20, air max 95, nike r6, airmax,
jordan;adidas, jordan nike, mesh belt, nike jordan 6, air force, nike
timberland, air max 2004, new jordan ones, lv handbags, jordan;shox,
tn shoes, jordan;dunk, ecommerce, jordan gt;dubzero, jordan xx, nike
air max 97, air force1, handmade, shox tl, jordan x, fashion shoes,
jordan;air, adidas shoes, shoes nike, nike jordan 13, nikeshoes, shox
r4 tn, nike r5, jordans shoes, jordan, puma, nike air force one, nike
air jordan 21, nike jordan 1.2.3.4.5.6.7.19.20, rocawear, puma shoes,
jordan dub zero, jordan timberland, nike;adidas, jordan i xx, sell
nike shoes, buy nike shoes, nike tn shoes, tn shox, air jordan 13,
jordan;af1, jordan i xx shoes, seven jeans, nike 97, evisu, evisu
jeans, shox r5, nike air force, sell shoes, nike.jodan, nike jordan 1
21, air max shoes, air nike, timberland, prada, nike jordan 10, air
max shox tn, air jordan 3, nike footwear, air max 95 97 2003 2004 2005
tn, nike shoes tn, nike air oz, air jordan dz, nike tl, shox tn, shox
tl r4 nz, tn jordan, new adidas, shoes.air jordan, nike trainer, nike
shox eu, jordan13, air max 95 97 2003 2004 2005, nike air nz, tl3, air
jordan 4, jordan 16, timberland nike, nike air max 95, jordan ix, air
jordan 17, bape hoodies, tshirts, air jordan 20.5, nike shoes air
jordan 10, jordan21, air max 95 97 2003, nike air jordan 11, nike air
max tn, nike air max tn, shox tl, tl2, tl3, tshirt, shoes nike jordan,
air jordan 21, clear af1, clear air force one 1, sean john, machines,
jewelry, nike tn nike shox, bape jeans, redmonkey, football shoes, dub
zero, t.shirts, sunglass, polo t shirt, jordan 5.5, jordan 8, kids
shoes, mens shoes, womens shoes, basketball shoes, running
shoes]soccer shoes, athletic shoes, sports shoes, nike air jordan,
nike air force, nike air max, womens jeans, evisu jeans, red monkey
jeans, womens swimwear, wig, hair pices, jordan 3 clear, clear jordan
3, lacoste shirts, lacoste t-shirt, lacoste, jordan 21, jordanjordan
shoes, nike shoes, adidas shoes, shoes, jordan, nike, puma shoes,
pumas shoes, sport shoes, casual shoes, addidas shoes, prada shoes,
footwear shoes, nike nike, adidas adidas, puma puma, prada prada,
timberland shoes, timberland timberlan, footwear nike jordan, air
force max, air force one shoes, air force one sneakers, air force one
nikes, men's athletic shoes, shoes sports, women's athletic shoes,
mens athletic shoes, mens sport shoes, jordan, air max, air force one,
bape, nike shox, converse, adidas, prada, polo gucci, mulberry, chloe,
fendi, jimmy choo, christain dior, shoes, chanel, coach, lv, louis
vuitton, hermes, replicas sandals mirror image, balenciaga, kooba,
marc jacobs, replicas bags, knock off hermes, chanel, gucci, prada,
mulberry, fendi, chloe, coach, louis vuitton, bag, bags, handbag,
handbags, dior, wallet, purse, balenciage, leather wallets, womens
wallets hermes, chanel, gucci, prada, mulberry, fendi, chloe, coach,
louis vuitton, bag, bags, handbag, handbags, replica bag, wholesale
bag, wholesales bag, wholesale gucci bag, wholesale chanel bag,
wholesale hermes bag, purse, wallet soccer shoes, athletic shoes,
sports shoes, nike air jordan, nike air force, nike air max, womens
jeans, evisu jeans, red monkey jeans, womens swimwear, wig, hair
pices, clip-in hair, jordan 3 clear, clear jordan 3, lacoste shirts,
lacoste t-shirt, lacoste, jordan 21, jordan xxi jordan shoes, nike
shoes, adidas shoes, shoes, jordan, nike, puma shoes, pumas shoes,
sport shoes, casual shoes, addidas shoes, prada shoes, footwear shoes,
nike nike, adidas adidas, puma puma, prada prada, timberland shoes,
timberland timberlan, footwear nike jordan, air force max, air force
one shoes, air force one sneakers, air force one nikes, men's athletic
shoes, shoes sports, women's athletic shoes, mens athletic shoes, mens
sport shoes, jordan, air max, air force one, bape, nike shox,
converse, adidas, prada, polo gucci, mulberry, chloe, fendi, jimmy
choo, christain dior, shoes, chanel, coach, lv, louis vuitton, hermes,
replicas sandals mirror image, balenciaga, kooba, marc jacobs,
replicas bags, knock off hermes, chanel, gucci, prada, mulberry,
fendi, chloe, coach, louis vuitton, bag, bags, handbag, handbags,
dior, wallet, purse, balenciage, leather wallets, womens wallets
hermes, chanel, gucci, prada, mulberry, fendi, chloe, coach, louis
vuitton, bag, bags, handbag, handbags, replica bag, wholesale bag,
wholesales bag, wholesale gucci bag, wholesale chanel bag, wholesale
hermes bag, purse, wallet red monkey jeans, evisu jeans, bape&bbc
jeans, antic jeans, rocawear jeans, sean john jeans, abercrombie fitch
jeans, true religion jeans, seven jeans, akademiks jeans, levis jeans,
diesel jeans, d gjeans, men sunglasses, sport sunglasses, designer
sunglasses, fashion sunglasses, men black sunglasses, cool sunglasses,
dolce gabbana sunglasses, dg sunglasses, chanel handbag, tiffany
jewelry, gucci sun glasses, new rolex watch, sterling silver necklace,
fendi handbag, tiffany bracelet, wholesale gucci, womens watch, silver
necklace pendant, necklace pendant, fashion jewelry necklace, luggage
silver tag, jewelry silver tag, jewelry necklace, bracelets jewelry,
fashion jewelry, silver earrings, silver jewellery hats, caps, new
era. fashion accessory, fashion belts, fashion belt buckles, womens
fashion belt, wholesale fashion belt, lady fashion belt, beaded
fashion belt, woman fashion belt, wholesale fashion accessories
tiffany, ring, necklace, bracelet, earring, sterling sliver, jewelry,
jewellery, fashion jewelry, wholesales tiffany, wholesale tiffany,
wholesale tiffany jewelry, wholesale tiffany jewellery, bvlgari
jerseys, nba jersey, nfl jersey, soccer jersey, sports wear reebok
jersey, champion jersey, jersey, jerseys, nba shoes women, bape,
pendel, shox r5 energia women, air jordan 12 men, air force 1 women,
air jordan 9 men, dunk mid men, skirt, air jordan 15 men, levi's, air
jordan 13 kids, la, citizen, air max 2003 men, frankie b, loewe,
tod's, air jordan 19 men, akademiks, women, rado, shox rival men, long
women, shox tl3 men, shox r5 energia women, city men, dunk women, g
star, long sleeve men, air jordan 10 men, escada sports, mqueen, air
jordan 6 women, shox r4 women, air jordan 18 men, skirt, long sleeve
men, ice cream, shox tl3 men, air jordan 11 women, wallets, with bra
cup women, converse, solid color men, chloe, chloe, jacket, 2gb, air
jordan 6 women, air jordan 6.5 men, air jordan 7 women, loewe, solid
color men, air max 97 women, superstar 35th women, sweater, jimmy
choo, air max tn5 men, necklace women, air jordan 17 men, air jordan
11 women, bape, chloe, shox tl2 men, 1gb, new era, ipod, sixty, bikkem
bergs, energie, underwear(bikili), rift men, air max 90 men, 2gb,
necklace women, jeans, long sleeve men, new era, turdo, hoody,
christian dior, shox r4 men, jacobs, air jordan 5.5 men, air jordan
3.5 men, nba men, air max tn6 men, ray ban, pants, y-3 men, prada,
short sleeve men, dolce&gabbana, jack jones, g star, big polo women,
air jordan 21.5 men, gino green global, tiffany, air max 95 men, long
women, shox tl3 men, vogue, paul smith, kooda, gino green global,
louis vuitton, others men, ugg, hats(caps), short women, adicolor
women, air jordan 8 men, mp3/mp4, mac jacobs, ice cream, air jordan 11
women, shox nz women, ralph lauren(polo), underwear(bikili), air max
2003 men, air jordan 11 kids, gino green global, air jordan 11 men,
air jordan 17 men, shox r5 energia women, frankie b, shox r5 energia
women, dunhill, coach, jacobs, hoody, short men, billionaire boys
club, tod's, air jordan 7.5 men, armani, sandal, hermes, adicolor
women, citizen, shox tl men, ray ban, 4gb, air jordan 1 men, dunk
women, diesel, spyder, apple ipod, ipod mini, apple ipod nano, ipod
nanos, apple ipod shuffle, apple iphone, nokia n95, nokia n93,
nintendo wii, buy wii, wii console, digital camera, mobile phones,
home security systems, vacuum cleaners, dvd players, wii accessories,
wii controllers, nintendo wii controller, xbox controller, ps2


 high heels, dansko clogs, novelty slippers, womens slippers, bridal
flip flops, travel slippers, birkenstock clogs, nursing clogs, garden
clogs, mens clogs


From duncan.booth at invalid.invalid  Sat May 15 08:52:03 2010
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 15 May 2010 12:52:03 GMT
Subject: Picking a license
References: 
Message-ID: 

Ed Keith  wrote:

> I can not imagine anyone being stupid enough to pay me for rights to
> use code I had already published under the Boost License, which grants
> then the rights to do anything they want with it without paying me
> anything. 
>   -EdK
> 
Really?

The Boost License says, amongst other things:

> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
> NON-INFRINGEMENT. 

Are you sure you can't imagine anyone offering to pay you for an 
alternative license that came with some kind of warranty or support?



From utente at esempio.net  Sat May 15 08:55:20 2010
From: utente at esempio.net (superpollo)
Date: Sat, 15 May 2010 14:55:20 +0200
Subject: Human word reader
In-Reply-To: <4bee94f8$0$18652$4fafbaef@reader3.news.tin.it>
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	<4bee94f8$0$18652$4fafbaef@reader3.news.tin.it>
Message-ID: <4bee99c3$0$18661$4fafbaef@reader3.news.tin.it>

superpollo ha scritto:
> timo verbeek ha scritto:
>> I'm planning to create a human word program
>> A human inputs a string
>> "Give me the weather for London please."
>> Then I will strip the string.
>> "weather for london"
>> Then I get the useful information.
>> what:"weather" where:"london"
>> After that I use the info.
>>
>> I need help with getting the useful information how do I get the place
>> if I don't now how long the string is?
> 
> 
>  >>> query = "Give me the weather for London please."
>  >>> what = query.strip("Give me the ").split()[0]
>  >>> where = query.strip("Give me the " + what + " for ").split()[0]
>  >>> print what, where
> weather London
>  >>>

maybe better not with strip, fot it might not do what i intended (see 
docs); maybe preferable to use "partition" method:

 >>> query = "Give me the weather for London please."
 >>> what  = query.partition("Give me the ")[2].split()[0]
 >>> where = query.partition(" for ")[2].split()[0]
 >>> print what, where
weather London
 >>>


From e_d_k at yahoo.com  Sat May 15 09:30:56 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sat, 15 May 2010 06:30:56 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <872403.90739.qm@web58705.mail.re1.yahoo.com>

--- On Sat, 5/15/10, Duncan Booth  wrote:

> From: Duncan Booth 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Saturday, May 15, 2010, 8:52 AM
> Ed Keith 
> wrote:
> 
> > I can not imagine anyone being stupid enough to pay me
> for rights to
> > use code I had already published under the Boost
> License, which grants
> > then the rights to do anything they want with it
> without paying me
> > anything. 
> >???-EdK
> > 
> Really?
> 
> The Boost License says, amongst other things:
> 
> > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
> ANY KIND,
> > EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
> WARRANTIES OF
> > MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
> TITLE AND
> > NON-INFRINGEMENT. 
> 
> Are you sure you can't imagine anyone offering to pay you
> for an 
> alternative license that came with some kind of warranty or
> support?
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Would that be a license or a support contract?

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From nobody at nowhere.com  Sat May 15 10:05:30 2010
From: nobody at nowhere.com (Nobody)
Date: Sat, 15 May 2010 15:05:30 +0100
Subject: write a 20GB file
References: 
	<4BED2E45.6060301@ieee.org>
	
	
	
	
Message-ID: 

On Fri, 14 May 2010 18:38:55 -0400, J wrote:

>>> someone smarter than me can correct me, but file.write() will write when
>>> it's buffer is filled, or close() or flush() are called.
>>
>> And, in all probability, seek() will either flush it immediately or cause
>> the next write() to flush it before writing anything.
> 
> Ahhh... I didn't know that... I thought seek() just moved the pointer
> through the file a little further....

Think about how this affects buffering. write() writes at the current file
position. If you write, then seek, then write, it can't just concatenate
the two sets of data, as that would "lose" the seek.

Either the buffer has to contain multiple, distinct sets of data, each
with an associated position, or (far more likely), the original data must
be written to the correct location before the second set of data can be
stored.



From gehan.ameresekere at gmail.com  Sat May 15 10:05:37 2010
From: gehan.ameresekere at gmail.com (train)
Date: Sat, 15 May 2010 07:05:37 -0700 (PDT)
Subject: Pyinstaller on WINE - cannot install pywin32
Message-ID: <250f5073-8494-4c3c-a4bc-cd53f7e4e66d@e34g2000pra.googlegroups.com>

Pyinstaller works fine on Windows XP. I am trying to get it working on
WINE. Running
configure.py results in asking for pywin32, however pywin 32 will not
install

C:\pywin32-214>c:\python26\python setup.py
Building pywin32 2.6.214.0
This is a distutils setup-script for the pywin32 extensions

To build the pywin32 extensions, simply execute:
  python setup.py -q build
or
  python setup.py -q install
to build and install into your current Python installation.

These extensions require a number of libraries to build, some of which
may
require you to install special SDKs or toolkits.  This script will
attempt
to build as many as it can, and at the end of the build will report
any
extension modules that could not be built and why.
Currently, the Vista SDK and DirectX SDK are required to successfully
build
all extension modules - note that using the Vista SDK doesn't force
you to
use Vista as your build environment.  Please use google to find the
SDK -
links to microsoft.com seem to only stay current for a short time.
Also note
that the SDK that comes with VS2008 is not good enough to compile
earlier
versions.  If you installed VS2008 after the Vista SDK, try doing a
'repair'
on your SDK install.

Early versions of certain Windows headers/SDK versions will also cause
certain modules to be skipped. If you don't use the extensions that
fail to
build, you can ignore these warnings; if you do use them, you must
install
the correct libraries.

The 'exchange' extensions require headers that are no longer in any
current
SDKs, so these fail to build, but the 'mapi' extension should still
build.

Building:
---------

To install the pywin32 extensions, execute:
  python setup.py -q install

This will install the built extensions into your site-packages
directory,
create an appropriate .pth file, and should leave everything ready to
use.
There is no need to modify the registry.

To build or install debug (_d) versions of these extensions, ensure
you have
built or installed a debug version of Python itself, then pass the "--
debug"
flag to the build command - eg:
  python setup.py -q build --debug
or to build and install a debug version:
  python setup.py -q build --debug install

To build 64bit versions of this:

* py2.5 and earlier - sorry, I've given up in disgust.  Using VS2003
with
  the Vista SDK is just too painful to make work, and VS2005 is not
used for
  any released versions of Python. See revision 1.69 of this file for
the
  last version that attempted to support and document this process.

*  2.6 and later: On a 64bit OS, just build as you would on a 32bit
platform.
   On a 32bit platform (ie, to cross-compile), you must use VS2008 to
   cross-compile Python itself. Note that by default, the 64bit tools
are not
   installed with VS2008, so you may need to adjust your VS2008 setup.
Then
   use:

      setup.py build --plat-name=win-amd64

   see the distutils cross-compilation documentation for more details.

Standard usage information follows:
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

error: no commands supplied
C:\pywin32-214>c:\python26\python setup.py -q install
Building pywin32 2.6.214.0
error: Unable to find vcvarsall.bat
C:\pywin32-214>



From awilliam at whitemice.org  Sat May 15 10:12:40 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sat, 15 May 2010 10:12:40 -0400
Subject: Puzzled by code pages
In-Reply-To: <4bee7823$1@dnews.tpgi.com.au>
References: 
	<4bee7823$1@dnews.tpgi.com.au>
Message-ID: <1273932760.3929.18.camel@linux-yu4c.site>

On Sat, 2010-05-15 at 20:30 +1000, Lie Ryan wrote:
> On 05/15/10 10:27, Adam Tauno Williams wrote:
> > I'm trying to process OpenStep plist files in Python.  I have a parser
> > which works, but only for strict ASCII.  However plist files may contain
> > accented characters - equivalent to ISO-8859-2 (I believe).  For example
> > I read in the line:
> >>>> handle = open('file.txt', 'rb')
> >>>> data = handle.read()
> >>>> handle.close()
> >>>> data
> > '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
> > NSFileName;\n'
> I presume you're using Python 2.x.

Yes.  But the days of all-unicode-strings will be wonderful when it
comes. :)

> > What is the correct way to re-encode this data into UTF-8 so I can use
> > unicode strings, and then write the output back to ISO8859-?
> > I can read the file using codecs as ISO8859-2, but it still doesn't seem
> > correct.
> >>>> handle = codecs.open('file.txt', 'rb', encoding='iso8859-2')
> >>>> data = handle.read()
> >>>> handle.close()
> >>>> data
> > u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
> > NSFileName;\n'
> When printing in the interactive interpreter, python uses __repr__
> representation by default. If you want to use __str__ representation use
> "print data" (note, your terminal must support printing unicode
> characters); 

Using GNOME Terminal, so Unicode characters should display correctly.
And I do see the characters when I 'cat' the file.

> either way, even though the string looks like '\u0102' when
> printed on the terminal, the binary pattern inside the memory should
> correctly represents the accented character.

Yep.  But in the interpreter both unicode() and repr() produce the same
output.  Nothing displays the accented character.

h = codecs.open('file.txt', 'rb', encoding='iso8859-2')
data = h.read()
h.close()
str(data)

'ascii' codec can't encode characters in position 33-34: ordinal not in
range(128)

unicode(data)
u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
NSFileName;\n'

repr(data)
'u\'    "skyp4_filelist_10201/localit\\u0102\\xa0 termali_sortfield" =
NSFileName;\\n\''

I think I'm getting close.  Parsing the file seems to work, and while
writing it out does not error, rereading my own output fails. :(
Possibly I'm 'accidentally' writing the output as UTF-8 and not
ISO8859-2.  I need the internal data to be UTF-8 but read as ISO8859-2
and rewritten back to ISO8859-2 [at least that is what I believe from
the OpenStep files I'm seeing].

What is the 'official' way to encode something from UTF-8 to another
code page.  I *assumed* that if I wrote a unicode stream back through:

h = codecs.open(output_filename, 'wb', encoding='iso8859-2')
data = writer.store(defaults)
h.write(data)
h.close()

that is would be re-encoded [word?].  But maybe not?



> f = codecs.open("in.txt", 'rb', encoding="iso8859-2")
> f2 = codecs.open("out.txt", 'wb', encoding="utf-8")
> s = f.read()
> f2.write(s)
> f.close()
> f2.close()

-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba
-------------- next part --------------
    "skyp4_filelist_10201/localit? termali_sortfield" = NSFileName;

From mannu_0523 at rediffmail.com  Sat May 15 10:20:34 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 15 May 2010 14:20:34 -0000
Subject: =?utf-8?B?UmU6IFJlOiBqb2luaW5nIHR3byBjb2x1bW4=?=
In-Reply-To: <4BED9A9F.5040708@tim.thechases.com>
Message-ID: <1273862645.S.6081.40691.H.TlRpbSBDaGFzZQBSZTogam9pbmluZyB0d28gY29sdW1u.f4-234-202.old.1273933234.29073@webmail.rediffmail.com>



On Sat, 15 May 2010 00:14:05 +0530  wrote
>On 05/14/2010 12:55 PM, James Mills wrote:

>> file1:

>> a1 a2

>> a3 a4

>> a5 a6

>> a7 a8

>>

>> file2:

>> b1 b2

>> b3 b4

>> b5 b6

>> b7 b8

>>

>> and I want to join them so the output should look like this:

>>

>> a1 a2 b1 b2

>> a3 a4 b3 b4

>> a5 a6 b5 b6

>> a7 a8 b7 b8

>

> This is completely untested, but this "should" (tm) work:

>

> from itertools import chain

>

> input1 = open("input1.txt", "r").readlines()

> input2 = open("input2.txt", "r").readlines()

> open("output.txt", "w").write("".join(chain(input1, input2)))



I think you meant izip() instead of chain() ... the OP wanted to 

be able to join the two lines together, so I suspect it would 

look something like



  # OPTIONAL_DELIMITER = " "

  f1 = file("input1.txt")

  f2 = file("input2.txt")

  out = open("output.txt", 'w')

  for left, right in itertools.izip(f1, f2):

   out.write(left.rstrip('\r\n'))

   # out.write(OPTIONAL_DELIMITER)

   out.write(right)

  out.close()



This only works if the two files are the same length, or (if 

they're of differing lengths) you want the shorter version. The 

itertools lib also includes an izip_longest() function with 

optional fill, as of Python2.6 which you could use instead if you 

need all the lines



-tkc









-- 

with this 
from itertools import chain
# OPTIONAL_DELIMITER = " "
f1 = file("input1.txt")
f2 = file("input2.txt")
out = open("output.txt", 'w')
for left, right in itertools.izip(f1, f2):
  out.write(left.rstrip('\r\n'))
    # out.write(OPTIONAL_DELIMITER)
  out.write(right)
out.close()

it is showing error:
ph08001 at linux-af0n:~> python join.py
Traceback (most recent call last):
  File "join.py", line 6, in 
    for left, right in itertools.izip(f1, f2):
NameError: name 'itertools' is not defined
ph08001 at linux-af0n:~>



-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nathan.alexander.rice at gmail.com  Sat May 15 10:37:59 2010
From: nathan.alexander.rice at gmail.com (Nathan Rice)
Date: Sat, 15 May 2010 10:37:59 -0400
Subject: write a 20GB file
In-Reply-To: 
References: 
	<4BED2E45.6060301@ieee.org>
	
	
	
	
	
Message-ID: 

This is precisely the situation mmap was made for :)  It has almost the same
methods as a file so it should be an easy replacement.

On Sat, May 15, 2010 at 10:05 AM, Nobody  wrote:

> On Fri, 14 May 2010 18:38:55 -0400, J wrote:
>
> >>> someone smarter than me can correct me, but file.write() will write
> when
> >>> it's buffer is filled, or close() or flush() are called.
> >>
> >> And, in all probability, seek() will either flush it immediately or
> cause
> >> the next write() to flush it before writing anything.
> >
> > Ahhh... I didn't know that... I thought seek() just moved the pointer
> > through the file a little further....
>
> Think about how this affects buffering. write() writes at the current file
> position. If you write, then seek, then write, it can't just concatenate
> the two sets of data, as that would "lose" the seek.
>
> Either the buffer has to contain multiple, distinct sets of data, each
> with an associated position, or (far more likely), the original data must
> be written to the correct location before the second set of data can be
> stored.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From python.list at tim.thechases.com  Sat May 15 10:40:15 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Sat, 15 May 2010 09:40:15 -0500
Subject: joining two column
In-Reply-To: <1273862645.S.6081.40691.H.TlRpbSBDaGFzZQBSZTogam9pbmluZyB0d28gY29sdW1u.f4-234-202.old.1273933234.29073@webmail.rediffmail.com>
References: <1273862645.S.6081.40691.H.TlRpbSBDaGFzZQBSZTogam9pbmluZyB0d28gY29sdW1u.f4-234-202.old.1273933234.29073@webmail.rediffmail.com>
Message-ID: <4BEEB24F.5010605@tim.thechases.com>

On 05/15/2010 09:20 AM, mannu jha wrote:

BTW: your mailer makes an absolute mess of plain-text emails, 
putting multiple spaces



between


every


single


line


which


makes


it


very


hard


to


read.

Please fix it, use a real mailer, or risk getting ignored (or 
worse, plonked).  Fortunately, Vim makes it modestly easy to 
unmung the rubbishy format.

 >>    # OPTIONAL_DELIMITER = " "
 >>    f1 = file("input1.txt")
 >>    f2 = file("input2.txt")
 >>    out = open("output.txt", 'w')
 >>    for left, right in itertools.izip(f1, f2):
 >>     out.write(left.rstrip('\r\n'))
 >>     # out.write(OPTIONAL_DELIMITER)
 >>     out.write(right)
 >>    out.close()
 >> This only works if the two files are the same length, or (if
 >> they're of differing lengths) you want the shorter version. The
 >> itertools lib also includes an izip_longest() function with
 >> optional fill, as of Python2.6 which you could use instead if you
 >> need all the lines
 >
 > with this
 >
 > from itertools import chain
 > # OPTIONAL_DELIMITER = " "
 > f1 = file("input1.txt")
 > f2 = file("input2.txt")
 > out = open("output.txt", 'w')
 > for left, right in itertools.izip(f1, f2):
 >   out.write(left.rstrip('\r\n'))
 >     # out.write(OPTIONAL_DELIMITER)
 >   out.write(right)
 > out.close()
 > it is showing error:
 > ph08001 at linux-af0n:~> python join.py
 > Traceback (most recent call last):
 >   File "join.py", line 6, in
 >     for left, right in itertools.izip(f1, f2):
 > NameError: name 'itertools' is not defined

That's because you're not importing itertools, but you're just 
importing "chain" from within it.  So of course when you try to 
use "itertools.izip", itertools doesn't exist.  You can either use

   import itertools
   #...
   for left, right in itertools.izip(f1,f2):

or

   from itertools import izip
   #...
   for left, right in izip(f1,f2):

-tkc






From switch2mathan at gmail.com  Sat May 15 10:50:22 2010
From: switch2mathan at gmail.com (MathanK)
Date: Sat, 15 May 2010 02:50:22 -1200
Subject: Is there conversion method to convert pyunicodeobject to pybyteobject?
Message-ID: <1289c71c8d7.-2177546074900212455.7511215933185914503@gmail.com>

Hi All,

A variable whose data type is PyUnicodeObject is to be assigned to varioable of PyBytesObject type 

example :

PyUnicodeObject *p = ...whatever...; 
function( (PyByteObject*p)); 

compiled and got a Bus Error.

Cheers,
Mathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From robin.garen at gmail.com  Sat May 15 10:56:31 2010
From: robin.garen at gmail.com (technocake)
Date: Sat, 15 May 2010 07:56:31 -0700 (PDT)
Subject: platform-independent image copy/paste with Tkinter?
Message-ID: 

Hi.

Is there a good way to copy from or paste to the clipboard on all
systems running python using Tkinter?
started a small road too it here:

#!/usr/bin/python
__author__="technocake"
__date__ ="$15.mai.2010 15:53:39$"

from Tkinter import *

if __name__ == "__main__":

    def displayClipboard(event):
        try:
            data = event.widget.clipboard_get(type="STRING")
        except :
            #Need a method for displaying a image here..
            data = "Image" #
        finally: #Updates the textlabel
            lbl.config(text=data)

    root = Tk()
    lbl= Label(root, width=20)
    lbl.bind("", displayClipboard) #binding to leftclick
    lbl.pack()

    root.mainloop()



From aahz at pythoncraft.com  Sat May 15 11:24:58 2010
From: aahz at pythoncraft.com (Aahz)
Date: 15 May 2010 08:24:58 -0700
Subject: Picking a license
References: 
	 <87k4rgfutu.fsf@benfinney.id.au>
	
Message-ID: 

In article ,
Stefan Behnel   wrote:
>aahz at pythoncraft.com (Aahz) writes:
>>
>> Which license you use depends partly on your political philosophy.
>
>Did they close down debian-legal, or why is this thread growing so long?

Mea culpa, mea culpa, mea maxima culpa  ;-)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From aahz at pythoncraft.com  Sat May 15 11:28:37 2010
From: aahz at pythoncraft.com (Aahz)
Date: 15 May 2010 08:28:37 -0700
Subject: Picking a license
References: 
	<4bee0df4$0$8761$c3e8da3@news.astraweb.com>
	<7bfa5457-027d-4ee1-a54f-3c0baba45a55@e21g2000vbl.googlegroups.com>
Message-ID: 

In article <7bfa5457-027d-4ee1-a54f-3c0baba45a55 at e21g2000vbl.googlegroups.com>,
Patrick Maupin   wrote:
>
>So, there are good reasons for both kinds of licenses, which I think
>everybody on the pro-permissive side has been saying all along.  Of
>course, "force" is a more inflammatory word that "obligation" in some
>contexts, and that has been used in what I would admit on my part is a
>knee-jerk reaction to my belief that "free" and "freedom" are more
>inflammatory words than "rights" in the same contexts.

Yes, exactly.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From utente at esempio.net  Sat May 15 12:08:40 2010
From: utente at esempio.net (superpollo)
Date: Sat, 15 May 2010 18:08:40 +0200
Subject: parsing XML
In-Reply-To: 
References: 
Message-ID: <4beec709$0$18653$4fafbaef@reader3.news.tin.it>

kaklis at gmail.com ha scritto:
> Hi to all, let's say we have the following Xml
> 
>   
>     17.1
>     6.4
>   
>   
>     15.5
>     7.8
>   
> 
> 
> How can i get the players name, age and height?
> DOM or SAX and how
> 
> Thanks
> Antonis

another minimal xml.etree.ElementTree solution:

 >>> print document

   
     17.1
     6.4
   
   
     15.5
     7.8
   

 >>> import xml.etree.ElementTree as ET
 >>> team = ET.XML(document)
 >>> for player in team:
...     print player.attrib["name"]
...     print player.attrib["age"]
...     print player.attrib["height"]
...     print
...
Mick Fowler
27
1.96m

Ivan Ivanovic
29
2.04m

 >>>

bye


From lie.1296 at gmail.com  Sat May 15 12:20:58 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 16 May 2010 02:20:58 +1000
Subject: Puzzled by code pages
In-Reply-To: 
References: 	<4bee7823$1@dnews.tpgi.com.au>
	
Message-ID: <4beeca46$1@dnews.tpgi.com.au>

On 05/16/10 00:12, Adam Tauno Williams wrote:
> On Sat, 2010-05-15 at 20:30 +1000, Lie Ryan wrote:
>> On 05/15/10 10:27, Adam Tauno Williams wrote:
>>> I'm trying to process OpenStep plist files in Python.  I have a parser
>>> which works, but only for strict ASCII.  However plist files may contain
>>> accented characters - equivalent to ISO-8859-2 (I believe).  For example
>>> I read in the line:
>>>>>> handle = open('file.txt', 'rb')
>>>>>> data = handle.read()
>>>>>> handle.close()
>>>>>> data
>>> '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
>>> NSFileName;\n'
>> I presume you're using Python 2.x.
> 
> Yes.  But the days of all-unicode-strings will be wonderful when it
> comes. :)
> 
>>> What is the correct way to re-encode this data into UTF-8 so I can use
>>> unicode strings, and then write the output back to ISO8859-?
>>> I can read the file using codecs as ISO8859-2, but it still doesn't seem
>>> correct.
>>>>>> handle = codecs.open('file.txt', 'rb', encoding='iso8859-2')
>>>>>> data = handle.read()
>>>>>> handle.close()
>>>>>> data
>>> u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
>>> NSFileName;\n'
>> When printing in the interactive interpreter, python uses __repr__
>> representation by default. If you want to use __str__ representation use
>> "print data" (note, your terminal must support printing unicode
>> characters); 
> 
> Using GNOME Terminal, so Unicode characters should display correctly.
> And I do see the characters when I 'cat' the file.

'cat' works because 'cat' works in bytes and doesn't try to interpret
the stream it is writing. You can tell python to output string instead
of unicode to get the same effect.

> h = codecs.open('file.txt', 'rb', encoding='iso8859-2')
> data = h.read()
> h.close()
> str(data)
> 
> 'ascii' codec can't encode characters in position 33-34: ordinal not in
> range(128)

this means either your terminal can't print unicode or python for some
reason thinks that the terminal is ascii terminal. You can encode the
string manually, e.g.:

print u'\u0102\xa0'.encode('utf-8')

or you should figure out a way to set your terminal properly so python
recognizes it as utf-8 terminal, see
http://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/

when python tries to print unicode object, python first needs to encode
that 'unicode' object into 'str'; by default python uses
sys.stdout.encoding to determine the encoding to use when printing
unicode object.

> unicode(data)
> u'    "skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" =
> NSFileName;\n'

If data is a 'unicode', this is not surprising, as 'unicode(data)'
simply returns 'data'.

> I think I'm getting close.  Parsing the file seems to work, and while
> writing it out does not error, rereading my own output fails. :(
> Possibly I'm 'accidentally' writing the output as UTF-8 and not
> ISO8859-2.  I need the internal data to be UTF-8 but read as ISO8859-2
> and rewritten back to ISO8859-2 [at least that is what I believe from
> the OpenStep files I'm seeing].

unicode string doesn't have encoding (well, python needs some encoding
to store the unicode data in RAM, but that's implementation detail).
unicode string is not a stream of bytes encoded in specific way, it's an
encoding-agnostic block of text.

> What is the 'official' way to encode something from UTF-8 to another
> code page.  I *assumed* that if I wrote a unicode stream back through:
> 
> h = codecs.open(output_filename, 'wb', encoding='iso8859-2')
> data = writer.store(defaults)
> h.write(data)
> h.close()

what's "writer.store(defaults)"? It should return a 'unicode' if you
want h.write() to work properly. Otherwise, if data is 'str', h.write
will try to decode the 'str' to 'unicode' using the default decoder
(usually ascii), then encode that 'unicode' to 'iso8859-2'.


From utente at esempio.net  Sat May 15 12:25:05 2010
From: utente at esempio.net (superpollo)
Date: Sat, 15 May 2010 18:25:05 +0200
Subject: parsing XML
In-Reply-To: <4beec709$0$18653$4fafbaef@reader3.news.tin.it>
References: 
	<4beec709$0$18653$4fafbaef@reader3.news.tin.it>
Message-ID: <4beecaf1$0$18657$4fafbaef@reader3.news.tin.it>

superpollo ha scritto:
> kaklis at gmail.com ha scritto:
>> Hi to all, let's say we have the following Xml
>> 
>>   
>>     17.1
>>     6.4
>>   
>>   
>>     15.5
>>     7.8
>>   
>> 
>>
>> How can i get the players name, age and height?
>> DOM or SAX and how
>>
>> Thanks
>> Antonis
> 
> another minimal xml.etree.ElementTree solution:
> 
>  >>> print document
> 
>   
>     17.1
>     6.4
>   
>   
>     15.5
>     7.8
>   
> 
>  >>> import xml.etree.ElementTree as ET
>  >>> team = ET.XML(document)
>  >>> for player in team:
> ...     print player.attrib["name"]
> ...     print player.attrib["age"]
> ...     print player.attrib["height"]
> ...     print
> ...
> Mick Fowler
> 27
> 1.96m
> 
> Ivan Ivanovic
> 29
> 2.04m
> 
>  >>>
> 
> bye

or, an alternative xml.dom.minidom solution:

 >>> import xml.dom.minidom as MD
 >>> team = MD.parseString(document)
 >>> players = team.getElementsByTagName("player")
 >>> for player in players:
...     print player.getAttribute("name")
...     print player.getAttribute("age")
...     print player.getAttribute("height")
...     print
...
Mick Fowler
27
1.96m

Ivan Ivanovic
29
2.04m

 >>>

bye



From travis+ml-python at subspacefield.org  Sat May 15 12:42:16 2010
From: travis+ml-python at subspacefield.org (travis+ml-python at subspacefield.org)
Date: Sat, 15 May 2010 09:42:16 -0700
Subject: Is Python a functional programming language?
In-Reply-To: 
References: 
	
Message-ID: <20100515164216.GA9146@subspacefield.org>

On Mon, May 10, 2010 at 08:45:51PM +0100, Nobody wrote:
> On Tue, 11 May 2010 00:24:22 +1200, Samuel Williams wrote:
> > Is Python a functional programming language?
> Not in any meaningful sense of the term.

LOL

> > I heard that lambdas were limited to a single expression,
> 
> Yes. In a functional language that wouldn't be a problem, as there's no
> limit to the complexity of an expression. Python's expressions are far
> more limited, which restricts what can be done with a lambda.

One very annoying thing in Python is the distinction between
statements and expressions.

Ever since learning LISP (well, Scheme) in S&ICP I find myself
frequently annoyed by this pointless distinction, started by
C (or earlier), and propogated without much thought.

Often I'll want to write a lamda that, say, prints something, or
modifies a global variable, and find that, well, it's either
impossible or beyond my interest in figuring it out.

It appears there is finally a ternary operator (for making if/else
into "expressions"):
http://en.wikipedia.org/wiki/Ternary_operation#Python
Maybe it will grow on me - it makes sense in English, but on
first glance I thought the programmer suffered from dyslexia.

To be fair, it appears that Python's whitespace-sensitive syntax sort
of precludes the "make a complex function on one line" that is typical
of languages which don't have statement/expression distinctions, but
I'm not convinced it couldn't be solved, perhaps by allowing anonymous
functions to span multiple lines, just like named functions.

> > Finally, even if Python supports functional features, is this a model that
> > is used often in client/application code?
> 
> Not really. List comprehensions are probably the most common example of
> functional idioms, but again they're limited by Python's rather limited
> concept of an expression.

Map/reduce, lambda, apply, that kind of stuff... kinda similar to
functional languages.

But "statements lack any side effects"?  No way.

In fact, a common distinction you'll see observed, but not always, is
that "statements may have side effects, expressions do not".

For some definitions of "functional language", there are no
side-effects, so there is no need for a statement which doesn't
evaluate to a value, so there is no need for a statement/expression
distinction, so everything is an expression.

You may have seen Paul Graham's other article about Python and LISP:
http://www.paulgraham.com/icad.html

Upon re-skimming it, I find myself wondering if I got the
expression/statement annoyance from his pages, or from my own
experience.  I can't remember :-) Probably it was an annoyance that I
hadn't put my finger on until he spelled it out for me, like a
splinter in my mind :-)

He obliquely references my other pet peeve, the global/class/local
distinction, completely ignoring arbitrarily-nested lexical scoping.
From what I've read in this thread, there's a recent "nonlocal"
declaration that sounds like it might accomplish something useful in
this regard.

(I still haven't figured out how he managed to use lexical closures in
 his web server to allow one web page to use another to allow the user
 to select and return a value, like a color from a color wheel, unless
 he implemented his own web server in LISP, since HTTP is stateless).

I really like Scheme's clean syntax (never learned Common LISP, sorry,
too much to remember) but frankly, I've never looked at a problem and
said, "you know, Scheme would be perfect for this".  Maybe if I was
writing a program that did optimizing transformations on abstract
syntax trees, or something.  And since Scheme has never come in handy,
I never bothered with Common LISP.  I feel similarly about ML, OCAML
and Haskell... maybe one day when I'm bored, not today, not this
project.

So in the end, I find myself using python more than anything else,
fully acknowledging its warts.  I used to admire its simplicity, but
now with decorators, iterators, generators, metaclasses, and the
proliferation of special method names, I have to wonder if that still
holds true...  certainly I understand 90+% of python programs, but
do I understand that proportion of the constructs?

PS: Why do people call LISP object-oriented?  Are they smoking crack?
    No classes, no methods, no member variables... WTF?
-- 
A Weapon of Mass Construction
My emails do not have attachments; it's a digital signature that your mail
program doesn't understand. | http://www.subspacefield.org/~travis/ 
If you are a spammer, please email john at subspacefield.org to get blacklisted.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: 

From robert.kern at gmail.com  Sat May 15 13:10:03 2010
From: robert.kern at gmail.com (Robert Kern)
Date: Sat, 15 May 2010 12:10:03 -0500
Subject: Picking a license
In-Reply-To: <4bee08f9$0$8761$c3e8da3@news.astraweb.com>
References: 
	<4bee08f9$0$8761$c3e8da3@news.astraweb.com>
Message-ID: 

On 2010-05-14 21:37 , Steven D'Aprano wrote:
> On Fri, 14 May 2010 06:42:31 -0700, Ed Keith wrote:
>
>> I am not a lawyer, but as I understand the LGPL, If I give someone
>> something that used any LGPLed code I must give them the ability to
>> relink it with any future releases of the LGPLed code. I think that
>> means that I need to give them a linker and teach them how to use it,
>> and I do not want to go there.
>
> Surely you're joking?
>
> Does this mean that if they lose their hands in an accident, you have to
> come sit at their computer and do their typing?
>
> The LGPL and GPL don't grant people "the ability" to do anything, since
> that's not within our power to grant. Some people don't want to, or
> can't, program, or don't have time. It's not like the LGPL is the bite of
> a radioactive spider that can grant superpowers. It is a licence which
> grants *permissions*.

No, the LGPL requires you to do something extra to enable your users to be able 
to relink your program. You need to provide the ability to do this, up to some 
unspecified and untested limit of reasonableness (your example is obviously 
beyond the limit of reasonableness). You can't just give them, say, a statically 
linked program and nothing else. You can't require for-fee, proprietary linkers. 
This is usually not hard to do (just give them unlinked .o or .obj files and a 
Makefile or project file), but it is *not* just a matter of granting permissions.

But you're right, you don't have to teach them how to do it.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From shepard.dl at gmail.com  Sat May 15 13:18:04 2010
From: shepard.dl at gmail.com (Dave)
Date: Sat, 15 May 2010 10:18:04 -0700 (PDT)
Subject: Local variables persist across function calls
Message-ID: <89ea77da-2ae0-41e6-b26f-1eb34bc063be@q36g2000prg.googlegroups.com>

I've been writing Python for a few years now, and tonight I ran into
something that I didn't understand. I'm hoping someone can explain
this to me. I'm writing a recursive function for generating
dictionaries with keys that consist of all permutations of a certain
set. Here's the function:


def make_perm(levels, result = {}, key = ''):
	local = key
	if levels == 1:
		for i in ['a', 'b', 'c', 'd']:
			result [local + i] = ''
	else:
		for i in ['a', 'b', 'c', 'd']:
			make_perm(levels - 1, result, local + i)
	return result


The first time I ran it, make_perm(2) does what I expected, returning
a dictionary of the form {'aa': '', 'ab':'', 'ac':'', ... }. But, if I
run make_perm(3) after that, I get a dictionary that combines the
contents of make_perm(2) with the values of make_perm(3), a dictionary
like {'aaa':'', 'aab':'', ...}. Running make_perm(2) again will return
the same result as make_perm(3) just did. It's like the local variable
is preserved across different calls to the same function. I don't
understand why this happens: "result" is not a global variable, and
accessing it outside the function generates a NameError, as it should.
After running make_perm once, printing the value of result inside the
function produces the last result returned on the first iteration.

If, however, I explicitly pass an empty dictionary into make_perm as
the second argument, the value of "result" is returned correctly. So I
have a solution to my problem, but I still don't understand why it
works. I've tried this on both Python 2.6 and Python 3.2, both in IDLE
and from the command line, and it behaves the same way. So it seems
like this is an intentional language feature, but I'm not sure exactly
why it works this way, or what's going on. Anyway, I'd appreciate it
if someone could explain this to me.


From darragh.ssa at gmail.com  Sat May 15 13:28:37 2010
From: darragh.ssa at gmail.com (Kruptein)
Date: Sat, 15 May 2010 10:28:37 -0700 (PDT)
Subject: d-cm Controll Manager
References: 
Message-ID: 

http://launchpad.net/d-cm


From edquiver at gmail.com  Sat May 15 13:29:41 2010
From: edquiver at gmail.com (Yutao Deng)
Date: Sun, 16 May 2010 01:29:41 +0800
Subject: pickle.load() all dict
Message-ID: 

Hi all:
I'm trying to learn to use Python  wrote a applet to record every day doing.
and i use the pickle
pickle.dump something to file no problem i think.
but pickle.load whith a problem. can not load all dict do my way that what i
pickle.dump().

My code:
####
import cPickle as pickle
pickle_file = open("data2","rb")
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
####
console show :
{'2010-5-23': ['1242', 'first']}
{'2010-5-24': ['1232', 'third']}
{'2010-5-25': ['211', 'second']}
{'2010-3-22': ['3211', 'fourrrr']}
{'2050-3-2': ['3990', '322']}

This is i want but that's silly. if the dict too much, then i have not
ideas.

the other way from
http://mail.python.org/pipermail/tutor/2005-July/039859.html

####
import cPickle as pickle
pickle_file = open("data2","rb")

number_of_pickles = pickle.load(pickle_file)
for n in range(number_of_pickles):
    p = pickle.load(pickle_file)
    print p
####
this way didnt work for me.

console show:
Traceback (most recent call last):
    number_of_pickles = pickle.load(pickle_file)
cPickle.UnpicklingError: invalid load key, '
'.
how do i define the range of pickle.load a file. i mean that how can i know
how many dict in the data2.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From albert at spenarnc.xs4all.nl  Sat May 15 13:49:51 2010
From: albert at spenarnc.xs4all.nl (Albert van der Horst)
Date: 15 May 2010 17:49:51 GMT
Subject: Picking a license
References: 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
Message-ID: 

In article <7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e at d27g2000yqc.googlegroups.com>,
Patrick Maupin   wrote:

>
>That is correct.  All "privileges" as you put it are merely things
>that a user can do with the code without fear of a lawsuit by the
>author, and when an author uses a permissive license, he indicates
>that the things that he could possibly find egregious enough to sue
>over are very few.  For example, if you give an Ubuntu CD to your
>friend without giving source code or a written offer of source code,
>you have violated the license on quite a few of the programs on the
>CD, but not, for example, on Python or Apache, because these licenses
>do not attempt to forbid you from doing this.

Bit this is stupid! The GPL is to accomplish a political goal,
an operating system with tools available to all, that can be
modified by anybody capable of doing so.

Enforcements not amenable to that goal will not happen.

It might surprise even RMS himself but ...
The political goal has been large and by accomplished at the expense
of great legal effort and great efforts of Linus Torvalds c.s. Without
the GPL Linux would not exist -- except in the form of an academic
exercise -- and neither would gcc, so neither would Python.
By proxy I estimate that none of the software with a permissive
license you mention would not be available.

You seem to imply that RMS is a nasty guy.
Yes, RMS is a nasty guy. All warriors are! Get in his
way and you're blasted. But some warriors fight for a right
cause ... This really has nothing to do with anything.
The meek will inherit the world, yes, but only after
the second coming.

>
>Regards,
>Pat

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst



From aahz at pythoncraft.com  Sat May 15 13:52:38 2010
From: aahz at pythoncraft.com (Aahz)
Date: 15 May 2010 10:52:38 -0700
Subject: Is Python a functional programming language?
References: 
	
	
Message-ID: 

In article ,
  wrote:
>
>One very annoying thing in Python is the distinction between
>statements and expressions.

One extremely valuable thing in Python is the distinction between
statements and expressions.

In fact, given the semantic similarity between Python and Lisp, I would
argue that Python having the distinction is partly responsible for its
popularity.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From alfps at start.no  Sat May 15 13:56:33 2010
From: alfps at start.no (Alf P. Steinbach)
Date: Sat, 15 May 2010 19:56:33 +0200
Subject: Local variables persist across function calls
In-Reply-To: <89ea77da-2ae0-41e6-b26f-1eb34bc063be@q36g2000prg.googlegroups.com>
References: <89ea77da-2ae0-41e6-b26f-1eb34bc063be@q36g2000prg.googlegroups.com>
Message-ID: 

On 15.05.2010 19:18, * Dave:
> I've been writing Python for a few years now, and tonight I ran into
> something that I didn't understand. I'm hoping someone can explain
> this to me. I'm writing a recursive function for generating
> dictionaries with keys that consist of all permutations of a certain
> set. Here's the function:
>
> 
> def make_perm(levels, result = {}, key = ''):
> 	local = key
> 	if levels == 1:
> 		for i in ['a', 'b', 'c', 'd']:
> 			result [local + i] = ''
> 	else:
> 		for i in ['a', 'b', 'c', 'd']:
> 			make_perm(levels - 1, result, local + i)
> 	return result
> 

I bet this is a FAQ, but I don't know where the FAQ is (probably at python.org?).

The defaults for formal parameters are evaluated /once/, namely at function 
definition time, when the execution first passes through the definition.

And what you're doing is to update that original default 'result' dictionary.

To achieve the effect that you apparently want you can do


   def make_perm( levels, result = None, key = '' )
       if result is None: result = {}  # Evaluated for each call.
       # Blah blah, the rest


There are also other ways.


Cheers & hth.,

- Alf

-- 
blog at 


From clp2 at rebertia.com  Sat May 15 14:01:03 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Sat, 15 May 2010 11:01:03 -0700
Subject: Local variables persist across function calls
In-Reply-To: <89ea77da-2ae0-41e6-b26f-1eb34bc063be@q36g2000prg.googlegroups.com>
References: <89ea77da-2ae0-41e6-b26f-1eb34bc063be@q36g2000prg.googlegroups.com>
Message-ID: 

On Sat, May 15, 2010 at 10:18 AM, Dave  wrote:
> I've been writing Python for a few years now, and tonight I ran into
> something that I didn't understand. I'm hoping someone can explain
> this to me. I'm writing a recursive function for generating
> dictionaries with keys that consist of all permutations of a certain
> set. Here's the function:
>
> 
> def make_perm(levels, result = {}, key = ''):
> ? ? ? ?local = key
> ? ? ? ?if levels == 1:
> ? ? ? ? ? ? ? ?for i in ['a', 'b', 'c', 'd']:
> ? ? ? ? ? ? ? ? ? ? ? ?result [local + i] = ''
> ? ? ? ?else:
> ? ? ? ? ? ? ? ?for i in ['a', 'b', 'c', 'd']:
> ? ? ? ? ? ? ? ? ? ? ? ?make_perm(levels - 1, result, local + i)
> ? ? ? ?return result
> 
>
> The first time I ran it, make_perm(2) does what I expected, returning
> a dictionary of the form {'aa': '', 'ab':'', 'ac':'', ... }. But, if I
> run make_perm(3) after that, I get a dictionary that combines the
> contents of make_perm(2) with the values of make_perm(3), a dictionary
> like {'aaa':'', 'aab':'', ...}. Running make_perm(2) again will return
> the same result as make_perm(3) just did. It's like the local variable
> is preserved across different calls to the same function. I don't
> understand why this happens: "result" is not a global variable, and
> accessing it outside the function generates a NameError, as it should.
> After running make_perm once, printing the value of result inside the
> function produces the last result returned on the first iteration.
>
> If, however, I explicitly pass an empty dictionary into make_perm as
> the second argument, the value of "result" is returned correctly. So I
> have a solution to my problem, but I still don't understand why it
> works. I've tried this on both Python 2.6 and Python 3.2, both in IDLE
> and from the command line, and it behaves the same way. So it seems
> like this is an intentional language feature, but I'm not sure exactly
> why it works this way, or what's going on. Anyway, I'd appreciate it
> if someone could explain this to me.

Default argument values are only evaluated *once*, at
function-definition time, *not* every time the function is called. So
whenever you call make_perm() without specifying the `result`
argument, `result` will get *the same dictionary* as its value every
time, and modifications to that dictionary will thus persist across
calls.

When a default argument value is of a mutable type such as a
dictionary, the following idiom is used to get around the
aforementioned behavior:

def make_perm(levels, result = None, key = ''):
    if result is None:
        result = {}
    #rest same as before...

This ensures `result` gets a fresh dictionary every time.

See also the "Important warning" on
http://docs.python.org/tutorial/controlflow.html#default-argument-values

Cheers,
Chris
--
I'm not a fan of this behavior either.
http://blog.rebertia.com


From pmaupin at gmail.com  Sat May 15 14:09:29 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 11:09:29 -0700 (PDT)
Subject: Picking a license
References: 
	<1999a08d-dc3d-4ed6-94ac-d9dd9d3a494f@37g2000yqm.googlegroups.com>
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com> 
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638ae@q30g2000yqd.googlegroups.com> 
	<039c264d-e0d0-41c9-bdfd-56a4dce29cb7@m31g2000pre.googlegroups.com> 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com> 
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	<7c3bc297-a88e-4fa9-b457-52425a5703d9@42g2000prb.googlegroups.com> 
	 
	<4bece8de$0$8761$c3e8da3@news.astraweb.com>
	
Message-ID: <12d81b67-6ab8-454f-851d-6a32b3bfa529@f14g2000vbn.googlegroups.com>

On May 14, 8:04?am, Ethan Furman  wrote:
> Steven D'Aprano wrote:

>> You've never had to recode something because it was nominally available
>> under a proprietary licence that you (or your client) was unwilling to
>> use? Lucky you!

> Steven, did you actually read what he wrote? ?If you did, why would you
> say something so stupid?

Well, in Steven's defense, my literal words "... labor that could have
been spent elsewhere if someone else had done something differently.
The only time that comes into play in my programming life is when I
have to recode something that is nominally available under the GPL..."
could easily be taken to mean that I have never had to recode
something that was under a proprietary license.

In truth most of what any of us write is probably very similar to
stuff that others have written, so taken in a very literal sense, yes,
obviously, there are several times that I have had to recode
proprietary software.  But I was responding to Brendan's "broken
window" analogy, and, rightly or wrongly, I *assumed* he was only
referring to software that was free *at one time* but then was somehow
taken out of the commons.  To my knowledge, I've never recoded such
software, and to the extent that anybody might be suggesting that
*all* software belongs in an easily-accessible commons and that nobody
should ever have to recode anything -- well, I could probably be
seduced by the Utopian vision, but I strongly reject that the sort of
rights-pooling mandated by the GPL is the single way to get there.

If everybody believes in the Utopian vision, the GPL is rendered
unnecessary, and to the extent that some people *really* don't believe
in the Utopian vision, the wording of the GPL makes a gentle
transition from proprietary to free difficult for programmers with
feet in both camps.  However, the GPL *does* provide a core focal
point for the actual Utopian vision itself, and this does serve a
useful purpose.  Personally, I think we are gradually lurching towards
the Utopian vision, and probably at a faster pace than if we only had
the GPL or if we only had permissive licenses.  I think even RMS
believes this; as a matter of practicality he will suggest the LGPL or
even permissive licensing under some circumstances.

Regards,
Pat


From awilliam at whitemice.org  Sat May 15 14:37:22 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sat, 15 May 2010 14:37:22 -0400
Subject: Reading XML namespaces
Message-ID: <1273948642.2322.10.camel@linux-yu4c.site>

Say I have an XML document that begins with:



...

How can one access the namespaces define in this node?  I've done a fair
amount of XML in Python, but haven't been able to uncover the call to
enumerate the namespaces.

Primarily I am using etree from lxml.
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba



From pmaupin at gmail.com  Sat May 15 14:46:57 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 11:46:57 -0700 (PDT)
Subject: Picking a license
References: 
	<5f2abe7a-fb91-4a2f-bfa3-9492e5761fc5@e1g2000yqe.googlegroups.com>
	<75a27ef5-6a50-4ed2-864c-6a2a2e4638
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	
Message-ID: 

On May 15, 12:49?pm, Albert van der Horst 
wrote:
> In article <7bdce8a7-bf7d-4f1f-bc9d-1eca26974... at d27g2000yqc.googlegroups.com>,
> Patrick Maupin ? wrote:
> 
>
> >That is correct. ?All "privileges" as you put it are merely things
> >that a user can do with the code without fear of a lawsuit by the
> >author, and when an author uses a permissive license, he indicates
> >that the things that he could possibly find egregious enough to sue
> >over are very few. ?For example, if you give an Ubuntu CD to your
> >friend without giving source code or a written offer of source code,
> >you have violated the license on quite a few of the programs on the
> >CD, but not, for example, on Python or Apache, because these licenses
> >do not attempt to forbid you from doing this.
>
> Bit this is stupid! The GPL is to accomplish a political goal,
> an operating system with tools available to all, that can be
> modified by anybody capable of doing so.

Sure.

> Enforcements not amenable to that goal will not happen.

Absolutely agreed.  I have no real problem with that.  I *do* have a
problem with some of the faithful acting like I'm completely wrong and
trying to actively mislead about how the license works, but then I
guess that's par for the course for politics.

> It might surprise even RMS himself but ...
> The political goal has been large and by accomplished at the expense
> of great legal effort and great efforts of Linus Torvalds.

Agreed.

> c.s. Without
> the GPL Linux would not exist -- except in the form of an academic
> exercise

Not sure that's true.  Linus would have picked *some* license.
Possibly something like the BSD.  He started development using Minix,
which certainly wasn't licensed freely, and which was first released 2
years before the GPL, so the GPL was not instrumental in providing his
first development environment.  He might have had to choose a
different compiler if GCC weren't available, but there was a compiler
with Unix.  I can believe that the GPL helped Linux gain some momentum
it wouldn't have had otherwise, but I reject your absolute assertion.

> -- and neither would gcc,

Well, not gcc itself, but there were compilers around...

> so neither would Python.

That I *completely* disagree with.  Python was written for the amoeba
O/S, which was in existence and had compilers a good 3 or 4 years
before the first release of gcc.

> By proxy I estimate that none of the software with a permissive
> license you mention would not be available.

I disagree.  If Linux weren't around, MS would not be the sole
winner.  Free development would have coalesced around one of the BSDs
(which in absolute numbers are still pretty big projects right now, in
any case, just lacking the mindshare of Linux).  As apache and other
projects have shown, the propensity of the few to try to lock things
up can easily be overcome with sheer numbers and willpower -- no
reciprocal license required.

> You seem to imply that RMS is a nasty guy.

I think we both agree that people who make history are often
unreasonable.  I really don't have a problem with that, but I do have
a problem with apologists claiming it isn't so in his case.

> Yes, RMS is a nasty guy. All warriors are! Get in his
> way and you're blasted.

So maybe you're not one of the ones I have a problem with.

> But some warriors fight for a right
> cause ... This really has nothing to do with anything.
> The meek will inherit the world, yes, but only after
> the second coming.

If you read all the posts carefully, you will see that people arguing
that sometimes permissive licenses are the right ones also allow a
place for the GPL.  It is only some of the GPL adherents who accuse
some of the "non-believers" of acting duplicitously, with malice, of
being against "freedom".  I reject that characterization of myself,
and when people accuse me of this, I mentally place them in the
category of "religious nutter".  Once I have placed someone in that
category, it is sometimes hard for me to respond civilly to them,
especially when they write something stupid.  I have not yet placed
you in that category, but I do categorically reject your
interpretation of some of the relevant historical events.

Regards,
Pat


From metolone+gmane at gmail.com  Sat May 15 15:31:26 2010
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Sat, 15 May 2010 12:31:26 -0700
Subject: Puzzled by code pages
References: <4bee7823$1@dnews.tpgi.com.au>
	<1273932760.3929.18.camel@linux-yu4c.site>
Message-ID: 


"Adam Tauno Williams"  wrote in message 
news:1273932760.3929.18.camel at linux-yu4c.site...
> On Sat, 2010-05-15 at 20:30 +1000, Lie Ryan wrote:
>> On 05/15/10 10:27, Adam Tauno Williams wrote:
 [snip]

> Yep.  But in the interpreter both unicode() and repr() produce the same
> output.  Nothing displays the accented character.
>
> h = codecs.open('file.txt', 'rb', encoding='iso8859-2')
> data = h.read()
> h.close()
> str(data)

Here you are correctly reading an iso8859-2-encoded file and converting it 
to Unicode.

Try "print data".  "str(data)" converts from Unicode strings to byte 
strings, but only uses the default encoding, which is 'ascii'.  print will 
use the stdout encoding of your terminal, if known.   Try these commands on 
your system (mine is Windows XP):

>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> sys.stdout.encoding
'cp437'

You should only attempt to "print" Unicode strings or byte strings encoded 
in the stdout encoding.  Printing byte strings in any other encoding will 
often print garbage.

[snip]
> I think I'm getting close.  Parsing the file seems to work, and while
> writing it out does not error, rereading my own output fails. :(
> Possibly I'm 'accidentally' writing the output as UTF-8 and not
> ISO8859-2.  I need the internal data to be UTF-8 but read as ISO8859-2
> and rewritten back to ISO8859-2 [at least that is what I believe from
> the OpenStep files I'm seeing].

"internal data" is Unicode, not UTF-8.  Unicode is the absence of an 
encoding (Python uses UTF-16 or UTF-32 internally, but that is an 
implementation detail).  UTF-8 is a byte-encoding.

If you actually need the internal data as UTF-8 (maybe you are working with 
a library that works with UTF-8 strings, then:

>>> f = codecs.open("in.txt", 'rb', encoding="iso8859-2")
>>> s = f.read()  # s is a Unicode string.
>>> s = s.encode('utf-8') # now s is a UTF-8 byte string
>>> f.close()

(process data as UTF-8 here).

>>> s = s.decode('utf-8') # s is Unicode again.
>>> f2 = codecs.open("out.txt", 'wb', encoding="iso8859-2")
>>> f2.write(s)
>>> f2.close()

Note you *decode* byte strings to Unicode and *encode* Unicode into byte 
strings.

-Mark




From paul at boddie.org.uk  Sat May 15 15:59:06 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Sat, 15 May 2010 12:59:06 -0700 (PDT)
Subject: Picking a license
References: 
	
Message-ID: 

On 15 Mai, 04:20, Lawrence D'Oliveiro  wrote:
> In message , Paul Boddie wrote:
> > Although people can argue that usage of the GPL prevents people from
> > potentially contributing because they would not be able to sell
> > proprietary versions of the software ...
>
> It doesn?t prevent them from selling proprietary versions of their own
> contributions, any more than any other licence does.

I already mentioned this several days ago, upon which it was regarded
as not addressing some complaint or other. You own your own work, but
if you release that work to someone and it makes use of a GPL-licensed
work, then the user must be able to deal with the work according to
the terms of the GPL.

> The fact that their contribution may not be much use without the rest of
> that GPL?d code is entirely another matter. It was their choice to build on
> the work of others; they could have reinvented it from scratch themselves.

Yes. I mentioned this before: WebKit (or probably more specifically
WebCore) is an example of both originally building on GPL-licensed
code, and also building on permissively licensed code. The code
specifically belonging to WebKit and its predecessor was never GPL-
licensed itself.

My point about a platform vendor choosing to undertake the multiple
man-year task of rewriting an existing, mature GPL-licensed library
purely so that people are then able to sell proprietary software is
grounded in the observation that if people were content to make their
source code available for their products on such a platform, the GPL
would be a satisfactory basis for such activities: they own their own
code, can license it permissively (but compatibly with the GPL), and
the sources remain available; they don't need a "weaker" copyleft
licence or a permissive licence to do any of this.

Now, since it is unlikely that a business is going to spend money on a
project that doesn't change the situation in any practical sense -
that people are content with having their source code available to
their users, but now (after several man-years of effort) can link to a
permissively licensed (or weak-copyleft licensed) library - the actual
motivation emerges for choosing the LGPL or a permissive licence as
the basis for the platform's licensing: to permit the only thing that
the GPL does not, which is to let people release their software and
not commit to offering the source code; to permit, in effect, the
delivery of proprietary software.

Any claim that a licensing change is needed merely to let people
develop open source applications on the platform is dishonest,
especially as the "about" page for PySide spells out the licensing
objective. Take away the proprietary software requirement and you
might as well use the GPL.

Paul


From john at castleamber.com  Sat May 15 16:22:43 2010
From: john at castleamber.com (John Bokma)
Date: Sat, 15 May 2010 15:22:43 -0500
Subject: Picking a license
References: 
	
	
Message-ID: <87bpcgx6cs.fsf@castleamber.com>

Paul Boddie  writes:

> especially as the "about" page for PySide spells out the licensing
> objective. Take away the proprietary software requirement and you
> might as well use the GPL.

Thank you for mentioning PySide, I wasn't aware of this project.

-- 
John Bokma                                                               j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development


From stefan_ml at behnel.de  Sat May 15 16:29:49 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 15 May 2010 22:29:49 +0200
Subject: Reading XML namespaces
In-Reply-To: <1273948642.2322.10.camel@linux-yu4c.site>
References: <1273948642.2322.10.camel@linux-yu4c.site>
Message-ID: 

Adam Tauno Williams, 15.05.2010 20:37:
> Say I have an XML document that begins with:
>
> 
> 
> ...
>
> How can one access the namespaces define in this node?  I've done a fair
> amount of XML in Python, but haven't been able to uncover the call to
> enumerate the namespaces.
>
> Primarily I am using etree from lxml.

What do you need the namespaces for?

Stefan



From ksa.908 at gmail.com  Sat May 15 16:37:38 2010
From: ksa.908 at gmail.com (Mr.Ss)
Date: Sat, 15 May 2010 13:37:38 -0700 (PDT)
Subject: pass xxx site  ;0
Message-ID: <29d0a789-0e82-483e-b633-30242da6293e@u7g2000vbq.googlegroups.com>

pass xxx site

http://www.2shared.com/uploadComplete.jsp?sId=ISfomojyvBaVf129


From ksa.908 at gmail.com  Sat May 15 16:38:46 2010
From: ksa.908 at gmail.com (Mr.Ss)
Date: Sat, 15 May 2010 13:38:46 -0700 (PDT)
Subject: pass xxx site 2  ;0
Message-ID: 

pass xxx site

http://www.2shared.com/file/MqzpLfxz/pass_xxx_site.html


From awilliam at whitemice.org  Sat May 15 16:40:59 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sat, 15 May 2010 16:40:59 -0400
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>
	
Message-ID: <1273956059.4023.0.camel@linux-yu4c.site>

On Sat, 2010-05-15 at 22:29 +0200, Stefan Behnel wrote:
> Adam Tauno Williams, 15.05.2010 20:37:
> > Say I have an XML document that begins with:
> > 
> > 
> > How can one access the namespaces define in this node?  I've done a fair
> > amount of XML in Python, but haven't been able to uncover the call to
> > enumerate the namespaces.
> > Primarily I am using etree from lxml.
> What do you need the namespaces for?

One needs to know the defined namespace in order to perform xpath
operations.



From stefan_ml at behnel.de  Sat May 15 16:58:06 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 15 May 2010 22:58:06 +0200
Subject: Reading XML namespaces
In-Reply-To: <1273956059.4023.0.camel@linux-yu4c.site>
References: <1273948642.2322.10.camel@linux-yu4c.site>	
	<1273956059.4023.0.camel@linux-yu4c.site>
Message-ID: 

Adam Tauno Williams, 15.05.2010 22:40:
> On Sat, 2010-05-15 at 22:29 +0200, Stefan Behnel wrote:
>> Adam Tauno Williams, 15.05.2010 20:37:
>>> Say I have an XML document that begins with:
>>> 
>>> 
>>> How can one access the namespaces define in this node?  I've done a fair
>>> amount of XML in Python, but haven't been able to uncover the call to
>>> enumerate the namespaces.
>>> Primarily I am using etree from lxml.
>> What do you need the namespaces for?
>
> One needs to know the defined namespace in order to perform xpath
> operations.

Well, yes, but unless you already know the namespace (URI), you can't know 
what the tag you find signifies in the first place.

Unless, obviously, you are confusing namespaces with namespace prefixes. 
But you don't need to know the prefixes for XPath.

Does this help?

http://codespeak.net/lxml/xpathxslt.html#namespaces-and-prefixes

Stefan



From pmaupin at gmail.com  Sat May 15 16:59:30 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 13:59:30 -0700 (PDT)
Subject: Picking a license
References: 
	
	
Message-ID: <1dbd201e-2111-4625-9084-3213d64f609b@c11g2000vbe.googlegroups.com>

On May 15, 2:59?pm, Paul Boddie  wrote:

[Rest of the post, that contains points previously debated and well-
refuted, snipped]

> Any claim that a licensing change is needed merely to let people
> develop open source applications on the platform is dishonest,

See, there you go again, impugning the motives and character of
others.  Is it really that surprising that sometimes others get
annoyed by this and start to assume things about your personality that
you disagree with?

> especially as the "about" page for PySide spells out the licensing
> objective.

Yes, it does: "PySide is licensed under the LGPL version 2.1 license,
allowing both Free/Open source software and proprietary software
development."

> Take away the proprietary software requirement and you
> might as well use the GPL.

You obviously agree that PySide was coded as a direct replacement for
PyQt, for licensing reasons, so certainly there's a perception that
*something* is wrong with PyQt's license.  Let's see what the PyQt
license page has to say about it:

PyQt is available under the following licenses.

    * GNU General Public License v2
    * GNU General Public License v3
    * PyQt Commercial License

Hmm, the only thing that PySide seems to allow that is missing from
this list seems to be the "O" in "FOSS".  But of course, you already
knew that, because I already explained it, and as you've told me that
you read and think about everything very carefully, obviously your
objective in repeating this nonsense is to mislead and confuse.

Regards,
Pat


From awilliam at whitemice.org  Sat May 15 17:04:06 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sat, 15 May 2010 17:04:06 -0400
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>
	
	<1273956059.4023.0.camel@linux-yu4c.site>
	
Message-ID: <1273957446.4023.6.camel@linux-yu4c.site>

On Sat, 2010-05-15 at 22:58 +0200, Stefan Behnel wrote:
> Adam Tauno Williams, 15.05.2010 22:40:
> > On Sat, 2010-05-15 at 22:29 +0200, Stefan Behnel wrote:
> >> Adam Tauno Williams, 15.05.2010 20:37:
> >>> Say I have an XML document that begins with:
> >>> 
> >>> 
> >>> How can one access the namespaces define in this node?  I've done a fair
> >>> amount of XML in Python, but haven't been able to uncover the call to
> >>> enumerate the namespaces.
> >>> Primarily I am using etree from lxml.
> >> What do you need the namespaces for?
> > One needs to know the defined namespace in order to perform xpath
> > operations.
> Well, yes, but unless you already know the namespace (URI), you can't know 
> what the tag you find signifies in the first place.
> Unless, obviously, you are confusing namespaces with namespace prefixes. 
> But you don't need to know the prefixes for XPath.
> Does this help?
> http://codespeak.net/lxml/xpathxslt.html#namespaces-and-prefixes

I know that.  I'm getting an XML document and an xpath and need to
execute it.  But i have to tell xpath via namespaces= the prefixes &
namespaces; so I need to get that data out of the document.   

"If your XPath expression uses namespace prefixes, you must define them
in a prefix mapping"
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba



From sjmachin at lexicon.net  Sat May 15 17:07:20 2010
From: sjmachin at lexicon.net (John Machin)
Date: Sat, 15 May 2010 21:07:20 +0000 (UTC)
Subject: Puzzled by code pages
References: <1273883238.3929.8.camel@linux-yu4c.site>
	<1273883923.3929.10.camel@linux-yu4c.site>
Message-ID: 

Adam Tauno Williams  whitemice.org> writes:

> On Fri, 2010-05-14 at 20:27 -0400, Adam Tauno Williams wrote:
> > I'm trying to process OpenStep plist files in Python.  I have a parser
> > which works, but only for strict ASCII.  However plist files may contain
> > accented characters - equivalent to ISO-8859-2 (I believe).  For example
> > I read in the line:

> > '    "skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" =
> > NSFileName;\n'
> > What is the correct way to re-encode this data into UTF-8 so I can use
> > unicode strings, and then write the output back to ISO8859-?

> Buried in the parser is a str(...) call.  Replacing that with
> unicode(...) and now the OpenSTEP plist parser is working with Italian
> plists.

Some observations:

Italian text is much more likely to be encoded in ISO-8859-1 than ISO-8859-2.
The latter covers eastern European languages (e.g. Polish, Czech, Hungarian)
that use the Latin alphabet with many "decorations" not found in western 
alphabets.

Let's look at the 'localit\xc3\xa0' example. Using ISO-8859-2, that decodes to
u'localit\u0102\xa0'. The second-last character is LATIN CAPITAL LETTER A WITH
BREVE (according to unicodedata.name()). The last character is NO-BREAK SPACE.
Doesn't look like an Italian word to me.

However, using UTF-8, that decodes to u'localit\xe0'. The last character is
LATIN SMALL LETTER A WITH GRAVE. Looks like a plausible Italian word to me. Also
to Wikipedia: "A localit? (literally "locality"; plural localit?) is the name
given in Italian administrative law to a type of territorial subdivision of a
comune ..."

Conclusions:

It's worth closely scrutinising "accented characters - equivalent to ISO-8859-2
(I believe)". Which variety of "OpenStep plist files" are you looking at:
NeXTSTEP, GNUstep, or MAC OS X? If the latter, it's evidently an XML document,
and you should be letting the XML parser decode it for you and in any case as an
XML document it's most likely UTF-8, not ISO-8859-2.

It's worth examining your definition of "working".




From diazona at ellipsix.net  Sat May 15 17:13:10 2010
From: diazona at ellipsix.net (David Zaslavsky)
Date: Sat, 15 May 2010 17:13:10 -0400
Subject: Human word reader
In-Reply-To: 
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
	
Message-ID: <201005151713.11373.diazona@ellipsix.net>

Here's my take on that:

 loc = re.search('for\s+(\w+)', string).group(1)

Not much different, really, but it does allow for multiple spaces (\s+) as 
well as requiring at least one character in the word (\w+), and I use a 
matching group to extract the location directly instead of splitting the 
string "by hand".

:) David

On Saturday 15 May 2010 8:38:01 am Xavier Ho wrote:
> On Sat, May 15, 2010 at 9:32 PM, timo verbeek 
wrote:
> > On May 15, 1:02 pm, timo verbeek  wrote:
> > Place starts always with for
> 
> Okay, much better.
> 
> Given that constraint, it looks like regular expression can do the job. I'm
> not very experienced with regex, though.
> 
> \w* matches a whole word composed of letters and numbers by default.
> 
> >>> result = re.search('for \w*', 'Give me the weather for London please.')
> >>> result.group()
> 
> 'for London'
> 
> >>> result.group().split()[1]
> 
> 'London'
> 
> Cheers,
> Xav
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part.
URL: 

From stefan_ml at behnel.de  Sat May 15 17:25:33 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 15 May 2010 23:25:33 +0200
Subject: Reading XML namespaces
In-Reply-To: <1273957446.4023.6.camel@linux-yu4c.site>
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>	
	<1273957446.4023.6.camel@linux-yu4c.site>
Message-ID: 

Adam Tauno Williams, 15.05.2010 23:04:
> On Sat, 2010-05-15 at 22:58 +0200, Stefan Behnel wrote:
>> Adam Tauno Williams, 15.05.2010 22:40:
>>> On Sat, 2010-05-15 at 22:29 +0200, Stefan Behnel wrote:
>>>> Adam Tauno Williams, 15.05.2010 20:37:
>>>>> Say I have an XML document that begins with:
>>>>> 
>>>>> 
>>>>> How can one access the namespaces define in this node?  I've done a fair
>>>>> amount of XML in Python, but haven't been able to uncover the call to
>>>>> enumerate the namespaces.
>>>>> Primarily I am using etree from lxml.
>>>> What do you need the namespaces for?
>>> One needs to know the defined namespace in order to perform xpath
>>> operations.
>> Well, yes, but unless you already know the namespace (URI), you can't know
>> what the tag you find signifies in the first place.
>> Unless, obviously, you are confusing namespaces with namespace prefixes.
>> But you don't need to know the prefixes for XPath.
>> Does this help?
>> http://codespeak.net/lxml/xpathxslt.html#namespaces-and-prefixes
>
> I know that.  I'm getting an XML document and an xpath and need to
> execute it.  But i have to tell xpath via namespaces= the prefixes&
> namespaces; so I need to get that data out of the document.

Ah, you didn't provide that information in your initial post. So you 
control neither the document nor the XPath expression, right? Can't you get 
the namespace-prefix mapping from your user? After all, he/she is the only 
one who knows the meaning of the XPath expression. I'd just reject any 
expression with an undefined prefix.

BTW, I'm still not sure I understand your problem. Could you provide some 
more details?

Stefan



From martin at v.loewis.de  Sat May 15 17:37:10 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sat, 15 May 2010 23:37:10 +0200
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>
	
Message-ID: <4BEF1406.7010205@v.loewis.de>

> BTW, I'm still not sure I understand your problem. Could you provide
> some more details?
>

Wouldn't it be easier if you told the OP how to access the prefix
mappings in lxml etree, or, if this was actually not possible, admitted
that it is actually not possible?

FWIW, in the DOM, you look at all attributes of an element node, and
search for those whose namespace is "http://www.w3.org/2000/xmlns/"

In SAX, you watch the startPrefixMapping events.

Regards,
Martin


From martin at v.loewis.de  Sat May 15 17:42:43 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sat, 15 May 2010 23:42:43 +0200
Subject: Puzzled by code pages
In-Reply-To: 
References: <1273883238.3929.8.camel@linux-yu4c.site>	<1273883923.3929.10.camel@linux-yu4c.site>
	
Message-ID: <4BEF1553.8020706@v.loewis.de>


> Conclusions:
> 
> It's worth closely scrutinising "accented characters - equivalent to ISO-8859-2
> (I believe)". Which variety of "OpenStep plist files" are you looking at:
> NeXTSTEP, GNUstep, or MAC OS X? If the latter, it's evidently an XML document,
> and you should be letting the XML parser decode it for you and in any case as an
> XML document it's most likely UTF-8, not ISO-8859-2.
> 
> It's worth examining your definition of "working".

I came to the same conclusions after reading the OP's article.

Regards,
Martin


From awilliam at whitemice.org  Sat May 15 17:43:53 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sat, 15 May 2010 17:43:53 -0400
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>
		<1273956059.4023.0.camel@linux-yu4c.site>
	
	<1273957446.4023.6.camel@linux-yu4c.site>
	
Message-ID: <1273959833.4023.13.camel@linux-yu4c.site>

On Sat, 2010-05-15 at 23:25 +0200, Stefan Behnel wrote:
> Ah, you didn't provide that information in your initial post. So you 
> control neither the document nor the XPath expression, right? 

Correct.

> Can't you get the namespace-prefix mapping from your user? 

Nope. Or they are not going to be expecting to have to [since this works
just fine in Java, which for this feature we are pretty much porting
from].

> After all, he/she is the only one who knows the meaning of the XPath expression. 

???  The namespaces are embedded in the document.  Personally I find it
odd I have to tell xpath about the namespace of the document it is a
$*&@(*& method of.

> I'd just reject any expression with an undefined prefix.

Which I'm okay with;  whether the prefix is undefined can be determined
from the document!

> BTW, I'm still not sure I understand your problem. Could you provide some 
> more details?

This is an action in a workflow action (business process modeling).  It
has an input message of an XML document and a parameter of an xpath;  it
invokes a subordinate action [think: foreach] for each node resulting
from the expression.

-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba



From paul at boddie.org.uk  Sat May 15 18:03:53 2010
From: paul at boddie.org.uk (Paul Boddie)
Date: Sat, 15 May 2010 15:03:53 -0700 (PDT)
Subject: Picking a license
References: 
	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>
	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com> 
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com> 
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com> 
	 
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com> 
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com> 
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com> 
	 
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com> 
	<47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com> 
	
Message-ID: <9c23d9ef-6ddc-4b04-a92a-9aa887411eb4@i31g2000vbt.googlegroups.com>

On 15 Mai, 03:46, Patrick Maupin  wrote:
> On May 14, 6:52?pm, Paul Boddie  wrote:
> > And suggesting that people have behavioural disorders ("Or because
> > have OCD?") might be a source of amusement to you, or may be a neat
> > debating trick in certain circles you admire, but rest assured that I
> > am neither amused nor impressed, nor are others likely to be.
>
> That was in an honest response to a question you asked "Really, if at
> this point you think I'm playing games with you." where I explained
> that I don't know what to think, because often, when you claimed to be
> addressing my point, you would bring up other red herrings and spend
> more time on those, and often assign positions to me that I never
> took.

You can spare us the excuses. As I said, I was attempting to be
thorough and to explore all possible means of distribution, not least
because this was not your original point - you were originally upset
about Mr Finney's remark, which you still don't accept, but there's
probably no convincing you now - and were then upset at the FSF
definition of a work "based on" or derived from another, leading you
to talk about various strategies for defending potential GPL
violations in the course of copyright infringement litigation. At this
point, it isn't unreasonable to think that you will think of some
other objection to the GPL which you will then have everyone explore.

I have pointed out at least once the section of the GPLv3 which could
reasonably permit someone to receive a binary distribution and there
not be an immediate licence violation, plus an FAQ entry which more or
less addresses the very situation you describe, and I even provided a
link to a discussion of these very issues on the debian-legal mailing
list. You can repeat as often as you like that you don't believe it,
but I have explained my understanding of precisely the "giving CD to a
friend" situation. To summarise: your friend gets the sources from the
same place as the binaries, which is from you. (The SFLC document
seems to treat section 6(d) of GPLv3 as being about Internet
distribution, but given that the term "network server" is only
mentioned after two sentences, and only then in the conditional form,
I regard the FAQ entry I referred to as offering relevant guidance,
and even others [*] have considered the text to be subject to similar
interpretation.)

[*] http://www.gerv.net/hacking/gplv3/draft3/

For the GPLv2 the requirement of a written offer appears to be more
dominant, and I believe the physical media actually shipped by Ubuntu
is accompanied by such an offer. If Ubuntu encourages others to share
media (produced in whichever fashion) or software without any written
offer then it is, as I remarked before, a matter that should be
discussed with them. Yes, it is unfortunate that the obligations are
not communicated, and that is one reason why there is a successor to
that licence, but it merely indicates that the balance of obligation
and tolerance in the licence, maintained without enabling the
widespread and malicious circumvention of the licence, is difficult to
achieve. It doesn't invalidate the intent of the licence, and if
anything it validates the adoption of GPLv3 in preference to GPLv2.

[...]

> (BTW, IMO this was one of your better posts in terms of tone and being
> on-point, etc., and I appreciate that.)

As I said before, spare me the condescension. Making a remark that
someone has a behavioural disorder - a matter, whether true or not,
that should have no influence on the course of any discussion -
especially when that person has attempted to provide explanations for
every quibble spontaneously raised over the course of several days,
not only indicates a certain level of hypocrisy, but it indicates that
as far as you are concerned any remark about a person's mental health
or well-being is fair game if it serves to belittle that person's
standing and ridicule what that person has written.

Paul


From tjreedy at udel.edu  Sat May 15 18:08:21 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Sat, 15 May 2010 18:08:21 -0400
Subject: Is Python a functional programming language?
In-Reply-To: <20100515164216.GA9146@subspacefield.org>
References: 	
	<20100515164216.GA9146@subspacefield.org>
Message-ID: 

On 5/15/2010 12:42 PM, travis+ml-python at subspacefield.org wrote:

> One very annoying thing in Python is the distinction between
> statements and expressions.

GvR regards it as a feature, claiming that research in the 1980s showed 
that the syntactic heterogeneity aided comprehension. I believe this is 
true for me.

> Ever since learning LISP (well, Scheme) in S&ICP I find myself
> frequently annoyed by this pointless distinction,

You have missed the very important distinction generally reflected in 
the statement/expression divide. Some code is meant to be evaluated 
immediately and some is meant to be quoted for later evaluation. In 
general (yes, there are some exceptions), Python statements are either 
restricted gotos or statements that implicitly quote part of the code in 
the statement. And in general, with a few exceptions, including lambda, 
expressions are completely and immediately evaluated. Changing print and 
exec from statements to functions made Py3 more consistent in this 
respect this distinction.

In List, one either quotes explicitly or must remember that certain 
'functions' are not really functions but are 'special functions' or 
'macros' that implicitly quote the code, just like Python statements do.

Simple statement example:

name = expression

The name is implicitely quoted. Behind the scenes, this is a function 
call. At module level, one can write the call explictly, with explicit 
quotes:

globals().__setitem__('name', expression)

If the statement form annoys you, use the expression equivalent. (Within 
functions, however, you do not have this choice in CPython because, for 
efficiency, function local namespaces are not Python objects and hence 
there is no Python function to directly manipulate them.)

In Lisp, the expression would be something like

(set 'name expression)

Compound statement example:

def f(a, b=3);
	'doc for a'
	

The def keyword, default arg expression(s), and doc string are evaluated 
immediately. The function name, parameter names, and body code must be 
quoted somehow. In Python, this is done implicitly as signalled by def 
being a statement keyword rather than a function name. Behind the 
scenes, the def statement is implemented mainly by two function calls: 
compile the (quoted) code and create a function object. I believe that 
one could define functions with explicit calls rather than a statement, 
but it would be much more work and require explicit quotes. Turning a 
class statement into an exec() and type() call is easier, but still 
extra work.

Terry Jan Reedy



From cjw at ncf.ca  Sat May 15 18:34:47 2010
From: cjw at ncf.ca (cjw)
Date: Sat, 15 May 2010 18:34:47 -0400
Subject: Access to comp.lang.python
Message-ID: 

This isn't about Python but I'm seeking suggestions as to the best way 
to access the newsgroup.

It seems that messages are coming from a number of sources, such as 
gmane and google groups.

The problem is that many messages seem to get unlinked from their threads.

I use Thunderbird 3.0.5 and wonder whether the problem lies with the 
merge process, the server or my reader.

Would it be better to go to gmane, google groups or some such provider.

In the past, use of Ctrl K had neatly disposed of thread that are of no 
interest.

I would welcome advice.

Colin W.


From pietro.campe at gmail.com  Sat May 15 18:56:41 2010
From: pietro.campe at gmail.com (Pietro Campesato)
Date: Sat, 15 May 2010 15:56:41 -0700 (PDT)
Subject: parsing XML
References: 
Message-ID: 

On May 14, 7:57?am, "kak... at gmail.com"  wrote:
> Hi to all, let's say we have the following Xml
> 
> ? 
> ? ? 17.1
> ? ? 6.4
> ? 
> ? 
> ? ? 15.5
> ? ? 7.8
> ? 
> 
>
> How can i get the players name, age and height?
> DOM or SAX and how
>
> Thanks
> Antonis

I've found some code which converts an XML string to a dictionary
here:
http://nonplatonic.com/ben.php?title=python_xml_to_dict_bow_to_my_recursive_g&more=1&c=1&tb=1&pb=1

Once your data is in a dictionary extracting info will be much easier.


From davea at ieee.org  Sat May 15 20:09:40 2010
From: davea at ieee.org (Dave Angel)
Date: Sat, 15 May 2010 20:09:40 -0400
Subject: write a 20GB file
In-Reply-To: 
References: 	<4BED2E45.6060301@ieee.org>					
	
Message-ID: <4BEF37C4.4090709@ieee.org>

Nathan Rice wrote:
> This is precisely the situation mmap was made for :)  It has almost the same
> methods as a file so it should be an easy replacement.
>
> 

Only on a 64bit system, and I'm not sure it's even possible there in 
every case.  On a 32bit system, it would be impossible to mmap a 20gb 
file.  You only have 4gb of address space to play with, total.

DaveA



From pmaupin at gmail.com  Sat May 15 20:30:51 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 17:30:51 -0700 (PDT)
Subject: write a 20GB file
References: 
	<4BED2E45.6060301@ieee.org>
	 
	
	 
	
	 
	 
	
Message-ID: <98a5a026-6e5a-41e1-b096-17866b3e0f4e@m21g2000vbr.googlegroups.com>

On May 15, 7:09?pm, Dave Angel  wrote:
> Nathan Rice wrote:
> > This is precisely the situation mmap was made for :) ?It has almost the same
> > methods as a file so it should be an easy replacement.
>
> > 
>
> Only on a 64bit system, and I'm not sure it's even possible there in
> every case. ?On a 32bit system, it would be impossible to mmap a 20gb
> file. ?You only have 4gb of address space to play with, total.
>
> DaveA



From pmaupin at gmail.com  Sat May 15 20:32:38 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sat, 15 May 2010 17:32:38 -0700 (PDT)
Subject: write a 20GB file
References: 
	<4BED2E45.6060301@ieee.org>
	 
	
	 
	
	 
	 
	
Message-ID: <1fb377ce-e1c7-4ec3-bed4-dc5c124af217@d12g2000vbr.googlegroups.com>

On May 15, 7:09?pm, Dave Angel  wrote:
> Nathan Rice wrote:
> > This is precisely the situation mmap was made for :) ?It has almost the same
> > methods as a file so it should be an easy replacement.
>
> > 
>
> Only on a 64bit system, and I'm not sure it's even possible there in
> every case. ?On a 32bit system, it would be impossible to mmap a 20gb
> file. ?You only have 4gb of address space to play with, total.
>
> DaveA

Well, depending on the OS, I think you could have multiple mappings
per file.  So you could maintain your own mapping cache.  That could
get a bit ugly, but depending on what you are doing, it might not be
too bad.

Regards,
Pat


From martin at v.loewis.de  Sat May 15 20:37:33 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sun, 16 May 2010 02:37:33 +0200
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>	
	
Message-ID: <4BEF3E4D.9090404@v.loewis.de>

> ???  The namespaces are embedded in the document.  Personally I find it
> odd I have to tell xpath about the namespace of the document it is a
> $*&@(*& method of.

How so? Why do you say it's a "method", and why do you say "of"?

Usually, xpath expressions are *not* part of the document they operate
on, but part of the code that performs the operation. Consequentially,
the namespace prefixes in the xpath expression do *not* occur in the
document (other than by chance), but are defined by whoever writes the
xpath expression. That is typically somebody different from the one
writing the document - if you would always write them together, you
wouldn't need xpath in the first place, but could produce the selection
result right away.

Regards.
Martin


From martin at v.loewis.de  Sat May 15 20:37:33 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sun, 16 May 2010 02:37:33 +0200
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>	
	
Message-ID: <4BEF3E4D.9090404@v.loewis.de>

> ???  The namespaces are embedded in the document.  Personally I find it
> odd I have to tell xpath about the namespace of the document it is a
> $*&@(*& method of.

How so? Why do you say it's a "method", and why do you say "of"?

Usually, xpath expressions are *not* part of the document they operate
on, but part of the code that performs the operation. Consequentially,
the namespace prefixes in the xpath expression do *not* occur in the
document (other than by chance), but are defined by whoever writes the
xpath expression. That is typically somebody different from the one
writing the document - if you would always write them together, you
wouldn't need xpath in the first place, but could produce the selection
result right away.

Regards.
Martin


From ldo at geek-central.gen.new_zealand  Sat May 15 23:05:20 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sun, 16 May 2010 15:05:20 +1200
Subject: Picking a license
References: 
	
	
Message-ID: 

In message
, Patrick 
Maupin wrote:

> On May 14, 9:21 pm, Lawrence D'Oliveiro  central.gen.new_zealand> wrote:
>
>> In message , Ed
>> Keith wrote:
>>
>>> I just refuse to use [the GPL] in any code for a client, because I
>>> do not want to require someone who does not know source code from Morse
>>> code code to figure out what they need to do to avoid violating the
>>> license.
>>
>> Why don?t you just put the source code on the same disc you send them,
>> and tell them to pass copies of the entire disc to anyone they want?
> 
> What you would really have to tell them is "don't pass along the
> program *unless* you copy the whole disk."  That's no longer a
> courtesy -- that's a mandate.  By not using the GPL, Ed avoids having
> to mandate to his customer how to treat the software he has delivered
> to them.

But that?s what ?copyright? means, it means ?right to copy?. It?s his right 
to impose terms on how copies of stuff he created are treated.


From ldo at geek-central.gen.new_zealand  Sat May 15 23:06:54 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sun, 16 May 2010 15:06:54 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> On Fri, 5/14/10, Lawrence D'Oliveiro
>  wrote:
> 
>> In message ,
>> Ed Keith wrote:
>> 
>>> Yes, under the GPL every one has one set of freedoms,
>>> under the MIT or Boost license every one has more freedoms. Under other
>>> licenses they have fewer freedoms.
>> 
>> But what about the ?freedom? to take away other
>> people?s freedom? Is that really ?freedom??
> 
> Yes.

But that?s a ?freedom? that non-GPL licences do not give you, that the GPL 
does. So which licence gives you more ?freedoms?, again?


From ldo at geek-central.gen.new_zealand  Sat May 15 23:08:38 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sun, 16 May 2010 15:08:38 +1200
Subject: Picking a license
References: 
	<93d67bd9-6721-4759-a3de-412b95b29a93@c11g2000vbe.googlegroups.com>
Message-ID: 

In message
<93d67bd9-6721-4759-a3de-412b95b29a93 at c11g2000vbe.googlegroups.com>, Paul 
Boddie wrote:

> Although Bill Gates once apparently claimed that no-one needs the
> source code for their word processor or office suite ...

Thereby committing the sealed-bonnet fallacy.


From ldo at geek-central.gen.new_zealand  Sat May 15 23:09:32 2010
From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro)
Date: Sun, 16 May 2010 15:09:32 +1200
Subject: Picking a license
References: 
Message-ID: 

In message , Ed Keith 
wrote:

> But if my client give someone else a copy of the binary I gave them, they
> are now in violation.

Why would they be in violation? It seems to me a violation would only occur 
if someone asked them for the source, and they refused.


From awilliam at whitemice.org  Sun May 16 00:00:59 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sun, 16 May 2010 00:00:59 -0400
Subject: Reading XML namespaces
In-Reply-To: <4BEF1406.7010205@v.loewis.de>
References: <1273948642.2322.10.camel@linux-yu4c.site>
		<1273956059.4023.0.camel@linux-yu4c.site>
		<1273957446.4023.6.camel@linux-yu4c.site>
	
	<4BEF1406.7010205@v.loewis.de>
Message-ID: <1273982459.28715.2.camel@linux-yu4c.site>

On Sat, 2010-05-15 at 23:37 +0200, Martin v. Loewis wrote:
> > BTW, I'm still not sure I understand your problem. Could you provide
> > some more details?
> Wouldn't it be easier if you told the OP how to access the prefix

:)

> mappings in lxml etree, or, if this was actually not possible, admitted
> that it is actually not possible?

I suspect that it is not;  but that seems rather surprising. 

> FWIW, in the DOM, you look at all attributes of an element node, and
> search for those whose namespace is "http://www.w3.org/2000/xmlns/"
> In SAX, you watch the startPrefixMapping events.

Given that XML documents can be very large I'd rather avoid a parsing of
the document [beyond what lxml/etree] has already done] just to retrieve
the namespaces and their prefixes.



From awilliam at whitemice.org  Sun May 16 00:11:57 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Sun, 16 May 2010 00:11:57 -0400
Subject: Reading XML namespaces
In-Reply-To: <4BEF3E4D.9090404@v.loewis.de>
References: <1273948642.2322.10.camel@linux-yu4c.site>
		<1273956059.4023.0.camel@linux-yu4c.site>
		<1273957446.4023.6.camel@linux-yu4c.site>
	
	
	<4BEF3E4D.9090404@v.loewis.de>
Message-ID: <1273983117.28715.11.camel@linux-yu4c.site>

On Sun, 2010-05-16 at 02:37 +0200, Martin v. Loewis wrote:
> > ???  The namespaces are embedded in the document.  Personally I find it
> > odd I have to tell xpath about the namespace of the document it is a
> > $*&@(*& method of.
> How so? Why do you say it's a "method", and why do you say "of"?
> Usually, xpath expressions are *not* part of the document they operate
> on, but part of the code that performs the operation.

from lxml import etree

doc = etree.parse(data)
doc.xpath(....)

>  Consequentially,
> the namespace prefixes in the xpath expression do *not* occur in the
> document (other than by chance), but are defined by whoever writes the
> xpath expression. That is typically somebody different from the one
> writing the document 

Maybe true technically, but false in practice.  If I receive XML data
from source XYZ or service XYZ the use of namespaces and their prefixes
is extremely consistent [in practice] and very customary (for example:
I've never seen the DSML namespace abbreviated as anything other than
"dsml" and I rarely see WebDAV propfind XML use a namespace prefix other
than "D").  The odds that a customer or vendors ERP will generate
different namespaces and abbreviations between requests is ludicrously
remote [I don't recall ever seeing it happen].

And if the xpath fails to produce normal [or any] output the workflow
with either do nothing or abend which will draw the attention of an
administrator.

> - if you would always write them together, you
> wouldn't need xpath in the first place, but could produce the selection
> result right away.




From robert.kern at gmail.com  Sun May 16 00:31:19 2010
From: robert.kern at gmail.com (Robert Kern)
Date: Sat, 15 May 2010 23:31:19 -0500
Subject: Picking a license
In-Reply-To: 
References: 		
	
Message-ID: 

On 2010-05-15 22:05 , Lawrence D'Oliveiro wrote:
> In message
> , Patrick
> Maupin wrote:
>
>> On May 14, 9:21 pm, Lawrence D'Oliveiro> central.gen.new_zealand>  wrote:
>>
>>> In message, Ed
>>> Keith wrote:
>>>
>>>> I just refuse to use [the GPL] in any code for a client, because I
>>>> do not want to require someone who does not know source code from Morse
>>>> code code to figure out what they need to do to avoid violating the
>>>> license.
>>>
>>> Why don?t you just put the source code on the same disc you send them,
>>> and tell them to pass copies of the entire disc to anyone they want?
>>
>> What you would really have to tell them is "don't pass along the
>> program *unless* you copy the whole disk."  That's no longer a
>> courtesy -- that's a mandate.  By not using the GPL, Ed avoids having
>> to mandate to his customer how to treat the software he has delivered
>> to them.
>
> But that?s what ?copyright? means, it means ?right to copy?. It?s his right
> to impose terms on how copies of stuff he created are treated.

It's also his right to choose which terms to impose, depending on the client and 
project. If he doesn't think the GPL serves his goals, then he shouldn't use it. 
It shouldn't matter to him how well it serves your goals or how unburdensome you 
personally find the GPL's requirements.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From no.email at nospam.invalid  Sun May 16 00:36:32 2010
From: no.email at nospam.invalid (Paul Rubin)
Date: Sat, 15 May 2010 21:36:32 -0700
Subject: Is Python a functional programming language?
References: 
	
	
Message-ID: <7xocggv4xb.fsf@ruckus.brouhaha.com>

travis+ml-python at subspacefield.org writes:
> To be fair, it appears that Python's whitespace-sensitive syntax sort
> of precludes the "make a complex function on one line" that is typical
> of languages which don't have statement/expression distinctions, but
> I'm not convinced it couldn't be solved, perhaps by allowing anonymous
> functions to span multiple lines, just like named functions.

Haskell has whitespace-based syntax like Python (you can alternatively
use curly braces).  Their term for it is "layout".  You can
alternatively use curly braces and semi-colons.  I'd have to say that
Haskell's indentation rules are a bit harder to understand than Python's
at first.


From tjreedy at udel.edu  Sun May 16 01:00:07 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Sun, 16 May 2010 01:00:07 -0400
Subject: Access to comp.lang.python
In-Reply-To: 
References: 
Message-ID: 

On 5/15/2010 6:34 PM, cjw wrote:
> This isn't about Python but I'm seeking suggestions as to the best way
> to access the newsgroup.
>
> It seems that messages are coming from a number of sources, such as
> gmane and google groups.
>
> The problem is that many messages seem to get unlinked from their threads.

Some people have said that that is due to newreaders not tagging 
responses properly.

> I use Thunderbird 3.0.5 and wonder whether the problem lies with the
> merge process, the server or my reader.
>
> Would it be better to go to gmane, google groups or some such provider.

I believe some spam (like from Google accounts) is filtered out between 
c.l.p and python-list. Gmane mirrors python-list, not c.l.p., so it gets 
the benefit of the filtering. You can see from the headers that that is 
where I post from.

tjr





From aahz at pythoncraft.com  Sun May 16 01:12:11 2010
From: aahz at pythoncraft.com (Aahz)
Date: 15 May 2010 22:12:11 -0700
Subject: Access to comp.lang.python
References: 
	
Message-ID: 

In article ,
Terry Reedy   wrote:
>On 5/15/2010 6:34 PM, cjw wrote:
>>
>> The problem is that many messages seem to get unlinked from their threads.
>
>Some people have said that that is due to newreaders not tagging 
>responses properly.

It's also at least partly due to problems with mail<->news gateways and
the differing fields used to maintain threading.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From prologic at shortcircuit.net.au  Sun May 16 01:31:59 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sun, 16 May 2010 15:31:59 +1000
Subject: Access to comp.lang.python
In-Reply-To: 
References: 
	 
	
Message-ID: 

On Sun, May 16, 2010 at 3:12 PM, Aahz  wrote:
> It's also at least partly due to problems with mail<->news gateways and
> the differing fields used to maintain threading.

Some blame goes on MUAs too :)


From kwatch at gmail.com  Sun May 16 02:41:48 2010
From: kwatch at gmail.com (kwatch)
Date: Sat, 15 May 2010 23:41:48 -0700 (PDT)
Subject: [ANN] Benchmarker 1.0.0 - a samll utility for benchmarking
Message-ID: <4feb1d2e-aa4b-49b6-acd5-06f23762e1a1@11g2000prv.googlegroups.com>

Hi,

I released Benchmarker 1.0.0.
http://pypi.python.org/pypi/Benchmarker/

Benchmarker is a small library for benchmarking.


Example
-------

ex.py::

    def fib(n):
        return n <= 2 and 1 or fib(n-1) + fib(n-2)
    from benchmarker import Benchmarker
    bm = Benchmarker()  # or Benchmarker(width=30, out=sys.stderr,
header=True)
    ## Python 2.5 or later
    with bm('fib(n) (n==34)'):  fib(34)
    with bm('fib(n) (n==35)'):  fib(35)
    ## Python 2.4
    bm('fib(n) (n==34)').run(lambda: fib(34))
    bm('fib(n) (n==35)').run(lambda: fib(35))

Output::

    $ python ex.py
                                       utime      stime
total       real
    fib(n) (n==34)                    4.3700     0.0200     4.3900
4.9449
    fib(n) (n==35)                    7.1500     0.0500     7.2000
8.0643


Download
--------

http://pypi.python.org/pypi/Benchmarker/

Installation::

    ## if you have installed easy_install:
    $ sudo easy_install Benchmarker
    ## or download Benchmarker-1.0.0.tar.gz and install it
    $ wget http://pypi.python.org/packages/source/B/Benchmarker/Benchmarker-1.0.0.tar.gz
    $ tar xzf Benchmarker-1.0.0.tar.gz
    $ cd Benchmarker-1.0.0/
    $ sudo python setup.py install


License
-------

Public Domain


Copyright
---------

copyright(c) 2010 kuwata-lab.com all rights reserved


From stefan_ml at behnel.de  Sun May 16 02:55:48 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sun, 16 May 2010 08:55:48 +0200
Subject: Reading XML namespaces
In-Reply-To: <4BEF1406.7010205@v.loewis.de>
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>	
	<4BEF1406.7010205@v.loewis.de>
Message-ID: 

Martin v. Loewis, 15.05.2010 23:37:
>> BTW, I'm still not sure I understand your problem. Could you provide
>> some more details?
>
> Wouldn't it be easier if you told the OP how to access the prefix
> mappings in lxml etree, or, if this was actually not possible, admitted
> that it is actually not possible?

Well, there's an "nsmap" property on each Element that provides the mapping 
of prefixes to namespace URIs that form the scope of the Element. However, 
while this is what the OP asked for, it is not what the OP wants, simply 
because it doesn't solve the problem. Prefixes can get defined and 
redefined arbitrarily often, so there is no such thing as a 
prefix-namespace mapping "of the document". Example:

     
         
             
>>>>> 
>>>>> How can one access the namespaces define in this node?  I've done a fair
>>>>> amount of XML in Python, but haven't been able to uncover the call to
>>>>> enumerate the namespaces.
>>>>> Primarily I am using etree from lxml.
>>>> What do you need the namespaces for?
>>> One needs to know the defined namespace in order to perform xpath
>>> operations.
>> Well, yes, but unless you already know the namespace (URI), you can't know
>> what the tag you find signifies in the first place.
>> Unless, obviously, you are confusing namespaces with namespace prefixes.
>> But you don't need to know the prefixes for XPath.
>> Does this help?
>> http://codespeak.net/lxml/xpathxslt.html#namespaces-and-prefixes
>
> I know that.

I just remembered that there's also this:

http://codespeak.net/lxml/FAQ.html#how-can-i-find-out-which-namespace-prefixes-are-used-in-a-document

Stefan



From martin at v.loewis.de  Sun May 16 03:07:53 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sun, 16 May 2010 09:07:53 +0200
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>		<4BEF1406.7010205@v.loewis.de>
	
Message-ID: <4BEF99C9.5070709@v.loewis.de>

> Well, there's an "nsmap" property on each Element that provides the
> mapping of prefixes to namespace URIs that form the scope of the
> Element. However, while this is what the OP asked for, it is not what
> the OP wants, simply because it doesn't solve the problem.

Well, it solves the problem at hand: he gets some prefix mapping.

He probably could have used a hard-coded prefix mapping for the 20 or so
namespaces in his application instead (with a different set of flaws in
that approach).

> That's why I asked for more details in order to understand what the
> actual problem is that the OP is trying to solve, because the approach
> that the OP is apparently trying to follow is clearly misguided.

I completely agree. However, I recommend that we let him find out on his
 own. I suspect he has some idiomatic usage of XML, perhaps with all
namespace prefixes defined in the root element. He'll find out that his
approach is flawed in the general case when he encounters such a case.
It's probably pointless trying to convince him in the abstract.

Regards,
Martin


From stefan_ml at behnel.de  Sun May 16 03:21:37 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sun, 16 May 2010 09:21:37 +0200
Subject: Reading XML namespaces
In-Reply-To: <4BEF99C9.5070709@v.loewis.de>
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>		<4BEF1406.7010205@v.loewis.de>	
	<4BEF99C9.5070709@v.loewis.de>
Message-ID: 

Martin v. Loewis, 16.05.2010 09:07:
>> the approach that the OP is apparently trying to follow is
>> clearly misguided.
>
> I completely agree. However, I recommend that we let him find out on his
>   own. I suspect he has some idiomatic usage of XML, perhaps with all
> namespace prefixes defined in the root element. He'll find out that his
> approach is flawed in the general case when he encounters such a case.
> It's probably pointless trying to convince him in the abstract.

Probably, yes. It's just that I prefer it if broken code doesn't get 
written in the first place, rather than having to fix it later on, which in 
this case even seems to imply breaking a user visible feature. But you're 
right, let's leave the decision to the OP.

Stefan



From ninmonkeys at gmail.com  Sun May 16 03:40:07 2010
From: ninmonkeys at gmail.com (Jake b)
Date: Sun, 16 May 2010 02:40:07 -0500
Subject: parsing XML
In-Reply-To: 
References: 
	<4beec709$0$18653$4fafbaef@reader3.news.tin.it>
	
Message-ID: 

Check out Amara: http://www.xml3k.org/Amara/QuickRef

It looks promising. For a pythonic solution over sax / dom.

>>> Iter(doc.team.player)
# or
>>> doc.team.player[0].name

[ new to the list, so I'm not sure why my previous response failed. Is
it on me? Because using iPod, vs thunderbird?

However, looking at superpollo, the reply-to didn't include
python-list. Or even a valid address ?

Message below. Ty.

On Saturday, May 15, 2010, Mail Delivery Subsystem
 wrote:
> Delivery to the following recipient failed permanently:
>
>  ? ? utente at esempio.net
>
> Technical details of permanent failure:
> Google tried to deliver your message, but it was rejected by the recipient domain. We recommend contacting the other email provider for further information about the cause of this error. The error that the other server returned was: 554 554 : Relay access denied (state 14).
>
> ----- Original message -----
>
> MIME-Version: 1.0
> Received: by 10.91.208.24 with SMTP id k24mr18590agq.155.1273969257113; Sat,
>  ? ? ? ?15 May 2010 17:20:57 -0700 (PDT)
> Received: by 10.90.80.20 with HTTP; Sat, 15 May 2010 17:20:57 -0700 (PDT)
> In-Reply-To: <4beec709$0$18653$4fafbaef at reader3.news.tin.it>
> References: 
>  ? ? ? ? <4beec709$0$18653$4fafbaef at reader3.news.tin.it>
> Date: Sat, 15 May 2010 19:20:57 -0500
> Message-ID: 
> Subject: Re: parsing XML
> From: Jake b 
> To: superpollo 
> Content-Type: text/plain; charset=ISO-8859-1
>
> Check out Amara: http://www.xml3k.org/Amara/QuickRef
> For a pythonic solution over sax / dom.
>>> Iter(doc.team.player)
> or
>>> doc.team.player[0].name
>
> --
> Jake
>

--
Jake

-- 
Jake


From prologic at shortcircuit.net.au  Sun May 16 03:43:53 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Sun, 16 May 2010 17:43:53 +1000
Subject: joining files
In-Reply-To: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
References: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
Message-ID: 

On Sun, May 16, 2010 at 5:02 PM, mannu jha  wrote:
> Hi,
>
> I have few files like this:
> file1:
> 22 110.1
> 33 331.5 22.7
> 5 271.9 17.2 33.4
> 4 55.1
>
> file1 has total 4 column but some of them are missing in few row.
>
> file2:
> 5 H
> 22 0
>
> file3:
> 4 T
> 5 B
> 22 C
> 121 S
>
> in all these files first column is the main source of matching their
> entries. So What I want in the output is only those entries which is coming
> in all three files.
> output required:
> 5 271.9 17.2 33.4 5 H 5 T
> 22 110.1 22 0 22 C

This had better not be yet another assignment
you're asking us to help you with ? *sigh*

Break your problem down!

Since you haven't really asked a specific question
I can't give you a specific answer.

--James


From kwatch at gmail.com  Sun May 16 03:46:55 2010
From: kwatch at gmail.com (kwatch)
Date: Sun, 16 May 2010 00:46:55 -0700 (PDT)
Subject: [ANN] Oktest 0.3.0 released - a new style testing library
Message-ID: <7e11c574-9a34-4f2f-aeb7-469b03ac5622@u3g2000prl.googlegroups.com>

Hi,
I released Oktest 0.3.0.

http://packages.python.org/Oktest/
http://pypi.python.org/pypi/Oktest/


Overview
--------

Oktest is a new-style testing library for Python.
::

    from oktest import ok
    ok (x) > 0                 # same as assert_(x > 0)
    ok (s) == 'foo'            # same as assertEqual(s, 'foo')
    ok (s) != 'foo'            # same as assertNotEqual(s, 'foo')
    ok (f).raises(ValueError)  # same as assertRaises(ValueError, f)
    ok (u'foo').is_a(unicode)  # same as assert_(isinstance(u'foo',
unicode))
    not_ok (u'foo').is_a(int)  # same as assert_(not
isinstance(u'foo', int))
    ok ('A.txt').is_file()     # same as
assert_(os.path.isfile('A.txt'))
    not_ok ('A.txt').is_dir()  # same as assert_(not
os.path.isdir('A.txt'))

You can use ok() instead of 'assertXxx()' in unittest.

Oktest requires Python 2.3 or later. Oktest is ready for Python 3.

NOTICE!! Oktest is a young project and specification may change in the
future.

See http://packages.python.org/Oktest/ for details.


Changes
-------

* enhanced 'ok (s1) == s2' to display unified diff (diff -u)
* changed to call 'before()/after()' instead of 'before_each()/
after_each()'
  (currently 'before_each()/after_each()' is also enabled but they
will be
   disabled in the future)
* improved compatibility with unittest module
* (internal) 'ValueObject' class is renamed to 'AssertionObject'
* (internal) 'Reporter#before_each()' and '#after_each()' are renamed
into
  '#before()' and '#after()'


Have fun!

--
regards,
makoto kuwata


From stefan_ml at behnel.de  Sun May 16 03:52:22 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sun, 16 May 2010 09:52:22 +0200
Subject: parsing XML
In-Reply-To: 
References: 	<4beec709$0$18653$4fafbaef@reader3.news.tin.it>	
	
Message-ID: 

Jake b, 16.05.2010 09:40:
> Check out Amara: http://www.xml3k.org/Amara/QuickRef
>
> It looks promising. For a pythonic solution over sax / dom.
>
> >>> Iter(doc.team.player)
> # or
> >>> doc.team.player[0].name

Ah, right, and there's also lxml.objectify:

     from lxml.objectify import parse

     root = parse('teamfile.xml').getroot()

     for player in root.player:
         print(player.attrib)

Prints an attribute dict for each player.

Stefan



From clp2 at rebertia.com  Sun May 16 04:18:25 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Sun, 16 May 2010 01:18:25 -0700
Subject: joining files
In-Reply-To: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
References: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
Message-ID: 

On Sun, May 16, 2010 at 12:02 AM, mannu jha  wrote:
> Hi,
>
> I have few files like this:
> file1:
> 22 110.1
> 33 331.5 22.7
> 5 271.9 17.2 33.4
> 4 55.1
>
> file1 has total 4 column but some of them are missing in few row.
>
> file2:
> 5 H
> 22 0
>
> file3:
> 4 T
> 5 B
> 22 C
> 121 S
>
> in all these files first column is the main source of matching their
> entries. So What I want in the output is only those entries which is coming
> in all three files.
> output required:
> 5 271.9 17.2 33.4 5 H 5 T
> 22 110.1 22 0 22 C

Outline of approach:
1. For each file, create a dict mapping the first number on each line
to that line.
2. Take the set intersection of the key sets of the dictionaries.
3. For each key in the intersection, get the values associated with it
from all the dicts and combine them, then output the combination.

HTH, but you're not gonna get any code out of me.
Some trivial parsing and knowledge of Python's datatypes is involved;
you should already know that or be able to readily figure it out from
the docs.

Cheers,
Chris
--

http://blog.rebertia.com


From davea at ieee.org  Sun May 16 04:25:59 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 16 May 2010 04:25:59 -0400
Subject: joining files
In-Reply-To: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
References: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
Message-ID: <4BEFAC17.6020909@ieee.org>

mannu jha wrote:
> Hi,
>
> I have few files like this:
> file1:
> 22 110.1  
> 33 331.5 22.7 
> 5 271.9 17.2 33.4
> 4 55.1 
>
> file1 has total 4 column but some of them are missing in few row.
>
> file2:
> 5 H
> 22 0
>
> file3:
> 4 T
> 5 B
> 22 C
> 121 S
>
> in all these files first column is the main source of matching their entries. So What I want in the output is only those entries which is coming in all three files.
> output required:
> 5 271.9 17.2 33.4 5 H  5 T
> 22 110.1         22 0 22 C
>
>
>   
Do you have a spec?  Have you added any code to the last assignment to 
deal with this question, and in what way isn't it working?  Why don't 
you post your code?

Generally, you seem to have lines where the first "word" is a key to the 
line.  The word appears to be distinguished by whitespace.  So finding 
the key from a line would be just   line.split()[0]    Then you build a 
dictionary from each file.  You didn't specify whether a given file 
might have multiple lines with the same key, so I'll just say to watch 
out for that, as a dictionary will cheerfully overwrite entries with new 
ones.

Since your rule on multiple files is apparently to throw out any line 
whose key isn't in all files, you'd need to make a dictionary for each 
file, then analyze all  of them in a later pass.  That pass could 
involve iterating through one of the dictionaries, and for each key 
deciding if it's in all of the others.  One way to do that is to build a 
list and run all() on it.

DaveA





From clp2 at rebertia.com  Sun May 16 04:40:07 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Sun, 16 May 2010 01:40:07 -0700
Subject: Setup global variables settings for the entire applications
In-Reply-To: 
References: 
Message-ID: 

On Fri, May 14, 2010 at 7:32 AM, AON LAZIO  wrote:
> Hi,
> ?? Say I have an application which requires a global settings for the user.
> When the user finishes setting those global variables for the app. Any class
> can use that variables (which are the same for all), something like that.
> What is the suitable mechanism for this solution?

Have a module that either contains the variables directly or contains
a configuration object that has the variables. Then just import the
module wherever you need to access the variables.

For example:

#config.py
power_user_mode = True
user_avatar = "bacon.jpg"

#elsewhere.py
import mypackage.config as config

class Foo(object):
    #...
    def whatever(self):
        self.set_avatar(config.user_avatar)
        if config.power_user_mode:
            self.show_advanced_interface()
    #...
    def something(self):
        new_avatar = self.avatar_chooser()
        config.user_avatar = new_avatar
        self.set_avatar(new_avatar)

Cheers,
Chris
--
Why bacon? Reddit.
http://blog.rebertia.com


From martin at v.loewis.de  Sun May 16 05:05:51 2010
From: martin at v.loewis.de (Martin v. Loewis)
Date: Sun, 16 May 2010 11:05:51 +0200
Subject: Reading XML namespaces
In-Reply-To: 
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>			<4BEF3E4D.9090404@v.loewis.de>
	
Message-ID: <4BEFB56F.9040102@v.loewis.de>

> Maybe true technically, but false in practice.  If I receive XML data
> from source XYZ or service XYZ the use of namespaces and their prefixes
> is extremely consistent [in practice] and very customary (for example:
> I've never seen the DSML namespace abbreviated as anything other than
> "dsml" and I rarely see WebDAV propfind XML use a namespace prefix other
> than "D").  The odds that a customer or vendors ERP will generate
> different namespaces and abbreviations between requests is ludicrously
> remote [I don't recall ever seeing it happen].

In that case, you could also hard-code all prefixes in your application;
no need to traverse the input document.

Regards,
Martin


From tuomas.vesterinen at iki.fi  Sun May 16 05:07:08 2010
From: tuomas.vesterinen at iki.fi (Tuomas Vesterinen)
Date: Sun, 16 May 2010 12:07:08 +0300
Subject: Using site-packages with alt-installed Python version
Message-ID: <4befb5c3$0$2537$9b536df3@news.fv.fi>

I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native 
Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.

Aplication GUI uses:
import pygtk
pygtk.require('2.0')
import gtk
import gobject

I go to:
$ cd /usr/local/lib/python2.4/site-packages

and say:
$ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py
$ sudo ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0

and try:
$ python2.4 gui_utils.py
Traceback (most recent call last):
   File "gui_utils.py", line 57, in ?
     import gtk
   File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line 
30, in ?
     import gobject as _gobject
   File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py", 
line 26, in ?
     from glib import spawn_async, idle_add, timeout_add, 
timeout_add_seconds, \
   File 
"/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line 
22, in ?
     from glib._glib import *
ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol: 
_PyObject_CallFunction_SizeT

What I should say more to get access to the GTK?

Tuomas Vesterinen


From paul.hankin at gmail.com  Sun May 16 07:16:41 2010
From: paul.hankin at gmail.com (Paul Hankin)
Date: Sun, 16 May 2010 04:16:41 -0700 (PDT)
Subject: huh??? weird problem
References: <61c86b8b-69d4-4832-8aea-234b67a0bed4@s13g2000prc.googlegroups.com>
	
Message-ID: 

On May 15, 3:41?am, Dave Angel  wrote:
> cerr wrote:
> > Hi There,
>
> > I got following code:
> > start=time.time()
> > print 'warnTimeout '+str(WarnTimeout)
> > print 'critTimeout '+str(CritTimeout)
> > print 'start',str(start)
> > while wait:
> > ? ? passed = ?time.time()-start
> > ? ? print 'passed ',str(passed)
> > ? ? if passed >= WarnTimeout:
> > ? ? ? print ' Warning!'
> > ?...
> > ...
> > ...
> > which basically means that the loops should go until the warning time
> > has been reached and then i want it to print 'warning!' and execute
> > some warning code. But weirdly enough i get following screen output:
> > warnTimeout 3
> > critTimeout 5
> > start 1273882010.43
> > passed ?7.60555267334e-05
> > passed ?0.998471975327
> > passed ?1.99847102165
> > passed ?2.9984691143
> > passed ?3.99847006798
> > passed ?4.998472929
> > ...
> > ...
> > any one a clue why after 3 seconds it doesn't go into the the if an
> > print 'Warning!'? That's odd... :o Crazy, what am i not seeing? :(
>
> we're not seeing all the relevant code. ?While I can ignore the missing
> import, I don't see any creation of the variables WarnTimeout and
> CritTimeout. ?Simplest explanation that fits your sample run is that
> they are not of type float.

Yes, and most likely str. A good debugging tip is to use repr rather
than str to print out debugging messages.

--
Paul Hankin


From alister.ware at ntlworld.com  Sun May 16 07:38:12 2010
From: alister.ware at ntlworld.com (Alister)
Date: Sun, 16 May 2010 11:38:12 GMT
Subject: Using site-packages with alt-installed Python version
References: <4befb5c3$0$2537$9b536df3@news.fv.fi>
Message-ID: 

On Sun, 16 May 2010 12:07:08 +0300, Tuomas Vesterinen wrote:

> I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native
> Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.
> 
> Aplication GUI uses:
> import pygtk
> pygtk.require('2.0')
> import gtk
> import gobject
> 
> I go to:
> $ cd /usr/local/lib/python2.4/site-packages
> 
> and say:
> $ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py $ sudo
> ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0
> 
> and try:
> $ python2.4 gui_utils.py
> Traceback (most recent call last):
>    File "gui_utils.py", line 57, in ?
>      import gtk
>    File
> "/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line
> 30, in ?
>      import gobject as _gobject
>    File
> "/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py",
> line 26, in ?
>      from glib import spawn_async, idle_add, timeout_add,
> timeout_add_seconds, \
>    File
> "/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line
> 22, in ?
>      from glib._glib import *
> ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol:
> _PyObject_CallFunction_SizeT
> 
> What I should say more to get access to the GTK?
> 
> Tuomas Vesterinen

I am not a great expert on this But I think you need to use the Redhat 
alternatives system to switch between versions rather than trying to 
change things manually.

as i understand it the Alternatives system sets up and changes various 
symlinks to ensure everything works correctly. 



-- 
"When the going gets tough, the tough get empirical."
		-- Jon Carroll


From mannu_0523 at rediffmail.com  Sun May 16 09:10:19 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 16 May 2010 13:10:19 -0000
Subject: =?utf-8?B?Rnc6IFJlOiBSZTogam9pbmluZyBmaWxlcw==?=
Message-ID: <1274015375.S.6197.18004.f4mail-235-133.rediffmail.com.1274015419.6048@webmail.rediffmail.com>

Note: Forwarded message attached

-- Original Message --

From: "mannu jha"mannu_0523 at rediffmail.com
To: davea at ieee.org
Subject: Re: Re: joining files
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
An embedded message was scrubbed...
From: "mannu jha"
Subject: Re: Re: joining files
Date: no date
Size: 6032
URL: 

From e_d_k at yahoo.com  Sun May 16 09:40:30 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sun, 16 May 2010 06:40:30 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <468368.26117.qm@web58701.mail.re1.yahoo.com>

--- On Sat, 5/15/10, Robert Kern  wrote:

> From: Robert Kern 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Saturday, May 15, 2010, 1:10 PM
> On 2010-05-14 21:37 , Steven D'Aprano
> wrote:
> > On Fri, 14 May 2010 06:42:31 -0700, Ed Keith wrote:
> > 
> >> I am not a lawyer, but as I understand the LGPL,
> If I give someone
> >> something that used any LGPLed code I must give
> them the ability to
> >> relink it with any future releases of the LGPLed
> code. I think that
> >> means that I need to give them a linker and teach
> them how to use it,
> >> and I do not want to go there.
> > 
> > Surely you're joking?
> > 
> > Does this mean that if they lose their hands in an
> accident, you have to
> > come sit at their computer and do their typing?
> > 
> > The LGPL and GPL don't grant people "the ability" to
> do anything, since
> > that's not within our power to grant. Some people
> don't want to, or
> > can't, program, or don't have time. It's not like the
> LGPL is the bite of
> > a radioactive spider that can grant superpowers. It is
> a licence which
> > grants *permissions*.
> 
> No, the LGPL requires you to do something extra to enable
> your users to be able to relink your program. You need to
> provide the ability to do this, up to some unspecified and
> untested limit of reasonableness (your example is obviously
> beyond the limit of reasonableness). You can't just give
> them, say, a statically linked program and nothing else. You
> can't require for-fee, proprietary linkers. This is usually
> not hard to do (just give them unlinked .o or .obj files and
> a Makefile or project file), but it is *not* just a matter
> of granting permissions.
> 
> But you're right, you don't have to teach them how to do
> it.
> 
> -- Robert Kern
> 
> "I have come to believe that the whole world is an enigma,
> a harmless enigma
>  that is made terrible by our own mad attempt to interpret
> it as though it had
>  an underlying truth."
> ? -- Umberto Eco
> 
> -- http://mail.python.org/mailman/listinfo/python-list
> 

But most of my clients run MS-Windows, and I do most of my development in C++, so they would need to use a proprietary linker.

    -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From davea at ieee.org  Sun May 16 10:04:42 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 16 May 2010 10:04:42 -0400
Subject: joining files
In-Reply-To: <1273998151.S.3807.41729.H.TkRhdmUgQW5nZWwAUmU6IGpvaW5pbmcgZmlsZXM_.f4-234-213.old.1274015374.26493@webmail.rediffmail.com>
References: <1273998151.S.3807.41729.H.TkRhdmUgQW5nZWwAUmU6IGpvaW5pbmcgZmlsZXM_.f4-234-213.old.1274015374.26493@webmail.rediffmail.com>
Message-ID: <4BEFFB7A.2020404@ieee.org>

(You forgot to include the python-list in your response.  So it only 
went to me.  Normally, you just do reply-all to the message)

mannu jha wrote:
> On Sun, 16 May 2010 13:52:31 +0530  wrote
>   
>> mannu jha wrote:
>>     
>
>   
>> Hi,
>>     
>
>   
>
>   
>> I have few files like this:
>> file1:
>> 22 110.1 
>> 33 331.5 22.7 
>> 5 271.9 17.2 33.4
>> 4 55.1 
>>     
>
>   
>> file1 has total 4 column but some of them are missing in few row.
>>     
>
>   
>> file2:
>> 5 H
>> 22 0
>>     
>
>   
>> file3:
>> 4 T
>> 5 B
>> 22 C
>> 121 S
>>     
>
>   
>
>   
>> in all these files first column is the main source of matching their entries. So What I want in the output is only those entries which is coming in all three files.
>>     
>
>   
>> output required:
>>     
>
>   
>> 5 271.9 17.2 33.4 5 H 5 T
>> 22 110.1     22 0 22 C
>>     
>
>   
> I am trying with this :
>
> from collections import defaultdict
>
> def merge(sources):
>     blanks = [blank for items, blank, keyfunc in sources]
>     d = defaultdict(lambda: blanks[:])
>     for index, (items, blank, keyfunc) in enumerate(sources):
>         for item in items:
>             d[keyfunc(item)][index] = item
>     for key in sorted(d):
>         yield d[key]
>
> if __name__ == "__main__":
>     a = open("input1.txt")
>     
>     c = open("input2.txt")
>
>     def key(line):
>         return line[:2]
>     def source(stream, blank="", key=key):
>         return (line.strip() for line in stream), blank, key
>     for m in merge([source(x) for x in [a,c]]):
>         print "|".join(c.ljust(10) for c in m)
>
> but with input1.txt:
> 187    7.79   122.27   54.37   4.26   179.75
> 194    8.00   121.23   54.79   4.12   180.06
> 15    8.45   119.04   55.02   4.08   178.89
> 176    7.78   118.68   54.57   4.20   181.06
> 180    7.50   119.21   53.93      179.80
> 190    7.58   120.44   54.62   4.25   180.02
> 152    8.39   120.63   55.10   4.15   179.10
> 154    7.79   119.62   54.47   4.22   180.46
> 175    8.42   120.50   55.31   4.04   180.33
> and input2.txt:
>  15   H 
>  37   H 
>  95   T
> 124   H 
> 130   H 
> 152   H 
> 154   H 
> 158   H 
> 164   H
> 175   H 
> 176   H 
> 180   H
> 187   H 
> 190   T
> 194   C
> 196   H 
> 207   H 
> 210   H 
> 232   H 
> it is giving output as:
>           |
>           |124   H
>           |130   H
> 154    7.79   119.62   54.47   4.22   180.46|158   H
>           |164   H
> 175    8.42   120.50   55.31   4.04   180.33|176   H
> 180    7.50   119.21   53.93      179.80|187   H
> 190    7.58   120.44   54.62   4.25   180.02|196   H
>           |207   H
>           |210   H
>           |232   H
>           |37   H
>           |95   T
> so it not matching it properly, can anyone please suggest where I am doing mistake.
>
>
>
>   
I'm about to travel all day, so my response will be quite brief.

Not sure what you mean by the blank and key values that source() takes, 
since they're just passed on to its return value.

I don't see any place where you compare the items from the various 
files, so you aren't checking if an item is in multiple files.

DaveA



From e_d_k at yahoo.com  Sun May 16 10:19:14 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sun, 16 May 2010 07:19:14 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <331306.35765.qm@web58706.mail.re1.yahoo.com>

--- On Sat, 5/15/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Saturday, May 15, 2010, 11:06 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > On Fri, 5/14/10, Lawrence D'Oliveiro
> > 
> wrote:
> > 
> >> In message ,
> >> Ed Keith wrote:
> >> 
> >>> Yes, under the GPL every one has one set of
> freedoms,
> >>> under the MIT or Boost license every one has
> more freedoms. Under other
> >>> licenses they have fewer freedoms.
> >> 
> >> But what about the ?freedom? to take away
> other
> >> people?s freedom? Is that really ?freedom??
> > 
> > Yes.
> 
> But that?s a ?freedom? that non-GPL licences do not
> give you, that the GPL 
> does. So which licence gives you more ?freedoms?,
> again?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 


????? You just answered your own question. The The GPL does not give you the freedoms to take away other people freedom, so the the less restrictive license have less restrictions (which is why they are called "less restrictive" by the way) "Less restrictions" is a synonym for "more freedoms". To the extent that something is "restricted" it is not "free". To the extent which something if "free" it is not "restricted". 

There is clearly some kind of communication problem here. Either were are speaking different languages with some faulty transaction program interviewing, or one of is is either stupid or senile (seems a bit early for me, but it is possible); or you are being disingenuous. 

If you type the word 'restrict' into thesaurus.com you will get the following antonyms: enlarge, expand, free, let go, release, Note the second word on the list. Please do not take my word for it, try it yourself. Try other sites, if you think I may have rigged this one.

     -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com





      


From e_d_k at yahoo.com  Sun May 16 10:25:53 2010
From: e_d_k at yahoo.com (Ed Keith)
Date: Sun, 16 May 2010 07:25:53 -0700 (PDT)
Subject: Picking a license
In-Reply-To: 
Message-ID: <216371.45903.qm@web58703.mail.re1.yahoo.com>


--- On Sat, 5/15/10, Lawrence D'Oliveiro  wrote:

> From: Lawrence D'Oliveiro 
> Subject: Re: Picking a license
> To: python-list at python.org
> Date: Saturday, May 15, 2010, 11:09 PM
> In message ,
> Ed Keith 
> wrote:
> 
> > But if my client give someone else a copy of the
> binary I gave them, they
> > are now in violation.
> 
> Why would they be in violation? It seems to me a violation
> would only occur 
> if someone asked them for the source, and they refused.
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

No, the GPL makes it clear that the responsibly is on the distributor to either supply the source or written notice, Caveat venditor. The violation exists regardless of whether or not the recipient makes a request.

   -EdK

Ed Keith
e_d_k at yahoo.com

Blog: edkeith.blogspot.com




      


From aahz at pythoncraft.com  Sun May 16 10:48:06 2010
From: aahz at pythoncraft.com (Aahz)
Date: 16 May 2010 07:48:06 -0700
Subject: joining files
References: <20100516070203.650.qmail@f4mail-234-123.rediffmail.com>
	
Message-ID: 

In article ,
Chris Rebert   wrote:
>
>--
>

That's not funny.  I'm sure I'd have little difficulty finding poor
programmers of whatever demographic groups you belong to.  Or perhaps you
haven't noticed that PEBKACs are everywhere?
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From cjw at ncf.ca  Sun May 16 11:29:44 2010
From: cjw at ncf.ca (cjw)
Date: Sun, 16 May 2010 11:29:44 -0400
Subject: Access to comp.lang.python
In-Reply-To: 
References: 	
	
	
Message-ID: 

On 16-May-10 01:31 AM, James Mills wrote:
> On Sun, May 16, 2010 at 3:12 PM, Aahz  wrote:
>> It's also at least partly due to problems with mail<->news gateways and
>> the differing fields used to maintain threading.
>
> Some blame goes on MUAs too :)

Thanks for the responses.

Is it possible to connect a newsreader to gmane?  Or is web access required?

Is Thunderbird known to have problems?

Colin W


From invalid at invalid.invalid  Sun May 16 11:35:08 2010
From: invalid at invalid.invalid (Grant Edwards)
Date: Sun, 16 May 2010 15:35:08 +0000 (UTC)
Subject: Access to comp.lang.python
References: 
	
	
	
	
Message-ID: 

On 2010-05-16, cjw  wrote:
> On 16-May-10 01:31 AM, James Mills wrote:
>> On Sun, May 16, 2010 at 3:12 PM, Aahz  wrote:
>>> It's also at least partly due to problems with mail<->news gateways and
>>> the differing fields used to maintain threading.
>>
>> Some blame goes on MUAs too :)
>
> Thanks for the responses.
>
> Is it possible to connect a newsreader to gmane?

nntp://news.gmane.org/

-- 
Grant



From stefan_ml at behnel.de  Sun May 16 11:55:26 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sun, 16 May 2010 17:55:26 +0200
Subject: Reading XML namespaces
In-Reply-To: <4BEFB56F.9040102@v.loewis.de>
References: <1273948642.2322.10.camel@linux-yu4c.site>		<1273956059.4023.0.camel@linux-yu4c.site>		<1273957446.4023.6.camel@linux-yu4c.site>			<4BEF3E4D.9090404@v.loewis.de>	
	<4BEFB56F.9040102@v.loewis.de>
Message-ID: 

Martin v. Loewis, 16.05.2010 11:05:
>> Maybe true technically, but false in practice.  If I receive XML data
>> from source XYZ or service XYZ the use of namespaces and their prefixes
>> is extremely consistent [in practice] and very customary (for example:
>> I've never seen the DSML namespace abbreviated as anything other than
>> "dsml" and I rarely see WebDAV propfind XML use a namespace prefix other
>> than "D").  The odds that a customer or vendors ERP will generate
>> different namespaces and abbreviations between requests is ludicrously
>> remote [I don't recall ever seeing it happen].
>
> In that case, you could also hard-code all prefixes in your application;
> no need to traverse the input document.

+1. Hard-coding the prefixes is the best way to make the interface of your 
code consistent and predictable.

Stefan



From john at castleamber.com  Sun May 16 12:17:36 2010
From: john at castleamber.com (John Bokma)
Date: Sun, 16 May 2010 11:17:36 -0500
Subject: Access to comp.lang.python
References: 
	
	
	
	
Message-ID: <87y6fjhlcv.fsf@castleamber.com>

cjw  writes:

> Is it possible to connect a newsreader to gmane?

http://johnbokma.com/mexit/2005/01/14/gmane-mail-to-news.html

> Is Thunderbird known to have problems?

It worked good for me, but that was 5+ years ago. (Time flies)

-- 
John Bokma                                                               j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development


From jf_byrnes at comcast.net  Sun May 16 12:47:22 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Sun, 16 May 2010 11:47:22 -0500
Subject: Access to comp.lang.python
In-Reply-To: 
References: 				
	
Message-ID: <4BF0219A.3080004@comcast.net>

Grant Edwards wrote:
> On 2010-05-16, cjw  wrote:
>> On 16-May-10 01:31 AM, James Mills wrote:
>>> On Sun, May 16, 2010 at 3:12 PM, Aahz   wrote:
>>>> It's also at least partly due to problems with mail<->news gateways and
>>>> the differing fields used to maintain threading.
>>>
>>> Some blame goes on MUAs too :)
>>
>> Thanks for the responses.
>>
>> Is it possible to connect a newsreader to gmane?
>
> nntp://news.gmane.org/
>

Could someone please explain how to subscribe to this list on gmane.  I 
subscribe to a couple of other groups there but can't find this one.

Regards,  Jim


From tlikonen at iki.fi  Sun May 16 13:05:28 2010
From: tlikonen at iki.fi (Teemu Likonen)
Date: Sun, 16 May 2010 20:05:28 +0300
Subject: Object-oriented (was: Is Python a functional programming language?)
References: 
	
	
Message-ID: <87ljbj6alj.fsf_-_@mithlond.arda>

* 2010-05-15 09:42 (-0700), travis wrote:

> PS: Why do people call LISP object-oriented?  Are they smoking crack?
>     No classes, no methods, no member variables... WTF?

Maybe because Common Lisp has a strong support for object-oriented
programming.


Peter Seibel: Practical Common Lisp

    Generic functions and methods (chapter 16)
    http://www.gigamonkeys.com/book/object-reorientation-generic-functions.html

    Classes (chapter 17)
    http://www.gigamonkeys.com/book/object-reorientation-classes.html

Paul Graham: On Lisp

    Object-Oriented Lisp (chapter 25)
    http://www.bookshelf.jp/texi/onlisp/onlisp_26.html#SEC156

Wikipedia: Common Lisp Object System

    http://en.wikipedia.org/wiki/Common_Lisp_Object_System


From thom1948 at gmail.com  Sun May 16 13:36:16 2010
From: thom1948 at gmail.com (Thomas)
Date: Sun, 16 May 2010 10:36:16 -0700 (PDT)
Subject: Updating values in a dictionary
Message-ID: 

Greetings

I am having a darn awful time trying to update a matrix:

row = dict([(x,0) for x in range(3)])
matrix = dict([(x,row) for x in range(-3,4,1)])

matrix[2][1] += 1
matrix[-1][2] += 1

"""
Got: a 1 in all col 1 and 2
{-3: {0: 0, 1: 1, 2: 1},
 -2: {0: 0, 1: 1, 2: 1},
 -1: {0: 0, 1: 1, 2: 1},
  0: {0: 0, 1: 1, 2: 1},
  1: {0: 0, 1: 1, 2: 1},
  2: {0: 0, 1: 1, 2: 1},
  3: {0: 0, 1: 1, 2: 1}}
Expected: a 1 in row 2 col 1 and row -1 col 2
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
  0: {0: 0, 1: 0, 2: 0},
  1: {0: 0, 1: 0, 2: 0},
  2: {0: 0, 1: 1, 2: 0},
  3: {0: 0, 1: 0, 2: 0}}
"""

I must be doing something wrong. Researched and researched. Nothing
clicks.


From half.italian at gmail.com  Sun May 16 13:41:54 2010
From: half.italian at gmail.com (Sean DiZazzo)
Date: Sun, 16 May 2010 10:41:54 -0700 (PDT)
Subject: recursively remove all the directories and files which begin with
	'.'
References: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>
	
	<67827508-ddda-44e8-8b88-aae4f78e23da@o8g2000yqo.googlegroups.com>
Message-ID: <9609b853-c7b1-4357-aaf0-b173aebc6879@11g2000prv.googlegroups.com>

On May 14, 8:27?am, albert kao  wrote:
> On May 14, 11:01?am, J  wrote:
>
>
>
> > On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>
> > > C:\python>rmdir.py
> > > C:\test\com.comp.hw.prod.proj.war\bin
> > > ['.svn', 'com']
> > > d .svn
> > > dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
> > > Traceback (most recent call last):
> > > ?File "C:\python\rmdir.py", line 14, in 
> > > ? ?rmtree(os.path.join(curdir, d))
> > > ?File "C:\Python31\lib\shutil.py", line 235, in rmtree
> > > ? ?onerror(os.remove, fullname, sys.exc_info())
> > > ?File "C:\Python31\lib\shutil.py", line 233, in rmtree
> > > ? ?os.remove(fullname)
> > > WindowsError: [Error 5] Access is denied: 'C:\\test\
> > > \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
>
> > You don't have permissions to remove the subdir or file entries in the
> > .svn directory...
>
> > Maybe that file is still open, or still has a lock attached to it?
>
> I reboot my windows computer and run this script as administrator.
> Do my script has a bug?

Are the directory or files marked as read only?

See this recipe and the comment from Chad Stryker:

http://code.activestate.com/recipes/193736-clean-up-a-directory-tree/

"Although it is true you can use shutil.rmtree() in many cases, there
are some cases where it does not work. For example, files that are
marked read-only under Windows cannot be deleted by shutil.rmtree().
By importing the win32api and win32con modules from PyWin32 and adding
line like "win32api.SetFileAttributes(path,
win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this
obstacle can be overcome."

It might not be your problem, but if it is, this had me stumped for a
few weeks before I found this comment!

~Sean


From clp2 at rebertia.com  Sun May 16 13:48:24 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Sun, 16 May 2010 10:48:24 -0700
Subject: Updating values in a dictionary
In-Reply-To: 
References: 
Message-ID: 

On Sun, May 16, 2010 at 10:36 AM, Thomas  wrote:
> Greetings
>
> I am having a darn awful time trying to update a matrix:
>
> row = dict([(x,0) for x in range(3)])
> matrix = dict([(x,row) for x in range(-3,4,1)])

All the columns refer to the very same row dict (`row` obviously).
Python doesn't do any copying unless you explicitly request it.

Try:
matrix = dict([(x, dict([(x,0) for x in range(3)]) ) for x in range(-3,4,1)])

This way, the row-creation code gets called for each column and thus
fresh row dicts are created rather than all just referencing the exact
same one row dict.
Nested comprehensions may be hard to understand, so you may wish to
write it using a function instead:

def make_row():
    return dict([(x,0) for x in range(3)])

matrix = dict([(x,make_row()) for x in range(-3,4,1)])

See also http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list

Cheers,
Chris
--
http://blog.rebertia.com


From aonlazio at gmail.com  Sun May 16 13:50:29 2010
From: aonlazio at gmail.com (AON LAZIO)
Date: Sun, 16 May 2010 13:50:29 -0400
Subject: Global variables for python applications
Message-ID: 

Hi,
   How can I set up global variables for the entire python applications?
Like I can call and set this variables in any .py files.
   Think of it as a global variable in a single .py file but this is for the
entire application.
   Thanks

-- 
Aonlazio
'Peace is always the way.' NW
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From utente at esempio.net  Sun May 16 13:51:41 2010
From: utente at esempio.net (superpollo)
Date: Sun, 16 May 2010 19:51:41 +0200
Subject: Updating values in a dictionary
In-Reply-To: 
References: 
Message-ID: <4bf030ae$0$40284$4fafbaef@reader2.news.tin.it>

Thomas ha scritto:
> Greetings
> 
> I am having a darn awful time trying to update a matrix:
> 
> row = dict([(x,0) for x in range(3)])
> matrix = dict([(x,row) for x in range(-3,4,1)])
> 
> matrix[2][1] += 1
> matrix[-1][2] += 1
> 
> """
> Got: a 1 in all col 1 and 2
> {-3: {0: 0, 1: 1, 2: 1},
>  -2: {0: 0, 1: 1, 2: 1},
>  -1: {0: 0, 1: 1, 2: 1},
>   0: {0: 0, 1: 1, 2: 1},
>   1: {0: 0, 1: 1, 2: 1},
>   2: {0: 0, 1: 1, 2: 1},
>   3: {0: 0, 1: 1, 2: 1}}
> Expected: a 1 in row 2 col 1 and row -1 col 2
> {-3: {0: 0, 1: 0, 2: 0},
>  -2: {0: 0, 1: 0, 2: 0},
>  -1: {0: 0, 1: 0, 2: 1},
>   0: {0: 0, 1: 0, 2: 0},
>   1: {0: 0, 1: 0, 2: 0},
>   2: {0: 0, 1: 1, 2: 0},
>   3: {0: 0, 1: 0, 2: 0}}
> """
> 
> I must be doing something wrong. Researched and researched. Nothing
> clicks.

clone the row:

 >>> row = dict([(x,0) for x in range(3)])
 >>> import copy
 >>> matrix = dict([(x,copy.copy(row)) for x in range(-3,4,1)])
 >>> matrix[2][1] += 1
 >>> matrix[-1][2] += 1
 >>> import pprint
 >>> pp = pprint.PrettyPrinter()
 >>> pp.pprint(matrix)
{-3: {0: 0, 1: 0, 2: 0},
  -2: {0: 0, 1: 0, 2: 0},
  -1: {0: 0, 1: 0, 2: 1},
  0: {0: 0, 1: 0, 2: 0},
  1: {0: 0, 1: 0, 2: 0},
  2: {0: 0, 1: 1, 2: 0},
  3: {0: 0, 1: 0, 2: 0}}
 >>>

bye



From __peter__ at web.de  Sun May 16 13:58:13 2010
From: __peter__ at web.de (Peter Otten)
Date: Sun, 16 May 2010 19:58:13 +0200
Subject: Updating values in a dictionary
References: 
	
Message-ID: 

Chris Rebert wrote:

> Nested comprehensions may be hard to understand, so you may wish to
> write it using a function instead:
> 
> def make_row():
> return dict([(x,0) for x in range(3)])
> 
> matrix = dict([(x,make_row()) for x in range(-3,4,1)])

Another way to skin the cat:

>>> row = dict.fromkeys(range(3), 0)
>>> matrix = dict((x, row.copy()) for x in range(-3, 4))
>>> matrix[2][1] += 1
>>> matrix[-1][2] += 1
>>> from pprint import pprint
>>> pprint(matrix)
{-3: {0: 0, 1: 0, 2: 0},
 -2: {0: 0, 1: 0, 2: 0},
 -1: {0: 0, 1: 0, 2: 1},
 0: {0: 0, 1: 0, 2: 0},
 1: {0: 0, 1: 0, 2: 0},
 2: {0: 0, 1: 1, 2: 0},
 3: {0: 0, 1: 0, 2: 0}}



From prologic at shortcircuit.net.au  Sun May 16 13:58:18 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 17 May 2010 03:58:18 +1000
Subject: Global variables for python applications
In-Reply-To: 
References: 
Message-ID: 

On Mon, May 17, 2010 at 3:50 AM, AON LAZIO  wrote:
> Hi,
> ?? How can I set up global variables for the entire python applications?
> Like I can call and set this variables in any .py files.
> ?? Think of it as a global variable in a single .py file but this is for the
> entire application.

If you have to use global variables in your application you are
designing it WRONG!

Python has powerful support for object orientated programming. Use it!

I highly recommend the Python tutorial - especially the section on classes.

--James


From irmen-NOSPAM- at xs4all.nl  Sun May 16 13:59:21 2010
From: irmen-NOSPAM- at xs4all.nl (Irmen de Jong)
Date: Sun, 16 May 2010 19:59:21 +0200
Subject: recursively remove all the directories and files which begin
	with  '.'
In-Reply-To: <9609b853-c7b1-4357-aaf0-b173aebc6879@11g2000prv.googlegroups.com>
References: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>
	
	<67827508-ddda-44e8-8b88-aae4f78e23da@o8g2000yqo.googlegroups.com>
	<9609b853-c7b1-4357-aaf0-b173aebc6879@11g2000prv.googlegroups.com>
Message-ID: <4bf03277$0$22938$e4fe514c@news.xs4all.nl>

On 16-5-2010 19:41, Sean DiZazzo wrote:
> On May 14, 8:27 am, albert kao  wrote:
>> On May 14, 11:01 am, J  wrote:
>>
>>
>>
>>> On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>>
>>>> C:\python>rmdir.py
>>>> C:\test\com.comp.hw.prod.proj.war\bin
>>>> ['.svn', 'com']
>>>> d .svn
>>>> dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
>>>> Traceback (most recent call last):
>>>>   File "C:\python\rmdir.py", line 14, in
>>>>     rmtree(os.path.join(curdir, d))
>>>>   File "C:\Python31\lib\shutil.py", line 235, in rmtree
>>>>     onerror(os.remove, fullname, sys.exc_info())
>>>>   File "C:\Python31\lib\shutil.py", line 233, in rmtree
>>>>     os.remove(fullname)
>>>> WindowsError: [Error 5] Access is denied: 'C:\\test\
>>>> \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>>
>>>> --
>>>> http://mail.python.org/mailman/listinfo/python-list
>>
>>> You don't have permissions to remove the subdir or file entries in the
>>> .svn directory...
>>
>>> Maybe that file is still open, or still has a lock attached to it?
>>
>> I reboot my windows computer and run this script as administrator.
>> Do my script has a bug?
>
> Are the directory or files marked as read only?
>
> See this recipe and the comment from Chad Stryker:
>
> http://code.activestate.com/recipes/193736-clean-up-a-directory-tree/
>
> "Although it is true you can use shutil.rmtree() in many cases, there
> are some cases where it does not work. For example, files that are
> marked read-only under Windows cannot be deleted by shutil.rmtree().
> By importing the win32api and win32con modules from PyWin32 and adding
> line like "win32api.SetFileAttributes(path,
> win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this
> obstacle can be overcome."
>
> It might not be your problem, but if it is, this had me stumped for a
> few weeks before I found this comment!
>
> ~Sean

You should be able to do this with os.chmod as well (no extra modules 
required). I'm not sure what the mode should be though. Perhaps 0777 
does the trick.

-irmen



From krister.svanlund at gmail.com  Sun May 16 14:00:46 2010
From: krister.svanlund at gmail.com (Krister Svanlund)
Date: Sun, 16 May 2010 20:00:46 +0200
Subject: Global variables for python applications
In-Reply-To: 
References: 
Message-ID: 

On Sun, May 16, 2010 at 7:50 PM, AON LAZIO  wrote:
> Hi,
> ?? How can I set up global variables for the entire python applications?
> Like I can call and set this variables in any .py files.
> ?? Think of it as a global variable in a single .py file but this is for the
> entire application.
> ?? Thanks
>
> --
> Aonlazio
> 'Peace is always the way.' NW

First: Do NOT use global variables, it is bad practice and will
eventually give you loads of s**t.

But if you want to create global variables in python I do believe it
is possible to specify them in a .py file and then simply import it as
a module in your application. If you change one value in a module the
change will be available in all places you imported that module in.


From clp2 at rebertia.com  Sun May 16 14:01:15 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Sun, 16 May 2010 11:01:15 -0700
Subject: Global variables for python applications
In-Reply-To: 
References: 
Message-ID: 

On Sun, May 16, 2010 at 10:50 AM, AON LAZIO  wrote:
> Hi,
> ?? How can I set up global variables for the entire python applications?
> Like I can call and set this variables in any .py files.
> ?? Think of it as a global variable in a single .py file but this is for the
> entire application.

Thankfully, there is no such thing (can you say spaghetti code?). The
closest approximation, as I said in my previous reply, is to use the
namespace of a designated module for this purpose, and import that
module wherever you need to access/modify these "superglobal"
variables.

Example:
#g.py:
#this module exists to hold superglobal vars
global1 = "foo"
global2 = "bar"


#elsewhere.py:
#this is some other module in the same program
import mypackage.g as g

print "global #1 = ", g.global1
print "global #2 =", g.global2
g.global1 = "baz" # modify a superglobal
g.global3 = "qux" # create a new superglobal


Cheers,
Chris
--
http://blog.rebertia.com


From tuomas.vesterinen at iki.fi  Sun May 16 14:01:17 2010
From: tuomas.vesterinen at iki.fi (Tuomas Vesterinen)
Date: Sun, 16 May 2010 21:01:17 +0300
Subject: joining files
In-Reply-To: 
References: <1273998151.S.3807.41729.H.TkRhdmUgQW5nZWwAUmU6IGpvaW5pbmcgZmlsZXM_.f4-234-213.old.1274015374.26493@webmail.rediffmail.com>
	
Message-ID: <4bf03335$0$11843$9b536df3@news.fv.fi>

On 05/16/2010 05:04 PM, Dave Angel wrote:
> (You forgot to include the python-list in your response.  So it only
> went to me. Normally, you just do reply-all to the message)
>
> mannu jha wrote:
>> On Sun, 16 May 2010 13:52:31 +0530 wrote
>>> mannu jha wrote:
>>
>>> Hi,
>>
>>
>>> I have few files like this:
>>> file1:
>>> 22 110.1 33 331.5 22.7 5 271.9 17.2 33.4
>>> 4 55.1
>>
>>> file1 has total 4 column but some of them are missing in few row.
>>
>>> file2:
>>> 5 H
>>> 22 0
>>
>>> file3:
>>> 4 T
>>> 5 B
>>> 22 C
>>> 121 S
>>
>>
>>> in all these files first column is the main source of matching their
>>> entries. So What I want in the output is only those entries which is
>>> coming in all three files.
>>
>>> output required:
>>
>>> 5 271.9 17.2 33.4 5 H 5 T
>>> 22 110.1 22 0 22 C
>>
>> I am trying with this :
>>
>> from collections import defaultdict
>>
>> def merge(sources):
>> blanks = [blank for items, blank, keyfunc in sources]
>> d = defaultdict(lambda: blanks[:])
>> for index, (items, blank, keyfunc) in enumerate(sources):
>> for item in items:
>> d[keyfunc(item)][index] = item
>> for key in sorted(d):
>> yield d[key]
>>
>> if __name__ == "__main__":
>> a = open("input1.txt")
>> c = open("input2.txt")
>>
>> def key(line):
>> return line[:2]
>> def source(stream, blank="", key=key):
>> return (line.strip() for line in stream), blank, key
>> for m in merge([source(x) for x in [a,c]]):
>> print "|".join(c.ljust(10) for c in m)
>>
>> but with input1.txt:
>> 187 7.79 122.27 54.37 4.26 179.75
>> 194 8.00 121.23 54.79 4.12 180.06
>> 15 8.45 119.04 55.02 4.08 178.89
>> 176 7.78 118.68 54.57 4.20 181.06
>> 180 7.50 119.21 53.93 179.80
>> 190 7.58 120.44 54.62 4.25 180.02
>> 152 8.39 120.63 55.10 4.15 179.10
>> 154 7.79 119.62 54.47 4.22 180.46
>> 175 8.42 120.50 55.31 4.04 180.33
>> and input2.txt:
>> 15 H 37 H 95 T
>> 124 H 130 H 152 H 154 H 158 H 164 H
>> 175 H 176 H 180 H
>> 187 H 190 T
>> 194 C
>> 196 H 207 H 210 H 232 H it is giving output as:
>> |
>> |124 H
>> |130 H
>> 154 7.79 119.62 54.47 4.22 180.46|158 H
>> |164 H
>> 175 8.42 120.50 55.31 4.04 180.33|176 H
>> 180 7.50 119.21 53.93 179.80|187 H
>> 190 7.58 120.44 54.62 4.25 180.02|196 H
>> |207 H
>> |210 H
>> |232 H
>> |37 H
>> |95 T
>> so it not matching it properly, can anyone please suggest where I am
>> doing mistake.
>>
>>
>>
> I'm about to travel all day, so my response will be quite brief.
>
> Not sure what you mean by the blank and key values that source() takes,
> since they're just passed on to its return value.
>
> I don't see any place where you compare the items from the various
> files, so you aren't checking if an item is in multiple files.
>
> DaveA
>
import os

def merge_sources(sources):
     # sources is a list of tuples (source_name, source_data)
     data = []
     keysets = []
     for nme, sce in sources:
         lines = {}
         for line in sce.split(os.linesep):
             lst = line.split()
             lines[lst[0]] = (nme, lst)
         keysets.append(set(lines.keys()))
         data.append(lines)
     common_keys = keysets[0]
     for keys in keysets[1:]:
         common_keys = common_keys.intersection(keys)
     result = {}
     for key in common_keys:
         result[key] = dict(d[key] for d in data if key in d)
     return result

if __name__ == "__main__":
     # Your test files here are replaced by local strings
     print merge_sources([("file1", file1), ("file2", file2), ("file3", 
file3)])
     print merge_sources([("input1", input1), ("input2", input2)])

Test_results = '''
{'22': {'file3': ['22', 'C'],
         'file2': ['22', '0'],
         'file1': ['22', '110.1', '33', '331.5', '22.7', '5', '271.9',
                   '17.2', '33.4']}}

{'194': {'input2': ['194', 'C'],
          'input1': ['194', '8.00', '121.23', '54.79', '4.12',
                     '180.06']},
  '175': {'input2': ['175', 'H', '176', 'H', '180', 'H'],
          'input1': ['175', '8.42', '120.50', '55.31', '4.04',
                     '180.33']},
   '15': {'input2': ['15', 'H', '37', 'H', '95', 'T'],
          'input1': ['15', '8.45', '119.04', '55.02', '4.08',
                     '178.89']},
  '187': {'input2': ['187', 'H', '190', 'T'],
          'input1': ['187', '7.79', '122.27', '54.37', '4.26',
                     '179.75']}}
'''



From prologic at shortcircuit.net.au  Sun May 16 14:20:26 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 17 May 2010 04:20:26 +1000
Subject: Global variables for python applications
In-Reply-To: 
References:  
	
Message-ID: 

On Mon, May 17, 2010 at 4:00 AM, Krister Svanlund
 wrote:
> On Sun, May 16, 2010 at 7:50 PM, AON LAZIO  wrote:
>> ?? How can I set up global variables for the entire python applications?
>> Like I can call and set this variables in any .py files.
>> ?? Think of it as a global variable in a single .py file but this is for the
>> entire application.
>
> First: Do NOT use global variables, it is bad practice and will
> eventually give you loads of s**t.
>
> But if you want to create global variables in python I do believe it
> is possible to specify them in a .py file and then simply import it as
> a module in your application. If you change one value in a module the
> change will be available in all places you imported that module in.

The only place global variables are considered somewhat "acceptable"
are as constants in a module shared as a static value.

Anything else should be an object that you share. Don't get into the
habit of using global variables!

--james


From omsdiver at gmail.com  Sun May 16 14:28:38 2010
From: omsdiver at gmail.com (OMS)
Date: Sun, 16 May 2010 11:28:38 -0700 (PDT)
Subject: Qt and progressBar - how to update
Message-ID: <808ce044-dfd5-44bf-9c5a-ecf3c657eda5@b21g2000vbh.googlegroups.com>

I am quite new to Python and Qt and need very urgently advice on how
to update Qt progressBar while executing a process. I have went thrugh
number of 'google' stuff and saw different solution, hence none worked
for me. The best idea I have seen is the usage of QThread and emiting
signal from thread to MainWindow. I do not know however why the code I
have written is not working. Most likely a stupid 'beginner related'
error but as far as I am beginner I can't get it. There is a code
below:

#!/opt/local/bin/python2.6

import os
import sys
import time
from PyQt4 import QtCore
from PyQt4 import QtGui

from uiTest import Ui_MainWindow

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),
self.runWorker)

    def runWorker(self):
        self.worker = Worker()
        self.connect(self.worker, QtCore.SIGNAL("progressUpdated"),
self.updateWorkerProgress)
        self.worker.start()

    def updateWorkerProgress(self, min, max, progress):
        self.ui.progressBar.setMinimum = min
        self.ui.progressBar.setMaximum = max
        self.ui.progressBar.setValue = progress
        self.ui.progressBar.repaint()
        #print min, progress, max

class Worker(QtCore.QThread):
    __pyqtSignals__ = ("progressUpdated")
    def __init__(self):
        QtCore.QThread.__init__(self)
        self.min = 0
        self.max = 1000
        self.progress = 0
    def run(self):
        for self.progress in range(self.min, self.max):
            self.emit(QtCore.SIGNAL("progressUpdated"), self.min,
self.max, self.progress)
            time.sleep(0.005)

def main():
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

the uiTest is generated by pyuic4 and for reference can be found
below:

# Form implementation generated from reading ui file 'test.ui'
#
# Created: Sun May 16 19:54:59 2010
#      by: PyQt4 UI code generator 4.7.2
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(640, 480)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(40, 40, 113, 32))
        self.pushButton.setObjectName("pushButton")
        self.progressBar = QtGui.QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QtCore.QRect(50, 80, 431, 23))
        self.progressBar.setProperty("value", 24)
        self.progressBar.setObjectName("progressBar")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
 
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow",
"MainWindow", None, QtGui.QApplication.UnicodeUTF8))
 
self.pushButton.setText(QtGui.QApplication.translate("MainWindow",
"PushButton", None, QtGui.QApplication.UnicodeUTF8))


From tuomas.vesterinen at iki.fi  Sun May 16 14:29:10 2010
From: tuomas.vesterinen at iki.fi (Tuomas Vesterinen)
Date: Sun, 16 May 2010 21:29:10 +0300
Subject: Using site-packages with alt-installed Python version
In-Reply-To: 
References: <4befb5c3$0$2537$9b536df3@news.fv.fi>
	
Message-ID: <4bf039e2$0$2008$9b536df3@news.fv.fi>

On 05/16/2010 02:38 PM, Alister wrote:
> On Sun, 16 May 2010 12:07:08 +0300, Tuomas Vesterinen wrote:
>
>> I am testing an application GUI with Python 2.4, 2.5 and 2.6. The native
>> Python (in Fedora 12) is 2.6. Versions 2.4 and 2.5 are alt-installed.
>>
>> Aplication GUI uses:
>> import pygtk
>> pygtk.require('2.0')
>> import gtk
>> import gobject
>>
>> I go to:
>> $ cd /usr/local/lib/python2.4/site-packages
>>
>> and say:
>> $ sudo ln -s /usr/lib/python2.6/site-packages/pygtk.py pygtk.py $ sudo
>> ln -s /usr/lib/python2.6/site-packages/gtk-2.0 gtk-2.0
>>
>> and try:
>> $ python2.4 gui_utils.py
>> Traceback (most recent call last):
>>     File "gui_utils.py", line 57, in ?
>>       import gtk
>>     File
>> "/usr/local/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py", line
>> 30, in ?
>>       import gobject as _gobject
>>     File
>> "/usr/local/lib/python2.4/site-packages/gtk-2.0/gobject/__init__.py",
>> line 26, in ?
>>       from glib import spawn_async, idle_add, timeout_add,
>> timeout_add_seconds, \
>>     File
>> "/usr/local/lib/python2.4/site-packages/gtk-2.0/glib/__init__.py", line
>> 22, in ?
>>       from glib._glib import *
>> ImportError: /usr/lib/libpyglib-2.0-python.so.0: undefined symbol:
>> _PyObject_CallFunction_SizeT
>>
>> What I should say more to get access to the GTK?
>>
>> Tuomas Vesterinen
>
> I am not a great expert on this But I think you need to use the Redhat
> alternatives system to switch between versions rather than trying to
> change things manually.
>
> as i understand it the Alternatives system sets up and changes various
> symlinks to ensure everything works correctly.
>

Yes, my first trial is not the solution because byte compiled .pyc files 
must be produced by the corresponding Python version.

PEP 3147 http://www.python.org/dev/peps/pep-3147 suggests a common 
solution, but only for Python 3.2 and perhaps 2.7. So I am still looking 
for hints. Have You some helpful links to those "Alternatives system"?

Tuomas Vesterinen


From walterwefft at googlemail.com  Sun May 16 14:33:30 2010
From: walterwefft at googlemail.com (Walter Wefft)
Date: Sun, 16 May 2010 19:33:30 +0100
Subject: recursively remove all the directories and files which begin
	with  '.'
In-Reply-To: <4bf03277$0$22938$e4fe514c@news.xs4all.nl>
References: <360f8c82-d705-4329-a269-4559ea7448a4@a21g2000yqn.googlegroups.com>		<67827508-ddda-44e8-8b88-aae4f78e23da@o8g2000yqo.googlegroups.com>	<9609b853-c7b1-4357-aaf0-b173aebc6879@11g2000prv.googlegroups.com>
	<4bf03277$0$22938$e4fe514c@news.xs4all.nl>
Message-ID: 

Irmen de Jong wrote:
> On 16-5-2010 19:41, Sean DiZazzo wrote:
>> On May 14, 8:27 am, albert kao  wrote:
>>> On May 14, 11:01 am, J  wrote:
>>>
>>>
>>>
>>>> On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>>>
>>>>> C:\python>rmdir.py
>>>>> C:\test\com.comp.hw.prod.proj.war\bin
>>>>> ['.svn', 'com']
>>>>> d .svn
>>>>> dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
>>>>> Traceback (most recent call last):
>>>>>   File "C:\python\rmdir.py", line 14, in
>>>>>     rmtree(os.path.join(curdir, d))
>>>>>   File "C:\Python31\lib\shutil.py", line 235, in rmtree
>>>>>     onerror(os.remove, fullname, sys.exc_info())
>>>>>   File "C:\Python31\lib\shutil.py", line 233, in rmtree
>>>>>     os.remove(fullname)
>>>>> WindowsError: [Error 5] Access is denied: 'C:\\test\
>>>>> \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>>>
>>>>> -- 
>>>>> http://mail.python.org/mailman/listinfo/python-list
>>>
>>>> You don't have permissions to remove the subdir or file entries in the
>>>> .svn directory...
>>>
>>>> Maybe that file is still open, or still has a lock attached to it?
>>>
>>> I reboot my windows computer and run this script as administrator.
>>> Do my script has a bug?
>>
>> Are the directory or files marked as read only?
>>
>> See this recipe and the comment from Chad Stryker:
>>
>> http://code.activestate.com/recipes/193736-clean-up-a-directory-tree/
>>
>> "Although it is true you can use shutil.rmtree() in many cases, there
>> are some cases where it does not work. For example, files that are
>> marked read-only under Windows cannot be deleted by shutil.rmtree().
>> By importing the win32api and win32con modules from PyWin32 and adding
>> line like "win32api.SetFileAttributes(path,
>> win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this
>> obstacle can be overcome."
>>
>> It might not be your problem, but if it is, this had me stumped for a
>> few weeks before I found this comment!
>>
>> ~Sean
> 
> You should be able to do this with os.chmod as well (no extra modules 
> required). I'm not sure what the mode should be though. Perhaps 0777 
> does the trick.
> 
> -irmen
> 

def make_readable(fpath):
     '''
     On windows, this will make a read-only file readable.
     '''
     mode = os.stat(fpath)[stat.ST_MODE] | stat.S_IREAD | stat.S_IWRITE
     chmod(fpath, mode)



From thom.1948 at live.com  Sun May 16 14:39:38 2010
From: thom.1948 at live.com (Thomas)
Date: Sun, 16 May 2010 14:39:38 -0400
Subject: Updating values in a dictionary
In-Reply-To: 
References: 
	
Message-ID: <92f55$4bf03bea$6213ba37$27306@ALLTEL.NET>

Chris

Wow, that was a very fast response.
Thank you, it works  (of course)...

Cheers

"Chris Rebert"  wrote in message 
news:mailman.264.1274032106.32709.python-list at python.org...
> On Sun, May 16, 2010 at 10:36 AM, Thomas  wrote:
>> Greetings
>>
>> I am having a darn awful time trying to update a matrix:
>>
>> row = dict([(x,0) for x in range(3)])
>> matrix = dict([(x,row) for x in range(-3,4,1)])
>
> All the columns refer to the very same row dict (`row` obviously).
> Python doesn't do any copying unless you explicitly request it.
>
> Try:
> matrix = dict([(x, dict([(x,0) for x in range(3)]) ) for x in 
> range(-3,4,1)])
>
> This way, the row-creation code gets called for each column and thus
> fresh row dicts are created rather than all just referencing the exact
> same one row dict.
> Nested comprehensions may be hard to understand, so you may wish to
> write it using a function instead:
>
> def make_row():
>    return dict([(x,0) for x in range(3)])
>
> matrix = dict([(x,make_row()) for x in range(-3,4,1)])
>
> See also 
> http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com 



From pacman128 at gmail.com  Sun May 16 14:51:58 2010
From: pacman128 at gmail.com (Paul Carter)
Date: Sun, 16 May 2010 11:51:58 -0700 (PDT)
Subject: imports and exec
Message-ID: <20297a4b-6fc8-4fa0-a203-decdd2586805@l18g2000vbn.googlegroups.com>

We are using python for our build system. Each subproject dir has a
python script that builds it. Parent dirs have python scripts that
recurse into their children and use exec to invoke the python scripts.
Recently we discovered that one of the python scripts works when
invoked directly, but fails when invoked with exec. I've created a
very simple pair of python scripts that demonstrates the problem.
(We're using python 2.6)

Can someone explain or point to a good explanation of why this problem
occurs?

I have two python files: prim.py and sec.py.
prim.py:
-----------------------------------------
#!/usr/bin/env python

##sec2 = open('sec.py')
##exec sec2

def invoke():
  sec = open('sec.py')
  exec sec

invoke()
------------------------------

and sec.py:
----------------------------------
import sys

def sec():
  print('Inside sec(): ' +  str(sys.argv))

print('Outside sec(): ' + str(sys.argv))
sec()
--------------------------------------

When I run prim.py, I get an error:
--------------------------------
Outside sec(): ['./prim.py']
Traceback (most recent call last):
  File "./prim.py", line 10, in 
    invoke()
  File "./prim.py", line 8, in invoke
    exec sec
  File "sec.py", line 7, in 
    sec()
  File "sec.py", line 4, in sec
    print('Inside sec(): ' +  str(sys.argv))
NameError: global name 'sys' is not defined
----------------------------------

I don't understand why the sys import is not visible in the sec()
function. I can fix this by adding a:
  global sys
or
  import sys
inside the sec() function. But I would like to understand why this is
necessary, especially since sys is visible in sec.py outside of the
sec() function. I found this page discussing exec

http://docs.python.org/reference/executionmodel.html

but I'm afraid I couldn't quite follow it. It makes me think that a
free variable is involved, but I don't see how. It did made me try
invoking exec in prim.py outside of the invoke() function (see the
commented out code). Everything worked fine when I did that.

Can someone set me straight? Suggestions on avoiding this problem are
welcome as well!

Thanks in advance.

Paul Carter


From robert.kern at gmail.com  Sun May 16 14:52:17 2010
From: robert.kern at gmail.com (Robert Kern)
Date: Sun, 16 May 2010 13:52:17 -0500
Subject: Qt and progressBar - how to update
In-Reply-To: <808ce044-dfd5-44bf-9c5a-ecf3c657eda5@b21g2000vbh.googlegroups.com>
References: <808ce044-dfd5-44bf-9c5a-ecf3c657eda5@b21g2000vbh.googlegroups.com>
Message-ID: 

On 2010-05-16 13:28 , OMS wrote:
> I am quite new to Python and Qt and need very urgently advice on how
> to update Qt progressBar while executing a process. I have went thrugh
> number of 'google' stuff and saw different solution, hence none worked
> for me. The best idea I have seen is the usage of QThread and emiting
> signal from thread to MainWindow. I do not know however why the code I
> have written is not working. Most likely a stupid 'beginner related'
> error but as far as I am beginner I can't get it. There is a code
> below:
>
> #!/opt/local/bin/python2.6
>
> import os
> import sys
> import time
> from PyQt4 import QtCore
> from PyQt4 import QtGui
>
> from uiTest import Ui_MainWindow
>
> class MainWindow(QtGui.QMainWindow):
>      def __init__(self):
>          QtGui.QMainWindow.__init__(self)
>          self.ui=Ui_MainWindow()
>          self.ui.setupUi(self)
>          self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),
> self.runWorker)
>
>      def runWorker(self):
>          self.worker = Worker()
>          self.connect(self.worker, QtCore.SIGNAL("progressUpdated"),
> self.updateWorkerProgress)
>          self.worker.start()
>
>      def updateWorkerProgress(self, min, max, progress):
>          self.ui.progressBar.setMinimum = min
>          self.ui.progressBar.setMaximum = max
>          self.ui.progressBar.setValue = progress

These should be

self.ui.progressBar.setMinimum(min)
self.ui.progressBar.setMaximum(max)
self.ui.progressBar.setValue(progress)

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From robert.kern at gmail.com  Sun May 16 14:53:06 2010
From: robert.kern at gmail.com (Robert Kern)
Date: Sun, 16 May 2010 13:53:06 -0500
Subject: Access to comp.lang.python
In-Reply-To: <4BF0219A.3080004@comcast.net>
References: 					
	<4BF0219A.3080004@comcast.net>
Message-ID: 

On 2010-05-16 11:47 , Jim Byrnes wrote:
> Grant Edwards wrote:
>> On 2010-05-16, cjw wrote:
>>> On 16-May-10 01:31 AM, James Mills wrote:
>>>> On Sun, May 16, 2010 at 3:12 PM, Aahz wrote:
>>>>> It's also at least partly due to problems with mail<->news gateways
>>>>> and
>>>>> the differing fields used to maintain threading.
>>>>
>>>> Some blame goes on MUAs too :)
>>>
>>> Thanks for the responses.
>>>
>>> Is it possible to connect a newsreader to gmane?
>>
>> nntp://news.gmane.org/
>>
>
> Could someone please explain how to subscribe to this list on gmane. I
> subscribe to a couple of other groups there but can't find this one.

It's name on GMane is gmane.comp.python.general

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From cmpython at gmail.com  Sun May 16 14:57:30 2010
From: cmpython at gmail.com (CM)
Date: Sun, 16 May 2010 11:57:30 -0700 (PDT)
Subject: Human word reader
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
Message-ID: <09bfe5e4-9362-406d-8730-e123bb9ac91c@c7g2000vbc.googlegroups.com>

> > I need help with getting the useful information how do I get the place
> > if I don't now how long the string is?
>
> ? ? ? ? And is it supposed to handle
>
> ? ? ? ? for london give the weather to me
> ? ? ? ? for the london weather give me
>
> ...
>
> ? ? ? ? Do a search on "natural language processing"... You are at the level
> of algorithms, and algorithms are not limited to Python...

Yes, this is a major field of research.  For basic purposes in Python,
maybe just try to trigger off the presence of the word "weather" and
the presence of a particular city's name.  It will not work if the
user tries to trick it ("Don't give me the weather in London"), but,
like a search engine, it will more or less give what people want for
common queries.  Like:

list_of_cities = ['london', 'moscow', 'new york', 'paris']
user_string = 'Give me the weather for London please.'
user_word_list = user_string.split()  #if they put a comma after city,
this will be a problem
for word in user_word_list:
    period_free_word = word.rstrip('.') #strips trailing period for
final word, in case there
    lowered_word = period_free_word.lower()  #makes it case
insensitive
    if lowered_word in list_of_cities:
         print 'The city is: ' + lowered_word
         DoSomething(lowered_word)  #go and get the weather data for
that city I guess

Che






From cmpython at gmail.com  Sun May 16 15:08:13 2010
From: cmpython at gmail.com (CM)
Date: Sun, 16 May 2010 12:08:13 -0700 (PDT)
Subject: Human word reader
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
	<09bfe5e4-9362-406d-8730-e123bb9ac91c@c7g2000vbc.googlegroups.com>
Message-ID: <6305d10e-5c4d-4b2b-8279-a34c670edfff@v18g2000vbc.googlegroups.com>

On May 16, 2:57?pm, CM  wrote:
> > > I need help with getting the useful information how do I get the place
> > > if I don't now how long the string is?
>
> > ? ? ? ? And is it supposed to handle
>
> > ? ? ? ? for london give the weather to me
> > ? ? ? ? for the london weather give me
>
> > ...
>
> > ? ? ? ? Do a search on "natural language processing"... You are at the level
> > of algorithms, and algorithms are not limited to Python...
>
> Yes, this is a major field of research. ?For basic purposes in Python,
> maybe just try to trigger off the presence of the word "weather" and
> the presence of a particular city's name. ?It will not work if the
> user tries to trick it ("Don't give me the weather in London"), but,
> like a search engine, it will more or less give what people want for
> common queries. ?Like:
>
> list_of_cities = ['london', 'moscow', 'new york', 'paris']
> user_string = 'Give me the weather for London please.'
> user_word_list = user_string.split() ?#if they put a comma after city,
> this will be a problem
> for word in user_word_list:
> ? ? period_free_word = word.rstrip('.') #strips trailing period for
> final word, in case there
> ? ? lowered_word = period_free_word.lower() ?#makes it case
> insensitive
> ? ? if lowered_word in list_of_cities:
> ? ? ? ? ?print 'The city is: ' + lowered_word
> ? ? ? ? ?DoSomething(lowered_word) ?#go and get the weather data for
> that city I guess
>
> Che

I forgot to split on two delimiters (a space and a comma).  See here:
http://mail.python.org/pipermail/tutor/2008-August/063570.html

Anyway, you get the idea...


From tjreedy at udel.edu  Sun May 16 15:11:21 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Sun, 16 May 2010 15:11:21 -0400
Subject: Access to comp.lang.python
In-Reply-To: 
References: 				
	
Message-ID: 

On 5/16/2010 11:35 AM, Grant Edwards wrote:
> On 2010-05-16, cjw  wrote:
>> On 16-May-10 01:31 AM, James Mills wrote:
>>> On Sun, May 16, 2010 at 3:12 PM, Aahz   wrote:
>>>> It's also at least partly due to problems with mail<->news gateways and
>>>> the differing fields used to maintain threading.
>>>
>>> Some blame goes on MUAs too :)
>>
>> Thanks for the responses.
>>
>> Is it possible to connect a newsreader to gmane?
>
> nntp://news.gmane.org/

Thunderbird 2 and 3 work fine with it.





From tjreedy at udel.edu  Sun May 16 15:22:20 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Sun, 16 May 2010 15:22:20 -0400
Subject: Updating values in a dictionary
In-Reply-To: 
References: 
Message-ID: 

On 5/16/2010 1:36 PM, Thomas wrote:
> Greetings
>
> I am having a darn awful time trying to update a matrix:
>
> row = dict([(x,0) for x in range(3)])
> matrix = dict([(x,row) for x in range(-3,4,1)])
>
> matrix[2][1] += 1
> matrix[-1][2] += 1

Dicts are fine for sparse matrixes, but when filled in, a list of lists 
is perhaps easier and more efficient. And you can iterate and be 
guaranteed to get the sublists in the expected order.



From xcr4cx at googlemail.com  Sun May 16 15:27:21 2010
From: xcr4cx at googlemail.com (christian schulze)
Date: Sun, 16 May 2010 12:27:21 -0700 (PDT)
Subject: Global variables for python applications
References:  
	 
	
Message-ID: 

On 16 Mai, 20:20, James Mills  wrote:
> On Mon, May 17, 2010 at 4:00 AM, Krister Svanlund
>
>  wrote:
> > On Sun, May 16, 2010 at 7:50 PM, AON LAZIO  wrote:
> >> ?? How can I set up global variables for the entire python applications?
> >> Like I can call and set this variables in any .py files.
> >> ?? Think of it as a global variable in a single .py file but this is for the
> >> entire application.
>
> > First: Do NOT use global variables, it is bad practice and will
> > eventually give you loads of s**t.
>
> > But if you want to create global variables in python I do believe it
> > is possible to specify them in a .py file and then simply import it as
> > a module in your application. If you change one value in a module the
> > change will be available in all places you imported that module in.
>
> The only place global variables are considered somewhat "acceptable"
> are as constants in a module shared as a static value.
>
> Anything else should be an object that you share. Don't get into the
> habit of using global variables!
>
> --james

Exactly! Python's OOP is awesome. Use it. Global vars used as anything
but constants is bad practice. It isn't that much work to implement
that.


From pmaupin at gmail.com  Sun May 16 15:33:09 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sun, 16 May 2010 12:33:09 -0700 (PDT)
Subject: Picking a license
References: 
Message-ID: <078264e1-d518-40ef-acb1-a7234cfc839e@k31g2000vbu.googlegroups.com>

On May 16, 9:19?am, Ed Keith  wrote:
> --- On Sat, 5/15/10, Lawrence D'Oliveiro  wrote:
> > >> But what about the ?freedom? to take away
> > other
> > >> people?s freedom? Is that really ?freedom??
>
> > > Yes.
>
> > But that?s a ?freedom? that non-GPL licences do not
> > give you, that the GPL
> > does. So which licence gives you more ?freedoms?,
> > again?

[ stuff snipped]

> There is clearly some kind of communication problem here. Either were are speaking different languages with some faulty transaction program interviewing, or one of is is either stupid or senile (seems a bit early for me, but it is possible); or you are being disingenuous.

Lawrence is certainly being overly clever.  He is somewhat technically
correct, but is playing a shell game where he moves around who the
potential "freedom" giver is and who the potential "freedom" receiver
is.

The problem is, you have to handle this sort of argument very
carefully, or someone will come along and then point out (again,
somewhat technically correctly) that copyright law restricts the
"freedoms", and the GPL license only gives them out, so where's the
problem?  It's easy to lose sight of where the pea is, particularly
when you were expecting straightforward communication rather than this
sort of sophistry.

When people in this thread previously said that permissive licenses
give you the "freedom" to take away others' "freedoms", but the GPL
does not, the "you" they are referring to is "a person who has
received the software from someone else".

When Lawrence is now saying that the GPL gives you the "freedom" to
take away others' "freedoms" but other licenses do not, the "you" he
is referring to is the "author of the software", who I think we all
agree retains more "freedom" to restrict others' "freedoms" if he uses
the GPL than if he uses a permissive license.

So in this instance, the thing that disappeared under the shell where
you thought it was and reappeared under a different shell was the very
definition of the word "you".  But don't feel bad; some of the
thimbleriggers around here are quite accomplished, and very hard to
catch out.

Regards,
Pat


From omsdiver at gmail.com  Sun May 16 15:38:04 2010
From: omsdiver at gmail.com (OMS)
Date: Sun, 16 May 2010 12:38:04 -0700 (PDT)
Subject: Qt and progressBar - how to update
References: <808ce044-dfd5-44bf-9c5a-ecf3c657eda5@b21g2000vbh.googlegroups.com>
	
Message-ID: <83dbfb8c-31a3-4a90-b623-c017b5ec70f3@p17g2000vbe.googlegroups.com>

On 16 Maj, 20:52, Robert Kern  wrote:
> On 2010-05-16 13:28 , OMS wrote:
>
>
>
> > I am quite new to Python and Qt and need very urgently advice on how
> > to update Qt progressBar while executing a process. I have went thrugh
> > number of 'google' stuff and saw different solution, hence none worked
> > for me. The best idea I have seen is the usage of QThread and emiting
> > signal from thread to MainWindow. I do not know however why the code I
> > have written is not working. Most likely a stupid 'beginner related'
> > error but as far as I am beginner I can't get it. There is a code
> > below:
>
> > #!/opt/local/bin/python2.6
>
> > import os
> > import sys
> > import time
> > from PyQt4 import QtCore
> > from PyQt4 import QtGui
>
> > from uiTest import Ui_MainWindow
>
> > class MainWindow(QtGui.QMainWindow):
> > ? ? ?def __init__(self):
> > ? ? ? ? ?QtGui.QMainWindow.__init__(self)
> > ? ? ? ? ?self.ui=Ui_MainWindow()
> > ? ? ? ? ?self.ui.setupUi(self)
> > ? ? ? ? ?self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),
> > self.runWorker)
>
> > ? ? ?def runWorker(self):
> > ? ? ? ? ?self.worker = Worker()
> > ? ? ? ? ?self.connect(self.worker, QtCore.SIGNAL("progressUpdated"),
> > self.updateWorkerProgress)
> > ? ? ? ? ?self.worker.start()
>
> > ? ? ?def updateWorkerProgress(self, min, max, progress):
> > ? ? ? ? ?self.ui.progressBar.setMinimum = min
> > ? ? ? ? ?self.ui.progressBar.setMaximum = max
> > ? ? ? ? ?self.ui.progressBar.setValue = progress
>
> These should be
>
> self.ui.progressBar.setMinimum(min)
> self.ui.progressBar.setMaximum(max)
> self.ui.progressBar.setValue(progress)
>
> --
> Robert Kern

Thanks. You have saved the day. I knew it must be something only
greenhorn could do.

Once again thanks!


From vincent at vincentdavis.net  Sun May 16 15:55:51 2010
From: vincent at vincentdavis.net (Vincent Davis)
Date: Sun, 16 May 2010 13:55:51 -0600
Subject: Access to comp.lang.python
In-Reply-To: 
References: 
Message-ID: 

I have no problem with threads
Using gmail in a browser.
That said I like how google groups handles email.
I am also ways having to fix the reply on this list to send back to the list
and not to the list and the last author. If someone knows a way to fix that
I would be happy to hear it.

Vincent


On Sat, May 15, 2010 at 4:34 PM, cjw  wrote:

> This isn't about Python but I'm seeking suggestions as to the best way to
> access the newsgroup.
>
> It seems that messages are coming from a number of sources, such as gmane
> and google groups.
>
> The problem is that many messages seem to get unlinked from their threads.
>
> I use Thunderbird 3.0.5 and wonder whether the problem lies with the merge
> process, the server or my reader.
>
> Would it be better to go to gmane, google groups or some such provider.
>
> In the past, use of Ctrl K had neatly disposed of thread that are of no
> interest.
>
> I would welcome advice.
>
> Colin W.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

  *Vincent Davis
720-301-3003 *
vincent at vincentdavis.net
 my blog  |
LinkedIn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From pmaupin at gmail.com  Sun May 16 16:22:08 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sun, 16 May 2010 13:22:08 -0700 (PDT)
Subject: imports and exec
References: <20297a4b-6fc8-4fa0-a203-decdd2586805@l18g2000vbn.googlegroups.com>
Message-ID: 

On May 16, 1:51?pm, Paul Carter  wrote:
> We are using python for our build system. Each subproject dir has a
> python script that builds it. Parent dirs have python scripts that
> recurse into their children and use exec to invoke the python scripts.
> Recently we discovered that one of the python scripts works when
> invoked directly, but fails when invoked with exec. I've created a
> very simple pair of python scripts that demonstrates the problem.
> (We're using python 2.6)
>
> Can someone explain or point to a good explanation of why this problem
> occurs?
>
> I have two python files: prim.py and sec.py.
> prim.py:
> -----------------------------------------
> #!/usr/bin/env python
>
> ##sec2 = open('sec.py')
> ##exec sec2
>
> def invoke():
> ? sec = open('sec.py')
> ? exec sec
>
> invoke()
> ------------------------------
>
> and sec.py:
> ----------------------------------
> import sys
>
> def sec():
> ? print('Inside sec(): ' + ?str(sys.argv))
>
> print('Outside sec(): ' + str(sys.argv))
> sec()
> --------------------------------------
>
> When I run prim.py, I get an error:
> --------------------------------
> Outside sec(): ['./prim.py']
> Traceback (most recent call last):
> ? File "./prim.py", line 10, in 
> ? ? invoke()
> ? File "./prim.py", line 8, in invoke
> ? ? exec sec
> ? File "sec.py", line 7, in 
> ? ? sec()
> ? File "sec.py", line 4, in sec
> ? ? print('Inside sec(): ' + ?str(sys.argv))
> NameError: global name 'sys' is not defined
> ----------------------------------
>
> I don't understand why the sys import is not visible in the sec()
> function. I can fix this by adding a:
> ? global sys
> or
> ? import sys
> inside the sec() function. But I would like to understand why this is
> necessary, especially since sys is visible in sec.py outside of the
> sec() function. I found this page discussing exec
>
> http://docs.python.org/reference/executionmodel.html
>
> but I'm afraid I couldn't quite follow it. It makes me think that a
> free variable is involved, but I don't see how. It did made me try
> invoking exec in prim.py outside of the invoke() function (see the
> commented out code). Everything worked fine when I did that.
>
> Can someone set me straight? Suggestions on avoiding this problem are
> welcome as well!
>
> Thanks in advance.

Yes.  Since you did not pass any dictionaries to your exec of "sec",
sec inherited the globals and locals from the calling function.  So
the import of sys happened in that functions locals (bad practice in
any case) and the globals used by sec() are the globals of your main
module.

Especially if invoked from inside a function, you should always pass a
dict to exec.  Just "exec sec() in {}" will do the trick.  But if you
want to use your caller's dictionaries, you can do "exec sec() in
globals()"  But you should *not* use a functions locals directly if
you are going to modify them (as you are currently doing).

Regards,
Pat


From vicente.soler at gmail.com  Sun May 16 17:42:40 2010
From: vicente.soler at gmail.com (vsoler)
Date: Sun, 16 May 2010 14:42:40 -0700 (PDT)
Subject: global variables in imported modules
Message-ID: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>

Taken from www.python.org, FAQ 2.3 How do I share global variables
across modules?

config.py:

x = 0   # Default value of the 'x' configuration setting


mod.py:

import config
config.x = 1


main.py:

import config       # try removing it
import mod
print config.x

The example, such as shown in the website, works perfectly well.
However, I don't fully understand why I have to import config in
main.py, since it has already been imported by mod.py.

As the website explains, there is only one module namespace for each
module, and mod.py has aleady created the config namespace by
importing it. Why should I import it again in main.py if that
namespace already exists?

If I remove ->   import config       # try removing it     in main.py,
the application does not run

What am I missing?


From pmaupin at gmail.com  Sun May 16 18:05:43 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sun, 16 May 2010 15:05:43 -0700 (PDT)
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
Message-ID: 

On May 16, 4:42?pm, vsoler  wrote:
> Taken fromwww.python.org, FAQ 2.3 How do I share global variables
> across modules?
>
> config.py:
>
> x = 0 ? # Default value of the 'x' configuration setting
>
> mod.py:
>
> import config
> config.x = 1
>
> main.py:
>
> import config ? ? ? # try removing it
> import mod
> print config.x
>
> The example, such as shown in the website, works perfectly well.
> However, I don't fully understand why I have to import config in
> main.py, since it has already been imported by mod.py.
>
> As the website explains, there is only one module namespace for each
> module, and mod.py has aleady created the config namespace by
> importing it. Why should I import it again in main.py if that
> namespace already exists?
>
> If I remove -> ? import config ? ? ? # try removing it ? ? in main.py,
> the application does not run
>
> What am I missing?

What you are missing is that the interpreter has to look *inside* a
namespace in order to actually find the object associated with a
name.  As you found out, there is a namespace per module.  So
main.py's namespace is where the code in main.py will search for
variables.  If 'mod' imports config, then the 'mod' module's namespace
is updated with 'config' -> the config module.  But the act of 'mod'
importing 'config' will not alter the namespace of 'main' at all.  So
if you want to access variable 'x' inside 'config' from main you can
either import config directly into main and access it as config.x, or
you can import config into mod and import mod into main and access it
as mod.config.x.

Regards,
Pat


From rhodri at wildebst.demon.co.uk  Sun May 16 18:23:18 2010
From: rhodri at wildebst.demon.co.uk (Rhodri James)
Date: Sun, 16 May 2010 23:23:18 +0100
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
Message-ID: 

On Sun, 16 May 2010 22:42:40 +0100, vsoler  wrote:

> Taken from www.python.org, FAQ 2.3 How do I share global variables
> across modules?
>
> config.py:
>
> x = 0   # Default value of the 'x' configuration setting
>
>
> mod.py:
>
> import config
> config.x = 1
>
>
> main.py:
>
> import config       # try removing it
> import mod
> print config.x
>
> The example, such as shown in the website, works perfectly well.
> However, I don't fully understand why I have to import config in
> main.py, since it has already been imported by mod.py.

Globals are only global to a module.  As you can see above, they
don't magically appear in the namespace of the module you import
them into (not unless you do something careless like "from config
import *", at which point you deserve all the confusion you're
going to get).  In both mod.py and main.py you get at the global
x through its module: config.x

Now as you say, main.py imports mod.  In exactly the same way as
mod imports config.  *Exactly*.  We get at the contents of mod
(the things in its namespace) in the same way: mod.thing.  When
mod imports config it imports it into its own namespace only;
there is no magic that makes it appear in the namespace of anything
importing mod any more than happens for anything else.

If you want to access config in main.py without importing it
directly because you know that (in this case) mod has already
imported it, you have to access it through the module that did
the importing.  Instead of "config.x", in main it would be
"mod.config.x".

-- 
Rhodri James *-* Wildebeeste Herder to the Masses


From vicente.soler at gmail.com  Sun May 16 18:26:01 2010
From: vicente.soler at gmail.com (vsoler)
Date: Sun, 16 May 2010 15:26:01 -0700 (PDT)
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
	
Message-ID: 

On 17 mayo, 00:05, Patrick Maupin  wrote:
> On May 16, 4:42?pm, vsoler  wrote:
>
>
>
> > Taken fromwww.python.org, FAQ 2.3 How do I share global variables
> > across modules?
>
> > config.py:
>
> > x = 0 ? # Default value of the 'x' configuration setting
>
> > mod.py:
>
> > import config
> > config.x = 1
>
> > main.py:
>
> > import config ? ? ? # try removing it
> > import mod
> > print config.x
>
> > The example, such as shown in the website, works perfectly well.
> > However, I don't fully understand why I have to import config in
> > main.py, since it has already been imported by mod.py.
>
> > As the website explains, there is only one module namespace for each
> > module, and mod.py has aleady created the config namespace by
> > importing it. Why should I import it again in main.py if that
> > namespace already exists?
>
> > If I remove -> ? import config ? ? ? # try removing it ? ? in main.py,
> > the application does not run
>
> > What am I missing?
>
> What you are missing is that the interpreter has to look *inside* a
> namespace in order to actually find the object associated with a
> name. ?As you found out, there is a namespace per module. ?So
> main.py's namespace is where the code in main.py will search for
> variables. ?If 'mod' imports config, then the 'mod' module's namespace
> is updated with 'config' -> the config module. ?But the act of 'mod'
> importing 'config' will not alter the namespace of 'main' at all. ?So
> if you want to access variable 'x' inside 'config' from main you can
> either import config directly into main and access it as config.x, or
> you can import config into mod and import mod into main and access it
> as mod.config.x.
>
> Regards,
> Pat

Thank you Pat, it's very clear.

However, can I be 100% sure that,no matter how I access variable
'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
that either reference of 'x' points to the same id(memory position)?

Thank you


From prologic at shortcircuit.net.au  Sun May 16 18:38:48 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 17 May 2010 08:38:48 +1000
Subject: global variables in imported modules
In-Reply-To: 
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
	 
	
Message-ID: 

On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> However, can I be 100% sure that,no matter how I access variable
> 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> that either reference of 'x' points to the same id(memory position)?

Yes it does unless you re-assign it.

--James


From vicente.soler at gmail.com  Sun May 16 18:45:54 2010
From: vicente.soler at gmail.com (vsoler)
Date: Sun, 16 May 2010 15:45:54 -0700 (PDT)
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
	 
	 
	
Message-ID: <79a4c855-8fbc-4c49-98e6-78a7fe728698@c7g2000vbc.googlegroups.com>

On 17 mayo, 00:38, James Mills  wrote:
> On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> > However, can I be 100% sure that,no matter how I access variable
> > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> > that either reference of 'x' points to the same id(memory position)?
>
> Yes it does unless you re-assign it.
>
> --James

Understood, thank you very much

Vicente Soler


From pmaupin at gmail.com  Sun May 16 18:52:37 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Sun, 16 May 2010 15:52:37 -0700 (PDT)
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
	 
	 
	
Message-ID: 

On May 16, 5:38?pm, James Mills  wrote:
> On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> > However, can I be 100% sure that,no matter how I access variable
> > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> > that either reference of 'x' points to the same id(memory position)?
>
> Yes it does unless you re-assign it.
>
> --James


To expand a bit on what James is saying:

If, for example, inside your main module, you got tired of typing
"mod.config.x" everywhere you were using it, and decided that you
could make a local reference to the same variable:

x = mod.config.x

Now, whenever you use just plain x inside the main module, you are
also referencing the exact same object, *until* some other function
decides to do:

mod.config.x = y

At this point in time, the 'x' inside main references the object that
mod.config.x originally referenced, but mod.config.x now references a
different object.

Unlike C, for example, where the assignment operator physically places
an item into a specific memory location (either fixed globally or
within a stack frame), the assignment operator in python simply stores
a key/value pair into a namespace dictionary.  So whenever you
retrieve a value from the dictionary using that key, you will get the
value that was last associated with that key.

So, 'mod.config.x' will first retrieve the object associated with the
key 'mod' from the main module's namespace dictionary, then will
retrieve the object associated with the key 'config' from that
module's namespace dictionary, then will retrieve the object
associated with the key 'x' from that module's namespace dictionary.
Unless you later modify any of those key/value pairs, subsequent
retrieval will always result in the same final value.

Regards,
Pat


From paul.lafollette at gmail.com  Sun May 16 18:58:45 2010
From: paul.lafollette at gmail.com (Paul LaFollette)
Date: Sun, 16 May 2010 18:58:45 -0400
Subject: A couple questions about classes and inheritance
Message-ID: 

Kind people,
Using Python 3.1

I have been poking around trying to get more insight into Python's
innards, and I have a couple of (marginally) related questions.

First, I've looked a fair bit and can't find how one can find the base
classes of a subclass?  isinstance and issubclass sort of do the
opposite of what I want.  Surely somewhere there is something like

MyThingee.something.orOther.baseClasses()

that returns a tuple of the parents?  If there is, can you point me to
the appropriate documentation?

Second,
I can subclass most builtin things like int and float and list and so
on, and then override operators to play Twilight Zone if I am so
inclined.

  But what happens if I try to subclass function?

First attempt:
>>>
>>> class MyFunction(function):
...       pass
...
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'function' is not defined
>>>

OK.. so second attempt:


>>>
>>> def a():
...       pass
...
>>> a

>>> function
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'function' is not defined
>>> function=type(a)
>>> function

>>>
>>> class MyFunction(function):
...       pass
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: type 'function' is not an acceptable base type
>>>

So, it appears that function is perhaps the equivalent of a Java final
class? Or isn't really a class at all but something that "looks like"
a class?

Anyway, again can you point me to somewhere that I can learn more?  In
particular, is there a list somewhere of the builtin types that are
not subclassable?

I'm willing to root through the source code if that is what I need to
do, but even there (especially there) a hint as to where to start
looking would be helpful.

Thank you in advance,
Paul


From ethan at stoneleaf.us  Sun May 16 19:00:19 2010
From: ethan at stoneleaf.us (Ethan Furman)
Date: Sun, 16 May 2010 16:00:19 -0700
Subject: Picking a license
In-Reply-To: <9c23d9ef-6ddc-4b04-a92a-9aa887411eb4@i31g2000vbt.googlegroups.com>
References: 	<26ceda8d-f1fd-4414-99aa-61870f017fe4@b7g2000yqk.googlegroups.com>	<1e9fbfbf-f312-4286-b2dc-2820671398da@k2g2000yqe.googlegroups.com>
	<2d625c61-7a94-4c71-8953-69c3b3c76d07@k29g2000yqh.googlegroups.com>
	<7bdce8a7-bf7d-4f1f-bc9d-1eca2697497e@d27g2000yqc.googlegroups.com>
	
	<94dccf53-f387-478d-bbc4-0515cc7c4b26@i9g2000yqi.googlegroups.com>
	<3584e080-96c0-44a1-afe6-321deb55c3e2@k29g2000yqh.googlegroups.com>
	<29a51781-1e5c-4422-bb33-4bd7f9dd5690@s29g2000yqd.googlegroups.com>
	
	<41ddb97c-4f54-4bdc-ae33-1f200ab59889@k31g2000vbu.googlegroups.com>
	<47972413-21a8-4427-ae08-a71229fd6432@c7g2000vbc.googlegroups.com>
	
	<9c23d9ef-6ddc-4b04-a92a-9aa887411eb4@i31g2000vbt.googlegroups.com>
Message-ID: <4BF07903.1040304@stoneleaf.us>

Paul Boddie wrote:
> As I said before, spare me the condescension. 

Spare us your self-righteous bull-crap.

Do you think we haven't seen your false accusations and made-up motives 
against Patrick Maupin?  If I cared more and/or had more time, I'd make 
a summary -- but quite frankly Pat has defended himself quite well, 
while being very reasonable, and has said at least twice (more, I'm 
sure) that the choice of license is up to the author, and that there are 
good reasons for choosing any of the free licenses (including the GPL).

~Ethan~


From lists at cheimes.de  Sun May 16 19:17:19 2010
From: lists at cheimes.de (Christian Heimes)
Date: Mon, 17 May 2010 01:17:19 +0200
Subject: A couple questions about classes and inheritance
In-Reply-To: 
References: 
Message-ID: 

> First, I've looked a fair bit and can't find how one can find the base
> classes of a subclass?  isinstance and issubclass sort of do the
> opposite of what I want.  Surely somewhere there is something like
>
> MyThingee.something.orOther.baseClasses()

You can get the direct parents of a class with the attribute __bases__. 
The class attribute __mro__ returns a tuple of for the method resolution 
order. But instead of poking around yourself I suggest you use the 
inspect module. It provides a high level interface.

>>> class Example:
...     pass
...
>>> Example.__bases__
(,)
>>> Example.__mro__
(, )


>    But what happens if I try to subclass function?
>
> First attempt:
>>>>
>>>> class MyFunction(function):
> ....       pass
> ....
> Traceback (most recent call last):
>    File "", line 1, in
> NameError: name 'function' is not defined

There is no object called function in the list of builtins. You can't 
subclass from function anyway so there is no point in accessing the 
function object. If you want to create some callable class you have to 
provide a method call "__call__". It's called when you call the 
instances of your class like a function.

>>> def a():
...     pass
...
>>> type(a)

>>> function = type(a)
>>> class MyFunc(function):
...     pass
...
Traceback (most recent call last):
   File "", line 1, in 
TypeError: type 'function' is not an acceptable base type

> Anyway, again can you point me to somewhere that I can learn more?  In
> particular, is there a list somewhere of the builtin types that are
> not subclassable?

I don't think it's documented anyway. You have to try yourself. In 
general you don't have to subclass builtin types. Some classes are 
tricky to subclass like e.g. immutable classes (str, bytes) or dict.

Christian



From vicente.soler at gmail.com  Sun May 16 19:21:41 2010
From: vicente.soler at gmail.com (vsoler)
Date: Sun, 16 May 2010 16:21:41 -0700 (PDT)
Subject: global variables in imported modules
References: <42c50ee6-6cb3-4704-8ce2-ce3801997ea3@o15g2000vbb.googlegroups.com>
	 
	 
	
	
Message-ID: <4a532680-303c-497f-80dc-0dbbf985a3d9@s41g2000vba.googlegroups.com>

On 17 mayo, 00:52, Patrick Maupin  wrote:
> On May 16, 5:38?pm, James Mills  wrote:
>
> > On Mon, May 17, 2010 at 8:26 AM, vsoler  wrote:
> > > However, can I be 100% sure that,no matter how I access variable
> > > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean
> > > that either reference of 'x' points to the same id(memory position)?
>
> > Yes it does unless you re-assign it.
>
> > --James
>
> To expand a bit on what James is saying:
>
> If, for example, inside your main module, you got tired of typing
> "mod.config.x" everywhere you were using it, and decided that you
> could make a local reference to the same variable:
>
> x = mod.config.x
>
> Now, whenever you use just plain x inside the main module, you are
> also referencing the exact same object, *until* some other function
> decides to do:
>
> mod.config.x = y
>
> At this point in time, the 'x' inside main references the object that
> mod.config.x originally referenced, but mod.config.x now references a
> different object.
>
> Unlike C, for example, where the assignment operator physically places
> an item into a specific memory location (either fixed globally or
> within a stack frame), the assignment operator in python simply stores
> a key/value pair into a namespace dictionary. ?So whenever you
> retrieve a value from the dictionary using that key, you will get the
> value that was last associated with that key.
>
> So, 'mod.config.x' will first retrieve the object associated with the
> key 'mod' from the main module's namespace dictionary, then will
> retrieve the object associated with the key 'config' from that
> module's namespace dictionary, then will retrieve the object
> associated with the key 'x' from that module's namespace dictionary.
> Unless you later modify any of those key/value pairs, subsequent
> retrieval will always result in the same final value.
>
> Regards,
> Pat

Really interesting, it helps a lot.

Thank you


From steve at REMOVE-THIS-cybersource.com.au  Sun May 16 19:55:33 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 16 May 2010 23:55:33 GMT
Subject: A couple questions about classes and inheritance
References: 
Message-ID: <4bf085f5$0$8846$c3e8da3@news.astraweb.com>

On Sun, 16 May 2010 18:58:45 -0400, Paul LaFollette wrote:

> First, I've looked a fair bit and can't find how one can find the base
> classes of a subclass?

subclass.__base__
subclass.__bases__
subclass.__mro__

(The third one stands for "Method Resolution Order".)


See also the inspect module.



> So, it appears that function is perhaps the equivalent of a Java final
> class? Or isn't really a class at all but something that "looks like" a
> class?

No, it really is a class, at least as far as Python is concerned:

>>> type(lambda: None)

>>> type(type(lambda: None))


but as you've discovered, it's also special. Unfortunately I can't find 
any explanation of *why* (other than the obvious that subclassing doesn't 
work).



> Anyway, again can you point me to somewhere that I can learn more?  In
> particular, is there a list somewhere of the builtin types that are not
> subclassable?


I don't believe so. Apart from intellectual curiosity, is there any 
reason you need to know?


This may be helpful:

http://www.python.org/dev/peps/pep-0253/

You can also google for the error message, although in my few minutes of 
searching I've only found people demonstrating the failure and not 
explaining it.

Here's a rather long discussion about subclassing function:

http://mail.python.org/pipermail/python-list/2008-March/531661.html

but again, no explanation of why type(function) isn't subclassable.




-- 
Steven


From pavlovevidence at gmail.com  Sun May 16 20:38:41 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sun, 16 May 2010 17:38:41 -0700 (PDT)
Subject: A couple questions about classes and inheritance
References:  
	
Message-ID: <52bce3fa-2852-46fe-b724-d8ab47ea3285@t26g2000prt.googlegroups.com>

On May 16, 4:17?pm, Christian Heimes  wrote:
> > First, I've looked a fair bit and can't find how one can find the base
> > classes of a subclass? ?isinstance and issubclass sort of do the
> > opposite of what I want. ?Surely somewhere there is something like
>
> > MyThingee.something.orOther.baseClasses()
>
> You can get the direct parents of a class with the attribute __bases__.
> The class attribute __mro__ returns a tuple of for the method resolution
> order. But instead of poking around yourself I suggest you use the
> inspect module. It provides a high level interface.
>
> >>> class Example:
>
> ... ? ? pass
> ...>>> Example.__bases__
> (,)
> >>> Example.__mro__
>
> (, )
>
> > ? ?But what happens if I try to subclass function?
>
> > First attempt:
>
> >>>> class MyFunction(function):
> > .... ? ? ? pass
> > ....
> > Traceback (most recent call last):
> > ? ?File "", line 1, in
> > NameError: name 'function' is not defined
>
> There is no object called function in the list of builtins. You can't
> subclass from function anyway so there is no point in accessing the
> function object. If you want to create some callable class you have to
> provide a method call "__call__". It's called when you call the
> instances of your class like a function.
>
> >>> def a():
>
> ... ? ? pass
> ...>>> type(a)
> 
> >>> function = type(a)
> >>> class MyFunc(function):
>
> ... ? ? pass
> ...
> Traceback (most recent call last):
> ? ?File "", line 1, in 
> TypeError: type 'function' is not an acceptable base type
>
> > Anyway, again can you point me to somewhere that I can learn more? ?In
> > particular, is there a list somewhere of the builtin types that are
> > not subclassable?
>
> I don't think it's documented anyway. You have to try yourself. In
> general you don't have to subclass builtin types. Some classes are
> tricky to subclass like e.g. immutable classes (str, bytes) or dict.


It's not a list, but you can tell if a given type is subclassable by
testing bit 10 of the __flags__ attribute:

type(lambda:0).__flags__ & 1024  ->  0
int.__flags__ & 1024  ->  1024


The reason some types are not subclassable is simply because there's
more involved to write a type at the C level that's subclassable.  For
a lot of types the work wasn't considered worth it.


If you think you want to subclass function, consider whether you can
do what you want with decorator syntax.


Carl Banks


From tjreedy at udel.edu  Sun May 16 20:58:04 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Sun, 16 May 2010 20:58:04 -0400
Subject: A couple questions about classes and inheritance
In-Reply-To: 
References: 
Message-ID: 

On 5/16/2010 6:58 PM, Paul LaFollette wrote:

> Anyway, again can you point me to somewhere that I can learn more?  In
> particular, is there a list somewhere of the builtin types that are
> not subclassable?

I believe that in 3.1, the builtin classes with builtin names can be 
subclassed and and those without cannot. (If you find any exceptionss, 
please post ;-). The ones with names are exactly the ones you are 
expected to directly interact with in normal code.

Terry Jan Reedy



From nagle at animats.com  Sun May 16 21:57:15 2010
From: nagle at animats.com (John Nagle)
Date: Sun, 16 May 2010 18:57:15 -0700
Subject: Global variables for python applications
In-Reply-To: 
References: 
	
	
Message-ID: <4bf09ce6$0$1661$742ec2ed@news.sonic.net>

James Mills wrote:
> The only place global variables are considered somewhat "acceptable"
> are as constants in a module shared as a static value.

    Python really ought to have named constants.

    For one thing, it's fine to share constants across threads, while
sharing globals is generally undesirable.  Also, more compile-time
arithmetic becomes possible.

    Python does have a few built-in named unassignable constants:
"True", "None", "__debug__", etc.  "Ellipsis" is supposed to be a
constant, too, but in fact you can assign to it, at least through Python 3.1.

    I think there's some religious objection to constants in Python, but
it predated threading.

					John Nagle


From mehgcap at gmail.com  Sun May 16 22:41:37 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Sun, 16 May 2010 22:41:37 -0400
Subject: tone generation for motherboard and sound card speakers?
Message-ID: 

Hi all,
I am wondering if there is a way to generate a tone for the
motherboard speaker, like the call to Beep() in C++?

Also, is there a module to generate tones in Python using the sound
card? A module that can beep at a given frequency for a given time
using the usual sine wave is okay, but the fancier the better
(different waves, sweeping, and so on).

My final question will likely hinge upon the answer to the second
question, but is there a way to play a tone in a given position in the
stereo field? For example, I have a Battleship tactical board (my name
for where the little red and white pins go) which I am trying to
sonify using different tones for each status (not fired on, ship
sighted, ship hit, ship sunk). I want each row to play, from top to
bottom, but each square in each row should start at the left and
continue to the last square playing in the right speaker, giving the
user a better idea of where each square is. Oh, this is for blind
users, in case you were wondering why anyone would want to sonify a
battleship board.
Thanks for any information, and note that I am using Python2.6; unless
there is an easy way to use a module meant for 2.5 or before inside a
2.6 project, I would need a 2.6 module.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


From marky1991 at gmail.com  Sun May 16 22:52:41 2010
From: marky1991 at gmail.com (Mark Young)
Date: Sun, 16 May 2010 22:52:41 -0400
Subject: A couple questions about classes and inheritance
In-Reply-To: 
References: 
	
Message-ID: 

You can't subclass Ellipsis.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From prologic at shortcircuit.net.au  Sun May 16 23:34:57 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 17 May 2010 13:34:57 +1000
Subject: Global variables for python applications
In-Reply-To: <4bf09ce6$0$1661$742ec2ed@news.sonic.net>
References:  
	 
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
Message-ID: 

On Mon, May 17, 2010 at 11:57 AM, John Nagle  wrote:
> ? For one thing, it's fine to share constants across threads, while
> sharing globals is generally undesirable. ?Also, more compile-time
> arithmetic becomes possible.
>
> ? Python does have a few built-in named unassignable constants:
> "True", "None", "__debug__", etc. ?"Ellipsis" is supposed to be a
> constant, too, but in fact you can assign to it, at least through Python
> 3.1.
>
> ? I think there's some religious objection to constants in Python, but
> it predated threading.

To be honest, classes work just fine for defining constants.
(Though in my own code I use ALL UPPER CASE variables as it the style).

--James


From steven at REMOVE.THIS.cybersource.com.au  Mon May 17 00:24:08 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 17 May 2010 04:24:08 GMT
Subject: Global variables for python applications
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
	
Message-ID: 

On Mon, 17 May 2010 13:34:57 +1000, James Mills wrote:

> On Mon, May 17, 2010 at 11:57 AM, John Nagle  wrote:
>> ? For one thing, it's fine to share constants across threads, while
>> sharing globals is generally undesirable. ?Also, more compile-time
>> arithmetic becomes possible.
>>
>> ? Python does have a few built-in named unassignable constants:
>> "True", "None", "__debug__", etc. ?"Ellipsis" is supposed to be a
>> constant, too, but in fact you can assign to it, at least through
>> Python 3.1.
>>
>> ? I think there's some religious objection to constants in Python, but
>> it predated threading.
> 
> To be honest, classes work just fine for defining constants. (Though in
> my own code I use ALL UPPER CASE variables as it the style).


In what way are they constant? Can you not modify them and rebind them?


-- 
Steven


From aahz at pythoncraft.com  Mon May 17 00:28:54 2010
From: aahz at pythoncraft.com (Aahz)
Date: 16 May 2010 21:28:54 -0700
Subject: Picking a license
References: 
	
	 <87r5ldbw3k.fsf@benfinney.id.au>
Message-ID: 

In article <87r5ldbw3k.fsf at benfinney.id.au>,
Ben Finney   wrote:
>aahz at pythoncraft.com (Aahz) writes:
>>
>> You can't really sell Open Source software in any practical way;
>> someone will always undercut you once it's out in the wild. You can
>> only sell support for the software, which is entirely different.
>
>Not at all. I've been selling all the software I write for clients for
>the past ten years, and it's all free software. It's been very practical
>for me and those I've worked with.
>
>You can't sell free software like selling loaves of bread, but that's a
>much more limited case and a far cry from your claim. Selling free
>software is quite practical and a good way to fund development of
>software that otherwise wouldn't be written as free software.

>From my POV, if you're not selling COTS, you're really selling support
and consulting services, because that's what keeps your competitors from
just picking up your software and reselling it for cheaper.  BTDT.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From steven at REMOVE.THIS.cybersource.com.au  Mon May 17 00:29:20 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 17 May 2010 04:29:20 GMT
Subject: Global variables for python applications
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
Message-ID: 

On Sun, 16 May 2010 18:57:15 -0700, John Nagle wrote:

> James Mills wrote:
>> The only place global variables are considered somewhat "acceptable"
>> are as constants in a module shared as a static value.
> 
>     Python really ought to have named constants.

+1

Unfortunately, it will most likely require new syntax, and semantics. 
While the concept of a constant is pretty straightforward for immutable 
types like ints and strings, what about mutable types?

And then there's the moratorium, so even if we had agreement on semantics 
and syntax, and a patch, it couldn't be deployed for a few years.



-- 
Steven


From ninmonkeys at gmail.com  Mon May 17 00:31:10 2010
From: ninmonkeys at gmail.com (Jake b)
Date: Sun, 16 May 2010 23:31:10 -0500
Subject: tone generation for motherboard and sound card speakers?
In-Reply-To: 
References: 
Message-ID: 

For sound ( not internal beep ) you can check out:

   - pygame: http://www.pygame.org/project-PygSoundTestTest-1453-.html
   - python.org/sound : http://wiki.python.org/moin/PythonInMusic
   - pk http://trac2.assembla.com/pkaudio/
   - pureData http://puredata.info/Members/thomas/py



-- 
Jake
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From prologic at shortcircuit.net.au  Mon May 17 00:31:23 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 17 May 2010 14:31:23 +1000
Subject: Global variables for python applications
In-Reply-To: 
References:  
	 
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net> 
	
	
Message-ID: 

On Mon, May 17, 2010 at 2:24 PM, Steven D'Aprano
 wrote:
> In what way are they constant? Can you not modify them and rebind them?

It's just style/convention :)
Much like _ to denote private variables and methods!

--james


From pavlovevidence at gmail.com  Mon May 17 00:53:21 2010
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sun, 16 May 2010 21:53:21 -0700 (PDT)
Subject: an element from a set
References: <28560792.post@talk.nabble.com>
	 
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com> 
	
Message-ID: <248cbfa6-5992-4bc3-bef6-a240a901a07b@42g2000prb.googlegroups.com>

On May 14, 11:52?pm, Chris Rebert  wrote:
> On Fri, May 14, 2010 at 11:23 PM, Carl Banks  wrote:
> > On May 14, 9:39?am, Terry Reedy  wrote:
> >> On 5/14/2010 11:24 AM, gerardob wrote:
> >> > Hello, let S be a python set which is not empty
> >> > (http://docs.python.org/library/sets.html)
>
> >> > i would like to obtain one element (anyone, it doesn't matter which one) and
> >> > assign it to a variable.
>
> >> > How can i do this?
>
> >> Depends on whether or not you want the element removed from the set
>
> >> #3.1
> >> ?>>> s=set(range(10))
> >> ?>>> s
> >> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
> >> ?>>> x=next(iter(s))
> >> ?>>> x
> >> 0
> >> ?>>> s
> >> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # x not removed
> >> ?>>> x = s.pop()
> >> ?>>> x
> >> 0
> >> ?>>> s
> >> {1, 2, 3, 4, 5, 6, 7, 8, 9} # x has been removed
>
> >> The choice of 0 is an implementation artifact. It could have been any
> >> member.
>
> > Which brings up an interesting question: how do you get a random
> > element from a set?
>
> > random.choice(list(s))
>
> > is the most straightforward way and will work a lot of the time, but
> > how would you avoid creating the list? ?I can't think of a way off
> > hand.
>
> def random_set_elem(s):
> ? ? iterator = iter(s)
> ? ? n = random.randint(0, len(s)-1)
> ? ? for i in xrange(n):
> ? ? ? ? next(iterator)
> ? ? return next(iterator)
>
> Avoids creating the list, but it's still O(M). If you're gonna pick
> multiple times from the same set, you're better off just converting it
> to a list.

I've never had to do it (at least not in any situations where I had
any reluctance to call list on it), but it seems like a fairly bad
limitation.  Random element from a set is such a natural idea.

Even if we were to modify the set type at the C level to support it, I
can't think of an easy way to get a random element without selection
bias.  For instance, if you start from a random hash code, some
elements are more likely to be selected than others, depending on
distance between entries in the hash table.  You'd probably have to
choose an number in range(len(s)) and count off that many, but then
might as well have just converted it to a list or used an iterator.  A
little disappointing, actually.

Probably the "right" way is to use a binary-tree-based set.


Carl Banks


From steven at REMOVE.THIS.cybersource.com.au  Mon May 17 02:21:17 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 17 May 2010 06:21:17 GMT
Subject: an element from a set
References: <28560792.post@talk.nabble.com>
	
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
	
	<248cbfa6-5992-4bc3-bef6-a240a901a07b@42g2000prb.googlegroups.com>
Message-ID: 

On Sun, 16 May 2010 21:53:21 -0700, Carl Banks wrote:

> I've never had to do it (at least not in any situations where I had any
> reluctance to call list on it), but it seems like a fairly bad
> limitation.  Random element from a set is such a natural idea.

There was a long discussion on the Python-Dev mailing list about that. As 
I recall, there was no consensus about this, and the moratorium hit, so 
as far as I can tell it went absolutely nowhere.

The thread started here:

http://mail.python.org/pipermail/python-dev/2009-October/093227.html

and there was a patch here:

http://mail.python.org/pipermail/python-dev/2009-October/093228.html




-- 
Steven


From davea at ieee.org  Mon May 17 03:16:25 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 17 May 2010 03:16:25 -0400
Subject: joining files
In-Reply-To: <1273998151.S.3807.41729.H.TkRhdmUgQW5nZWwAUmU6IGpvaW5pbmcgZmlsZXM_.f4-234-213.old.1274015374.26493@webmail.rediffmail.com>
References: <1273998151.S.3807.41729.H.TkRhdmUgQW5nZWwAUmU6IGpvaW5pbmcgZmlsZXM_.f4-234-213.old.1274015374.26493@webmail.rediffmail.com>
Message-ID: <4BF0ED49.4060008@ieee.org>

mannu jha wrote:
> On Sun, 16 May 2010 13:52:31 +0530  wrote
>   
>> mannu jha wrote:
>>     
>
>   
>> Hi,
>>     
>
>   
>
>   
>> I have few files like this:
>> file1:
>> 22 110.1 
>> 33 331.5 22.7 
>> 5 271.9 17.2 33.4
>> 4 55.1 
>>     
>
>   
>> file1 has total 4 column but some of them are missing in few row.
>>     
>
>   
>> file2:
>> 5 H
>> 22 0
>>     
>
>   
>> file3:
>> 4 T
>> 5 B
>> 22 C
>> 121 S
>>     
>
>   
>
>   
>> in all these files first column is the main source of matching their entries. So What I want in the output is only those entries which is coming in all three files.
>>     
>
>   
>> output required:
>>     
>
>   
>> 5 271.9 17.2 33.4 5 H 5 T
>> 22 110.1     22 0 22 C
>>     
>
>   
> I am trying with this :
>
> from collections import defaultdict
>
> def merge(sources):
>     blanks = [blank for items, blank, keyfunc in sources]
>     d = defaultdict(lambda: blanks[:])
>     for index, (items, blank, keyfunc) in enumerate(sources):
>         for item in items:
>             d[keyfunc(item)][index] = item
>     for key in sorted(d):
>         yield d[key]
>
> if __name__ == "__main__":
>     a = open("input1.txt")
>     
>     c = open("input2.txt")
>
>     def key(line):
>         return line[:2]
>     def source(stream, blank="", key=key):
>         return (line.strip() for line in stream), blank, key
>     for m in merge([source(x) for x in [a,c]]):
>         print "|".join(c.ljust(10) for c in m)
>
> but with input1.txt:
> 187    7.79   122.27   54.37   4.26   179.75
> 194    8.00   121.23   54.79   4.12   180.06
> 15    8.45   119.04   55.02   4.08   178.89
> 176    7.78   118.68   54.57   4.20   181.06
> 180    7.50   119.21   53.93      179.80
> 190    7.58   120.44   54.62   4.25   180.02
> 152    8.39   120.63   55.10   4.15   179.10
> 154    7.79   119.62   54.47   4.22   180.46
> 175    8.42   120.50   55.31   4.04   180.33
> and input2.txt:
>  15   H 
>  37   H 
>  95   T
> 124   H 
> 130   H 
> 152   H 
> 154   H 
> 158   H 
> 164   H
> 175   H 
> 176   H 
> 180   H
> 187   H 
> 190   T
> 194   C
> 196   H 
> 207   H 
> 210   H 
> 232   H 
> it is giving output as:
>           |
>           |124   H
>           |130   H
> 154    7.79   119.62   54.47   4.22   180.46|158   H
>           |164   H
> 175    8.42   120.50   55.31   4.04   180.33|176   H
> 180    7.50   119.21   53.93      179.80|187   H
> 190    7.58   120.44   54.62   4.25   180.02|196   H
>           |207   H
>           |210   H
>           |232   H
>           |37   H
>           |95   T
> so it not matching it properly, can anyone please suggest where I am doing mistake.
>
>
>   
Several mistakes here, some in making it unnecessarily complex, but I'll 
concentrate on the ones that just don't work.

Your key() function returns the first two characters of the line.  So 
you're keying not on the whole number, but only on the first two digits 
of it.  To find out what's going on, you need to decompose the complex 
line from:
  

            d[keyfunc(item)][index] = item

to some things you can actually examine:
                       key = keyfunc(item)
                       d[key][index] = item


You don't make any check to see if a particular item is in all the 
files.  For your particular data structure, this would mean that a 
particular value in the dictionary (which is a list of two items) has 
all non-blank strings in it.  To do this, you might want to do an all() 
function on the list.


DaveA




From switch2mathan at gmail.com  Mon May 17 03:22:22 2010
From: switch2mathan at gmail.com (gmail)
Date: Sun, 16 May 2010 19:22:22 -1200
Subject: Convert PyUnicodeObject to PyBytesObject in python3.x?
Message-ID: <128a5245954.-448886445627513620.-3443650374649801849@gmail.com>

Hi All,

A variable whose data type is PyUnicodeObject needs to passed to a function as an argument whose data type should be PyBytesObject type 

example :

PyUnicodeObject *p = ...whatever...; 
function (PyByteObject* a); 

function((PyBytesObject *)p);

compiled and got a Bus Error.

Thanks for spending ur valuable time.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From Gabyswisswatch1900 at gmail.com  Mon May 17 03:24:06 2010
From: Gabyswisswatch1900 at gmail.com (Gaby)
Date: Mon, 17 May 2010 15:24:06 +0800
Subject: tone generation for motherboard and sound card speakers?
References: 
Message-ID: 

It is amazing, the Ballon Bleu de Cartier Replica Watches at 
http://www.swizwatch.com/ are perfect, cheap and high quality.

Ballon Bleu de Cartier Watches Collection: 
http://www.swizwatch.com/ballon-bleu-de-cartier-replica-watches.html

Replica Cartier Ballon Bleu de Cartier Two-Tone Ladies Watch W69007Z3
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Two-Tone-Ladies-Watch-W69007Z3-.html

Replica Cartier Ballon Bleu de Cartier 18K Yellow Gold Leather Strap Mens 
Watch W6900551
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-18K-Yellow-Gold-Leather-Strap-Mens-Watch-W6900551.html

Replica Cartier Ballon Bleu de Cartier Two-Tone Mens Watch W69009Z3
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Two-Tone-Mens-Watch-W69009Z3.html

Replica Cartier Ballon Bleu de Cartier 18K Rose Gold Mens Watch W69006Z2
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-18K-Rose-Gold-Mens-Watch-W69006Z2.html

Replica Cartier Ballon Bleu de Cartier Mens Gold Watch W69013Z2

http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Mens-Gold-Watch-W69013Z2.html


Buy more Cartier replica watches at low price by click:
http://www.swizwatch.com/cartier-replica-watches.html

"Alex Hall"  
??????:mailman.280.1274064100.32709.python-list at python.org...
> Hi all,
> I am wondering if there is a way to generate a tone for the
> motherboard speaker, like the call to Beep() in C++?
>
> Also, is there a module to generate tones in Python using the sound
> card? A module that can beep at a given frequency for a given time
> using the usual sine wave is okay, but the fancier the better
> (different waves, sweeping, and so on).
>
> My final question will likely hinge upon the answer to the second
> question, but is there a way to play a tone in a given position in the
> stereo field? For example, I have a Battleship tactical board (my name
> for where the little red and white pins go) which I am trying to
> sonify using different tones for each status (not fired on, ship
> sighted, ship hit, ship sunk). I want each row to play, from top to
> bottom, but each square in each row should start at the left and
> continue to the last square playing in the right speaker, giving the
> user a better idea of where each square is. Oh, this is for blind
> users, in case you were wondering why anyone would want to sonify a
> battleship board.
> Thanks for any information, and note that I am using Python2.6; unless
> there is an easy way to use a module meant for 2.5 or before inside a
> 2.6 project, I would need a 2.6 module.
>
> -- 
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap 




From greg.ewing at canterbury.ac.nz  Mon May 17 03:26:15 2010
From: greg.ewing at canterbury.ac.nz (Gregory Ewing)
Date: Mon, 17 May 2010 19:26:15 +1200
Subject: Human word reader
In-Reply-To: 
References: <11efab98-5422-4f63-80d6-3800e923e767@o12g2000vba.googlegroups.com>
	
Message-ID: <85c8q9FqboU1@mid.individual.net>

Dennis Lee Bieber wrote:

> 	And is it supposed to handle
> 
> 	for london give the weather to me
> 	for the london weather give me

Or

         Where can I buy some new weather boarding for my
         house in London?

:-)

-- 
Greg

> 
> ...
> 
> 	Do a search on "natural language processing"... You are at the level
> of algorithms, and algorithms are not limited to Python...


From greg.ewing at canterbury.ac.nz  Mon May 17 03:39:40 2010
From: greg.ewing at canterbury.ac.nz (Gregory Ewing)
Date: Mon, 17 May 2010 19:39:40 +1200
Subject: Updating values in a dictionary
In-Reply-To: 
References: 
	
Message-ID: <85c9jhFv7fU1@mid.individual.net>

> On 5/16/2010 1:36 PM, Thomas wrote:
>> row = dict([(x,0) for x in range(3)])
>> matrix = dict([(x,row) for x in range(-3,4,1)])
>>
>> matrix[2][1] += 1
>> matrix[-1][2] += 1

Another possibility is to use a single dict with
tuples for the indexes.

   matrix = dict([((x, y), 0) for x in range(-3, 4) for y in range(3)])

   matrix[2, 1] += 1
   matrix[-1, 2] += 1

-- 
Greg


From greg.ewing at canterbury.ac.nz  Mon May 17 03:56:15 2010
From: greg.ewing at canterbury.ac.nz (Gregory Ewing)
Date: Mon, 17 May 2010 19:56:15 +1200
Subject: Global variables for python applications
In-Reply-To: <4bf09ce6$0$1661$742ec2ed@news.sonic.net>
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
Message-ID: <85caikF5auU1@mid.individual.net>

John Nagle wrote:
> Also, more compile-time arithmetic becomes possible.

But only if their values can be computed at compile time. This
leads to a huge can of worms if you want to be able to import
named constants from other modules. A large part of what
currently happens only at run time would have to become
possible at compile time as well. Either that or so many
restrictions would have to be placed on the way that the
values of named constants are specified that they would not
be very useful in practice.

>    I think there's some religious objection to constants in Python,

Not religious, but pragmatic. What appears to be a simple and
obvious idea on the surface turns out not to be nearly so simple
or obvious in a language as dynamic as Python.

-- 
Greg


From mannu_0523 at rediffmail.com  Mon May 17 04:25:37 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 17 May 2010 08:25:37 -0000
Subject: =?utf-8?B?UmU6IFJlOiBqb2luaW5nIGZpbGVz?=
In-Reply-To: <4bf03335$0$11843$9b536df3@news.fv.fi>
Message-ID: <1274034070.S.7524.33809.H.TlR1b21hcyBWZXN0ZXJpbmVuAFJlOiBqb2luaW5nIGZpbGVz.f4-234-216.old.1274084737.24357@webmail.rediffmail.com>


On Sun, 16 May 2010 23:51:10 +0530  wrote
>On 05/16/2010 05:04 PM, Dave Angel wrote:
> (You forgot to include the python-list in your response. So it only
> went to me. Normally, you just do reply-all to the message)
> mannu jha wrote:
>> On Sun, 16 May 2010 13:52:31 +0530 wrote
>>> mannu jha wrote:
>>> Hi,
>>> I have few files like this:
>>> file1:
>>> 22 110.1 33 331.5 22.7 5 271.9 17.2 33.4
>>> 4 55.1
>>> file1 has total 4 column but some of them are missing in few row.
>>> file2:
>>> 5 H
>>> 22 0
>>> file3:
>>> 4 T
>>> 5 B
>>> 22 C
>>> 121 S
>>> in all these files first column is the main source of matching their entries. So What I want in the output is only those entries which is coming in all three files. output required:
>>> 5 271.9 17.2 33.4 5 H 5 T
>>> 22 110.1 22 0 22 C
>> I am trying with this :
>> from collections import defaultdict
>> def merge(sources):
>> blanks = [blank for items, blank, keyfunc in sources]
>> d = defaultdict(lambda: blanks[:])
>> for index, (items, blank, keyfunc) in enumerate(sources):
>> for item in items:
>> d[keyfunc(item)][index] = item
>> for key in sorted(d):
>> yield d[key]
>> if __name__ == "__main__":
>> a = open("input1.txt")
>> c = open("input2.txt")
>> def key(line):
>> return line[:2]
>> def source(stream, blank="", key=key):
>> return (line.strip() for line in stream), blank, key
>> for m in merge([source(x) for x in [a,c]]):
>> print "|".join(c.ljust(10) for c in m)
>> but with input1.txt:
>> 187 7.79 122.27 54.37 4.26 179.75
>> 194 8.00 121.23 54.79 4.12 180.06
>> 15 8.45 119.04 55.02 4.08 178.89
>> 176 7.78 118.68 54.57 4.20 181.06
>> 180 7.50 119.21 53.93 179.80
>> 190 7.58 120.44 54.62 4.25 180.02
>> 152 8.39 120.63 55.10 4.15 179.10
>> 154 7.79 119.62 54.47 4.22 180.46
>> 175 8.42 120.50 55.31 4.04 180.33
>> and input2.txt:
>> 15 H 37 H 95 T
>> 124 H 130 H 152 H 154 H 158 H 164 H
>> 175 H 176 H 180 H
>> 187 H 190 T
>> 194 C
>> 196 H 207 H 210 H 232 H it is giving output as:
>> |
>> |124 H
>> |130 H
>> 154 7.79 119.62 54.47 4.22 180.46|158 H
>> |164 H
>> 175 8.42 120.50 55.31 4.04 180.33|176 H
>> 180 7.50 119.21 53.93 179.80|187 H
>> 190 7.58 120.44 54.62 4.25 180.02|196 H
>> |207 H
>> |210 H
>> |232 H
>> |37 H
>> |95 T
>> so it not matching it properly, can anyone please suggest where I am doing mistake.

import os

def merge_sources(sources):
   # sources is a list of tuples (source_name, source_data)
   data = []
   keysets = []
   for nme, sce in sources:
     lines = {}
     for line in sce.split(os.linesep):
       lst = line.split()
       lines[lst[0]] = (nme, lst)
     keysets.append(set(lines.keys()))
     data.append(lines)
   common_keys = keysets[0]
   for keys in keysets[1:]:
     common_keys = common_keys.intersection(keys)
   result = {}
   for key in common_keys:
     result[key] = dict(d[key] for d in data if key in d)
   return result
if __name__ == "__main__":
   # Your test files here are replaced by local strings
   print merge_sources([("file1", file1), ("file2", file2), ("file3", 
file3)])
   print merge_sources([("input1", input1), ("input2", input2)])
Test_results = '''
{'22': {'file3': ['22', 'C'],
     'file2': ['22', '0'],
     'file1': ['22', '110.1', '33', '331.5', '22.7', '5', '271.9',
          '17.2', '33.4']}}
{'194': {'input2': ['194', 'C'],
     'input1': ['194', '8.00', '121.23', '54.79', '4.12',
           '180.06']},
 '175': {'input2': ['175', 'H', '176', 'H', '180', 'H'],
     'input1': ['175', '8.42', '120.50', '55.31', '4.04',
           '180.33']},
  '15': {'input2': ['15', 'H', '37', 'H', '95', 'T'],
     'input1': ['15', '8.45', '119.04', '55.02', '4.08',
           '178.89']},
 '187': {'input2': ['187', 'H', '190', 'T'],
     'input1': ['187', '7.79', '122.27', '54.37', '4.26',
           '179.75']}}

Dear Sir,

I tried above program but with that it is showing error:
nmruser at caf:~> python join1.py
Traceback (most recent call last):
  File "join1.py", line 24, in 
    print merge_sources([("file1", file1), ("file2", file2), ("file3",
NameError: name 'file1' is not defined                                
nmruser at caf:~> 



-- 

http://mail.python.org/mailman/listinfo/python-list

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From greg.ewing at canterbury.ac.nz  Mon May 17 04:26:05 2010
From: greg.ewing at canterbury.ac.nz (Gregory Ewing)
Date: Mon, 17 May 2010 20:26:05 +1200
Subject: tone generation for motherboard and sound card speakers?
In-Reply-To: 
References: 
Message-ID: <4BF0FD9D.80004@canterbury.ac.nz>

Alex Hall wrote:

> Also, is there a module to generate tones in Python using the sound
> card? A module that can beep at a given frequency for a given time
> using the usual sine wave is okay, but the fancier the better
> (different waves, sweeping, and so on).
> 
> My final question will likely hinge upon the answer to the second
> question, but is there a way to play a tone in a given position in the
> stereo field?

The mixer module of pygame will do all of this, I think:

    http://www.pygame.org/

You may find the rest of pygame useful for implementing your
battleship game as well, if you haven't already chosen a library
for that.

-- 
Greg


From ershantibhushan at gmail.com  Mon May 17 04:34:51 2010
From: ershantibhushan at gmail.com (shanti bhushan)
Date: Mon, 17 May 2010 01:34:51 -0700 (PDT)
Subject: reading XML file using python
Message-ID: 

Hi ,
i am new to python.i want to read the XML file using python it ,by
using DOm or SAX any of them.
I want to read the http://www.google.com(any hyper text) from XML and
print that.
please give me the sample program for this.
regards
Shanti Bhushan
Bangalore,India


From stefan_ml at behnel.de  Mon May 17 05:01:24 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 17 May 2010 11:01:24 +0200
Subject: reading XML file using python
In-Reply-To: 
References: 
Message-ID: 

shanti bhushan, 17.05.2010 10:34:
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com (any hyper text) from XML and
> print that.

Note that web sites usually are HTML, not XML. Are you sure you want to 
read XML as well? Also, DOM/SAX are certainly not the easiest way to 
extract information from XML, use the xml.etree.ElementTree package instead.

To parse HTML from web pages, you can use several different tools in 
Python, see

http://www.google.com/search?q=python+web+scraping

Stefan



From mannu_0523 at rediffmail.com  Mon May 17 05:01:38 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 17 May 2010 09:01:38 -0000
Subject: =?utf-8?B?Rnc6IFJlOiBSZTogUmU6IGpvaW5pbmcgZmlsZXM=?=
Message-ID: <1274086839.S.12359.51906.f4mail-235-142.rediffmail.com.1274086897.56220@webmail.rediffmail.com>

Note: Forwarded message attached

-- Original Message --

From: "mannu jha"mannu_0523 at rediffmail.com
To: mannu_0523 at rediffmail.com
Subject: Re: Re: Re: joining files
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
An embedded message was scrubbed...
From: "mannu jha"
Subject: Re: Re: Re: joining files
Date: no date
Size: 12135
URL: 

From kelnreiter at gmail.com  Mon May 17 05:05:12 2010
From: kelnreiter at gmail.com (Franz Kelnreiter)
Date: Mon, 17 May 2010 11:05:12 +0200
Subject: reading XML file using python
In-Reply-To: 
References: 
Message-ID: 

2010/5/17 shanti bhushan :
> Hi ,
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com(any hyper text) from XML and
> print that.
> please give me the sample program for this.
Hi Shanti,
The question how to read an XML file has already been answerd more
than 50 times within this group. So I fear nobody wont any longer be
willing to repeat this matter every 15 days...
Greetings,
Franz


From simon at brunningonline.net  Mon May 17 05:12:39 2010
From: simon at brunningonline.net (Simon Brunning)
Date: Mon, 17 May 2010 10:12:39 +0100
Subject: reading XML file using python
In-Reply-To: 
References: 
Message-ID: 

On 17 May 2010 09:34:51 UTC+1, shanti bhushan  wrote:
> Hi ,
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com(any hyper text) from XML and
> print that.
> please give me the sample program for this.

Your question isn't very clear. Do you want to read the data from a
URL (such as http://www.google.com) and parse it? If so, you probably
don't want an XML parser as such - try Beautiful Soup.

Or do you have a piece of XML with some URLs in it that you want to
extract? ElementTree in the standard library is one good choice here
if you're not wedded to one of DOM or SAX.

What have you tried so far? No one is going to write code for you, but
we'd be happy to help you fix problems with your own code.
 might be worth a
read.

-- 
Cheers,
Simon B.


From steven at REMOVE.THIS.cybersource.com.au  Mon May 17 05:13:35 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 17 May 2010 09:13:35 GMT
Subject: Global variables for python applications
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
	<85caikF5auU1@mid.individual.net>
Message-ID: 

On Mon, 17 May 2010 19:56:15 +1200, Gregory Ewing wrote:

> John Nagle wrote:
>> Also, more compile-time arithmetic becomes possible.
> 
> But only if their values can be computed at compile time.

John said "more", not "everything imaginable can be calculated at compile 
time" :)

Python already does constant folding at compile time:


>>> code = compile('"abc"*2*3', '', 'single')
>>> dis.dis(code)
  1           0 LOAD_CONST               5 ('abcabcabcabcabcabc')
              3 PRINT_EXPR
              4 LOAD_CONST               3 (None)
              7 RETURN_VALUE



> This leads to
> a huge can of worms if you want to be able to import named constants
> from other modules.


Why? Once the module is loaded, the named constant is bound to an object. 
Provided that it can't be rebound or mutated, where's the can of worms?


> A large part of what currently happens only at run
> time would have to become possible at compile time as well. Either that
> or so many restrictions would have to be placed on the way that the
> values of named constants are specified that they would not be very
> useful in practice.

I disagree. Enforcing immutability would be tricky, but enforcing once-
only name binding is relatively simple. There's even a recipe for it in 
the Python Cookbook.




-- 
Steven


From switch2mathan at gmail.com  Mon May 17 05:24:07 2010
From: switch2mathan at gmail.com (gmail)
Date: Sun, 16 May 2010 21:24:07 -1200
Subject: Issue with PyUnicodeObject type variables
Message-ID: <128a593d08d.2531741629325199127.7040266275157033338@gmail.com>

A variable whose data type is PyUnicodeObject checked whether it is a UnicodeObject type.
Got output as false

example :

PyUnicodeObject *p; 

if (PyUnicode_Check(path)) {
        printf("\nTrue.\n");
        
}
else {
        printf("\nfalse.\n");
}

output: false


Confused what went wrong.

regards
mathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From utente at esempio.net  Mon May 17 05:24:34 2010
From: utente at esempio.net (superpollo)
Date: Mon, 17 May 2010 11:24:34 +0200
Subject: reading XML file using python
In-Reply-To: 
References: 
	
Message-ID: <4bf10b53$0$31374$4fafbaef@reader1.news.tin.it>

Simon Brunning ha scritto:
> On 17 May 2010 09:34:51 UTC+1, shanti bhushan  wrote:
>> Hi ,
>> i am new to python.i want to read the XML file using python it ,by
>> using DOm or SAX any of them.
>> I want to read the http://www.google.com(any hyper text) from XML and
>> print that.
>> please give me the sample program for this.
> 
> Your question isn't very clear. Do you want to read the data from a
> URL (such as http://www.google.com) and parse it? If so, you probably
> don't want an XML parser as such - try Beautiful Soup.

btw, is there any chance that bs will be part of the stdlib anytime soon?

bye


From stefan_ml at behnel.de  Mon May 17 05:33:40 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 17 May 2010 11:33:40 +0200
Subject: Issue with PyUnicodeObject type variables
In-Reply-To: <128a593d08d.2531741629325199127.7040266275157033338@gmail.com>
References: <128a593d08d.2531741629325199127.7040266275157033338@gmail.com>
Message-ID: 

gmail, 17.05.2010 11:24:
> A variable whose data type is PyUnicodeObject checked whether it is a UnicodeObject type.
> Got output as false
>
> example :
>
> PyUnicodeObject *p;
> if (PyUnicode_Check(path)) {
>          printf("\nTrue.\n");
>
> }
> else {
>          printf("\nfalse.\n");
> }
>
> output: false

Doesn't surprise me at all. Could you make sure this is the code you are 
using? Especially the names 'p' and 'path'? And that you are initialising 
neither of the two in your code?

Stefan



From stefan_ml at behnel.de  Mon May 17 05:35:21 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 17 May 2010 11:35:21 +0200
Subject: reading XML file using python
In-Reply-To: <4bf10b53$0$31374$4fafbaef@reader1.news.tin.it>
References: 	
	<4bf10b53$0$31374$4fafbaef@reader1.news.tin.it>
Message-ID: 

superpollo, 17.05.2010 11:24:
> Simon Brunning ha scritto:
>> On 17 May 2010 09:34:51 UTC+1, shanti bhushan wrote:
>>> i am new to python.i want to read the XML file using python it ,by
>>> using DOm or SAX any of them.
>>> I want to read the http://www.google.com(any hyper text) from XML and
>>> print that.
>>> please give me the sample program for this.
>>
>> Your question isn't very clear. Do you want to read the data from a
>> URL (such as http://www.google.com) and parse it? If so, you probably
>> don't want an XML parser as such - try Beautiful Soup.
>
> btw, is there any chance that bs will be part of the stdlib anytime soon?

If someone takes over maintainership and offers support for the stdlib, 
this might be worth discussing. Otherwise, no.

Stefan



From simon at brunningonline.net  Mon May 17 05:49:38 2010
From: simon at brunningonline.net (Simon Brunning)
Date: Mon, 17 May 2010 10:49:38 +0100
Subject: reading XML file using python
In-Reply-To: 
References: 
	
	
Message-ID: 

On 17 May 2010 10:43:06 UTC+1, Shanti Bhushan  wrote:
> Hi simon,
> you are right in 2nd paragaraph.
> i have a piece of XML with some URLs in it that?i want to
> extract.
> I have no clue from where to get help on this.
> Please atleast guide me for document or link where i can get such help
> i can use elementary tree also but i dont know how to proceed with that.

You've not given us any idea as to the structure of your XML, so this
won't work. ;-)

import xml.etree.ElementTree as ET

for node in ET.parse('our.xml'):
    print node.text

An introduction to ElementTree at .

-- 
Cheers,
Simon B.


From jmheralds at gmail.com  Mon May 17 06:05:58 2010
From: jmheralds at gmail.com (James Heralds)
Date: Mon, 17 May 2010 03:05:58 -0700 (PDT)
Subject: Call for papers: SETP-10, USA, July 2010
Message-ID: <64a2e2d5-5416-4831-870f-1fd07ec524b7@r9g2000vbk.googlegroups.com>

It would be highly appreciated if you could share this announcement
with your colleagues, students and individuals whose research is in
software engineering, software testing, software quality assurance,
software design and related areas.

Call for papers: SETP-10, USA, July 2010

The 2010 International Conference on Software Engineering Theory and
Practice (SETP-10) (website: http://www.PromoteResearch.org ) will be
held during 12-14 of July 2010 in Orlando, FL, USA.  SETP is an
important event in the areas of Software development, maintenance, and
other areas of software engineering and related topics.

The conference will be held at the same time and location where
several other major international conferences will be taking place.
The conference will be held as part of 2010 multi-conference
(MULTICONF-10). MULTICONF-10 will be held during July 12-14, 2010 in
Orlando, Florida, USA. The primary goal of MULTICONF is to promote
research and developmental activities in computer science, information
technology, control engineering, and related fields. Another goal is
to promote the dissemination of research to a multidisciplinary
audience and to facilitate communication among researchers,
developers, practitioners in different fields. The following
conferences are planned to be organized as part of MULTICONF-10.

?	International Conference on Artificial Intelligence and Pattern
Recognition (AIPR-10)
?	 International Conference on Automation, Robotics and Control
Systems (ARCS-10)
?	International Conference on Bioinformatics, Computational Biology,
Genomics and Chemoinformatics (BCBGC-10)
?	International Conference on Computer Communications and Networks
(CCN-10)
?	International Conference on Enterprise Information Systems and Web
Technologies (EISWT-10)
?	International Conference on High Performance Computing Systems
(HPCS-10)
?	International Conference on Information Security and Privacy
(ISP-10)
?	International Conference on Image and Video Processing and Computer
Vision (IVPCV-10)
?	International Conference on Software Engineering Theory and Practice
(SETP-10)
?	International Conference on Theoretical and Mathematical Foundations
of Computer Science (TMFCS-10)

MULTICONF-10 will be held at Imperial Swan Hotel and Suites.  It is a
full-service resort that puts you in the middle of the fun! Located
1/2 block south of the famed International Drive, the hotel is just
minutes from great entertainment like Walt Disney World? Resort,
Universal Studios and Sea World Orlando. Guests can enjoy free
scheduled transportation to these theme parks, as well as spacious
accommodations, outdoor pools and on-site dining ? all situated on 10
tropically landscaped acres. Here, guests can experience a full-
service resort with discount hotel pricing in Orlando.


We invite draft paper submissions. Please see the website
http://www.PromoteResearch.org  for more details.

Sincerely
James Heralds


From switch2mathan at gmail.com  Mon May 17 06:12:45 2010
From: switch2mathan at gmail.com (mathan kumar)
Date: Mon, 17 May 2010 15:42:45 +0530
Subject: Conversion method for PyUnicodeObject type to PyBytesObject type
Message-ID: 

A variable whose data type is PyUnicodeObject needs to be passed to a
function as an argument whose data type should be PyBytesObject type

example :
function (PyByteObject* a){
.....operations....
}
PyUnicodeObject *p = somevalue;
function((PyBytesObject *)p);

ouptut: Got a Bus Error.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From switch2mathan at gmail.com  Mon May 17 06:16:34 2010
From: switch2mathan at gmail.com (mathan kumar)
Date: Mon, 17 May 2010 15:46:34 +0530
Subject: Issue with PyUnicodeObject type variables
Message-ID: 

---------- Forwarded message ----------
From: Stefan Behnel 
To: python-list at python.org
Date: Mon, 17 May 2010 11:33:40 +0200
Subject: Re: Issue with PyUnicodeObject type variables
gmail, 17.05.2010 11:24:

> A variable whose data type is PyUnicodeObject checked whether it is a
> UnicodeObject type.
> Got output as false
>
> example :
>
> PyUnicodeObject *p;
> if (PyUnicode_Check(path)) {
>         printf("\nTrue.\n");
>
> }
> else {
>         printf("\nfalse.\n");
> }
>
> output: false
>

Doesn't surprise me at all. Could you make sure this is the code you are
using? Especially the names 'p' and 'path'? And that you are initialising
neither of the two in your code?

Stefan


Tat was a typo mistake instead of *p pls consider *path as follows.

PyUnicodeObject *path;
if (PyUnicode_Check(path)) {
        printf("\nTrue.\n");

}
else {
        printf("\nfalse.\n");
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From eric.brunel.pragmadev at gmail.com  Mon May 17 06:18:37 2010
From: eric.brunel.pragmadev at gmail.com (eb303)
Date: Mon, 17 May 2010 03:18:37 -0700 (PDT)
Subject: platform-independent image copy/paste with Tkinter?
References: 
Message-ID: <74406aa5-e570-40d5-97c8-e638c37810e2@j27g2000vbp.googlegroups.com>

On May 15, 4:56?pm, technocake  wrote:
> Hi.
>
> Is there a good way to copy from or paste to the clipboard on all
> systems running python using Tkinter?
> started a small road too it here:
>
> #!/usr/bin/python
> __author__="technocake"
> __date__ ="$15.mai.2010 15:53:39$"
>
> from Tkinter import *
>
> if __name__ == "__main__":
>
> ? ? def displayClipboard(event):
> ? ? ? ? try:
> ? ? ? ? ? ? data = event.widget.clipboard_get(type="STRING")
> ? ? ? ? except :
> ? ? ? ? ? ? #Need a method for displaying a image here..
> ? ? ? ? ? ? data = "Image" #
> ? ? ? ? finally: #Updates the textlabel
> ? ? ? ? ? ? lbl.config(text=data)
>
> ? ? root = Tk()
> ? ? lbl= Label(root, width=20)
> ? ? lbl.bind("", displayClipboard) #binding to leftclick
> ? ? lbl.pack()
>
> ? ? root.mainloop()

The copy part is done via the methods clipboard_clear and
clipboard_append, available on all Tkinter widgets. By the way, the
default value for the 'type' option is 'STRING', so you actually don't
need it here, and neither do you in clipboard_append.

To be able to copy/paste images is much more platform dependent. There
are actually types for clipboard contents that handle images, but they
will vary from platform to platform and sometimes from application to
application. You can even have several types for the same contents. To
get these, you can use:
widget.selection_get(selection='CLIPBOARD', type='TARGETS')
You can try to copy an image on various platforms with various
applications, then print the value for this expression to figure out
what you can do with it.

HTH
 - Eric -


From kaklis at gmail.com  Mon May 17 06:23:03 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Mon, 17 May 2010 03:23:03 -0700 (PDT)
Subject: parsing XML
References: 
	<4beec709$0$18653$4fafbaef@reader3.news.tin.it>
	 
	 
	
Message-ID: <8ff02667-182e-4fad-a621-9eaa4437ad25@p17g2000vbe.googlegroups.com>

On May 16, 10:52?am, Stefan Behnel  wrote:
> Jake b, 16.05.2010 09:40:
>
> > Check out Amara:http://www.xml3k.org/Amara/QuickRef
>
> > It looks promising. For a pythonic solution over sax / dom.
>
> > >>> Iter(doc.team.player)
> > # or
> > >>> doc.team.player[0].name
>
> Ah, right, and there's also lxml.objectify:
>
> ? ? ?from lxml.objectify import parse
>
> ? ? ?root = parse('teamfile.xml').getroot()
>
> ? ? ?for player in root.player:
> ? ? ? ? ?print(player.attrib)
>
> Prints an attribute dict for each player.
>
> Stefan

Thank you all so much!!!
And it's not for a homework.
Just trying to find out the style DOM, SAX, ElementTree etc. that fits
better to my kind of thinking.
Antonis


From stefan_ml at behnel.de  Mon May 17 06:27:05 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 17 May 2010 12:27:05 +0200
Subject: Issue with PyUnicodeObject type variables
In-Reply-To: 
References: 
Message-ID: 

mathan kumar, 17.05.2010 12:16:
> From: Stefan Behnel
>> Doesn't surprise me at all. Could you make sure this is the code you are
>> using? Especially the names 'p' and 'path'? And that you are initialising
>> neither of the two in your code?
>
> Tat was a typo mistake instead of *p pls consider *path as follows.
>
> PyUnicodeObject *path;
> if (PyUnicode_Check(path)) {

Again, you are not initialising the pointer, so it contains an arbitrary 
value when you run the program. You are lucky that it gives you a result at 
all, instead of just plain crashing.

You do not seem to have much experience with C. Is there any reason why you 
want to use it? Or is this just for curiosity?

Stefan



From bryanjugglercryptographer at yahoo.com  Mon May 17 06:42:43 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Mon, 17 May 2010 03:42:43 -0700 (PDT)
Subject: an element from a set
References: <28560792.post@talk.nabble.com>
	 
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com> 
	
	<248cbfa6-5992-4bc3-bef6-a240a901a07b@42g2000prb.googlegroups.com>
Message-ID: <84fd3929-ab9c-4e7d-9d3f-533f4313d7eb@q36g2000prg.googlegroups.com>

Carl Banks wrote:
[...]
>?Random element from a set is such a natural idea.
>
> Even if we were to modify the set type at the C level to support it, I
> can't think of an easy way to get a random element without selection
> bias. ?For instance, if you start from a random hash code, some
> elements are more likely to be selected than others, depending on
> distance between entries in the hash table. ?You'd probably have to
> choose an number in range(len(s)) and count off that many, but then
> might as well have just converted it to a list or used an iterator. ?A
> little disappointing, actually.
>
> Probably the "right" way is to use a binary-tree-based set.

There's a reasonably straightforward solution supporting O(1) time
random choice that also preserves the O(1) average-case time of set's
add(), remove(), and 'in'. The trick is to keep each element in both a
list and a hash table. Implementing Python's entire set interface is a
bit of project, so the code below just supports enough for a demo.

-Bryan Olson

# --------

from random import choice

class SetWithRandom:

    def __init__(self, *args):
        self.lst = list(*args)
        self.dct = dict((elem, i) for (i, elem) in
                enumerate(self.lst))

    def audit(self):
        # Test consistency of dict and list.
        assert len(self.lst) == len(self.dct)
        for elem in self.dct:
            assert self.lst[self.dct[elem]] == elem

    def random(self):
        return choice(self.lst)

    def add(self, elem):
        if elem not in self.dct:
            self.dct[elem] = len(self.lst)
            self.lst.append(elem)

    def remove(self, elem):
        index = self.dct[elem]
        # Move the last item into vacated index.
        mover = self.lst[-1]
        self.lst[index] = mover
        self.dct[mover] = index
        del self.dct[elem]
        self.lst.pop()

    def __len__(self):
        return len(self.lst)

    def __contains__(self, elem):
        return elem in self.dct

    def __iter__(self):
        return self.dct.__iter__()


# ---------
# Test against Python's built-in set.
for i in range(0, 100, 20):
    trange = list(range(1000, 1000 + i))
    pyset = set(trange)
    testset = SetWithRandom(pyset)
    testset.audit()
    assert pyset == set(testset)
    rands = set(testset.random() for _ in trange)
    assert len(rands) >= i / 4
    while pyset:
        randx = testset.random()
        pyset.remove(randx)
        testset.remove(randx)
        testset.audit()
        for _ in range(choice([0, 0, 1, 2])):
            randx = choice(trange)
            pyset.add(randx)
            testset.add(randx)
        assert pyset == set(testset)
    assert not testset



From kaklis at gmail.com  Mon May 17 08:11:25 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Mon, 17 May 2010 05:11:25 -0700 (PDT)
Subject: cmd with three arguments
Message-ID: 

Hi pythonistas,
While playing with the Python Standard Library, i came across "cmd".
So I'm trying to make a console application. Everything works fine, i
created many function with do_....(self, line) prefix, but when i
tried to create a function with more arguments
 i can't make it work.  e.g
def do_connect(self, ip, command):

>>> connect 127.0.0.1 delete
 Are there any work arounds

Thanks in advance

Antonis


From python.list at tim.thechases.com  Mon May 17 09:12:39 2010
From: python.list at tim.thechases.com (Tim Chase)
Date: Mon, 17 May 2010 08:12:39 -0500
Subject: cmd with three arguments
In-Reply-To: 
References: 
Message-ID: <4BF140C7.3030502@tim.thechases.com>

On 05/17/2010 07:11 AM, kaklis at gmail.com wrote:
> While playing with the Python Standard Library, i came across "cmd".
> So I'm trying to make a console application. Everything works fine, i
> created many function with do_....(self, line) prefix, but when i
> tried to create a function with more arguments
>   i can't make it work.  e.g
> def do_connect(self, ip, command):
>
>>>> connect 127.0.0.1 delete
>   Are there any work arounds

You simply receive all the text after the command:

   class C(Cmd):
     def do_thing(self, arguments):
       print repr(arguments)

If you want to split it, you can do it boringly:

     def do_thing(self, arguments):
       args = arguments.split()

or you can let Python's standard library do some heavy-lifting 
for you:

   import shlex
   #...
     def do_thing(self, arguments):
       args = shlex.split(arguments)

-tkc





From oxfordenergyservices at googlemail.com  Mon May 17 09:20:42 2010
From: oxfordenergyservices at googlemail.com (a)
Date: Mon, 17 May 2010 06:20:42 -0700 (PDT)
Subject: python application question
Message-ID: <8df6cb20-f822-4286-a075-2633c6025e84@z17g2000vbd.googlegroups.com>

I am trying to write an application that takes two files from over the
internet and plots one against the other

i am getting the data ok.

if i want to plot it i have to use something like matplotlib?  but
this doesn't come with the standard installation.  so if i want
someone else to use this application, do they have to install
matplotlib themselves or is there a better way?

ps someone helped me with enumerate(), which works on the linux but
not on the windows?

thanks


From kaklis at gmail.com  Mon May 17 09:25:30 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Mon, 17 May 2010 06:25:30 -0700 (PDT)
Subject: cmd with three arguments
References: 
	
Message-ID: <2897c931-8809-4a3f-9dc8-d05e74a376d7@z17g2000vbd.googlegroups.com>

On May 17, 4:12?pm, Tim Chase  wrote:
> On 05/17/2010 07:11 AM, kak... at gmail.com wrote:
>
> > While playing with the Python Standard Library, i came across "cmd".
> > So I'm trying to make a console application. Everything works fine, i
> > created many function with do_....(self, line) prefix, but when i
> > tried to create a function with more arguments
> > ? i can't make it work. ?e.g
> > def do_connect(self, ip, command):
>
> >>>> connect 127.0.0.1 delete
> > ? Are there any work arounds
>
> You simply receive all the text after the command:
>
> ? ?class C(Cmd):
> ? ? ?def do_thing(self, arguments):
> ? ? ? ?print repr(arguments)
>
> If you want to split it, you can do it boringly:
>
> ? ? ?def do_thing(self, arguments):
> ? ? ? ?args = arguments.split()
>
> or you can let Python's standard library do some heavy-lifting
> for you:
>
> ? ?import shlex
> ? ?#...
> ? ? ?def do_thing(self, arguments):
> ? ? ? ?args = shlex.split(arguments)
>
> -tkc

Thanks, great answer!!!


From __peter__ at web.de  Mon May 17 09:34:10 2010
From: __peter__ at web.de (Peter Otten)
Date: Mon, 17 May 2010 15:34:10 +0200
Subject: cmd with three arguments
References: 
Message-ID: 

kaklis at gmail.com wrote:

> Hi pythonistas,
> While playing with the Python Standard Library, i came across "cmd".
> So I'm trying to make a console application. Everything works fine, i
> created many function with do_....(self, line) prefix, but when i
> tried to create a function with more arguments
>  i can't make it work.  e.g
> def do_connect(self, ip, command):
> 
>>>> connect 127.0.0.1 delete
>  Are there any work arounds
> 
> Thanks in advance
> 
> Antonis

You have to split the user input into arguments yourself. You can do this in 
the body of the do_xxx() methods, use a decorator, or subclass cmd.Cmd.

Here's a solution using a decorator:

import cmd
import inspect
import shlex

def split(f):
    def g(self, line):
        argvalues = shlex.split(line)
        argnames = inspect.getargspec(f).args
        argcount = len(argnames) - 1
        if len(argvalues) != argcount:
            print "Need exactly %d args" % argcount
            return
        return f(self, *argvalues)
    return g

class Cmd(cmd.Cmd):
    @split
    def do_connect(self, ip, command):
        print "ip=%r, command=%r" % (ip, command)


if __name__ == "__main__":
    c = Cmd()
    c.cmdloop()

And here's a subclass that avoids the need for explicit @split decorations:

import cmd
import inspect
import shlex

def split(f):
    def g(line):
        argvalues = shlex.split(line)
        argnames = inspect.getargspec(f).args
        argcount = len(argnames) -1
        if len(argvalues) != argcount:
            print "Need exactly %d args" % argcount
            return
        return f(*argvalues)
    return g

class CmdBase(cmd.Cmd, object):
    def __getattribute__(self, name):
        attr = object.__getattribute__(self, name)
        if name.startswith("do_"):
            attr = split(attr)
        return attr

class Cmd(CmdBase):
    def do_connect(self, ip, command):
        print "ip=%r, command=%r" % (ip, command)


if __name__ == "__main__":
    c = Cmd()
    c.cmdloop()

Now you've got an idea of the general direction you can certainly come up 
with something less hackish ;)

Peter


From mouadino at gmail.com  Mon May 17 09:35:11 2010
From: mouadino at gmail.com (mouadino)
Date: Mon, 17 May 2010 06:35:11 -0700 (PDT)
Subject: abc don't play well with private method
References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com>
	<4be18d3d$0$19014$426a34cc@news.free.fr>
Message-ID: 

Hello
and thanx for your answer it's was very helpful

but just to clear some thinks :

> There's no such thing as a "private" attribute in Python. The
> name-mangling mechanism invoked by "__name" is really meant to avoid
> accidental redefinition of the attribute in a derived class.

> In this case, your attribute is expected to be redefined, so you
> definitly don't want any name mangling here.

yes , but what i have supposed is that the name mangling will not be
applied when you use abc especially when you decorate the function
with abc.abstractmethod , because it's will(should) be redefined (so
something is wrong with the abc module) .

> Also and FWIW, the naming convention for "implementation attributes" is
> a single leading underscore

sorry but i don't agree on this. the two underscore (__) are used in
classes level for defining private method in the python way, and the
one underscore (_) is used in the module level :

"""Prepending a single underscore (_) has some support for protecting
module variables and functions (not included with import * from).
Prepending a double underscore (__) to an instance variable or method
effectively serves to make the variable or method private to its class
(using name mangling). """
src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

> > ? ? def close(self):
>
> > ? ? ? ? self.close()
>
> > ? ? def quit(self):
>
> > ? ? ? ? self.quit()
>
> Don't you see kind of a problem here ? Something like, say, an infinite
> recursion ?

yep , thanx




From mouadino at gmail.com  Mon May 17 09:35:42 2010
From: mouadino at gmail.com (mouadino)
Date: Mon, 17 May 2010 06:35:42 -0700 (PDT)
Subject: abc don't play well with private method
References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com>
	<4be18d3d$0$19014$426a34cc@news.free.fr>
Message-ID: <65ef6ef8-efe5-4d00-9700-e23c9cffae3f@o1g2000vbe.googlegroups.com>

Hello
and thanx for your answer it's was very helpful

but just to clear some thinks :

> There's no such thing as a "private" attribute in Python. The
> name-mangling mechanism invoked by "__name" is really meant to avoid
> accidental redefinition of the attribute in a derived class.

> In this case, your attribute is expected to be redefined, so you
> definitly don't want any name mangling here.

yes , but what i have supposed is that the name mangling will not be
applied when you use abc especially when you decorate the function
with abc.abstractmethod , because it's will(should) be redefined (so
something is wrong with the abc module) .

> Also and FWIW, the naming convention for "implementation attributes" is
> a single leading underscore

sorry but i don't agree on this. the two underscore (__) are used in
classes level for defining private method in the python way, and the
one underscore (_) is used in the module level :

"""Prepending a single underscore (_) has some support for protecting
module variables and functions (not included with import * from).
Prepending a double underscore (__) to an instance variable or method
effectively serves to make the variable or method private to its class
(using name mangling). """
src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

> > ? ? def close(self):
>
> > ? ? ? ? self.close()
>
> > ? ? def quit(self):
>
> > ? ? ? ? self.quit()
>
> Don't you see kind of a problem here ? Something like, say, an infinite
> recursion ?

yep , thanx




From kaklis at gmail.com  Mon May 17 09:36:44 2010
From: kaklis at gmail.com (kaklis at gmail.com)
Date: Mon, 17 May 2010 06:36:44 -0700 (PDT)
Subject: cmd with three arguments
References: 
	
Message-ID: 

On May 17, 4:34?pm, Peter Otten <__pete... at web.de> wrote:
> kak... at gmail.com wrote:
> > Hi pythonistas,
> > While playing with the Python Standard Library, i came across "cmd".
> > So I'm trying to make a console application. Everything works fine, i
> > created many function with do_....(self, line) prefix, but when i
> > tried to create a function with more arguments
> > ?i can't make it work. ?e.g
> > def do_connect(self, ip, command):
>
> >>>> connect 127.0.0.1 delete
> > ?Are there any work arounds
>
> > Thanks in advance
>
> > Antonis
>
> You have to split the user input into arguments yourself. You can do this in
> the body of the do_xxx() methods, use a decorator, or subclass cmd.Cmd.
>
> Here's a solution using a decorator:
>
> import cmd
> import inspect
> import shlex
>
> def split(f):
> ? ? def g(self, line):
> ? ? ? ? argvalues = shlex.split(line)
> ? ? ? ? argnames = inspect.getargspec(f).args
> ? ? ? ? argcount = len(argnames) - 1
> ? ? ? ? if len(argvalues) != argcount:
> ? ? ? ? ? ? print "Need exactly %d args" % argcount
> ? ? ? ? ? ? return
> ? ? ? ? return f(self, *argvalues)
> ? ? return g
>
> class Cmd(cmd.Cmd):
> ? ? @split
> ? ? def do_connect(self, ip, command):
> ? ? ? ? print "ip=%r, command=%r" % (ip, command)
>
> if __name__ == "__main__":
> ? ? c = Cmd()
> ? ? c.cmdloop()
>
> And here's a subclass that avoids the need for explicit @split decorations:
>
> import cmd
> import inspect
> import shlex
>
> def split(f):
> ? ? def g(line):
> ? ? ? ? argvalues = shlex.split(line)
> ? ? ? ? argnames = inspect.getargspec(f).args
> ? ? ? ? argcount = len(argnames) -1
> ? ? ? ? if len(argvalues) != argcount:
> ? ? ? ? ? ? print "Need exactly %d args" % argcount
> ? ? ? ? ? ? return
> ? ? ? ? return f(*argvalues)
> ? ? return g
>
> class CmdBase(cmd.Cmd, object):
> ? ? def __getattribute__(self, name):
> ? ? ? ? attr = object.__getattribute__(self, name)
> ? ? ? ? if name.startswith("do_"):
> ? ? ? ? ? ? attr = split(attr)
> ? ? ? ? return attr
>
> class Cmd(CmdBase):
> ? ? def do_connect(self, ip, command):
> ? ? ? ? print "ip=%r, command=%r" % (ip, command)
>
> if __name__ == "__main__":
> ? ? c = Cmd()
> ? ? c.cmdloop()
>
> Now you've got an idea of the general direction you can certainly come up
> with something less hackish ;)
>
> Peter

Thanks great advice!
Antonis


From mouadino at gmail.com  Mon May 17 09:36:44 2010
From: mouadino at gmail.com (mouadino)
Date: Mon, 17 May 2010 06:36:44 -0700 (PDT)
Subject: abc don't play well with private method
References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com>
	<4be18d3d$0$19014$426a34cc@news.free.fr>
Message-ID: <148e3e6a-b4a9-4041-8951-9f965927a3c0@b21g2000vbh.googlegroups.com>

Hello
and thanx for your answer it's was very helpful

but just to clear some thinks :

> There's no such thing as a "private" attribute in Python. The
> name-mangling mechanism invoked by "__name" is really meant to avoid
> accidental redefinition of the attribute in a derived class.

> In this case, your attribute is expected to be redefined, so you
> definitly don't want any name mangling here.

yes , but what i have supposed is that the name mangling will not be
applied when you use abc especially when you decorate the function
with abc.abstractmethod , because it's will(should) be redefined (so
something is wrong with the abc module) .

> Also and FWIW, the naming convention for "implementation attributes" is
> a single leading underscore

sorry but i don't agree on this. the two underscore (__) are used in
classes level for defining private method in the python way, and the
one underscore (_) is used in the module level :

"""Prepending a single underscore (_) has some support for protecting
module variables and functions (not included with import * from).
Prepending a double underscore (__) to an instance variable or method
effectively serves to make the variable or method private to its class
(using name mangling). """
src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

> > ? ? def close(self):
>
> > ? ? ? ? self.close()
>
> > ? ? def quit(self):
>
> > ? ? ? ? self.quit()
>
> Don't you see kind of a problem here ? Something like, say, an infinite
> recursion ?

yep , thanx




From jayeola at gmail.com  Mon May 17 09:37:55 2010
From: jayeola at gmail.com (John Maclean)
Date: Mon, 17 May 2010 14:37:55 +0100
Subject: pythonic ssh
Message-ID: <4BF146B3.2070207@gmail.com>

hi,

pyssh, pexpect, paramiko or creating your your own sockets. what do you 
use to pythonically ssh to boxes?


-- 
John Maclean
MSc. (DIC) BSc. (Hons)
Linux Systems and Applications
07739 171 531


From awilliam at whitemice.org  Mon May 17 09:45:44 2010
From: awilliam at whitemice.org (Adam Tauno Williams)
Date: Mon, 17 May 2010 09:45:44 -0400
Subject: python application question
In-Reply-To: <8df6cb20-f822-4286-a075-2633c6025e84@z17g2000vbd.googlegroups.com>
References: <8df6cb20-f822-4286-a075-2633c6025e84@z17g2000vbd.googlegroups.com>
Message-ID: <1274103944.9420.2.camel@linux-yu4c.site>

On Mon, 2010-05-17 at 06:20 -0700, a wrote:
> if i want to plot it i have to use something like matplotlib?  but
> this doesn't come with the standard installation.  so if i want
> someone else to use this application, do they have to install
> matplotlib themselves or is there a better way?

Use PyPI to distribute your application and declare matplotlib as a
requirement in your setup.py.  Then when they easy_install it should
take care of it.



From pacman128 at gmail.com  Mon May 17 09:52:26 2010
From: pacman128 at gmail.com (Paul Carter)
Date: Mon, 17 May 2010 06:52:26 -0700 (PDT)
Subject: imports and exec
References: <20297a4b-6fc8-4fa0-a203-decdd2586805@l18g2000vbn.googlegroups.com>
	
Message-ID: 

On May 16, 4:22?pm, Patrick Maupin  wrote:
> On May 16, 1:51?pm, Paul Carter  wrote:
>
>
>
> > We are using python for our build system. Each subproject dir has a
> > python script that builds it. Parent dirs have python scripts that
> > recurse into their children and use exec to invoke the python scripts.
> > Recently we discovered that one of the python scripts works when
> > invoked directly, but fails when invoked with exec. I've created a
> > very simple pair of python scripts that demonstrates the problem.
> > (We're using python 2.6)
>
> > Can someone explain or point to a good explanation of why this problem
> > occurs?
>
> > I have two python files: prim.py and sec.py.
> > prim.py:
> > -----------------------------------------
> > #!/usr/bin/env python
>
> > ##sec2 = open('sec.py')
> > ##exec sec2
>
> > def invoke():
> > ? sec = open('sec.py')
> > ? exec sec
>
> > invoke()
> > ------------------------------
>
> > and sec.py:
> > ----------------------------------
> > import sys
>
> > def sec():
> > ? print('Inside sec(): ' + ?str(sys.argv))
>
> > print('Outside sec(): ' + str(sys.argv))
> > sec()
> > --------------------------------------
>
> > When I run prim.py, I get an error:
> > --------------------------------
> > Outside sec(): ['./prim.py']
> > Traceback (most recent call last):
> > ? File "./prim.py", line 10, in 
> > ? ? invoke()
> > ? File "./prim.py", line 8, in invoke
> > ? ? exec sec
> > ? File "sec.py", line 7, in 
> > ? ? sec()
> > ? File "sec.py", line 4, in sec
> > ? ? print('Inside sec(): ' + ?str(sys.argv))
> > NameError: global name 'sys' is not defined
> > ----------------------------------
>
> > I don't understand why the sys import is not visible in the sec()
> > function. I can fix this by adding a:
> > ? global sys
> > or
> > ? import sys
> > inside the sec() function. But I would like to understand why this is
> > necessary, especially since sys is visible in sec.py outside of the
> > sec() function. I found this page discussing exec
>
> >http://docs.python.org/reference/executionmodel.html
>
> > but I'm afraid I couldn't quite follow it. It makes me think that a
> > free variable is involved, but I don't see how. It did made me try
> > invoking exec in prim.py outside of the invoke() function (see the
> > commented out code). Everything worked fine when I did that.
>
> > Can someone set me straight? Suggestions on avoiding this problem are
> > welcome as well!
>
> > Thanks in advance.
>
> Yes. ?Since you did not pass any dictionaries to your exec of "sec",
> sec inherited the globals and locals from the calling function. ?So
> the import of sys happened in that functions locals (bad practice in
> any case) and the globals used by sec() are the globals of your main
> module.
>
> Especially if invoked from inside a function, you should always pass a
> dict to exec. ?Just "exec sec() in {}" will do the trick. ?But if you
> want to use your caller's dictionaries, you can do "exec sec() in
> globals()" ?But you should *not* use a functions locals directly if
> you are going to modify them (as you are currently doing).
>
> Regards,
> Pat

Thanks, that helped a lot! I was misunderstanding what exec does by
default.

--
Paul


From pmaupin at gmail.com  Mon May 17 09:58:13 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Mon, 17 May 2010 06:58:13 -0700 (PDT)
Subject: python application question
References: <8df6cb20-f822-4286-a075-2633c6025e84@z17g2000vbd.googlegroups.com>
Message-ID: <8ee69746-422b-4c25-b8b4-247218c196c5@o12g2000vba.googlegroups.com>

On May 17, 8:20?am, a  wrote:

> ps someone helped me with enumerate(), which works on the linux but
> not on the windows?

enumerate() works fine on windows.  Perhaps your windows box has a
really old Python?

Regards,
Pat


From schettino72 at gmail.com  Mon May 17 10:11:31 2010
From: schettino72 at gmail.com (Eduardo Schettino)
Date: Mon, 17 May 2010 22:11:31 +0800
Subject: [ANN] doit - automation tool 0.8 released
Message-ID: 

pypi: http://pypi.python.org/pypi/doit
homepage: http://python-doit.sourceforge.net/


`doit` comes from the idea of bringing the power of build-tools to
execute any kind of task. It will keep track of dependencies between
"tasks" and execute them only when necessary. It was designed to be
easy to use and "get out of your way".

Features:

 * Easy to use, "no-API"
 * Use python to dynamically create tasks on-the-fly
 * Flexible, adapts to many workflows for creation of tasks/rules/recipes
 * Support for multi-process parallel execution
 * Built-in integration of inotify (automatically re-execution)

`doit` can be used as:

 * a build tool (generic and flexible)
 * home of your management scripts (it helps you organize and combine
shell scripts and python scripts)
 * a functional tests runner (combine together different tools)


From mannu_0523 at rediffmail.com  Mon May 17 10:24:28 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 17 May 2010 14:24:28 -0000
Subject: =?utf-8?B?Rnc6IFJlOiBSZTogam9pbmluZyBmaWxlcw==?=
Message-ID: <1274106232.S.7666.37655.f4mail-234-211.rediffmail.com.1274106266.38667@webmail.rediffmail.com>

Note: Forwarded message attached

-- Original Message --

From: "mannu jha"mannu_0523 at rediffmail.com
To: tuomas.vesterinen at iki.fi
Subject: Re: Re: joining files
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
An embedded message was scrubbed...
From: "mannu jha"
Subject: Re: Re: joining files
Date: no date
Size: 7506
URL: 

From cjw at ncf.ca  Mon May 17 10:57:40 2010
From: cjw at ncf.ca (cjw)
Date: Mon, 17 May 2010 10:57:40 -0400
Subject: Access to comp.lang.python
In-Reply-To: 
References: 					
	
Message-ID: 

On 16-May-10 12:47 PM, Jim Byrnes wrote:
> Grant Edwards wrote:
>> On 2010-05-16, cjw wrote:
>>> On 16-May-10 01:31 AM, James Mills wrote:
>>>> On Sun, May 16, 2010 at 3:12 PM, Aahz wrote:
>>>>> It's also at least partly due to problems with mail<->news gateways
>>>>> and
>>>>> the differing fields used to maintain threading.
>>>>
>>>> Some blame goes on MUAs too :)
>>>
>>> Thanks for the responses.
>>>
>>> Is it possible to connect a newsreader to gmane?
>>
>> nntp://news.gmane.org/
>>
>
> Could someone please explain how to subscribe to this list on gmane. I
> subscribe to a couple of other groups there but can't find this one.
>
> Regards, Jim

With Thunderbird, you need to set up a new account:

Tools => AccountSettings => Account Actions => Add another account.

=> News Group Account => Next

 From there, it's a matter of filling in the blanks.

The news server is "news.gmane.org".

I'm just trying it.

Colin W,


From mcrute at gmail.com  Mon May 17 10:59:43 2010
From: mcrute at gmail.com (Michael Crute)
Date: Mon, 17 May 2010 10:59:43 -0400
Subject: pythonic ssh
In-Reply-To: <4BF146B3.2070207@gmail.com>
References: <4BF146B3.2070207@gmail.com>
Message-ID: 

On Mon, May 17, 2010 at 9:37 AM, John Maclean  wrote:
> pyssh, pexpect, paramiko or creating your your own sockets. what do you use
> to pythonically ssh to boxes?

I think the answer to this depends on your goals. Paramiko is the best
way to go if you want a pythonic API to ssh but you also will
introduce a dependency on paramiko and a transitive dependency on
pycrypto (which requires openssl). I personally prefer to just use
subprocess with the ssh binary for most of my scripts because it
doesn't introduce any extra dependencies and is relatively easy to
implement. pyssh tries to wrap up the common ssh patterns using
os.popen but it hasn't been maintained in several years so your best
bet is probably to stick with using subprocess if you don't go with
paramiko.

-- 
Michael E. Crute
http://mike.crute.org

It is a mistake to think you can solve any major problem just with
potatoes. --Douglas Adams


From jonvspython at gmail.com  Mon May 17 11:05:12 2010
From: jonvspython at gmail.com (jon vs. python)
Date: Mon, 17 May 2010 17:05:12 +0200
Subject: Pyserial and pysqlite data types, need advice
Message-ID: 

Hi,
I'm trying to store frames received via serial port (using Pyserial) into a
sqlite database (using Pysqlite) in order to perform off-line processing.
Thus I could use both SQL's power and Python's magic to make everything
easier. I'd like my code to be generic and work both for binary and ascii
protocols, too.

Which kind of data should I use to store the frames?
Should I store every byte as a char in VARCHAR? (This seems to fail when
trying to store non printable characters).
Should I encapsulate frames in buffer objects and store them in BLOBs? (This
seems to work but hides content and thus doesn't allow to use database
operations directly on the data)
I've also tried, unsuccessfully, to use bytearrays with pysqlite...

Any suggestion?

Thanks, Jon.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From keobox at gmail.com  Mon May 17 11:09:59 2010
From: keobox at gmail.com (keobox)
Date: Mon, 17 May 2010 08:09:59 -0700 (PDT)
Subject: [jython] Problem with an huge dictionary
Message-ID: 

Hi,
I apologize if this is not the right group for posting question
related to jython.
Please give me the right directions if this is the case.

The question is:
Is there a limit on the number of entries a dictionary can have i
jython?

I wrote a little app where my data is stored in a huge dictionary
(11746 entries) generated with a python script.
When I try to import the dictionary, jython complains with the
following message:

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\ceplacan\My Documents\Documents\Source\source
\Python\j
moco-test>jython
Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.5.0_13
Type "help", "copyright", "credits" or "license" for more information.
>>> import jmoco_event_data
Traceback (most recent call last):
  File "", line 1, in 
java.lang.ClassFormatError: Invalid this class index 3241 in constant
pool in cl
ass file _1076
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
        at org.python.core.BytecodeLoader
$Loader.loadClassFromBytes(BytecodeLoad
er.java:119)
        at
org.python.core.BytecodeLoader.makeClass(BytecodeLoader.java:37)
        at org.python.core.BytecodeLoader.makeCode(BytecodeLoader.java:
67)
        at org.python.core.imp.createFromSource(imp.java:288)
        at org.python.core.imp.loadFromSource(imp.java:514)
        at org.python.core.imp.find_module(imp.java:411)
        at org.python.core.imp.import_next(imp.java:635)
        at org.python.core.imp.import_name(imp.java:746)
        at org.python.core.imp.importName(imp.java:806)
        at org.python.core.ImportFunction.__call__(__builtin__.java:
1232)
        at org.python.core.PyObject.__call__(PyObject.java:367)
        at org.python.core.__builtin__.__import__(__builtin__.java:
1202)
        at org.python.core.__builtin__.__import__(__builtin__.java:
1185)
        at org.python.core.imp.importOne(imp.java:817)
        at org.python.pycode._pyx1.f$0(:1)
        at org.python.pycode._pyx1.call_function()
        at org.python.core.PyTableCode.call(PyTableCode.java:165)
        at org.python.core.PyCode.call(PyCode.java:18)
        at org.python.core.Py.runCode(Py.java:1204)
        at org.python.core.Py.exec(Py.java:1248)
        at
org.python.util.PythonInterpreter.exec(PythonInterpreter.java:181)
        at
org.python.util.InteractiveInterpreter.runcode(InteractiveInterpreter
.java:89)
        at
org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
er.java:70)
        at
org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
er.java:46)
        at
org.python.util.InteractiveConsole.push(InteractiveConsole.java:110)
        at
org.python.util.InteractiveConsole.interact(InteractiveConsole.java:9
0)
        at org.python.util.jython.run(jython.java:316)
        at org.python.util.jython.main(jython.java:129)

java.lang.ClassFormatError: java.lang.ClassFormatError: Invalid this
class index
 3241 in constant pool in class file _1076

What can I do to avoid this?

Regards,
Cesare


From pierre.ruyssen at gmail.com  Mon May 17 11:38:05 2010
From: pierre.ruyssen at gmail.com (Pierre)
Date: Mon, 17 May 2010 08:38:05 -0700 (PDT)
Subject: [BarCamp] WebWorkersCamp BarCamp: NodeJS, NoSQL, Message Queues, 
	Asynchronous programming, Web Sockets, Distributed Applications, 
	Decentralized Social Networks, buzzword generators...
Message-ID: <3797a708-ffd0-4330-acbd-7281699b2af4@o1g2000vbe.googlegroups.com>

Hello,

AF83 will be holding a barcamp event on Saturday afternoon, July 3rd
in Paris (in La Cantine, a famous Parisian tech place). We wanted to
let you know about this event and tell you that you would be most
welcome if you could join us on that day.

In the ever-growing context of real-time web and multiplying
webservices, websites as they are now designed are hardly scalable, or
at high costs. So we thought appropriate to hold an event to discuss
the technologies which will allow us to code differently in order to
solve these issues.

Our guests will be invited to share their experience in asynchronous
programming (server-side javascript with NodeJS, Python?s Tornado,
Ruby?s Event Machine, etc.) as well as Websockets, NoSQL databases,
queues, XMPP and others.

We?d be thrilled to have you amongst us and hear your story on this
matter! We thought this could be the opportunity for you to tell us
about your work and learn from other developers. Would you be
interested in coming and, if you wish, leading a workshop?
Then register on http://barcamp.org/WebWorkersCamp .

We?re looking forward to hearing from you soon,

Thank you,
The AF83 team.


From python at rcn.com  Mon May 17 11:43:23 2010
From: python at rcn.com (Raymond Hettinger)
Date: Mon, 17 May 2010 08:43:23 -0700 (PDT)
Subject: an element from a set
References: 
Message-ID: <3a3dd59c-4280-46b1-98af-7e9fe8a4bd2f@q33g2000vbt.googlegroups.com>

On May 14, 3:24?pm, gerardob  wrote:
> Hello, let S be a python set which is not empty
> (http://docs.python.org/library/sets.html)
>
> i would like to obtain one element (anyone, it doesn't matter which one) and
> assign it to a variable.
>
> How can i do this?

x = next(iter(s))

or you can supply a default value in case the set is empty:

x = next(iter(s), default_value)


Raymond


From alley at dragoncreativeworks.net  Mon May 17 11:51:36 2010
From: alley at dragoncreativeworks.net (Allan Davis)
Date: Mon, 17 May 2010 10:51:36 -0500
Subject: [jython] Problem with an huge dictionary
In-Reply-To: 
References: 
Message-ID: 

KeoBox,

Can i look at the jython file you are executing? the ClassFormatException is
not with the size of the dictionary.  Jython is failing on an import.

thanks,
--------------------------------------------------------------
Allan Davis
Member of NetBeans Dream Team
http://wiki.netbeans.org/NetBeansDreamTeam
Lead Developer, nbPython
http://wiki.netbeans.org/Python
http://codesnakes.blogspot.com (my blog)
Co-Chair, CajunJUG
http://www.cajunjug.org


On Mon, May 17, 2010 at 10:09 AM, keobox  wrote:

> Hi,
> I apologize if this is not the right group for posting question
> related to jython.
> Please give me the right directions if this is the case.
>
> The question is:
> Is there a limit on the number of entries a dictionary can have i
> jython?
>
> I wrote a little app where my data is stored in a huge dictionary
> (11746 entries) generated with a python script.
> When I try to import the dictionary, jython complains with the
> following message:
>
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
>
> C:\Documents and Settings\ceplacan\My Documents\Documents\Source\source
> \Python\j
> moco-test>jython
> Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
> [Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.5.0_13
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import jmoco_event_data
> Traceback (most recent call last):
>  File "", line 1, in 
> java.lang.ClassFormatError: Invalid this class index 3241 in constant
> pool in cl
> ass file _1076
>        at java.lang.ClassLoader.defineClass1(Native Method)
>        at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
>        at org.python.core.BytecodeLoader
> $Loader.loadClassFromBytes(BytecodeLoad
> er.java:119)
>        at
> org.python.core.BytecodeLoader.makeClass(BytecodeLoader.java:37)
>        at org.python.core.BytecodeLoader.makeCode(BytecodeLoader.java:
> 67)
>        at org.python.core.imp.createFromSource(imp.java:288)
>        at org.python.core.imp.loadFromSource(imp.java:514)
>        at org.python.core.imp.find_module(imp.java:411)
>        at org.python.core.imp.import_next(imp.java:635)
>        at org.python.core.imp.import_name(imp.java:746)
>        at org.python.core.imp.importName(imp.java:806)
>        at org.python.core.ImportFunction.__call__(__builtin__.java:
> 1232)
>        at org.python.core.PyObject.__call__(PyObject.java:367)
>        at org.python.core.__builtin__.__import__(__builtin__.java:
> 1202)
>        at org.python.core.__builtin__.__import__(__builtin__.java:
> 1185)
>        at org.python.core.imp.importOne(imp.java:817)
>        at org.python.pycode._pyx1.f$0(:1)
>        at org.python.pycode._pyx1.call_function()
>        at org.python.core.PyTableCode.call(PyTableCode.java:165)
>        at org.python.core.PyCode.call(PyCode.java:18)
>        at org.python.core.Py.runCode(Py.java:1204)
>        at org.python.core.Py.exec(Py.java:1248)
>        at
> org.python.util.PythonInterpreter.exec(PythonInterpreter.java:181)
>        at
> org.python.util.InteractiveInterpreter.runcode(InteractiveInterpreter
> .java:89)
>        at
> org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
> er.java:70)
>        at
> org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
> er.java:46)
>        at
> org.python.util.InteractiveConsole.push(InteractiveConsole.java:110)
>        at
> org.python.util.InteractiveConsole.interact(InteractiveConsole.java:9
> 0)
>        at org.python.util.jython.run(jython.java:316)
>        at org.python.util.jython.main(jython.java:129)
>
> java.lang.ClassFormatError: java.lang.ClassFormatError: Invalid this
> class index
>  3241 in constant pool in class file _1076
>
> What can I do to avoid this?
>
> Regards,
> Cesare
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From cde3 at live.com  Mon May 17 11:54:37 2010
From: cde3 at live.com (Sandy Ydnas)
Date: Mon, 17 May 2010 20:54:37 +0500
Subject: python and GNU plot
Message-ID: 


 

pls pls help how to use Gnuplot 

 

Gnuplot runs from Python under Vista

 

downloaded  Gnuplot, but what they suggest only Run wgnuplot.exe

 

Thank you very much in advance!!!!!!!!!!!

 

Sandy
 		 	   		  
_________________________________________________________________
Hotmail: Trusted email with Microsoft?s powerful SPAM protection.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From sam.bancal at gmail.com  Mon May 17 11:54:38 2010
From: sam.bancal at gmail.com (Samuel Bancal)
Date: Mon, 17 May 2010 17:54:38 +0200
Subject: subprocess and gvfs-mount
Message-ID: 

Hi,

I'm coding a script that does some automates for my users ... including
mounting a smb share.

Because we are using Gnome, I choosed to use gvfs-mount, which is quite
similar to "Places > Connect to Server > ..."

Now my script does :
        print "*** Mounting the FILER ..."
        cmd = "/usr/bin/gvfs-mount smb://%s\;%s at myfiler.domain.ch/data/%s" %
(my_domain, my_user_name, my_user_name)
        try:
            retCode = subprocess.call(cmd, shell=True)
        except KeyboardInterrupt, e:
            sys.stderr.write("Interrupted by ctrl-c. Exiting\n")
            sys.exit(1)
        if retCode != 0:
            sys.stderr.write("Error while mounting : %s\n" % retCode)

I have two major problems with this code :
- In case of "ctr-c" while the password is asked to the user, I get a
Terminal in which the output from keyboard is inhibited... (like while
typing password)
- When the user runs this script by "double-click > Run" (not "Run in
terminal") ... there is no interaction with the user.

I also did some try with subprocess.Popen ... with no success yet...

Thanks for any comment or suggestion!

Regards,
Samuel Bancal

ps : Or anyone knows how to get that gvfs-mount in GUI mode... Could see
nautilus-connect-server ... but couldn't find any options.

-- 
Samuel Bancal - CH
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nima.irt at gmail.com  Mon May 17 12:12:32 2010
From: nima.irt at gmail.com (Nima)
Date: Mon, 17 May 2010 09:12:32 -0700 (PDT)
Subject: Installing Lightweight Python
Message-ID: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>

I'd like to install python on an embedded system. It's a powerful x86-
based computer with the only limitation of having a small-size flash
ROM as its secondary storage. So there is no hard drive and the system
is booted from the flash memory.
The operating system, BusyBox (a flavor of Linux), and other
applications occupy most of the flash memory. As the subject implies,
Python isn't already installed on the box. I tried to compile/install
python on a Linux box which roughly took 60MB of the memory. The
maximum amount of Flash memory I'm permitted to use is about 10-20 MB.
Is there a light-weight implementation of python which I could use? Is
there a way to remove unnecessary modules?
BTW,
+ I'm supposed to write a web management interface for this system
(using python).
+ I know how to use Google!
+ I'm a newbie, so please be gentle :)


From tjreedy at udel.edu  Mon May 17 12:24:04 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Mon, 17 May 2010 12:24:04 -0400
Subject: an element from a set
In-Reply-To: <248cbfa6-5992-4bc3-bef6-a240a901a07b@42g2000prb.googlegroups.com>
References: <28560792.post@talk.nabble.com>	
	<213b4a61-1bbe-4d48-802e-291975b8d196@g39g2000pri.googlegroups.com>
	
	<248cbfa6-5992-4bc3-bef6-a240a901a07b@42g2000prb.googlegroups.com>
Message-ID: 

On 5/17/2010 12:53 AM, Carl Banks wrote:

> Even if we were to modify the set type at the C level to support it, I
> can't think of an easy way to get a random element without selection
> bias.

At the C level, a (hashed) set is a list with empty slots. So the C 
function would have to pick random ints in the appropriate range until 
it got an index for a non-empty slot. A sequence of selections from 
equal sets would not, in general, be reproducible, since the internal 
array need not be the same.



From yourpadre at gmail.com  Mon May 17 12:27:53 2010
From: yourpadre at gmail.com (Miguel Beltran R.)
Date: Mon, 17 May 2010 11:27:53 -0500
Subject: OT Pagina sobre programacion en paralelo
Message-ID: 

Hola Lista,

Disculpen el off-topic, pero creo que aqui fue donde una vez postearon un
enlace sobre programaci?n en paralelo y explica porque no es el doble de
rapido que con 1 micro.

Tambien hablaba de que si el algoritmo es log(n) o log(n2) o algo asi

ya lo busque en el historial pero no lo encuentro, alguien tiene el enlace?
o no lo vi aqui?

-- 
________________________________________
Lo bueno de vivir un dia mas
es saber que nos queda un dia menos de vida
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From tjreedy at udel.edu  Mon May 17 12:56:12 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Mon, 17 May 2010 12:56:12 -0400
Subject: A couple questions about classes and inheritance
In-Reply-To: 
References: 	
	
Message-ID: 

On 5/16/2010 10:52 PM, Mark Young wrote:
> You can't subclass Ellipsis.

You clipped what I believe you were responding to that I posted:
"I believe that in 3.1, the builtin classes with builtin names can be 
subclassed and and those without cannot. (If you find any exceptionss, 
please post ;-). The ones with names are exactly the ones you are 
expected to directly interact with in normal code."

Ellipsis is not an exception to what I said but rather an example that 
supports my point. It is not a class, but an instance of an 
intentionally *unnamed* class which one cannot subclass. It is unnamed 
in the sense of not being bound to a name in a namespace (builtins), 
even though, like all classes, it has a 'definition' or name-attribute name.

 >>> Ellipsis
Ellipsis
 >>> type(Ellipsis)

 >>> class C(type(Ellipsis)): pass

Traceback (most recent call last):
   File "", line 1, in 
     class C(type(Ellipsis)): pass
TypeError: type 'ellipsis' is not an acceptable base type

The class of None is also unnamed, while the class of True and False, 
bool, is named so we can call it. It does turn out that bool *is* an 
exception to the general rule.

 >>> class C(bool): pass

Traceback (most recent call last):
   File "", line 1, in 
     class C(bool): pass
TypeError: type 'bool' is not an acceptable base type

If there were a practical reason to subclass it, a subclass of int 
instead should do just as well.

Terry Jan Reedy



From debatem1 at gmail.com  Mon May 17 13:00:30 2010
From: debatem1 at gmail.com (geremy condra)
Date: Mon, 17 May 2010 10:00:30 -0700
Subject: Installing Lightweight Python
In-Reply-To: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
Message-ID: 

On Mon, May 17, 2010 at 9:12 AM, Nima  wrote:
> I'd like to install python on an embedded system. It's a powerful x86-
> based computer with the only limitation of having a small-size flash
> ROM as its secondary storage. So there is no hard drive and the system
> is booted from the flash memory.
> The operating system, BusyBox (a flavor of Linux), and other
> applications occupy most of the flash memory. As the subject implies,
> Python isn't already installed on the box. I tried to compile/install
> python on a Linux box which roughly took 60MB of the memory. The
> maximum amount of Flash memory I'm permitted to use is about 10-20 MB.
> Is there a light-weight implementation of python which I could use? Is
> there a way to remove unnecessary modules?
> BTW,
> + I'm supposed to write a web management interface for this system
> (using python).
> + I know how to use Google!
> + I'm a newbie, so please be gentle :)
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I'm not an expert, but there are probably a large-ish number of modules
you could remove without much sacrifice on your part. Looking at the
module list and just picking the platform-dependent ones:

* _winreg
* aepack
* aetools
* aetypes
* AL
* al
* applesingle
* autoGIL
* buildtools
* Carbon
* cd
* cfmfile
* chunk
* colorpicker
* etc
* etc
* etc

You could also probably remove things like 2to3, tabnanny, etc,
and I doubt tkinter is doing you much good.

I also recall someone at pycon talking about importing modules
from a .zip archive. I'm not sure how easy/hard that is, but you
may want to look at PEP 302.

Geremy Condra


From tjreedy at udel.edu  Mon May 17 13:00:57 2010
From: tjreedy at udel.edu (Terry Reedy)
Date: Mon, 17 May 2010 13:00:57 -0400
Subject: OT Pagina sobre programacion en paralelo
In-Reply-To: 
References: 
Message-ID: 

On 5/17/2010 12:27 PM, Miguel Beltran R. wrote:

> Disculpen el off-topic, pero creo que aqui fue donde una vez postearon
> un enlace sobre programaci?n en paralelo y explica porque no es el doble
> de rapido que con 1 micro.

No me recuerdo algo como esto. Lo dudo mucho.





From python at bdurham.com  Mon May 17 13:54:27 2010
From: python at bdurham.com (python at bdurham.com)
Date: Mon, 17 May 2010 13:54:27 -0400
Subject: Converting datetime.ctime() values to Unicode
Message-ID: <1274118867.15576.1375504195@webmail.messagingengine.com>

I would like to convert datetime.ctime() values to Unicode.

Using Python 2.6.4 running under Windows I can set my locale to
Spanish like below:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'esp' )

Then I can pass %a, %A, %b, and %B to ctime() to get day and
month names and abbreviations.

>>> import datetime
>>> dateValue = datetime.date( 2010, 5, 15 )
>>> dayName = dateValue.strftime( '%A' )
>>> dayName
's\xe1bado'

How do I convert the 's\xe1bado' value to Unicode? Specifically what
encoding do I use?

I'm thinking I might do something like the following, but I'm not sure
this is the right approach.

>>> codePage = locale.getdefaultlocale()[ 1 ]
>>> dayNameUnicode = unicode( dayName, codePage )
>>> dayNameUnicode
u's\xe1bado'

Feedback appreciated.

Regards,
Malcolm



From eike.welk at gmx.net  Mon May 17 14:09:37 2010
From: eike.welk at gmx.net (Eike Welk)
Date: Mon, 17 May 2010 20:09:37 +0200
Subject: Engineering numerical format PEP discussion
References: 
Message-ID: 

Keith wrote:

> I am considering writing a PEP for the inclusion of an engineering
> format specifier, and would appreciate input from others.

I think it's a good idea. I regularly type numbers into my pocket calculator 
just to do this conversion. 


Eike.


From python at bdurham.com  Mon May 17 14:14:27 2010
From: python at bdurham.com (python at bdurham.com)
Date: Mon, 17 May 2010 14:14:27 -0400
Subject: Converting datetime.ctime() values to Unicode
In-Reply-To: <1274118867.15576.1375504195@webmail.messagingengine.com>
References: <1274118867.15576.1375504195@webmail.messagingengine.com>
Message-ID: <1274120067.18728.1375508915@webmail.messagingengine.com>

In researching a solution, I believe locale.getpreferredencoding() might
be a better choice (than locale.getdefaultlocale()[ 1 ]) for determining
a system's default encoding?

In other words change:

>>> codePage = locale.getdefaultlocale()[ 1 ]

To this:

>>> codePage = locale.getpreferredencoding() 

... in my original post's code (original post follows my signature).

Malcolm

----- Original message -----
From: python at bdurham.com
To: python-list at python.org
Date: Mon, 17 May 2010 13:54:27 -0400
Subject: Converting datetime.ctime() values to Unicode

I would like to convert datetime.ctime() values to Unicode.

Using Python 2.6.4 running under Windows I can set my locale to
Spanish like below:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'esp' )

Then I can pass %a, %A, %b, and %B to ctime() to get day and
month names and abbreviations.

>>> import datetime
>>> dateValue = datetime.date( 2010, 5, 15 )
>>> dayName = dateValue.strftime( '%A' )
>>> dayName
's\xe1bado'

How do I convert the 's\xe1bado' value to Unicode? Specifically what
encoding do I use?

I'm thinking I might do something like the following, but I'm not sure
this is the right approach.

>>> codePage = locale.getdefaultlocale()[ 1 ]
>>> dayNameUnicode = unicode( dayName, codePage )
>>> dayNameUnicode
u's\xe1bado'

Feedback appreciated.

Regards,
Malcolm

-- 
http://mail.python.org/mailman/listinfo/python-list



From malaclypse2 at gmail.com  Mon May 17 14:32:59 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Mon, 17 May 2010 14:32:59 -0400
Subject: Converting datetime.ctime() values to Unicode
In-Reply-To: <1274120067.18728.1375508915@webmail.messagingengine.com>
References: <1274118867.15576.1375504195@webmail.messagingengine.com>
	<1274120067.18728.1375508915@webmail.messagingengine.com>
Message-ID: 

On Mon, May 17, 2010 at 2:14 PM,   wrote:
> In researching a solution, I believe locale.getpreferredencoding() might
> be a better choice (than locale.getdefaultlocale()[ 1 ]) for determining
> a system's default encoding?

I haven't used the locale module a lot, but it seems to me that if
you're setting the locale with locale.setlocale(), you should get the
encoding from locale.getlocale()[1].

You're not really interested in the system's default encoding at this
point, you're interested in the encoding of the locale you've
explicitly set.

-- 
Jerry


From dodo_do_not_wake_up at yahoo.Fr  Mon May 17 14:34:21 2010
From: dodo_do_not_wake_up at yahoo.Fr (Dodo)
Date: Mon, 17 May 2010 20:34:21 +0200
Subject: Python3 buffer extra byte??
Message-ID: <4bf18c2d$0$27615$ba4acef3@reader.news.orange.fr>

Let's consider this code:

#!/usr/bin/python3
import cgi, sys
print("Content-type:image/jpeg\n\n")
f = open("img.jpg","rb")
sys.stdout.flush()
sys.stdout.buffer.write( f.read() )
f.close()

I receive the file with one padding byte at the start of the file (0x0a)
http://www.1pix.org/multi/images/wg7zg58gsgbhc9cppo5i.jpg

Any idea why?

Dorian
(yes, this is the continuation of "CGI python 3 write RAW BINARY")


From solipsis at pitrou.net  Mon May 17 14:46:12 2010
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Mon, 17 May 2010 20:46:12 +0200
Subject: Python3 buffer extra byte??
References: <4bf18c2d$0$27615$ba4acef3@reader.news.orange.fr>
Message-ID: <20100517204612.262b301f@pitrou.net>

On Mon, 17 May 2010 20:34:21 +0200
Dodo  wrote:

> Let's consider this code:
> 
> #!/usr/bin/python3
> import cgi, sys
> print("Content-type:image/jpeg\n\n")

print() adds an additional \n, so there's one too many.
Also, HTTP headers should be separated with \r\n, not \n.

(besides, under Windows \n will be converted to \r\n by the text I/O
layer, therefore, it would be better to use the binary I/O layer, a.k.a
sys.stdout.buffer, if you want your script to be portable)

Therefore, I would advocate rewriting it as:

sys.stdout.buffer.write(b"Content-type:image/jpeg\r\n\r\n")





From nima.irt at gmail.com  Mon May 17 15:08:02 2010
From: nima.irt at gmail.com (Nima Mohammadi)
Date: Mon, 17 May 2010 12:08:02 -0700 (PDT)
Subject: Installing Lightweight Python
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	
Message-ID: 

Thanks Geremy :)

The majority of installed files (56MB of data) reside in /lib/
python2.6/. So far, I took these steps to make it as compact as
possible:
1. I deleted /lib/python2.6/test directory. This reduced the size by
20MB.
2. I deleted .py files (cause the corresponding pyc ones are there).
This reduced the size by 9MB.
3. I deleted the /lib/libpython2.6.a which was 6MB.
* By far the python runs flawlessly.

4. I zip up the /lib/python2.6/ as python26.zip and place it in the /
lib/ directory.
Then I delete the /lib/python2.6/ directory. By running python, I get
this output, though /lib/python26.zip is in the sys.path variable.

nima at nima-desktop:~/py$ ./bin/python
Could not find platform independent libraries 
Could not find platform dependent libraries 
Consider setting $PYTHONHOME to [:]
'import site' failed; use -v for traceback
Python 2.6.5 (r265:79063, May 17 2010, 18:36:54)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/',
'/home/nima/py/lib/python2.6/plat-linux2', '/home/nima/py/lib/
python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old', '/home/nima/
py/lib/lib-dynload']



On May 17, 9:00?pm, geremy condra  wrote:
> I'm not an expert, but there are probably a large-ish number of modules
> you could remove without much sacrifice on your part. Looking at the
> module list and just picking the platform-dependent ones:
>
> * _winreg
> * aepack
> * aetools
> * aetypes
> * AL
> * al
> * applesingle
> * autoGIL
> * buildtools
> * Carbon
> * cd
> * cfmfile
> * chunk
> * colorpicker
> * etc
> * etc
> * etc
>
> You could also probably remove things like 2to3, tabnanny, etc,
> and I doubt tkinter is doing you much good.
>
> I also recall someone at pycon talking about importing modules
> from a .zip archive. I'm not sure how easy/hard that is, but you
> may want to look at PEP 302.
>
> Geremy Condra

Yours sincerely,
Nima Mohammadi


From mannu_0523 at rediffmail.com  Mon May 17 15:35:51 2010
From: mannu_0523 at rediffmail.com (mannu jha)
Date: 17 May 2010 19:35:51 -0000
Subject: =?utf-8?B?UmU6IFJlOiBqb2luaW5nIGZpbGVz?=
In-Reply-To: <4BF18BCD.6050407@iki.fi>
Message-ID: <1274120838.S.6249.7432.H.TlR1b21hcyBWZXN0ZXJpbmVuAFJlOiBqb2luaW5nIGZpbGVz.f4-234-233.1274124951.59048@webmail.rediffmail.com>



On Mon, 17 May 2010 23:57:18 +0530  wrote
>Try:
file = open("input11.txt")
file1 = file.read() # file1 is a string
file.close()
or
file1 = open("input11.txt") # file1 is an open file object
and replace lines:
     for line in sce.split(os.linesep):
       lst = line.split()
       lines[lst[0]] = (nme, lst)
with lines:
     for line in sce:
       lst = line.split()
       lines[lst[0]] = (nme, lst)
     sce.close()


Thankyou very much sir it has worked. Thankyou once again.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nima.irt at gmail.com  Mon May 17 16:05:29 2010
From: nima.irt at gmail.com (Nima)
Date: Tue, 18 May 2010 00:35:29 +0430
Subject: Installing Lightweight Python
In-Reply-To: 
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	
Message-ID: 

Well, I tried to run Python with -v option. It seems that python26.zip is
partially loaded but can't be used, because zlib is "unavailable".

nima at nima-desktop:~/py$ ./bin/*python -v*
Could not find platform independent libraries 
Could not find platform dependent libraries 
Consider setting $PYTHONHOME to [:]
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
*# zipimport: found 2509 names in /home/nima/py/lib/python26.zip*
# zipimport: *zlib UNAVAILABLE*
'import site' failed; traceback:
*zipimport.ZipImportError: can't decompress data; zlib not available
# zipimport: zlib UNAVAILABLE*
Python 2.6.5 (r265:79063, May 17 2010, 18:36:54)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/',
'/home/nima/py/lib/python2.6/plat-linux2',
'/home/nima/py/lib/python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old',
'/home/nima/py/lib/lib-dynload']


-- 
*Yours sincerely,
Nima Mohammadi*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nima.irt at gmail.com  Mon May 17 16:11:41 2010
From: nima.irt at gmail.com (Nima Mohammadi)
Date: Mon, 17 May 2010 13:11:41 -0700 (PDT)
Subject: Installing Lightweight Python
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	
	
Message-ID: <5b9dd21e-43c7-4603-90a7-51299e1a599b@f13g2000vbm.googlegroups.com>

Well, I tried to run Python with -v option. It seems that python26.zip
is partially loaded but can't be used, because zlib is "unavailable".

nima at nima-desktop:~/py$ ./bin/python -v
Could not find platform independent libraries 
Could not find platform dependent libraries 
Consider setting $PYTHONHOME to [:]
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# zipimport: found 2509 names in /home/nima/py/lib/python26.zip
# zipimport: zlib UNAVAILABLE
'import site' failed; traceback:
zipimport.ZipImportError: can't decompress data; zlib not available
# zipimport: zlib UNAVAILABLE

Python 2.6.5 (r265:79063, May 17 2010, 18:36:54)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/',
'/home/nima/py/lib/python2.6/plat-linux2', '/home/nima/py/lib/
python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old', '/home/nima/
py/lib/lib-dynload']


--
Yours sincerely,
Nima Mohammadi


From mehgcap at gmail.com  Mon May 17 16:19:59 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 17 May 2010 16:19:59 -0400
Subject: classes and __init__ question
Message-ID: 

Hi all,
I am a bit confused about classes. What do you pass a class, since all
the actual information is passed to __init__? For example, say you
have a dog class. The dog object has a name, a size, and a color. I
believe you would say this:

class dog():
 def __init__(self, name, size, color):
  self.name=name
  self.size=size
  self.color=color
 #end def
#end class

What, then, gets passed to the class constructor?
class dog(whatGoesHere?):
Sometimes I see things passed to this. For example, if you create a
class for a wxPython frame, you will say:
class myapp(wx.App):
In this case you pass something. However, I have a class that I use in
one of my programs to create "contact" objects, which looks like this:
class contact():
 def __init__(self, name, email, status, service):
  self.name=name
  self.email=email
  self.status=status
  self.service=service
 #end def
#end class

Here, I do not pass anything to the class, only to __init__. What is going on?

On a related note, is it horrible for resource usage to create a large
array, up to 500 or so, where each member is a small object? I am
thinking of, for example, a game board array where each member of the
array is a "square" object. A square might have a status, a color, and
other flags associated with it, so you could then say something like
board[i][j].hasGamePiece=True. Lookups and adjustments like this will
be going on a lot. Am I better off using an array of numbers where
each number means something different?

Thanks in advance for any info.


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


From debatem1 at gmail.com  Mon May 17 16:30:52 2010
From: debatem1 at gmail.com (geremy condra)
Date: Mon, 17 May 2010 13:30:52 -0700
Subject: Installing Lightweight Python
In-Reply-To: 
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	
	
Message-ID: 

On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> Well, I tried to run Python with -v option. It seems that python26.zip is
> partially loaded but can't be used, because zlib is "unavailable".

is the zlib module among the files you've compressed?

Geremy Condra


From pmaupin at gmail.com  Mon May 17 16:38:34 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Mon, 17 May 2010 13:38:34 -0700 (PDT)
Subject: classes and __init__ question
References: 
Message-ID: <9a25af1e-a41d-44cd-a965-e82acd6caa76@40g2000vbr.googlegroups.com>

On May 17, 3:19?pm, Alex Hall  wrote:
> Hi all,
> I am a bit confused about classes. What do you pass a class, since all
> the actual information is passed to __init__? For example, say you
> have a dog class. The dog object has a name, a size, and a color. I
> believe you would say this:
>
> class dog():
> ?def __init__(self, name, size, color):
> ? self.name=name
> ? self.size=size
> ? self.color=color
> ?#end def
> #end class
>
> What, then, gets passed to the class constructor?
> class dog(whatGoesHere?):
> Sometimes I see things passed to this. For example, if you create a
> class for a wxPython frame, you will say:
> class myapp(wx.App):
> In this case you pass something. However, I have a class that I use in
> one of my programs to create "contact" objects, which looks like this:
> class contact():
> ?def __init__(self, name, email, status, service):
> ? self.name=name
> ? self.email=email
> ? self.status=status
> ? self.service=service
> ?#end def
> #end class
>
> Here, I do not pass anything to the class, only to __init__. What is going on?
>
> On a related note, is it horrible for resource usage to create a large
> array, up to 500 or so, where each member is a small object? I am
> thinking of, for example, a game board array where each member of the
> array is a "square" object. A square might have a status, a color, and
> other flags associated with it, so you could then say something like
> board[i][j].hasGamePiece=True. Lookups and adjustments like this will
> be going on a lot. Am I better off using an array of numbers where
> each number means something different?
>
> Thanks in advance for any info.
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg... at gmail.com;http://www.facebook.com/mehgcap

What you are calling "passing to a class" is the superclass (or list
of superclasses) if you are creating a subclass.

Under Python 2.x, you might want to subclass object (if you need/want
a newstyle class), so it is fairly common to see:

class foo(object):
   whatever

Regards,
Pat


From python at bdurham.com  Mon May 17 16:45:47 2010
From: python at bdurham.com (python at bdurham.com)
Date: Mon, 17 May 2010 16:45:47 -0400
Subject: How to determine subprocess.Popen() failed when shell=True
Message-ID: <1274129147.11923.1375533733@webmail.messagingengine.com>

Windows version of Python 2.6.4: Is there any way to determine if
subprocess.Popen() fails when using shell=True?

Popen() successfully fails when shell=False

>>> import subprocess
>>> p = subprocess.Popen( 'Nonsense.application', shell=False )
Traceback (most recent call last):
  File "", line 1, in 
    p = subprocess.Popen( 'Nonsense.application' )
  File "C:\Python26\lib\subprocess.py", line 621, in __init__
    errread, errwrite)
  File "C:\Python26\lib\subprocess.py", line 830, in
_execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

But when shell=True, there appears to be no way to determine if a
Popen() call was successful or not.

>>> p = subprocess.Popen( 'Nonsense.application', shell=True )
>>> p

>>> p.pid
6620
>>> p.returncode
>>>

Regards,
Malcolm



From clp2 at rebertia.com  Mon May 17 16:51:50 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Mon, 17 May 2010 13:51:50 -0700
Subject: classes and __init__ question
In-Reply-To: 
References: 
Message-ID: 

On Mon, May 17, 2010 at 1:19 PM, Alex Hall  wrote:
> Hi all,
> I am a bit confused about classes. What do you pass a class, since all
> the actual information is passed to __init__? For example, say you
> have a dog class. The dog object has a name, a size, and a color. I
> believe you would say this:
>
> class dog():
> ?def __init__(self, name, size, color):
> ?self.name=name
> ?self.size=size
> ?self.color=color
> ?#end def
> #end class
>
> What, then, gets passed to the class constructor?
> class dog(whatGoesHere?):
> Sometimes I see things passed to this. For example, if you create a
> class for a wxPython frame, you will say:
> class myapp(wx.App):
> In this case you pass something. However, I have a class that I use in
> one of my programs to create "contact" objects, which looks like this:
> class contact():
> ?def __init__(self, name, email, status, service):
> ?self.name=name
> ?self.email=email
> ?self.status=status
> ?self.service=service
> ?#end def
> #end class
>
> Here, I do not pass anything to the class, only to __init__. What is going on?

There is no notion of "passing" stuff to classes (at least in the way
you're thinking about it). The parentheses in these cases have nothing
to do with function calls.

`class Foo(Bar, Baz):` declares a new class with classes Bar and Baz
as base classes (Python has multiple inheritance).

`class Foo():` declares a new class with only the class `object` as
its implicit base class. The parentheses can and almost always are
omitted in such cases, so one would normally write `class Foo:`
instead.

There's some metaclass magic involved and the constructor of the
metaclass is called (in the earlier case, with Bar and Baz among the
parameters) behind the scenes to create the class Foo itself, but Foo
itself isn't "called" when Foo is being created; indeed, that wouldn't
even make sense, for how could the class possibly be called when it's
still being defined?

In other words, the parentheses in class declarations have nothing
directly to do with function calls and it's probably best not to
conceptualize it that way; they're used just to specify base classes
(and the metaclass in recent Python versions with some extra syntax).

> On a related note, is it horrible for resource usage to create a large
> array, up to 500 or so, where each member is a small object? I am
> thinking of, for example, a game board array where each member of the
> array is a "square" object. A square might have a status, a color, and
> other flags associated with it, so you could then say something like
> board[i][j].hasGamePiece=True. Lookups and adjustments like this will
> be going on a lot. Am I better off using an array of numbers where
> each number means something different?

Premature optimization is the root of all evil. Only *if* your program
ends up using too much memory *and* memory profiling shows the board
to be a significant contributor to the problem, *then* you would start
looking into such memory optimizations.

Cheers,
Chris
--
http://blog.rebertia.com


From mehgcap at gmail.com  Mon May 17 16:55:20 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 17 May 2010 16:55:20 -0400
Subject: classes and __init__ question
In-Reply-To: <9a25af1e-a41d-44cd-a965-e82acd6caa76@40g2000vbr.googlegroups.com>
References: 
	<9a25af1e-a41d-44cd-a965-e82acd6caa76@40g2000vbr.googlegroups.com>
Message-ID: 

On 5/17/10, Patrick Maupin  wrote:
> On May 17, 3:19 pm, Alex Hall  wrote:
>> Hi all,
>> I am a bit confused about classes. What do you pass a class, since all
>> the actual information is passed to __init__? For example, say you
>> have a dog class. The dog object has a name, a size, and a color. I
>> believe you would say this:
>>
>> class dog():
>>  def __init__(self, name, size, color):
>>   self.name=name
>>   self.size=size
>>   self.color=color
>>  #end def
>> #end class
>>
>> What, then, gets passed to the class constructor?
>> class dog(whatGoesHere?):
>> Sometimes I see things passed to this. For example, if you create a
>> class for a wxPython frame, you will say:
>> class myapp(wx.App):
>> In this case you pass something. However, I have a class that I use in
>> one of my programs to create "contact" objects, which looks like this:
>> class contact():
>>  def __init__(self, name, email, status, service):
>>   self.name=name
>>   self.email=email
>>   self.status=status
>>   self.service=service
>>  #end def
>> #end class
>>
>> Here, I do not pass anything to the class, only to __init__. What is going
>> on?
>>
>> On a related note, is it horrible for resource usage to create a large
>> array, up to 500 or so, where each member is a small object? I am
>> thinking of, for example, a game board array where each member of the
>> array is a "square" object. A square might have a status, a color, and
>> other flags associated with it, so you could then say something like
>> board[i][j].hasGamePiece=True. Lookups and adjustments like this will
>> be going on a lot. Am I better off using an array of numbers where
>> each number means something different?
>>
>> Thanks in advance for any info.
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehg... at gmail.com;http://www.facebook.com/mehgcap
>
> What you are calling "passing to a class" is the superclass (or list
> of superclasses) if you are creating a subclass.
So what is a subclass compared to a class? Are you saying that what is
passed to the class, so what is in the parentheses of the class, is
really the superclass? If so, what is the advantage of doing this; why
not just create a class that is not a sub? I thinking I am missing
something elementary here. :)
>
> Under Python 2.x, you might want to subclass object (if you need/want
> a newstyle class), so it is fairly common to see:
>
> class foo(object):
>    whatever
In Java, a class is an object. Is Python the same thing? Would you say
that my dog class, for example, creates a new dog object when an
instance is instantiated?
Thanks.
>
> Regards,
> Pat
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


From clp2 at rebertia.com  Mon May 17 16:59:56 2010
From: clp2 at rebertia.com (Chris Rebert)
Date: Mon, 17 May 2010 13:59:56 -0700
Subject: How to determine subprocess.Popen() failed when shell=True
In-Reply-To: <1274129147.11923.1375533733@webmail.messagingengine.com>
References: <1274129147.11923.1375533733@webmail.messagingengine.com>
Message-ID: 

On Mon, May 17, 2010 at 1:45 PM,   wrote:
> Windows version of Python 2.6.4: Is there any way to determine if
> subprocess.Popen() fails when using shell=True?
>
> Popen() successfully fails when shell=False
>
>>>> import subprocess
>>>> p = subprocess.Popen( 'Nonsense.application', shell=False )
> Traceback (most recent call last):
> ?File "", line 1, in 
> ? ?p = subprocess.Popen( 'Nonsense.application' )
> ?File "C:\Python26\lib\subprocess.py", line 621, in __init__
> ? ?errread, errwrite)
> ?File "C:\Python26\lib\subprocess.py", line 830, in
> _execute_child
> ? ?startupinfo)
> WindowsError: [Error 2] The system cannot find the file specified
>
> But when shell=True, there appears to be no way to determine if a
> Popen() call was successful or not.
>
>>>> p = subprocess.Popen( 'Nonsense.application', shell=True )
>>>> p
> 
>>>> p.pid
> 6620
>>>> p.returncode
>>>>

I don't have a Windows box to test on, but have you tried p.wait()?
Worked for me on *nix:
$ python
Python 2.6.5 (r265:79063, May 11 2010, 13:15:13)
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen
>>> a = Popen("nonsense", shell=True)
>>> /bin/sh: nonsense: command not found

>>> a.returncode
>>> a.wait()
127
>>> a.returncode
127

Cheers,
Chris
--
http://blog.rebertia.com


From nima.irt at gmail.com  Mon May 17 17:04:18 2010
From: nima.irt at gmail.com (Nima Mohammadi)
Date: Mon, 17 May 2010 14:04:18 -0700 (PDT)
Subject: Installing Lightweight Python
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	 
	 
	
Message-ID: <34179bf9-88b2-4b8e-b21a-1b09d5bacfa3@o39g2000vbd.googlegroups.com>

On May 18, 12:30?am, geremy condra  wrote:
> On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> > Well, I tried to run Python with -v option. It seems that python26.zip is
> > partially loaded but can't be used, because zlib is "unavailable".
>
> is the zlib module among the files you've compressed?
>
> Geremy Condra

zlib.so is a shared library which is in the /lib/python2.6/lib-
dynload/ directory.
In PEP 273 is noted that:

> Any files may be present in the zip archive, but only files
> *.py and *.py[co] are available for import.  Zip import of
> dynamic modules (*.pyd, *.so) is disallowed.

http://www.python.org/dev/peps/pep-0273/

--
Yours sincerely,
Nima Mohammadi


From pmaupin at gmail.com  Mon May 17 17:09:34 2010
From: pmaupin at gmail.com (Patrick Maupin)
Date: Mon, 17 May 2010 14:09:34 -0700 (PDT)
Subject: classes and __init__ question
References:  
	<9a25af1e-a41d-44cd-a965-e82acd6caa76@40g2000vbr.googlegroups.com> 
	
Message-ID: 

On May 17, 3:55?pm, Alex Hall  wrote:

> So what is a subclass compared to a class? Are you saying that what is
> passed to the class, so what is in the parentheses of the class, is
> really the superclass? If so, what is the advantage of doing this; why
> not just create a class that is not a sub? I thinking I am missing
> something elementary here. :)

A subclass can inherit methods and attributes from a base class.  This
is not necessary, but is sometimes useful.

> In Java, a class is an object. Is Python the same thing?

Yes, a class is an object.  A class's class is its "metaclass".

An instance of a class is also an object.

> Would you say
> that my dog class, for example, creates a new dog object when an
> instance is instantiated?

Yes. But the actual act of coding something like:

class foo(object):
    pass

Creates a class object, which is a subclass of the 'object' object,
and is an instance of the 'type' object.  Since Python is so dynamic,
you can easily determine this at the command prompt:

>>> class foo(object):
...     pass
...
>>> x = foo()
>>>
>>> type(x)

>>> type(foo)

>>>


Regards,
Pat


From nima.irt at gmail.com  Mon May 17 17:09:43 2010
From: nima.irt at gmail.com (Nima Mohammadi)
Date: Mon, 17 May 2010 14:09:43 -0700 (PDT)
Subject: Installing Lightweight Python
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	 
	 
	
	<34179bf9-88b2-4b8e-b21a-1b09d5bacfa3@o39g2000vbd.googlegroups.com>
Message-ID: <2f3354d5-85e5-41ce-8eac-e23154867113@d12g2000vbr.googlegroups.com>

On May 18, 1:04?am, Nima Mohammadi  wrote:
> On May 18, 12:30?am, geremy condra  wrote:
>
> > On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> > > Well, I tried to run Python with -v option. It seems that python26.zip is
> > > partially loaded but can't be used, because zlib is "unavailable".
>
> > is the zlib module among the files you've compressed?
>
> > Geremy Condra
>
> zlib.so is a shared library which is in the /lib/python2.6/lib-
> dynload/ directory.
> In PEP 273 is noted that:
>
> > Any files may be present in the zip archive, but only files
> > *.py and *.py[co] are available for import. ?Zip import of
> > dynamic modules (*.pyd, *.so) is disallowed.
>
> http://www.python.org/dev/peps/pep-0273/
>
> --
> Yours sincerely,
> Nima Mohammadi

The problem is solved! I just needed to make a directory named
"python2.6" in the /lib/ directory and copy the lib-dynload/ directory
in it.
Thanks for your precious help, Geremy :)

Does anyone have the list of essentials modules to run python?


From apt.shansen at gmail.com  Mon May 17 17:18:13 2010
From: apt.shansen at gmail.com (Stephen Hansen)
Date: Mon, 17 May 2010 14:18:13 -0700
Subject: Installing Lightweight Python
In-Reply-To: <34179bf9-88b2-4b8e-b21a-1b09d5bacfa3@o39g2000vbd.googlegroups.com>
References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com>
	 
	 
	
	<34179bf9-88b2-4b8e-b21a-1b09d5bacfa3@o39g2000vbd.googlegroups.com>
Message-ID: 

On Mon, May 17, 2010 at 2:04 PM, Nima Mohammadi  wrote:

> On May 18, 12:30 am, geremy condra  wrote:
> > On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> > > Well, I tried to run Python with -v option. It seems that python26.zip
> is
> > > partially loaded but can't be used, because zlib is "unavailable".
> >
> > is the zlib module among the files you've compressed?
> >
> > Geremy Condra
>
> zlib.so is a shared library which is in the /lib/python2.6/lib-
> dynload/ directory.
>


Yes, but you're not running python from say, /bin; if you were, it might go
out and look in /lib and such to find files. You're running it from a local
directory, ./bin/python. Thus, its finding its "center" (where the
executable is installed), and from there building a search path.

Its center -- PYTHONHOME -- is /home/nima/py; from there, it adds
/home/nima/py/lib-dynload among other search paths.

So: zlib.so needs to be in /home/nima/py/lib-dynload. If its not, then it
won't be able to decompress python26.zip into memory.

In PEP 273 is noted that:
>
> > Any files may be present in the zip archive, but only files
> > *.py and *.py[co] are available for import.  Zip import of
> > dynamic modules (*.pyd, *.so) is disallowed.
>
> http://www.python.org/dev/peps/pep-0273/


He knows, he was wondering if you accidentally zipped up zlib.so in the zip,
basically. I think :)

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rolf.oltmans at gmail.com  Mon May 17 17:19:05 2010
From: rolf.oltmans at gmail.com (Oltmans)
Date: Mon, 17 May 2010 14:19:05 -0700 (PDT)
Subject: Some help needed with small multi-threaded program!
Message-ID: 

I've a small multi-threaded program that is written by keeping
Producer-Consumer pattern in mind. In the Producer part of the program
we create new users by doing a POST to a certain web URL whereas in
the Consumer part of the program we try to login newly created users.
Problem is that program sort of runs fine, however, it never
terminates itself and, more importantly, it doesn't print last-three
lines of the program(which is important for my purposes). I've looked
at the docs, but I couldn't figure out a solution so if someone can
spot the problem and suggest a solution that will be highly
appreciated. Many thanks in advance.

-----
#!/usr/bin/env python

import Queue
import re
import random
import time
import threading
import urllib2
import simplejson
from urllib2 import HTTPError
import urllib

base_url = "http://example.com/"
queue = Queue.Queue()
total_users = 0
#keeps the record of time it takes to create a user
create_user_times = {}
#keeps the record of time it takes to authenticate a user
login_user_times = {}
lock = threading.Lock()
errors = []

class User():
    def
__init__(self,firstName,lastName,email,password,userName,active):
        self.firstName = firstName
        self.lastName = lastName
        self.password = password
        self.email = email
        self.userName = userName
#producer
class CreateUsers(threading.Thread):
    def __init__(self,queue,limit):
        threading.Thread.__init__(self)
        self.queue = queue
        self.limit = limit

    def create_user(self):

        url = base_url + "users/"
        email = "stokeywonder+"+str(random.randrange(0,100000))
+"@example.com"
        obj = {'firstName' : 'Coyotee',
        'lastName' : 'Stevey', 'email' : email,
        'password':'7887',
        'userName':email
        }
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE
5.5; Windows NT)')
        req.add_header("Content-Type","application/json")
        req.add_data(simplejson.dumps(obj))

        try:

            t = time.time()
            f = urllib2.urlopen(req)
            page = f.read()
            if str(f.code) != '200':
                pass
            else:
                create_user_times[obj['userName']] = str("%.
2f"%float(time.time() - t))
                user = User(**obj)
                self.queue.put(user)

        except:
            errors.append(obj['userName'])

    def run(self):
        global total_users
        global lock

        while total_users < self.limit:
            lock.acquire()
            try:
                total_users += 1
            finally:
                lock.release()

            self.create_user()
            if total_users == self.limit:
                try:
                    self.queue.task_done()
                except ValueError:
                    pass

#Consumer
class TestService(threading.Thread):
    def __init__(self,queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def login(self,user):

        user_name = user.userName
        pwd = user.password
        url = base_url+'u?uName='+user_name+'&pwd='+pwd
        user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        req = urllib2.Request(url)
        req.add_header('User-Agent', user_agent)
        try:
            t = time.time()

            f = urllib2.urlopen(req)

            if str(f.code) != '200':
                pass
            else:
                login_user_times[user_name] = str("%.
2f"%float(time.time() - t))
        except:
            errors.append(user_name)

    def run (self):
        while True:
            user = self.queue.get()
            if user:
                self.login(user)


if __name__ == "__main__":
    #limit = number of users
    limit = 5
    th = []
    for i in range(2):
        t = CreateUsers(queue,limit)
        t1 = TestService(queue)
        t.start()
        t1.start()
        th.append(t1)
        th.append(t)

    for t in th:
        t.join()
    print create_user_times
    print '---------------'
    print login_user_times





From nahooda at hotmail.de  Mon May 17 17:29:49 2010
From: nahooda at hotmail.de (D. Schramm)
Date: Mon, 17 May 2010 23:29:49 +0200
Subject: wxPython: How to get letter colour from TextCtrl
Message-ID: <85dqqkFl53U1@mid.individual.net>

Hello,

I've got a problem getting the colour of a single letter within the 
TextCtrl widget:

letterstyle = wx.TextAttr()
self.p1.GetStyle(self.p1.XYToPosition(0,0),letterstyle)
color = letterstyle.GetTextColour()
print color

This should display the colour value of the very first letter in the 
very first line of the TextCtrl. But no matter what I try, it always 
returns the value (-1, -1, -1, 255).

Any help?

Thanks in advance,

Dennis Schramm


From ethan at stoneleaf.us  Mon May 17 18:01:35 2010
From: ethan at stoneleaf.us (Ethan Furman)
Date: Mon, 17 May 2010 15:01:35 -0700
Subject: classes and __init__ question
In-Reply-To: 
References: 
Message-ID: <4BF1BCBF.4010506@stoneleaf.us>

Alex Hall wrote:
> Hi all,
> I am a bit confused about classes. What do you pass a class, since all
> the actual information is passed to __init__? For example, say you
> have a dog class. The dog object has a name, a size, and a color. I
> believe you would say this:
> 
> class dog():
>  def __init__(self, name, size, color):
>   self.name=name
>   self.size=size
>   self.color=color

Here you have defined a dog class (you have not called it, yet).


> What, then, gets passed to the class constructor?
> class dog(whatGoesHere?):

whatGoesHere = any parent classes (the constructor is *not* being called 
yet)

parent classes can be used when you want what they have, but need to 
either add more, or change some, of the methods/attributes that the 
parent has.

> Sometimes I see things passed to this. For example, if you create a
> class for a wxPython frame, you will say:
> class myapp(wx.App):

wx.App is not being passed, per se, rather Python is being told that 
myapp is based on wx.App, and will have all the methods/attributes that 
wx.App has, plus whatever else follows.

So far, all that has been done is to _define_ classes.

> class contact():
>  def __init__(self, name, email, status, service):
>   self.name=name
>   self.email=email
>   self.status=status
>   self.service=service
> 
> Here, I do not pass anything to the class, only to __init__. What is going on?

You have defined a class -- nothing more, nothing less.

When you actually call the class is when any necessary items are passed 
to the constructor (__init__):

a_dog = dog('Ralph', 'big', RED)

this_app = myapp()

fred = contact('Fred Flinstone','f1 at flinstone.gv','active','exemplary')

Hope this helps.

~Ethan~


From stef.mientki at gmail.com  Mon May 17 18:05:31 2010
From: stef.mientki at gmail.com (Stef Mientki)
Date: Tue, 18 May 2010 00:05:31 +0200
Subject: wxPython: How to get letter colour from TextCtrl
In-Reply-To: <85dqqkFl53U1@mid.individual.net>
References: <85dqqkFl53U1@mid.individual.net>
Message-ID: <4BF1BDAB.7040503@gmail.com>

On 17-05-2010 23:29, D. Schramm wrote:
> Hello,
>
> I've got a problem getting the colour of a single letter within the
> TextCtrl widget:
>
> letterstyle = wx.TextAttr()
> self.p1.GetStyle(self.p1.XYToPosition(0,0),letterstyle)
> color = letterstyle.GetTextColour()
> print color
>
> This should display the colour value of the very first letter in the
> very first line of the TextCtrl. But no matter what I try, it always
> returns the value (-1, -1, -1, 255).
>
> Any help?
>
AFAIK, TextAttributes are just onw way, you can set them, but never read
them back.

cheers,
Stef
>
> Thanks in advance,
>
> Dennis Schramm



From ben+python at benfinney.id.au  Mon May 17 18:05:50 2010
From: ben+python at benfinney.id.au (Ben Finney)
Date: Tue, 18 May 2010 08:05:50 +1000
Subject: Picking a license
References: 
	
	 <87r5ldbw3k.fsf@benfinney.id.au>
	
Message-ID: <87fx1qji9t.fsf@benfinney.id.au>

aahz at pythoncraft.com (Aahz) writes:

> Ben Finney   wrote:
> >[It is impractical to] sell free software like selling loaves of
> >bread, but that's a much more limited case and a far cry from your
> >claim [that it's impractical to sell free software]. Selling free
> >software is quite practical and a good way to fund development of
> >software that otherwise wouldn't be written as free software.
>
> From my POV, if you're not selling COTS, you're really selling support
> and consulting services, because that's what keeps your competitors
> from just picking up your software and reselling it for cheaper. BTDT.

This thread has revealed some staggering gulfs in concepts as held by
different people. For example, I don't think it's at all germane to the
definition of ?sell FOO? that ?your competitors can pick up the FOO and
resell it cheaper?. Whether they can or not, that doesn't change that
fact that one is selling FOO.

Moreover, I don't try to prevent my competitors from reselling the
software (so long as they don't misrepresent who holds copyright or
further restrict the terms). That's part and parcel of the freedoms in
the software. Indeed, I find that helps the customers trust me more and
tend to come back when they want something else new; and my customers
are free to show others the solutions I've already implemented.

Thus is an ongoing business relationship crafted, including return
customers and referrals for new work. It really is practical to sell
free software.

-- 
 \          ?It's dangerous to be right when the government is wrong.? |
  `\                                   ?Francois Marie Arouet Voltaire |
_o__)                                                                  |
Ben Finney


From jbravado at gmail.com  Mon May 17 18:10:25 2010
From: jbravado at gmail.com (JB)
Date: Mon, 17 May 2010 15:10:25 -0700 (PDT)
Subject: Encoding troubles
Message-ID: <7bb834e4-940f-43eb-8ebb-8c29599dda87@h37g2000pra.googlegroups.com>

I'm working on the webapp of our company intranet and I had a question
about proper handling of user input that's causing encoding issues.

Some of the uesrs take notes in Microsoft Office and copy/paste these
into textarea's of the webapp. Some of the characters from Word such
as hypens (?) and apostrophes (?) are in an odd encoding. When passed
to the database using sqlalchemy they appear as ??? and other
characters.

What's the proper handling (conversion?) of user input before it gets
to my database. Do I need to start making a list of the offending
characters and .replace them? Or is there a means to decode/encode the
user input to something more generic? Thanks for your time.


From pengyu.ut at gmail.com  Mon May 17 18:26:51 2010
From: pengyu.ut at gmail.com (Peng Yu)
Date: Mon, 17 May 2010 17:26:51 -0500
Subject: Can't find _sqlite3.so in lib-dynload
Message-ID: 

I compiled python2.6.4 from source. But I can't find _sqlite3.so in
the install directory. I thought that _sqlite3.so should be generated
to the install directory.

Would you please let me know how to fix it?

-- 
Regards,
Peng


From debatem1 at gmail.com  Mon May 17 18:48:01 2010
From: debatem1 at gmail.com (geremy condra)
Date: Mon, 17 May 2010 15:48:01 -0700
Subject: Picking a license
In-Reply-To: <87fx1qji9t.fsf@benfinney.id.au>
References: 
	
	 <87r5ldbw3k.fsf@benfinney.id.au>
	 <87fx1qji9t.fsf@benfinney.id.au>
Message-ID: 

This whole conversation is ridiculous, and better suited to slashdot than
python-list. Is it really necessary for it to continue?

Geremy Condra


From rhodri at wildebst.demon.co.uk  Mon May 17 18:54:38 2010
From: rhodri at wildebst.demon.co.uk (Rhodri James)
Date: Mon, 17 May 2010 23:54:38 +0100
Subject: Global variables for python applications
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
	
Message-ID: 

On Mon, 17 May 2010 05:29:20 +0100, Steven D'Aprano  
 wrote:

> On Sun, 16 May 2010 18:57:15 -0700, John Nagle wrote:
>
>> James Mills wrote:
>>> The only place global variables are considered somewhat "acceptable"
>>> are as constants in a module shared as a static value.
>>
>>     Python really ought to have named constants.
>
> +1
>
> Unfortunately, it will most likely require new syntax, and semantics.
> While the concept of a constant is pretty straightforward for immutable
> types like ints and strings, what about mutable types?
>
> And then there's the moratorium, so even if we had agreement on semantics
> and syntax, and a patch, it couldn't be deployed for a few years.

Careful, you're reconflating two concepts that John separated: mutability  
of an object and binding of a name.  I'm on the side of 'named constant'  
meaning 'this name (in this scope) is bound to this object and cannot be  
rebound.'  That would cover most of the cases people care about, and the  
gotchas are essentially the same as with default arguments.

But yes, it would require new syntax.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses


From nyamatongwe+thunder at gmail.com  Mon May 17 19:05:10 2010
From: nyamatongwe+thunder at gmail.com (Neil Hodgson)
Date: Mon, 17 May 2010 23:05:10 GMT
Subject: Encoding troubles
In-Reply-To: <7bb834e4-940f-43eb-8ebb-8c29599dda87@h37g2000pra.googlegroups.com>
References: <7bb834e4-940f-43eb-8ebb-8c29599dda87@h37g2000pra.googlegroups.com>
Message-ID: 

JB:

> as hypens (?) and apostrophes (?) are in an odd encoding. When passed
> to the database using sqlalchemy they appear as ??? and other
> characters.

   The encoding is UTF-8. Normally the best way to handle encodings is
to convert to Unicode strings (unicode(s, "UTF-8")) as soon as possible
and perform most processing in Unicode.

   Neil


From bryanjugglercryptographer at yahoo.com  Mon May 17 19:29:22 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Mon, 17 May 2010 16:29:22 -0700 (PDT)
Subject: Some help needed with small multi-threaded program!
References: 
Message-ID: <94c05c9b-2f5f-42b2-a320-e0f7db7fab23@a2g2000prd.googlegroups.com>

Oltmans wrote:
> I've a small multi-threaded program that is written by keeping
> Producer-Consumer pattern in mind.
[...]
> Problem is that program sort of runs fine, however, it never
> terminates itself and, more importantly, it doesn't print last-three
> lines of the program(which is important for my purposes). I've looked
> at the docs, but I couldn't figure out a solution so if someone can
> spot the problem and suggest a solution that will be highly
> appreciated. Many thanks in advance.

Well, "the problem" may be a bit presumptuous, but here's *a* problem:

> class TestService(threading.Thread):
[...]
> ? ? def run (self):
> ? ? ? ? while True:
> ? ? ? ? ? ? user = self.queue.get()
> ? ? ? ? ? ? if user:
> ? ? ? ? ? ? ? ? self.login(user)

That thread will not exit, and your main thread tries to join it.

In other news. There's no reason to call queue.task_done() if you
never call queue.join(). Your exception handling is kind of whacked;
that errors[] list doesn't collect enough info and if your program
hangs it's no use.

Your Producer-Consumer pattern is a misfit. Registering a user then
trying to log her in is a nice sequential unit of work that one thread
could handle. The reason for threading in this problem is so that when
one user's work is waiting for the network, you can make progress on
other users.

Hope that helps.

-Bryan Olson


From g.rodola at gmail.com  Mon May 17 19:33:52 2010
From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=)
Date: Tue, 18 May 2010 01:33:52 +0200
Subject: Global variables for python applications
In-Reply-To: 
References: 
	
Message-ID: 

2010/5/16 Chris Rebert :
> On Sun, May 16, 2010 at 10:50 AM, AON LAZIO  wrote:
>> Hi,
>>    How can I set up global variables for the entire python applications?
>> Like I can call and set this variables in any .py files.
>>    Think of it as a global variable in a single .py file but this is for the
>> entire application.
>
> Thankfully, there is no such thing (can you say spaghetti code?). The
> closest approximation, as I said in my previous reply, is to use the
> namespace of a designated module for this purpose, and import that
> module wherever you need to access/modify these "superglobal"
> variables.
>
> Example:
> #g.py:
> #this module exists to hold superglobal vars
> global1 = "foo"
> global2 = "bar"
>
>
> #elsewhere.py:
> #this is some other module in the same program
> import mypackage.g as g
>
> print "global #1 = ", g.global1
> print "global #2 =", g.global2
> g.global1 = "baz" # modify a superglobal
> g.global3 = "qux" # create a new superglobal
>
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
> --
> http://mail.python.org/mailman/listinfo/python-list

I agree global variables are evil, but a config.py module within a
serie of global constants which are supposed to be shared amongst all
other modules is a little less evil, and also a different beast IMO.
Even if you use a class to store such data, a "global" reference to
its instance accessible from everywhere must still exist, so the
problem basically still stands.
I would be interested to know a good practice to solve such a problem.


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil


From aahz at pythoncraft.com  Mon May 17 19:38:56 2010
From: aahz at pythoncraft.com (Aahz)
Date: 17 May 2010 16:38:56 -0700
Subject: Can't find _sqlite3.so in lib-dynload
References: 
Message-ID: 

In article ,
Peng Yu   wrote:
>
>I compiled python2.6.4 from source. But I can't find _sqlite3.so in
>the install directory. I thought that _sqlite3.so should be generated
>to the install directory.
>
>Would you please let me know how to fix it?

Only if you provide some relevant details.  Such as, what OS?

http://www.mikeash.com/getting_answers.html
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.


From pengyu.ut at gmail.com  Mon May 17 20:08:35 2010
From: pengyu.ut at gmail.com (Peng Yu)
Date: Mon, 17 May 2010 17:08:35 -0700 (PDT)
Subject: Can't find _sqlite3.so in lib-dynload
References:  
	
Message-ID: <2f84cf3b-dda7-42f9-bf8e-ac35f99e9318@u7g2000vbq.googlegroups.com>

On May 17, 6:38?pm, a... at pythoncraft.com (Aahz) wrote:
> In article ,
> Peng Yu ? wrote:
>
>
>
> >I compiled python2.6.4 from source. But I can't find _sqlite3.so in
> >the install directory. I thought that _sqlite3.so should be generated
> >to the install directory.
>
> >Would you please let me know how to fix it?
>
> Only if you provide some relevant details. ?Such as, what OS?
>
> http://www.mikeash.com/getting_answers.html

ubuntu.


From alessandro at molarulez.com  Mon May 17 20:13:52 2010
From: alessandro at molarulez.com (Alessandro Molari)
Date: Tue, 18 May 2010 02:13:52 +0200
Subject: reading XML file using python
In-Reply-To: 
References: 
Message-ID: <201005180213.52470.alessandro@molarulez.com>

I can suggest you the lxml library at http://codespeak.net/lxml/

I've already used it and I think it works very well, it's more pythonic 
than the built-in xml library

For a simple use of xml functionalities you can read 
http://codespeak.net/lxml/tutorial.html

--------
Alessandro Molari
--------
On Monday 17 May 2010 10:34:51 shanti bhushan wrote:
> Hi ,
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com(any hyper text) from XML 
and
> print that.
> please give me the sample program for this.
> regards
> Shanti Bhushan
> Bangalore,India


From steve at REMOVE-THIS-cybersource.com.au  Mon May 17 20:22:52 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 18 May 2010 00:22:52 GMT
Subject: Global variables for python applications
References: 
	
	
	<4bf09ce6$0$1661$742ec2ed@news.sonic.net>
	
	
Message-ID: <4bf1dddc$0$27851$c3e8da3@news.astraweb.com>

On Mon, 17 May 2010 23:54:38 +0100, Rhodri James wrote:

> On Mon, 17 May 2010 05:29:20 +0100, Steven D'Aprano
>  wrote:
> 
>> On Sun, 16 May 2010 18:57:15 -0700, John Nagle wrote:
>>
>>> James Mills wrote:
>>>> The only place global variables are considered somewhat "acceptable"
>>>> are as constants in a module shared as a static value.
>>>
>>>     Python really ought to have named constants.
>>
>> +1
>>
>> Unfortunately, it will most likely require new syntax, and semantics.
>> While the concept of a constant is pretty straightforward for immutable
>> types like ints and strings, what about mutable types?
>>
>> And then there's the moratorium, so even if we had agreement on
>> semantics and syntax, and a patch, it couldn't be deployed for a few
>> years.
> 
> Careful, you're reconflating two concepts that John separated:
> mutability of an object and binding of a name.

In my own head the two issues of mutability and rebinding were completely 
separate, but I see now that didn't come through as clearly as I hoped in 
my post. My apologies for any confusion.


> I'm on the side of
> 'named constant' meaning 'this name (in this scope) is bound to this
> object and cannot be rebound.'  That would cover most of the cases
> people care about, and the gotchas are essentially the same as with
> default arguments.

I think it is an abuse of the term constant to allow you to talk about a 
mutable object being "constant", since it can vary. Generally, you don't 
care about identity, only equality. Making up a syntax on the spot:

constant pi = [3.1415]
assert pi = 3.1415
pi[0] = 3
assert pi = 3.1415

makes a mockery of the concept of a constant.

Having said that, recognising mutable objects is a hard problem, so 
simply for reasons of practicality we might have to just live with the 
limitation that "constants" can be mutated if the object supports it.



> But yes, it would require new syntax.


Ideally, but there may be alternatives. I've already mentioned the 
Cookbook recipe, or perhaps something like:

import constants
constants.register('pi')
pi = 3.1415


-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Mon May 17 20:36:13 2010
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 18 May 2010 00:36:13 GMT
Subject: abc don't play well with private method
References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com>
	<4be18d3d$0$19014$426a34cc@news.free.fr>
	
Message-ID: <4bf1e0fd$0$27851$c3e8da3@news.astraweb.com>

On Mon, 17 May 2010 06:35:11 -0700, mouadino wrote:

>> There's no such thing as a "private" attribute in Python. The
>> name-mangling mechanism invoked by "__name" is really meant to avoid
>> accidental redefinition of the attribute in a derived class.
> 
>> In this case, your attribute is expected to be redefined, so you
>> definitly don't want any name mangling here.
> 
> yes , but what i have supposed is that the name mangling will not be
> applied when you use abc especially when you decorate the function with
> abc.abstractmethod , because it's will(should) be redefined (so
> something is wrong with the abc module) .

No, your expectations are wrong. Name mangling works the same no matter 
what class, whether you are using ABCs or not.


>> Also and FWIW, the naming convention for "implementation attributes" is
>> a single leading underscore
> 
> sorry but i don't agree on this. the two underscore (__) are used in
> classes level for defining private method in the python way, and the one
> underscore (_) is used in the module level :

Whether you agree or not, single underscores are commonly used as the 
convention for private methods and attributes. See PEP 8, which is 
written by Python's creator, Guido van Rossum:

http://www.python.org/dev/peps/pep-0008/




> """Prepending a single underscore (_) has some support for protecting
> module variables and functions (not included with import * from).
> Prepending a double underscore (__) to an instance variable or method
> effectively serves to make the variable or method private to its class
> (using name mangling). """
> src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html


If that's what it says, it's wrong, because there's nothing "effective" 
about double-underscore privacy. It's a very weak, easily bypassed 
(deliberately and accidentally) form of privacy, and it complicates 
debugging.

Generally, most people here recommend you ignore leading double-
underscores and just flag your methods as "private by convention" with a 
single leading underscore.



-- 
Steven


From parag.kanade at gmail.com  Mon May 17 22:02:18 2010
From: parag.kanade at gmail.com (paragk)
Date: Mon, 17 May 2010 19:02:18 -0700 (PDT)
Subject: pickle unable to load collection
Message-ID: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com>

Hi,

I am unable to figure out the cause of python pickle unable to find
the collection module.

I am getting

    __import__(module)
ImportError: No module named collections

when I try to load a pickled object.

Details:

Python version:

Python 2.6 (r26:66721, Oct  2 2008, 11:35:03) [MSC v.1500 32 bit
(Intel)] on win32


[CODE]

import sys
import glob
import collections
import pickle

...

SomeListDict = collections.defaultdict(list)

... # Populate SomeListDict

DictFile = open (options.saveDict, 'w')
pickle.dump(SomeListDict , DictFile, -1)
DictFile.close()

...

# Try loading the dictionary

LoadDictFile = open(options.loadDict, 'rb')
SomeListDict = pickle.load(LoadDictFile)
LoadDictFile.close()

...
 [CODE END]

The pickle.dump(CallGraphDict, DictFile, -1) works fine. The
dictionary is saved.

The interesting thing is, the dump function is able to find the
collections module.
        try:
            __import__(module)
            mod = sys.modules[module]
            klass = getattr(mod, name)

The above try block succeeds.

module
str: collections

mod
module: 

klass
type: 


The SomeListDict = pickle.load(LoadDictFile) fails with

    __import__(module)
ImportError: No module named collections


The sequence of calls is:

    def load_global(self):
        module = self.readline()[:-1]
        name = self.readline()[:-1]
        klass = self.find_class(module, name)
        self.append(klass)
    dispatch[GLOBAL] = load_global

Variables:

module
str: collections

name
str: defaultdict


The code where the exception occurs is:

    def find_class(self, module, name):
        # Subclasses may override this
        __import__(module)
        mod = sys.modules[module]
        klass = getattr(mod, name)
        return klass


>From the above analysis, clearly the collection module exists, since
the dump works.

What am I missing?


From steven at REMOVE.THIS.cybersource.com.au  Mon May 17 22:07:56 2010
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 18 May 2010 02:07:56 GMT
Subject: pickle unable to load collection
References: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com>
Message-ID: 

On Mon, 17 May 2010 19:02:18 -0700, paragk wrote:

> Hi,
> 
> I am unable to figure out the cause of python pickle unable to find the
> collection module.
> 
> I am getting
> 
>     __import__(module)
> ImportError: No module named collections

What is the actual value of module? Here's an obvious failure mode:

>>> __import__("collections ")
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named collections


> module
> str: collections

Try printing repr(str) to see what's actually there.


It may also help if you post a copy-and-paste of the complete traceback.



-- 
Steven


From bryanjugglercryptographer at yahoo.com  Mon May 17 22:38:51 2010
From: bryanjugglercryptographer at yahoo.com (Bryan)
Date: Mon, 17 May 2010 19:38:51 -0700 (PDT)
Subject: Encoding troubles
References: <7bb834e4-940f-43eb-8ebb-8c29599dda87@h37g2000pra.googlegroups.com>
	
Message-ID: <2a2b3dcb-d323-4733-9efe-77f6466dd788@k25g2000prh.googlegroups.com>

Neil Hodgson wrote:
> JB:
>
> > as hypens (?) and apostrophes (?) are in an odd encoding. When passed
> > to the database using sqlalchemy they appear as ??? and other
> > characters.
>
> ? ?The encoding is UTF-8. Normally the best way to handle encodings is
> to convert to Unicode strings (unicode(s, "UTF-8")) as soon as possible
> and perform most processing in Unicode.

Good advice to work in Unicode (and in Python 3.X str is unicode), but
I'd guess the encoding he's getting is "Windows-1252". The default
character set of HTTP is ISO-8859-1, but Microsoft likes to use
Windows-1252 in it's place.

What to do about it? First, try specifying utf-8 in the form
containing the textarea, as in

  
Note that specifying ISO-8859-1 will not work, in that Microsoft will still use Windows-1252. I've heard they've gotten better at supporting utf-8, but I haven't tested. When a request comes in, check for a Content-Type header that names the character set, which should be: Content-Type: application/x-www-form-urlencoded; charset=utf-8 Then you con decode to a unicode object as Neil Hodgson explained. In case you still have to deal with Windows-1252, Python knows how to translate Windows-1252 to the best-fit in Unicode. In current Python 2.x: ustring = unicode(raw_string, 'Windows-1252') In Python 3.X, what comes from a socket is bytes, and str means unicode: ustring = str(raw_bytes, 'Windows-1252') Of course this all assumes that JB's database likes Unicode. If it chokes, then alternatives include encoding back to utf-8 and storing as binary, or translating characters to some best-fit in the set the database supports. -- --Bryan Olson From shuvro05 at gmail.com Mon May 17 23:52:01 2010 From: shuvro05 at gmail.com (shuvro) Date: Mon, 17 May 2010 20:52:01 -0700 (PDT) Subject: getting attributes and methods of class without creating object Message-ID: <50a7abf5-bbe7-4c2d-af53-209be5822a6a@q13g2000vbm.googlegroups.com> Suppose I have a class like this - class myClass(object): def __init__(self): self.a = 10 self.b = 20 def my_method(self,var = 20): self.local_var = var I want to know about its method(__init__ and my_method) and variables(a,b, local_var) without creating the object of it. I tried getmembers function of inspect module. But it can do this with an object of myClass as argument. Like import inspect var = myClass() inspect.getmembers(var) I have to know about this without creating the object of myClass. Can anyone help me please? From r1chardj0n3s at gmail.com Tue May 18 00:12:53 2010 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Tue, 18 May 2010 14:12:53 +1000 Subject: PyCon Australia 2010 program announced Message-ID: Hi all, The program for PyCon Australia 2010, to be held at the Sydney Masonic Center over the weekend of June 26 and 27, has been posted. View the full list of presentations and the schedule at: http://pycon-au.org/2010/conference/ Register here: http://pycon-au.org/reg Richard Jones PyCon Australia 2010 Program Chair From pmaupin at gmail.com Tue May 18 00:50:15 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Mon, 17 May 2010 21:50:15 -0700 (PDT) Subject: getting attributes and methods of class without creating object References: <50a7abf5-bbe7-4c2d-af53-209be5822a6a@q13g2000vbm.googlegroups.com> Message-ID: <25494d5d-19cd-43f2-8483-07bcdfa71a27@e28g2000vbd.googlegroups.com> On May 17, 10:52?pm, shuvro wrote: > Suppose I have a class like this - > > class myClass(object): > > ? ? def __init__(self): > ? ? ? ? self.a = 10 > ? ? ? ? self.b = 20 > > ? ? def my_method(self,var = 20): > ? ? ? ? self.local_var = var > > I want to know about its method(__init__ and my_method) and > variables(a,b, local_var) without creating the object of it. I tried > getmembers function of inspect module. But it can do this with an > object of myClass as argument. Like > > import inspect > var = myClass() > inspect.getmembers(var) > > I have to know about this without creating the object of myClass. > Can anyone help me please? Well, you can do the same thing with myClass itself: inspect.getmembers(myClass) But that won't show you a,b, or local_var, because those don't belong to the class. They only belong to class instances, and maybe even not all class instances. (For example, if my_method is not called, then the instance won't have local_var defined.) Python is a very dynamic language, and class instances (and even the classes themselves!) can be modified at any time during execution. You don't even have to be executing inside a class's function to add stuff to it: class foo: pass bar = foo() bar.a = 3 So to "know" about the attributes of an instance of a class without actually creating that instance is very difficult. You didn't specify why you want to do this, but often the reason is to try to catch potential errors without actually running code. This is typically called "linting", and there are a few Python packages designed to do this, such as pylint and pychecker. Probably others, but I don't know anything about them, because I find that in most cases, the best way to test or to reason about Python code is to actually run it. Regards, Pat From ershantibhushan at gmail.com Tue May 18 01:18:44 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Mon, 17 May 2010 22:18:44 -0700 (PDT) Subject: url fetching from xml depending upon selection Message-ID: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> I have a sample.XML file the code is like this My Podcasts Sun, 07 Mar 2010 15:53:26 GMT Sun, 07 Mar 2010 15:53:26 GMT This my python code from xml.etree import ElementTree with open('our.xml', 'rt') as f: tree = ElementTree.parse(f) for node, value in tree.findall('.//TestCase/Input'): url=node.attrib.get('url') print url i want to print the url depending on name="sprint_001". If i change my option to sprint_002 it should print url for sprint_002 From vincent at vincentdavis.net Tue May 18 01:21:32 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 17 May 2010 23:21:32 -0600 Subject: Is this an ok thing to do in a class Message-ID: Just wondering if there is a problem with mixing a dictionary into a class like this. Everything seems to work as I would expect. class foo(object): def __init__(self, x): self.letter = dict(a=1,b=2,c=3) self.A=self.letter['a'] self.x=self.letter[x] >>> afoo = foo('b') >>> afoo.x 2 >>> afoo.A 1 >>> afoo.letter['a'] 1 >>> afoo.letter.items() [('a', 1), ('c', 3), ('b', 2)] *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From ershantibhushan at gmail.com Tue May 18 01:23:43 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Mon, 17 May 2010 22:23:43 -0700 (PDT) Subject: url fetching from xml depending upon selection References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: <878c9bd6-eda2-4b97-b78a-c49b32ee7328@h37g2000pra.googlegroups.com> On May 18, 10:18?am, shanti bhushan wrote: > I have a sample.XML file > the code is like this > > > > > ? ? ? ? My Podcasts > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > > > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > > > > This my python code > from xml.etree import ElementTree > > with open('our.xml', 'rt') as f: > ? ? tree = ElementTree.parse(f) > > for node, value in tree.findall('.//TestCase/Input'): > > ? ? ? ? url=node.attrib.get('url') > ? ? ? ? print url > > i want to print the url depending on name="sprint_001". > If i change my option to sprint_002 it should print url for sprint_002 this code print all URL but there is no option to select URLs depending upon my choice from xml.etree import ElementTree with open('our.xml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.findall('.//TestCase/Input'): url=node.attrib.get('url') print url From ershantibhushan at gmail.com Tue May 18 01:45:13 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Mon, 17 May 2010 22:45:13 -0700 (PDT) Subject: url fetching from xml depending upon selection References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: <371a76e4-3fce-4578-9dfc-a20294607550@t14g2000prm.googlegroups.com> On May 18, 10:18?am, shanti bhushan wrote: > I have a sample.XML file > the code is like this > > > > > ? ? ? ? My Podcasts > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > > > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > > > > This my python code > from xml.etree import ElementTree > > with open('our.xml', 'rt') as f: > ? ? tree = ElementTree.parse(f) > > for node, value in tree.findall('.//TestCase/Input'): > > ? ? ? ? url=node.attrib.get('url') > ? ? ? ? print url > > i want to print the url depending on name="sprint_001". > If i change my option to sprint_002 it should print url for sprint_002 i am trying to do with this code please correct my code from xml.etree import ElementTree with open('our.xml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.findall('.//TestCase/Input'): if name=='Sprint_001': print node.attrib.get('url') i want to print only url that comes under name=Sprint_001 From shuvro05 at gmail.com Tue May 18 02:11:29 2010 From: shuvro05 at gmail.com (shuvro) Date: Mon, 17 May 2010 23:11:29 -0700 (PDT) Subject: getting attributes and methods of class without creating object References: <50a7abf5-bbe7-4c2d-af53-209be5822a6a@q13g2000vbm.googlegroups.com> <25494d5d-19cd-43f2-8483-07bcdfa71a27@e28g2000vbd.googlegroups.com> Message-ID: <84f6e33a-05da-4f3e-9d9f-532d7ce72d10@q13g2000vbm.googlegroups.com> On May 18, 11:50?am, Patrick Maupin wrote: > On May 17, 10:52?pm, shuvro wrote: > > > > > Suppose I have a class like this - > > > class myClass(object): > > > ? ? def __init__(self): > > ? ? ? ? self.a = 10 > > ? ? ? ? self.b = 20 > > > ? ? def my_method(self,var = 20): > > ? ? ? ? self.local_var = var > > > I want to know about its method(__init__ and my_method) and > > variables(a,b, local_var) without creating the object of it. I tried > > getmembers function of inspect module. But it can do this with an > > object of myClass as argument. Like > > > import inspect > > var = myClass() > > inspect.getmembers(var) > > > I have to know about this without creating the object of myClass. > > Can anyone help me please? > > Well, you can do the same thing with myClass itself: > > inspect.getmembers(myClass) > > But that won't show you a,b, or local_var, because those don't belong > to the class. ?They only belong to class instances, and maybe even not > all class instances. ?(For example, if my_method is not called, then > the instance won't have local_var defined.) > > Python is a very dynamic language, and class instances (and even the > classes themselves!) can be modified at any time during execution. > You don't even have to be executing inside a class's function to add > stuff to it: > > class foo: > ? ? pass > > bar = foo() > bar.a = 3 > > So to "know" about the attributes of an instance of a class without > actually creating that instance is very difficult. ?You didn't specify > why you want to do this, but often the reason is to try to catch > potential errors without actually running code. ?This is typically > called "linting", and there are a few Python packages designed to do > this, such as pylint and pychecker. ?Probably others, but I don't know > anything about them, because I find that in most cases, the best way > to test or to reason about Python code is to actually run it. > > Regards, > Pat Thanks Pat for your informative reply. Actually what I am trying to do is to write an external exporter for the data types an open source software(Blender). So, I have to collect the properties of the classes. Here, I have no chance to edit the class and add inspect codes there, neither I can create objects of the existing classes (that will do some additional things which I not want). Is it not possible with the existing python facilities (without adding external libraries) ? Shuvro From stefan_ml at behnel.de Tue May 18 03:04:14 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 May 2010 09:04:14 +0200 Subject: url fetching from xml depending upon selection In-Reply-To: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: shanti bhushan, 18.05.2010 07:18: > I have a sample.XML file > the code is like this > > > > > My Podcasts > Sun, 07 Mar 2010 15:53:26 > > GMT > Sun, 07 Mar 2010 15:53:26 > > GMT > > > > > > > > > > > > > > > > > > > > > > This my python code > from xml.etree import ElementTree > > with open('our.xml', 'rt') as f: > tree = ElementTree.parse(f) > > for node, value in tree.findall('.//TestCase/Input'): > > url=node.attrib.get('url') > print url > > i want to print the url depending on name="sprint_001". for test_case in tree.findall('.//TestCase'): if test_case.get('name') == 'sprint_002': for input_el in test_case: print input_el.get('url') Stefan From __peter__ at web.de Tue May 18 03:10:24 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 May 2010 09:10:24 +0200 Subject: pickle unable to load collection References: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com> Message-ID: paragk wrote: > Hi, > > I am unable to figure out the cause of python pickle unable to find > the collection module. > > I am getting > > __import__(module) > ImportError: No module named collections > > when I try to load a pickled object. > > Details: > > Python version: > > Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit > (Intel)] on win32 > > > [CODE] > > import sys > import glob > import collections > import pickle > > ... > > SomeListDict = collections.defaultdict(list) > > ... # Populate SomeListDict > > DictFile = open (options.saveDict, 'w') > pickle.dump(SomeListDict , DictFile, -1) > DictFile.close() [...] > From the above analysis, clearly the collection module exists, since > the dump works. > > What am I missing? You have to open the file in binary mode "wb". >>> import collections >>> import pickle >>> data = pickle.dumps(collections.defaultdict()) >>> pickle.loads(data) defaultdict(None, {}) Now simulate the effect of writing in text mode and reading in binary mode: >>> garbled_data = data.replace("\n", "\r\n") >>> pickle.loads(garbled_data) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/pickle.py", line 1374, in loads return Unpickler(file).load() File "/usr/lib/python2.6/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.6/pickle.py", line 1090, in load_global klass = self.find_class(module, name) File "/usr/lib/python2.6/pickle.py", line 1124, in find_class __import__(module) ImportError: No module named collections >>> try: pickle.loads(garbled_data) ... except ImportError as e: ... e ... ImportError('No module named collections\r',) So as Steven suspected there was a whitespace char in the module name: pickle.load() was looking for the "collections\r" module. Peter From jonvspython at gmail.com Tue May 18 03:31:51 2010 From: jonvspython at gmail.com (jon vs. python) Date: Tue, 18 May 2010 09:31:51 +0200 Subject: Pyserial and pysqlite data types, need advice In-Reply-To: References: Message-ID: The best thing I've found is this: http://eli.thegreenplace.net/2009/05/29/storing-blobs-in-a-sqlite-db-with-pythonpysqlite/ On Mon, May 17, 2010 at 5:05 PM, jon vs. python wrote: > Hi, > I'm trying to store frames received via serial port (using Pyserial) into a > sqlite database (using Pysqlite) in order to perform off-line processing. > Thus I could use both SQL's power and Python's magic to make everything > easier. I'd like my code to be generic and work both for binary and ascii > protocols, too. > > Which kind of data should I use to store the frames? > Should I store every byte as a char in VARCHAR? (This seems to fail when > trying to store non printable characters). > Should I encapsulate frames in buffer objects and store them in BLOBs? > (This seems to work but hides content and thus doesn't allow to use database > operations directly on the data) > I've also tried, unsuccessfully, to use bytearrays with pysqlite... > > Any suggestion? > > Thanks, Jon. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ershantibhushan at gmail.com Tue May 18 04:06:08 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Tue, 18 May 2010 01:06:08 -0700 (PDT) Subject: url fetching from xml depending upon selection References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: On May 18, 10:18?am, shanti bhushan wrote: > I have a sample.XML file > the code is like this > > > > > ? ? ? ? My Podcasts > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > ? ? ? ? Sun, 07 Mar 2010 15:53:26 > > GMT > > > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > ? > ? ? > ? ? > ? ? > ? > > > > This my python code > from xml.etree import ElementTree > > with open('our.xml', 'rt') as f: > ? ? tree = ElementTree.parse(f) > > for node, value in tree.findall('.//TestCase/Input'): > > ? ? ? ? url=node.attrib.get('url') > ? ? ? ? print url > > i want to print the url depending on name="sprint_001". > If i change my option to sprint_002 it should print url for sprint_002 i have tried some new things here from xml.etree import ElementTree with open('our.xml', 'rt') as f: tree = ElementTree.parse(f) for node in tree.findall('.//TestCase/'): print node.attrib.keys() print node.attrib.items() print node.attrib.get(1) url=node.attrib.get('url') print url but i am not getting idea ... how to achive my motive From ershantibhushan at gmail.com Tue May 18 04:08:48 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Tue, 18 May 2010 01:08:48 -0700 (PDT) Subject: url fetching from xml depending upon selection References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: <9bf77ce4-474a-45ff-9955-23faadf8bac2@s4g2000prh.googlegroups.com> On May 18, 12:04?pm, Stefan Behnel wrote: > shanti bhushan, 18.05.2010 07:18: > > > > > > > I have a sample.XML file > > the code is like this > > > > > > > > > ? ?My Podcasts > > ? ?Sun, 07 Mar 2010 15:53:26 > > > GMT > > ? ?Sun, 07 Mar 2010 15:53:26 > > > GMT > > > > > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > > > > > > This my python code > > from xml.etree import ElementTree > > > with open('our.xml', 'rt') as f: > > ? ? ?tree = ElementTree.parse(f) > > > for node, value in tree.findall('.//TestCase/Input'): > > > ? ? ? ? ?url=node.attrib.get('url') > > ? ? ? ? ?print url > > > i want to print the url depending on name="sprint_001". > > ? ? ?for test_case in tree.findall('.//TestCase'): > ? ? ? ? ?if test_case.get('name') == 'sprint_002': > ? ? ? ? ? ? for input_el in test_case: > ? ? ? ? ? ? ? ? print input_el.get('url') > > Stefan- Hide quoted text - > > - Show quoted text - Hi Stevan i tried your logic i am not getting any out put for this From stefan_ml at behnel.de Tue May 18 04:12:57 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 May 2010 10:12:57 +0200 Subject: url fetching from xml depending upon selection In-Reply-To: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: shanti bhushan, 18.05.2010 07:18: > I have a sample.XML file > the code is like this > > > > > My Podcasts > Sun, 07 Mar 2010 15:53:26 > > GMT > Sun, 07 Mar 2010 15:53:26 > > GMT > > > > > > > > > > > > > > > > > > > > > > This my python code > from xml.etree import ElementTree > > with open('our.xml', 'rt') as f: > tree = ElementTree.parse(f) > > for node, value in tree.findall('.//TestCase/Input'): > > url=node.attrib.get('url') > print url > > > > i want to print the url depending on name="sprint_001". > If i change my option to sprint_002 it should print url for sprint_002 Actually, try this: test_cases = dict( (test_case.get('name'), [ el.get('url') for el in test_case ]) for test_case in tree.findall('.//TestCase') ) print test_cases['Sprint_001'] # -> prints list of URLs That gives you a dict of test case names that are mapped to the list of their URLs. Stefan From ershantibhushan at gmail.com Tue May 18 04:19:20 2010 From: ershantibhushan at gmail.com (shanti bhushan) Date: Tue, 18 May 2010 01:19:20 -0700 (PDT) Subject: url fetching from xml depending upon selection References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> Message-ID: <57174614-2db9-4171-bd4e-6d2720f1552c@h20g2000prn.googlegroups.com> On May 18, 12:04?pm, Stefan Behnel wrote: > shanti bhushan, 18.05.2010 07:18: > > > > > > > I have a sample.XML file > > the code is like this > > > > > > > > > ? ?My Podcasts > > ? ?Sun, 07 Mar 2010 15:53:26 > > > GMT > > ? ?Sun, 07 Mar 2010 15:53:26 > > > GMT > > > > > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > ? ? > > ? ? ? > > ? ? ? > > ? ? ? > > ? ? > > > > > > > This my python code > > from xml.etree import ElementTree > > > with open('our.xml', 'rt') as f: > > ? ? ?tree = ElementTree.parse(f) > > > for node, value in tree.findall('.//TestCase/Input'): > > > ? ? ? ? ?url=node.attrib.get('url') > > ? ? ? ? ?print url > > > i want to print the url depending on name="sprint_001". > > ? ? ?for test_case in tree.findall('.//TestCase'): > ? ? ? ? ?if test_case.get('name') == 'sprint_002': > ? ? ? ? ? ? for input_el in test_case: > ? ? ? ? ? ? ? ? print input_el.get('url') > > Stefan- Hide quoted text - > > - Show quoted text - Great Help Stefan - my regards to you thankyou once again it waorks fine ... From parag.kanade at gmail.com Tue May 18 04:26:24 2010 From: parag.kanade at gmail.com (paragk) Date: Tue, 18 May 2010 01:26:24 -0700 (PDT) Subject: pickle unable to load collection References: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com> Message-ID: On May 18, 12:10?am, Peter Otten <__pete... at web.de> wrote: > paragk wrote: > > Hi, > > > I am unable to figure out the cause of python pickle unable to find > > the collection module. > > > I am getting > > > ? ? __import__(module) > > ImportError: No module named collections > > > when I try to load a pickled object. > > > Details: > > > Python version: > > > Python 2.6 (r26:66721, Oct ?2 2008, 11:35:03) [MSC v.1500 32 bit > > (Intel)] on win32 > > > [CODE] > > > import sys > > import glob > > import collections > > import pickle > > > ... > > > SomeListDict = collections.defaultdict(list) > > > ... # Populate SomeListDict > > > DictFile = open (options.saveDict, 'w') > > pickle.dump(SomeListDict , DictFile, -1) > > DictFile.close() > > [...] > > > From the above analysis, clearly the collection module exists, since > > the dump works. > > > What am I missing? > > You have to open the file in binary mode "wb". > > >>> import collections > >>> import pickle > >>> data = pickle.dumps(collections.defaultdict()) > >>> pickle.loads(data) > > defaultdict(None, {}) > > Now simulate the effect of writing in text mode and reading in binary mode: > > >>> garbled_data = data.replace("\n", "\r\n") > >>> pickle.loads(garbled_data) > > Traceback (most recent call last): > ? File "", line 1, in > ? File "/usr/lib/python2.6/pickle.py", line 1374, in loads > ? ? return Unpickler(file).load() > ? File "/usr/lib/python2.6/pickle.py", line 858, in load > ? ? dispatch[key](self) > ? File "/usr/lib/python2.6/pickle.py", line 1090, in load_global > ? ? klass = self.find_class(module, name) > ? File "/usr/lib/python2.6/pickle.py", line 1124, in find_class > ? ? __import__(module) > ImportError: No module named collections > > >>> try: pickle.loads(garbled_data) > > ... except ImportError as e: > ... ? ? e > ... > ImportError('No module named collections\r',) > > So as Steven suspected there was a whitespace char in the module name: > pickle.load() was looking for the "collections\r" module. > > Peter Thank you for the suggestions. Opening the file in 'wb' mode worked. Thanks, Parag From stefan_ml at behnel.de Tue May 18 04:26:47 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 May 2010 10:26:47 +0200 Subject: url fetching from xml depending upon selection In-Reply-To: <9bf77ce4-474a-45ff-9955-23faadf8bac2@s4g2000prh.googlegroups.com> References: <4e5ef034-168a-4103-993a-9db65f2f97ba@k25g2000prh.googlegroups.com> <9bf77ce4-474a-45ff-9955-23faadf8bac2@s4g2000prh.googlegroups.com> Message-ID: shanti bhushan, 18.05.2010 10:08: > On May 18, 12:04 pm, Stefan Behnel wrote: >> shanti bhushan, 18.05.2010 07:18: >>> [...] >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >> >>> This my python code >>> from xml.etree import ElementTree >> >>> with open('our.xml', 'rt') as f: >>> tree = ElementTree.parse(f) >> >>> for node, value in tree.findall('.//TestCase/Input'): >> >>> url=node.attrib.get('url') >>> print url >> >>> i want to print the url depending on name="sprint_001". >> >> for test_case in tree.findall('.//TestCase'): >> if test_case.get('name') == 'sprint_002': >> for input_el in test_case: >> print input_el.get('url') >> > i tried your logic i am not getting any out put for this Obviously, because the correct name value is 'Sprint_002', not 'sprint_002'. Please ask back if you need help in understanding the code I posted. Stefan From duncan.booth at invalid.invalid Tue May 18 04:39:43 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 May 2010 08:39:43 GMT Subject: Global variables for python applications References: <4bf09ce6$0$1661$742ec2ed@news.sonic.net> <4bf1dddc$0$27851$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I think it is an abuse of the term constant to allow you to talk about a > mutable object being "constant", since it can vary. Generally, you don't > care about identity, only equality. Making up a syntax on the spot: > > constant pi = [3.1415] > assert pi = 3.1415 > pi[0] = 3 > assert pi = 3.1415 > > makes a mockery of the concept of a constant. A better keyword might be something like 'alias' to imply that the name and value are interchangeable. -- Duncan Booth http://kupuguy.blogspot.com From simon at brunningonline.net Tue May 18 04:54:37 2010 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 18 May 2010 09:54:37 +0100 Subject: Is this an ok thing to do in a class In-Reply-To: References: Message-ID: On 18 May 2010 06:21:32 UTC+1, Vincent Davis wrote: > > Just wondering if there is a problem with mixing a dictionary into a class like this. Everything seems to work as I would expect. No problem at all AFAIC. -- Cheers, Simon B. From pacopyc at gmail.com Tue May 18 05:45:03 2010 From: pacopyc at gmail.com (pacopyc) Date: Tue, 18 May 2010 02:45:03 -0700 (PDT) Subject: max time wait for a function Message-ID: <4418c1f3-564f-48c1-85e3-48d5678a4f38@y21g2000vba.googlegroups.com> Hi, I've a question for you. I'd like to call a function and waiting its return value for a time max (30 sec). The function could not respond and then I must avoid to wait for infinite time. OS is Windows XP. Can you help me? Thank From marduk at letterboxes.org Tue May 18 06:24:23 2010 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 18 May 2010 06:24:23 -0400 Subject: max time wait for a function In-Reply-To: <4418c1f3-564f-48c1-85e3-48d5678a4f38@y21g2000vba.googlegroups.com> References: <4418c1f3-564f-48c1-85e3-48d5678a4f38@y21g2000vba.googlegroups.com> Message-ID: <1274178263.232897.38.camel@paska> On Tue, 2010-05-18 at 02:45 -0700, pacopyc wrote: > Hi, I've a question for you. I'd like to call a function and waiting > its return value for a time max (30 sec). > The function could not respond and then I must avoid to wait for > infinite time. OS is Windows XP. > Can you help me? > > Thank This is how I do it with a function decorator. I probably borrowed this from someone and not attributed it. Anyway, it works on Linux, not sure about Windows: def function_timeout(seconds): """Function decorator to raise a timeout on a function call""" import signal class FunctionTimeOut(Exception): pass def decorate(f): def timeout(signum, frame): raise FunctionTimeOut() def funct(*args, **kwargs): old = signal.signal(signal.SIGALRM, timeout) signal.alarm(seconds) try: result = f(*args, **kwargs) finally: signal.signal(signal.SIGALRM, old) signal.alarm(0) return result return funct return decorate From kushal.kumaran+python at gmail.com Tue May 18 07:10:23 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 18 May 2010 16:40:23 +0530 Subject: Can't find _sqlite3.so in lib-dynload In-Reply-To: <2f84cf3b-dda7-42f9-bf8e-ac35f99e9318@u7g2000vbq.googlegroups.com> References: <2f84cf3b-dda7-42f9-bf8e-ac35f99e9318@u7g2000vbq.googlegroups.com> Message-ID: On Tue, May 18, 2010 at 5:38 AM, Peng Yu wrote: > On May 17, 6:38?pm, a... at pythoncraft.com (Aahz) wrote: >> In article , >> Peng Yu ? wrote: >> >> >> >> >I compiled python2.6.4 from source. But I can't find _sqlite3.so in >> >the install directory. I thought that _sqlite3.so should be generated >> >to the install directory. >> >> >Would you please let me know how to fix it? >> >> Only if you provide some relevant details. ?Such as, what OS? >> >> http://www.mikeash.com/getting_answers.html > > ubuntu. Did the build process give a message at the end listing out the modules it couldn't build? Was _sqlite3 in that list? Do you have the sqlite3 dev package installed? With ubuntu, that's the libsqlite3-dev package. -- regards, kushal From awilliam at whitemice.org Tue May 18 08:12:59 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 18 May 2010 08:12:59 -0400 Subject: subprocess and gvfs-mount In-Reply-To: References: Message-ID: <1274184779.4085.2.camel@linux-yu4c.site> On Mon, 2010-05-17 at 17:54 +0200, Samuel Bancal wrote: > Hi, > I'm coding a script that does some automates for my users ... > including mounting a smb share. > Because we are using Gnome, I choosed to use gvfs-mount, which is > quite similar to "Places > Connect to Server > ..."= > Now my script does : > print "*** Mounting the FILER ..." > cmd = "/usr/bin/gvfs-mount smb://%s\;% > s at myfiler.domain.ch/data/%s" % (my_domain, my_user_name, my_user_name) > try: > retCode = subprocess.call(cmd, shell=True) > except KeyboardInterrupt, e: > sys.stderr.write("Interrupted by ctrl-c. Exiting\n") > sys.exit(1) > if retCode != 0: > sys.stderr.write("Error while mounting : %s\n" % retCode > I have two major problems with this code : > - In case of "ctr-c" while the password is asked to the user, I get a > Terminal in which the output from keyboard is inhibited... (like while > typing password) > - When the user runs this script by "double-click > Run" (not "Run in > terminal") ... there is no interaction with the user. Which is normal [there is a run-in-terminal check box somewhere?]. If your users are running it in GNOME then you should implement a GUI (PyGTK) for the user interaction [prompting for the password]. Or better use the GNOME keyring. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From bryanjugglercryptographer at yahoo.com Tue May 18 09:22:23 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 18 May 2010 06:22:23 -0700 (PDT) Subject: max time wait for a function References: <4418c1f3-564f-48c1-85e3-48d5678a4f38@y21g2000vba.googlegroups.com> Message-ID: <5d0c68d3-21b0-49aa-ab78-dad0bccbfe45@v29g2000prb.googlegroups.com> pacopyc wrote: > I'd like to call a function and waiting > its return value for a time max (30 sec). > The function could not respond and then I must avoid to wait for > infinite time. OS is Windows XP. You can do that using the multiprocessing module, which is in the standard library of Python 2.6 or better. It has certain limitations, but works on XP. The functions have to be defined at module scope, and the arguments and return value must be pickleable. The way multiprocessing works on Windows, it launches a new process which runs the Python interpreter on the module again, and pickles the arguments to pipe them to the new process. Below is a simple working demo/test. The demo uses a timeout of 1 second, rather than the specified 30, to avoid excessive boringness. In practice, timeout_function() would be recklessly inefficient for controlling quick operations; it creates a new pool of processes for each function call that it might need to time-out. That's fixable, but the question here is about a 30-second-plus processing problem, and in that kind of case the overhead of creating one or a few new processes is lost in the noise. -Bryan Olson #-------------------- from multiprocessing import Pool, TimeoutError def timeout_function(timeout, f, args=(), kwargs={}): """ Return f(*args, **kwargs), or if that takes to long raise multiprocessing.TimeoutError. """ pool = Pool(1) return pool.apply_async(f, args, kwargs).get(timeout) #-------------- # simple demo-test: from random import random as rand from time import sleep def sillyfunc(sleeptime): # Time-absorbing function for testing sleep(sleeptime) return 'Done.' if __name__ == '__main__': timeout = 1.0 print "Timeout is %f seconds" % timeout trials = 100 ntimeouts = 0 for _ in range(trials): # time-out probability a bit over 0.5 sleeptime = rand() * timeout * 2 try: result = timeout_function( timeout, sillyfunc, (sleeptime,)) assert result == 'Done.' print 'Ran without timing out' except TimeoutError: ntimeouts += 1 print 'Timed out' if sleeptime < timeout: print '...Sucks! Slept %f' % sleeptime print 'Timed out %d out of %d' % (ntimeouts, trials) From backgoodoo at gmail.com Tue May 18 09:48:55 2010 From: backgoodoo at gmail.com (Back9) Date: Tue, 18 May 2010 06:48:55 -0700 (PDT) Subject: Regular expression Message-ID: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> Hi, I have a string like this: 0x340x5A0x9B0xBA I want to extract 0x from the string but the first one. How I can use re for this case? The string size will vary. TIA From terenzio.berni at gmail.com Tue May 18 10:09:48 2010 From: terenzio.berni at gmail.com (ilvecchio) Date: Tue, 18 May 2010 07:09:48 -0700 (PDT) Subject: Regular expression References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> Message-ID: <70937fa2-8e91-4343-91e5-2abfc7b755b6@y21g2000vba.googlegroups.com> On May 18, 3:48?pm, Back9 wrote: > ?Hi, > > I have a string like this: > 0x340x5A0x9B0xBA > I want to extract 0x from the string but the first one. > > How I can use re for this case? > > The string size will vary. > > TIA Maybe the easy way is something like this: m = re.match('(0x)(.*)','0x340x5A0x9B0xBA') m.groups()[1] Terenzio From backgoodoo at gmail.com Tue May 18 10:32:54 2010 From: backgoodoo at gmail.com (Back9) Date: Tue, 18 May 2010 07:32:54 -0700 (PDT) Subject: Regular expression References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> <70937fa2-8e91-4343-91e5-2abfc7b755b6@y21g2000vba.googlegroups.com> Message-ID: <7d9d0c8a-26b7-4cc2-8a20-11dc852e2800@j27g2000vbp.googlegroups.com> On May 18, 10:09?am, ilvecchio wrote: > On May 18, 3:48?pm, Back9 wrote: > > > ?Hi, > > > I have a string like this: > > 0x340x5A0x9B0xBA > > I want to extract 0x from the string but the first one. > > > How I can use re for this case? > > > The string size will vary. > > > TIA > > Maybe the easy way is something like this: > > m = re.match('(0x)(.*)','0x340x5A0x9B0xBA') > m.groups()[1] > > Terenzio I mean the result should be like this: 0x345A9BBA From lourosas at gmail.com Tue May 18 10:35:57 2010 From: lourosas at gmail.com (Lou) Date: Tue, 18 May 2010 07:35:57 -0700 (PDT) Subject: Multi-Threading in Python Message-ID: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> Can anyone tell me how easy it is to do multi-threading in Python? This has probably been brought up already, so if it has, thanks anyway From joncle at googlemail.com Tue May 18 10:37:22 2010 From: joncle at googlemail.com (Jon Clements) Date: Tue, 18 May 2010 07:37:22 -0700 (PDT) Subject: Regular expression References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> <70937fa2-8e91-4343-91e5-2abfc7b755b6@y21g2000vba.googlegroups.com> <7d9d0c8a-26b7-4cc2-8a20-11dc852e2800@j27g2000vbp.googlegroups.com> Message-ID: <5f25fa23-0968-4426-bcd4-7075c94f4b64@e21g2000vbl.googlegroups.com> On 18 May, 15:32, Back9 wrote: > On May 18, 10:09?am, ilvecchio wrote: > > > > > On May 18, 3:48?pm, Back9 wrote: > > > > ?Hi, > > > > I have a string like this: > > > 0x340x5A0x9B0xBA > > > I want to extract 0x from the string but the first one. > > > > How I can use re for this case? > > > > The string size will vary. > > > > TIA > > > Maybe the easy way is something like this: > > > m = re.match('(0x)(.*)','0x340x5A0x9B0xBA') > > m.groups()[1] > > > Terenzio > > I mean the result should be like this: > 0x345A9BBA Something like: re.sub(r'\B(0x)', '', s) hth, Jon. From jcd at sdf.lonestar.org Tue May 18 10:40:56 2010 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 18 May 2010 10:40:56 -0400 Subject: Regular expression In-Reply-To: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> Message-ID: <1274193656.13989.10.camel@jcdyer-laptop> Don't use regular expressions for that. s = '0x340x5A0x9B0xBA' return '0x' + ''.join(s.split('0x')) On Tue, 2010-05-18 at 06:48 -0700, Back9 wrote: > Hi, > > I have a string like this: > 0x340x5A0x9B0xBA > I want to extract 0x from the string but the first one. > > How I can use re for this case? > > The string size will vary. > > TIA > From awilliam at whitemice.org Tue May 18 10:45:11 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 18 May 2010 10:45:11 -0400 Subject: Multi-Threading in Python In-Reply-To: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> Message-ID: <1274193911.4085.13.camel@linux-yu4c.site> On Tue, 2010-05-18 at 07:35 -0700, Lou wrote: > Can anyone tell me how easy it is to do multi-threading in Python? Very easy. Or as easy as in any other platform - and as easy to screw up. Personally I prefer to use multiprocessing [which is a module that 'simulates' threads using separate processes]. IMO, it is hard to screw up as you don't get any shared-state for free. > This has probably been brought up already, so if it has, thanks anyway -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From bruno.42.desthuilliers at websiteburo.invalid Tue May 18 10:50:51 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 18 May 2010 16:50:51 +0200 Subject: Is this an ok thing to do in a class In-Reply-To: References: Message-ID: <4bf2a930$0$14553$426a74cc@news.free.fr> Simon Brunning a ?crit : > On 18 May 2010 06:21:32 UTC+1, Vincent Davis wrote: >> Just wondering if there is a problem with mixing a dictionary into a class like this. Everything seems to work as I would expect. > > No problem at all AFAIC. OP didn't show up on c.l.py, so too bad you snipped the relevant code snippet... From bruno.42.desthuilliers at websiteburo.invalid Tue May 18 11:17:35 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 18 May 2010 17:17:35 +0200 Subject: abc don't play well with private method In-Reply-To: References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com> <4be18d3d$0$19014$426a34cc@news.free.fr> Message-ID: <4bf2af74$0$24527$426a74cc@news.free.fr> mouadino a ?crit : > Hello > and thanx for your answer it's was very helpful > > but just to clear some thinks : > >> There's no such thing as a "private" attribute in Python. The >> name-mangling mechanism invoked by "__name" is really meant to avoid >> accidental redefinition of the attribute in a derived class. > >> In this case, your attribute is expected to be redefined, so you >> definitly don't want any name mangling here. > > yes , but what i have supposed is that the name mangling will not be > applied when you use abc especially when you decorate the function > with abc.abstractmethod , because it's will(should) be redefined (so > something is wrong with the abc module) . I agree this might be a bit inconsistant - or at least that your expectations were rather understandable. But well, that's how it is and you'll have to deal with it for at least a few years. Now I bet the name_mangling mechanism is applied in such a way that implementing your expectations would be rather impractical or add way to much overhead. Specially when almost no one ever seem to find a use for this "feature". As far as I'm concerned, I think I didn't used it more half a dozen times, for some very deep implementation detail of some miniframework, and mostly because I'm a bit on the paranoid side. > >> Also and FWIW, the naming convention for "implementation attributes" is >> a single leading underscore > > sorry but i don't agree on this. So you disagree with the established convention followed by (wild guess) about 99.99% of the regulars here and applied in most of the existing python code base. > the two underscore (__) are used in > classes level for defining private method in the python way, The __names are used to invoke name mangling on the attribute (whatever type it is). It doesn't make it "private" - just a bit less subject to accidental override. And - I have ton insist on this - it applies to every attribute. FWIW, Python's "methods" are really not what you may think they are !-) > and the > one underscore (_) is used in the module level : ... to avoid export such named symbols in the case of a wildcard import AND if the module didn't defined an __ALL__ attribute. The _names are used to denote implementation attribute - IOW, don't touch unless you're ready to pay the price. > """Prepending a single underscore (_) has some support for protecting > module variables and functions (not included with import * from). > Prepending a double underscore (__) to an instance variable or method > effectively serves to make the variable or method private to its class > (using name mangling). """ > src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html This is at best badly formulated and really needs a rewrite. From cde3 at live.com Tue May 18 11:29:41 2010 From: cde3 at live.com (Sandy Ydnas) Date: Tue, 18 May 2010 20:29:41 +0500 Subject: Multi-Threading in Python In-Reply-To: <1274193911.4085.13.camel@linux-yu4c.site> References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com>, <1274193911.4085.13.camel@linux-yu4c.site> Message-ID: great can help to find some examples of multiprocessing Sandy > Subject: Re: Multi-Threading in Python > From: awilliam at whitemice.org > To: python-list at python.org > Date: Tue, 18 May 2010 10:45:11 -0400 > > On Tue, 2010-05-18 at 07:35 -0700, Lou wrote: > > Can anyone tell me how easy it is to do multi-threading in Python? > > Very easy. Or as easy as in any other platform - and as easy to screw > up. Personally I prefer to use multiprocessing [which is a module that > 'simulates' threads using separate processes]. IMO, it is hard to screw > up as you don't get any shared-state for free. > > > This has probably been brought up already, so if it has, thanks anyway > > -- > Adam Tauno Williams LPIC-1, Novell CLA > > OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba > > -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Hotmail: Free, trusted and rich email service. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From switch2mathan at gmail.com Tue May 18 11:41:29 2010 From: switch2mathan at gmail.com (MathanK) Date: Tue, 18 May 2010 03:41:29 -1200 Subject: Getting System error with PyModule_AddIntConstant funtion Message-ID: <128ac13aa89.1830538159355529885.-4186638668702438058@gmail.com> Following is a Python C api which runs properly without PyModule_AddIntConstant function. But when PyModule_AddIntConstant() function is used, getting the following error when i call c. path("test call"); " SystemError: NULL result without error in PyObject_Call " Python C api- c.c int test(int a){ return (2*a+a); } PyObject* dict = NULL; static PyObject* path(PyObject* self, PyObject* args) { char *cpath; PyUnicodeObject *path; PyUnicodeObject *test; if (!PyArg_ParseTuple(args, "s", &path)) return NULL; cpath = (char *)path; test = (PyUnicodeObject*)(cpath); PyObject *testDict = PyDict_New(); int testVal = PyDict_SetItem(testDict, (PyObject *)PyUnicode_FromString(cpath), (PyObject *)PyUnicode_FromString(cpath)); return Py_BuildValue("s", test); } static PyObject* c(PyObject* self, PyObject* args) { int a; int result; if(!PyArg_ParseTuple(args, "i", &a)) return NULL; result = test(a); return Py_BuildValue("i", result); } static PyMethodDef cmethods[] = { {"c", c, METH_VARARGS, "watch"}, {"path", path, METH_VARARGS, "test"}, {NULL, NULL, 0, NULL}, }; static struct PyModuleDef c_Module = { PyModuleDef_HEAD_INIT, "c", ( "Interface." ), -1, cmethods }; PyMODINIT_FUNC PyInit_c(void) { PyObject* obj = PyModule_Create(&c_Module); long lon1 = 0; PyModule_AddIntConstant(obj, "test", lon1); } int main(int argc, wchar_t *argv[]) { PyImport_AppendInittab("c", PyInit_c); Py_SetProgramName(argv[0]); Py_Initialize(); PyImport_ImportModule("c"); return 0; } -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Tue May 18 11:50:46 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 18 May 2010 11:50:46 -0400 Subject: Getting System error with PyModule_AddIntConstant funtion In-Reply-To: <128ac13aa89.1830538159355529885.-4186638668702438058@gmail.com> References: <128ac13aa89.1830538159355529885.-4186638668702438058@gmail.com> Message-ID: <84A0B79D-BE5B-482A-A100-4E0B6EEF457F@semanchuk.com> On May 18, 2010, at 11:41 AM, MathanK wrote: > Following is a Python C api which runs properly without > PyModule_AddIntConstant function. > > > But when PyModule_AddIntConstant() function is used, getting the > following error when i call > c. path("test call"); > " SystemError: NULL result without error in PyObject_Call " Hi Mathan, You're not checking the return code from PyModule_Create(). Is it returning NULL? Also, there's a list specific to Python's C API. You might get a better response to your question there: http://mail.python.org/mailman/listinfo/capi-sig bye Philip > > > Python C api- c.c > > > int test(int a){ > return (2*a+a); > } > > > PyObject* dict = NULL; > > > static PyObject* path(PyObject* self, PyObject* args) { > char *cpath; > PyUnicodeObject *path; > PyUnicodeObject *test; > > > if (!PyArg_ParseTuple(args, "s", &path)) > return NULL; > cpath = (char *)path; > test = (PyUnicodeObject*)(cpath); > PyObject *testDict = PyDict_New(); > int testVal = PyDict_SetItem(testDict, (PyObject > *)PyUnicode_FromString(cpath), (PyObject > *)PyUnicode_FromString(cpath)); > > return Py_BuildValue("s", test); > } > static PyObject* c(PyObject* self, PyObject* args) { > > int a; > int result; > if(!PyArg_ParseTuple(args, "i", &a)) > return NULL; > result = test(a); > return Py_BuildValue("i", result); > > } > > > static PyMethodDef cmethods[] = { > {"c", c, METH_VARARGS, "watch"}, > {"path", path, METH_VARARGS, "test"}, > {NULL, NULL, 0, NULL}, > }; > > > static struct PyModuleDef c_Module = { > PyModuleDef_HEAD_INIT, > "c", > ( > "Interface." > ), > -1, > cmethods > }; > > > PyMODINIT_FUNC PyInit_c(void) { > > PyObject* obj = PyModule_Create(&c_Module); > long lon1 = 0; > PyModule_AddIntConstant(obj, "test", lon1); > > } > > > int main(int argc, wchar_t *argv[]) > { > PyImport_AppendInittab("c", PyInit_c); > Py_SetProgramName(argv[0]); > Py_Initialize(); > PyImport_ImportModule("c"); > return 0; > } > -- > http://mail.python.org/mailman/listinfo/python-list From robert.kern at gmail.com Tue May 18 12:03:53 2010 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 18 May 2010 11:03:53 -0500 Subject: Picking a license In-Reply-To: <216371.45903.qm@web58703.mail.re1.yahoo.com> References: <216371.45903.qm@web58703.mail.re1.yahoo.com> Message-ID: On 2010-05-16 09:25 , Ed Keith wrote: > > --- On Sat, 5/15/10, Lawrence D'Oliveiro wrote: > >> From: Lawrence D'Oliveiro >> Subject: Re: Picking a license >> To: python-list at python.org >> Date: Saturday, May 15, 2010, 11:09 PM >> In message, >> Ed Keith >> wrote: >> >>> But if my client give someone else a copy of the >> binary I gave them, they >>> are now in violation. >> >> Why would they be in violation? It seems to me a violation >> would only occur >> if someone asked them for the source, and they refused. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > No, the GPL makes it clear that the responsibly is on the distributor to either supply the source or written notice, Caveat venditor. The violation exists regardless of whether or not the recipient makes a request. No, one of the options for you is that you make the source available upon request. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From tjreedy at udel.edu Tue May 18 12:03:55 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 12:03:55 -0400 Subject: getting attributes and methods of class without creating object In-Reply-To: <84f6e33a-05da-4f3e-9d9f-532d7ce72d10@q13g2000vbm.googlegroups.com> References: <50a7abf5-bbe7-4c2d-af53-209be5822a6a@q13g2000vbm.googlegroups.com> <25494d5d-19cd-43f2-8483-07bcdfa71a27@e28g2000vbd.googlegroups.com> <84f6e33a-05da-4f3e-9d9f-532d7ce72d10@q13g2000vbm.googlegroups.com> Message-ID: On 5/18/2010 2:11 AM, shuvro wrote: >> to know the attributes of an instance of a class without >> actually creating that instance is very difficult. > Is it not possible with the existing python facilities (without adding > external libraries) ? To know what a function would do if you were to call it, without actually calling it, look at the function code with the dis (assembler) module. #3.1 >>> import dis >>> class C: def __init__(self, a): self.a = a >>> dis.dis(C.__init__) 2 0 LOAD_FAST 1 (a) 3 LOAD_FAST 0 (self) 6 STORE_ATTR 0 (a) 9 LOAD_CONST 0 (None) 12 RETURN_VALUE If you read the doc, or know assembler, you would see that the instance gets attribute a. Use dir(C) to find all the methods to disassemble. Terry Jan Reedy From bluesmanu at gmail.com Tue May 18 12:05:50 2010 From: bluesmanu at gmail.com (bluesmanu) Date: Tue, 18 May 2010 09:05:50 -0700 (PDT) Subject: Discover PyH Message-ID: Hi all, I would like to present my first python library : PyH. PyH is a concise and powerful module that lets you build your HTML pages like a GUI. Tags are objects that can be created, included and modified at any time during your script. Discover it at http://pyh.googlecode.com . You can file bug reports and feature requests at https://launchpad.net/pyh . Cheers, Emmanuel Turlay From debatem1 at gmail.com Tue May 18 12:07:31 2010 From: debatem1 at gmail.com (geremy condra) Date: Tue, 18 May 2010 09:07:31 -0700 Subject: Multi-Threading in Python In-Reply-To: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> Message-ID: On Tue, May 18, 2010 at 7:35 AM, Lou wrote: > Can anyone tell me how easy it is to do multi-threading in Python? > This has probably been brought up already, so if it has, thanks anyway > -- > http://mail.python.org/mailman/listinfo/python-list It's very easy, but it's probably best to use multiple processes to take advantage of multiple cores. Take a look at the threading and multiprocessing modules. Geremy Condra From tjreedy at udel.edu Tue May 18 12:11:57 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 12:11:57 -0400 Subject: Is there conversion method to convert pyunicodeobject to pybyteobject? In-Reply-To: <1289c71c8d7.-2177546074900212455.7511215933185914503@gmail.com> References: <1289c71c8d7.-2177546074900212455.7511215933185914503@gmail.com> Message-ID: On 5/15/2010 10:50 AM, MathanK wrote: This is the third time, at least, that you posted this, though the first time you asked a question. You have given no indication that you bothered to look in the manual before or between postings. > A variable whose data type is PyUnicodeObject is to be assigned to > varioable of PyBytesObject type > > example : > > PyUnicodeObject *p = ...whatever...; > function( (PyByteObject*p)); C casting is usually not conversion. It says "pretend that the data is another type, even though it is not." Only use it when you actually know what you are doing. > compiled and got a Bus Error. In Python, b = p.encode('utf-8') or whatever encoding you want. Look in the C-API manual for the CPython function that actually does this. From tjreedy at udel.edu Tue May 18 12:22:58 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 12:22:58 -0400 Subject: max time wait for a function In-Reply-To: <1274178263.232897.38.camel@paska> References: <4418c1f3-564f-48c1-85e3-48d5678a4f38@y21g2000vba.googlegroups.com> <1274178263.232897.38.camel@paska> Message-ID: On 5/18/2010 6:24 AM, Albert Hopkins wrote: > On Tue, 2010-05-18 at 02:45 -0700, pacopyc wrote: >> Hi, I've a question for you. I'd like to call a function and waiting >> its return value for a time max (30 sec). >> The function could not respond and then I must avoid to wait for >> infinite time. OS is Windows XP. >> Can you help me? >> >> Thank > > This is how I do it with a function decorator. I probably borrowed this > from someone and not attributed it. Anyway, it works on Linux, not sure > about Windows: > > def function_timeout(seconds): > """Function decorator to raise a timeout on a function call""" > import signal > class FunctionTimeOut(Exception): > pass > > def decorate(f): > def timeout(signum, frame): > raise FunctionTimeOut() > > def funct(*args, **kwargs): > old = signal.signal(signal.SIGALRM, timeout) > signal.alarm(seconds) from help(signal): alarm() -- cause SIGALRM after a specified time [Unix only] I do not know of any replacement in the stdlib, but one could check the code for multiprocessing to see how it does a timeout. Or check the pywin32 library http://pypi.python.org/pypi/pywin32/210 > try: > result = f(*args, **kwargs) > finally: > signal.signal(signal.SIGALRM, old) > signal.alarm(0) > return result > > return funct > > return decorate > > From tjreedy at udel.edu Tue May 18 12:25:38 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 12:25:38 -0400 Subject: Multi-Threading in Python In-Reply-To: References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com>, <1274193911.4085.13.camel@linux-yu4c.site> Message-ID: On 5/18/2010 11:29 AM, Sandy Ydnas wrote: > can help to find some examples of multiprocessing Multiprocessing is designed to be api-compatible with threading. Search the archives of this list/newsgroup for several examples. From awilliam at whitemice.org Tue May 18 12:45:37 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 18 May 2010 12:45:37 -0400 Subject: Multi-Threading in Python In-Reply-To: References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com> ,<1274193911.4085.13.camel@linux-yu4c.site> Message-ID: <1274201137.7652.3.camel@linux-yu4c.site> On Tue, 2010-05-18 at 20:29 +0500, Sandy Ydnas wrote: > great > can help to find some examples of multiprocessing There is the reasonably good documentation at: I did a Multiprocessing presentation recently: And I use multiprocessing in my project; but less than previously as I now use AMQ for the IPC and multiprocessing only for the process management. But an entire project is quite a bit to pick through. > > Subject: Re: Multi-Threading in Python > > From: awilliam at whitemice.org > > To: python-list at python.org > > Date: Tue, 18 May 2010 10:45:11 -0400 > > > > On Tue, 2010-05-18 at 07:35 -0700, Lou wrote: > > > Can anyone tell me how easy it is to do multi-threading in Python? > > > > Very easy. Or as easy as in any other platform - and as easy to > screw > > up. Personally I prefer to use multiprocessing [which is a module > that > > 'simulates' threads using separate processes]. IMO, it is hard to > screw > > up as you don't get any shared-state for free. > > > > > This has probably been brought up already, so if it has, thanks > anyway > > > > -- > > Adam Tauno Williams LPIC-1, Novell CLA > > > > OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > ______________________________________________________________________ > Hotmail: Free, trusted and rich email service. Get it now. From e_d_k at yahoo.com Tue May 18 12:45:41 2010 From: e_d_k at yahoo.com (Ed Keith) Date: Tue, 18 May 2010 09:45:41 -0700 (PDT) Subject: Picking a license In-Reply-To: Message-ID: <993000.4063.qm@web58707.mail.re1.yahoo.com> --- On Tue, 5/18/10, Robert Kern wrote: > From: Robert Kern > Subject: Re: Picking a license > To: python-list at python.org > Date: Tuesday, May 18, 2010, 12:03 PM > On 2010-05-16 09:25 , Ed Keith > wrote: > > > > --- On Sat, 5/15/10, Lawrence D'Oliveiro? > wrote: > > > >> From: Lawrence D'Oliveiro > >> Subject: Re: Picking a license > >> To: python-list at python.org > >> Date: Saturday, May 15, 2010, 11:09 PM > >> In message, > >> Ed Keith > >> wrote: > >> > >>> But if my client give someone else a copy of > the > >> binary I gave them, they > >>> are now in violation. > >> > >> Why would they be in violation? It seems to me a > violation > >> would only occur > >> if someone asked them for the source, and they > refused. > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > > > > No, the GPL makes it clear that the responsibly is on > the distributor to either supply the source or written > notice, Caveat venditor. The violation exists regardless of > whether or not the recipient makes a request. > > No, one of the options for you is that you make the source > available upon request. > But I am required to give written notice to that effect. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From cde3 at live.com Tue May 18 13:06:01 2010 From: cde3 at live.com (Sandy Ydnas) Date: Tue, 18 May 2010 22:06:01 +0500 Subject: Multi-Threading in Python In-Reply-To: <1274201137.7652.3.camel@linux-yu4c.site> References: <356dd76c-0e61-4b0e-aaaf-2de11ad52e9d@s4g2000prh.googlegroups.com>, , <1274193911.4085.13.camel@linux-yu4c.site>, , <1274201137.7652.3.camel@linux-yu4c.site> Message-ID: good thanks a lot Sandy > Subject: RE: Multi-Threading in Python > From: awilliam at whitemice.org > To: python-list at python.org > Date: Tue, 18 May 2010 12:45:37 -0400 > > On Tue, 2010-05-18 at 20:29 +0500, Sandy Ydnas wrote: > > great > > can help to find some examples of multiprocessing > > There is the reasonably good documentation at: > > > I did a Multiprocessing presentation recently: > > > And I use multiprocessing in my project; but less than previously as I > now use AMQ for the IPC and multiprocessing only for the process > management. > > But an entire project is quite a bit to pick through. > > > > Subject: Re: Multi-Threading in Python > > > From: awilliam at whitemice.org > > > To: python-list at python.org > > > Date: Tue, 18 May 2010 10:45:11 -0400 > > > > > > On Tue, 2010-05-18 at 07:35 -0700, Lou wrote: > > > > Can anyone tell me how easy it is to do multi-threading in Python? > > > > > > Very easy. Or as easy as in any other platform - and as easy to > > screw > > > up. Personally I prefer to use multiprocessing [which is a module > > that > > > 'simulates' threads using separate processes]. IMO, it is hard to > > screw > > > up as you don't get any shared-state for free. > > > > > > > This has probably been brought up already, so if it has, thanks > > anyway > > > > > > -- > > > Adam Tauno Williams LPIC-1, Novell CLA > > > > > > OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > ______________________________________________________________________ > > Hotmail: Free, trusted and rich email service. Get it now. > > > -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Hotmail: Trusted email with powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue May 18 13:07:00 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 13:07:00 -0400 Subject: pickle unable to load collection In-Reply-To: References: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com> Message-ID: On 5/18/2010 3:10 AM, Peter Otten wrote: > Now simulate the effect of writing in text mode and reading in binary mode: > >>>> >>> garbled_data = data.replace("\n", "\r\n") >>>> >>> pickle.loads(garbled_data) > Traceback (most recent call last): ... > ImportError: No module named collections > >>>> >>> try: pickle.loads(garbled_data) > ... except ImportError as e: > ... e > ... > ImportError('No module named collections\r',) Nice catch, Peter. I filed a request that the message quote the name it cannot import, so that the OP would have seen the more informative ImportError: No module named 'collections\r' http://bugs.python.org/issue8754 Terry Jan Reedy From tjreedy at udel.edu Tue May 18 13:11:42 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 13:11:42 -0400 Subject: Regular expression In-Reply-To: <1274193656.13989.10.camel@jcdyer-laptop> References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> <1274193656.13989.10.camel@jcdyer-laptop> Message-ID: On 5/18/2010 10:40 AM, J. Cliff Dyer wrote: > Don't use regular expressions for that. > > s = '0x340x5A0x9B0xBA' > return '0x' + ''.join(s.split('0x')) or >>> '0x'+s[2:].replace('0x','') '0x345A9BBA' Take your pick, you should learn and understand both. > On Tue, 2010-05-18 at 06:48 -0700, Back9 wrote: >> Hi, >> >> I have a string like this: >> 0x340x5A0x9B0xBA >> I want to extract 0x from the string but the first one. >> >> How I can use re for this case? >> >> The string size will vary. >> >> TIA >> > > From pmaupin at gmail.com Tue May 18 13:22:30 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Tue, 18 May 2010 10:22:30 -0700 (PDT) Subject: Picking a license References: <216371.45903.qm@web58703.mail.re1.yahoo.com> Message-ID: On May 18, 11:03?am, Robert Kern wrote: > On 2010-05-16 09:25 , Ed Keith wrote: > > No, the GPL makes it clear that the responsibly is on the distributor to either supply the source or written notice, Caveat venditor. The violation exists regardless of whether or not the recipient makes a request. > > No, one of the options for you is that you make the source available upon request. Do you have a citation for that? My reading, of both GPL v2 section 3 and GPL v3 section 6, is that someone distributing GPL licensed object must do one of the following: - supply the source with the object - supply a written offer for source with the object - supply a copy of someone else's written offer for source with the object (only allowed sometimes) - Perhaps verbally communicate an offer (GPL v2 only, very liberal reading of 3c, but even then the communication must "accompany" the object distribution). - supply object by "offering access from a designated place" as long as you "offer equivalent access to the Corresponding Source in the same way through the same place" or "you maintain clear directions next to the object code saying where to find the Corresponding Source". That last one effectively has "written offer" defined in a slightly different way ("maintain clear directions"), and also might allow you to just have a pile of source DVDs adjacent to a pile of object CDs with no explicit written offer, but I honestly can't see how even that can be stretched to cover just handing somebody an object CD without even mentioning that source is available, and then only later giving them source if they explicitly ask for it. Sure, if you give somebody source after they ask for it, you have probably "cured" any violation, but I think the very act of handing someone an object CD without source or a written offer of source would put you in violation of the license at the time you give them the object CD. It may be that saying "oh, by the way, source code's available if you want it" would suffice in some cases under GPL v2, but it doesn't look like that would work at all for GPL v3. Regards, Pat From switch2mathan at gmail.com Tue May 18 13:31:06 2010 From: switch2mathan at gmail.com (MathanK) Date: Tue, 18 May 2010 05:31:06 -1200 Subject: Getting System error with PyModule_AddIntConstant funtion Message-ID: <128ac78068e.753885165126954409.7078058063089783964@gmail.com> I checked for Null also. But No change in the result. Still getting the system error. But when i m calling only c.c(5) function and not calling c.path("hi python c api") function, i m getting proper output without any system error. Any clue? Subject: Re: Getting System error with PyModule_AddIntConstant funtion From: Philip Semanchuk <philip at semanchuk.com> Date: Tue, 18 May 2010 11:50:46 -0400 To: "python-list (General)" <python-list at python.org> ------------------------- Contents ------------------------- On May 18, 2010, at 11:41 AM, MathanK wrote: > Following is a Python C api which runs properly without > PyModule_AddIntConstant function. > > > But when PyModule_AddIntConstant() function is used, getting the > following error when i call > c. path("test call"); > " SystemError: NULL result without error in PyObject_Call " Hi Mathan, You're not checking the return code from PyModule_Create(). Is it returning NULL? Also, there's a list specific to Python's C API. You might get a better response to your question there: http://mail.python.org/mailman/listinfo/capi-sig bye Philip > > > Python C api- c.c > > > int test(int a){ > return (2*a+a); > } > > > PyObject* dict = NULL; > > > static PyObject* path(PyObject* self, PyObject* args) { > char *cpath; > PyUnicodeObject *path; > PyUnicodeObject *test; > > > if (!PyArg_ParseTuple(args, "s", &amp;path)) > return NULL; > cpath = (char *)path; > test = (PyUnicodeObject*)(cpath); > PyObject *testDict = PyDict_New(); > int testVal = PyDict_SetItem(testDict, (PyObject > *)PyUnicode_FromString(cpath), (PyObject > *)PyUnicode_FromString(cpath)); > > return Py_BuildValue("s", test); > } > static PyObject* c(PyObject* self, PyObject* args) { > > int a; > int result; > if(!PyArg_ParseTuple(args, "i", &amp;a)) > return NULL; > result = test(a); > return Py_BuildValue("i", result); > > } > > > static PyMethodDef cmethods[] = { > {"c", c, METH_VARARGS, "watch"}, > {"path", path, METH_VARARGS, "test"}, > {NULL, NULL, 0, NULL}, > }; > > > static struct PyModuleDef c_Module = { > PyModuleDef_HEAD_INIT, > "c", > ( > "Interface." > ), > -1, > cmethods > }; > > > PyMODINIT_FUNC PyInit_c(void) { > > PyObject* obj = PyModule_Create(&amp;c_Module); > long lon1 = 0; > PyModule_AddIntConstant(obj, "test", lon1); > > } > > > int main(int argc, wchar_t *argv[]) > { > PyImport_AppendInittab("c", PyInit_c); > Py_SetProgramName(argv[0]); > Py_Initialize(); > PyImport_ImportModule("c"); > return 0; > } -------------- next part -------------- An HTML attachment was scrubbed... URL: From utente at esempio.net Tue May 18 13:31:42 2010 From: utente at esempio.net (superpollo) Date: Tue, 18 May 2010 19:31:42 +0200 Subject: recall function definition from shell Message-ID: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> >>> def myfun(): ... return "WOW" ... >>> myfun() 'WOW' >>> now, i would like to "list" the funcion definition, something like this: >>> myfun.somethinglikethis() def myfun(): return "WOW" >>> is there something like this around? bye From fasteliteprogrammer at gmail.com Tue May 18 14:18:49 2010 From: fasteliteprogrammer at gmail.com (packet) Date: Tue, 18 May 2010 13:18:49 -0500 Subject: upgrade python Message-ID: <4BF2DA09.7090208@gmail.com> Would it be safe to upgrade from python 2.6.4 to 2.6.5 without hurting the 2.6.4? From pmaupin at gmail.com Tue May 18 14:32:40 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Tue, 18 May 2010 11:32:40 -0700 (PDT) Subject: recall function definition from shell References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> Message-ID: <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> On May 18, 12:31?pm, superpollo wrote: > ?>>> def myfun(): > ... ? ? return "WOW" > ... > ?>>> myfun() > 'WOW' > ?>>> > > now, i would like to "list" the funcion definition, something like this: > > ?>>> myfun.somethinglikethis() > def myfun(): > ? ? ?return "WOW" > ?>>> > > is there something like this around? > > bye Sure, just give it a docstring and then you can call help on it: >>> def myfun(): ... ''' myfun returns "WOW" when called. ... This is just a Python __doc__ string ... ''' ... return "WOW" ... >>> help(myfun) Regards, Pat From utente at esempio.net Tue May 18 14:41:50 2010 From: utente at esempio.net (superpollo) Date: Tue, 18 May 2010 20:41:50 +0200 Subject: recall function definition from shell In-Reply-To: <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> Message-ID: <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> Patrick Maupin ha scritto: > On May 18, 12:31 pm, superpollo wrote: >> >>> def myfun(): >> ... return "WOW" >> ... >> >>> myfun() >> 'WOW' >> >>> >> >> now, i would like to "list" the funcion definition, something like this: >> >> >>> myfun.somethinglikethis() >> def myfun(): >> return "WOW" >> >>> >> >> is there something like this around? >> >> bye > > Sure, just give it a docstring and then you can call help on it: > >>>> def myfun(): > ... ''' myfun returns "WOW" when called. > ... This is just a Python __doc__ string > ... ''' > ... return "WOW" > ... >>>> help(myfun) > > Regards, > Pat mmm... thanks but not quite what i meant :-( bye From pmaupin at gmail.com Tue May 18 14:50:32 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Tue, 18 May 2010 11:50:32 -0700 (PDT) Subject: recall function definition from shell References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> Message-ID: <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> On May 18, 1:41?pm, superpollo wrote: > Patrick Maupin ha scritto: > > > > > On May 18, 12:31 pm, superpollo wrote: > >> ?>>> def myfun(): > >> ... ? ? return "WOW" > >> ... > >> ?>>> myfun() > >> 'WOW' > > >> now, i would like to "list" the funcion definition, something like this: > > >> ?>>> myfun.somethinglikethis() > >> def myfun(): > >> ? ? ?return "WOW" > > >> is there something like this around? > > >> bye > > > Sure, just give it a docstring and then you can call help on it: > > >>>> def myfun(): > > ... ? ? ''' myfun returns "WOW" when called. > > ... ? ? ? ? This is just a Python __doc__ string > > ... ? ? ''' > > ... ? ? return "WOW" > > ... > >>>> help(myfun) > > > Regards, > > Pat > > mmm... thanks but not quite what i meant :-( > > bye Well, I don't think Python remembers exactly how you typed it in, but you can always ask Python for what it remembers about the function: >>> def myfun(): ... return "WOW" ... >>> import dis >>> dis.dis(myfun) 2 0 LOAD_CONST 1 ('WOW') 3 RETURN_VALUE The inspect module is useful, as well. But AFAIK Python doesn't "remember" the source code for stuff you typed in. (For functions in imported modules, there is sufficient information remembered for tracebacks to allow you to print out the lines of a function.) Regards, Pat From utente at esempio.net Tue May 18 14:55:17 2010 From: utente at esempio.net (superpollo) Date: Tue, 18 May 2010 20:55:17 +0200 Subject: recall function definition from shell In-Reply-To: <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> Message-ID: <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Patrick Maupin ha scritto: > On May 18, 1:41 pm, superpollo wrote: >> Patrick Maupin ha scritto: >> >> >> >>> On May 18, 12:31 pm, superpollo wrote: >>>> >>> def myfun(): >>>> ... return "WOW" >>>> ... >>>> >>> myfun() >>>> 'WOW' >>>> now, i would like to "list" the funcion definition, something like this: >>>> >>> myfun.somethinglikethis() >>>> def myfun(): >>>> return "WOW" >>>> is there something like this around? >>>> bye >>> Sure, just give it a docstring and then you can call help on it: >>>>>> def myfun(): >>> ... ''' myfun returns "WOW" when called. >>> ... This is just a Python __doc__ string >>> ... ''' >>> ... return "WOW" >>> ... >>>>>> help(myfun) >>> Regards, >>> Pat >> mmm... thanks but not quite what i meant :-( >> >> bye > > Well, I don't think Python remembers exactly how you typed it in yes python does not, but maybe the *shell* does, or so i thought. i just wanted to dump the code for the function in a file, after i tested in the shell... From __peter__ at web.de Tue May 18 15:08:33 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 May 2010 21:08:33 +0200 Subject: recall function definition from shell References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Message-ID: superpollo wrote: > Patrick Maupin ha scritto: >> On May 18, 1:41 pm, superpollo wrote: >>> Patrick Maupin ha scritto: >>> >>> >>> >>>> On May 18, 12:31 pm, superpollo wrote: >>>>> >>> def myfun(): >>>>> ... return "WOW" >>>>> ... >>>>> >>> myfun() >>>>> 'WOW' >>>>> now, i would like to "list" the funcion definition, something like >>>>> this: >>>>> >>> myfun.somethinglikethis() >>>>> def myfun(): >>>>> return "WOW" >>>>> is there something like this around? >>>>> bye >>>> Sure, just give it a docstring and then you can call help on it: >>>>>>> def myfun(): >>>> ... ''' myfun returns "WOW" when called. >>>> ... This is just a Python __doc__ string >>>> ... ''' >>>> ... return "WOW" >>>> ... >>>>>>> help(myfun) >>>> Regards, >>>> Pat >>> mmm... thanks but not quite what i meant :-( >>> >>> bye >> >> Well, I don't think Python remembers exactly how you typed it in > > yes python does not, but maybe the *shell* does, or so i thought. i just > wanted to dump the code for the function in a file, after i tested in > the shell... You could try ipython: $ ipython Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: def f(): ...: return 42 ...: In [2]: f() Out[2]: 42 In [3]: %save tmp.py 1 The following commands were written to file `tmp.py`: def f(): return 42 In [4]: Do you really want to exit ([y]/n)? $ cat tmp.py def f(): return 42 $ Peter From __peter__ at web.de Tue May 18 15:12:05 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 May 2010 21:12:05 +0200 Subject: pickle unable to load collection References: <1a55e954-d295-4a94-bc8f-1df7e8e72a18@a2g2000prd.googlegroups.com> Message-ID: Terry Reedy wrote: > Nice catch, Peter. I filed a request that the message quote the name it > cannot import, so that the OP would have seen the more informative > > ImportError: No module named 'collections\r' > > http://bugs.python.org/issue8754 Good idea; thank you for taking the initiative. Peter From utente at esempio.net Tue May 18 15:13:50 2010 From: utente at esempio.net (superpollo) Date: Tue, 18 May 2010 21:13:50 +0200 Subject: recall function definition from shell In-Reply-To: References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Message-ID: <4bf2e6ef$0$18992$4fafbaef@reader5.news.tin.it> Peter Otten ha scritto: > superpollo wrote: > >> Patrick Maupin ha scritto: >>> On May 18, 1:41 pm, superpollo wrote: >>>> Patrick Maupin ha scritto: >>>> >>>> >>>> >>>>> On May 18, 12:31 pm, superpollo wrote: >>>>>> >>> def myfun(): >>>>>> ... return "WOW" >>>>>> ... >>>>>> >>> myfun() >>>>>> 'WOW' >>>>>> now, i would like to "list" the funcion definition, something like >>>>>> this: >>>>>> >>> myfun.somethinglikethis() >>>>>> def myfun(): >>>>>> return "WOW" >>>>>> is there something like this around? >>>>>> bye >>>>> Sure, just give it a docstring and then you can call help on it: >>>>>>>> def myfun(): >>>>> ... ''' myfun returns "WOW" when called. >>>>> ... This is just a Python __doc__ string >>>>> ... ''' >>>>> ... return "WOW" >>>>> ... >>>>>>>> help(myfun) >>>>> Regards, >>>>> Pat >>>> mmm... thanks but not quite what i meant :-( >>>> >>>> bye >>> Well, I don't think Python remembers exactly how you typed it in >> yes python does not, but maybe the *shell* does, or so i thought. i just >> wanted to dump the code for the function in a file, after i tested in >> the shell... > > You could try ipython: > > $ ipython > Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) > Type "copyright", "credits" or "license" for more information. > > IPython 0.10 -- An enhanced Interactive Python. > ? -> Introduction and overview of IPython's features. > %quickref -> Quick reference. > help -> Python's own help system. > object? -> Details about 'object'. ?object also works, ?? prints more. > > In [1]: def f(): > ...: return 42 > ...: > > In [2]: f() > Out[2]: 42 > > In [3]: %save tmp.py 1 > The following commands were written to file `tmp.py`: > def f(): > return 42 > > > In [4]: > Do you really want to exit ([y]/n)? > $ cat tmp.py > def f(): > return 42 > $ > > Peter hey great! thanks a lot! best regards From lists at necoro.eu Tue May 18 15:21:18 2010 From: lists at necoro.eu (=?UTF-8?B?UmVuw6kgJ05lY29ybycgTmV1bWFubg==?=) Date: Tue, 18 May 2010 21:21:18 +0200 Subject: recall function definition from shell In-Reply-To: <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Message-ID: <4BF2E8AE.2020208@necoro.eu> Am 18.05.2010 20:55, schrieb superpollo: > > yes python does not, but maybe the *shell* does, or so i thought. i just > wanted to dump the code for the function in a file, after i tested in > the shell... You might want to have a look at the IPython shell [1]. I personally do not use it myself, but I thought to remember that it had some feature like this (perhaps not dump _one function_, but all the input, which you then only need to cleanup). A quick glance revealed f.ex. the history and edit functionality [2] -- a bit more digging might really show up the thing you are looking for. - Ren? [1] http://ipython.scipy.org/ [2] http://ipython.scipy.org/doc/manual/html/interactive/tutorial.html#source-code-handling-tips -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From ethan at stoneleaf.us Tue May 18 15:26:47 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 12:26:47 -0700 Subject: recall function definition from shell In-Reply-To: <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Message-ID: <4BF2E9F7.6040806@stoneleaf.us> superpollo wrote: > Patrick Maupin ha scritto: >> On May 18, 1:41 pm, superpollo wrote: >>> Patrick Maupin ha scritto: >>> >>> >>> >>>> On May 18, 12:31 pm, superpollo wrote: >>>>> >>> def myfun(): >>>>> ... return "WOW" >>>>> ... >>>>> >>> myfun() >>>>> 'WOW' >>>>> now, i would like to "list" the funcion definition, something like >>>>> this: >>>>> >>> myfun.somethinglikethis() >>>>> def myfun(): >>>>> return "WOW" >>>>> is there something like this around? >>>>> bye >>>> Sure, just give it a docstring and then you can call help on it: >>>>>>> def myfun(): >>>> ... ''' myfun returns "WOW" when called. >>>> ... This is just a Python __doc__ string >>>> ... ''' >>>> ... return "WOW" >>>> ... >>>>>>> help(myfun) >>>> Regards, >>>> Pat >>> mmm... thanks but not quite what i meant :-( >>> >>> bye >> >> Well, I don't think Python remembers exactly how you typed it in > > yes python does not, but maybe the *shell* does, or so i thought. i just > wanted to dump the code for the function in a file, after i tested in > the shell... Take a look at ipython -- it has many enhancements: ipython.scipy.org ~Ethan~ From ethan at stoneleaf.us Tue May 18 15:28:25 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 12:28:25 -0700 Subject: Picking a license In-Reply-To: <87fx1qji9t.fsf@benfinney.id.au> References: <87r5ldbw3k.fsf@benfinney.id.au> <87fx1qji9t.fsf@benfinney.id.au> Message-ID: <4BF2EA59.6090209@stoneleaf.us> Ben Finney wrote: > aahz at pythoncraft.com (Aahz) writes: > >> Ben Finney wrote: >>> [It is impractical to] sell free software like selling loaves of >>> bread, but that's a much more limited case and a far cry from your >>> claim [that it's impractical to sell free software]. Selling free >>> software is quite practical and a good way to fund development of >>> software that otherwise wouldn't be written as free software. >> From my POV, if you're not selling COTS, you're really selling support >> and consulting services, because that's what keeps your competitors >> from just picking up your software and reselling it for cheaper. BTDT. > > This thread has revealed some staggering gulfs in concepts as held by > different people. For example, I don't think it's at all germane to the > definition of ?sell FOO? that ?your competitors can pick up the FOO and > resell it cheaper?. Whether they can or not, that doesn't change that > fact that one is selling FOO. > > Moreover, I don't try to prevent my competitors from reselling the > software (so long as they don't misrepresent who holds copyright or > further restrict the terms). That's part and parcel of the freedoms in > the software. Indeed, I find that helps the customers trust me more and > tend to come back when they want something else new; and my customers > are free to show others the solutions I've already implemented. > > Thus is an ongoing business relationship crafted, including return > customers and referrals for new work. It really is practical to sell > free software. > This doesn't make sense to me, but I'm willing to learn -- how do you do this in practice? Are you really selling the software, or rather selling things like setup, support, new code (or time to code), etc? ~Ethan~ From grenander at gmail.com Tue May 18 16:15:13 2010 From: grenander at gmail.com (Art) Date: Tue, 18 May 2010 13:15:13 -0700 (PDT) Subject: setting variables in pdb Message-ID: <8596b692-2e9f-452d-99b0-ba55ec592936@h37g2000pra.googlegroups.com> If I am in Pdb, I would like to set a temporary variable, for example: (Pdb) r = 1 The 'r' gets interpreted as 'return' by Pdb. Is there a Pdb instruction that guarantees the intended effect, like: (Pdb) let r = 1 I can usually avoid using such variable names, but if I am changing the value of a local variable, it is convenient to be able to make sure that trying to change that variable doesn't unintentionally call a Pdb routine. Thanks, Art. From vincent at vincentdavis.net Tue May 18 16:17:57 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 14:17:57 -0600 Subject: Is this an ok thing to do in a class In-Reply-To: <4bf2a930$0$14553$426a74cc@news.free.fr> References: <4bf2a930$0$14553$426a74cc@news.free.fr> Message-ID: Thanks for the feed back Vincent On Tue, May 18, 2010 at 8:50 AM, Bruno Desthuilliers wrote: > Simon Brunning a ?crit : > >> On 18 May 2010 06:21:32 UTC+1, Vincent Davis >> wrote: >> >>> Just wondering if there is a problem with mixing a dictionary into a >>> class like this. Everything seems to work as I would expect. >>> >> >> No problem at all AFAIC. >> > > OP didn't show up on c.l.py, so too bad you snipped the relevant code > snippet... > > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjposner at optimum.net Tue May 18 16:32:15 2010 From: jjposner at optimum.net (John Posner) Date: Tue, 18 May 2010 16:32:15 -0400 Subject: setting variables in pdb In-Reply-To: <8596b692-2e9f-452d-99b0-ba55ec592936@h37g2000pra.googlegroups.com> References: <8596b692-2e9f-452d-99b0-ba55ec592936@h37g2000pra.googlegroups.com> Message-ID: <4BF2F94F.9050604@optimum.net> On 5/18/2010 4:15 PM, Art wrote: > If I am in Pdb, I would like to set a temporary variable, for example: > > (Pdb) r = 1 > > The 'r' gets interpreted as 'return' by Pdb. > > Is there a Pdb instruction that guarantees the intended effect, like: > > (Pdb) let r = 1 > > I can usually avoid using such variable names, but if I am changing > the value of a local variable, it is convenient to be able to make > sure that trying to change that variable doesn't unintentionally call > a Pdb routine. Try setting *two* values at the interactive prompt: foo, r = 0, 3456 Variable "r" now has the value 3456. HTH, John From duncan.booth at invalid.invalid Tue May 18 16:33:27 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 May 2010 20:33:27 GMT Subject: setting variables in pdb References: <8596b692-2e9f-452d-99b0-ba55ec592936@h37g2000pra.googlegroups.com> Message-ID: Art wrote: > If I am in Pdb, I would like to set a temporary variable, for example: > > (Pdb) r = 1 > > The 'r' gets interpreted as 'return' by Pdb. > > Is there a Pdb instruction that guarantees the intended effect, like: > > (Pdb) let r = 1 (Pdb) exec "r=1" From vincent at vincentdavis.net Tue May 18 16:39:13 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 14:39:13 -0600 Subject: how to cause a request for a missing class attribute cause its calculation Message-ID: Lets say I have class foo(object): def __init__(self, x, y): self.x=x self.y=y def xplusy(self): self.xy = x+y inst = foo(1,2) inst.xy # no value, but I what this to cause the calculation of inst.xy I don't what to have self.xy calculated before it is called. Thanks *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Tue May 18 16:41:59 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 13:41:59 -0700 Subject: Is this an ok thing to do in a class In-Reply-To: References: Message-ID: <4BF2FB97.6040205@stoneleaf.us> Vincent Davis wrote: > Just wondering if there is a problem with mixing a dictionary into a > class like this. Everything seems to work as I would expect. > > class foo(object): > def __init__(self, x): > self.letter = dict(a=1,b=2,c=3) > self.A=self.letter['a'] > self.x=self.letter[x] > > >>> afoo = foo('b') > >>> afoo.x > 2 > >>> afoo.A > 1 > >>> afoo.letter['a'] > 1 > >>> afoo.letter.items() > [('a', 1), ('c', 3), ('b', 2)] Do you expect afoo.letter[x] to always be afoo.x? Because they aren't: >>> afoo.A = 9 >>> afoo.letter['a'] 1 ~Ethan~ From vincent at vincentdavis.net Tue May 18 16:49:30 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 14:49:30 -0600 Subject: Is this an ok thing to do in a class In-Reply-To: <4BF2FB97.6040205@stoneleaf.us> References: <4BF2FB97.6040205@stoneleaf.us> Message-ID: On Tue, May 18, 2010 at 2:41 PM, Ethan Furman wrote: > > Do you expect afoo.letter[x] to always be afoo.x? Because they aren't: > > >>> afoo.A = 9 > >>> afoo.letter['a'] > 1 > What you are pointing out is that the assignment is not reversed . But that does make me thing of something I had not. >>> afoo.letter['a'] = 345 >>> afoo.A 1 Thats kinda a bummer, whats a good way to make sure affo.A gets updated? Vincent > > ~Ethan~ > > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue May 18 16:54:30 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 May 2010 13:54:30 -0700 Subject: how to cause a request for a missing class attribute cause its calculation In-Reply-To: References: Message-ID: On Tue, May 18, 2010 at 1:39 PM, Vincent Davis wrote: > > Lets say I have > class foo(object): > ?? ?def __init__(self, x, y): > ?? ? ? ?self.x=x > ?? ? ? ?self.y=y > ?? ?def xplusy(self): > ?? ? ? ?self.xy = x+y > inst = foo(1,2) > inst.xy ? # no value, but I what this to cause the calculation of inst.xy > I don't what to have self.xy calculated before it is called. class Foo(object): def __init__(self, x, y): self.x = x self.y = y @property def xy(self): '''Will calculate x+y every time''' return self.x + self.y Or if Foo is immutable and you wish to cache x+y: class Foo(object): def __init__(self, x, y): self.x = x self.y = y self._xy = None @property def xy(self): if self._xy is None: self._xy = self.x + self.y return self._xy Suggested reading: http://docs.python.org/library/functions.html#property Cheers, Chris -- http://blog.rebertia.com From ethan at stoneleaf.us Tue May 18 17:15:04 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 14:15:04 -0700 Subject: Is this an ok thing to do in a class In-Reply-To: References: <4BF2FB97.6040205@stoneleaf.us> Message-ID: <4BF30358.1010005@stoneleaf.us> Vincent Davis wrote: > On Tue, May 18, 2010 at 2:41 PM, Ethan Furman > wrote: > > Do you expect afoo.letter[x] to always be afoo.x? Because they aren't: > > >>> afoo.A = 9 > >>> afoo.letter['a'] > 1 > > > What you are pointing out is that the assignment is not reversed . But > that does make me thing of something I had not. > > >>> afoo.letter['a'] = 345 > >>> afoo.A > 1 > > Thats kinda a bummer, whats a good way to make sure affo.A gets updated? It's possible, and not too tough, but... why do you need it done that way? Keeping redundant information seems like extra work with no advantage. ~Ethan~ From ethan at stoneleaf.us Tue May 18 17:19:39 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 14:19:39 -0700 Subject: how to cause a request for a missing class attribute cause its calculation In-Reply-To: References: Message-ID: <4BF3046B.7060100@stoneleaf.us> Vincent Davis wrote: > Lets say I have > class foo(object): > def __init__(self, x, y): > self.x=x > self.y=y > def xplusy(self): > self.xy = x+y ^ this needs to be self.x + self.y > > inst = foo(1,2) > inst.xy # no value, but I what this to cause the calculation of inst.xy > > I don't what to have self.xy calculated before it is called. My current favorite method: def __getattr__(self, name): if name != 'xy': raise AttributeError("%s not found" % name) self.xy = self.x + self.y return self.xy ~Ethan~ From vincent at vincentdavis.net Tue May 18 17:36:49 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 15:36:49 -0600 Subject: Is this an ok thing to do in a class In-Reply-To: <4BF30358.1010005@stoneleaf.us> References: <4BF2FB97.6040205@stoneleaf.us> <4BF30358.1010005@stoneleaf.us> Message-ID: On Tue, May 18, 2010 at 3:15 PM, Ethan Furman wrote: > Vincent Davis wrote: > >> >> What you are pointing out is that the assignment is not reversed . But >> that does make me thing of something I had not. >> >> >>> afoo.letter['a'] = 345 >> >>> afoo.A >> 1 >> >> Thats kinda a bummer, whats a good way to make sure afoo.A gets updated? >> > > It's possible, and not too tough, but... why do you need it done that way? > Keeping redundant information seems like extra work with no advantage. > > Not sure I do, basicly I have a long list of values that could be calculated from data. Some may take some time depending on the amount of data. I don't what to calculate them all if not needed but I don't what the user to need to know which are and which are not. But maybe @property is what I need to be looking at, see my other post on the list. Thanks Vincent > ~Ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Tue May 18 17:51:33 2010 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 18 May 2010 17:51:33 -0400 Subject: another question about classes and subclassing Message-ID: Hi again all, More about classes. I am still looking into my battleship game, and I will have several different craft. All craft have common attribs (position, alive, and so on) but each craft may be a surface ship, submarine, or airplane. All three are craft, but a submarine can be submerged or not, which does not apply to a surface ship or a plane, while a plane can be airborne or not, which is not applicable to the other two. Is there any advantage to creating a craft class: class craft(): #has attribs common to any and all craft #end class then doing something like: class submarine(craft): #sub-specific attribs #end class How would I create a submarine, and then get at the craft-level attribs? Come to think of it, how would I pass anything to the craft constructor (position and alive, for example) when creating a new submarine object? Am I even doing this right to make submarine a subclass of craft? Thanks. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From astan.chee at al.com.au Tue May 18 18:05:05 2010 From: astan.chee at al.com.au (Astan Chee) Date: Wed, 19 May 2010 08:05:05 +1000 Subject: sound effects in python Message-ID: <4BF30F11.1050402@al.com.au> Hi, I have a sound file (e.g. .wav; .mp3, etc) in python that I'd like to modify (e.g. change tempo, pitch, add echo, amplify, etc). Any recommendation on how I can achieve this in python independent of platform? Thanks From ethan at stoneleaf.us Tue May 18 18:26:57 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 May 2010 15:26:57 -0700 Subject: how to cause a request for a missing class attribute cause its calculation In-Reply-To: <4BF3046B.7060100@stoneleaf.us> References: <4BF3046B.7060100@stoneleaf.us> Message-ID: <4BF31431.8030809@stoneleaf.us> Ethan Furman wrote: > Vincent Davis wrote: >> Lets say I have class foo(object): >> def __init__(self, x, y): >> self.x=x >> self.y=y >> def xplusy(self): >> self.xy = x+y > ^ this needs to be self.x + self.y >> >> inst = foo(1,2) >> inst.xy # no value, but I what this to cause the calculation of inst.xy >> >> I don't what to have self.xy calculated before it is called. > > My current favorite method: > > def __getattr__(self, name): > if name != 'xy': > raise AttributeError("%s not found" % name) > self.xy = self.x + self.y > return self.xy > > > ~Ethan~ Chris' reply is more on-point, I think -- I was thinking of attributes that are only calculated once. *sigh* ~Ethan~ From vincent at vincentdavis.net Tue May 18 19:06:25 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 17:06:25 -0600 Subject: sound effects in python In-Reply-To: <4BF30F11.1050402@al.com.au> References: <4BF30F11.1050402@al.com.au> Message-ID: There was a talk at pycon about this. Sounded interecting but I don't know much about it. http://us.pycon.org/2010/conference/schedule/event/136/ Vincent On Tue, May 18, 2010 at 4:05 PM, Astan Chee wrote: > Hi, > I have a sound file (e.g. .wav; .mp3, etc) in python that I'd like to > modify (e.g. change tempo, pitch, add echo, amplify, etc). > Any recommendation on how I can achieve this in python independent of > platform? > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Tue May 18 19:27:08 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 18 May 2010 18:27:08 -0500 Subject: Access to comp.lang.python In-Reply-To: References: Message-ID: <4BF3224C.4060707@tim.thechases.com> On 05/15/2010 05:34 PM, cjw wrote: > It seems that messages are coming from a number of sources, such as > gmane and google groups. > > The problem is that many messages seem to get unlinked from their threads. > > I use Thunderbird 3.0.5 and wonder whether the problem lies with the > merge process, the server or my reader. While others have told you about using gmane or other sources (direct email, etc), I haven't seen anything fly by regarding the "unlinked from their threads" portion of your question. Thunderbird 2.0 -> 3.0 changed the default value for mail.strict_threading from False to True. Pulling up the config editor (essentially the about:config, buried in the options->advanced stuff, I think; or perhaps I have the "about:config" plugin to do that) allows you to toggle this value back to "True". This setting controls whether threads are defined *only* by the mail header (strict=True), or whether TB also tries to guess based on the Subject header (strict=False). Toggle it (and perhaps restart TB?) and see if that helps rectify the threading. There are a lot of folks here on c.l.p that use broken newsreaders that don't correctly set news/threading headers. -tkc From robin.garen at gmail.com Tue May 18 20:27:39 2010 From: robin.garen at gmail.com (technocake) Date: Tue, 18 May 2010 17:27:39 -0700 (PDT) Subject: sound effects in python References: Message-ID: <05a04ed0-3315-48fe-80f4-a2665c7a0b65@o39g2000vbd.googlegroups.com> On 19 Mai, 00:05, Astan Chee wrote: > Hi, > I have a sound file (e.g. .wav; .mp3, etc) in python that I'd like to > modify (e.g. change tempo, pitch, add echo, amplify, etc). > Any recommendation on how I can achieve this in python independent of > platform? > Thanks You could have a look on PyAudio : http://people.csail.mit.edu/hubert/pyaudio/ I have not any experience with it, so I can only point you to it for now. Hope you find it useful technocake From davea at ieee.org Tue May 18 21:31:11 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 18 May 2010 21:31:11 -0400 Subject: another question about classes and subclassing In-Reply-To: References: Message-ID: <4BF33F5F.2030207@ieee.org> Alex Hall wrote: > Hi again all, > More about classes. I am still looking into my battleship game, and I > will have several different craft. All craft have common attribs > (position, alive, and so on) but each craft may be a surface ship, > submarine, or airplane. All three are craft, but a submarine can be > submerged or not, which does not apply to a surface ship or a plane, > while a plane can be airborne or not, which is not applicable to the > other two. Is there any advantage to creating a craft class: > > class craft(): > #has attribs common to any and all craft > #end class > > then doing something like: > > class submarine(craft): > #sub-specific attribs > #end class > > How would I create a submarine, and then get at the craft-level > attribs? Come to think of it, how would I pass anything to the craft > constructor (position and alive, for example) when creating a new > submarine object? Am I even doing this right to make submarine a > subclass of craft? Thanks. > > Inside the __init__() method of Submarine, simply call the __init__() method of Craft, with appropriate parameters. As for getting at the attributes of the Craft parent class, from a Submarine object, you simply reference the attributes as always. If they're not overridden in Submarine, they'll be searched for in Craft. DaveA From mehgcap at gmail.com Tue May 18 21:41:31 2010 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 18 May 2010 21:41:31 -0400 Subject: another question about classes and subclassing In-Reply-To: <4BF33F5F.2030207@ieee.org> References: <4BF33F5F.2030207@ieee.org> Message-ID: Okay, that makes sense. So by calling submarine(craft) I am bringing in all of craft's attribs (subclassing)? Or does calling craft's __init__ method do that instead? Is there an advantage to doing it this way, rather than just making separate classes for everything, except for my own sense of organization; speed, memory usage, less coding? Thanks. On 5/18/10, Dave Angel wrote: > Alex Hall wrote: >> Hi again all, >> More about classes. I am still looking into my battleship game, and I >> will have several different craft. All craft have common attribs >> (position, alive, and so on) but each craft may be a surface ship, >> submarine, or airplane. All three are craft, but a submarine can be >> submerged or not, which does not apply to a surface ship or a plane, >> while a plane can be airborne or not, which is not applicable to the >> other two. Is there any advantage to creating a craft class: >> >> class craft(): >> #has attribs common to any and all craft >> #end class >> >> then doing something like: >> >> class submarine(craft): >> #sub-specific attribs >> #end class >> >> How would I create a submarine, and then get at the craft-level >> attribs? Come to think of it, how would I pass anything to the craft >> constructor (position and alive, for example) when creating a new >> submarine object? Am I even doing this right to make submarine a >> subclass of craft? Thanks. >> >> > Inside the __init__() method of Submarine, simply call the __init__() > method of Craft, with appropriate parameters. > > As for getting at the attributes of the Craft parent class, from a > Submarine object, you simply reference the attributes as always. If > they're not overridden in Submarine, they'll be searched for in Craft. > > > DaveA > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From aahz at pythoncraft.com Tue May 18 21:47:41 2010 From: aahz at pythoncraft.com (Aahz) Date: 18 May 2010 18:47:41 -0700 Subject: upgrade python References: Message-ID: In article , packet wrote: > >Would it be safe to upgrade from python 2.6.4 to 2.6.5 without hurting >the 2.6.4? Define "hurting". Generally speaking, it's always safe to upgrade a point release, but you should replace the previous version. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From davea at ieee.org Tue May 18 22:01:07 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 18 May 2010 22:01:07 -0400 Subject: another question about classes and subclassing In-Reply-To: References: <4BF33F5F.2030207@ieee.org> Message-ID: <4BF34663.2000704@ieee.org> Alex Hall wrote: > Okay, that makes sense. So by calling submarine(craft) I am bringing > in all of craft's attribs (subclassing)? Or does calling craft's > __init__ method do that instead? Is there an advantage to doing it > this way, rather than just making separate classes for everything, > except for my own sense of organization; speed, memory usage, less > coding? Thanks. > > >> You put your response at the wrong end of the message. It should *follow* whatever you're quoting. So in your case, I'm forced to delete everything just to make the order correct. You don't call Submarine(Craft), as it's not a function. That's a class definition. You instantiate a Submarine by something like: sub = Submarine(arg1, arg2, arg3) And those three arguments are then passed to the __init__() method of Submarine. It may choose to call the __init__() method of Craft, in the method. There are lots of advantages of using inheritance. First, any common code only has to be entered once, so you'll only have to fix it once when you find mistakes, or decide to redesign. Second, it's easier to read - very important. It may take less memory, but probably not. And it's not likely to have any speed impact. Craft instances don't have any instance data attributes if nobody assigns them. And that's normally the job of __init__(). So naturally, you need to call it from the Submarine class. Incidentally, convention is to capitalize class names. DaveA From gobnat at optusnet.com.au Tue May 18 22:05:14 2010 From: gobnat at optusnet.com.au (gobnat) Date: Wed, 19 May 2010 12:05:14 +1000 Subject: Pointers on packaging python programs for installation on multiple platforms? Message-ID: <4BF3475A.80304@optusnet.com.au> Hi all I am trying to release my first python program. I would like to be able to create a download which will automatically do stuff like add menu items (eg for KDE, GNOME and Windows). Is there anywhere which explains how to do this? Thanks in advance Brendan From mehgcap at gmail.com Tue May 18 22:12:37 2010 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 18 May 2010 22:12:37 -0400 Subject: another question about classes and subclassing In-Reply-To: <4BF34663.2000704@ieee.org> References: <4BF33F5F.2030207@ieee.org> <4BF34663.2000704@ieee.org> Message-ID: On 5/18/10, Dave Angel wrote: > Alex Hall wrote: >> Okay, that makes sense. So by calling submarine(craft) I am bringing >> in all of craft's attribs (subclassing)? Or does calling craft's >> __init__ method do that instead? Is there an advantage to doing it >> this way, rather than just making separate classes for everything, >> except for my own sense of organization; speed, memory usage, less >> coding? Thanks. >> >> >>> > You put your response at the wrong end of the message. It should > *follow* whatever you're quoting. So in your case, I'm forced to delete > everything just to make the order correct. Sorry, top-posting is a habit on some other lists I am on, and sometimes it follows me to lists where in-line posting is the way to do it. > > You don't call Submarine(Craft), as it's not a function. That's a class > definition. You instantiate a Submarine by something like: > > sub = Submarine(arg1, arg2, arg3) > > And those three arguments are then passed to the __init__() method of > Submarine. It may choose to call the __init__() method of Craft, in the > method. So that is the only way of making submarine inherit craft, by calling craft's __init__ inside submarine's __init__. Okay, I think I get it. > > There are lots of advantages of using inheritance. First, any common > code only has to be entered once, so you'll only have to fix it once > when you find mistakes, or decide to redesign. Very true. > Second, it's easier to > read - very important. It may take less memory, but probably not. And > it's not likely to have any speed impact. > > Craft instances don't have any instance data attributes if nobody > assigns them. And that's normally the job of __init__(). So naturally, > you need to call it from the Submarine class. Right, I think I have it now... At least I hope I do! > > Incidentally, convention is to capitalize class names. Yes, I had planned on doing that in my project, but I got caught up in just making it work and forgot to do so. Thanks for the reminder. > > DaveA > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From tjreedy at udel.edu Tue May 18 22:28:40 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 22:28:40 -0400 Subject: Access to comp.lang.python In-Reply-To: <4BF3224C.4060707@tim.thechases.com> References: <4BF3224C.4060707@tim.thechases.com> Message-ID: On 5/18/2010 7:27 PM, Tim Chase wrote: > On 05/15/2010 05:34 PM, cjw wrote: >> It seems that messages are coming from a number of sources, such as >> gmane and google groups. >> >> The problem is that many messages seem to get unlinked from their >> threads. >> >> I use Thunderbird 3.0.5 and wonder whether the problem lies with the >> merge process, the server or my reader. > > While others have told you about using gmane or other sources (direct > email, etc), I haven't seen anything fly by regarding the "unlinked from > their threads" portion of your question. Thunderbird 2.0 -> 3.0 changed > the default value for mail.strict_threading from False to True. Pulling > up the config editor (essentially the about:config, buried in the > options->advanced stuff, I think; or perhaps I have the "about:config" > plugin to do that) allows you to toggle this value back to "True". This > setting controls whether threads are defined *only* by the mail header > (strict=True), or whether TB also tries to guess based on the Subject > header (strict=False). I solved the problem for me, well enough, by sorting threads by subject instead of 'Date' (actually, time) so that disconnect threads sort together anyway. From tjreedy at udel.edu Tue May 18 22:36:32 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 22:36:32 -0400 Subject: recall function definition from shell In-Reply-To: <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> References: <4bf2ceff$0$18987$4fafbaef@reader5.news.tin.it> <1c5b5657-1ed1-42ae-bc68-d221367a5588@q8g2000vbm.googlegroups.com> <4bf2df6e$0$18999$4fafbaef@reader5.news.tin.it> <19cb9d7d-dd3f-49d1-b6e6-b6613b9f6353@c13g2000vbr.googlegroups.com> <4bf2e296$0$18997$4fafbaef@reader5.news.tin.it> Message-ID: On 5/18/2010 2:55 PM, superpollo wrote: > yes python does not, but maybe the *shell* does, or so i thought. i just > wanted to dump the code for the function in a file, after i tested in > the shell... On Windows, you can tell the shell (command window) how many lines to remember. One can sensibly make this a lot higher on a gigabyte machine than back in the 640K days. No idea about other systems. From tjreedy at udel.edu Tue May 18 22:39:42 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2010 22:39:42 -0400 Subject: upgrade python In-Reply-To: References: Message-ID: On 5/18/2010 9:47 PM, Aahz wrote: > In article, > packet wrote: >> >> Would it be safe to upgrade from python 2.6.4 to 2.6.5 without hurting >> the 2.6.4? > > Define "hurting". Generally speaking, it's always safe to upgrade a > point release, but you should replace the previous version. The default action on windows is replace. I keep the previous installer around with the current one fora while in case a bugfix release has a problem and I need to revert. From ben+python at benfinney.id.au Tue May 18 22:54:04 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 May 2010 12:54:04 +1000 Subject: Picking a license References: <87r5ldbw3k.fsf@benfinney.id.au> <87fx1qji9t.fsf@benfinney.id.au> Message-ID: <87ocgciotv.fsf@benfinney.id.au> This thread is already off-topic and too long. I'm conflicted about my role in that; I have endeavoured only to address falsehoods that IMO were not otherwise being addressed. So I'll try to keep this brief. Ethan Furman writes: > This doesn't make sense to me, but I'm willing to learn -- how do you > do this in practice? Are you really selling the software Perhaps in private email we can discuss what you mean by ?really selling the software?; it's too off-topic here. By my understanding of that term, yes, I am selling software. > or rather selling things like setup, support, new code (or time to > code), etc? All of the above, depending on the project. -- \ ?If you don't know what your program is supposed to do, you'd | `\ better not start writing it.? ?Edsger W. Dijkstra | _o__) | Ben Finney From see at signature.invalid Tue May 18 23:01:10 2010 From: see at signature.invalid (Nigel Rowe) Date: Wed, 19 May 2010 13:01:10 +1000 Subject: help need to write a python spell checker References: Message-ID: On Fri, 14 May 2010 18:19, harry k wrote in comp.lang.python <>: > Write a spell checking tool that will identify all misspelled word in a text file using a provided dictionary. > > > > Extend the spell-checking tool so that the program will also print out a list of possible correct spellings for the words. > I'm happy to do you homework for you, cost is us$1000 per hour. Email to your professor automatically on receipt. From steve-REMOVE-THIS at cybersource.com.au Tue May 18 23:37:45 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 May 2010 03:37:45 GMT Subject: help need to write a python spell checker References: Message-ID: <4bf35d09$0$8802$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 13:01:10 +1000, Nigel Rowe wrote: > I'm happy to do you homework for you, cost is us$1000 per hour. Email > to your professor automatically on receipt. I'll do it for $700 an hour! -- Steven From awasilenko at gmail.com Tue May 18 23:39:20 2010 From: awasilenko at gmail.com (Adam W.) Date: Tue, 18 May 2010 20:39:20 -0700 (PDT) Subject: Classes and threading Message-ID: I thought I knew how classes worked, but this code sample is making my second guess myself: import threading class nThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self,args): print self.name print self.args pants = nThread(args=('fruit'),name='charlie') pants.start() Traceback (most recent call last): File "C:\Users\Adam\Desktop\PyTiVo\task_master.py", line 13, in pants = nThread(args=('fruit'),name='charlie') TypeError: __init__() got an unexpected keyword argument 'args' Shouldn't __init__ still handle these (as per http://docs.python.org/library/threading.html#thread-objects ), even if its subclassed? I thought this was the whole idea of inheritance and overdriving. And sort of related, why does this crash IDLE GUI but not the command line?: import threading class nThread(threading.Thread): def run(self): print 2+2 pants = nThread() pants.start() From frank.zhu.mingyu at gmail.com Tue May 18 23:42:10 2010 From: frank.zhu.mingyu at gmail.com (frank zhu) Date: Tue, 18 May 2010 23:42:10 -0400 Subject: question on logging module Message-ID: Hi, >From the python 2.6.4 tutorial, refer to http://docs.python.org/release/2.6.4/tutorial/stdlib2.html#logging The above example doesn't work for me. Here is script log ############################################# oem at oem-desktop ~ $ python -V Python 2.6.4 oem at oem-desktop ~ $ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> logging.debug('debug information') Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'debug' ################################################ I am current using python2.6.4. Can anyone point out what's problem? Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Wed May 19 00:04:40 2010 From: max at alcyone.com (Erik Max Francis) Date: Tue, 18 May 2010 21:04:40 -0700 Subject: Classes and threading In-Reply-To: References: Message-ID: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> Adam W. wrote: > I thought I knew how classes worked, but this code sample is making my > second guess myself: > > import threading > > class nThread(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > > def run(self,args): > print self.name > print self.args > > pants = nThread(args=('fruit'),name='charlie') > pants.start() > > Traceback (most recent call last): > File "C:\Users\Adam\Desktop\PyTiVo\task_master.py", line 13, in > > pants = nThread(args=('fruit'),name='charlie') > TypeError: __init__() got an unexpected keyword argument 'args' > > Shouldn't __init__ still handle these (as per > http://docs.python.org/library/threading.html#thread-objects ), even > if its subclassed? I thought this was the whole idea of inheritance > and overdriving. You've overridden the __init__ method to _not_ take any arguments, and explicitly call its parent constructor not passing anything. So it shouldn't be a wonder that it won't accept any arguments. If you don't intend to override the constructor in the parent class, simply don't define it. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis I like young girls. Their stories are shorter. -- Thomas McGuane From pmaupin at gmail.com Wed May 19 00:18:46 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Tue, 18 May 2010 21:18:46 -0700 (PDT) Subject: help need to write a python spell checker References: Message-ID: <49bffe0f-00a7-47a2-a857-1c1e35ac8870@p17g2000vbe.googlegroups.com> On May 14, 3:19?am, "harry k" wrote: > Write a spell checking tool that will identify all misspelled word in a text file using a provided dictionary. Well, this has been educational. Both my daughters just finished their final exams last week, so I was confused about seeing the homework assignment. Then I saw the email address. Although it makes perfect sense, I never really thought much about the possibility that the school year would be "upside down" "down under"... Regards, Pat From sjmachin at lexicon.net Wed May 19 00:23:44 2010 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 May 2010 21:23:44 -0700 (PDT) Subject: help need to write a python spell checker References: <4bf35d09$0$8802$c3e8da3@news.astraweb.com> Message-ID: <47839461-9f71-48cf-a7f2-dd9af2ef40d3@k17g2000pro.googlegroups.com> On May 19, 1:37?pm, Steven D'Aprano wrote: > On Wed, 19 May 2010 13:01:10 +1000, Nigel Rowe wrote: > > I'm happy to do you homework for you, cost is us$1000 per hour. ?Email > > to your professor automatically on receipt. > > I'll do it for $700 an hour! he could save the money if he oogledgay orvignay ellspay eckerchay From cs at zip.com.au Wed May 19 00:33:34 2010 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 19 May 2010 14:33:34 +1000 Subject: question on logging module In-Reply-To: References: Message-ID: <20100519043334.GA17039@cskk.homeip.net> On 18May2010 23:42, frank zhu wrote: | Hi, | >From the python 2.6.4 tutorial, refer to | http://docs.python.org/release/2.6.4/tutorial/stdlib2.html#logging | | The above example doesn't work for me. | Here is script log | | ############################################# | | oem at oem-desktop ~ $ python -V | Python 2.6.4 | oem at oem-desktop ~ $ python | Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) | [GCC 4.4.1] on linux2 | Type "help", "copyright", "credits" or "license" for more information. | >>> import logging | >>> logging.debug('debug information') | Traceback (most recent call last): | File "", line 1, in | AttributeError: 'module' object has no attribute 'debug' | | ################################################ | | I am current using python2.6.4. | | Can anyone point out what's problem? I don't suppose you have a file called "logging.py" in your working directory? Python will find it before the system libraries; it is a bad idea to name .py files the same as library module for this reason. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ The First Law of Internet Communications: Be liberal in what you accept, and conservative in what you send. - Jon Postel From contact at xavierho.com Wed May 19 00:45:49 2010 From: contact at xavierho.com (Xavier Ho) Date: Wed, 19 May 2010 14:45:49 +1000 Subject: help need to write a python spell checker In-Reply-To: <49bffe0f-00a7-47a2-a857-1c1e35ac8870@p17g2000vbe.googlegroups.com> References: <49bffe0f-00a7-47a2-a857-1c1e35ac8870@p17g2000vbe.googlegroups.com> Message-ID: Yeah, most unis here commence in March, and the first semester usually finish in June, when the exams are. - Xav on his 'droid On 19/05/2010 2:21 PM, "Patrick Maupin" wrote: On May 14, 3:19 am, "harry k" wrote: > Write a spell checking tool that wil... Well, this has been educational. Both my daughters just finished their final exams last week, so I was confused about seeing the homework assignment. Then I saw the email address. Although it makes perfect sense, I never really thought much about the possibility that the school year would be "upside down" "down under"... Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at vincentdavis.net Wed May 19 01:14:49 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 18 May 2010 23:14:49 -0600 Subject: __str__ for each function in a class Message-ID: I am sure this is easy but I am not sure how to do it and google was failing me. Lets say I have a class() with an def x() and def y() and I want print(class.x) and (class.y) to have custom prints (__str__) how do I do this For example class C(object): def __init__(self, new): self.letter = dict(a=1,b=2,c=3, amin=np.amin) self.new = new self._x = None self._Y = None @property def x(self): """I'm the 'x' property.""" self._x = self.new return self._x @property def y(self): """I'm the 'x' property.""" self._y = self.new*-1 return self._y ....... >>> print(class.x) ****x**** >>> print(class.y) --------- ++++y++++ --------- *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From hellofromsahar at gmail.com Wed May 19 02:07:13 2010 From: hellofromsahar at gmail.com (sahar Dar) Date: Tue, 18 May 2010 23:07:13 -0700 (PDT) Subject: Quality Indian Dresses At Reasonable Prices Message-ID: <5ec2a0b4-17e1-4ddd-9ee2-de17c4128c96@o1g2000vbe.googlegroups.com> Dear All, My Ladies Wear Site Is Live Now. We Bring You the Latest Designer Wear From All Over THE World specially India & Pakistan. To Place Your Orders Checkout www.e-atitude.com From switch2mathan at gmail.com Wed May 19 02:57:40 2010 From: switch2mathan at gmail.com (MathanK) Date: Tue, 18 May 2010 18:57:40 -1200 Subject: Is there conversion method to convert pyunicodeobject to pybyteobject? Message-ID: <128af5a76ca.2387060254380996511.-7043682202504556201@gmail.com> Got it worked with the following change. PyUnicodeObject *p = ...whatever...; char* tmp = (char *)p; PyObject* arg = PyBytes_FromString (tmp); function( (PyBytesObject*) arg); >From : MathanK<switch2mathan at gmail.com> To : "python-list" <python-list at python.org> Date : Sat, 15 May 2010 02:50:22 -1200 Subject : Is there conversion method to convert pyunicodeobject to pybyteobject? Hi All, A variable whose data type is PyUnicodeObject is to be assigned to varioable of PyBytesObject type example : void function( (PyBytesObject* byte){........} PyUnicodeObject *p = ...whatever...; function( (PyBytesObject*)p); compiled and got a Bus Error. Cheers, Mathan -------------- next part -------------- An HTML attachment was scrubbed... URL: From tomf.sessile at gmail.com Wed May 19 03:16:56 2010 From: tomf.sessile at gmail.com (TomF) Date: Wed, 19 May 2010 00:16:56 -0700 Subject: Global variables for python applications References: Message-ID: <2010051900165614229-tomfsessile@gmailcom> On 2010-05-16 12:27:21 -0700, christian schulze said: > On 16 Mai, 20:20, James Mills wrote: >> On Mon, May 17, 2010 at 4:00 AM, Krister Svanlund >> >> wrote: >>> On Sun, May 16, 2010 at 7:50 PM, AON LAZIO wrote: >>>> ?? How can I set up global variables for the entire python applications? >>>> Like I can call and set this variables in any .py files. >>>> ?? Think of it as a global variable in a single .py file but thisis for the >>>> entire application. >> >>> First: Do NOT use global variables, it is bad practice and will >>> eventually give you loads of s**t. >> >>> But if you want to create global variables in python I do believe it >>> is possible to specify them in a .py file and then simply import it as >>> a module in your application. If you change one value in a module the >>> change will be available in all places you imported that module in. >> >> The only place global variables are considered somewhat "acceptable" >> are as constants in a module shared as a static value. >> >> Anything else should be an object that you share. Don't get into the >> habit of using global variables! >> >> --james > > Exactly! Python's OOP is awesome. Use it. Global vars used as anything > but constants is bad practice. It isn't that much work to implement > that. Let's say you have a bunch of globals, one of which is a verbose flag. If I understand the difference, using a module gbls.py: # in gbls.py verbose = False # elsewhere: import gbls gbls.verbose = True Using a class: # In the main module: class gbls(object): def __init__(self, verbose=False): self.verbose = verbose my_globals = gbls.gbls(verbose=True) ... some_function(my_globals, ...) If this is what you have in mind, I'm not really seeing how one is good practice and the other is bad. The OOP method is more verbose (no pun intended) and I don't see how I'm any less likely to shoot myself in the foot with it. -Tom From cmpython at gmail.com Wed May 19 03:17:05 2010 From: cmpython at gmail.com (CM) Date: Wed, 19 May 2010 00:17:05 -0700 (PDT) Subject: help need to write a python spell checker References: Message-ID: I love how he just copied and pasted the assignment without any other remarks. From anthra.norell at bluewin.ch Wed May 19 03:26:17 2010 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Wed, 19 May 2010 09:26:17 +0200 Subject: Regular expression In-Reply-To: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> References: <8281ee68-948b-42c6-832c-db338232a63f@y21g2000vba.googlegroups.com> Message-ID: <4BF39299.1090804@bluewin.ch> Back9 wrote: > Hi, > > I have a string like this: > 0x340x5A0x9B0xBA > I want to extract 0x from the string but the first one. > > How I can use re for this case? > > The string size will vary. > > TIA > > Unless the use of a regular expression is a requirement I'd do it like this: '0x%s' % s.split ('x', 1)[1].replace ('x', '') Frederic From awasilenko at gmail.com Wed May 19 03:50:48 2010 From: awasilenko at gmail.com (Adam W.) Date: Wed, 19 May 2010 00:50:48 -0700 (PDT) Subject: Classes and threading References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> Message-ID: On May 19, 12:04?am, Erik Max Francis wrote: > Adam W. wrote: > > I thought I knew how classes worked, but this code sample is making my > > second guess myself: > > > import threading > > > class nThread(threading.Thread): > > ? ? def __init__(self): > > ? ? ? ? threading.Thread.__init__(self) > > > ? ? def run(self,args): > > ? ? ? ? print self.name > > ? ? ? ? print self.args > > > pants = nThread(args=('fruit'),name='charlie') > > pants.start() > > > Traceback (most recent call last): > > ? File "C:\Users\Adam\Desktop\PyTiVo\task_master.py", line 13, in > > > > ? ? pants = nThread(args=('fruit'),name='charlie') > > TypeError: __init__() got an unexpected keyword argument 'args' > > > Shouldn't __init__ still handle these (as per > >http://docs.python.org/library/threading.html#thread-objects), even > > if its subclassed? ?I thought this was the whole idea of inheritance > > and overdriving. > > You've overridden the __init__ method to _not_ take any arguments, and > explicitly call its parent constructor not passing anything. ?So it > shouldn't be a wonder that it won't accept any arguments. > > If you don't intend to override the constructor in the parent class, > simply don't define it. Hummm, so lets say I wanted it pass all the variables to the parent constructor, how would I do that? I wouldn't have to list every variable it could possible receive would I? This is like the opposite behavior I remember. When working with PyQt GUI classes, I swear I just sub classed the few things I wanted to change, and everything else would refer back to the parent... What I really just want to do is pass run() some args, which is what I assumed the default __init__'s args was for, but I give it args without sub classing __init__ and it has no idea what to do with them. I subclass __init__ to take args, and I break everything else? Is this really how this is supposed to work? From mail at timgolden.me.uk Wed May 19 03:55:42 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 19 May 2010 08:55:42 +0100 Subject: Pointers on packaging python programs for installation on multiple platforms? In-Reply-To: <4BF3475A.80304@optusnet.com.au> References: <4BF3475A.80304@optusnet.com.au> Message-ID: <4BF3997E.5080805@timgolden.me.uk> On 19/05/2010 03:05, gobnat wrote: > I am trying to release my first python program. I would like to be > able to create a download which will automatically do stuff like add > menu items (eg for KDE, GNOME and Windows). Is there anywhere which > explains how to do this? Speaking from the Windows perspective (although the same probably applies elsewhere): this is the kind of thing which installer generators handle for you. If you wrap your installer using NSIS [1] or Wix [2] or whatever other installer-generator, that will include options to add menu items. (Caveat: this is informed hearsay; I've never actually used either of those in earnest). If you *want* to do it yourself then, on Windows, you basically want to create folders and shortcuts within the user's Start Menu shell folder. It's not too hard even from scratch; my winshell module might help a little, too. [3] TJG [1] http://nsis.sourceforge.net/Main_Page [2] http://wix.sourceforge.net/ [3]http://timgolden.me.uk/python/winshell.html From greg.ewing at canterbury.ac.nz Wed May 19 04:04:32 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 19 May 2010 20:04:32 +1200 Subject: another question about classes and subclassing In-Reply-To: References: <4BF33F5F.2030207@ieee.org> <4BF34663.2000704@ieee.org> Message-ID: <85hjq5FdqlU1@mid.individual.net> Alex Hall wrote: > Sorry, top-posting is a habit on some other lists I am on, and > sometimes it follows me to lists where in-line posting is the way to > do it. Which list you're on shouldn't matter. You should cultivate the habit of always quoting selectively and minimally, on any list. It may take you a little longer to write your reply that way, but it will make your posts a lot easier for everyone else to read and understand. -- Greg From greg.ewing at canterbury.ac.nz Wed May 19 04:15:30 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 19 May 2010 20:15:30 +1200 Subject: another question about classes and subclassing In-Reply-To: References: <4BF33F5F.2030207@ieee.org> Message-ID: <85hkenFhdkU1@mid.individual.net> Alex Hall wrote: > So by calling submarine(craft) I am bringing > in all of craft's attribs (subclassing)? Or does calling craft's > __init__ method do that instead? By making Submarine a subclass of Craft, you are inheriting any methods, or other class attributes, defined in the classes themselves. Instance attributes are a little different -- they only come into existence when you assign to them, which is usually done for the first time in the __init__ method. Each instance has its own dictionary that holds the values of its instance attributes, and it's just a flat namespace -- there is no real distinction between an instance attribute of a class or a subclass. Any "inheritance" of instance attributes is just a consequence of one __init__ method calling another. -- Greg From duncan.booth at invalid.invalid Wed May 19 04:17:41 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 May 2010 08:17:41 GMT Subject: Classes and threading References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> Message-ID: "Adam W." wrote: >> If you don't intend to override the constructor in the parent class, >> simply don't define it. > > Hummm, so lets say I wanted it pass all the variables to the parent > constructor, how would I do that? I wouldn't have to list every > variable it could possible receive would I? > No, you just have to handle them the way you would for any function that accepts arguments that it doesn't know in advance: class nThread(threading.Thread): def __init__(self, *args, **kw): threading.Thread.__init__(self, *args, **kw) If you want to add your own additional arguments then name them explicitly and don't pass them through: class nThread(threading.Thread): def __init__(self, myarg1, mayarg2, *args, **kw): threading.Thread.__init__(self, *args, **kw) -- Duncan Booth http://kupuguy.blogspot.com From greg.ewing at canterbury.ac.nz Wed May 19 04:22:21 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 19 May 2010 20:22:21 +1200 Subject: another question about classes and subclassing In-Reply-To: References: Message-ID: <85hkrkFjqlU1@mid.individual.net> Dave Angel wrote: > Inside the __init__() method of Submarine, simply call the __init__() > method of Craft, with appropriate parameters. To elaborate on that a little, it looks like this: class Craft: def __init__(self, position): self.position = position class Submarine(Craft): def __init__(self, position, depth): Craft.__init__(self, position) self.depth = depth Note the explicit 'self' passed to the __init__ method of Craft. This is necessary because you are calling the method's underlying function directly, bypassing the magic which normally inserts 'self' automatically. -- Greg From greg.ewing at canterbury.ac.nz Wed May 19 04:30:11 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 19 May 2010 20:30:11 +1200 Subject: Classes and threading In-Reply-To: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> Message-ID: <85hla5FjqlU2@mid.individual.net> Erik Max Francis wrote: > Adam W. wrote: > >> class nThread(threading.Thread): >> def __init__(self): >> threading.Thread.__init__(self) > > If you don't intend to override the constructor in the parent class, > simply don't define it. Or if you do need to override it for some reason, you need to accept the extra args and pass them on: class nThread(threading.Thread): def __init__(self, *args, **kwds): threading.Thread.__init__(self, *args, **kwds) # your other stuff here -- Greg From awasilenko at gmail.com Wed May 19 05:08:24 2010 From: awasilenko at gmail.com (Adam W.) Date: Wed, 19 May 2010 02:08:24 -0700 (PDT) Subject: Classes and threading References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> <85hla5FjqlU2@mid.individual.net> Message-ID: <1459066c-5611-4fe4-8a8b-5cc264e7fa4d@o15g2000vbb.googlegroups.com> On May 19, 4:30?am, Gregory Ewing wrote: > Or if you do need to override it for some reason, you > need to accept the extra args and pass them on: > > ? ?class nThread(threading.Thread): > > ? ? ? ?def __init__(self, *args, **kwds): > ? ? ? ? ? ?threading.Thread.__init__(self, *args, **kwds) > ? ? ? ? ? ?# your other stuff here > Amazing, I've never seen *args used before outside of documentation, I didn't think it was "real" :P One problem down, still looking for why printing inside a thread crashes IDLE. From jimmy.cullen at gmail.com Wed May 19 05:28:15 2010 From: jimmy.cullen at gmail.com (Jimoid) Date: Wed, 19 May 2010 02:28:15 -0700 (PDT) Subject: Reading data from a Microsoft Access 2003 database Message-ID: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> Hi All, I use Ubuntu 64 bit and need to develop a programme (ideally in Python) to work on data that is contained in a Microsoft Access 2003 database. I do not need to modify the database, simply read a few columns of data from some tables. Google hasn't been able to offer me a suitable solution to this problem, and although there are some references to this problem in the archives of this group, they are mainly very old and I wonder if there is anything more recent that members could suggest to me? Python would be my language of choice, however if someone has any other suggestions then I'm open to ideas. TIA, Jimmy From lists at cheimes.de Wed May 19 05:43:49 2010 From: lists at cheimes.de (Christian Heimes) Date: Wed, 19 May 2010 11:43:49 +0200 Subject: Classes and threading In-Reply-To: <85hla5FjqlU2@mid.individual.net> References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> <85hla5FjqlU2@mid.individual.net> Message-ID: > Or if you do need to override it for some reason, you > need to accept the extra args and pass them on: > > class nThread(threading.Thread): > > def __init__(self, *args, **kwds): > threading.Thread.__init__(self, *args, **kwds) > # your other stuff here Since Thread is a new style class, this should read: class NThread(threading.thread): def __init__(self, *args, **kwargs): super(NThread, self).__init__(*args, **kwargs) Christian From simon at brunningonline.net Wed May 19 06:13:19 2010 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 19 May 2010 11:13:19 +0100 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> Message-ID: On 19 May 2010 10:28:15 UTC+1, Jimoid wrote: > I use Ubuntu 64 bit and need to develop a programme (ideally in > Python) to work on data that is contained in a Microsoft Access 2003 > database. I do not need to modify the database, simply read a few > columns of data from some tables. mxODBC might well be what you are looking for, -- Cheers, Simon B. From jmontoyaz at gmail.com Wed May 19 06:53:44 2010 From: jmontoyaz at gmail.com (Javier Montoya) Date: Wed, 19 May 2010 03:53:44 -0700 (PDT) Subject: remove elements incrementally from a list Message-ID: Dear all, I've a list of float numbers and I would like to delete incrementally a set of elements in a given range of indexes, sth. like: for j in range(beginIndex, endIndex+1): print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j] However, since I'm iterating over the same list, the indexes (range) are not valid any more for the new list. Does anybody has some suggestions on how to delete the elements properly? Best wishes From utente at esempio.net Wed May 19 07:00:01 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 13:00:01 +0200 Subject: remove elements incrementally from a list In-Reply-To: References: Message-ID: <4bf3c4b1$0$40285$4fafbaef@reader2.news.tin.it> Javier Montoya ha scritto: > Dear all, > > I've a list of float numbers and I would like to delete incrementally > a set of elements in a given range of indexes, sth. like: > > for j in range(beginIndex, endIndex+1): > print ("remove [%d] => val: %g" % (j, myList[j])) > del myList[j] > > However, since I'm iterating over the same list, the indexes (range) > are not valid any more for the new list. > Does anybody has some suggestions on how to delete the elements > properly? clone the list, and then loop over the copy while deleting from the original bye From solderluke at gmail.com Wed May 19 07:24:27 2010 From: solderluke at gmail.com (zLuke) Date: Wed, 19 May 2010 04:24:27 -0700 (PDT) Subject: multiprocessing module - could it use google protocol buffers? Message-ID: <210a0635-c5f5-48ca-8696-760e1bf2b361@p17g2000vbe.googlegroups.com> Does it make sense to be able to substitute the pickling action in the multiprocessing module with google protocol buffers instead? If so, has anyone thought how to do it? I wanted some operation more compact/ faster than pickling for ipc of data. Also, has anyone built any wrappers for the multiprocessing module that gives a simple pp flavor kind of construct? Curious, zLuke From breamoreboy at yahoo.co.uk Wed May 19 07:38:16 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 19 May 2010 12:38:16 +0100 Subject: remove elements incrementally from a list In-Reply-To: References: Message-ID: On 19/05/2010 11:53, Javier Montoya wrote: > Dear all, > > I've a list of float numbers and I would like to delete incrementally > a set of elements in a given range of indexes, sth. like: > > for j in range(beginIndex, endIndex+1): > print ("remove [%d] => val: %g" % (j, myList[j])) > del myList[j] > > However, since I'm iterating over the same list, the indexes (range) > are not valid any more for the new list. > Does anybody has some suggestions on how to delete the elements > properly? > > Best wishes You can delete the lot in one hit using a slice, see section 5.2 here http://docs.python.org/tutorial/datastructures.html Regards. Mark Lawrence From shahmed at sfwmd.gov Wed May 19 07:47:41 2010 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Wed, 19 May 2010 07:47:41 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> Message-ID: <77F33A87D54B2F47AB06A81DA7B5252736D7C9@EXCHVS02.ad.sfwmd.gov> -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of Simon Brunning Sent: Wednesday, May 19, 2010 6:13 AM To: python-list Subject: Re: Reading data from a Microsoft Access 2003 database On 19 May 2010 10:28:15 UTC+1, Jimoid wrote: > I use Ubuntu 64 bit and need to develop a programme (ideally in > Python) to work on data that is contained in a Microsoft Access 2003 > database. I do not need to modify the database, simply read a few > columns of data from some tables. mxODBC might well be what you are looking for, -- Cheers, Simon B. -- Or you can use pyodbc DBfile = '/path/*.mdb conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+DBfile, autocommit=True) cursor = conn.cursor() Thanks Shakir From schaffer at optonline.net Wed May 19 08:05:49 2010 From: schaffer at optonline.net (Les Schaffer) Date: Wed, 19 May 2010 08:05:49 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> Message-ID: <4bf3d419$0$31275$607ed4bc@cv.net> Jimoid wrote: > I use Ubuntu 64 bit and need to develop a programme (ideally in > Python) to work on data that is contained in a Microsoft Access 2003 > database. I do not need to modify the database, simply read a few > columns of data from some tables. this worked like a charm for me: http://code.activestate.com/recipes/528868-extraction-and-manipulation-class-for-microsoft-ac/ Les From awilliam at whitemice.org Wed May 19 08:17:58 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Wed, 19 May 2010 08:17:58 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: <4bf3d419$0$31275$607ed4bc@cv.net> References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> Message-ID: <1274271478.4282.1.camel@linux-yu4c.site> On Wed, 2010-05-19 at 08:05 -0400, Les Schaffer wrote: > Jimoid wrote: > > > I use Ubuntu 64 bit and need to develop a programme (ideally in > > Python) to work on data that is contained in a Microsoft Access 2003 > > database. I do not need to modify the database, simply read a few > > columns of data from some tables. > > this worked like a charm for me: > http://code.activestate.com/recipes/528868-extraction-and-manipulation-class-for-microsoft-ac/ The OP: "I use Ubuntu 64 bit" Does something that contains "import win32com.client" work on anything other than Windows? -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From awilliam at whitemice.org Wed May 19 08:23:20 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Wed, 19 May 2010 08:23:20 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> Message-ID: <1274271800.4282.6.camel@linux-yu4c.site> On Wed, 2010-05-19 at 02:28 -0700, Jimoid wrote: > Hi All, > I use Ubuntu 64 bit and need to develop a programme (ideally in > Python) to work on data that is contained in a Microsoft Access 2003 > database. I do not need to modify the database, simply read a few > columns of data from some tables. > Google hasn't been able to offer me a suitable solution to this Google is a poor way to look for such things. It is better to go to Freshmeat / SourceForge or PyPI directly. Try mdbtools is your best bet unless you are willing to pay for the EasySoft drivers. I've had mixed success with mdbtools; if all you need to do is extract data their ODBC driver will probably work. If you are willing to use Jython (Python on the JVM) you have a *lot* more options for this kind of thing. > problem, and although there are some references to this problem in the > archives of this group, they are mainly very old and I wonder if there > is anything more recent that members could suggest to me? > Python would be my language of choice, however if someone has any > other suggestions then I'm open to ideas. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From mouadino at gmail.com Wed May 19 08:32:58 2010 From: mouadino at gmail.com (mouadino) Date: Wed, 19 May 2010 05:32:58 -0700 (PDT) Subject: abc don't play well with private method References: <61304a50-68ad-445c-b441-c85ab2ccc1e1@q32g2000yqb.googlegroups.com> <4be18d3d$0$19014$426a34cc@news.free.fr> <4bf2af74$0$24527$426a74cc@news.free.fr> Message-ID: <0be11297-65b3-4943-a361-80ee04953b78@r9g2000vbk.googlegroups.com> Hello, and thank you for ALL the informations. i think i was reading the wrong documents :) For my use of ABC, i wanted to implement a plugin interface with the ABC, in first i define a Base class (ABC) that other class inherit(implement) so that they can be interfaced as plugins. but i did have some confusing about the privates method . thank you all again. Khalil_ibn_Ahmad (http://en.wikipedia.org/wiki/Khalil_ibn_Ahmad) sayed : They are 4 kind of man : the one that know that he don't know, this is a ignorant so teach him the one that know that he know, this is a savant so take from him the knowledge the one that don't know that he know, this one has forget so remind him the one that don't know that he don't know , this is a fool From steveo at syslang.net Wed May 19 09:47:22 2010 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 19 May 2010 09:47:22 -0400 Subject: remove elements incrementally from a list In-Reply-To: References: Message-ID: <4BF3EBEA.7000903@syslang.net> On 5/19/2010 6:53 AM, Javier Montoya wrote: > I've a list of float numbers and I would like to delete incrementally > a set of elements in a given range of indexes, sth. like: > > for j in range(beginIndex, endIndex+1): > print ("remove [%d] => val: %g" % (j, myList[j])) > del myList[j] > > However, since I'm iterating over the same list, the indexes (range) > are not valid any more for the new list. > Does anybody has some suggestions on how to delete the elements > properly? How about using numpy? to_be_deleted is an array of indexes to be deleted from myList. You seem to already have that list created but your list is contiguous. Just in case it isn't, you can say stuff like: to_be_deleted = numpy.where( myList > allowed_or_something ) myList = numpy.delete( myList, to_be_deleted ) -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From schaffer at optonline.net Wed May 19 10:00:15 2010 From: schaffer at optonline.net (Les Schaffer) Date: Wed, 19 May 2010 10:00:15 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> Message-ID: <4bf3eeeb$0$31263$607ed4bc@cv.net> Adam Tauno Williams wrote: > The OP: "I use Ubuntu 64 bit" woops, my bad ... From steve at REMOVE-THIS-cybersource.com.au Wed May 19 10:06:44 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 May 2010 14:06:44 GMT Subject: remove elements incrementally from a list References: Message-ID: <4bf3f074$0$27861$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 03:53:44 -0700, Javier Montoya wrote: > Dear all, > > I've a list of float numbers and I would like to delete incrementally a > set of elements in a given range of indexes, sth. like: > > for j in range(beginIndex, endIndex+1): > print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j] > > However, since I'm iterating over the same list, the indexes (range) are > not valid any more for the new list. Does anybody has some suggestions > on how to delete the elements properly? Just delete the slice: del myList[beginIndex:endIndex+1] For small lists where you are deleting small chunks, this is the simplest, most straight-forward way. Alternatively, create a new list excluding the bits you would have deleted, and assign it in place: myList[:] = myList[:beginIndex] + myList[endIndex+1:] Note carefully that you aren't just re-binding the name "myList", but assigning to the slice myList[:]. Then there is the old-fashioned way: iterate over the list backwards, deleting from the end towards the front. for j in range(endIndex, beginIndex-1, -1): del myList[j] If your list is HUGE and you have very little memory, this is probably the least worst way. It might be slow, but it will work. Finally, we have this: myList[beginIndex:] = myList[endIndex+1:] -- Steven From ninmonkeys at gmail.com Wed May 19 10:21:20 2010 From: ninmonkeys at gmail.com (Jake b) Date: Wed, 19 May 2010 09:21:20 -0500 Subject: View Html/ py code in a zip as HTML/text ? ( for phone ) Message-ID: I'm trying to figure out the best way to view python snippets / smaller files on the itouch/iPhone. I'm reading a new projects docs, but it's not easy to view the zip. It can't view zip files. Say I want to read pyglet examples, I need unzip at least one file and serve that. If it is text/HTML/py , then view in pastebin. Is there a trick to do this? Or maybe for certain sites. I thought I had seen a way google did it to a zip not hosted on google code, but can't find it. 1) is there existing web app to do this? 2) if not, I am on wifi, with apache mod-wsgi python enabled, so I could use that? -- Jake From kcronline at gmail.com Wed May 19 10:21:48 2010 From: kcronline at gmail.com (Kevin Rea) Date: Wed, 19 May 2010 10:21:48 -0400 Subject: Python Script for Website Mirroring Message-ID: Hello Folks: Can you please point me to a decent Python script(s) that I could customize to do automatic Website mirroring? Thanks Much! Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Wed May 19 10:34:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 May 2010 14:34:37 GMT Subject: Global variables for python applications References: <2010051900165614229-tomfsessile@gmailcom> Message-ID: <4bf3f6fc$0$27861$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 00:16:56 -0700, TomF wrote: > Let's say you have a bunch of globals, one of which is a verbose flag. > If I understand the difference, using a module gbls.py: > > # in gbls.py > verbose = False > # elsewhere: > import gbls > gbls.verbose = True > > Using a class: > > # In the main module: > class gbls(object): > def __init__(self, verbose=False): > self.verbose = verbose > > my_globals = gbls.gbls(verbose=True) > ... > some_function(my_globals, ...) > > > If this is what you have in mind, I'm not really seeing how one is good > practice and the other is bad. The OOP method is more verbose (no pun > intended) and I don't see how I'm any less likely to shoot myself in the > foot with it. Exactly! Both are considered harmful. Best is to avoid the use of globals if possible, not to disguise them by wrapping them in a class. The second case (using a class) is slightly less harmful, because you can set up multiple global namespaces and do this: some_function(my_globals, ...) some_function(other_globals, ...) which at least allows you to replace the globals on demand, but it is still somewhat of a code-smell. Best is to find a way of doing without them. (Note that global constants and functions are usually fine.) Unfortunately, it's rarely possible to do entirely without global settings, except in trivial applications. But what you can do is use Python's dynamic programming to reduce the need to keep globals hanging around: # Untested. def verbose_print(arg, level, verbosity=1): if level <= verbosity: print arg def my_function(arg): my_print(arg, level=2) return arg.upper() if __name__ == '__main__': if '--verbose' in sys.argv: my_print = functools.partial(verbose_print, verbosity=2) elif '--quiet' in sys.argv: my_print = functools.partial(verbose_print, verbosity=0) my_function("hello world") Note that although there is no verbosity global setting, every function that calls my_print will do the right thing (unless I've got the test backwards...), and if a function needs to override the implicit verbosity setting, it can just call verbose_print directly. -- Steven From thomas.fischer at gmail.com Wed May 19 10:41:38 2010 From: thomas.fischer at gmail.com (pilgrim773) Date: Wed, 19 May 2010 07:41:38 -0700 (PDT) Subject: Delete files from FTP Server older then 7 days. Using ftputil and ftplib. Message-ID: <6da6fa93-9298-4577-89b5-d58cb126d6fe@b21g2000vbh.googlegroups.com> Hello I am new to Python programming. I need a write a script which will delete files from a FTP server after they have reached a certain age, like 7 days for example. I have prepared this code below, but I get an error message: The system cannot find the path specified: '/test123/*.*' Probably someone can help me further? Thank you in advance! import os, time, ftputil from ftplib import FTP ftp = FTP('127.0.0.1') print "Automated FTP Maintainance" print 'Logging in.' ftp.login('admin', 'admin') # This is the directory that we want to go to directory = 'test123' print 'Changing to:' + directory ftp.cwd(directory) files = ftp.retrlines('LIST') print 'List of Files:' + files # ftp.remove('LIST') #------------------------------------------- now = time.time() for f in os.listdir(directory): if os.stat(f).st_mtime < now - 7 * 86400: if os.directory.isfile(f): os.remove(os.directory.join(directory, f)) #except: #exit ("Cannot delete files") #------------------------------------------- print 'Closing FTP connection' ftp.close() From tjreedy at udel.edu Wed May 19 11:02:38 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 May 2010 11:02:38 -0400 Subject: __str__ for each function in a class In-Reply-To: References: Message-ID: On 5/19/2010 1:14 AM, Vincent Davis wrote: > > I am sure this is easy but I am not sure how to do it and google was > failing me. > Lets say I have a class() with an def x() and def y() and I want > print(class.x) and (class.y) to have custom prints (__str__) how do I do > this > For example > class C(object): > def __init__(self, new): > self.letter = dict(a=1,b=2,c=3, amin=np.amin) > self.new = new > self._x = None > self._Y = None > > @property > def x(self): > """I'm the 'x' property.""" > self._x = self.new > return self._x > > @property > def y(self): > """I'm the 'x' property.""" > self._y = self.new*-1 > return self._y > > ....... > >>> print(class.x) 'class' is a keyword, so this is a syntax error. Did you mean C.x? > ****x**** In any case, the printing of an object ob is controlled by type(ob).__str__ and type(ob).__repr__, so you can only control the printing of instances of custom type. You cannot replace methods of builtin classes. Terry Jan Reedy From tjreedy at udel.edu Wed May 19 11:07:33 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 May 2010 11:07:33 -0400 Subject: help need to write a python spell checker In-Reply-To: References: Message-ID: On 5/19/2010 3:17 AM, CM wrote: > I love how he just copied and pasted the assignment without any other > remarks. Yeah, that way he did not mess it up ;-). From contact at xavierho.com Wed May 19 11:09:24 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 20 May 2010 01:09:24 +1000 Subject: __str__ for each function in a class In-Reply-To: References: Message-ID: On 5/19/2010 1:14 AM, Vincent Davis wrote: > class C(object): >> def __init__(self, new): >> self.letter = dict(a=1,b=2,c=3, amin=np.amin) >> self.new = new >> self._x = None >> self._Y = None >> >> @property >> def x(self): >> """I'm the 'x' property.""" >> self._x = self.new >> return self._x >> > I just wanted to point out that your self._x = self.new does not give you a new object. Instead, _x is assigned a reference that points to this object called 'new', which is passed in during the class initialisation. I think your variable naming needs some improvement to show/correct your understanding. Also, you can just use `x` and `y` for the variable names; you don't need the underscore. If you want to use a pseudo-private variable, use __x (double prefix underscore) instead. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmontoyaz at gmail.com Wed May 19 11:29:19 2010 From: jmontoyaz at gmail.com (Javier Montoya) Date: Wed, 19 May 2010 08:29:19 -0700 (PDT) Subject: remove elements incrementally from a list References: <4bf3f074$0$27861$c3e8da3@news.astraweb.com> Message-ID: On May 19, 4:06?pm, Steven D'Aprano wrote: > On Wed, 19 May 2010 03:53:44 -0700, Javier Montoya wrote: > > Dear all, > > > I've a list of float numbers and I would like to delete incrementally a > > set of elements in a given range of indexes, sth. like: > > > for j in range(beginIndex, endIndex+1): > > ? ?print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j] > > > However, since I'm iterating over the same list, the indexes (range) are > > not valid any more for the new list. Does anybody has some suggestions > > on how to delete the elements properly? > > Just delete the slice: > > del myList[beginIndex:endIndex+1] > > For small lists where you are deleting small chunks, this is the > simplest, most straight-forward way. > > Alternatively, create a new list excluding the bits you would have > deleted, and assign it in place: > > myList[:] = myList[:beginIndex] + myList[endIndex+1:] > > Note carefully that you aren't just re-binding the name "myList", but > assigning to the slice myList[:]. > > Then there is the old-fashioned way: iterate over the list backwards, > deleting from the end towards the front. > > for j in range(endIndex, beginIndex-1, -1): > ? ? del myList[j] > > If your list is HUGE and you have very little memory, this is probably > the least worst way. It might be slow, but it will work. > > Finally, we have this: > > myList[beginIndex:] = myList[endIndex+1:] > > -- > Steven Hi guys, A big thanks to everybody, it's amazing! Cheers From doesnotexist at franzoni.invalid Wed May 19 11:42:38 2010 From: doesnotexist at franzoni.invalid (Alan Franzoni) Date: Wed, 19 May 2010 15:42:38 GMT Subject: abc for generators? Message-ID: Hello, I was looking for an ABC for generators in python. While there's a types.GeneratorType type object - which can't be used directly and it's not an abc - and many collections-related ABCs in the collections module, there's no way to say a user-defined class as a generator, even though it could expose the very same interface as a builtin, yield-based generator. I think it would be pretty useful. comments? -- Alan Franzoni contact me at public@[mysurname].eu From python at mrabarnett.plus.com Wed May 19 11:43:00 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 19 May 2010 16:43:00 +0100 Subject: Delete files from FTP Server older then 7 days. Using ftputil and ftplib. In-Reply-To: <6da6fa93-9298-4577-89b5-d58cb126d6fe@b21g2000vbh.googlegroups.com> References: <6da6fa93-9298-4577-89b5-d58cb126d6fe@b21g2000vbh.googlegroups.com> Message-ID: <4BF40704.3000907@mrabarnett.plus.com> pilgrim773 wrote: > Hello I am new to Python programming. I need a write a script which > will delete files from a FTP server after they have reached a certain > age, like 7 days for example. I have prepared this code below, but I > get an error message: > The system cannot find the path specified: '/test123/*.*' Probably > someone can help me further? Thank you in advance! > > import os, time, ftputil > from ftplib import FTP > > ftp = FTP('127.0.0.1') > print "Automated FTP Maintainance" > print 'Logging in.' > ftp.login('admin', 'admin') > > # This is the directory that we want to go to > directory = 'test123' > print 'Changing to:' + directory > ftp.cwd(directory) > files = ftp.retrlines('LIST') > print 'List of Files:' + files > # ftp.remove('LIST') > It's better to pass the full filename instead of changing the directory because it means that you don't need to keep track of which directory you're currently in, for example: files = ftp.retrlines(directory + '/LIST') > #------------------------------------------- > now = time.time() > for f in os.listdir(directory): > if os.stat(f).st_mtime < now - 7 * 86400: > if os.directory.isfile(f): > os.remove(os.directory.join(directory, f)) The os module works with _local_ files, not the remote files on a server. You can list the files and get info about them like this: reply = [] ftp.retrlines("LIST " + directory, reply.append) 'reply' will be a list of lines, one per file, which you can then parse. It shouldn't be too difficult to write a function to hide the messy details. :-) > #except: > #exit ("Cannot delete files") Bare excepts are almost always a very bad idea. > #------------------------------------------- > > print 'Closing FTP connection' > ftp.close() > From enleverLesX_XXmcX at XmclavXeauX.com.invalid Wed May 19 12:12:08 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Wed, 19 May 2010 18:12:08 +0200 Subject: Discover PyH References: Message-ID: <4bf40ddd$0$2975$ba4acef3@reader.news.orange.fr> Bonsoir ! La d?marche me semble int?ressante. Je testerai le module quand j'aurai un peu de temps. @-salutations -- Michel Claveau From cmertes at techfak.uni-bielefeld.de Wed May 19 12:23:18 2010 From: cmertes at techfak.uni-bielefeld.de (Christian Mertes) Date: Wed, 19 May 2010 18:23:18 +0200 Subject: What's the matter with docs.python.org? Message-ID: <1274286198.6623.351.camel@Inara> by kjon 2010-03-24T16:40:21+00:00. > In Philip Semanchuk writes: > >On Mar 24, 2010, at 12:05 PM, kj wrote: > >> In the last couple of weeks, docs.python.org has been down repeatedly > >> (like right now). Has anyone else noticed this? > >http://downforeveryoneorjustme.com/docs.python.org > Very handy. Thanks! > ~K Hey kjon, I just found your mail in the archives because I've been experiencing the same weird problems and I couldn't believe they wouldn't fix their server for such a long time. I'd like to know what downforeveryoneorjustme.com does because it's so lightning fast. Pinging the server? Works for me. Looking for port 80? It's open. Connecting to it and getting a web page? That's where things start to get interesting: > $ telnet docs.python.org 80 > Trying 2001:888:2000:d::a2... > Trying 82.94.164.162... > Connected to docs.python.org. > Escape character is '^]'. > GET / HTTP/1.0 > > > > Connection closed by foreign host. ... after a really long time. The server wouldn't serve me. Opera reports a network error right away though, not waiting for a timeout. And the best part: Chrome and Firefox just get me the website. Wireshark reveals that both latter browsers get a "304 Not Modified" response and then do a lot of weird stuff involving DNS as well as HTTP to finally deliver a web page. Opera does no such thing but only sends a request to 2001:888:2000:d::a2. Yeah, right, that's an IPv6 address. I really don't understand the details of what's going on here but chances are that you also use Opera, kjon and those who replied to you didn't? I reported docs.python.org as a broken page to the Opera devs but I'm also Ccing this mail to the server admin because this seems to be a more complex problem than just a broken (if at all) web browser. Best regards, Christian -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 185 bytes Desc: This is a digitally signed message part URL: From hari2981 at gmail.com Wed May 19 12:40:01 2010 From: hari2981 at gmail.com (Harikrishnan R) Date: Wed, 19 May 2010 22:10:01 +0530 Subject: Import Module Message-ID: Hi , I have a file a.py contains from one.two import abc -------------------------------------------- is there any way to find out "one.two" the import Path of abc. ? I don't want one.two.abc . Any function or attribute which directly give one.two ? -Regards -- Harikrishan R http://harikrishnanr.wordpress.com/ From thudfoo at opensuse.us Wed May 19 12:54:13 2010 From: thudfoo at opensuse.us (member thudfoo) Date: Wed, 19 May 2010 09:54:13 -0700 Subject: What's the matter with docs.python.org? In-Reply-To: <1274286198.6623.351.camel@Inara> References: <1274286198.6623.351.camel@Inara> Message-ID: On Wed, May 19, 2010 at 9:23 AM, Christian Mertes wrote: > by kjon 2010-03-24T16:40:21+00:00. >> In Philip Semanchuk writes: >> >On Mar 24, 2010, at 12:05 PM, kj wrote: >> >> In the last couple of weeks, docs.python.org has been down repeatedly >> >> (like right now). Has anyone else noticed this? >> >http://downforeveryoneorjustme.com/docs.python.org >> Very handy. Thanks! >> ~K > > Hey kjon, > > I just found your mail in the archives because I've been experiencing the > same weird problems and I couldn't believe they wouldn't fix their server > for such a long time. I'd like to know what downforeveryoneorjustme.com does > because it's so lightning fast. Pinging the server? Works for me. Looking for > port 80? It's open. Connecting to it and getting a web page? That's where things > start to get interesting: > >> $ telnet docs.python.org 80 >> Trying 2001:888:2000:d::a2... >> Trying 82.94.164.162... >> Connected to docs.python.org. >> Escape character is '^]'. >> GET / HTTP/1.0 >> >> >> >> Connection closed by foreign host. > > ... after a really long time. The server wouldn't serve me. Opera reports a > network error right away though, not waiting for a timeout. And the best part: > Chrome and Firefox just get me the website. Wireshark reveals that both latter > browsers get a "304 Not Modified" response and then do a lot of weird stuff involving > DNS as well as HTTP to finally deliver a web page. Opera does no such thing but only > sends a request to 2001:888:2000:d::a2. Yeah, right, that's an IPv6 address. > I really don't understand the details of what's going on here but chances are > that you also use Opera, kjon and those who replied to you didn't? > > I reported docs.python.org as a broken page to the Opera devs but I'm also Ccing this > mail to the server admin because this seems to be a more complex problem than just > a broken (if at all) web browser. > > Best regards, > > ? ? ? ?Christian > Worked for me: ~/isos2burn> telnet docs.python.org 80 Trying 82.94.164.162... Connected to docs.python.org. Escape character is '^]'. GET/HTTP/1.0 302 Found

Found

The document has moved here.


Apache/2.2.9 (Debian) DAV/2 SVN/1.5.1 mod_ssl/2.2.9 OpenSSL/0.9.8g mod_wsgi/2.5 Python/2.5.2 Server at dinsdale.python.org Port 80
Connection closed by foreign host. ~/isos2burn> date Wed May 19 09:49:11 PDT 2010 From python at bdurham.com Wed May 19 13:00:22 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 19 May 2010 13:00:22 -0400 Subject: How to determine subprocess.Popen() failed when shell=True In-Reply-To: <1274129147.11923.1375533733@webmail.messagingengine.com> References: <1274129147.11923.1375533733@webmail.messagingengine.com> Message-ID: <1274288422.22019.1375896829@webmail.messagingengine.com> For the archives - solution posted at http://stackoverflow.com/questions/2861548/how-to-determine-subprocess-popen-failed-when-shelltrue Malcolm From jjposner at optimum.net Wed May 19 13:06:11 2010 From: jjposner at optimum.net (John Posner) Date: Wed, 19 May 2010 13:06:11 -0400 Subject: how to cause a request for a missing class attribute cause its calculation In-Reply-To: References: Message-ID: <4BF41A83.8010805@optimum.net> On 5/18/2010 4:54 PM, Chris Rebert wrote: > Suggested reading: http://docs.python.org/library/functions.html#property I've placed a revision to this official *property* documentation at: http://wiki.python.org/moin/AlternativeDescriptionOfProperty There's also a gentle (I hope) intro to the *property* feature on the Wiki: http://wiki.python.org/moin/ComputedAttributesUsingPropertyObjects -John From utente at esempio.net Wed May 19 13:11:51 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 19:11:51 +0200 Subject: ipython question Message-ID: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> In [39]: def f(): ....: return 42 ....: In [40]: %psource f No source found for f In [41]: i expected to see the source... From cjw at ncf.ca Wed May 19 13:19:44 2010 From: cjw at ncf.ca (cjw) Date: Wed, 19 May 2010 13:19:44 -0400 Subject: Access to comp.lang.python In-Reply-To: References: Message-ID: <4BF41DB0.6050505@ncf.ca> On 18-May-10 19:27 PM, Tim Chase wrote: > On 05/15/2010 05:34 PM, cjw wrote: >> It seems that messages are coming from a number of sources, such as >> gmane and google groups. >> >> The problem is that many messages seem to get unlinked from their >> threads. >> >> I use Thunderbird 3.0.5 and wonder whether the problem lies with the >> merge process, the server or my reader. > > While others have told you about using gmane or other sources (direct > email, etc), I haven't seen anything fly by regarding the "unlinked from > their threads" portion of your question. Thunderbird 2.0 -> 3.0 changed > the default value for mail.strict_threading from False to True. Pulling > up the config editor (essentially the about:config, buried in the > options->advanced stuff, I think; or perhaps I have the "about:config" > plugin to do that) allows you to toggle this value back to "True". This > setting controls whether threads are defined *only* by the mail header > (strict=True), or whether TB also tries to guess based on the Subject > header (strict=False). > > Toggle it (and perhaps restart TB?) and see if that helps rectify the > threading. There are a lot of folks here on c.l.p that use broken > newsreaders that don't correctly set news/threading headers. > > -tkc > > > Thanks, mine is already set to "true". Colin W. From cjw at ncf.ca Wed May 19 13:19:44 2010 From: cjw at ncf.ca (cjw) Date: Wed, 19 May 2010 13:19:44 -0400 Subject: Access to comp.lang.python In-Reply-To: References: Message-ID: <4BF41DB0.6050505@ncf.ca> On 18-May-10 19:27 PM, Tim Chase wrote: > On 05/15/2010 05:34 PM, cjw wrote: >> It seems that messages are coming from a number of sources, such as >> gmane and google groups. >> >> The problem is that many messages seem to get unlinked from their >> threads. >> >> I use Thunderbird 3.0.5 and wonder whether the problem lies with the >> merge process, the server or my reader. > > While others have told you about using gmane or other sources (direct > email, etc), I haven't seen anything fly by regarding the "unlinked from > their threads" portion of your question. Thunderbird 2.0 -> 3.0 changed > the default value for mail.strict_threading from False to True. Pulling > up the config editor (essentially the about:config, buried in the > options->advanced stuff, I think; or perhaps I have the "about:config" > plugin to do that) allows you to toggle this value back to "True". This > setting controls whether threads are defined *only* by the mail header > (strict=True), or whether TB also tries to guess based on the Subject > header (strict=False). > > Toggle it (and perhaps restart TB?) and see if that helps rectify the > threading. There are a lot of folks here on c.l.p that use broken > newsreaders that don't correctly set news/threading headers. > > -tkc > > > Thanks, mine is already set to "true". Colin W. From cjw at ncf.ca Wed May 19 13:21:37 2010 From: cjw at ncf.ca (cjw) Date: Wed, 19 May 2010 13:21:37 -0400 Subject: another question about classes and subclassing In-Reply-To: References: Message-ID: On 18-May-10 17:51 PM, Alex Hall wrote: > Hi again all, > More about classes. I am still looking into my battleship game, and I > will have several different craft. All craft have common attribs > (position, alive, and so on) but each craft may be a surface ship, > submarine, or airplane. All three are craft, but a submarine can be > submerged or not, which does not apply to a surface ship or a plane, > while a plane can be airborne or not, which is not applicable to the > other two. Is there any advantage to creating a craft class: > > class craft(): > #has attribs common to any and all craft > #end class > > then doing something like: > > class submarine(craft): > #sub-specific attribs > #end class > > How would I create a submarine, and then get at the craft-level > attribs? Come to think of it, how would I pass anything to the craft > constructor (position and alive, for example) when creating a new > submarine object? Am I even doing this right to make submarine a > subclass of craft? Thanks. > Looks OK to me. Colin W. From pavlovevidence at gmail.com Wed May 19 13:24:41 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 19 May 2010 10:24:41 -0700 (PDT) Subject: abc for generators? References: Message-ID: On May 19, 8:42?am, Alan Franzoni wrote: > Hello, > I was looking for an ABC for generators in python. While there's a > types.GeneratorType type object - which can't be used directly ?and it's > not an abc - and many collections-related ABCs in the collections > module, there's no way to say a user-defined class as a generator, even > though it could expose the very same interface as a builtin, yield-based > generator. > > I think it would be pretty useful. > > comments? collections.Iterator You don't actually need abc's to write custom iterators, BTW, the following is an iterator for instance. class Noise: def __iter__(self): return self def __next__(self): return random.random() which is equivalent to the generator def Noise(): while True: yield random.random() Carl Banks From rsomerville at sjgeophysics.com Wed May 19 13:54:55 2010 From: rsomerville at sjgeophysics.com (Robert Somerville) Date: Wed, 19 May 2010 10:54:55 -0700 Subject: Best XML python package to learn for Ubuntu Linux ? Message-ID: <4BF425EF.3070207@sjgeophysics.com> Hi; I am about to get my feet wet with Python XML, there appears to be many libraries ... can someone recommend a good package to use on Ubuntu ??? regards; Robert Somerville From philip at semanchuk.com Wed May 19 14:06:51 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 19 May 2010 14:06:51 -0400 Subject: Best XML python package to learn for Ubuntu Linux ? In-Reply-To: <4BF425EF.3070207@sjgeophysics.com> References: <4BF425EF.3070207@sjgeophysics.com> Message-ID: On May 19, 2010, at 1:54 PM, Robert Somerville wrote: > Hi; > > I am about to get my feet wet with Python XML, there appears to be > many libraries ... can someone recommend > a good package to use on Ubuntu ??? Hi Robert, xml.etree.ElementTree is in the Python standard library as of version 2.5. It was a popular 3rd party package even before it became part of the standard library, so a lot of code uses it. It's a good place to start. HTH Philip From cmertes at techfak.uni-bielefeld.de Wed May 19 14:30:42 2010 From: cmertes at techfak.uni-bielefeld.de (Christian Mertes) Date: Wed, 19 May 2010 20:30:42 +0200 Subject: What's the matter with docs.python.org? In-Reply-To: References: <1274286198.6623.351.camel@Inara> Message-ID: <1274293842.7713.32.camel@Inara> On Mi, 2010-05-19 at 09:54 -0700, member thudfoo wrote: > Worked for me: > > ~/isos2burn> telnet docs.python.org 80 > Trying 82.94.164.162... > Connected to docs.python.org. > Escape character is '^]'. > GET/HTTP/1.0 > > > 302 Found > >

Found

>

The document has moved here.

>
>
Apache/2.2.9 (Debian) DAV/2 SVN/1.5.1 mod_ssl/2.2.9 > OpenSSL/0.9.8g mod_wsgi/2.5 Python/2.5.2 Server at dinsdale.python.org > Port 80
> Interesting. You did read the content you got though, didn't you? Regards, Christian -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 185 bytes Desc: This is a digitally signed message part URL: From backgoodoo at gmail.com Wed May 19 14:38:09 2010 From: backgoodoo at gmail.com (Back9) Date: Wed, 19 May 2010 11:38:09 -0700 (PDT) Subject: how to preserve hex value Message-ID: <288ca40f-e167-4f1f-bc9b-fdb9ed612587@m33g2000vbi.googlegroups.com> Hi, When converting a hex value, I'd like to preserve the decimal position. For example, 0x0A is converted to 0A not just A in string. How do I do this? TIA From g.rodola at gmail.com Wed May 19 14:41:34 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Wed, 19 May 2010 20:41:34 +0200 Subject: Delete files from FTP Server older then 7 days. Using ftputil and ftplib. In-Reply-To: <6da6fa93-9298-4577-89b5-d58cb126d6fe@b21g2000vbh.googlegroups.com> References: <6da6fa93-9298-4577-89b5-d58cb126d6fe@b21g2000vbh.googlegroups.com> Message-ID: 2010/5/19 pilgrim773 : > Hello I am new to Python programming. I need a write a script which > will delete files from a FTP server after they have reached a certain > age, like 7 days for example. I have prepared this code below, but I > get an error message: > The system cannot find the path specified: '/test123/*.*' Probably > someone can help me further? Thank you in advance! > > import os, time, ftputil > from ftplib import FTP > > ftp = FTP('127.0.0.1') > print "Automated FTP Maintainance" > print 'Logging in.' > ftp.login('admin', 'admin') > > # This is the directory that we want to go to > directory = 'test123' > print 'Changing to:' + directory > ftp.cwd(directory) > files = ftp.retrlines('LIST') > print 'List of Files:' + files > # ftp.remove('LIST') > > #------------------------------------------- > now = time.time() > for f in os.listdir(directory): > if os.stat(f).st_mtime < now - 7 * 86400: > if os.directory.isfile(f): > os.remove(os.directory.join(directory, f)) > #except: > #exit ("Cannot delete files") > #------------------------------------------- > > print 'Closing FTP connection' > ftp.close() > > -- > http://mail.python.org/mailman/listinfo/python-list > Instead of parsing the LIST response you can use MDTM command instead (if the server supports it) which returns a standardized time-like response for every file (ftp.sendcmd('MDTM filename')). Alternatively you can do as you're doing now but using MLSD instead of LIST (again, the server must support it). MLSD returns something like this: type=file;size=156;perm=r;modify=20071029155301;unique=801cd2; music.mp3 type=dir;size=0;perm=el;modify=20071127230206;unique=801e33; ebooks type=file;size=211;perm=r;modify=20071103093626;unique=801e32; module.py This would also be a lot cheaper in terms of data exchanged between client and server and hence faster as you proceed "per-directory" instead of "per-file in every directory". Note that if the server is RFC-compliant both MDTM and MLSD times are expressed as GMT times so an extra conversion to your local time may be necessary. Hope this helps, --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From thudfoo at opensuse.us Wed May 19 15:01:27 2010 From: thudfoo at opensuse.us (member thudfoo) Date: Wed, 19 May 2010 12:01:27 -0700 Subject: how to preserve hex value In-Reply-To: <288ca40f-e167-4f1f-bc9b-fdb9ed612587@m33g2000vbi.googlegroups.com> References: <288ca40f-e167-4f1f-bc9b-fdb9ed612587@m33g2000vbi.googlegroups.com> Message-ID: On Wed, May 19, 2010 at 11:38 AM, Back9 wrote: > Hi, > > When converting a hex value, I'd like to preserve the decimal > position. > For example, 0x0A is converted to 0A not just A in string. > > How do I do this? > > TIA > -- > http://mail.python.org/mailman/listinfo/python-list > |109> '%02X' % 10 <109> '0A' From jcd at sdf.lonestar.org Wed May 19 15:06:39 2010 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Wed, 19 May 2010 15:06:39 -0400 Subject: how to preserve hex value In-Reply-To: <288ca40f-e167-4f1f-bc9b-fdb9ed612587@m33g2000vbi.googlegroups.com> References: <288ca40f-e167-4f1f-bc9b-fdb9ed612587@m33g2000vbi.googlegroups.com> Message-ID: <1274295999.4704.18.camel@jcdyer-laptop> On Wed, 2010-05-19 at 11:38 -0700, Back9 wrote: > Hi, > > When converting a hex value, I'd like to preserve the decimal > position. > For example, 0x0A is converted to 0A not just A in string. > > How do I do this? > > TIA I'm not sure I understand what your use case is, but generally speaking, it is better to treat hex values as integers (which they are) than as string (which they are not). 0x0a is an integer value of ten. There is no change of decimal position gained by prepending a zero digit. It means exactly the same thing. If you know how large a chunk is, you can multiply (or bit-shift) and add to get the behavior you're looking for. def concat(byte1, byte2): return (byte1 << 8) + byte2 >>> hex(concat(0x43, 0x0a)) 0x430a One common use case is when using hex notation to represent sequences of bytes. In this case, you may want to work with a byte string instead. To concatenate your numbers this way, convert each number to a byte using chr(x) (Python 2.x) To print it as hex, do something like this: def bytestring_to_hex(s): return '0x + ''.join('%02x' % ord(x) for x in s) However, if you need an arbitrary number of zeros preserved, you're out of luck. They are semantically meaningless in python. (Is semantically meaningless redundant?) Cheers, Cliff From utente at esempio.net Wed May 19 15:58:04 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 21:58:04 +0200 Subject: function that counts... Message-ID: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> ... how many positive integers less than n have digits that sum up to m: In [197]: def prttn(m, n): tot = 0 for i in range(n): s = str(i) sum = 0 for j in range(len(s)): sum += int(s[j]) if sum == m: tot += 1 return tot .....: In [207]: prttn(25, 10000) Out[207]: 348 any suggestion for pythonizin' it? bye From robert.kern at gmail.com Wed May 19 16:01:34 2010 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 19 May 2010 15:01:34 -0500 Subject: ipython question In-Reply-To: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> References: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> Message-ID: On 5/19/10 12:11 PM, superpollo wrote: > In [39]: def f(): > ....: return 42 > ....: > > In [40]: %psource f > No source found for f > > In [41]: > > i expected to see the source... You will want to ask IPython questions on the IPython mailing list: http://mail.scipy.org/mailman/listinfo/ipython-user The reason you do not get the source is because there is no file that contains functions defined in the interactive interpreter. %psource uses the inspect module, and the inspect module explicitly only looks in real files using the linecache module. IPython could be modified to inject fake files into the linecache, but that's a chunk of work. I am sure they would be happy to incorporate a patch if you were to provide it to them. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From utente at esempio.net Wed May 19 16:10:43 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:10:43 +0200 Subject: ipython question In-Reply-To: References: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> Message-ID: <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> Robert Kern ha scritto: > On 5/19/10 12:11 PM, superpollo wrote: >> In [39]: def f(): >> ....: return 42 >> ....: >> >> In [40]: %psource f >> No source found for f >> >> In [41]: >> >> i expected to see the source... > > You will want to ask IPython questions on the IPython mailing list: > > http://mail.scipy.org/mailman/listinfo/ipython-user > > The reason you do not get the source is because there is no file that > contains functions defined in the interactive interpreter. %psource uses > the inspect module, and the inspect module explicitly only looks in real > files but still: In [218]: def f(): .....: return 42 .....: In [219]: %save tmp.py 218 File `tmp.py` exists. Overwrite (y/[N])? y The following commands were written to file `tmp.py`: def f(): return 42 In [220]: !cat tmp.py def f(): return 42 In [221]: %psource f No source found for f From utente at esempio.net Wed May 19 16:14:43 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:14:43 +0200 Subject: ipython question In-Reply-To: <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bf446b4$0$31377$4fafbaef@reader1.news.tin.it> superpollo ha scritto: > Robert Kern ha scritto: >> On 5/19/10 12:11 PM, superpollo wrote: >>> In [39]: def f(): >>> ....: return 42 >>> ....: >>> >>> In [40]: %psource f >>> No source found for f >>> >>> In [41]: >>> >>> i expected to see the source... >> >> You will want to ask IPython questions on the IPython mailing list: >> >> http://mail.scipy.org/mailman/listinfo/ipython-user >> >> The reason you do not get the source is because there is no file that >> contains functions defined in the interactive interpreter. %psource >> uses the inspect module, and the inspect module explicitly only looks >> in real files > > but still: > > In [218]: def f(): > .....: return 42 > .....: > > In [219]: %save tmp.py 218 > File `tmp.py` exists. Overwrite (y/[N])? y > The following commands were written to file `tmp.py`: > def f(): > return 42 > > > In [220]: !cat tmp.py > def f(): > return 42 > > In [221]: %psource f > No source found for f maybe i got it: In [230]: import tmp In [231]: %psource tmp.f def f(): return 42 From malaclypse2 at gmail.com Wed May 19 16:14:54 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 19 May 2010 16:14:54 -0400 Subject: function that counts... In-Reply-To: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: > ... how many positive integers less than n have digits that sum up to m: ... > any suggestion for pythonizin' it? This is how I would do it: def prttn(m, n): """How many positive integers less than n have digits that sum up to m""" total = 0 for testval in range(n): sumofdigits = sum(int(char) for char in str(testval)) if sumofdigits == m: total += 1 return total I added a docstring to the function, saying what it does, and what the arguments are supposed to represent. I also moved the convert-to-string-and-sum-the-digits logic into a single generator expression that's passed to the builtin sum function. Oh, and I tried to use slightly more expressive variable names. -- Jerry From robert.kern at gmail.com Wed May 19 16:24:13 2010 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 19 May 2010 15:24:13 -0500 Subject: ipython question In-Reply-To: <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: On 5/19/10 3:10 PM, superpollo wrote: > Robert Kern ha scritto: >> On 5/19/10 12:11 PM, superpollo wrote: >>> In [39]: def f(): >>> ....: return 42 >>> ....: >>> >>> In [40]: %psource f >>> No source found for f >>> >>> In [41]: >>> >>> i expected to see the source... >> >> You will want to ask IPython questions on the IPython mailing list: >> >> http://mail.scipy.org/mailman/listinfo/ipython-user >> >> The reason you do not get the source is because there is no file that >> contains functions defined in the interactive interpreter. %psource >> uses the inspect module, and the inspect module explicitly only looks >> in real files > > but still: > > In [218]: def f(): > .....: return 42 > .....: > > In [219]: %save tmp.py 218 > File `tmp.py` exists. Overwrite (y/[N])? y > The following commands were written to file `tmp.py`: > def f(): > return 42 > > > In [220]: !cat tmp.py > def f(): > return 42 > > In [221]: %psource f > No source found for f So? The function object f knows nothing about the file tmp.py. If you were to import tmp and then ask for %psource tmp.f, it should work. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From lists at necoro.eu Wed May 19 16:24:42 2010 From: lists at necoro.eu (=?UTF-8?B?UmVuw6kgJ05lY29ybycgTmV1bWFubg==?=) Date: Wed, 19 May 2010 22:24:42 +0200 Subject: function that counts... In-Reply-To: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4BF4490A.50007@necoro.eu> Am 19.05.2010 21:58, schrieb superpollo: > ... how many positive integers less than n have digits that sum up to m: > > In [197]: def prttn(m, n): > tot = 0 > for i in range(n): > s = str(i) > sum = 0 > for j in range(len(s)): > sum += int(s[j]) > if sum == m: > tot += 1 > return tot > .....: > > In [207]: prttn(25, 10000) > Out[207]: 348 > > any suggestion for pythonizin' it? > > bye An idea would be: >>> def prttn(m, n): ... return sum(1 for x in range(n) if sum(map(int, str(x))) == m) A small oneliner :) (I first had "return len([x for x in ...])" but the above avoids creating an intermediate list) - Ren? -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From utente at esempio.net Wed May 19 16:25:31 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:25:31 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> Jerry Hill ha scritto: > On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: >> ... how many positive integers less than n have digits that sum up to m: > ... >> any suggestion for pythonizin' it? > > This is how I would do it: > > def prttn(m, n): > """How many positive integers less than n have digits that sum up to m""" > total = 0 > for testval in range(n): > sumofdigits = sum(int(char) for char in str(testval)) this line gives me this: TypeError: 'int' object is not callable is it some new feature in >2.5 ? > if sumofdigits == m: > total += 1 > return total > > I added a docstring to the function, saying what it does, and what the > arguments are supposed to represent. I also moved the > convert-to-string-and-sum-the-digits logic into a single generator > expression that's passed to the builtin sum function. Oh, and I tried > to use slightly more expressive variable names. > From utente at esempio.net Wed May 19 16:30:56 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:30:56 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bf44a80$0$31377$4fafbaef@reader1.news.tin.it> Ren? 'Necoro' Neumann ha scritto: > Am 19.05.2010 21:58, schrieb superpollo: >> ... how many positive integers less than n have digits that sum up to m: >> >> In [197]: def prttn(m, n): >> tot = 0 >> for i in range(n): >> s = str(i) >> sum = 0 >> for j in range(len(s)): >> sum += int(s[j]) >> if sum == m: >> tot += 1 >> return tot >> .....: >> >> In [207]: prttn(25, 10000) >> Out[207]: 348 >> >> any suggestion for pythonizin' it? >> >> bye > > An idea would be: > >>>> def prttn(m, n): > ... return sum(1 for x in range(n) if sum(map(int, str(x))) == m) TypeError: 'int' object is not callable on 2.5.4 > > A small oneliner :) > > (I first had "return len([x for x in ...])" but the above avoids > creating an intermediate list) > > - Ren? > From news1234 at free.fr Wed May 19 16:32:14 2010 From: news1234 at free.fr (News123) Date: Wed, 19 May 2010 22:32:14 +0200 Subject: Installing Lightweight Python In-Reply-To: <5b9dd21e-43c7-4603-90a7-51299e1a599b@f13g2000vbm.googlegroups.com> References: <3620ca8c-4071-4691-827d-2a578f081b8c@m21g2000vbr.googlegroups.com> <5b9dd21e-43c7-4603-90a7-51299e1a599b@f13g2000vbm.googlegroups.com> Message-ID: <4bf44ace$0$20283$426a34cc@news.free.fr> Nima Mohammadi wrote: > Well, I tried to run Python with -v option. It seems that python26.zip > is partially loaded but can't be used, because zlib is "unavailable". This is normal. the zip library itself cannot be zipped, as it is needed to unzip and extract th other libs. > > nima at nima-desktop:~/py$ ./bin/python -v > Could not find platform independent libraries > Could not find platform dependent libraries > Consider setting $PYTHONHOME to [:] > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > # zipimport: found 2509 names in /home/nima/py/lib/python26.zip > # zipimport: zlib UNAVAILABLE > 'import site' failed; traceback: > zipimport.ZipImportError: can't decompress data; zlib not available > # zipimport: zlib UNAVAILABLE > > Python 2.6.5 (r265:79063, May 17 2010, 18:36:54) > [GCC 4.4.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.path > ['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/', > '/home/nima/py/lib/python2.6/plat-linux2', '/home/nima/py/lib/ > python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old', '/home/nima/ > py/lib/lib-dynload'] > > > -- > Yours sincerely, > Nima Mohammadi From malaclypse2 at gmail.com Wed May 19 16:46:43 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 19 May 2010 16:46:43 -0400 Subject: function that counts... In-Reply-To: <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: On Wed, May 19, 2010 at 4:25 PM, superpollo wrote: > Jerry Hill ha scritto: >> ? ? ? ?sumofdigits = sum(int(char) for char in str(testval)) > > this line gives me this: > > TypeError: 'int' object is not callable > > is it some new feature in >2.5 ? No, sum() has been a builtin since Python 2.3. Based on your first post, you have probably shadowed the builtin "sum" function by assigning an integer to a variable named "sum". -- Jerry From dickinsm at gmail.com Wed May 19 16:48:46 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 19 May 2010 13:48:46 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf44a80$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <325e30b0-f7d4-4bed-9da8-d5b1e4fe0c5a@p17g2000vbe.googlegroups.com> On May 19, 9:30?pm, superpollo wrote: > Ren? 'Necoro' Neumann ha scritto: > > An idea would be: > > >>>> def prttn(m, n): > > ... ? ? ? ?return sum(1 for x in range(n) if sum(map(int, str(x))) == m) > > TypeError: 'int' object is not callable > > on 2.5.4 The TypeError is almost certainly because you've created a integer 'sum' variable in your script/interpreter session, hiding the built-in sum function. -- Mark From utente at esempio.net Wed May 19 16:58:22 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:58:22 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bf450ef$0$31372$4fafbaef@reader1.news.tin.it> Jerry Hill ha scritto: > On Wed, May 19, 2010 at 4:25 PM, superpollo wrote: >> Jerry Hill ha scritto: >>> sumofdigits = sum(int(char) for char in str(testval)) >> this line gives me this: >> >> TypeError: 'int' object is not callable >> >> is it some new feature in >2.5 ? > > No, sum() has been a builtin since Python 2.3. Based on your first > post, you have probably shadowed the builtin "sum" function by > assigning an integer to a variable named "sum". o my... thanks! In [266]: del(sum) In [267]: def prttn2(m, n): """How many positive integers less than n have digits that sum up to m""" total = 0 for testval in range(n): sumofdigits = sum(int(char) for char in str(testval)) if sumofdigits == m: total += 1 return total .....: In [275]: def prttn3(m, n): return sum(1 for x in range(n) if sum(map(int, str(x))) == m) .....: In [277]: prttn(25, 10000) Out[277]: 348 In [278]: prttn2(25, 10000) Out[278]: 348 In [279]: prttn3(25, 10000) Out[279]: 348 ok, bye! From utente at esempio.net Wed May 19 16:58:40 2010 From: utente at esempio.net (superpollo) Date: Wed, 19 May 2010 22:58:40 +0200 Subject: function that counts... In-Reply-To: <325e30b0-f7d4-4bed-9da8-d5b1e4fe0c5a@p17g2000vbe.googlegroups.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf44a80$0$31377$4fafbaef@reader1.news.tin.it> <325e30b0-f7d4-4bed-9da8-d5b1e4fe0c5a@p17g2000vbe.googlegroups.com> Message-ID: <4bf45101$0$31372$4fafbaef@reader1.news.tin.it> Mark Dickinson ha scritto: > On May 19, 9:30 pm, superpollo wrote: >> Ren? 'Necoro' Neumann ha scritto: >>> An idea would be: >>>>>> def prttn(m, n): >>> ... return sum(1 for x in range(n) if sum(map(int, str(x))) == m) >> TypeError: 'int' object is not callable >> >> on 2.5.4 > > The TypeError is almost certainly because you've created a integer > 'sum' variable in your script/interpreter session, hiding the built-in > sum function. thx From doesnotexist at franzoni.invalid Wed May 19 17:27:50 2010 From: doesnotexist at franzoni.invalid (Alan Franzoni) Date: Wed, 19 May 2010 21:27:50 GMT Subject: abc for generators? In-Reply-To: References: Message-ID: On 5/19/10 7:24 PM, Carl Banks wrote: > collections.Iterator That would just support the next() method. But enhanced generators interface - supporting coroutines as well - include send(), throw() and close(). -- Alan Franzoni contact me at public@[mysurname].eu From lists at necoro.eu Wed May 19 17:31:51 2010 From: lists at necoro.eu (=?UTF-8?B?UmVuw6kgJ05lY29ybycgTmV1bWFubg==?=) Date: Wed, 19 May 2010 23:31:51 +0200 Subject: function that counts... In-Reply-To: <4bf450ef$0$31372$4fafbaef@reader1.news.tin.it> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> <4bf450ef$0$31372$4fafbaef@reader1.news.tin.it> Message-ID: <4BF458C7.6090200@necoro.eu> Am 19.05.2010 22:58, schrieb superpollo: > > In [277]: prttn(25, 10000) > Out[277]: 348 > > In [278]: prttn2(25, 10000) > Out[278]: 348 > > In [279]: prttn3(25, 10000) > Out[279]: 348 > > ok, bye! Just because I was curios: necoro at Zakarumiy ~ % python -m timeit "import test; test.prttn(25,10000)" 10 loops, best of 3: 108 msec per loop necoro at Zakarumiy ~ % python -m timeit "import test; test.prttn2(25,10000)" 10 loops, best of 3: 157 msec per loop necoro at Zakarumiy ~ % python -m timeit "import test; test.prttn3(25,10000)" 10 loops, best of 3: 137 msec per loop Note: This is probably not representative ... just a quick check to get a raw feeling. - Ren? -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From steve-REMOVE-THIS at cybersource.com.au Wed May 19 17:45:44 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 May 2010 21:45:44 GMT Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> <4bf450ef$0$31372$4fafbaef@reader1.news.tin.it> Message-ID: <4bf45c08$0$8837$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 22:58:22 +0200, superpollo wrote: > In [266]: del(sum) del is a statement, not a function, so the brackets are pointless. This is like writing: x = (1) instead of x = 1 `del sum` is all you need. -- Steven From steve-REMOVE-THIS at cybersource.com.au Wed May 19 17:51:23 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 19 May 2010 21:51:23 GMT Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: > ... how many positive integers less than n have digits that sum up to m: > > In [197]: def prttn(m, n): Does the name "prttn" mean anything? I'm afraid I keep reading it as a mispelling of "print n". [...] > s = str(i) > sum = 0 > for j in range(len(s)): > sum += int(s[j]) Rather than iterating over an index j = 0, 1, 2, ... and then fetching the jth character of the string, you can iterate over the characters directly. So the inner loop is better written: for c in s: sum += int(c) -- Steven From leehwasoo at gmail.com Wed May 19 17:53:40 2010 From: leehwasoo at gmail.com (Back9) Date: Wed, 19 May 2010 14:53:40 -0700 (PDT) Subject: struct Message-ID: <8a4bba29-b5ca-49ed-806f-9e7a87f28ecf@u7g2000vbq.googlegroups.com> Can anyone explain the difference between f and d in struct unpack? When using them, some data work in either one not both. To me it seems to be same, TIA From gherron at islandtraining.com Wed May 19 18:07:41 2010 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 19 May 2010 15:07:41 -0700 Subject: struct In-Reply-To: <8a4bba29-b5ca-49ed-806f-9e7a87f28ecf@u7g2000vbq.googlegroups.com> References: <8a4bba29-b5ca-49ed-806f-9e7a87f28ecf@u7g2000vbq.googlegroups.com> Message-ID: <4BF4612D.3070201@islandtraining.com> On 05/19/2010 02:53 PM, Back9 wrote: > Can anyone explain the difference between f and d in struct unpack? > When using them, some data work in either one not both. > To me it seems to be same, > > TIA > 'f' is single precision float (32 bits), and 'd' is a double precision float (64 bits) Gary Herron From iurisilvio at gmail.com Wed May 19 18:12:30 2010 From: iurisilvio at gmail.com (Iuri) Date: Wed, 19 May 2010 19:12:30 -0300 Subject: compile() error Message-ID: >>> compile("for i in [1,2,3]:\n pass\n#end\n", "test_file.py", "exec") at 0x266a378, file "test_file.py", line 1> >>> compile("for i in [1,2,3]:\n pass\n#end", "test_file.py", "exec") Traceback (most recent call last): File "", line 1, in File "", line 2, in cptest File "test_file.py", line 3 #end ^ SyntaxError: invalid syntax I guess these commands explain the problem. Any ideas about what is happening? Regards, iuri -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin at python.org Wed May 19 18:31:31 2010 From: benjamin at python.org (Benjamin Peterson) Date: Wed, 19 May 2010 22:31:31 +0000 (UTC) Subject: compile() error References: Message-ID: Iuri gmail.com> writes: > Any ideas about what is happening? Until Python 2.7/3.2, compile() does't like sources which don't end in a newline. From vincent at vincentdavis.net Wed May 19 18:35:42 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Wed, 19 May 2010 16:35:42 -0600 Subject: Python Script for Website Mirroring In-Reply-To: References: Message-ID: Probably need a little more info to help. Are you running both sites, are there database involved....? If it is a simple site you could just transfer with ftp and have the script updated any urls. Vincent On Wed, May 19, 2010 at 8:21 AM, Kevin Rea wrote: > Hello Folks: > > Can you please point me to a decent Python script(s) that I could customize > to do automatic Website mirroring? > > Thanks Much! > Kevin > > -- > http://mail.python.org/mailman/listinfo/python-list > > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From iurisilvio at gmail.com Wed May 19 18:39:42 2010 From: iurisilvio at gmail.com (Iuri) Date: Wed, 19 May 2010 19:39:42 -0300 Subject: compile() error In-Reply-To: References: Message-ID: Thanks, Benjamin. I used Python 2.6 to these tests. []s iuri On Wed, May 19, 2010 at 7:31 PM, Benjamin Peterson wrote: > Iuri gmail.com> writes: > > Any ideas about what is happening? > > Until Python 2.7/3.2, compile() does't like sources which don't end in a > newline. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cmertes at techfak.uni-bielefeld.de Wed May 19 18:49:34 2010 From: cmertes at techfak.uni-bielefeld.de (Christian Mertes) Date: Thu, 20 May 2010 00:49:34 +0200 Subject: Python Script for Website Mirroring In-Reply-To: References: Message-ID: <1274309374.7713.300.camel@Inara> On Mi, 2010-05-19 at 16:35 -0600, Vincent Davis wrote: > If it is a simple site you could just transfer with ftp Or rsync -a or wget -m ... like tools that were specifically made for this task. Therefore something like subprocess.call(["rsync", "-az", "-e", "ssh", "--delete", source, target]) should be part of your Python script I guess ;) Regards, Christian -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 185 bytes Desc: This is a digitally signed message part URL: From kaklis at gmail.com Wed May 19 18:54:01 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Wed, 19 May 2010 15:54:01 -0700 (PDT) Subject: client server console app with cmd library Message-ID: <5577f90a-e8d9-43b4-bad5-9a10b17a2fdd@e28g2000vbd.googlegroups.com> Hi to all, i need some hints about a console application i' m trying. I want to make it act as a client and as a server at a same time. And since it is a console application i' m using cmd library. I want something that works like asterisk. while working with my app i want to listen for incoming requests, that they appear automatically at my console. Any design considerations? Do i have to use threads? Please i want your advice. Any examples somewhere? Thanks in advance! Antonis From rhodri at wildebst.demon.co.uk Wed May 19 19:27:24 2010 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 20 May 2010 00:27:24 +0100 Subject: What's the matter with docs.python.org? References: Message-ID: On Wed, 19 May 2010 17:23:18 +0100, Christian Mertes wrote: > I reported docs.python.org as a broken page to the Opera devs but I'm > also Ccing this > mail to the server admin because this seems to be a more complex problem > than just > a broken (if at all) web browser. It's been working fine for me, using Opera on Window and Ubuntu, for the last week or so. -- Rhodri James *-* Wildebeeste Herder to the Masses From aahz at pythoncraft.com Wed May 19 19:41:10 2010 From: aahz at pythoncraft.com (Aahz) Date: 19 May 2010 16:41:10 -0700 Subject: Classes and threading References: <-cWdne10J4LF_m7WnZ2dnUVZ_jmdnZ2d@giganews.com> <85hla5FjqlU2@mid.individual.net> Message-ID: In article , Christian Heimes wrote: >> >> class nThread(threading.Thread): >> def __init__(self, *args, **kwds): >> threading.Thread.__init__(self, *args, **kwds) >> # your other stuff here > >Since Thread is a new style class, this should read: > >class NThread(threading.thread): > def __init__(self, *args, **kwargs): > super(NThread, self).__init__(*args, **kwargs) "Should" is too strong. There are plenty of reasons for wanting to avoid the mess of super(). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From aahz at pythoncraft.com Wed May 19 19:42:49 2010 From: aahz at pythoncraft.com (Aahz) Date: 19 May 2010 16:42:49 -0700 Subject: What's the matter with docs.python.org? References: Message-ID: In article , Christian Mertes wrote: > > $ telnet docs.python.org 80 > Trying 2001:888:2000:d::a2... > Trying 82.94.164.162... > Connected to docs.python.org. > Escape character is '^]'. IPv6 has sometimes been problematical -- try disabling it. Also, I think you need to pass the host HTTP header to access docs.python.org -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From jurgen.erhard at gmail.com Wed May 19 19:58:59 2010 From: jurgen.erhard at gmail.com (=?UTF-8?Q?J=C3=BCrgen_Erhard?=) Date: Thu, 20 May 2010 01:58:59 +0200 Subject: KaPy -- Karlsruhe Python User Group meeting, 2010-05-21, 19:00 Message-ID: The Karlsruhe Python User Group (KaPy) meets again. Friday, 2010-04-16 (May 21st) at 19:00 (7pm) in the rooms of Entropia eV (the local affiliate of the CCC). See http://entropia.de/wiki/Anfahrt on how to get there. For your calendars: meetings are held monthly, on the 3rd Friday. Bye, J PS: Sorry for the late announcement. From pavlovevidence at gmail.com Wed May 19 20:04:16 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 19 May 2010 17:04:16 -0700 (PDT) Subject: abc for generators? References: Message-ID: <84f37e28-76aa-4b86-918d-d52d3860b180@c13g2000vbr.googlegroups.com> On May 19, 2:27?pm, Alan Franzoni wrote: > On 5/19/10 7:24 PM, Carl Banks wrote: > > > collections.Iterator > > That would just support the next() method. But enhanced generators > interface - supporting coroutines as well - include send(), throw() and > close(). Hmm, don't know. Maybe you could contribute one, it sounds like a rather unobjectionable idea likely to be accepted into Python. Carl Banks From tjreedy at udel.edu Wed May 19 20:09:23 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 May 2010 20:09:23 -0400 Subject: ipython question In-Reply-To: <4bf446b4$0$31377$4fafbaef@reader1.news.tin.it> References: <4bf41bd7$0$31375$4fafbaef@reader1.news.tin.it> <4bf445c4$0$31377$4fafbaef@reader1.news.tin.it> <4bf446b4$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: On 5/19/2010 4:14 PM, superpollo wrote: >> In [219]: %save tmp.py 218 >> File `tmp.py` exists. Overwrite (y/[N])? y >> The following commands were written to file `tmp.py`: >> def f(): >> return 42 >> >> >> In [220]: !cat tmp.py >> def f(): >> return 42 >> >> In [221]: %psource f >> No source found for f > > maybe i got it: > > In [230]: import tmp > > In [231]: %psource tmp.f > def f(): > return 42 I use IDLE, write functions and other code as desired in a temp file to begin with, hit F5, and the window with source stays around until closef it and the file until deleted. From steve-REMOVE-THIS at cybersource.com.au Wed May 19 20:52:06 2010 From: steve-REMOVE-THIS at cybersource.com.au (Steven D'Aprano) Date: 20 May 2010 00:52:06 GMT Subject: compile() error References: Message-ID: <4bf487b5$0$8837$c3e8da3@news.astraweb.com> On Wed, 19 May 2010 22:31:31 +0000, Benjamin Peterson wrote: > Iuri gmail.com> writes: >> Any ideas about what is happening? > > Until Python 2.7/3.2, compile() does't like sources which don't end in a > newline. Are you sure about that? >>> x = compile("print __import__('sys').version, 'see ma, no newline'", "", "single") >>> exec x 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] see ma, no newline The original post isn't showing up for me, so I don't know the full context, but it seems to me that compile can deal with the lack of newline. >>> x = compile("""import sys ... print sys.version ... print 'see ma, still no final newline!'""", "", "exec") >>> exec x 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] see ma, still no final newline! -- Steven From Eric_Dexter at msn.com Wed May 19 20:57:22 2010 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Wed, 19 May 2010 17:57:22 -0700 (PDT) Subject: links button gone from python.org Message-ID: <290f2f31-0893-469a-a12c-49eff9ffbf6f@y21g2000vba.googlegroups.com> I noticed that that the link to that section is gone. The page seems to be there when I use the url that is stored on my computer. Unrelated but I will mention that It is sad to see that dr dobs python newsletter has vanished, I enjoyed reading that from time to time. From iurisilvio at gmail.com Wed May 19 21:06:14 2010 From: iurisilvio at gmail.com (Iuri) Date: Wed, 19 May 2010 22:06:14 -0300 Subject: compile() error In-Reply-To: <4bf487b5$0$8837$c3e8da3@news.astraweb.com> References: <4bf487b5$0$8837$c3e8da3@news.astraweb.com> Message-ID: Steven, it works fine to some cases. I have problem only when last line is a comment and before it I have an indentation. It is a specific case, and it is not a common case. >>> compile("for i in [1,2,3]:\n pass\n#end", "test_file.py", "exec") What I understanded about Benjamin's answer is compile() without a new line at the end has an indetermined behaviour, so in some cases it works. Iuri de Silvio On Wed, May 19, 2010 at 9:52 PM, Steven D'Aprano < steve-REMOVE-THIS at cybersource.com.au> wrote: > On Wed, 19 May 2010 22:31:31 +0000, Benjamin Peterson wrote: > > > Iuri gmail.com> writes: > >> Any ideas about what is happening? > > > > Until Python 2.7/3.2, compile() does't like sources which don't end in a > > newline. > > > Are you sure about that? > > > >>> x = compile("print __import__('sys').version, 'see ma, no newline'", > "", "single") > >>> exec x > 2.5 (r25:51908, Nov 6 2007, 16:54:01) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] see ma, no newline > > > The original post isn't showing up for me, so I don't know the full > context, but it seems to me that compile can deal with the lack of > newline. > > > >>> x = compile("""import sys > ... print sys.version > ... print 'see ma, still no final newline!'""", "", "exec") > >>> exec x > 2.5 (r25:51908, Nov 6 2007, 16:54:01) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] > see ma, still no final newline! > > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Wed May 19 21:12:24 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 19 May 2010 21:12:24 -0400 Subject: compile() error In-Reply-To: <4bf487b5$0$8837$c3e8da3@news.astraweb.com> References: <4bf487b5$0$8837$c3e8da3@news.astraweb.com> Message-ID: On Wed, May 19, 2010 at 8:52 PM, Steven D'Aprano wrote: > On Wed, 19 May 2010 22:31:31 +0000, Benjamin Peterson wrote: >> Iuri gmail.com> writes: >>> Any ideas about what is happening? >> >> Until Python 2.7/3.2, compile() does't like sources which don't end in a >> newline. It appears to be this bug: http://bugs.python.org/issue1184112 which is still open. Maybe a fix got checked in without the bug being closed? I don't have 2.7 or 3.2 here to test with. > The original post isn't showing up for me, so I don't know the full > context, but it seems to me that compile can deal with the lack of > newline. The original example was: compile("for i in [1,2,3]:\n pass\n#end", "test_file.py", "exec") Bug 1184112 is only triggered with an indented block followed by a comment with no newline following the comment. -- Jerry From frank.zhu.mingyu at gmail.com Wed May 19 21:14:00 2010 From: frank.zhu.mingyu at gmail.com (frank zhu) Date: Wed, 19 May 2010 21:14:00 -0400 Subject: Fwd: question on logging module - solved Message-ID: FYI. ---------- Forwarded message ---------- From: Cameron Simpson Date: Wed, May 19, 2010 at 6:18 PM Subject: Re: question on logging module To: frank zhu On 19May2010 11:55, frank zhu wrote: | Thanks Cameron. That was the problem. I copied the sample code and named it | logging.py. which was bad. You might want to post this info to the list to save follow-on discussion. One way to check that what you want actually happened is like this: [/Users/cameron]g4*> python Python 2.6.5 (r265:79063, May 17 2010, 14:44:07) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> sorted(logging.__dict__.keys()) which will report the names in what you imported. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From Rick at home.com Wed May 19 21:35:03 2010 From: Rick at home.com (Rick at home.com) Date: Wed, 19 May 2010 21:35:03 -0400 Subject: Display file names in Tkinter Listbox Message-ID: Hello, My first attenpt at a simple python Tkinter application. I wanted to see how to load file names into a listbox from a menu. This is what I got until the part of displaying the file names in a listbox, which I could not figfure out how to do? Any help would be appreciated. Trying to do this as simple as possible to understand. The "print fileNames" does work but how to display it in listbox? from Tkinter import * from tkFileDialog import askopenfilenames class MyCode: def __init__(self): root = Tk() menubar = Menu(root) filemenu = Menu(menubar) lbox = Listbox(root, width=50).pack() menubar.add_cascade(label='File', menu=filemenu) filemenu.add_command(label='New Project') filemenu.add_command(label='Load Files...', command=self.OnLoad) filemenu.add_command(label='Exit', command=root.quit) root.config(menu=menubar) root.mainloop() def OnLoad(self): fileNames = askopenfilenames(filetypes=[('Split Files', '*')]) print fileNames myApp = MyCode() From chardster at gmail.com Wed May 19 21:36:22 2010 From: chardster at gmail.com (Richard Thomas) Date: Wed, 19 May 2010 18:36:22 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <75cf168b-9d67-4602-9201-774cc8dd48e9@z33g2000vbb.googlegroups.com> For this kind of problem you should avoid all that stringification. I find it best to deal with sequences of digits of a fixed length and go from there. For example: def count1(m, n, cache={}): """Number of digit sequences of length `n` summing to `m`.""" if n < 0 or m < 0: return 0 elif n == 0: return int(m == 0) elif (m, n) in cache: return cache[m, n] # This is an optimisation using the combinatoric choose function. #elif m < 10: # result = choose(n + m - 1, n - 1) else: result = 0 for digit in xrange(min(10, m + 1)): result += count1(m - digit, n - 1) cache[m, n] = result return result Notice the caching of results. With this we can compute the required thing quite easily: def count2(m, n): """Number of numbers less than `n` whose digits sum to `m`.""" result = 0 digits = map(int, str(n)) length = len(digits) for idx, digit in enumerate(digits): for seq_digit in xrange(digit): seq_limit = m - seq_digit seq_length = length - idx - 1 result += count1(seq_limit, seq_length) m -= digit return result Essentially we move through the number left to right, choose digits less than the digit in the number and count digit sequences to fill the remainder. Then fix the actual digit and step forward. An approach like this avoids the relatively slow stringification process and makes decent use of caching and iteration (both easy and efficient in Python). In [1]: count2(25, 10000) Out[1]: 348 In [2]: timeit count2(25, 10000) 100000 loops, best of 3: 12.6 us per loop From nobrac at nospam.tampabay.rr.com Wed May 19 22:27:39 2010 From: nobrac at nospam.tampabay.rr.com (Carbon) Date: 20 May 2010 02:27:39 GMT Subject: Newbie Alert: subprocess.call Message-ID: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> I am new to Python and am trying to write a GUI wrapper script in python 2.5 to get username and passwords from Linux users to send as options to run an app on a 2X terminal server. I came across the easygui module and its multpasswordbox function, which made popping a dialog box and storing the usernames very painless. However, subprocess.call as implemented below doesn't work. For some reason the "-s ts.mycompany.org:80" parameter is being interpreted differently by the application when sent from the python script than it does when sent from the BASH script below. The :80 is the default port so it isn't technically required, but the script doesn't work without it either. Any ideas where I should look? Is subprocess.call the best way to do what I want? Any advice would be most appreciated. Here's the broken bit: print "Reply was:", fieldValues print "Reply was:", fieldValues[0], fieldValues[1] subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u fieldValues [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d corp", "-S local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"]) Output: me at work:~/bin$ ./demo2.py Reply was: ['MyUsername', 'MyPassword'] Reply was: MyUsername MyPassword ERROR in CTcpConnector: ts.mycompany.org: unable to resolve host Error 7: TCP/IP connection: unable to resolve host. This BASH script runs correctly: me at work:~/bin$ cat 2xconnect #!/bin/bash USER=$1 PASS=$2 /opt/2X/Client/bin/appserverclient \ -u "$USER" \ -p "$PASS" \ -s ts.mycompany.org:80 \ -d corp \ -S local \ -c 16 \ -e 0xF \ -l 0x0409 \ -m 2G \ -a "#1" From pmaupin at gmail.com Wed May 19 22:38:07 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Wed, 19 May 2010 19:38:07 -0700 (PDT) Subject: Newbie Alert: subprocess.call References: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> Message-ID: On May 19, 9:27?pm, Carbon wrote: > I am new to Python and am trying to write a GUI wrapper script in python > 2.5 to get username and passwords from Linux users to send as options to > run an app on a 2X terminal server. I came across the easygui module and > its multpasswordbox function, which made popping a dialog box and storing > the usernames very painless. > > However, subprocess.call as implemented below doesn't work. For some > reason the "-s ts.mycompany.org:80" parameter is being interpreted > differently by the application when sent from the python script than it > does when sent from the BASH script below. The :80 is the default port so > it isn't technically required, but the script doesn't work without it > either. > > Any ideas where I should look? Is subprocess.call the best way to do what > I want? Any advice would be most appreciated. > > Here's the broken bit: > > print "Reply was:", fieldValues > print "Reply was:", fieldValues[0], fieldValues[1] > > subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u fieldValues > [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d corp", "-S > local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"]) > > Output: > > me at work:~/bin$ ./demo2.py > Reply was: ['MyUsername', 'MyPassword'] > Reply was: MyUsername MyPassword > > ERROR in CTcpConnector: ?ts.mycompany.org: unable to resolve host > Error 7: TCP/IP connection: unable to resolve host. > > This BASH script runs correctly: > me at work:~/bin$ cat 2xconnect > #!/bin/bash > > USER=$1 > PASS=$2 > > /opt/2X/Client/bin/appserverclient \ > -u "$USER" \ > -p "$PASS" \ > -s ts.mycompany.org:80 \ > -d corp \ > -S local \ > -c 16 \ > -e 0xF \ > -l 0x0409 \ > -m 2G \ > -a "#1" I think, for example, instead of "-d corp", you want "-d" and "corp" in your list. I usually make a string like I would pass to bash, and then do .split() on it to get the list. This works fine unless you need embedded spaces anywhere. Regards, Pat From ben+python at benfinney.id.au Wed May 19 23:28:12 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 20 May 2010 13:28:12 +1000 Subject: Newbie Alert: subprocess.call References: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> Message-ID: <87mxvvgskz.fsf@benfinney.id.au> Patrick Maupin writes: > On May 19, 9:27?pm, Carbon wrote: > > subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u > > fieldValues [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d > > corp", "-S local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"]) As Patrick says, you need to give the arguments to the command as the shell would pass them. That means option arguments separate from value arguments, etc. > I think, for example, instead of "-d corp", you want "-d" and "corp" > in your list. Right. > I usually make a string like I would pass to bash, and then do > .split() on it to get the list. This works fine unless you need > embedded spaces anywhere. Better is to use ?shlex.split? to split the string as a shell parser would do . -- \ ?Not using Microsoft products is like being a non-smoker 40 or | `\ 50 years ago: You can choose not to smoke, yourself, but it's | _o__) hard to avoid second-hand smoke.? ?Michael Tiemann | Ben Finney From python at bdurham.com Wed May 19 23:34:13 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 19 May 2010 23:34:13 -0400 Subject: How to unescape a raw string? Message-ID: <1274326453.19171.1375982237@webmail.messagingengine.com> How can I unescape a raw string so that it behaves as a non-raw string? For example, if I read the string "\n\t A B C\" D E F \xa0 \u1234" from a text file, how can I convert (unescape?) this string so that \n, \t, \", \x, and \u get converted to a newline, tab, double quote, hex encoded and unicode encoded chars? I know I can do this explictly via a series of .replace() methods, but certainly there must be a built-in way to do this on a generic basis? Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed May 19 23:36:32 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 19 May 2010 20:36:32 -0700 Subject: Newbie Alert: subprocess.call In-Reply-To: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> References: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> Message-ID: On Wed, May 19, 2010 at 7:27 PM, Carbon wrote: > I am new to Python and am trying to write a GUI wrapper script in python > 2.5 to get username and passwords from Linux users to send as options to > run an app on a 2X terminal server. I came across the easygui module and > its multpasswordbox function, which made popping a dialog box and storing > the usernames very painless. > > However, subprocess.call as implemented below doesn't work. For some > reason the "-s ts.mycompany.org:80" parameter is being interpreted > differently by the application when sent from the python script than it > does when sent from the BASH script below. The :80 is the default port so > it isn't technically required, but the script doesn't work without it > either. > > Any ideas where I should look? Is subprocess.call the best way to do what > I want? Any advice would be most appreciated. > > > Here's the broken bit: > > print "Reply was:", fieldValues > print "Reply was:", fieldValues[0], fieldValues[1] > > subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u fieldValues > [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d corp", "-S > local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"]) RTFineM (http://docs.python.org/library/subprocess.html#subprocess.Popen ). Verbatim quote, emphasis mine: >>> command_line = raw_input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print args ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success! ***Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements***, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements. Cheers, Chris -- http://blog.rebertia.com From jjposner at optimum.net Wed May 19 23:40:06 2010 From: jjposner at optimum.net (John Posner) Date: Wed, 19 May 2010 23:40:06 -0400 Subject: function that counts... In-Reply-To: <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> Message-ID: <4bf4af26$0$7594$607ed4bc@cv.net> On 5/19/2010 5:51 PM, Steven D'Aprano wrote: > On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: > > > Rather than iterating over an index j = 0, 1, 2, ... and then fetching > the jth character of the string, you can iterate over the characters > directly. So the inner loop is better written: > > for c in s: > sum += int(c) > Or, as a one-liner (and not shadowing the built-in *sum* function): mysum = sum(map(int, str(i))) -John From clp2 at rebertia.com Wed May 19 23:42:55 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 19 May 2010 20:42:55 -0700 Subject: How to unescape a raw string? In-Reply-To: <1274326453.19171.1375982237@webmail.messagingengine.com> References: <1274326453.19171.1375982237@webmail.messagingengine.com> Message-ID: On Wed, May 19, 2010 at 8:34 PM, wrote: > How can I unescape a raw string so that it behaves as a non-raw string? That's not what the notion of raw strings in Python technically means, but anyway... > For example, if I read the string "\n\t A B C\" D E F \xa0 \u1234" I'll assume you're quoting the file contents itself verbatim here, rather than a Python string literal (which would require doubling up on the backslashes). > from a > text file, how can I convert (unescape?) this string so that \n, \t, \", \x, > and \u get converted to a newline, tab, double quote, hex encoded and > unicode encoded chars? > > I know I can do this explictly via a series of .replace() methods, but > certainly there must be a built-in way to do this on a generic basis? new_string = your_string.decode('string_escape') Cheers, Chris -- http://blog.rebertia.com From python at bdurham.com Wed May 19 23:53:59 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 19 May 2010 23:53:59 -0400 Subject: Best practice for string substition with gettext Message-ID: <1274327639.21961.1375982987@webmail.messagingengine.com> Looking for best practice advice on what string substitution technique to use when using gettext(). Or do all techniques apply equally? I can think of at least 3 string techniques: 1. Classic "%" based formatting: "My name is %(name)s" % locals() 2. .format() based formatting: "My name is {name}".format( locals() ) 3. string.Template.safe_substitute() import string template = string.Template( "My name is ${name}" ) template.safe_substitute( locals() ) The advantage of the string.Template technique is that a translated string with with an incorrectly spelled variable reference can still yield a usable string value while the other techniques unconditionally raise an exception. The downside of the string.Template technique appears to be the inability for one to customize how a variable is formatted (padding, justification, width, etc). Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Thu May 20 00:13:28 2010 From: python at bdurham.com (python at bdurham.com) Date: Thu, 20 May 2010 00:13:28 -0400 Subject: How to unescape a raw string? In-Reply-To: References: <1274326453.19171.1375982237@webmail.messagingengine.com> Message-ID: <1274328808.24186.1375984875@webmail.messagingengine.com> Hi Chris, > That's not what the notion of raw strings in Python technically means, but anyway... Agree - I was having a difficult time trying to describe my dilemma - thanks for hanging in there with my rather awkward intro :) > I'll assume you're quoting the file contents itself verbatim here, rather than a Python string literal (which would require doubling up on the backslashes). Yes. > new_string = your_string.decode('string_escape') That's just the clue I needed. The actual decoder I needed turned out to be 'unicode_escape' because of my embedded \uxxxx markup. new_string = your_string.decode('unicode_escape') Thank you for your help Chris! Regards, Malcolm From pmaupin at gmail.com Thu May 20 00:29:29 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Wed, 19 May 2010 21:29:29 -0700 (PDT) Subject: Newbie Alert: subprocess.call References: <4bf49e1b$0$4855$9a6e19ea@unlimited.newshosting.com> <87mxvvgskz.fsf@benfinney.id.au> Message-ID: On May 19, 10:28?pm, Ben Finney wrote: > Better is to use ?shlex.split? to split the string as a shell parser > would do . Good point. I always forget about shlex.split because I'm usually passing (relatively) constant strings with no funny quoting. Regards, Pat From wuwei23 at gmail.com Thu May 20 00:40:19 2010 From: wuwei23 at gmail.com (alex23) Date: Wed, 19 May 2010 21:40:19 -0700 (PDT) Subject: help need to write a python spell checker References: <49bffe0f-00a7-47a2-a857-1c1e35ac8870@p17g2000vbe.googlegroups.com> Message-ID: <9450223d-70ab-4b57-9dc7-0a34016c64d8@11g2000prv.googlegroups.com> Patrick Maupin wrote: > Although it makes > perfect sense, I never really thought much about the possibility that > the school year would be "upside down" "down under"... Yes, having the school year run within the actual year instead of across two is such a topsy-turvy concept, it's pretty obvious the blood is constantly rushing to our heads ;) From jmcmonagle at NO.SPAM.velseis.com.au Thu May 20 01:36:59 2010 From: jmcmonagle at NO.SPAM.velseis.com.au (John McMonagle) Date: Thu, 20 May 2010 15:36:59 +1000 Subject: Display file names in Tkinter Listbox In-Reply-To: References: Message-ID: <4BF4CA7B.6000008@NO.SPAM.velseis.com.au> Rick at home.com wrote: > Hello, > > My first attenpt at a simple python Tkinter application. I wanted to > see how to load file names into a listbox from a menu. This is what I > got until the part of displaying the file names in a listbox, which I > could not figfure out how to do? > > Any help would be appreciated. Trying to do this as simple as possible > to understand. > > The "print fileNames" does work but how to display it in listbox? > > from Tkinter import * > from tkFileDialog import askopenfilenames > > class MyCode: > def __init__(self): > root = Tk() > > menubar = Menu(root) > filemenu = Menu(menubar) > > lbox = Listbox(root, width=50).pack() Your problem is the above line of code. Here you are assigning the return value of the pack (None if I recall). Later when you want to put things in the Listbox you don't have the widget reference anymore. It's probably a good idea to make the Listbox widget an attribute of your class so you can use it in class methods without having to pass it as an argument. So, change the above line of code to: self.lbox = Listbox(root, width=50) self.lbox.pack() > > menubar.add_cascade(label='File', menu=filemenu) > filemenu.add_command(label='New Project') > filemenu.add_command(label='Load Files...', command=self.OnLoad) > > > filemenu.add_command(label='Exit', command=root.quit) > > root.config(menu=menubar) > > root.mainloop() > > > def OnLoad(self): > fileNames = askopenfilenames(filetypes=[('Split Files', '*')]) > print fileNames > Now that you've got a reference to your Listbox widget that is an attribute of your class, you should be able to insert the file names into the Listbox like so. self.lbox.insert(0, fileNames) Regards, John From sanamsingh at hotmail.com Thu May 20 01:51:19 2010 From: sanamsingh at hotmail.com (sanam singh) Date: Thu, 20 May 2010 05:51:19 +0000 Subject: error importing numpy Message-ID: Hi, when i import numpy in python i get following error : Python 2.6.5 (r265:79063, May 2 2010, 10:47:11) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy Traceback (most recent call last): File "", line 1, in ImportError: No module named numpy however when i do sudo apt-get install python-numpy i get : Reading package lists... Done Building dependency tree Reading state information... Done python-numpy is already the newest version. 0 upgraded, 0 newly installed, 0 to remove and 118 not upgraded. please help me . Thanks. _________________________________________________________________ Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rogerb at rogerbinns.com Thu May 20 01:58:34 2010 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 19 May 2010 22:58:34 -0700 Subject: Loading C extension from memory In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/13/2010 06:14 AM, mk wrote: > I wonder if there is a way to load C extension from in-memory object, > not from the file on the disk? > > I'm asking bc I would like to download C extensions over network and > load them into Python interpreter (without storing the C extension in > file on the disk). You could download the C source over the network, compile and use that. It has the advantage of working on all platforms where you have a compiler so you wouldn't have to have the same extension compiled for Mac, Linux, Windows, 32 and 64 bit. If the local machine doesn't have a compiler you can even use libtcc or something newer. For example see this 3 year old page, as well as links at the bottom: http://www.cs.tut.fi/~ask/cinpy/ Roger -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iEYEARECAAYFAkv0z4UACgkQmOOfHg372QQ1UQCg2+ODiHMzi36//gG3gK6j4Uib 2u8AoMI2LXU7BFYa7Jn5b+vF42/EnNYU =RWO+ -----END PGP SIGNATURE----- From lists at cheimes.de Thu May 20 02:17:26 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 May 2010 08:17:26 +0200 Subject: Loading C extension from memory In-Reply-To: References: Message-ID: mk wrote: > I wonder if there is a way to load C extension from in-memory object, > not from the file on the disk? No, that's not possible since Python depends on the operating system. A lot of operating systems require a physical file to load the shared library from. Python uses dlopen() on most Un*x platforms and LoadLibraryEx() on Windows. From cmertes at techfak.uni-bielefeld.de Thu May 20 02:19:07 2010 From: cmertes at techfak.uni-bielefeld.de (Christian Mertes) Date: Thu, 20 May 2010 08:19:07 +0200 Subject: What's the matter with docs.python.org? In-Reply-To: References: Message-ID: <1274336347.4612.40.camel@Inara> On Mi, 2010-05-19 at 16:42 -0700, Aahz wrote: > > IPv6 has sometimes been problematical -- try disabling it. Wow, can I have that on a t-shirt? ;) > Also, I think you need to pass the host HTTP header to access > docs.python.org Look, I don't really want to read Python docs via telnet. I basically wanted to point out that there is strange behaviour and someone might feel responsible and look into it. Unfortunately the webmaster at docs.python.org address doesn't seem to work which might be explained by the fact that there is no mx record for this domain. Anyway, it currently works with both Opera and I-sit-in-Siberia-style telnet. Have a nice day, Christian PS: I think I'll get off the list again because with my broken evolution mail filters it's just too much traffic. So if there should be another reply, please put me in the Cc. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 185 bytes Desc: This is a digitally signed message part URL: From gherron at islandtraining.com Thu May 20 02:30:50 2010 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 19 May 2010 23:30:50 -0700 Subject: How to unescape a raw string? In-Reply-To: <1274326453.19171.1375982237@webmail.messagingengine.com> References: <1274326453.19171.1375982237@webmail.messagingengine.com> Message-ID: <4BF4D71A.6030201@islandtraining.com> On 05/19/2010 08:34 PM, python at bdurham.com wrote: > How can I unescape a raw string so that it behaves as a non-raw string? > For example, if I read the string "\n\t A B C\" D E F \xa0 \u1234" > from a text file, how can I convert (unescape?) this string so that > \n, \t, \", \x, and \u get converted to a newline, tab, double quote, > hex encoded and unicode encoded chars? > I know I can do this explictly via a series of .replace() methods, but > certainly there must be a built-in way to do this on a generic basis? > Thank you, > Malcolm That question makes no sense -- a string is a string is a string in Python. The syntax you use to specify the string (for instance, raw or not, hex characters or not, or one or another quote choice) is irrelevant and completely forgotten once the string is internal. No need to use replace, the \n is already stored as a newline, and the \t as a tab and so on. Various methods of output may or may not convert those characters back into \n and \t and so on. But that's a matter of output not internal storage. So tell us what you're trying to accomplish -- and better also tell us Python2 or Python3? Gary Herron -------------- next part -------------- An HTML attachment was scrubbed... URL: From cosmeticsafrolatino003 at gmail.com Thu May 20 02:51:54 2010 From: cosmeticsafrolatino003 at gmail.com (cosmeticsafrolatino) Date: Wed, 19 May 2010 23:51:54 -0700 (PDT) Subject: helo Message-ID: hi From jimmy.cullen at gmail.com Thu May 20 03:37:20 2010 From: jimmy.cullen at gmail.com (Jimoid) Date: Thu, 20 May 2010 00:37:20 -0700 (PDT) Subject: Reading data from a Microsoft Access 2003 database References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> <4bf3eeeb$0$31263$607ed4bc@cv.net> Message-ID: <3c40f8d8-b29c-484f-b5b3-6dff0f68a032@m21g2000vbr.googlegroups.com> Thanks to all for your helpful suggestions. So far I have installed and played around with mdbtools, and it appears that I can use this from the shell to extract the information I need, e.g. mdb-export for dumping an entire table or mdb-sql to run a query. I am also interested by mxODBC and pyodbc as these seem to be python only solutions, so could be useful for platform independent python solutions (it may be that my programme will be used by some Windows users, if it is successful). To give it a bit of context, I am extracting data from the on-board flight planning software from an aerial survey plane (the Access database). I will extract the GPS data for each image taken so that I can then georeference the images. Cheers, Jimmy From martin.hellwig at dcuktec.org Thu May 20 03:39:05 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 20 May 2010 08:39:05 +0100 Subject: 250 In-Reply-To: References: Message-ID: On 05/20/10 07:51, cosmeticsafrolatino wrote: > hi 250 locahost.local Hello WimaxUser3645-219.wateen.net [110.36.45.219], pleased to meet you From jimmy.cullen at gmail.com Thu May 20 05:45:10 2010 From: jimmy.cullen at gmail.com (Jimoid) Date: Thu, 20 May 2010 02:45:10 -0700 (PDT) Subject: Reading data from a Microsoft Access 2003 database References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> <4bf3eeeb$0$31263$607ed4bc@cv.net> <3c40f8d8-b29c-484f-b5b3-6dff0f68a032@m21g2000vbr.googlegroups.com> Message-ID: <16c9daac-293a-4cb6-b847-489e696682bd@c11g2000vbe.googlegroups.com> I've now had a closer look at both pyODBC and mxODBC and it seems to me that they both require the database to be running to be able to query it. Is this correct? If so I think I will have to use mdb-* as the database I want to query is not running. Cheers, Jimmy From t.lehmann at rtsgroup.net Thu May 20 05:49:06 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Thu, 20 May 2010 02:49:06 -0700 (PDT) Subject: intervall of about 1 second for xmlrpc calls? Message-ID: Hi, I'm wondering about the behavior. Running this example - it looks like - that each rpc call is triggered in a visible interval (about one second). What's wrong? Thomas APPENDIX: import threading from xmlrpc.server import SimpleXMLRPCServer import xmlrpc.client class MyServer(threading.Thread): def __init__(self, host, port): threading.Thread.__init__(self) self.server = SimpleXMLRPCServer((host, port)) self.server.register_function(self.is_even, "is_even") self.server.register_function(self.stop, "stop_server") def run(self): print("server: waiting for requests...") self.server.serve_forever() print("server: is down.") def stop(self): print("server: shutdown requested...") self.stoptimer = threading.Timer(1, self.server.shutdown) self.stoptimer.start() return "done." def is_even(self, n): print("server: check %d to be even" % (n)) return n%2 == 0 # server as thread server = MyServer("localhost", 1234) server.start() # client code serverProxy = xmlrpc.client.ServerProxy("http://localhost:1234") for n in range(1,2+1): print("%d is %s" % (n, ["odd", "even"][serverProxy.is_even(n)])) serverProxy.stop_server() From apardon at forel.vub.ac.be Thu May 20 06:07:51 2010 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 May 2010 10:07:51 GMT Subject: Transferring an exception from one thread to an other. Message-ID: I have a numver of tarfiles on a remote host that I need to process and that I fetch via FTP. I wrote the following as a test to see how I would best approach this. (I'm using python 2.5) -------------------------------- ftptst1 -------------------------------- import tarfile as tar from ftplib import FTP, error_perm as FTPError, error_temp as FTPProblem from socket import error as SocketError ftp = FTP(host, user, password) def gettarfile(rfn): import tempfile tfl = tempfile.TemporaryFile() ftp.retrbinary("RETR %s" % (rfn,), tfl.write) tfl.seek(0) return tar.open(mode = "r:bz2", fileobj = tfl) def process(): for rfn in ("testfile.tbz", "nosuchfile"): try: tf = gettarfile(rfn) for tarinfo in tf: print tarinfo.name print except Exception: print "Something went wrong with '%s'" % rfn process() ------------------------------------------------------------------------- Executing this gives me this result: testfile/ testfile/tstfl.0 Something went wrong with 'nosuchfile' However the tarfile can be to big to store localy. That is why I rewrote the above as follows: -------------------------------- ftptst2 -------------------------------- import tarfile as tar from ftplib import FTP, error_perm as FTPError, error_temp as FTPProblem from socket import error as SocketError ftp = FTP("nestor", "apardon", "0nZM,F!m") def connect(lfl, rfn): ftp.retrbinary("RETR %s" % (rfn,), lfl.write) lfl.close() def gettarfile(rfn): import os, threading rfd, wfd = os.pipe() wfl = os.fdopen(wfd, "w") rfl = os.fdopen(rfd, "r") xfer = threading.Thread(target = connect, args = (wfl, rfn)) xfer.setDaemon(True) xfer.start() return tar.open(mode = "r|bz2", fileobj = rfl) def process(): for rfn in ("testfile.tbz", "nosuchfile"): try: tf = gettarfile(rfn) for tarinfo in tf: print tarinfo.name print except Exception: print "Something went wrong with '%s'" % rfn process() ------------------------------------------------------------------------- Executing this new test gives this result: testfile/ testfile/tstfl.0 Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner self.run() File "/usr/lib/python2.5/threading.py", line 446, in run self.__target(*self.__args, **self.__kwargs) File "ftptst2", line 10, in connect ftp.retrbinary("RETR %s" % (rfn,), lfl.write) File "/usr/lib/python2.5/ftplib.py", line 390, in retrbinary conn = self.transfercmd(cmd, rest) File "/usr/lib/python2.5/ftplib.py", line 356, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "/usr/lib/python2.5/ftplib.py", line 327, in ntransfercmd resp = self.sendcmd(cmd) File "/usr/lib/python2.5/ftplib.py", line 241, in sendcmd return self.getresp() File "/usr/lib/python2.5/ftplib.py", line 216, in getresp raise error_perm, resp error_perm: 550 nosuchfile: No such file or directory. Now I totally understand what is happening. What is less clear is how best to fix ftptst2, so that it behaves like ftptst1 in case of ftp problems. I know about the PyThreadState_SetAsyncExc function; would this be an acceptable solution here by catching the excption in the xfer/connect thread and raising them in the main thread? Is there an other possibility of combining ftplib and tarfile, that doesn't need threads but also doesn't need to store the remote file locally? Any other suggestion? -- Antoon Pardon From t.lehmann at rtsgroup.net Thu May 20 06:40:46 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Thu, 20 May 2010 03:40:46 -0700 (PDT) Subject: intervall of about 1 second for xmlrpc calls? References: Message-ID: > What's wrong? > Obviously there's a problem with "localhost". When using the IP of my machine everything is working fast. From t.lehmann at rtsgroup.net Thu May 20 06:58:57 2010 From: t.lehmann at rtsgroup.net (Thomas Lehmann) Date: Thu, 20 May 2010 03:58:57 -0700 (PDT) Subject: Problem with an huge dictionary References: Message-ID: <70b8f82e-2dfe-4403-ae77-cb4d005578f1@y12g2000vbr.googlegroups.com> > > The question is: > Is there a limit on the number of entries a dictionary can have i > jython? > > I wrote a little app where my data is stored in a huge dictionary > (11746 entries) generated with a python script. > When I try to import the dictionary, jython complains with the > following message: > 1) You did not say what you have saved (content of your dictionary). 2) You did not say how you have saved. >From the callstack - also I have never used jython - it looks like that there is a try to create a class. It looks like - I may be wrong - that you have saved user objects in your dictionary - have you? If so you might fail on loading those objects - especially when your program does not have the code for it. More details are required... From nobody at nowhere.nil Thu May 20 07:02:53 2010 From: nobody at nowhere.nil (Christian Stapfer) Date: Thu, 20 May 2010 13:02:53 +0200 Subject: Drawing glyphs based on their index (NOT their character code) Message-ID: Here's an interesting little problem: I am given a master.ttf font file and a subset file subset.ttf of that font, and I am asked to map indices of all the glyphs in subset.ttf to the corresponding indices in master.ttf. The subset font file is the result of a pipeline of 3 tools (pdflatex, Adobe Reader, and the Microsoft XPS Document Writer). The resulting document format (XAML) holds indices into subset.ttf, and in order to display that document with reference to master.ttf, I need to do this mapping of indices: subset -> master. (Carrying subset.ttf along with the XAML code is not an option, I think, because I need to be able to support copy and paste of small snippets from that document through a shared whiteboard.) I have tried to parse the two font files to the point of having the x- and y-coordinate points of the outlines of glyphs handy. But, unfortunately, subset.ttf has been processed in a way that makes it very difficult to compare its glyph outlines with the outlines of glyphs in master.ttf. So my next best idea is to draw the various glyphs as, 16x16 B/W images, say, and use the 16*16 bits (that is, 16 ints or 8 longs) that result from this as a sufficiently precise description of the glyph to do the necessary comparisons. PIL would be great for this, except for one "little" problem: I need to be able to draw glyphs based on their index, not based on their character code. Any ideas to get around that limitation of PIL's drawing primitives? Thanks in advance, Christian From sanamsingh at hotmail.com Thu May 20 07:45:37 2010 From: sanamsingh at hotmail.com (sanam singh) Date: Thu, 20 May 2010 11:45:37 +0000 Subject: Error regarding numpy Message-ID: hi, when i import numpy i get following error >>> import numpy Traceback (most recent call last): File "/usr/lib/wingide-personal3.2/src/debug/tserver/_sandbox.py", line 1, in # Used internally for debug sandbox under external interpreter File "/usr/lib/python2.6/dist-packages/numpy/__init__.py", line 130, in import add_newdocs File "/usr/lib/python2.6/dist-packages/numpy/add_newdocs.py", line 9, in from lib import add_newdoc File "/usr/lib/python2.6/dist-packages/numpy/lib/__init__.py", line 152, in from type_check import * File "/usr/lib/python2.6/dist-packages/numpy/lib/type_check.py", line 8, in import numpy.core.numeric as _nx File "/usr/lib/python2.6/dist-packages/numpy/core/__init__.py", line 5, in import multiarray ImportError: /usr/lib/python2.6/dist-packages/numpy/core/multiarray.so: undefined symbol: _PyUnicodeUCS4_IsWhitespace please help me. Cheers _________________________________________________________________ Hotmail: Free, trusted and rich email service. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From awilliam at whitemice.org Thu May 20 07:51:14 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Thu, 20 May 2010 07:51:14 -0400 Subject: intervall of about 1 second for xmlrpc calls? In-Reply-To: References: Message-ID: <1274356274.7639.1.camel@linux-yu4c.site> On Thu, 2010-05-20 at 03:40 -0700, Thomas Lehmann wrote: > > What's wrong? > Obviously there's a problem with "localhost". When using the IP of my > machine everything is working fast. You box may first be trying to connect to ::1 (ipv6) and when that fails it falls back to 127.0.0.1. Make sure IPv6 is properly configured/enabled and try the script again. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From mftian at gmail.com Thu May 20 08:56:07 2010 From: mftian at gmail.com (Xie&Tian) Date: Thu, 20 May 2010 20:56:07 +0800 Subject: why struct.pack behave like this Message-ID: Hi When I use struct to pack binary data, I found this interesting behaviour: >>> import struct >>> struct.pack('B', 1) '\x01' >>> struct.pack('H', 200) '\xc8\x00' >>> struct.pack('BH',1, 200) '\x01\x00\xc8\x00' >>> struct.calcsize('BH') 4 Why does "struct.pack('BH',1, 200)" come out with an extra "\x00"? -- Luyun Xie http://magefromhell.blogspot.com/ (http://blog.hellmage.info/) -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at nowhere.nil Thu May 20 10:08:29 2010 From: nobody at nowhere.nil (Christian Stapfer) Date: Thu, 20 May 2010 16:08:29 +0200 Subject: Drawing glyphs based on their index (NOT their character code) In-Reply-To: References: Message-ID: <4f3f0$4bf54263$544ba447$24070@news.hispeed.ch> "Christian Stapfer" schrieb im Newsbeitrag news:b7256$4bf516e1$544ba447$20752 at news.hispeed.ch... > Here's an interesting little problem: I am given a master.ttf font file > and a subset file subset.ttf of that font, and I am asked to map indices > of all the glyphs in subset.ttf to the corresponding indices in > master.ttf. The subset font file is the result of a pipeline of 3 tools > (pdflatex, Adobe Reader, and the Microsoft XPS Document Writer). > So my next best idea is to draw the various glyphs as, 16x16 B/W images, > say, and use the 16*16 bits (that is, 16 ints or 8 longs) that result from > this as a sufficiently precise description of the glyph to do the > necessary comparisons. > > PIL would be great for this, except for one "little" problem: I need to be > able to draw glyphs based on their index, not based on their character > code. > > Any ideas to get around that limitation of PIL's drawing primitives? To answer my own question: I might parse the cmap table of the ttf file, and then invert that mapping char->index. I think that's going to be the next approach that I will try. Regards, Christian From gherron at islandtraining.com Thu May 20 10:20:15 2010 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 20 May 2010 07:20:15 -0700 Subject: Import Module In-Reply-To: References: Message-ID: <4BF5451F.5030904@islandtraining.com> On 05/19/2010 09:40 AM, Harikrishnan R wrote: > Hi , > I have a file a.py contains > > from one.two import abc > -------------------------------------------- > is there any way to find out "one.two" the import Path of abc. ? > I don't want one.two.abc . Any function or attribute which directly > give one.two ? > > -Regards > > What's so hard about computing what you want from what your can get. Since abc.__module__ gives gives you too much, trim it down -- perhaps even with os.path.splitext, although that's not what what splitext was meant for. os.path.splitext(abc.__module__)[0] Gary Herron From utente at esempio.net Thu May 20 10:37:41 2010 From: utente at esempio.net (superpollo) Date: Thu, 20 May 2010 16:37:41 +0200 Subject: function that counts... In-Reply-To: <4bf45c08$0$8837$c3e8da3@news.astraweb.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf4493c$0$31377$4fafbaef@reader1.news.tin.it> <4bf450ef$0$31372$4fafbaef@reader1.news.tin.it> <4bf45c08$0$8837$c3e8da3@news.astraweb.com> Message-ID: <4bf54935$0$12123$4fafbaef@reader4.news.tin.it> Steven D'Aprano ha scritto: > On Wed, 19 May 2010 22:58:22 +0200, superpollo wrote: > >> In [266]: del(sum) > > > del is a statement, not a function, so the brackets are pointless. This > is like writing: > > x = (1) > > instead of > > x = 1 > > `del sum` is all you need. sorry about that, thanks a lot! bye From utente at esempio.net Thu May 20 10:38:55 2010 From: utente at esempio.net (superpollo) Date: Thu, 20 May 2010 16:38:55 +0200 Subject: function that counts... In-Reply-To: <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> Message-ID: <4bf5497f$0$12123$4fafbaef@reader4.news.tin.it> Steven D'Aprano ha scritto: > On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: > >> ... how many positive integers less than n have digits that sum up to m: >> >> In [197]: def prttn(m, n): > > Does the name "prttn" mean anything? I'm afraid I keep reading it as a > mispelling of "print n". pArtItIOn > > > [...] >> s = str(i) >> sum = 0 >> for j in range(len(s)): >> sum += int(s[j]) > > Rather than iterating over an index j = 0, 1, 2, ... and then fetching > the jth character of the string, you can iterate over the characters > directly. So the inner loop is better written: > > for c in s: > sum += int(c) d'oh! some day i will learn to speak pythonese! thanks bye From utente at esempio.net Thu May 20 10:40:35 2010 From: utente at esempio.net (superpollo) Date: Thu, 20 May 2010 16:40:35 +0200 Subject: function that counts... In-Reply-To: <75cf168b-9d67-4602-9201-774cc8dd48e9@z33g2000vbb.googlegroups.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <75cf168b-9d67-4602-9201-774cc8dd48e9@z33g2000vbb.googlegroups.com> Message-ID: <4bf549e3$0$12123$4fafbaef@reader4.news.tin.it> Richard Thomas ha scritto: > For this kind of problem you should avoid all that stringification. I > find it best to deal with sequences of digits of a fixed length and go > from there. For example: > > def count1(m, n, cache={}): > """Number of digit sequences of length `n` summing to `m`.""" > if n < 0 or m < 0: > return 0 > elif n == 0: > return int(m == 0) > elif (m, n) in cache: > return cache[m, n] > # This is an optimisation using the combinatoric choose function. > #elif m < 10: > # result = choose(n + m - 1, n - 1) > else: > result = 0 > for digit in xrange(min(10, m + 1)): > result += count1(m - digit, n - 1) > cache[m, n] = result > return result > > Notice the caching of results. With this we can compute the required > thing quite easily: > > def count2(m, n): > """Number of numbers less than `n` whose digits sum to `m`.""" > result = 0 > digits = map(int, str(n)) > length = len(digits) > for idx, digit in enumerate(digits): > for seq_digit in xrange(digit): > seq_limit = m - seq_digit > seq_length = length - idx - 1 > result += count1(seq_limit, seq_length) > m -= digit > return result > > Essentially we move through the number left to right, choose digits > less than the digit in the number and count digit sequences to fill > the remainder. Then fix the actual digit and step forward. > > An approach like this avoids the relatively slow stringification > process and makes decent use of caching and iteration (both easy and > efficient in Python). > > In [1]: count2(25, 10000) > Out[1]: 348 > > In [2]: timeit count2(25, 10000) > 100000 loops, best of 3: 12.6 us per loop wow. impressive, thanks. From davea at ieee.org Thu May 20 11:44:00 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 20 May 2010 11:44:00 -0400 Subject: why struct.pack behave like this In-Reply-To: References: Message-ID: <4BF558C0.2050101@ieee.org> Xie&Tian wrote: > Hi > > When I use struct to pack binary data, I found this interesting behaviour: > > >>>> import struct >>>> struct.pack('B', 1) >>>> > '\x01' > >>>> struct.pack('H', 200) >>>> > '\xc8\x00' > >>>> struct.pack('BH',1, 200) >>>> > '\x01\x00\xc8\x00' > >>>> struct.calcsize('BH') >>>> > 4 > > Why does "struct.pack('BH',1, 200)" come out with an extra "\x00"? > > > To quote the help: >>By default, C numbers are represented in the machine?s native format and byte order, >>and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). C's standard rules say that when a smaller type is followed by a larger one, padding is used so that the second field is aligned according to its size. So a H type will be aligned to a 2byte boundary. If you had two B's before it, no padding would be added. In C, you can use a compiler switch or a pragma to override standard alignment. Similarly, here you can use a prefix like "=" to override the native alignment rules. DaveA From sit at home.com Thu May 20 11:58:51 2010 From: sit at home.com (sit at home.com) Date: Thu, 20 May 2010 11:58:51 -0400 Subject: Display file names in Tkinter Listbox References: <4BF4CA7B.6000008@NO.SPAM.velseis.com.au> Message-ID: On Thu, 20 May 2010 15:36:59 +1000, John McMonagle wrote: >Rick at home.com wrote: >> Hello, >> >> My first attenpt at a simple python Tkinter application. I wanted to >> see how to load file names into a listbox from a menu. This is what I >> got until the part of displaying the file names in a listbox, which I >> could not figfure out how to do? >> >> Any help would be appreciated. Trying to do this as simple as possible >> to understand. >> >> The "print fileNames" does work but how to display it in listbox? >> >> from Tkinter import * >> from tkFileDialog import askopenfilenames >> >> class MyCode: >> def __init__(self): >> root = Tk() >> >> menubar = Menu(root) >> filemenu = Menu(menubar) >> >> lbox = Listbox(root, width=50).pack() > >Your problem is the above line of code. > >Here you are assigning the return value of the pack (None if I recall). > >Later when you want to put things in the Listbox you don't have the >widget reference anymore. > >It's probably a good idea to make the Listbox widget an attribute of >your class so you can use it in class methods without having to pass it >as an argument. > >So, change the above line of code to: > > self.lbox = Listbox(root, width=50) > self.lbox.pack() > >> >> menubar.add_cascade(label='File', menu=filemenu) >> filemenu.add_command(label='New Project') >> filemenu.add_command(label='Load Files...', command=self.OnLoad) >> >> >> filemenu.add_command(label='Exit', command=root.quit) >> >> root.config(menu=menubar) >> >> root.mainloop() >> >> >> def OnLoad(self): >> fileNames = askopenfilenames(filetypes=[('Split Files', '*')]) >> print fileNames >> > >Now that you've got a reference to your Listbox widget that is an >attribute of your class, you should be able to insert the file names >into the Listbox like so. > > self.lbox.insert(0, fileNames) > >Regards, > >John Thank you John for your reply. I have made the modifications and it does print inside the listbox, however they are all printed on the same line. My files are named Name.0 Name.1 Name.2 Name.3 etc so I would like them to be printed sorted on a separate line. When I did a type(fileNames) it showed me that it was in unicode and printed character per line, so I tried it this way listFileNames = str(fileNames).split(' ') for fileName in listFileNames: self.lbox.insert(0, fileName) it works but does not print sorted. it prints name.2 name.1 name.0 name.3 Thank you for all your help. From ppearson at nowhere.invalid Thu May 20 12:06:33 2010 From: ppearson at nowhere.invalid (Peter Pearson) Date: 20 May 2010 16:06:33 GMT Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <85l509Fpe7U1@mid.individual.net> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: > ... how many positive integers less than n have digits that sum up to m: If it's important for the function to execute quickly for large n, you might get a useful speedup by testing only every ninth integer, since any two integers whose digits add up to m differ by a multiple of 9. A simple application of this observation would be to test range( m % 9, n, 9 ) rather than testing range( 1, n ). I suspect that further applications of number theory would provide additional, substantial speedups, but this wanders away from the subject of Python. -- To email me, substitute nowhere->spamcop, invalid->net. From victorsubervi at gmail.com Thu May 20 12:26:24 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 20 May 2010 12:26:24 -0400 Subject: Strange MySQL Problem Message-ID: Hi; I have this code: #!/usr/bin/python import cgitb; cgitb.enable() import cgi import sys,os sys.path.append(os.getcwd()) import MySQLdb from login import login def create_edit_passengers4(): print "Content-Type: text/html" print print ''' ''' user, passwd, db, host = login() database = MySQLdb.connect(host, user, passwd, db) cursor = database.cursor() form = cgi.FieldStorage() cursor.execute('create table if not exists Passengers (id int(11) auto_increment primary key, flights_id int(11) not null, customer_id int(11) not null, foreign key (id) references Flights (flights_id), foreign key (id) references Customers (customer_id), name varchar(40), weight int) engine=InnoDB;') new_passengers = int(form.getfirst('new_passengers')) i = 0 while i < new_passengers: cursor.execute('insert into Passengers values (Null, %s, %s, "%s", %s);' % (form.getfirst('%d:flight' % i), form.getfirst('%d:customer' % i), form.getfirst('%d:name' % i, ''), form.getfirst('%d:weight' % i))) i += 1 print "All passenger information has successfully been added." cursor.close() print "\n" create_edit_passengers4() Now, it throws no errors; however, it doesn't insert. If I print out the insert statement to screen and then manually insert it in MySQL it inserts. Huh?? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From angel.gutierrez.rodriguez at gmail.com Thu May 20 12:32:21 2010 From: angel.gutierrez.rodriguez at gmail.com (Angel) Date: Thu, 20 May 2010 09:32:21 -0700 (PDT) Subject: Python 2.6.1 + wxPython 2.8.9.1 compiled form source Message-ID: Hi, I have a Red Hat 4.6 machone and I compiled and installed python 2.6.1 from source. Then, I compiled wxPython 2.8.9.1 form source too. And then, when I try to run it: # python Python 2.6.1 (r261:67515, Mar 4 2009, 20:10:49) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import wx Aborted Any hint? Anything I am missing? Anyhere to check? Read? Thanks in advance. This in my environment: LD_LIBRARY_PATH=/opt/wxPython/2.8.9.1/lib:/opt/python/2.6.1/lib:/opt/ hpmpi/lib/linux_amd64:/opt/intel/cce/10.1.008/lib:/opt/intel/fce/ 10.1.008/lib:/lib:/lib64:/usr/lib:/usr/lib64:/usr/X11R6/lib:/usr/X11R6/ lib64:/usr/local/lib:/usr/local/lib64 PATH=/opt/wxPython/2.8.9.1/bin:/opt/python/2.6.1/bin:/root/aaks/bin:/ opt/hpmpi/bin:/opt/intel/cce/10.1.008/bin:/opt/intel/fce/10.1.008/bin:/ usr/local/bin:/usr/local/X11/bin:/opt/torque/2.3.6/bin:/opt/torque/ 2.3.6/sbin:/usr/java/jdk1.6.0_12/bin:/usr/local/sbin:/usr/local/bin:/ sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/etc:/usr/etc:/usr/local/ etc:.:/opt/maui/3.2.6p21/sbin:/opt/maui/3.2.6p21/bin:/root/bin:/opt/ pdsh/2.17/bin PYTHONPATH=/opt/wxPython/2.8.9.1:/opt/python/2.6.1 And.. a verbose output: # python -vv # installing zipimport hook import zipimport # builtin # installed zipimport hook # trying /opt/wxPython/2.8.9.1/site.so # trying /opt/wxPython/2.8.9.1/sitemodule.so # trying /opt/wxPython/2.8.9.1/site.py # trying /opt/wxPython/2.8.9.1/site.pyc # trying /opt/python/2.6.1/site.so # trying /opt/python/2.6.1/sitemodule.so # trying /opt/python/2.6.1/site.py # trying /opt/python/2.6.1/site.pyc # trying /opt/python/2.6.1/lib/python2.6/site.so # trying /opt/python/2.6.1/lib/python2.6/sitemodule.so # trying /opt/python/2.6.1/lib/python2.6/site.py # /opt/python/2.6.1/lib/python2.6/site.pyc matches /opt/python/2.6.1/ lib/python2.6/site.py import site # precompiled from /opt/python/2.6.1/lib/python2.6/ site.pyc # trying /opt/wxPython/2.8.9.1/os.so # trying /opt/wxPython/2.8.9.1/osmodule.so # trying /opt/wxPython/2.8.9.1/os.py # trying /opt/wxPython/2.8.9.1/os.pyc # trying /opt/python/2.6.1/os.so # trying /opt/python/2.6.1/osmodule.so # trying /opt/python/2.6.1/os.py # trying /opt/python/2.6.1/os.pyc # trying /opt/python/2.6.1/lib/python2.6/os.so # trying /opt/python/2.6.1/lib/python2.6/osmodule.so # trying /opt/python/2.6.1/lib/python2.6/os.py # /opt/python/2.6.1/lib/python2.6/os.pyc matches /opt/python/2.6.1/lib/ python2.6/os.py import os # precompiled from /opt/python/2.6.1/lib/python2.6/os.pyc import errno # builtin import posix # builtin # trying /opt/wxPython/2.8.9.1/posixpath.so # trying /opt/wxPython/2.8.9.1/posixpathmodule.so # trying /opt/wxPython/2.8.9.1/posixpath.py # trying /opt/wxPython/2.8.9.1/posixpath.pyc # trying /opt/python/2.6.1/posixpath.so # trying /opt/python/2.6.1/posixpathmodule.so # trying /opt/python/2.6.1/posixpath.py # trying /opt/python/2.6.1/posixpath.pyc # trying /opt/python/2.6.1/lib/python2.6/posixpath.so # trying /opt/python/2.6.1/lib/python2.6/posixpathmodule.so # trying /opt/python/2.6.1/lib/python2.6/posixpath.py # /opt/python/2.6.1/lib/python2.6/posixpath.pyc matches /opt/python/ 2.6.1/lib/python2.6/posixpath.py import posixpath # precompiled from /opt/python/2.6.1/lib/python2.6/ posixpath.pyc # trying /opt/wxPython/2.8.9.1/stat.so # trying /opt/wxPython/2.8.9.1/statmodule.so # trying /opt/wxPython/2.8.9.1/stat.py # trying /opt/wxPython/2.8.9.1/stat.pyc # trying /opt/python/2.6.1/stat.so # trying /opt/python/2.6.1/statmodule.so # trying /opt/python/2.6.1/stat.py # trying /opt/python/2.6.1/stat.pyc # trying /opt/python/2.6.1/lib/python2.6/stat.so # trying /opt/python/2.6.1/lib/python2.6/statmodule.so # trying /opt/python/2.6.1/lib/python2.6/stat.py # /opt/python/2.6.1/lib/python2.6/stat.pyc matches /opt/python/2.6.1/ lib/python2.6/stat.py import stat # precompiled from /opt/python/2.6.1/lib/python2.6/ stat.pyc # trying /opt/wxPython/2.8.9.1/genericpath.so # trying /opt/wxPython/2.8.9.1/genericpathmodule.so # trying /opt/wxPython/2.8.9.1/genericpath.py # trying /opt/wxPython/2.8.9.1/genericpath.pyc # trying /opt/python/2.6.1/genericpath.so # trying /opt/python/2.6.1/genericpathmodule.so # trying /opt/python/2.6.1/genericpath.py # trying /opt/python/2.6.1/genericpath.pyc # trying /opt/python/2.6.1/lib/python2.6/genericpath.so # trying /opt/python/2.6.1/lib/python2.6/genericpathmodule.so # trying /opt/python/2.6.1/lib/python2.6/genericpath.py # /opt/python/2.6.1/lib/python2.6/genericpath.pyc matches /opt/python/ 2.6.1/lib/python2.6/genericpath.py import genericpath # precompiled from /opt/python/2.6.1/lib/python2.6/ genericpath.pyc # trying /opt/wxPython/2.8.9.1/warnings.so # trying /opt/wxPython/2.8.9.1/warningsmodule.so # trying /opt/wxPython/2.8.9.1/warnings.py # trying /opt/wxPython/2.8.9.1/warnings.pyc # trying /opt/python/2.6.1/warnings.so # trying /opt/python/2.6.1/warningsmodule.so # trying /opt/python/2.6.1/warnings.py # trying /opt/python/2.6.1/warnings.pyc # trying /opt/python/2.6.1/lib/python2.6/warnings.so # trying /opt/python/2.6.1/lib/python2.6/warningsmodule.so # trying /opt/python/2.6.1/lib/python2.6/warnings.py # /opt/python/2.6.1/lib/python2.6/warnings.pyc matches /opt/python/ 2.6.1/lib/python2.6/warnings.py import warnings # precompiled from /opt/python/2.6.1/lib/python2.6/ warnings.pyc # trying /opt/wxPython/2.8.9.1/linecache.so # trying /opt/wxPython/2.8.9.1/linecachemodule.so # trying /opt/wxPython/2.8.9.1/linecache.py # trying /opt/wxPython/2.8.9.1/linecache.pyc # trying /opt/python/2.6.1/linecache.so # trying /opt/python/2.6.1/linecachemodule.so # trying /opt/python/2.6.1/linecache.py # trying /opt/python/2.6.1/linecache.pyc # trying /opt/python/2.6.1/lib/python2.6/linecache.so # trying /opt/python/2.6.1/lib/python2.6/linecachemodule.so # trying /opt/python/2.6.1/lib/python2.6/linecache.py # /opt/python/2.6.1/lib/python2.6/linecache.pyc matches /opt/python/ 2.6.1/lib/python2.6/linecache.py import linecache # precompiled from /opt/python/2.6.1/lib/python2.6/ linecache.pyc # trying /opt/wxPython/2.8.9.1/types.so # trying /opt/wxPython/2.8.9.1/typesmodule.so # trying /opt/wxPython/2.8.9.1/types.py # trying /opt/wxPython/2.8.9.1/types.pyc # trying /opt/python/2.6.1/types.so # trying /opt/python/2.6.1/typesmodule.so # trying /opt/python/2.6.1/types.py # trying /opt/python/2.6.1/types.pyc # trying /opt/python/2.6.1/lib/python2.6/types.so # trying /opt/python/2.6.1/lib/python2.6/typesmodule.so # trying /opt/python/2.6.1/lib/python2.6/types.py # /opt/python/2.6.1/lib/python2.6/types.pyc matches /opt/python/2.6.1/ lib/python2.6/types.py import types # precompiled from /opt/python/2.6.1/lib/python2.6/ types.pyc # trying /opt/wxPython/2.8.9.1/UserDict.so # trying /opt/wxPython/2.8.9.1/UserDictmodule.so # trying /opt/wxPython/2.8.9.1/UserDict.py # trying /opt/wxPython/2.8.9.1/UserDict.pyc # trying /opt/python/2.6.1/UserDict.so # trying /opt/python/2.6.1/UserDictmodule.so # trying /opt/python/2.6.1/UserDict.py # trying /opt/python/2.6.1/UserDict.pyc # trying /opt/python/2.6.1/lib/python2.6/UserDict.so # trying /opt/python/2.6.1/lib/python2.6/UserDictmodule.so # trying /opt/python/2.6.1/lib/python2.6/UserDict.py # /opt/python/2.6.1/lib/python2.6/UserDict.pyc matches /opt/python/ 2.6.1/lib/python2.6/UserDict.py import UserDict # precompiled from /opt/python/2.6.1/lib/python2.6/ UserDict.pyc # trying /opt/wxPython/2.8.9.1/_abcoll.so # trying /opt/wxPython/2.8.9.1/_abcollmodule.so # trying /opt/wxPython/2.8.9.1/_abcoll.py # trying /opt/wxPython/2.8.9.1/_abcoll.pyc # trying /opt/python/2.6.1/_abcoll.so # trying /opt/python/2.6.1/_abcollmodule.so # trying /opt/python/2.6.1/_abcoll.py # trying /opt/python/2.6.1/_abcoll.pyc # trying /opt/python/2.6.1/lib/python2.6/_abcoll.so # trying /opt/python/2.6.1/lib/python2.6/_abcollmodule.so # trying /opt/python/2.6.1/lib/python2.6/_abcoll.py # /opt/python/2.6.1/lib/python2.6/_abcoll.pyc matches /opt/python/ 2.6.1/lib/python2.6/_abcoll.py import _abcoll # precompiled from /opt/python/2.6.1/lib/python2.6/ _abcoll.pyc # trying /opt/wxPython/2.8.9.1/abc.so # trying /opt/wxPython/2.8.9.1/abcmodule.so # trying /opt/wxPython/2.8.9.1/abc.py # trying /opt/wxPython/2.8.9.1/abc.pyc # trying /opt/python/2.6.1/abc.so # trying /opt/python/2.6.1/abcmodule.so # trying /opt/python/2.6.1/abc.py # trying /opt/python/2.6.1/abc.pyc # trying /opt/python/2.6.1/lib/python2.6/abc.so # trying /opt/python/2.6.1/lib/python2.6/abcmodule.so # trying /opt/python/2.6.1/lib/python2.6/abc.py # /opt/python/2.6.1/lib/python2.6/abc.pyc matches /opt/python/2.6.1/ lib/python2.6/abc.py import abc # precompiled from /opt/python/2.6.1/lib/python2.6/abc.pyc # trying /opt/wxPython/2.8.9.1/copy_reg.so # trying /opt/wxPython/2.8.9.1/copy_regmodule.so # trying /opt/wxPython/2.8.9.1/copy_reg.py # trying /opt/wxPython/2.8.9.1/copy_reg.pyc # trying /opt/python/2.6.1/copy_reg.so # trying /opt/python/2.6.1/copy_regmodule.so # trying /opt/python/2.6.1/copy_reg.py # trying /opt/python/2.6.1/copy_reg.pyc # trying /opt/python/2.6.1/lib/python2.6/copy_reg.so # trying /opt/python/2.6.1/lib/python2.6/copy_regmodule.so # trying /opt/python/2.6.1/lib/python2.6/copy_reg.py # /opt/python/2.6.1/lib/python2.6/copy_reg.pyc matches /opt/python/ 2.6.1/lib/python2.6/copy_reg.py import copy_reg # precompiled from /opt/python/2.6.1/lib/python2.6/ copy_reg.pyc # trying /opt/wxPython/2.8.9.1/sitecustomize.so # trying /opt/wxPython/2.8.9.1/sitecustomizemodule.so # trying /opt/wxPython/2.8.9.1/sitecustomize.py # trying /opt/wxPython/2.8.9.1/sitecustomize.pyc # trying /opt/python/2.6.1/sitecustomize.so # trying /opt/python/2.6.1/sitecustomizemodule.so # trying /opt/python/2.6.1/sitecustomize.py # trying /opt/python/2.6.1/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-tk/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-tk/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-old/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/ sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-old/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/ sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/ sitecustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/sitecustomize.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/sitecustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/sitecustomize.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/sitecustomize.pyc # trying /opt/wxPython/2.8.9.1/usercustomize.so # trying /opt/wxPython/2.8.9.1/usercustomizemodule.so # trying /opt/wxPython/2.8.9.1/usercustomize.py # trying /opt/wxPython/2.8.9.1/usercustomize.pyc # trying /opt/python/2.6.1/usercustomize.so # trying /opt/python/2.6.1/usercustomizemodule.so # trying /opt/python/2.6.1/usercustomize.py # trying /opt/python/2.6.1/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-tk/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-tk/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-old/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/ usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-old/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/ usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/ usercustomize.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/usercustomize.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/usercustomizemodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/usercustomize.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/usercustomize.pyc # trying /opt/wxPython/2.8.9.1/encodings.so # trying /opt/wxPython/2.8.9.1/encodingsmodule.so # trying /opt/wxPython/2.8.9.1/encodings.py # trying /opt/wxPython/2.8.9.1/encodings.pyc # trying /opt/python/2.6.1/encodings.so # trying /opt/python/2.6.1/encodingsmodule.so # trying /opt/python/2.6.1/encodings.py # trying /opt/python/2.6.1/encodings.pyc import encodings # directory /opt/python/2.6.1/lib/python2.6/encodings # trying /opt/python/2.6.1/lib/python2.6/encodings/__init__.so # trying /opt/python/2.6.1/lib/python2.6/encodings/__init__module.so # trying /opt/python/2.6.1/lib/python2.6/encodings/__init__.py # /opt/python/2.6.1/lib/python2.6/encodings/__init__.pyc matches /opt/ python/2.6.1/lib/python2.6/encodings/__init__.py import encodings # precompiled from /opt/python/2.6.1/lib/python2.6/ encodings/__init__.pyc # trying /opt/python/2.6.1/lib/python2.6/encodings/codecs.so # trying /opt/python/2.6.1/lib/python2.6/encodings/codecsmodule.so # trying /opt/python/2.6.1/lib/python2.6/encodings/codecs.py # trying /opt/python/2.6.1/lib/python2.6/encodings/codecs.pyc # trying /opt/wxPython/2.8.9.1/codecs.so # trying /opt/wxPython/2.8.9.1/codecsmodule.so # trying /opt/wxPython/2.8.9.1/codecs.py # trying /opt/wxPython/2.8.9.1/codecs.pyc # trying /opt/python/2.6.1/codecs.so # trying /opt/python/2.6.1/codecsmodule.so # trying /opt/python/2.6.1/codecs.py # trying /opt/python/2.6.1/codecs.pyc # trying /opt/python/2.6.1/lib/python2.6/codecs.so # trying /opt/python/2.6.1/lib/python2.6/codecsmodule.so # trying /opt/python/2.6.1/lib/python2.6/codecs.py # /opt/python/2.6.1/lib/python2.6/codecs.pyc matches /opt/python/2.6.1/ lib/python2.6/codecs.py import codecs # precompiled from /opt/python/2.6.1/lib/python2.6/ codecs.pyc import _codecs # builtin # trying /opt/python/2.6.1/lib/python2.6/encodings/encodings.so # trying /opt/python/2.6.1/lib/python2.6/encodings/encodingsmodule.so # trying /opt/python/2.6.1/lib/python2.6/encodings/encodings.py # trying /opt/python/2.6.1/lib/python2.6/encodings/encodings.pyc # trying /opt/python/2.6.1/lib/python2.6/encodings/aliases.so # trying /opt/python/2.6.1/lib/python2.6/encodings/aliasesmodule.so # trying /opt/python/2.6.1/lib/python2.6/encodings/aliases.py # /opt/python/2.6.1/lib/python2.6/encodings/aliases.pyc matches /opt/ python/2.6.1/lib/python2.6/encodings/aliases.py import encodings.aliases # precompiled from /opt/python/2.6.1/lib/ python2.6/encodings/aliases.pyc # trying /opt/python/2.6.1/lib/python2.6/encodings/__builtin__.so # trying /opt/python/2.6.1/lib/python2.6/encodings/ __builtin__module.so # trying /opt/python/2.6.1/lib/python2.6/encodings/__builtin__.py # trying /opt/python/2.6.1/lib/python2.6/encodings/__builtin__.pyc # trying /opt/python/2.6.1/lib/python2.6/encodings/utf_8.so # trying /opt/python/2.6.1/lib/python2.6/encodings/utf_8module.so # trying /opt/python/2.6.1/lib/python2.6/encodings/utf_8.py # /opt/python/2.6.1/lib/python2.6/encodings/utf_8.pyc matches /opt/ python/2.6.1/lib/python2.6/encodings/utf_8.py import encodings.utf_8 # precompiled from /opt/python/2.6.1/lib/ python2.6/encodings/utf_8.pyc Python 2.6.1 (r261:67515, Mar 4 2009, 20:10:49) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. # trying readline.so # trying readlinemodule.so # trying readline.py # trying readline.pyc # trying /opt/wxPython/2.8.9.1/readline.so # trying /opt/wxPython/2.8.9.1/readlinemodule.so # trying /opt/wxPython/2.8.9.1/readline.py # trying /opt/wxPython/2.8.9.1/readline.pyc # trying /opt/python/2.6.1/readline.so # trying /opt/python/2.6.1/readlinemodule.so # trying /opt/python/2.6.1/readline.py # trying /opt/python/2.6.1/readline.pyc # trying /opt/python/2.6.1/lib/python2.6/readline.so # trying /opt/python/2.6.1/lib/python2.6/readlinemodule.so # trying /opt/python/2.6.1/lib/python2.6/readline.py # trying /opt/python/2.6.1/lib/python2.6/readline.pyc # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/readline.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/readlinemodule.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/readline.py # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/readline.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-tk/readline.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/readlinemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/readline.py # trying /opt/python/2.6.1/lib/python2.6/lib-tk/readline.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-old/readline.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/readlinemodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/readline.py # trying /opt/python/2.6.1/lib/python2.6/lib-old/readline.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/readline.so dlopen("/opt/python/2.6.1/lib/python2.6/lib-dynload/readline.so", 2); import readline # dynamically loaded from /opt/python/2.6.1/lib/ python2.6/lib-dynload/readline.so >>> import wx # trying wx.so # trying wxmodule.so # trying wx.py # trying wx.pyc # trying /opt/wxPython/2.8.9.1/wx.so # trying /opt/wxPython/2.8.9.1/wxmodule.so # trying /opt/wxPython/2.8.9.1/wx.py # trying /opt/wxPython/2.8.9.1/wx.pyc # trying /opt/python/2.6.1/wx.so # trying /opt/python/2.6.1/wxmodule.so # trying /opt/python/2.6.1/wx.py # trying /opt/python/2.6.1/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/wx.so # trying /opt/python/2.6.1/lib/python2.6/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/wx.py # trying /opt/python/2.6.1/lib/python2.6/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/wx.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/wx.py # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-tk/wx.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/wx.py # trying /opt/python/2.6.1/lib/python2.6/lib-tk/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-old/wx.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/wx.py # trying /opt/python/2.6.1/lib/python2.6/lib-old/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/wx.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/wx.py # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx.pyc import wx # directory /opt/python/2.6.1/lib/python2.6/site-packages/ wx-2.8-gtk2-unicode/wx # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__init__.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__init__module.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__init__.py # /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/ __init__.pyc matches /opt/python/2.6.1/lib/python2.6/site-packages/ wx-2.8-gtk2-unicode/wx/__init__.py import wx # precompiled from /opt/python/2.6.1/lib/python2.6/site- packages/wx-2.8-gtk2-unicode/wx/__init__.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__version__.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__version__module.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/__version__.py # /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/ __version__.pyc matches /opt/python/2.6.1/lib/python2.6/site-packages/ wx-2.8-gtk2-unicode/wx/__version__.py import wx.__version__ # precompiled from /opt/python/2.6.1/lib/ python2.6/site-packages/wx-2.8-gtk2-unicode/wx/__version__.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/wx.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/wxmodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/wx.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/wx.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/_core.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/_coremodule.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/_core.py # /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/ _core.pyc matches /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8- gtk2-unicode/wx/_core.py import wx._core # precompiled from /opt/python/2.6.1/lib/python2.6/ site-packages/wx-2.8-gtk2-unicode/wx/_core.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/_core_.so dlopen("/opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/wx/_core_.so", 2); # trying swig_runtime_data2.so # trying swig_runtime_data2module.so # trying swig_runtime_data2.py # trying swig_runtime_data2.pyc # trying /opt/wxPython/2.8.9.1/swig_runtime_data2.so # trying /opt/wxPython/2.8.9.1/swig_runtime_data2module.so # trying /opt/wxPython/2.8.9.1/swig_runtime_data2.py # trying /opt/wxPython/2.8.9.1/swig_runtime_data2.pyc # trying /opt/python/2.6.1/swig_runtime_data2.so # trying /opt/python/2.6.1/swig_runtime_data2module.so # trying /opt/python/2.6.1/swig_runtime_data2.py # trying /opt/python/2.6.1/swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/plat-linux2/ swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-tk/swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/ swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/lib-tk/swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/lib-tk/swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-old/swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/ swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/lib-old/swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/lib-old/ swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/lib-dynload/ swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/ swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/ swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/ swig_runtime_data2.pyc # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/swig_runtime_data2.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/swig_runtime_data2module.so # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/swig_runtime_data2.py # trying /opt/python/2.6.1/lib/python2.6/site-packages/wx-2.8-gtk2- unicode/swig_runtime_data2.pyc Aborted From utente at esempio.net Thu May 20 12:33:17 2010 From: utente at esempio.net (superpollo) Date: Thu, 20 May 2010 18:33:17 +0200 Subject: function that counts... In-Reply-To: <85l509Fpe7U1@mid.individual.net> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <85l509Fpe7U1@mid.individual.net> Message-ID: <4bf5644e$0$12129$4fafbaef@reader4.news.tin.it> Peter Pearson ha scritto: > On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: >> ... how many positive integers less than n have digits that sum up to m: > > If it's important for the function to execute quickly for large n, > you might get a useful speedup by testing only every ninth integer, > since any two integers whose digits add up to m differ by a multiple > of 9. A simple application of this observation would be to test > range( m % 9, n, 9 ) rather than testing range( 1, n ). > > I suspect that further applications of number theory would > provide additional, substantial speedups, but this wanders > away from the subject of Python. > great suggestion, thanks! From invalid at invalid.invalid Thu May 20 12:39:38 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 20 May 2010 16:39:38 +0000 (UTC) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> <4bf5497f$0$12123$4fafbaef@reader4.news.tin.it> Message-ID: On 2010-05-20, superpollo wrote: > Steven D'Aprano ha scritto: >> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: >> >>> ... how many positive integers less than n have digits that sum up to m: >>> >>> In [197]: def prttn(m, n): >> >> Does the name "prttn" mean anything? I'm afraid I keep reading it as a >> mispelling of "print n". > > pArtItIOn One might be tempted to suggest the name "partition". This isn't Fortran-IV. ;) -- Grant Edwards grant.b.edwards Yow! I've got a COUSIN at who works in the GARMENT gmail.com DISTRICT ... From python at mrabarnett.plus.com Thu May 20 12:56:59 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 20 May 2010 17:56:59 +0100 Subject: Strange MySQL Problem In-Reply-To: References: Message-ID: <4BF569DB.9010601@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > I have this code: > > #!/usr/bin/python > > import cgitb; cgitb.enable() > import cgi > import sys,os > sys.path.append(os.getcwd()) > import MySQLdb > from login import login > > def create_edit_passengers4(): > print "Content-Type: text/html" > print > print ''' > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> > > > > ''' > user, passwd, db, host = login() > database = MySQLdb.connect(host, user, passwd, db) > cursor = database.cursor() > form = cgi.FieldStorage() > cursor.execute('create table if not exists Passengers (id int(11) > auto_increment primary key, flights_id int(11) not null, customer_id > int(11) not null, foreign key (id) references Flights (flights_id), > foreign key (id) references Customers (customer_id), name varchar(40), > weight int) engine=InnoDB;') > new_passengers = int(form.getfirst('new_passengers')) > i = 0 > while i < new_passengers: > cursor.execute('insert into Passengers values (Null, %s, %s, "%s", > %s);' % (form.getfirst('%d:flight' % i), form.getfirst('%d:customer' % > i), form.getfirst('%d:name' % i, ''), form.getfirst('%d:weight' % i))) When performing SQL operations, don't insert the values using Python's string formatting, because that makes it vulnerable to SQL-injection attacks, ie don't do this: cursor.execute(sql_command % values) do this: cursor.execute(sql_command, values) > i += 1 > print "All passenger information has successfully been added." > cursor.close() > print "\n" > > create_edit_passengers4() > > Now, it throws no errors; however, it doesn't insert. If I print out the > insert statement to screen and then manually insert it in MySQL it > inserts. Huh?? > I think you need to 'commit' any changes to do to the database. From lists at cheimes.de Thu May 20 13:21:18 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 May 2010 19:21:18 +0200 Subject: Strange MySQL Problem In-Reply-To: <4BF569DB.9010601@mrabarnett.plus.com> References: <4BF569DB.9010601@mrabarnett.plus.com> Message-ID: MRAB wrote: > I think you need to 'commit' any changes to do to the database. Yeah, you are right. Also some RDBMS don't support DDL and DML statements inside one transaction. You may need to commit and begin after the create table DDL. Christian From victorsubervi at gmail.com Thu May 20 13:29:24 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 20 May 2010 13:29:24 -0400 Subject: Strange MySQL Problem In-Reply-To: <4BF569DB.9010601@mrabarnett.plus.com> References: <4BF569DB.9010601@mrabarnett.plus.com> Message-ID: On Thu, May 20, 2010 at 12:56 PM, MRAB wrote: > > When performing SQL operations, don't insert the values using Python's > string formatting, because that makes it vulnerable to SQL-injection > attacks, ie don't do this: > > cursor.execute(sql_command % values) > > do this: > > cursor.execute(sql_command, values) Oh, thank you! > I think you need to 'commit' any changes to do to the database. > Caught by the commit again. Yes, thanks. beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From tomf.sessile at gmail.com Thu May 20 14:17:11 2010 From: tomf.sessile at gmail.com (TomF) Date: Thu, 20 May 2010 11:17:11 -0700 Subject: Global variables for python applications References: <2010051900165614229-tomfsessile@gmailcom> <4bf3f6fc$0$27861$c3e8da3@news.astraweb.com> Message-ID: <2010052011171175-tomfsessile@gmailcom> On 2010-05-19 07:34:37 -0700, Steven D'Aprano said: > # Untested. > def verbose_print(arg, level, verbosity=1): > if level <= verbosity: > print arg > > def my_function(arg): > my_print(arg, level=2) > return arg.upper() > > if __name__ == '__main__': > if '--verbose' in sys.argv: > my_print = functools.partial(verbose_print, verbosity=2) > elif '--quiet' in sys.argv: > my_print = functools.partial(verbose_print, verbosity=0) > > my_function("hello world") > > > Note that although there is no verbosity global setting, every function > that calls my_print will do the right thing (unless I've got the test > backwards...), and if a function needs to override the implicit verbosity > setting, it can just call verbose_print directly. From utente at esempio.net Thu May 20 14:36:58 2010 From: utente at esempio.net (superpollo) Date: Thu, 20 May 2010 20:36:58 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> <4bf5497f$0$12123$4fafbaef@reader4.news.tin.it> Message-ID: <4bf5814b$0$12129$4fafbaef@reader4.news.tin.it> Grant Edwards ha scritto: > On 2010-05-20, superpollo wrote: >> Steven D'Aprano ha scritto: >>> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: >>> >>>> ... how many positive integers less than n have digits that sum up to m: >>>> >>>> In [197]: def prttn(m, n): >>> Does the name "prttn" mean anything? I'm afraid I keep reading it as a >>> mispelling of "print n". >> pArtItIOn > > One might be tempted to suggest the name "partition". no kidding: i was afraid to use some reserved word... From emile at fenx.com Thu May 20 15:19:48 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 20 May 2010 12:19:48 -0700 Subject: 250 In-Reply-To: References: Message-ID: On 5/20/2010 12:39 AM Martin P. Hellwig said... > On 05/20/10 07:51, cosmeticsafrolatino wrote: >> hi > 250 locahost.local Hello WimaxUser3645-219.wateen.net [110.36.45.219], > pleased to meet you :) From invalid at invalid.invalid Thu May 20 15:53:42 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 20 May 2010 19:53:42 +0000 (UTC) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> <4bf5497f$0$12123$4fafbaef@reader4.news.tin.it> <4bf5814b$0$12129$4fafbaef@reader4.news.tin.it> Message-ID: On 2010-05-20, superpollo wrote: > Grant Edwards ha scritto: >> On 2010-05-20, superpollo wrote: >>> Steven D'Aprano ha scritto: >>>> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote: >>>> >>>>> ... how many positive integers less than n have digits that sum up to m: >>>> >>>> Does the name "prttn" mean anything? I'm afraid I keep reading it as >>>> a mispelling of "print n". >>> >>> pArtItIOn >> >> One might be tempted to suggest the name "partition". > > no kidding: i was afraid to use some reserved word... Since Python is interactive, and you don't get charged for each time you run your deck through the reader, that's easy enough to check: $ python Python 2.6.4 (r264:75706, Mar 1 2010, 10:33:43) [GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> partition Traceback (most recent call last): File "", line 1, in NameError: name 'partition' is not defined >>> sum >>> int >>> file Lest my allusions to Fortran IV be lost upon the less grizzled, only the first 6 characters were significant in Fortran IV identifiers, and removing all of the vowels from a longer word was an idiomatic way to create an identifier with a length <= 6. IIRC, the number 6 was originally chosen because that's how many 6-bit characters you could hold in a single 36-bit CPU register. That way when writing a compiler/link/assembly you could compare two identifiers using a single "CMP" instruction. I'm not sure why 36-bits was such a popular ALU width, but many different vendors sold 36-bit machines back in the day. -- Grant Edwards grant.b.edwards Yow! Hand me a pair of at leather pants and a CASIO gmail.com keyboard -- I'm living for today! From emelysite at gmail.com Thu May 20 16:34:39 2010 From: emelysite at gmail.com (women) Date: Thu, 20 May 2010 13:34:39 -0700 (PDT) Subject: Save the message Important Links Message-ID: Save the message Important Links Infertility treatment for free http://echance.info/cj/fb.htm download youtube free and fast http://echance.info/cj/youtube.htm Get mobile talk for free http://echance.info/cj/freephone.htm Call any phone or mobile for free http://echance.info/cj/callphone.htm About your finances to reach in less than an hour Less commission for money transfer http://echance.info/cj/100dayloans.htm The best way to protect your site http://echance.info/cj/sitelock.htm http://echance.info/cj/fasthost.htm http://echance.info/cj/freegames.htm From emelysite at gmail.com Thu May 20 16:36:12 2010 From: emelysite at gmail.com (women) Date: Thu, 20 May 2010 13:36:12 -0700 (PDT) Subject: Infertility treatment for free Message-ID: Infertility treatment for free Bearing and speed of fertilization http://echance.info/cj/fb.htm From emelysite at gmail.com Thu May 20 16:37:04 2010 From: emelysite at gmail.com (women) Date: Thu, 20 May 2010 13:37:04 -0700 (PDT) Subject: Bearing and speed of fertilization Message-ID: <3aaab65d-fce9-4f63-9f6f-dcceb2500b3c@q13g2000vbm.googlegroups.com> Infertility treatment for free Bearing and speed of fertilization http://echance.info/cj/fb.htm From emelysite at gmail.com Thu May 20 16:37:30 2010 From: emelysite at gmail.com (women) Date: Thu, 20 May 2010 13:37:30 -0700 (PDT) Subject: download youtube free and fast Message-ID: <438723d2-ca4c-4db5-9885-dd0f4e5c5529@l6g2000vbo.googlegroups.com> download youtube free and fast http://echance.info/cj/youtube.htm From news1234 at free.fr Thu May 20 16:46:59 2010 From: news1234 at free.fr (News123) Date: Thu, 20 May 2010 22:46:59 +0200 Subject: intervall of about 1 second for xmlrpc calls? In-Reply-To: References: Message-ID: <4bf59fc3$0$23895$426a74cc@news.free.fr> Hi Adam, Adam Tauno Williams wrote: > On Thu, 2010-05-20 at 03:40 -0700, Thomas Lehmann wrote: >>> What's wrong? >> Obviously there's a problem with "localhost". When using the IP of my >> machine everything is working fast. I think you're right. localhost with IPV6 was also a problem for me. At least it was for me on a windows 7 host. I 'solved' the problem by disabling IPV6, but this is a workaround, not a proper solution. > > You box may first be trying to connect to ::1 (ipv6) and when that fails > it falls back to 127.0.0.1. Make sure IPv6 is properly > configured/enabled and try the script again. Do you know why the default config of IPV6 could be wrong on a windows 7 host? Having no experience with IPV6: How should it be configured? How to detect issues? thanks N From awilliam at whitemice.org Thu May 20 16:58:03 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Thu, 20 May 2010 16:58:03 -0400 Subject: intervall of about 1 second for xmlrpc calls? In-Reply-To: <4bf59fc3$0$23895$426a74cc@news.free.fr> References: <4bf59fc3$0$23895$426a74cc@news.free.fr> Message-ID: <1274389083.7821.4.camel@linux-yu4c.site> On Thu, 2010-05-20 at 22:46 +0200, News123 wrote: > Hi Adam, > Adam Tauno Williams wrote: > > On Thu, 2010-05-20 at 03:40 -0700, Thomas Lehmann wrote: > >>> What's wrong? > >> Obviously there's a problem with "localhost". When using the IP of my > >> machine everything is working fast. > I think you're right. > localhost with IPV6 was also a problem for me. At least it was for me > on a windows 7 host. > I 'solved' the problem by disabling IPV6, but this is a workaround, not > a proper solution. > > You box may first be trying to connect to ::1 (ipv6) and when that fails > > it falls back to 127.0.0.1. Make sure IPv6 is properly > > configured/enabled and try the script again. > Do you know why the default config of IPV6 could be wrong on a windows > 7 host? No. This would seem to have something to do with the resolver. If you do a nslookup for localhost what does it say. > Having no experience with IPV6: Have lots, it's really nice. Once you get most things cut over. > How should it be configured? > How to detect issues? Does nslookup localhost return the correct result? That might depend on your DNS server - not your local host. Also "ping ::1"? -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From db3l.net at gmail.com Thu May 20 17:11:55 2010 From: db3l.net at gmail.com (David Bolen) Date: Thu, 20 May 2010 17:11:55 -0400 Subject: What's the matter with docs.python.org? References: Message-ID: Christian Mertes writes: > On Mi, 2010-05-19 at 16:42 -0700, Aahz wrote: >> Also, I think you need to pass the host HTTP header to access >> docs.python.org > > Look, I don't really want to read Python docs via telnet. I basically > wanted to point out that there is strange behaviour and someone might > feel responsible and look into it. I think the point is that if you are going to use telnet as a diagnostic tool you need to more accurately represent the browser. I just tried and using the Host header renders a completely different response than not (presumably because the server is using virtual hosting). With an appropriate "Host: docs.python.org" you get the actual documentation home page, without it you get the "page has moved" text you saw. It may or may not have anything to do with the original problem, but it probably does explain the response you got when you tried to use telnet as a test tool. -- David From jmcmonagle at NO.SPAM.velseis.com.au Thu May 20 18:02:30 2010 From: jmcmonagle at NO.SPAM.velseis.com.au (John McMonagle) Date: Fri, 21 May 2010 08:02:30 +1000 Subject: Display file names in Tkinter Listbox In-Reply-To: References: <4BF4CA7B.6000008@NO.SPAM.velseis.com.au> Message-ID: <4BF5B176.5040006@NO.SPAM.velseis.com.au> sit at home.com wrote: > I have made the modifications and it does print inside the listbox, > however they are all printed on the same line. > Sorry, I didn't realize askopenfilenames returned the filenames as a whitespace separated string, on my system they are returned as a tuple of strings. > My files are named Name.0 Name.1 Name.2 Name.3 etc so I would like > them to be printed sorted on a separate line. When I did a > type(fileNames) it showed me that it was in unicode and printed > character per line, so I tried it this way > > listFileNames = str(fileNames).split(' ') > for fileName in listFileNames: > self.lbox.insert(0, fileName) > > it works but does not print sorted. > > it prints > > name.2 > name.1 > name.0 > name.3 > > You obviously need to sort the list before you loop over the items and add them to your listbox. listFileNames = sorted(str(filenames).split() Regards, John From tdelaney at avaya.com Thu May 20 18:42:56 2010 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 21 May 2010 06:42:56 +0800 Subject: Picking a license In-Reply-To: <87ocgciotv.fsf@benfinney.id.au> References: <87r5ldbw3k.fsf@benfinney.id.au> <87fx1qji9t.fsf@benfinney.id.au> <87ocgciotv.fsf@benfinney.id.au> Message-ID: From: Ben Finney > This thread is already off-topic and too long. I'm conflicted about my role in that; > I have endeavoured only to address falsehoods that IMO were not otherwise being addressed. > > So I'll try to keep this brief. > > Ethan Furman writes: > >> This doesn't make sense to me, but I'm willing to learn -- how do you >> do this in practice? Are you really selling the software > > Perhaps in private email we can discuss what you mean by "really selling the software"; > it's too off-topic here. By my understanding of that term, yes, I am selling software. > >> or rather selling things like setup, support, new code (or time to >> code), etc? > >All of the above, depending on the project. Considering that's one of the only two interesting things that have come out of this discussion, if you're willing to discuss that in public (in another thread) I'd be very interested in reading it. BTW, the other interesting thing is the inadvertent license violations where I tend to think Pat has the right interpretation, but am not sure. For the record, I tend to be in favour of permissive licenses both for releasing my own code and using others' (not least because I am employed by a company and it makes my work easier), but there are good reasons for using any license so long as you understand the consequences of your decision. Tim Delaney From sit at home.com Thu May 20 19:26:41 2010 From: sit at home.com (sit at home.com) Date: Thu, 20 May 2010 19:26:41 -0400 Subject: Display file names in Tkinter Listbox References: <4BF4CA7B.6000008@NO.SPAM.velseis.com.au> <4BF5B176.5040006@NO.SPAM.velseis.com.au> Message-ID: On Fri, 21 May 2010 08:02:30 +1000, John McMonagle wrote: >sit at home.com wrote: > >> I have made the modifications and it does print inside the listbox, >> however they are all printed on the same line. >> > >Sorry, I didn't realize askopenfilenames returned the filenames as a >whitespace separated string, on my system they are returned as a tuple >of strings. > > >> My files are named Name.0 Name.1 Name.2 Name.3 etc so I would like >> them to be printed sorted on a separate line. When I did a >> type(fileNames) it showed me that it was in unicode and printed >> character per line, so I tried it this way >> >> listFileNames = str(fileNames).split(' ') >> for fileName in listFileNames: >> self.lbox.insert(0, fileName) >> >> it works but does not print sorted. >> >> it prints >> >> name.2 >> name.1 >> name.0 >> name.3 >> >> > >You obviously need to sort the list before you loop over the items and >add them to your listbox. > >listFileNames = sorted(str(filenames).split() > > >Regards, > >John Thank you, it worked From catphive at catphive.net Thu May 20 19:57:40 2010 From: catphive at catphive.net (Brendan Miller) Date: Thu, 20 May 2010 16:57:40 -0700 Subject: starting repl programmatically Message-ID: I have a python script that sets up some environmental stuff. I would then like to be able to change back to interactive mode and use that environment. What's the best way to do that? From catphive at catphive.net Thu May 20 20:11:17 2010 From: catphive at catphive.net (Brendan Miller) Date: Thu, 20 May 2010 17:11:17 -0700 Subject: starting repl programmatically In-Reply-To: References: Message-ID: python -i myscript.py almost does what I want. The only problem is if I exit with exit(0) it does *not* enter interactive mode. I have to run off the end of the script as near as I can tell. Is there another way to exit without breaking python -i? On Thu, May 20, 2010 at 4:57 PM, Brendan Miller wrote: > I have a python script that sets up some environmental stuff. I would > then like to be able to change back to interactive mode and use that > environment. What's the best way to do that? > From stef.mientki at gmail.com Thu May 20 20:13:30 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 21 May 2010 02:13:30 +0200 Subject: Ugly modification of a class, can it be done better ? Message-ID: <4BF5D02A.9070600@gmail.com> hello, This might be a strange question, but as a practical guy, I'm not searching for the best solution, but for a practical solution. I've a class which I've used very extensively. Now I want to extend that class with an action on a double click event, but that action is determined by the main program. Normally I would create an derived class and add that specific action. But I find it too much effort in this specific case, half of the instances need the extension, half of it dont. So I want to change the behavior of the class dynamically. I've done it by adding a global variable (Base_Grid_Double_Click) in the module, initial set to None, but can be changed by the main program to some callback function. (see the code below) Is this a valid construction ( sorry I'm not a programmer), or are there better ways to accomplish similar dynamic behavior ? thanks, Stef Mientki #== module grid_library == Base_Grid_Double_Click = None class Base_Grid ( wx.grid.Grid ) : def __init__ ( self, .... self.Bind ( gridlib.EVT_GRID_CELL_LEFT_DCLICK , self._On_Double_Click ) def _On_Double_Click ( self, event ) : if Base_Grid_Double_Click : Row = event.Row Col = event.Col Col_Label = self.GetColLabelValue ( Col ) Row_Label = self.GetRowLabelValue ( Row ) Base_Grid_Double_Click ( self.GetCellValue ( Row, Col ), Col_Label, Row_Label ) else : event.Skip () -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu May 20 20:20:07 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 May 2010 00:20:07 GMT Subject: starting repl programmatically References: Message-ID: <4bf5d1b7$0$27861$c3e8da3@news.astraweb.com> On Thu, 20 May 2010 16:57:40 -0700, Brendan Miller wrote: > I have a python script that sets up some environmental stuff. I would > then like to be able to change back to interactive mode and use that > environment. What's the best way to do that? On most(?) Linux distros, `man python` is your friend. (Like all well- behaviour apps, python should come with a man page.) `python --help` is useful too, and will be platform independent. Both tell me that you want to pass -i as an option to enter the interactive interpreter after running a module or command: [steve at sylar ~]$ python -c "print 'hello world'; x = 2" hello world [steve at sylar ~]$ python -i -c "print 'hello world'; x = 2" hello world >>> x 2 You can also set an environment variable to force the same behaviour. See the help for details. -- Steven From jackdied at gmail.com Thu May 20 20:30:54 2010 From: jackdied at gmail.com (Jack Diederich) Date: Thu, 20 May 2010 20:30:54 -0400 Subject: Ugly modification of a class, can it be done better ? In-Reply-To: <4BF5D02A.9070600@gmail.com> References: <4BF5D02A.9070600@gmail.com> Message-ID: On Thu, May 20, 2010 at 8:13 PM, Stef Mientki wrote: > hello, > > This might be a strange question, but as a practical guy, I'm not searching > for the best solution, but for a practical solution. > > I've a class which I've used very extensively. > Now I want to extend that class with an action on a double click event, but > that action is determined by the main program. > Normally I would create an derived class and add that specific action. > But I find it too much effort in this specific case, half of the instances > need the extension, half of it dont. > So I want to change the behavior of the class dynamically. > I've done it by adding a global variable (Base_Grid_Double_Click) in the > module, > initial set to None, > but can be changed by the main program to some callback function. > (see the code below) > Is this a valid construction ( sorry I'm not a programmer), > or are there better ways to accomplish similar dynamic behavior ? > You can have two classes and then just change the class of the instances that need it. class A(object): def method1(self): pass class B(A): def method2(self): pass ob = A() # click happens ob.__class__ = B -Jack From pmaupin at gmail.com Thu May 20 20:35:06 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 20 May 2010 17:35:06 -0700 (PDT) Subject: starting repl programmatically References: Message-ID: On May 20, 6:57?pm, Brendan Miller wrote: > I have a python script that sets up some environmental stuff. I would > then like to be able to change back to interactive mode and use that > environment. What's the best way to do that? >>> import cmd >>> class MyCmd(cmd.Cmd): ... def default(self, line): ... exec line in globals() ... >>> MyCmd().cmdloop() (Cmd) s = 'The answer is probably to use %s' (Cmd) print s % 'the cmd module' The answer is probably to use the cmd module (Cmd) Regards, Pat From steve at REMOVE-THIS-cybersource.com.au Thu May 20 20:51:34 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 May 2010 00:51:34 GMT Subject: starting repl programmatically References: Message-ID: <4bf5d915$0$27861$c3e8da3@news.astraweb.com> On Thu, 20 May 2010 17:11:17 -0700, Brendan Miller wrote: > python -i myscript.py > > almost does what I want. The only problem is if I exit with exit(0) it > does *not* enter interactive mode. I have to run off the end of the > script as near as I can tell. Is there another way to exit without > breaking python -i? Upgrade to Python 2.6 and it will work as expected. [steve at sylar ~]$ python2.6 -i -c "import sys; sys.exit(0)" Traceback (most recent call last): File "", line 1, in SystemExit: 0 >>> If you're stuck with 2.5, you can wrap your script in a try...except and catch the exit: [steve at sylar ~]$ python -i -c "import sys > try: > x = 2 > sys.exit(0) > except SystemExit: > pass > " >>> x 2 The only side-effect I can think of is that you may lose any non-zero result codes, but you probably do that after entering interactive mode anyway. If you want to be fancy, you can inspect the state of the environment variable and Python options inside the except block, and re-raise if necessary. Untested: except SystemExit: if os.getenv('PYTHONINSPECT'): pass else: raise I can't find a way to check for a -i switch from inside Python 2.5. There is a sys.flags but it is only available in Python 2.6 or higher. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu May 20 21:27:59 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 May 2010 01:27:59 GMT Subject: Ugly modification of a class, can it be done better ? References: <4BF5D02A.9070600@gmail.com> Message-ID: <4bf5e19e$0$27861$c3e8da3@news.astraweb.com> Sorry for breaking threading, but Stef's original post has not come through to me. > On Thu, May 20, 2010 at 8:13 PM, Stef Mientki > wrote: >> So I want to change the behavior of the class dynamically. I've done it >> by adding a global variable (Base_Grid_Double_Click) in the module, >> initial set to None, >> but can be changed by the main program to some callback function. (see >> the code below) How is this supposed to work? If you have *one* global, then *every* instance will see the same setting. To change it dynamically, you enter a nightmare world of having to save the global, modify it, then restore it, every single time. Trust me, I've been there, this is the *worst* way of programming. This is why object oriented inheritance was invented, to escape this nonsense! The first thing is to make the callback specific to the class, not global. Why does your printing code need access to the callback that handles double-clicking on a grid? It doesn't! So don't give it that access (at least, not easy access). Put the callback in the class. class MyClass: callback = None def method(self, *args): if self.callback is None: behaviour_with_no_callback() else: behaviour_with_callback() Now if you want to apply a callback to some instances, and not others, it is totally simple: red = MyClass() blue = MyClass() red.callback = my_callback_function and you're done. If you have lots of instances that use the same callback? Make a subclass. class MyDottedClass(MyClass): pass red = MyClass() blue = MyClass() red_with_green_dots = MyDottedClass() blue_with_green_dots = MyDottedClass() MyDottedClass.callback = dotted_callback And now all the dot instances will use the same callback without effecting the undotted instances. What to change them all to use a different behaviour? MyDottedClass.callback = something_different and now they all change, again without effecting the undotted instances. >> Is this a valid construction ( sorry I'm not a programmer), or are >> there better ways to accomplish similar dynamic behavior ? Of course you're a programmer! You're writing programs, aren't you? -- Steven From darcy at druid.net Thu May 20 22:11:42 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 20 May 2010 22:11:42 -0400 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf45d5b$0$8837$c3e8da3@news.astraweb.com> <4bf5497f$0$12123$4fafbaef@reader4.news.tin.it> <4bf5814b$0$12129$4fafbaef@reader4.news.tin.it> Message-ID: <20100520221142.3b810d8d.darcy@druid.net> On Thu, 20 May 2010 19:53:42 +0000 (UTC) Grant Edwards wrote: > Since Python is interactive, and you don't get charged for each time > you run your deck through the reader, that's easy enough to check: Whoa! For a moment there I thought it was 1969. :-) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From mehgcap at gmail.com Thu May 20 22:56:42 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 20 May 2010 22:56:42 -0400 Subject: optional argument to a subclass of a class Message-ID: Hi all, I am now trying to allow my classes, all of which subclass a single class (if that is the term), to provide optional arguments. Here is some of my code: class Craft(): def __init__(self, name, isAircraft=False, id=helpers.id(), hits=0, weapons=[]): self.name=name self.id=id self.hits=hits self.weapons=weapons self.isAircraft=isAircraft #end def #end class #now a class for each type of craft in the game #each will subclass the Craft class, but each also has its own settings class Battleship(Craft): def __init__(self, name, maxHits): Craft.__init__(self, name) self.maxHits=maxHits self.length=maxHits #in Battleship, each ship's length is the same as how many times it can be hit #end def #end class I want to be able to say something like b=Battleship("battleship1", 4, weapons=["missile1","missile2"]) When I do that, though, I get a traceback on the above line saying "type error: __init__() got an unexpected keyword argument 'weapons'". What did I do wrong / what do I need to change so that any Craft (Battleship, Carrier, and so on) can optionally provide a list of weapons, or any other arguments to which I assign default values in my Craft class? I hope this makes sense. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From pmaupin at gmail.com Thu May 20 23:04:53 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 20 May 2010 20:04:53 -0700 (PDT) Subject: optional argument to a subclass of a class References: Message-ID: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> On May 20, 9:56?pm, Alex Hall wrote: > Hi all, > I am now trying to allow my classes, all of which subclass a single > class (if that is the term), to provide optional arguments. Here is > some of my code: > > class Craft(): > ?def __init__(self, > ?name, > ?isAircraft=False, > ?id=helpers.id(), > ?hits=0, > ?weapons=[]): > ? self.name=name > ? self.id=id > ? self.hits=hits > ? self.weapons=weapons > ? self.isAircraft=isAircraft > ?#end def > #end class > > #now a class for each type of craft in the game > #each will subclass the Craft class, but each also has its own settings > > class Battleship(Craft): > ?def __init__(self, > ?name, > ?maxHits): > ? Craft.__init__(self, name) > ? self.maxHits=maxHits > ? self.length=maxHits #in Battleship, each ship's length is the same > as how many times it can be hit > ?#end def > #end class > > I want to be able to say something like > b=Battleship("battleship1", 4, weapons=["missile1","missile2"]) > When I do that, though, I get a traceback on the above line saying > "type error: __init__() got an unexpected keyword argument 'weapons'". > What did I do wrong / what do I need to change so that any Craft > (Battleship, Carrier, and so on) can optionally provide a list of > weapons, or any other arguments to which I assign default values in my > Craft class? I hope this makes sense. > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg... at gmail.com;http://www.facebook.com/mehgcap You overrode the __init__method from the superclass. One thing you can do is in battleship, you can accept additional keyword arguments: def __init__(self, name, ..., **kw): Then you could invoke the superclass's init: Craft.__init__(self, name, **kw) Regards, Pat From mehgcap at gmail.com Thu May 20 23:35:01 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 20 May 2010 23:35:01 -0400 Subject: optional argument to a subclass of a class In-Reply-To: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> Message-ID: On 5/20/10, Patrick Maupin wrote: > On May 20, 9:56 pm, Alex Hall wrote: >> Hi all, >> I am now trying to allow my classes, all of which subclass a single >> class (if that is the term), to provide optional arguments. Here is >> some of my code: >> >> class Craft(): >> def __init__(self, >> name, >> isAircraft=False, >> id=helpers.id(), >> hits=0, >> weapons=[]): >> self.name=name >> self.id=id >> self.hits=hits >> self.weapons=weapons >> self.isAircraft=isAircraft >> #end def >> #end class >> >> #now a class for each type of craft in the game >> #each will subclass the Craft class, but each also has its own settings >> >> class Battleship(Craft): >> def __init__(self, >> name, >> maxHits): >> Craft.__init__(self, name) >> self.maxHits=maxHits >> self.length=maxHits #in Battleship, each ship's length is the same >> as how many times it can be hit >> #end def >> #end class >> >> I want to be able to say something like >> b=Battleship("battleship1", 4, weapons=["missile1","missile2"]) >> When I do that, though, I get a traceback on the above line saying >> "type error: __init__() got an unexpected keyword argument 'weapons'". >> What did I do wrong / what do I need to change so that any Craft >> (Battleship, Carrier, and so on) can optionally provide a list of >> weapons, or any other arguments to which I assign default values in my >> Craft class? I hope this makes sense. >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehg... at gmail.com;http://www.facebook.com/mehgcap > > You overrode the __init__method from the superclass. I know, I thought I had to in order to make all of Craft's attribs available to the Battleship. Is that not the case? > > One thing you can do is in battleship, you can accept additional > keyword arguments: > > def __init__(self, name, ..., **kw): > > Then you could invoke the superclass's init: > > Craft.__init__(self, name, **kw) So how do I get at anything inside **kw? Is it a list? > > Regards, > Pat > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From wuwei23 at gmail.com Thu May 20 23:50:54 2010 From: wuwei23 at gmail.com (alex23) Date: Thu, 20 May 2010 20:50:54 -0700 (PDT) Subject: optional argument to a subclass of a class References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> Message-ID: <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> Patrick Maupin wrote: > One thing you can do is in battleship, you can accept additional > keyword arguments: > > ? ? def __init__(self, name, ..., **kw): > > Then you could invoke the superclass's init: > > ? ? Craft.__init__(self, name, **kw) _All_ of which is covered in the tutorial. At what point do we expect people to actually put some effort into learning the language themselves? Is this why we're constantly spammed with "write my code for me" requests? If you're asking _basic_ "how do I" questions, and you don't even have the common sense to read through the support docs before doing so, then you really should be directing questions here: http://mail.python.org/mailman/listinfo/tutor From pmaupin at gmail.com Thu May 20 23:51:21 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 20 May 2010 20:51:21 -0700 (PDT) Subject: optional argument to a subclass of a class References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> Message-ID: <9c894192-e758-49f3-91e9-ca2554c90b10@j9g2000vbp.googlegroups.com> On May 20, 10:35?pm, Alex Hall wrote: > So how do I get at anything inside **kw? Is it a list? It's a dictionary. Use *args for a list. (As with self, the name is whatever you want to use, but some sort of consistency is nice.) One of the cool things about Python is how easy it is to play at the command prompt: >>> def foo(x=3, y=7): ... print x,y ... >>> def sam(**kw): ... print kw ... foo(**kw) ... >>> sam(x=5) {'x': 5} 5 7 >>> sam(y='hi there') {'y': 'hi there'} 3 hi there >>> sam(z=42) {'z': 42} Traceback (most recent call last): File "", line 1, in File "", line 3, in sam TypeError: foo() got an unexpected keyword argument 'z' >>> Regards, Pat From mehgcap at gmail.com Fri May 21 00:22:11 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 00:22:11 -0400 Subject: optional argument to a subclass of a class In-Reply-To: <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> Message-ID: On 5/20/10, alex23 wrote: > Patrick Maupin wrote: >> One thing you can do is in battleship, you can accept additional >> keyword arguments: >> >> def __init__(self, name, ..., **kw): >> >> Then you could invoke the superclass's init: >> >> Craft.__init__(self, name, **kw) > > _All_ of which is covered in the tutorial. At what point do we expect > people to actually put some effort into learning the language > themselves? Is this why we're constantly spammed with "write my code > for me" requests? I am certainly NOT asking anyone to write my code for me. In fact, I almost never copy and paste code, since writing it myself helps me to both remember it and examine it to see what is going on and figure out why it works. I am basically teaching myself Python; my experience is in Java (basic), JS (somewhat advanced), and a smattering of other languages. I have rarely dealt with classes before, and certainly not sub-classing. I have googled all of this and have read the docs and tutorials, but nothing made sense enough for me to figure out why I would be getting my particular error. I have since updated each ship's __init__ to accept all the arguments that Craft accepts so that I can support all optional arguments, but I thought subclassing was supposed to take care of this for me... Suppose not. > > If you're asking _basic_ "how do I" questions, and you don't even have > the common sense to read through the support docs before doing so, > then you really should be directing questions here: > http://mail.python.org/mailman/listinfo/tutor Again, I have read the docs. I often find them quite useful, but there are times where a new concept, in a relatively new language, just will not work and a doc is not going to say "at this point in your code, you should to A instead of B, because..." > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From dpalmboom at evafoam.co.za Fri May 21 02:03:43 2010 From: dpalmboom at evafoam.co.za (dpalmboom) Date: Fri, 21 May 2010 08:03:43 +0200 Subject: Help with PyQt4 tabwidget setup Message-ID: I am creating an application and I'm busy designing the main layout on the main window. What I would like to do is the following: Create a QTabWidget with a QVBoxLayout already inside it and also a scrollbar inside it. When a user triggers a menu item, a QDockWidget must be created and inserted into the QVBoxLayout, but it must not stretch to the bottom of the QTabWidget. The QDockWidget must keep a set size in the QVBoxLayout. When the user triggers another menu item, the next QDockWidget must go above or below the existing QDockWidgets in the QVBoxLayout. I currently have the following code for the QTabWidget: class PaneTabWidget(PyQt4.QtGui.QTabWidget): def __init__(self, tabs, parent=None): """ A tabwidget to go inside a Pane. """ super(PaneTabWidget, self).__init__(parent) for tab in tabs: if tab == "Properties": self.propertiesBin() elif tab == "Schedule": self.scheduleBin() elif tab == "Pricelist": self.pricelistBin() def setLayoutAndScrollBar(self, page): pass def addPanel(self, panel, type): self.addTab(panel, type) def propertiesBin(self): self.page = PyQt4.QtGui.QWidget() self.addTab(self.page, "Properties") self.setLayoutAndScrollBar(self.page) Right now, the dockwidget gets put into a new tab in the tab widget, but I would like to put it into an existing QVBoxLayout. I currently have a blank QWidget as a "placeholder" page of the tabwidget. If anyone can help me with this, it would be greatly appreciated. Thanks From chricki at gmx.net Fri May 21 02:51:44 2010 From: chricki at gmx.net (chris) Date: Fri, 21 May 2010 08:51:44 +0200 Subject: socket.getsockopt() and SO_ORIGINAL_DST Message-ID: Hi guys, On netfilter-based NAT systems there is theoretically a possibility to retrieve the original address *after* NAT'ing a connection. In C, this can be done as in squid, a transparent HTTP proxy: http://paste.pocoo.org/show/216495/ I'd like to do the same in Python. So I started with a small script: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 2626)) s.listen(1) conn, addr = s.accept() dst = conn.getsockopt(socket.SOL_IP, socket.SO_ORIGINAL_DST) Since SO_ORIGINAL_DST is not defined in socket.py, the program fails: AttributeError: 'module' object has no attribute 'SO_ORIGINAL_DST' So I thought I'd be smart and look up the constant myself. Indeed, I found it to be defined in: /usr/include/linux/netfilter_ipv4.h:75:#define SO_ORIGINAL_DST 80 I replaced the getsockopt() call with dst = conn.getsockopt(socket.SOL_IP, 80) and ran into a new problem: Traceback (most recent call last): File "listen.py", line 14, in dst = conn.getsockopt(socket.SOL_IP, 80) File "", line 1, in getsockopt socket.error: [Errno 22] Invalid argument In C, everything works fine. But I really need this problem to be solved in Python. Do you have any ideas? Thanks for any support in advance and regards, Chris PS: I know there are ugly work-arounds to parse /proc/net/ip_conntrack to do this job, but I will defenitely avoid that. From rnlatimer at gmail.com Fri May 21 03:19:56 2010 From: rnlatimer at gmail.com (Neal) Date: Fri, 21 May 2010 00:19:56 -0700 (PDT) Subject: Solutions for finding the 1000th prime Message-ID: I'm doing the MIT OpenCourseWare class that this assignment hails from and I don't doubt that its a relatively common assignment. Upon searching for it for some ideas of why my program wouldn't work one of the top results is this a thread from this group full of derision and sarcasm. Believe me I understand that the people here don't want to do another person's homework but for someone who isn't going to be coding for a living or is a hobbyist like I am, there could be some useful information. Eventually I figured out what I was doing wrong, and I was hoping to add some insight. At this point in the lectures about all we've learned to deal with as far as commands are: while, if, else, elif and some boolean operators. I started defining three variables I would need: One to count how many primes I have Which number I'm currently checking to be a prime Current number I'm dividing by as my checker The assignment states that its easiest to check all odd integers > 1 but not to forget that 2 is a prime, easiest probably just to start your counter at 1, I didn't but it took an extra 3 lines just to get my counter to 1, and then get to the next number I'm checking all without being in a usable loop. You start your loop with the stated condition, no need for it to run any more past counting the 1000th prime. You could have your program check to see if a number is divisible by every number less than itself and if so moving on to your next number. However you do know that any number isn't going to be divisible by another number in that sequence until it reaches itself divided by 2. If you keep in mind though that we are only dealing with odd numbers, you know that they will not be divisible by two, so instead we can move on to itself divided by 3. Every iteration of the loop when it finds a prime, needs to increase the count, move onto the next candidate you're checking, and redefine the divisor you're starting to check next time around. If a number is determined not to be a prime you need to move onto the next candidate and redefine your divisor (which is where I was stuck for a long time writing this program). If your not sure that the number is a prime or not a prime you simply need to redefine the divisor and continue the loop. From steve at REMOVE-THIS-cybersource.com.au Fri May 21 03:43:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 May 2010 07:43:37 GMT Subject: optional argument to a subclass of a class References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> Message-ID: <4bf639a9$0$27861$c3e8da3@news.astraweb.com> On Thu, 20 May 2010 23:35:01 -0400, Alex Hall wrote: >> You overrode the __init__method from the superclass. > > I know, I thought I had to in order to make all of Craft's attribs > available to the Battleship. Is that not the case? No, the opposite in fact. One of the basic features of objects (at least as implemented by Python, and many other languages) is inheritance. That is, a class inherits behaviour and state (methods and attributes) from its parent class (or classes). So if you have a class A and a subclass B, B inherits behaviour from A: >>> class A: ... def method(self): ... print("method in A") ... >>> class B(A): ... pass ... >>> b = B() >>> b.method() method in A But if you override method, then Python doesn't *automatically* call the parent's method. How can it know where to call it, and what to do with the result? Should it call it before the new method, or after, or somewhere in the middle? It's impossible to tell. >>> class C(A): ... def method(self): ... print("called from C") ... >>> c = C() >>> c.method() called from C If you want both behaviours, then you have to explicitly call the parent class, and pass the current instance as an argument: >>> class D(A): ... def method(self): ... print("called from D") ... A.method(self) ... >>> d = D() >>> d.method() called from D method in A Exactly the same rules apply to __init__, with the added complication that frequently you want to modify the function signature: >>> class Sandwich: ... def __init__(self, filling, bread='white'): ... self.filling = filling ... self.bread = bread ... def __str__(self): ... return ("%s on two slices of %s bread" % ... (self.filling, self.bread)) ... >>> s = Sandwich("cheese", "rye") >>> print(s) cheese on two slices of rye bread >>> >>> class BLT(Sandwich): ... def __init__(self): ... Sandwich.__init__(self, "bacon, lettuce and tomato", ... "sour dough") ... >>> b = BLT() >>> print(b) bacon, lettuce and tomato on two slices of sour dough bread Hope this helps. -- Steven From __peter__ at web.de Fri May 21 04:07:47 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2010 10:07:47 +0200 Subject: optional argument to a subclass of a class References: Message-ID: Alex Hall wrote: > Hi all, > I am now trying to allow my classes, all of which subclass a single > class (if that is the term), to provide optional arguments. Here is > some of my code: > > class Craft(): > def __init__(self, > name, > isAircraft=False, > id=helpers.id(), > hits=0, > weapons=[]): > self.name=name > self.id=id > self.hits=hits > self.weapons=weapons > self.isAircraft=isAircraft > #end def > #end class > > > #now a class for each type of craft in the game > #each will subclass the Craft class, but each also has its own settings > > class Battleship(Craft): > def __init__(self, > name, > maxHits): > Craft.__init__(self, name) > self.maxHits=maxHits > self.length=maxHits #in Battleship, each ship's length is the same > as how many times it can be hit > #end def > #end class > > > I want to be able to say something like > b=Battleship("battleship1", 4, weapons=["missile1","missile2"]) > When I do that, though, I get a traceback on the above line saying > "type error: __init__() got an unexpected keyword argument 'weapons'". > What did I do wrong / what do I need to change so that any Craft > (Battleship, Carrier, and so on) can optionally provide a list of > weapons, or any other arguments to which I assign default values in my > Craft class? I hope this makes sense. You have to repeat the arguments for the base class in the Battleship initializer. Battleship(...) will only invoke Battleship.__init__(...), not Craft.__init__(...) -- so you have to do that explicitly inside Battleship.__init__() while passing along all parameters it is supposed to process. As simplified example: class Craft(object): def __init__(self, name, id=None, weapons=None): if id is None: id = helpers.id() if weapons is None: weapons = [] self.name = name self.id = id self.weapons = weapons class Battleship(Craft): def __init__(self, name, id=None, weapons=None, max_hits=None): Craft.__init__(self, name, id, weapons) self.max_hits = max_hits Notice how using None to signal that a value was not provided simplifies things; without it you'd have to put a meanigful default for weapons into both the Craft and Battleship class. If you want a unique id for every Craft providing helpers.id() as a default is just wrong; default arguments are calculated once and you would end up with the same id for every Craft instance. Peter From chricki at gmx.net Fri May 21 04:26:04 2010 From: chricki at gmx.net (chris) Date: Fri, 21 May 2010 10:26:04 +0200 Subject: socket.getsockopt() and SO_ORIGINAL_DST In-Reply-To: References: Message-ID: Hi guys, I found a solution myself in O'Reilly's Security Power Tools. It works seamlessly as follows: from socket import * SO_ORIGINAL_DST = 80 s = socket(AF_INET, SOCK_STREAM) s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) s.bind(('192.168.255.254', 80)) s.listen(1) conn, addr = s.accept() dst = conn.getsockopt(SOL_IP, SO_ORIGINAL_DST, 16) srv_port, srv_ip = struct.unpack("!2xH4s8x", dst) print "original %s:%d" % (inet_ntoa(srv_ip), srv_port) Basically, my fault was not specifying the buffer length :( Have fun with it, whoever needs it. Regards, Chris chris wrote: > Hi guys, > > On netfilter-based NAT systems there is theoretically a possibility to > retrieve the original address *after* NAT'ing a connection. In C, this > can be done as in squid, a transparent HTTP proxy: > > http://paste.pocoo.org/show/216495/ > > > I'd like to do the same in Python. So I started with a small script: > > import socket > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind(('', 2626)) > s.listen(1) > conn, addr = s.accept() > dst = conn.getsockopt(socket.SOL_IP, socket.SO_ORIGINAL_DST) > > > > Since SO_ORIGINAL_DST is not defined in socket.py, the program fails: > AttributeError: 'module' object has no attribute 'SO_ORIGINAL_DST' > > So I thought I'd be smart and look up the constant myself. Indeed, I > found it to be defined in: > > /usr/include/linux/netfilter_ipv4.h:75:#define SO_ORIGINAL_DST 80 > > I replaced the getsockopt() call with > > dst = conn.getsockopt(socket.SOL_IP, 80) > > and ran into a new problem: > > Traceback (most recent call last): > File "listen.py", line 14, in > dst = conn.getsockopt(socket.SOL_IP, 80) > File "", line 1, in getsockopt > socket.error: [Errno 22] Invalid argument > > > In C, everything works fine. But I really need this problem to be solved > in Python. Do you have any ideas? > > Thanks for any support in advance and regards, > Chris > > PS: I know there are ugly work-arounds to parse /proc/net/ip_conntrack > to do this job, but I will defenitely avoid that. > From __peter__ at web.de Fri May 21 04:36:31 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2010 10:36:31 +0200 Subject: Solutions for finding the 1000th prime References: Message-ID: Neal wrote: > I'm doing the MIT OpenCourseWare class that this assignment hails from > and I don't doubt that its a relatively common assignment. Upon > searching for it for some ideas of why my program wouldn't work one of > the top results is this a thread from this group full of derision and > sarcasm. Believe me I understand that the people here don't want to do > another person's homework but for someone who isn't going to be coding > for a living or is a hobbyist like I am, there could be some useful > information. Eventually I figured out what I was doing wrong, and I > was hoping to add some insight. At this point in the lectures about > all we've learned to deal with as far as commands are: while, if, > else, elif and some boolean operators. I'd like to bring your attention to my contribution to the above-mentioned thread. http://mail.python.org/pipermail/python-list/2009-November/1226626.html I posted it late in the thread's life because like you I disliked the direction the "discussion" was taking. My answer is not so much about an efficient solution to the actual problem, but more about how to approach a programming problem that initially seems to be over your head. As a long time reader I can confirm that if you show that you have made a minimum effort to solve even "homeworky" problems you usually get constructive hints on comp.lang.python. There is also a mailing list http://mail.python.org/mailman/listinfo/tutor for the absolute beginner. Peter From rafalgulinski at gmail.com Fri May 21 05:10:36 2010 From: rafalgulinski at gmail.com (rav) Date: Fri, 21 May 2010 02:10:36 -0700 (PDT) Subject: intervall of about 1 second for xmlrpc calls? References: Message-ID: I had similar problem with SimpleXMLRPCServer Create the request handler class class ExtendedXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): # originally this one was slowing down my server A LOT due to DNS settings!!! def log_request(self, *args): pass and put it in your SimpleXMLRPCServer constructor (...) class MyServer(threading.Thread): def __init__(self, host, port): threading.Thread.__init__(self) self.server = SimpleXMLRPCServer((host, port), ExtendedXMLRPCRequestHandler) self.server.register_function(self.is_even, "is_even") self.server.register_function(self.stop, "stop_server") (...) I would also change all 'localhost' occurences in the code to ip '127.0.0.1'. Good luck! Rafal From samuelrobertson at gmail.com Fri May 21 05:23:09 2010 From: samuelrobertson at gmail.com (sam) Date: Fri, 21 May 2010 02:23:09 -0700 (PDT) Subject: CGI python 3 write RAW BINARY References: <4bd8ae7e$0$27615$ba4acef3@reader.news.orange.fr> <4bd96540$0$27597$ba4acef3@reader.news.orange.fr> <4bd9b4c2$0$27606$ba4acef3@reader.news.orange.fr> <4bd9fc1a$0$2980$ba4acef3@reader.news.orange.fr> <4bdc07d4$0$2980$ba4acef3@reader.news.orange.fr> <4be424a8$0$27586$ba4acef3@reader.news.orange.fr> Message-ID: On May 7, 7:33?am, Dodo wrote: > Le 01/05/2010 12:52, Dodo a ?crit : > > > > > > > Le 30/04/2010 17:52, Antoine Pitrou a ?crit : > >> Le Thu, 29 Apr 2010 23:37:32 +0200, Dodo a ?crit : > >>> ....I don't get a thing. > >>> Now with the fix : > >>> All browsers shows a different thing, but not the image! > >>>http://ddclermont.homeip.net/misc/python/ > > >>> If I save it to computer : > >>> * Windows image viewer won't read it > >>> * Irfanview can read it without problems > > >> Did you set the content-type and content-length in the HTTP headers? > >> Can you post your code? > > > I didn't know about content-lenght > > Here's the new code (I used a fixed image patch to make sure this is not > > the source of the problem) > > > #!/usr/bin/python3 > > import cgi, sys, cgitb > > cgitb.enable() > > > f = open("/home/dodo/54.jpg", "rb") > > data = f.read() > > l = len(data) > > f.close() > > > print("Content-type:image/jpg\nContent-length:%d\n\n" % l) > > > sys.stdout.flush() > > sys.stdout.buffer.write( data ) > > > Dorian > > Anyone? Yes for windows you need to call this before you write it out. And yes its totally retarded that you have to do this. The whole point of python is that I don't have to worry about the particular system its running on. def __SetStdOutForWindowsToBinaryMode(): # Without this method a windows server will translate '\n' into '\r\n' # even for binary output. This probably isn't needed on linux servers # so the exception will be caught harmlessly. # At some point we may have to worry about switching this mode *back* to original # (see http://bytes.com/topic/python/answers/30987-cgi-proplem-displaying-image) try: import msvcrt,os msvcrt.setmode( 1, os.O_BINARY ) # 1 = stdout; use 0 for stdin except ImportError: pass From kaklis at gmail.com Fri May 21 06:12:03 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 21 May 2010 03:12:03 -0700 (PDT) Subject: client server console app with cmd library References: <5577f90a-e8d9-43b4-bad5-9a10b17a2fdd@e28g2000vbd.googlegroups.com> Message-ID: <25d0000c-acaf-43b5-ab97-f91c9d79b0e3@k31g2000vbu.googlegroups.com> On May 20, 1:54?am, "kak... at gmail.com" wrote: > Hi to all, > i need some hints about a console application i' m trying. > I want to make it act as a client and as a server at a same time. > And since it is a console application i' m using cmd library. > I want something that works like asterisk. while working with my app > i want to listen for incoming requests, that they appear automatically > at my console. > Any design considerations? > Do i have to use threads? > Please i want your advice. > Any examples somewhere? > > Thanks in advance! > Antonis Hi again. I wonder is my question stupid, or what i want can't be done? From doctoresam at gmail.com Fri May 21 06:21:11 2010 From: doctoresam at gmail.com (Deep_Feelings) Date: Fri, 21 May 2010 03:21:11 -0700 (PDT) Subject: where are the program that are written in python? Message-ID: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> python is not a new programming language ,it has been there for the last .... 15+ years or so ? right ? however by having a look at this page http://wiki.python.org/moin/Applications i could not see many programs written in python (i will be interested more in COMMERCIAL programs written in python ). and to be honest ,i tried some of the programs in that list and all the programs that i tried either dead projects or so buggy ! 1- where are the programs that is written in python ? 2- python is high productivity language : why there are no commercial programs written in python ? is python a valid practical programming language ? why it is not used in commercial software ? please don't mention programs where python was used as a glue ,those programs are not actually written in python. any help will be appreciated thank you From simon at brunningonline.net Fri May 21 06:35:40 2010 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 21 May 2010 11:35:40 +0100 Subject: where are the program that are written in python? In-Reply-To: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On 21 May 2010 11:21:11 UTC+1, Deep_Feelings wrote: > 1- where are the programs that is written in python ? > 2- python is high productivity language : why there are no commercial > programs written in python ? See http://www.python.org/about/success/ -- Cheers, Simon B. From martin.hellwig at dcuktec.org Fri May 21 06:37:42 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 21 May 2010 11:37:42 +0100 Subject: where are the program that are written in python? In-Reply-To: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On 05/21/10 11:21, Deep_Feelings wrote: > python is not a new programming language ,it has been there for the > last .... 15+ years or so ? right ? Yeah about the same as Java > > however by having a look at this page http://wiki.python.org/moin/Applications > i could not see many programs written in python (i will be interested > more in COMMERCIAL programs written in python ). and to be honest ,i > tried some of the programs in that list and all the programs that i > tried either dead projects or so buggy ! It's a wiki, if anybody is interested they could change the page, I actually have never looked at it. > > 1- where are the programs that is written in python ? > 2- python is high productivity language : why there are no commercial > programs written in python ? > > is python a valid practical programming language ? > why it is not used in commercial software ? My experience is that Python is the FreeBSD of the programming languages. For example, the average user knows mac and windows, the average admin knows there is also something like linux, and the average linux admin knows there is also something like BSD. > > please don't mention programs where python was used as a glue ,those > programs are not actually written in python. Python is used in a lot in custom applications, while off the shelve software needs a lot of buzzwords to shift any market interest. I have participated in a couple of 'pure' Python programs, used by Airbus, Randstad and a whole fleet of small firms. But yes, off the shelve software seems to be either written in Java or any .net equivalent. > > any help will be appreciated > > thank you hth -- mph From ninmonkeys at gmail.com Fri May 21 06:49:37 2010 From: ninmonkeys at gmail.com (Jake b) Date: Fri, 21 May 2010 05:49:37 -0500 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: did this not go to the list? Arg, reply does in other mailing list. On Fri, May 21, 2010 at 5:48 AM, Jake b wrote: > I took it as game-domain only question: > I don't know of any big game written in python. ( meaning python code, > using c++ libs. ) Verses games that at their is in c++ , calling a scripting > language under the hood. > Even if a game is written at its base in python, it still uses python > libraries which can use c++ under the hood. > > WoW had a huge amount of logic, in LUA combined with xml. Was cool seeing > the crazy things implemented. > > There are a lot that use a c++ engine, with a scripting engine under the > hood. python, lua, unrealscript, etc... Civ4 uses python for map generation. > Not sure how much else? > Wouldn't be surprised, alpha centauria even had text files you could mod > the game with. > > Unreal games: U, UT, UT2k4, etc.. (since before UT original, use > scripting(unreal script) to control basically everything.) There are > classes, and methods that 'do the work' in c++ for speed. > > From development point, You're on a deadline, if your company all know the > existing language/engine/api, there isn't much incentive to learn a new api, > and convert existing code, and not having all the previous examples, and > api's. [ That can even mean using game engine X, even if Y is in the same > language, and is technically better. ] > > > -- > Jake > -- Jake -------------- next part -------------- An HTML attachment was scrubbed... URL: From ninmonkeys at gmail.com Fri May 21 06:54:59 2010 From: ninmonkeys at gmail.com (Jake b) Date: Fri, 21 May 2010 05:54:59 -0500 Subject: client server console app with cmd library In-Reply-To: <25d0000c-acaf-43b5-ab97-f91c9d79b0e3@k31g2000vbu.googlegroups.com> References: <5577f90a-e8d9-43b4-bad5-9a10b17a2fdd@e28g2000vbd.googlegroups.com> <25d0000c-acaf-43b5-ab97-f91c9d79b0e3@k31g2000vbu.googlegroups.com> Message-ID: Networking can be hard. I'd suggest checking out these libs. pygame mastermind: http://www.pygame.org/project-Mastermind+Networking+Lib-859-1773.html podSixNet : http://mccormick.cx/projects/PodSixNet/ twisted: http://wiki.python.org/moin/Twisted-Examples lots of references in the answers to this StackOverflow post: http://stackoverflow.com/questions/78704/good-python-network-programing-resource Twisted is the hardest in that list to get into. -- Jake -------------- next part -------------- An HTML attachment was scrubbed... URL: From doctoresam at gmail.com Fri May 21 07:12:18 2010 From: doctoresam at gmail.com (Deep_Feelings) Date: Fri, 21 May 2010 04:12:18 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> On May 21, 1:35?pm, Simon Brunning wrote: > On 21 May 2010 11:21:11 UTC+1, Deep_Feelings wrote: > > Seehttp://www.python.org/about/success/ thankx for reply. from that list i have a feeling that python is acting only as "quick and dirty work" nothing more ! From stefan_ml at behnel.de Fri May 21 07:13:10 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 21 May 2010 13:13:10 +0200 Subject: [ANN] oStri: Cython optimized String object In-Reply-To: <20100521063717.GD37105@mail.fu-manchu.org> References: <20100521063717.GD37105@mail.fu-manchu.org> Message-ID: Mike 'Fuzzy' Partin, 21.05.2010 08:37: > Optimized String-like Object is kind of a misnomer in that, the object > provided is a subclass of the base str type, adding optimized (Cython > bindings to the standard (POSIX) libc regex and string functions) > match() and sub() methods. Hi, could you give an idea what the advantage of this package is? Why would one want to use it? Also, while the main class is a subclass of str, it doesn't take advantage of that fact at all. Stefan From news1234 at free.fr Fri May 21 07:19:40 2010 From: news1234 at free.fr (News123) Date: Fri, 21 May 2010 13:19:40 +0200 Subject: where are the program that are written in python? In-Reply-To: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: <4bf66c4c$0$22462$426a74cc@news.free.fr> Deep_Feelings wrote: > On May 21, 1:35 pm, Simon Brunning wrote: >> On 21 May 2010 11:21:11 UTC+1, Deep_Feelings wrote: >> >> Seehttp://www.python.org/about/success/ > > thankx for reply. > > from that list i have a feeling that python is acting only as "quick > and dirty work" nothing more ! Too bad, that still nobody feels insulted isn't it? From sunckell at gmail.com Fri May 21 07:20:25 2010 From: sunckell at gmail.com (Chad Kellerman) Date: Fri, 21 May 2010 07:20:25 -0400 Subject: unique values of a Dictionary list (removing duplicate elements of a list) Message-ID: Python users, I am parsing an AIX trace file and creating a dictionary containing keys (PIDS) and values (a list of TIDS). With PIDS being unique process ids and TIDS, being a list of thread ids. My function populates the keys so that they are unique, but my list contains duplicates. Can someone point me in the right direction so that my dictionary value does not contain duplicate elements? here is what I got. -------------------------------- pidtids = {} # --- function to add pid and tid to a dictionary def addpidtids(pid,tid): pidtids.setdefault(pid,[]).append(tid) # --- function to parse a file def grep(pattern, fileObj, include_line_nums=False): r=[] compgrep = re.compile(pattern) for line_num, line in enumerate(fileObj): if compgrep.search(line): info = line.split() p = info[7].lstrip("pid=") t = info[8].lstrip("tid=") addpidtids(p,t) # process trace.int tf = open(tracefile, 'r') grep("cmd=java pid",tf) tf.close() -------------------------------- Any help would be greatly appreciated. Thanks, Chad -- A grasshopper walks into a bar and the bartender says "Hey, we have a drink named after you." And the grasshopper says "Really, You have a drink named Murray?" -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Fri May 21 07:22:27 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 21 May 2010 21:22:27 +1000 Subject: where are the program that are written in python? In-Reply-To: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: On Fri, May 21, 2010 at 9:12 PM, Deep_Feelings wrote: > thankx for reply. > > from that list i have a feeling that python is acting only as "quick > and dirty work" nothing more ! > You might have just offended a lot of people on the list here.... Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon at brunningonline.net Fri May 21 07:28:34 2010 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 21 May 2010 12:28:34 +0100 Subject: where are the program that are written in python? In-Reply-To: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: On 21 May 2010 12:12:18 UTC+1, Deep_Feelings wrote: > from that list i have a feeling that python is acting only as "quick > and dirty work" nothing more ! Really? Well, in any case, I can tell you that I know of a number of large commercial web sites built with Django. I just can't tell you what they are. ;-) -- Cheers, Simon B. From wolfgang at rohdewald.de Fri May 21 07:32:12 2010 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Fri, 21 May 2010 13:32:12 +0200 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <201005211332.12853.wolfgang@rohdewald.de> On Freitag 21 Mai 2010, Jake b wrote: > > I don't know of any big game written in python. ( meaning > > python code, using c++ libs would you call 8702 python statements big? If so, Kajongg would be a candidate. -- Wolfgang From __peter__ at web.de Fri May 21 07:50:06 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2010 13:50:06 +0200 Subject: unique values of a Dictionary list (removing duplicate elements of a list) References: Message-ID: Chad Kellerman wrote: > Python users, > I am parsing an AIX trace file and creating a dictionary containing > keys (PIDS) and values (a list of TIDS). With PIDS being unique process > ids > and TIDS, being a list of thread ids. My function populates the keys so > that they are unique, but my list contains duplicates. > > Can someone point me in the right direction so that my dictionary > value > does not contain duplicate elements? > > > here is what I got. > > -------------------------------- > > pidtids = {} > > # --- function to add pid and tid to a dictionary > def addpidtids(pid,tid): > pidtids.setdefault(pid,[]).append(tid) Use a set instead of a list (and maybe a defaultdict): from collections import defaultdict pidtids = defaultdict(set) def addpidtids(pid, tid): pidtids[pid].add(tid) Peter From sunckell at gmail.com Fri May 21 08:07:49 2010 From: sunckell at gmail.com (Chad Kellerman) Date: Fri, 21 May 2010 08:07:49 -0400 Subject: unique values of a Dictionary list (removing duplicate elements of a list) In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__peter__ at web.de> wrote: > Chad Kellerman wrote: > > > Python users, > > I am parsing an AIX trace file and creating a dictionary containing > > keys (PIDS) and values (a list of TIDS). With PIDS being unique process > > ids > > and TIDS, being a list of thread ids. My function populates the keys so > > that they are unique, but my list contains duplicates. > > > > Can someone point me in the right direction so that my dictionary > > value > > does not contain duplicate elements? > > > > > > here is what I got. > > > > -------------------------------- > > > > pidtids = {} > > > > # --- function to add pid and tid to a dictionary > > def addpidtids(pid,tid): > > pidtids.setdefault(pid,[]).append(tid) > > Use a set instead of a list (and maybe a defaultdict): > > from collections import defaultdict > > pidtids = defaultdict(set) > > def addpidtids(pid, tid): > pidtids[pid].add(tid) > > Peter > Thanks. I guess I should have posted this in my original question. I'm on 2.4.3 looks like defautldict is new in 2.5. I'll see if I can upgrade. Thanks again. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- A grasshopper walks into a bar and the bartender says "Hey, we have a drink named after you." And the grasshopper says "Really, You have a drink named Murray?" -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri May 21 08:13:53 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 08:13:53 -0400 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On 5/21/10, Peter Otten <__peter__ at web.de> wrote: > Alex Hall wrote: > >> Hi all, >> I am now trying to allow my classes, all of which subclass a single >> class (if that is the term), to provide optional arguments. Here is >> some of my code: >> >> class Craft(): >> def __init__(self, >> name, >> isAircraft=False, >> id=helpers.id(), >> hits=0, >> weapons=[]): >> self.name=name >> self.id=id >> self.hits=hits >> self.weapons=weapons >> self.isAircraft=isAircraft >> #end def >> #end class >> >> >> #now a class for each type of craft in the game >> #each will subclass the Craft class, but each also has its own settings >> >> class Battleship(Craft): >> def __init__(self, >> name, >> maxHits): >> Craft.__init__(self, name) >> self.maxHits=maxHits >> self.length=maxHits #in Battleship, each ship's length is the same >> as how many times it can be hit >> #end def >> #end class >> >> >> I want to be able to say something like >> b=Battleship("battleship1", 4, weapons=["missile1","missile2"]) >> When I do that, though, I get a traceback on the above line saying >> "type error: __init__() got an unexpected keyword argument 'weapons'". >> What did I do wrong / what do I need to change so that any Craft >> (Battleship, Carrier, and so on) can optionally provide a list of >> weapons, or any other arguments to which I assign default values in my >> Craft class? I hope this makes sense. > > You have to repeat the arguments for the base class in the Battleship > initializer. Battleship(...) will only invoke Battleship.__init__(...), not > Craft.__init__(...) -- so you have to do that explicitly inside > Battleship.__init__() while passing along all parameters it is supposed to > process. As simplified example: > > class Craft(object): > def __init__(self, name, id=None, weapons=None): > if id is None: > id = helpers.id() > if weapons is None: > weapons = [] > self.name = name > self.id = id > self.weapons = weapons > > class Battleship(Craft): > def __init__(self, name, id=None, weapons=None, max_hits=None): > Craft.__init__(self, name, id, weapons) > self.max_hits = max_hits > > Notice how using None to signal that a value was not provided simplifies > things; without it you'd have to put a meanigful default for weapons into > both the Craft and Battleship class. If you want a unique id for every Craft > providing helpers.id() as a default is just wrong; default arguments are > calculated once and you would end up with the same id for every Craft > instance. Yes, I found that out the hard way :), but it made perfect sense as soon as I realized that I was not getting unique IDs; the class() statement is just a fancy function call in Python, as I understand it, so of course it would be called only once, not each time I make a new instance. > > Peter > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From awilliam at whitemice.org Fri May 21 08:16:27 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 21 May 2010 08:16:27 -0400 Subject: intervall of about 1 second for xmlrpc calls? In-Reply-To: References: Message-ID: <1274444187.7777.0.camel@linux-yu4c.site> On Fri, 2010-05-21 at 02:10 -0700, rav wrote: > I had similar problem with SimpleXMLRPCServer > Create the request handler class > class ExtendedXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): > # originally this one was slowing down my server A LOT due to DNS > settings!!! > def log_request(self, *args): > pass > and put it in your SimpleXMLRPCServer constructor > (...) > class MyServer(threading.Thread): > def __init__(self, host, port): > threading.Thread.__init__(self) > self.server = SimpleXMLRPCServer((host, port), > ExtendedXMLRPCRequestHandler) > self.server.register_function(self.is_even, "is_even") > self.server.register_function(self.stop, "stop_server") > (...) > I would also change all 'localhost' occurences in the code to ip > '127.0.0.1'. Or the better solution is to fix your resolver. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From awilliam at whitemice.org Fri May 21 08:37:14 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 21 May 2010 08:37:14 -0400 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <1274445434.7777.20.camel@linux-yu4c.site> On Fri, 2010-05-21 at 11:37 +0100, Martin P. Hellwig wrote: > On 05/21/10 11:21, Deep_Feelings wrote: > > however by having a look at this page http://wiki.python.org/moin/Applications > > i could not see many programs written in python (i will be interested > > more in COMMERCIAL programs written in python ). and to be honest ,i > > tried some of the programs in that list and all the programs that i > > tried either dead projects or so buggy ! Most projects are dead projects; that is just the natural state of things regardless of language. Just browse Sourceforge for awhile. > It's a wiki, if anybody is interested they could change the page, I > actually have never looked at it. I've looked it over, there is some interesting stuff. But why contribute a story when you could be coding on your project! A perennial problem. :) > > 1- where are the programs that is written in python ? > > 2- python is high productivity language : why there are no commercial > > programs written in python ? > > is python a valid practical programming language ? > > why it is not used in commercial software ? I suppose it depends on your use of the term "used". It is used a *lot* in the SOA / Workflow world - in the form of Jython. That provides a very nice way to extend Java applications [it is still Python! Python is a language, not a runtime]. In general to 'core' of large applications are, IMO, easier to maintain in the more rigid statically typed languages as the toolchain can do more work for you. Of course someone here will have a fit about that statement. > > please don't mention programs where python was used as a glue Why not? And what about Gwibber? Zeitgeist? BitTorrent? Zope/Plone? Those are all certainly "real" applications. Zope is almost an industry unto itself. > ,those programs are not actually written in python. I think your distinction is not valid. "glue" is a vital part of every enterprise. And the sophistication of some "glue" certainly surpasses many "applications". > Python is used in a lot in custom applications, while off the shelve > software needs a lot of buzzwords to shift any market interest. > I have participated in a couple of 'pure' Python programs, used by > Airbus, Randstad and a whole fleet of small firms. But yes, off the > shelve software seems to be either written in Java or any .net equivalent. is an interesting read. Certainly the 'packaging' mechanism is less end-user friendly than .NET. I personally would not choose to create an end-user application in Python; but it has become my first choice for server-side development. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From awilliam at whitemice.org Fri May 21 08:46:33 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 21 May 2010 08:46:33 -0400 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> <4bf3eeeb$0$31263$607ed4bc@cv.net> <3c40f8d8-b29c-484f-b5b3-6dff0f68a032@m21g2000vbr.googlegroups.com> <16c9daac-293a-4cb6-b847-489e696682bd@c11g2000vbe.googlegroups.com> Message-ID: <1274445993.7777.23.camel@linux-yu4c.site> On Thu, 2010-05-20 at 22:58 -0700, Dennis Lee Bieber wrote: > On Thu, 20 May 2010 02:45:10 -0700 (PDT), Jimoid > declaimed the following in > gmane.comp.python.general: > > I've now had a closer look at both pyODBC and mxODBC and it seems to > > me that they both require the database to be running to be able to > > query it. Is this correct? If so I think I will have to use mdb-* as > > the database I want to query is not running. > To my knowledge, all "ODBC" modules (in any language) rely upon a > DBMS specific driver. Correct (of course, so does DB-API if you are using a 'native' Python connection). > Where the DB-API definition defines the common > Python side of a database interface, ODBC defines a common OS-level > interface to the DBMS, using a named driver (driver specified in the > connection string or, for Windows, externally with the connection string > specifying the connection definition) There is no distinction between how ODBC operates on Windows or LINUX. Both use the same connection strings [provided the drivers have the same names]. > to translate ODBC calls into actual DBMS calls. Yes, just like a DB-API provider, except that the 'translation' happens in the ODBC driver. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From sunckell at gmail.com Fri May 21 09:17:25 2010 From: sunckell at gmail.com (Chad Kellerman) Date: Fri, 21 May 2010 09:17:25 -0400 Subject: unique values of a Dictionary list (removing duplicate elements of a list) In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 8:07 AM, Chad Kellerman wrote: > > > On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__peter__ at web.de> wrote: > >> Chad Kellerman wrote: >> >> > Python users, >> > I am parsing an AIX trace file and creating a dictionary >> containing >> > keys (PIDS) and values (a list of TIDS). With PIDS being unique process >> > ids >> > and TIDS, being a list of thread ids. My function populates the keys so >> > that they are unique, but my list contains duplicates. >> > >> > Can someone point me in the right direction so that my dictionary >> > value >> > does not contain duplicate elements? >> > >> > >> > here is what I got. >> > >> > -------------------------------- >> > >> > pidtids = {} >> > >> > # --- function to add pid and tid to a dictionary >> > def addpidtids(pid,tid): >> > pidtids.setdefault(pid,[]).append(tid) >> >> Use a set instead of a list (and maybe a defaultdict): >> >> from collections import defaultdict >> >> pidtids = defaultdict(set) >> >> def addpidtids(pid, tid): >> pidtids[pid].add(tid) >> >> Peter >> > > Thanks. I guess I should have posted this in my original question. > > I'm on 2.4.3 looks like defautldict is new in 2.5. > > I'll see if I can upgrade. > > Thanks again. > instead of upgrading.. (probably be faster to use techniques in available 2.4.3) Couldn't I check to see if the pid exists (has_key I believe) and then check if the tid is a value, in the the list for that key, prior to passing it to the function? Or would that be too 'expensive'? > > > >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > A grasshopper walks into a bar and the bartender says "Hey, we have a drink > named after you." And the grasshopper says "Really, You have a drink named > Murray?" > -- A grasshopper walks into a bar and the bartender says "Hey, we have a drink named after you." And the grasshopper says "Really, You have a drink named Murray?" -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri May 21 09:46:55 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2010 15:46:55 +0200 Subject: unique values of a Dictionary list (removing duplicate elements of a list) References: Message-ID: Chad Kellerman wrote: > On Fri, May 21, 2010 at 8:07 AM, Chad Kellerman > wrote: > >> >> >> On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__peter__ at web.de> wrote: >> >>> Chad Kellerman wrote: >>> >>> > Python users, >>> > I am parsing an AIX trace file and creating a dictionary >>> containing >>> > keys (PIDS) and values (a list of TIDS). With PIDS being unique >>> > process ids >>> > and TIDS, being a list of thread ids. My function populates the keys >>> > so that they are unique, but my list contains duplicates. >>> > >>> > Can someone point me in the right direction so that my dictionary >>> > value >>> > does not contain duplicate elements? >>> > >>> > >>> > here is what I got. >>> > >>> > -------------------------------- >>> > >>> > pidtids = {} >>> > >>> > # --- function to add pid and tid to a dictionary >>> > def addpidtids(pid,tid): >>> > pidtids.setdefault(pid,[]).append(tid) >>> >>> Use a set instead of a list (and maybe a defaultdict): >>> >>> from collections import defaultdict >>> >>> pidtids = defaultdict(set) >>> >>> def addpidtids(pid, tid): >>> pidtids[pid].add(tid) >>> >>> Peter >>> >> >> Thanks. I guess I should have posted this in my original question. >> >> I'm on 2.4.3 looks like defautldict is new in 2.5. >> >> I'll see if I can upgrade. >> >> Thanks again. >> > > > instead of upgrading.. (probably be faster to use techniques in available > 2.4.3) > > Couldn't I check to see if the pid exists (has_key I believe) and then > check if the tid is a value, in the the list for that key, prior to > passing it to the function? > > Or would that be too 'expensive'? No. pidtids = {} def addpidtids(pid, tid): if pid in pidtids: pidtids[pid].add(tid) else: pidtids[pid] = set((tid,)) should be faster than def addpidtids(pid, tid): pidtids.setdefault(pid, set()).add(tid) and both should work in python2.4. Peter From invalid at invalid.invalid Fri May 21 10:20:39 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 21 May 2010 14:20:39 +0000 (UTC) Subject: Another "Go is Python-like" article. Message-ID: In a recent Reg article, there's yet more yammering on about how Go is somehow akin to Python -- referring to Go as a "Python-C++" crossbreed. http://www.theregister.co.uk/2010/05/20/go_in_production_at_google/ I still don't get it. What about Go, exactly, do people see as Phython-like? Go doesn't seem to have any of the salient features (either syntactic or semantic) of Python other than garbage collection. How is Go not just warmed-over Java? -- Grant Edwards grant.b.edwards Yow! RELATIVES!! at gmail.com From cournape at gmail.com Fri May 21 11:30:11 2010 From: cournape at gmail.com (David Cournapeau) Date: Sat, 22 May 2010 00:30:11 +0900 Subject: Another "Go is Python-like" article. In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 11:20 PM, Grant Edwards wrote: > In a recent Reg article, there's yet more yammering on about how Go is > somehow akin to Python -- referring to Go as a "Python-C++" crossbreed. > > http://www.theregister.co.uk/2010/05/20/go_in_production_at_google/ > > I still don't get it. > > What about Go, exactly, do people see as Phython-like? I guess the type system without a strict hierarchy, as well as very fast compilation enabling fast iteration. Granted, a lot of languages have those features nowadays, and I doubt anyone would speaks about it if it was not where it was coming from. The fact that google feels the need to create a new system programming language is maybe the most interesting fact of it ? cheers, David From timoverbeek10 at gmail.com Fri May 21 11:50:56 2010 From: timoverbeek10 at gmail.com (timo verbeek) Date: Fri, 21 May 2010 08:50:56 -0700 (PDT) Subject: creating addon system Message-ID: What is the easiest way in python to create a addon system? I found to easy ways: * using a import system like this: for striper in stripers: if striper["enabled"]: exec("from strip import %s as _x"%striper["striper"]) string = _x.start(string) * using exec for striper in stripers: if striper["enabled"]: use=open(stripper) exec(use) Do you now is the best way? From keobox at gmail.com Fri May 21 11:54:44 2010 From: keobox at gmail.com (keobox) Date: Fri, 21 May 2010 08:54:44 -0700 (PDT) Subject: Problem with an huge dictionary References: <70b8f82e-2dfe-4403-ae77-cb4d005578f1@y12g2000vbr.googlegroups.com> Message-ID: <40f4fe52-c4e9-43c6-b0be-4fd6da91555d@c11g2000vbe.googlegroups.com> On 20 Mag, 12:58, Thomas Lehmann wrote: > > The question is: > > Is there a limit on the number of entries a dictionary can have i > > jython? > > > I wrote a little app where my data is stored in a huge dictionary > > (11746 entries) generated with a python script. > > When I try to import the dictionary, jython complains with the > > following message: > > 1) You did not say what you have saved (content of your dictionary). - As you can see I received the error when I tried to import jmoco_event_data.py module from the jython interpreter prompt. - The "import" will cause the module compilation, jython will produce a .class file instead of .pyc. - jmoco_event_data.py contains 4 dictionaries: typesValToName={ 220:'EMS_EVENT_EMS_INTERNAL_BASE', 221:'EMS_EVENT_INTERNAL_TYPE_BASE', 222:'EMS_EVENT_INTERNAL_N_E_P_M_EVENT', 223:'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD', 224:'EMS_EVENT_NE_SPECIFIC_BASE', ... 11746 entries int key: string value } typesNameToVal={ 'EMS_EVENT_EMS_INTERNAL_BASE':220, 'EMS_EVENT_INTERNAL_TYPE_BASE':221, 'EMS_EVENT_INTERNAL_N_E_P_M_EVENT':222, 'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD':223, 'EMS_EVENT_NE_SPECIFIC_BASE':224, ... total 11746 entries string key: int value } causesValToName={ 0:'NOT_APPLICABLE_UNKNOWN', 1:'SOFTWARE_CAUSE_UNKNOWN', 2:'ABSENT_MODULE', 3:'FAULTY_MODULE', ... 483 entries int key: string value } causesNameToVal={ 'NOT_APPLICABLE_UNKNOWN':0, 'SOFTWARE_CAUSE_UNKNOWN':1, 'ABSENT_MODULE':2, 'FAULTY_MODULE':3, ... 483 entries string key: int value } > 2) You did not say how you have saved. The dictionaries are in the jmoco_event_data.py module. > From the callstack - also I have never used jython - it looks like > that > there is a try to create a class. It looks like - I may be wrong - > that > you have saved user objects in your dictionary - have you? Nope, the dictionaries are only int to string mappings and string to int mappings > If so you might fail on loading those objects - especially when your > program > does not have the code for it. The failure happens during module's import, so my question is: Is jython able to handle such big dictionaries? > More details are required... jmoco_event_data.py has a size of roughly 700KB. From albert at spenarnc.xs4all.nl Fri May 21 12:02:23 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 21 May 2010 16:02:23 GMT Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bf5814b$0$12129$4fafbaef@reader4.news.tin.it> Message-ID: In article , Grant Edwards wrote: > >Lest my allusions to Fortran IV be lost upon the less grizzled, only >the first 6 characters were significant in Fortran IV identifiers, and >removing all of the vowels from a longer word was an idiomatic way to >create an identifier with a length <= 6. > >IIRC, the number 6 was originally chosen because that's how many 6-bit >characters you could hold in a single 36-bit CPU register. That way >when writing a compiler/link/assembly you could compare two >identifiers using a single "CMP" instruction. > >I'm not sure why 36-bits was such a popular ALU width, but many >different vendors sold 36-bit machines back in the day. 16 bit mini computers were popular: the pdp11. Now 3 FORTRAN char's fitted in one word (radix 40). At least it helped to shoe horn identifier names into two words. > >-- >Grant Edwards grant.b.edwards Yow! Hand me a pair of > at leather pants and a CASIO > gmail.com keyboard -- I'm living > for today! -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From python at bdurham.com Fri May 21 12:04:11 2010 From: python at bdurham.com (python at bdurham.com) Date: Fri, 21 May 2010 12:04:11 -0400 Subject: string.Template.safe_substitute() with % type formatting? Message-ID: <1274457851.6768.1376258583@webmail.messagingengine.com> Python 2.6: Is there a programming technique or 3rd party formatting module that supports string.Template.safe_substitute() type string substituion with % type formatting rules for width, decimals, justification, etc? Or do I need to use a 3rd party template engine to get the best of both worlds? Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From albert at spenarnc.xs4all.nl Fri May 21 12:43:00 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 21 May 2010 16:43:00 GMT Subject: help need to write a python spell checker References: Message-ID: In article , Terry Reedy wrote: >On 5/19/2010 3:17 AM, CM wrote: >> I love how he just copied and pasted the assignment without any other >> remarks. > >Yeah, that way he did not mess it up ;-). OTOH it may be a copyright infringement. Or is posting an assignment to a newsgroup "fair use"? Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From jason.scheirer at gmail.com Fri May 21 12:51:34 2010 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Fri, 21 May 2010 09:51:34 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <03cb4e4e-23c9-4525-ab60-c67312038631@s4g2000prh.googlegroups.com> On May 21, 3:21?am, Deep_Feelings wrote: > python is not a new programming language ,it has been there for the > last .... 15+ years or so ? right ? > > however by having a look at this pagehttp://wiki.python.org/moin/Applications > i could not see many programs written in python (i will be interested > more in COMMERCIAL programs written in python ). and to be honest ,i > tried some of the programs in that list and all the programs that i > tried either dead projects or so buggy ! > > 1- where are the programs that is written in python ? > 2- python is high productivity language : why there are no commercial > programs written in python ? > > is python a valid practical programming language ? > why it is not used in commercial software ? > > please don't mention programs where python was used as a glue ,those > programs are not actually written in python. > > any help will be appreciated > > thank you I write commercial software full-time in Python (well, mixed with C++) at ESRI. I have been able to make a living developing in Python full time at various places for the last 4 years. I can assure you that there is plenty of commercial software out there that uses Python. The reason you don't *see* it is because the development language for a commercial product is a lot less important than the functionality of the product, so "WRITTEN IN PYTHON!!!!" is likely not going to be a bullet point on a marketing slide. And quite frankly, it should be a trade secret for the companies enlightened enough to use it as their language of choice because it is to productive that it provides a competitive advantage. From nagle at animats.com Fri May 21 13:29:40 2010 From: nagle at animats.com (John Nagle) Date: Fri, 21 May 2010 10:29:40 -0700 Subject: Strange MySQL Problem In-Reply-To: References: <4BF569DB.9010601@mrabarnett.plus.com> Message-ID: <4bf6bd55$0$1587$742ec2ed@news.sonic.net> Christian Heimes wrote: > MRAB wrote: >> I think you need to 'commit' any changes to do to the database. > > Yeah, you are right. > Also some RDBMS don't support DDL and DML statements inside one > transaction. You may need to commit and begin after the create table DDL. > > Christian Er, yes. Generally, you don't try a create on every insert transaction. Since your create has foreign keys, it will fail if the other tables don't already exist. So you need to have a more organized way of setting up the database. InnoDB is a proper transaction database. You must commit after insert or the inserts will be properly rolled back and undone after database disconnect. John Nagle From victorsubervi at gmail.com Fri May 21 13:31:04 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 21 May 2010 13:31:04 -0400 Subject: Another Strange MySQL Problem Message-ID: Hi; When I try to execute this code from my Python script, I get this error: Traceback (most recent call last): File "/var/www/html/creative.vi/clients/sea-flight/reservations/create_edit_bags3.py", line 38, in ? create_edit_bags3() File "/var/www/html/creative.vi/clients/sea-flight/reservations/create_edit_bags3.py", line 32, in create_edit_bags3 cursor.execute('insert into Baggage values (Null, %s, %s, %s, %s)', (flight_id, customer_id, weight, ticket_no)) File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue OperationalError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`seaflight/Baggage`, CONSTRAINT `Baggage_ibfk_2` FOREIGN KEY (`customer_id`) REFERENCES `Customers` (`id`))') However, when I try from the MySQL prompt after duly printing it out from the code, it works. Why? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri May 21 13:52:16 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2010 13:52:16 -0400 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On 5/20/2010 10:56 PM, Alex Hall wrote: A couple of style comments for you to consider. > class Craft(): > def __init__(self, > name, > isAircraft=False, > id=helpers.id(), > hits=0, > weapons=[]): Not indenting lines after def makes the code harder to read for me, and, I expect, many others here who use indentation as a cue. If you want one param per line, give them extra indents if you want. > self.name=name > self.id=id > self.hits=hits > self.weapons=weapons > self.isAircraft=isAircraft > #end def > #end class #end markers are fine for private code but are distracting noise to me, and, I expect, other experienced Python coders. Terry Jan Reedy From mehgcap at gmail.com Fri May 21 14:08:39 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 14:08:39 -0400 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On 5/21/10, Terry Reedy wrote: > On 5/20/2010 10:56 PM, Alex Hall wrote: > > A couple of style comments for you to consider. > >> class Craft(): >> def __init__(self, >> name, >> isAircraft=False, >> id=helpers.id(), >> hits=0, >> weapons=[]): > > Not indenting lines after def makes the code harder to read for me, and, > I expect, many others here who use indentation as a cue. If you want one > param per line, give them extra indents if you want. Good point, I had not considered that; Python's relyance on indentation made me think that indenting past the level of the class would cause problems. > >> self.name=name >> self.id=id >> self.hits=hits >> self.weapons=weapons >> self.isAircraft=isAircraft >> #end def >> #end class > > #end markers are fine for private code but are distracting noise to me, > and, I expect, other experienced Python coders. I will try to remember to remove them for posting, but I find them immensely helpful; using a screen reader, and so not being able to look at code and see the indentation, means that I have to have a way to tell myself where things end, much like braces in other languages. When I post here I will try to remove them, but for code I zip and put on my website they have to stay since I rely on them and the zip is just what I am working on at the time, plus there are a lot of those comments to remove from an entire project. > > Terry Jan Reedy > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From lists at cheimes.de Fri May 21 14:10:34 2010 From: lists at cheimes.de (Christian Heimes) Date: Fri, 21 May 2010 20:10:34 +0200 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: Am 21.05.2010 04:56, schrieb Alex Hall: > Hi all, > I am now trying to allow my classes, all of which subclass a single > class (if that is the term), to provide optional arguments. Here is > some of my code: > > class Craft(): > def __init__(self, > name, > isAircraft=False, > id=helpers.id(), > hits=0, > weapons=[]): I hope you are aware that helpers.id() is called just once when the *class* is defined and that the list weapons is shared across all instances of the craft class. :) Have you read about *args and **kwargs in the Python docs? I bet you find them useful for your problem. Christian From rnlatimer at gmail.com Fri May 21 14:12:14 2010 From: rnlatimer at gmail.com (Neal) Date: Fri, 21 May 2010 11:12:14 -0700 (PDT) Subject: Solutions for finding the 1000th prime References: Message-ID: <44049f3a-3fdd-4d64-953a-9445f4707b31@o39g2000vbd.googlegroups.com> You did provide a very constructive answer and I do apologize for generalizing the group or all the posts. And while the original poster did not seem to have made much of an effort, the tone of the initial response of that thread turns off anyone else who may be willing to make that effort. I also want people who may have forgotten to understand how early this problem shows up in an Introduction to Computer Science course. In this class its the second assignment, right after the obligatory 'Hello World!' variant. I'm sure that while finding solutions and new keywords is integral to learning how to program in a language, defining the a function isn't a tool that has been introduced quite yet, as simple as it may seem. Thank you for the link to the mailing list as well. From tjreedy at udel.edu Fri May 21 14:16:40 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2010 14:16:40 -0400 Subject: where are the program that are written in python? In-Reply-To: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: On 5/21/2010 7:12 AM, Deep_Feelings wrote: > On May 21, 1:35 pm, Simon Brunning wrote: >> On 21 May 2010 11:21:11 UTC+1, Deep_Feelings wrote: >> >> Seehttp://www.python.org/about/success/ > > thankx for reply. > > from that list i have a feeling that python is acting only as "quick > and dirty work" nothing more ! Try 'quick and clean' and you would be more accurate. But that would not be so trollish, would it? tjr From pmaupin at gmail.com Fri May 21 14:20:04 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 21 May 2010 11:20:04 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On May 21, 5:21?am, Deep_Feelings wrote: > i could not see many programs written in python Well you could try PyPi, or even a search on googlecode. > (i will be interested > more in COMMERCIAL programs written in python ). What do you mean by commercial, and why? > and to be honest ,i > tried some of the programs in that list and all the programs that i > tried either dead projects or so buggy ! So, you want us to believe that you desperately want to pay someone for working Python software, but are finding it hard to find some? > 1- where are the programs that is written in python ? All over the place. > 2- python is high productivity language : why there are no commercial > programs written in python ? There are a lot of commercial programs written in Python. But any company which thinks it has a lock on some kind of super secret sauce isn't going to use Python, because it's very easy to reverse engineer even compiled Python programs. Also, any company in a competitive market where execution speed is extremely important might choose some other language because, frankly, the fact that a development tool is highly productive is not something that the end user directly cares about. (But the up-front choice of another language simply for speed, rather than prototyping with Python and then recoding the slow bits, would probably be a decision borne of ignorance.) > is python a valid practical programming language ? Absolutely. I've been using it heavily for 11 years, for real work, for which I get paid. > why it is not used in commercial software ? What makes you think that it's not? Is this some kind of "big lie" strategy? To what end? > any help will be appreciated It's hard to help when you don't describe the problem. Reading between the lines, the most charitable and probable interpretation of your problem I can come up with is that you think you're going to create a multi-billion dollar computer program and you're desperately trying to validate your preconceived notion that Python isn't the language to write it in. Sorry, but I can't help with that. Regards, Pat From krister.svanlund at gmail.com Fri May 21 14:32:46 2010 From: krister.svanlund at gmail.com (Krister Svanlund) Date: Fri, 21 May 2010 20:32:46 +0200 Subject: creating addon system In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 5:50 PM, timo verbeek wrote: > What is the easiest way in python to create a addon system? > I found to easy ways: > * using a import system like this: > ? ? ? for striper in stripers: > ? ? ? ?if striper["enabled"]: > ? ? ? ? ? ?exec("from strip import %s as _x"%striper["striper"]) > ? ? ? ? ? ?string = _x.start(string) > * using exec > ? ? ? for striper in stripers: > ? ? ? ?if striper["enabled"]: > ? ? ? ? ? ?use=open(stripper) > ? ? ? ? ? ?exec(use) > > Do you now is the best way? > -- > http://mail.python.org/mailman/listinfo/python-list > Check this one out: http://docs.python.org/library/functions.html#__import__ From mehgcap at gmail.com Fri May 21 14:38:16 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 14:38:16 -0400 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On 5/21/10, Christian Heimes wrote: > Am 21.05.2010 04:56, schrieb Alex Hall: >> Hi all, >> I am now trying to allow my classes, all of which subclass a single >> class (if that is the term), to provide optional arguments. Here is >> some of my code: >> >> class Craft(): >> def __init__(self, >> name, >> isAircraft=False, >> id=helpers.id(), >> hits=0, >> weapons=[]): > > I hope you are aware that helpers.id() is called just once when the > *class* is defined and that the list weapons is shared across all > instances of the craft class. :) I know id is called once, but what do you mean weapons is shared? > > Have you read about *args and **kwargs in the Python docs? I bet you > find them useful for your problem. > > Christian > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From debatem1 at gmail.com Fri May 21 14:40:05 2010 From: debatem1 at gmail.com (geremy condra) Date: Fri, 21 May 2010 11:40:05 -0700 Subject: where are the program that are written in python? In-Reply-To: <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: On Fri, May 21, 2010 at 4:12 AM, Deep_Feelings wrote: > On May 21, 1:35?pm, Simon Brunning wrote: >> On 21 May 2010 11:21:11 UTC+1, Deep_Feelings wrote: >> >> Seehttp://www.python.org/about/success/ > > thankx for reply. > > from that list i have a feeling that python is acting only as "quick > and dirty work" nothing more ! Yeah, there's not really a lot of industry support. If only we could get a huge search engine like bing to use python extensively we'd be in a lot better shape. Geremy Condra From python.list at tim.thechases.com Fri May 21 14:40:49 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 21 May 2010 13:40:49 -0500 Subject: Another Strange MySQL Problem In-Reply-To: References: Message-ID: <4BF6D3B1.2070605@tim.thechases.com> On 05/21/2010 12:31 PM, Victor Subervi wrote: > cursor.execute('insert into Baggage values (Null, %s, %s, %s, > %s)', (flight_id, customer_id, weight, ticket_no)) You're trying to insert stuff... > OperationalError: (1452, 'Cannot add or update a child row: a foreign > key constraint fails (`seaflight/Baggage`, CONSTRAINT `Baggage_ibfk_2` > FOREIGN KEY (`customer_id`) REFERENCES `Customers` (`id`))') But the value you're giving for the customer_id doesn't exist in the Customers table (as mandated by the FK). Or perhaps the column-order for Baggage isn't what you think it is. I always specify it explicitly: INSERT INTO Baggage ( something, flight_id, customer_id, weight, ticket_no ) VALUES (Null, %s, %s, %s, %s) just in case the table column-order ever changes during a database update. -tkc From tjreedy at udel.edu Fri May 21 14:47:53 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2010 14:47:53 -0400 Subject: where are the program that are written in python? In-Reply-To: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On 5/21/2010 6:21 AM, Deep_Feelings wrote: > python is not a new programming language ,it has been there for the > last .... 15+ years or so ? right ? > > however by having a look at this page http://wiki.python.org/moin/Applications > i could not see many programs written in python (i will be interested > more in COMMERCIAL programs written in python ). and to be honest ,i There are two kinds of 'commercial' programs. 1. The vast majority are proprietary programs kept within a company for its own use. As long as these work as intended, they are mostly invisible to the outside world. 2. Programs sold to anyone who wants them. Python trades programmer speed for execution speed. If a successful Python program is going to be run millions of times, it makes economic sense to convert time-hogging parts to (for instance) C. In fact, this is a consideration in deciding what functions should be builtin and which stdlib modules are written or rewritten in C. Programs being sold tend to be compared to competitors on speed with perhaps more weight than they rationally should. Speed is easier to measure than, for instance, lack of bugs. Python programs can be and sometimes are distributed as .exe files. The users of such neither know nor care that some of the source is Python. > tried some of the programs in that list and all the programs that i > tried either dead projects or so buggy ! > > 1- where are the programs that is written in python ? Mostly kept private. For instance, GvR, Python's inventor, spent part of his first year at Google writing a neat-looking programmer console program in Python (Mondrian) designed to improve the productivity of Google programmers. As far as I know, Google has not released it. > please don't mention programs where python was used as a glue ,those > programs are not actually written in python. A C program glues together micro-coded functions. Even a 'pure' CPython program glues together C-coded functions. Some are in builtins, some are imported from the stdlib, and some can be imported from 3rd party packages. The extensibility of CPython is part of its design. Terry Jan Reedy From __peter__ at web.de Fri May 21 14:48:27 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2010 20:48:27 +0200 Subject: optional argument to a subclass of a class References: Message-ID: Alex Hall wrote: > On 5/21/10, Christian Heimes wrote: >> Am 21.05.2010 04:56, schrieb Alex Hall: >>> Hi all, >>> I am now trying to allow my classes, all of which subclass a single >>> class (if that is the term), to provide optional arguments. Here is >>> some of my code: >>> >>> class Craft(): >>> def __init__(self, >>> name, >>> isAircraft=False, >>> id=helpers.id(), >>> hits=0, >>> weapons=[]): >> >> I hope you are aware that helpers.id() is called just once when the >> *class* is defined and that the list weapons is shared across all >> instances of the craft class. :) > I know id is called once, but what do you mean weapons is shared? All Craft instances for which you don't provide a weapons argument explicitly will share the same list. If you later append a weapon to that list all these Craft instances will see this change and get the extra weapon: a = Craft("first") b = Craft("second") a.weapons.append("surprise") print b.weapons # ['surprise'] Peter From clp2 at rebertia.com Fri May 21 14:49:15 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 May 2010 11:49:15 -0700 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 11:38 AM, Alex Hall wrote: > On 5/21/10, Christian Heimes wrote: >> Am 21.05.2010 04:56, schrieb Alex Hall: >>> Hi all, >>> I am now trying to allow my classes, all of which subclass a single >>> class (if that is the term), to provide optional arguments. Here is >>> some of my code: >>> >>> class Craft(): >>> ? def __init__(self, >>> ? name, >>> ? isAircraft=False, >>> ? id=helpers.id(), >>> ? hits=0, >>> ? weapons=[]): >> >> I hope you are aware that helpers.id() is called just once when the >> *class* is defined and that the list weapons is shared across all >> instances of the craft class. :) > I know id is called once, but what do you mean weapons is shared? Read the "Important warning" on http://docs.python.org/tutorial/controlflow.html#default-argument-values `weapons` will be the *exact same list object* for all Craft instances the way you have it currently (i.e. it will not be copied and changes to it will affect all Crafts). Cheers, Chris -- http://blog.rebertia.com From python.list at tim.thechases.com Fri May 21 14:57:27 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 21 May 2010 13:57:27 -0500 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <7eaedfaf-e065-4052-9a7f-f2a220dec26f@m33g2000vbi.googlegroups.com> Message-ID: <4BF6D797.307@tim.thechases.com> On 05/21/2010 01:40 PM, geremy condra wrote: >>> See http://www.python.org/about/success/ >> >> thankx for reply. >> >> from that list i have a feeling that python is acting only as "quick >> and dirty work" nothing more ! > > Yeah, there's not really a lot of industry support. If only we could > get a huge search engine like bing to use python extensively we'd > be in a lot better shape. Or if an organization known to hire a bunch of rocket-scientists were to use Python...that would make it a real language... -tkc http://www.python.org/about/success/usa/ From clp2 at rebertia.com Fri May 21 15:01:43 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 May 2010 12:01:43 -0700 Subject: optional argument to a subclass of a class In-Reply-To: References: Message-ID: On Fri, May 21, 2010 at 11:49 AM, Chris Rebert wrote: > On Fri, May 21, 2010 at 11:38 AM, Alex Hall wrote: >> On 5/21/10, Christian Heimes wrote: >>> Am 21.05.2010 04:56, schrieb Alex Hall: >>>> Hi all, >>>> I am now trying to allow my classes, all of which subclass a single >>>> class (if that is the term), to provide optional arguments. Here is >>>> some of my code: >>>> >>>> class Craft(): >>>> ? def __init__(self, >>>> ? name, >>>> ? isAircraft=False, >>>> ? id=helpers.id(), >>>> ? hits=0, >>>> ? weapons=[]): >>> >>> I hope you are aware that helpers.id() is called just once when the >>> *class* is defined and that the list weapons is shared across all >>> instances of the craft class. :) >> I know id is called once, but what do you mean weapons is shared? > > Read the "Important warning" on > http://docs.python.org/tutorial/controlflow.html#default-argument-values > `weapons` will be the *exact same list object* for all Craft instances > the way you have it currently (i.e. it will not be copied and changes > to it will affect all Crafts). Er, all Craft instances /where you didn't pass an explicit `weapons` argument to the constructor/, that is. - Chris From ethan at stoneleaf.us Fri May 21 15:20:59 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 21 May 2010 12:20:59 -0700 Subject: optional argument to a subclass of a class In-Reply-To: References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> Message-ID: <4BF6DD1B.2070406@stoneleaf.us> Alex Hall wrote: > On 5/20/10, alex23 wrote: > I have since updated each ship's > __init__ to accept all the arguments that Craft accepts so that I can > support all optional arguments, Ick. Now you'll have to change several things if you make one change to the Craft class. Better to do it this way: [borrowing Peter's example] class Craft(object): def __init__(self, name, id=None, weapons=None): if id is None: id = helpers.id() if weapons is None: weapons = [] self.name = name self.id = id self.weapons = weapons class Battleship(Craft): def __init__(self, name, max_hits=None, **kwds): Craft.__init__(self, name, **kwds) self.max_hits = max_hits Notice the **kwds in Battleships's init, both in the parameter line, and in the call to Craft's init. This way all keyword arguments that Battleship doesn't directly support will be passed through to Craft. ~Ethan~ From awilliam at whitemice.org Fri May 21 15:43:10 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 21 May 2010 15:43:10 -0400 Subject: creating addon system In-Reply-To: References: Message-ID: <1274470990.9614.2.camel@linux-yu4c.site> On Fri, 2010-05-21 at 08:50 -0700, timo verbeek wrote: > What is the easiest way in python to create a addon system? > I found to easy ways: > * using a import system like this: > for striper in stripers: > if striper["enabled"]: > exec("from strip import %s as _x"%striper["striper"]) > string = _x.start(string) This is how I chose to do it. Just walking a list of bundles and discover the available classes [as plugins]. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From mehgcap at gmail.com Fri May 21 16:09:56 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 16:09:56 -0400 Subject: optional argument to a subclass of a class In-Reply-To: <4BF6DD1B.2070406@stoneleaf.us> References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> <4BF6DD1B.2070406@stoneleaf.us> Message-ID: On 5/21/10, Ethan Furman wrote: > Alex Hall wrote: >> On 5/20/10, alex23 wrote: >> I have since updated each ship's >> __init__ to accept all the arguments that Craft accepts so that I can >> support all optional arguments, > > Ick. Now you'll have to change several things if you make one change to > the Craft class. Better to do it this way: > > [borrowing Peter's example] > > class Craft(object): Curious: I do not pass Craft this "object" keyword and I have no problems. What is it for? Just a convention, something like self being called self? > def __init__(self, name, id=None, weapons=None): > if id is None: > id = helpers.id() > if weapons is None: > weapons = [] > self.name = name > self.id = id > self.weapons = weapons > > class Battleship(Craft): > def __init__(self, name, max_hits=None, **kwds): > Craft.__init__(self, name, **kwds) > self.max_hits = max_hits > > > > Notice the **kwds in Battleships's init, both in the parameter line, and > in the call to Craft's init. This way all keyword arguments that > Battleship doesn't directly support will be passed through to Craft. Thanks, the **kwords makes sense!! I implemented it much as you described, and life is much easier; each ship or aircraft now has a simple constructor, and I am still free to change any attrib I want later or at creation time. A very powerful concept, and I now have 2-line constructors. class Battleship(Craft): def __init__(self, name, **kwords): Craft.__init__(self, name, maxHits=4, **kwords) #call the superclass's __init__ class Carrier(Craft): def __init__(self, name, **kwords): Craft.__init__(self, name, maxHits=5, **kwords) #call the superclass's __init__ > > ~Ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From clp2 at rebertia.com Fri May 21 17:28:06 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 May 2010 14:28:06 -0700 Subject: optional argument to a subclass of a class In-Reply-To: References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> <4BF6DD1B.2070406@stoneleaf.us> Message-ID: On Fri, May 21, 2010 at 1:09 PM, Alex Hall wrote: > On 5/21/10, Ethan Furman wrote: >> Alex Hall wrote: >>> On 5/20/10, alex23 wrote: >>> I have since updated each ship's >>> __init__ to accept all the arguments that Craft accepts so that I can >>> support all optional arguments, >> >> Ick. ?Now you'll have to change several things if you make one change to >> the Craft class. ?Better to do it this way: >> >> [borrowing Peter's example] >> >> class Craft(object): > Curious: I do not pass Craft this "object" keyword and I have no > problems. What is it for? Just a convention, something like self being > called self? It causes the class to be "new-style". See http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes Cheers, Chris -- http://blog.rebertia.com From bkasterm at gmail.com Fri May 21 17:51:52 2010 From: bkasterm at gmail.com (Bart Kastermans) Date: Fri, 21 May 2010 15:51:52 -0600 Subject: First Tkinter script: requesting comments Message-ID: <87d3wokjnr.fsf@kasterma.Colorado.EDU> I wrote a first script using Tkinter. As I am new to its use, I am only just feeling my way around. I would very much like comments on the design of the script (and in fact any other comments on my code would also be very welcome). I have it posted (with syntax coloring) at: http://kasterma.wordpress.com/2010/05/21/first-experiments-with-tkinter/ But will also include it here for convenience. Thanks for any help, Best, Bart *********************** #!/usr/bin/env python # # Getting a list of students and grades displayed so that grades can # be updated, and we poll these changes (so that in the future we can # act on it). # # Bart Kastermans, www.bartk.nl """ Design of the window +-------------------------------------------------------------+ | root | | +------------------------------------------------------+ | | | title_frame | | | | +------------------------------+ | | | | | Label(title) | | | | | | | | | | | +------------------------------+ | | | +------------------------------------------------------+ | | +------------------------------------------------------+ | | | exam_grades_frames | | | | +-------------------------------------------------+ | | | | | Frame(ex) | | | | | | +--------------------+ +---------------------+ | | | | | | | Entry(name) | | Entry(grade) | | | | | | | | | | | | | | | | | +--------------------+ +---------------------+ | | | | | +-------------------------------------------------+ | | | | | | | +------------------------------------------------------+ | | | | +---------------------+ | | | quit_button | | | | | | | +---------------------+ | +-------------------------------------------------------------+ """ from Tkinter import * # global info for this specific example # four students no_stud = 4 exam_grades = [1,2,3,4] names = ["Ben", "Jim", "James", "Mel"] # upper bound for name length max_name_len = max (map (len, names)) # set up root window root = Tk() root.geometry ("400x400") exam_grades_string = map (lambda x: StringVar (root,str (x)), exam_grades) names_string = map (lambda x: StringVar (root, x), names) def setup (): """ setup the window with the list of students. This is test-code to figure out what the app finally should look like. """ # title frame, with title Grade Correction in it title_frame = Frame(root) title_frame.pack (fill=X) w = Label (title_frame, text = "Grade Correction", font = ("Helvetica", 25)) w.pack (side=LEFT) # from to hold the list of grades exam_grades_frame = Frame (root) exam_grades_frame.pack (fill=BOTH) exam_label = Label (exam_grades_frame, text="EXAMS") exam_label.pack () # set up the list of grades for i in range (0,no_stud): # a frame per student ex = Frame (exam_grades_frame) ex.pack () # name on the left name = Entry (ex, textvariable=names_string[i], width=max_name_len+2) name.config (state=DISABLED) name.pack (side=LEFT) # grade next to it grade = Entry (ex, textvariable=exam_grades_string [i], width=4) grade.pack (side=LEFT) # button to quit the application qb = Button (root) qb ['text'] = "quit" qb ['command'] = root.quit qb.pack () def to_int (st): """ helper function to convert strings to integers. Empty string represents 0. """ if len (st) == 0: return 0 else: return int (st) def get_curr_grades (): """ extract the grades from exam_grades_string. exam_grades_string consists of StringVar that get updated when the fields are updated in the GUI. """ grades = [] for i in range (0, no_stud): grades.append (exam_grades_string [i].get()) return grades # get the current grades curr_grades = map (to_int, get_curr_grades ()) def poll_exams (): """ function that keeps polling the current grades, looking for changes""" global curr_grades new_grades = map (to_int, get_curr_grades ()) if new_grades != curr_grades: print new_grades curr_grades = new_grades root.after( 250, poll_exams) # window setup setup () # start the polling poll_exams () # start the eventloop root.mainloop () # do cleanup root.destroy () sys.exit () From python at bdurham.com Fri May 21 18:01:58 2010 From: python at bdurham.com (python at bdurham.com) Date: Fri, 21 May 2010 18:01:58 -0400 Subject: gettext compatible, public domain collections of translations for strings commonly used in software applications? Message-ID: <1274479318.27084.1376307219@webmail.messagingengine.com> It seems to me that there must be some public domain collection of translated strings that could be searched for 1:1 or fuzzy translations for strings commonly used in software applications? Is there a technical and copyright friendly (LGPL licensed?) way to query services like Google's Translator Toolkit, LaunchPad, Mygengo, etc. to find translations for common strings? I've tried to google this topic without success. Example: public domain po (translation|translations) Thanks, Malcolm From mehgcap at gmail.com Fri May 21 18:27:33 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 21 May 2010 18:27:33 -0400 Subject: optional argument to a subclass of a class In-Reply-To: References: <58f14417-5101-4c4d-afa2-21cb48612823@j27g2000vbp.googlegroups.com> <8af6df9f-3408-4f95-b63b-9dd78faaf756@n37g2000prc.googlegroups.com> <4BF6DD1B.2070406@stoneleaf.us> Message-ID: On 5/21/10, Chris Rebert wrote: > On Fri, May 21, 2010 at 1:09 PM, Alex Hall wrote: >> On 5/21/10, Ethan Furman wrote: >>> Alex Hall wrote: >>>> On 5/20/10, alex23 wrote: >>>> I have since updated each ship's >>>> __init__ to accept all the arguments that Craft accepts so that I can >>>> support all optional arguments, >>> >>> Ick. Now you'll have to change several things if you make one change to >>> the Craft class. Better to do it this way: >>> >>> [borrowing Peter's example] >>> >>> class Craft(object): >> Curious: I do not pass Craft this "object" keyword and I have no >> problems. What is it for? Just a convention, something like self being >> called self? > > It causes the class to be "new-style". See > http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes Oh, I see. Thanks. > > Cheers, > Chris > -- > http://blog.rebertia.com > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From zac256 at gmail.com Fri May 21 19:22:52 2010 From: zac256 at gmail.com (Zac Burns) Date: Fri, 21 May 2010 16:22:52 -0700 Subject: Traceback spoofing Message-ID: Why can't I inherit from traceback to 'spoof' tracebacks? I would like to create a traceback that is save-able to re-raise exceptions later without leaking all the locals. (I'm sure this idea has been discussed before but I can't find it anymore.) class Traceback(types.TracebackType): pass TypeError: Error when calling the metaclass bases type 'traceback' is not an acceptable base type -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer Zindagi Games -------------- next part -------------- An HTML attachment was scrubbed... URL: From bryanjugglercryptographer at yahoo.com Fri May 21 19:41:53 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Fri, 21 May 2010 16:41:53 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <85l509Fpe7U1@mid.individual.net> Message-ID: <6025dfa5-bc54-412d-98e2-71d2ad4540a6@11g2000prv.googlegroups.com> Peter Pearson wrote: > If it's important for the function to execute quickly for large n, > you might get a useful speedup by testing only every ninth integer, Our standards for "quickly" and "large" seem kind of thin. > I suspect that further applications of number theory would > provide additional, substantial speedups, but this wanders > away from the subject of Python. I was thinking combinatorics more than number theory. I didn't find a neat formula, but I came up with a recursive memo-izing algorithm that handles 100-digit n's. I tested this against the initial algorithm plus Peter Pearson's optimization for numbers up to several thousand, and it agrees... well, after I fixed stuff that is. -Bryan Olson # ----------- _nds = {} def ndsums(m, d): """ How many d-digit ints' digits sum to m? """ assert m >= 0 and d >= 0 if m > d * 9: return 0 if m == 0 or d == 1: return 1 if (m, d) not in _nds: _nds[(m, d)] = sum(ndsums(m - i, d - 1) for i in range(min(10, m + 1))) return _nds[(m, d)] def prttn(m, n): assert m > 0 and n > 0 def inner(m, dls): if not dls: return 1 if m == 0 else 0 count = 0 msd, rest = dls[0], dls[1:] for d in range(msd): if m >= d: count += ndsums(m - d, len(dls) - 1) count += inner(m - msd, dls[1:]) return count return inner(m, [int(c) for c in str(n - 1)]) pi100 = 3141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067 print(prttn(500, pi100)) From steve at REMOVE-THIS-cybersource.com.au Fri May 21 20:13:27 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 May 2010 00:13:27 GMT Subject: gettext compatible, public domain collections of translations for strings commonly used in software applications? References: Message-ID: <4bf721a7$0$27861$c3e8da3@news.astraweb.com> On Fri, 21 May 2010 18:01:58 -0400, python wrote: > It seems to me that there must be some public domain collection of > translated strings that could be searched for 1:1 or fuzzy translations > for strings commonly used in software applications? There must be? Is that a law of nature or something? "I want it, so it must exist, QED." > Is there a technical and copyright friendly (LGPL licensed?) way to > query services like Google's Translator Toolkit, LaunchPad, Mygengo, > etc. to find translations for common strings? You would need to check the licence terms and conditions for those services. It's not enough to have LGPL-licenced software to access Translator Toolkit, if Google put limits or prohibitions on access. You will need to check the services in question to see if they publish an API for programmatically using their software. -- Steven From aahz at pythoncraft.com Fri May 21 21:20:44 2010 From: aahz at pythoncraft.com (Aahz) Date: 21 May 2010 18:20:44 -0700 Subject: links button gone from python.org References: <290f2f31-0893-469a-a12c-49eff9ffbf6f@y21g2000vba.googlegroups.com> Message-ID: In article <290f2f31-0893-469a-a12c-49eff9ffbf6f at y21g2000vba.googlegroups.com>, Eric_Dexter at msn.com wrote: > >I noticed that that the link to that section is gone. The page >seems to be there when I use the url that is stored on my computer. What are you talking about? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From tjreedy at udel.edu Fri May 21 21:42:19 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2010 21:42:19 -0400 Subject: Traceback spoofing In-Reply-To: References: Message-ID: On 5/21/2010 7:22 PM, Zac Burns wrote: > Why can't I inherit from traceback to 'spoof' tracebacks? Because a) they are, at least in part, an internal implementation detail of CPython, and b) even if you could, Python would use the builtin original with exceptions, and c) you can probably do anything sensible you want with them by wrapping them, as in, define a class with a traceback as the main instance attribute. From aahz at pythoncraft.com Fri May 21 21:45:05 2010 From: aahz at pythoncraft.com (Aahz) Date: 21 May 2010 18:45:05 -0700 Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: In article , Patrick Maupin wrote: > >There are a lot of commercial programs written in Python. But any >company which thinks it has a lock on some kind of super secret sauce >isn't going to use Python, because it's very easy to reverse engineer >even compiled Python programs. That's not always true. Both my employer (Egnyte) and one of our main competitors (Dropbox) use Python in our clients. We don't care much because using our servers is a requirement of the client. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From exarkun at twistedmatrix.com Fri May 21 22:12:43 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sat, 22 May 2010 02:12:43 -0000 Subject: Traceback spoofing In-Reply-To: References: Message-ID: <20100522021243.2209.112058618.divmod.xquotient.508@localhost.localdomain> On 01:42 am, tjreedy at udel.edu wrote: >On 5/21/2010 7:22 PM, Zac Burns wrote: >>Why can't I inherit from traceback to 'spoof' tracebacks? > >Because a) they are, at least in part, an internal implementation >detail of CPython, But you can just say this about anything, since there is no Python specification. So it's mostly meaningless. >and b) even if you could, Python would use the builtin original with >exceptions, Only if it were implemented that way. One could certainly an implementation with different behavior. >and c) you can probably do anything sensible you want with them by >wrapping them, as in, define a class with a traceback as the main >instance attribute. Except you can't re-raise them. Something like this feature has been proposed before. The only objects that I've ever heard raised are that it's harder to implement on CPython than anyone is willing to tackle. Jean-Paul From ben+python at benfinney.id.au Fri May 21 22:12:50 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 May 2010 12:12:50 +1000 Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <87mxvsfzvh.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > In article , > Patrick Maupin wrote: > > > >There are a lot of commercial programs written in Python. But any > >company which thinks it has a lock on some kind of super secret sauce > >isn't going to use Python, because it's very easy to reverse engineer > >even compiled Python programs. > > That's not always true. Both my employer (Egnyte) and one of our main > competitors (Dropbox) use Python in our clients. We don't care much > because using our servers is a requirement of the client. Doesn't that mean those companies don't fit the above description? That is, neither of them ?thinks it has a lock on some kind of super secret sauce? in the programs. So they don't seem to be counter-examples. -- \ ?The right to search for truth implies also a duty; one must | `\ not conceal any part of what one has recognized to be true.? | _o__) ?Albert Einstein | Ben Finney From zac256 at gmail.com Fri May 21 22:35:23 2010 From: zac256 at gmail.com (Zac Burns) Date: Fri, 21 May 2010 19:35:23 -0700 Subject: Traceback spoofing In-Reply-To: <20100522021243.2209.112058618.divmod.xquotient.508@localhost.localdomain> References: <20100522021243.2209.112058618.divmod.xquotient.508@localhost.localdomain> Message-ID: > Except you can't re-raise them. > Yes, I should have noted that in the original post: >>> raise RuntimeError, 'X', wrapped_traceback Traceback (most recent call last): File "", line 1, in TypeError: raise: arg 3 must be a traceback or None Does someone know where the thread went about it being hard to implement? I'm interested to see what makes it difficult. -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer Zindagi Games -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri May 21 23:03:39 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 22 May 2010 13:03:39 +1000 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <4bf749ef@dnews.tpgi.com.au> On 05/22/10 04:47, Terry Reedy wrote: > On 5/21/2010 6:21 AM, Deep_Feelings wrote: >> python is not a new programming language ,it has been there for the >> last .... 15+ years or so ? right ? >> >> however by having a look at this page >> http://wiki.python.org/moin/Applications >> i could not see many programs written in python (i will be interested >> more in COMMERCIAL programs written in python ). and to be honest ,i > > There are two kinds of 'commercial' programs. > 1. The vast majority are proprietary programs kept within a company for > its own use. As long as these work as intended, they are mostly > invisible to the outside world. > 2. Programs sold to anyone who wants them. > > Python trades programmer speed for execution speed. If a successful > Python program is going to be run millions of times, it makes economic > sense to convert time-hogging parts to (for instance) C. In fact, this > is a consideration in deciding what functions should be builtin and > which stdlib modules are written or rewritten in C. > > Programs being sold tend to be compared to competitors on speed with > perhaps more weight than they rationally should. Speed is easier to > measure than, for instance, lack of bugs. doubting python's speed? Look at Mercurial vs. SVN; Mercurial is written in Python while SVN in C. Mercurial beats SVN in speed by several orders of magnitude. One of Mercurial's design goal was to be faster than SVN, if the programmers have naively believed that choice of language would matter to program's speed, they'd choose to write Mercurial in assembly instead (the same argument applies to Git, written in shell scripts). Now, you may think this is an unfair comparison, since Mercurial is hype and new, SVN is antiquated and old. But it shows that in real-life, the language being inherently slow often dosn't matter. What matters more are the choice of data structure and algorithm, I/O speed, network latency, and development speed. From johnroth1 at gmail.com Fri May 21 23:26:56 2010 From: johnroth1 at gmail.com (John Roth) Date: Fri, 21 May 2010 20:26:56 -0700 (PDT) Subject: Another "Go is Python-like" article. References: Message-ID: On May 21, 8:20?am, Grant Edwards wrote: > In a recent Reg article, there's yet more yammering on about how Go is > somehow akin to Python -- referring to Go as a "Python-C++" crossbreed. > > http://www.theregister.co.uk/2010/05/20/go_in_production_at_google/ > > I still don't get it. > > What about Go, exactly, do people see as Phython-like? > > Go doesn't seem to have any of the salient features (either syntactic > or semantic) of Python other than garbage collection. > > How is Go not just warmed-over Java? > > -- > Grant Edwards ? ? ? ? ? ? ? grant.b.edwards ? ? ? ?Yow! RELATIVES!! > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? gmail.com ? ? ? ? ? ? Actually, Go seems to be more C implemented the way the C developers would have done it if they knew then what they know now. That's not a joke - look at the names on the development team. I haven't a clue how anyone can think it's similar to Python. Or Java, for that matter. John Roth From clp2 at rebertia.com Fri May 21 23:30:43 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 May 2010 20:30:43 -0700 Subject: where are the program that are written in python? In-Reply-To: <4bf749ef@dnews.tpgi.com.au> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> Message-ID: On Fri, May 21, 2010 at 8:03 PM, Lie Ryan wrote: > On 05/22/10 04:47, Terry Reedy wrote: >> On 5/21/2010 6:21 AM, Deep_Feelings wrote: >>> python is not a new programming language ,it has been there for the >>> last .... 15+ years or so ? right ? >>> >>> however by having a look at this page >>> http://wiki.python.org/moin/Applications >>> i could not see many programs written in python (i will be interested >>> more in COMMERCIAL programs written in python ). and to be honest ,i >> >> There are two kinds of 'commercial' programs. >> 1. The vast majority are proprietary programs kept within a company for >> its own use. As long as these work as intended, they are mostly >> invisible to the outside world. >> 2. Programs sold to anyone who wants them. >> >> Python trades programmer speed for execution speed. If a successful >> Python program is going to be run millions of times, it makes economic >> sense to convert time-hogging parts to (for instance) C. ?In fact, this >> is a consideration in deciding what functions should be builtin and >> which stdlib modules are written or rewritten in C. >> >> Programs being sold tend to be compared to competitors on speed with >> perhaps more weight than they rationally should. Speed is easier to >> measure than, for instance, lack of bugs. > > doubting python's speed? Look at Mercurial vs. SVN; Mercurial is written > in Python while SVN in C. Mercurial beats SVN in speed by several orders > of magnitude. Erm, in fairness, I recall hearing that some speed-critical bits of hg are written in C. It does lend credence to the "Python as glue language" argument though; I doubt hg's extensibility and friendly interface would have been as easy to implement it C (particularly the slick instant-server feature). Cheers, Chris -- http://blog.rebertia.com From pengyu.ut at gmail.com Fri May 21 23:47:42 2010 From: pengyu.ut at gmail.com (Peng Yu) Date: Fri, 21 May 2010 22:47:42 -0500 Subject: How to show the current line number with pdb.set_trace() Message-ID: After starting pdb.set_trace(), python doens't show line number. Could you let me know how to print the number by default so that I know where the current line is? -- Regards, Peng From pavlovevidence at gmail.com Sat May 22 00:49:39 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 21 May 2010 21:49:39 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On May 21, 3:21?am, Deep_Feelings wrote: > please don't mention programs where python was used as a glue ,those > programs are not actually written in python. I hate to answer a troll, but I'll just mention that when people talk about a "glue language", they're not talking about using some Python code to connect two big systems together (although Python is good for that). What they are saying is that Python is a good language to serve as high-level logic interfacing lots of different library codes--often but not always written in faster languages--together in one program. In that case, yes, the program is written in Python. The word "glue" is probably not the best metaphor, since to most people it means "something you use to connect two objects together". A better metaphor would be like a "substrate language". A lot of materials do use a form of glue as the substrate, but never mind that. Carl Banks From sturla at molden.no Sat May 22 02:15:37 2010 From: sturla at molden.no (sturlamolden) Date: Fri, 21 May 2010 23:15:37 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On 21 Mai, 12:21, Deep_Feelings wrote: > 1- where are the programs that is written in python ? You could search for them with Google and download your results Bittorrent. > is python a valid practical programming language ? No, it is probably Turing incomplete. From __peter__ at web.de Sat May 22 02:15:39 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 May 2010 08:15:39 +0200 Subject: Problem with an huge dictionary References: <70b8f82e-2dfe-4403-ae77-cb4d005578f1@y12g2000vbr.googlegroups.com> <40f4fe52-c4e9-43c6-b0be-4fd6da91555d@c11g2000vbe.googlegroups.com> Message-ID: keobox wrote: > On 20 Mag, 12:58, Thomas Lehmann wrote: >> > The question is: >> > Is there a limit on the number of entries a dictionary can have i >> > jython? >> >> > I wrote a little app where my data is stored in a huge dictionary >> > (11746 entries) generated with a python script. >> > When I try to import the dictionary, jython complains with the >> > following message: >> >> 1) You did not say what you have saved (content of your dictionary). > > - As you can see I received the error when I tried to import > jmoco_event_data.py module from the jython interpreter prompt. > - The "import" will cause the module compilation, jython will produce > a .class file instead of .pyc. > - jmoco_event_data.py contains 4 dictionaries: > > typesValToName={ > 220:'EMS_EVENT_EMS_INTERNAL_BASE', > 221:'EMS_EVENT_INTERNAL_TYPE_BASE', > 222:'EMS_EVENT_INTERNAL_N_E_P_M_EVENT', > 223:'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD', > 224:'EMS_EVENT_NE_SPECIFIC_BASE', > ... 11746 entries int key: string value > } > > typesNameToVal={ > 'EMS_EVENT_EMS_INTERNAL_BASE':220, > 'EMS_EVENT_INTERNAL_TYPE_BASE':221, > 'EMS_EVENT_INTERNAL_N_E_P_M_EVENT':222, > 'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD':223, > 'EMS_EVENT_NE_SPECIFIC_BASE':224, > ... total 11746 entries string key: int value > } > > causesValToName={ > 0:'NOT_APPLICABLE_UNKNOWN', > 1:'SOFTWARE_CAUSE_UNKNOWN', > 2:'ABSENT_MODULE', > 3:'FAULTY_MODULE', > ... 483 entries int key: string value > } > > causesNameToVal={ > 'NOT_APPLICABLE_UNKNOWN':0, > 'SOFTWARE_CAUSE_UNKNOWN':1, > 'ABSENT_MODULE':2, > 'FAULTY_MODULE':3, > ... 483 entries string key: int value > } > >> 2) You did not say how you have saved. > > The dictionaries are in the jmoco_event_data.py module. > >> From the callstack - also I have never used jython - it looks like >> that >> there is a try to create a class. It looks like - I may be wrong - >> that >> you have saved user objects in your dictionary - have you? > > Nope, the dictionaries are only int to string mappings and string to > int mappings > >> If so you might fail on loading those objects - especially when your >> program >> does not have the code for it. > > The failure happens during module's import, so my question is: Is > jython able to handle such big dictionaries? The problem seems to be the size of the code, i. e. the dict literal rather than the size of the dictionary. With a slightly smaller dict I get $ cat make_dict_source.py from itertools import chain, count, islice def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument("n", type=int, default=100) parser.add_argument("py") args = parser.parse_args() prefix = ["data = {\n"] suffix = ["}\n"] pairs = ("'enum_whatever_{0}': {0},\n".format(i) for i in count()) pairs = islice(pairs, args.n) with open(args.py, "w") as outstream: lines = chain(prefix, pairs, suffix) outstream.writelines(lines) if __name__ == "__main__": main() $ python make_dict_source.py 4000 tmp.py $ jython tmp.py Traceback (innermost last): (no code object) at line 0 java.lang.ClassFormatError: Invalid method Code length 71912 in class file org/python/pycode/_pyx0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:632) at org.python.core.BytecodeLoader2.loadClassFromBytes(Unknown Source) at org.python.core.BytecodeLoader.makeClass(Unknown Source) at org.python.core.BytecodeLoader.makeCode(Unknown Source) at org.python.core.Py.compile_flags(Unknown Source) at org.python.core.Py.compile_flags(Unknown Source) at org.python.core.__builtin__.execfile_flags(Unknown Source) at org.python.util.PythonInterpreter.execfile(Unknown Source) at org.python.util.jython.main(Unknown Source) java.lang.ClassFormatError: java.lang.ClassFormatError: Invalid method Code length 71912 in class file org/python/pycode/_pyx0 $ jython --version Jython 2.2.1 on java1.6.0_0 Jython seems to generate a method that is bigger than the 64K allowed by Java. The simplest workaround is probably to let your module read the dict data from a separate file in e. g. csv format. Peter From sturla at molden.no Sat May 22 02:20:31 2010 From: sturla at molden.no (sturlamolden) Date: Fri, 21 May 2010 23:20:31 -0700 (PDT) Subject: Another "Go is Python-like" article. References: Message-ID: On 21 Mai, 16:20, Grant Edwards wrote: > I still don't get it. > > What about Go, exactly, do people see as Phython-like? > > Go doesn't seem to have any of the salient features (either syntactic > or semantic) of Python other than garbage collection. > > How is Go not just warmed-over Java? Go is Algol 68. Reinventing the wheel is always fun. From pmaupin at gmail.com Sat May 22 02:25:53 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 21 May 2010 23:25:53 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <48616f72-3a7e-4b04-aabc-49acd853e01b@j9g2000vbp.googlegroups.com> On May 21, 8:45?pm, a... at pythoncraft.com (Aahz) wrote: > In article , > Patrick Maupin ? wrote: > >There are a lot of commercial programs written in Python. ?But any > >company which thinks it has a lock on some kind of super secret sauce > >isn't going to use Python, because it's very easy to reverse engineer > >even compiled Python programs. ? > > That's not always true. ?Both my employer (Egnyte) and one of our main > competitors (Dropbox) use Python in our clients. ?We don't care much > because using our servers is a requirement of the client. Absolutely. I wrote my post after the OP's second post, and from that short, derisive tome, I inferred that the OP's definition of "commercial" was quite narrow, so I was trying to respond on the basis of what he would consider "commercial," which BTW, probably wouldn't include a lot of programs that, e.g. Google uses to make money. Regards, Pat From pmaupin at gmail.com Sat May 22 02:29:37 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 21 May 2010 23:29:37 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <87mxvsfzvh.fsf@benfinney.id.au> Message-ID: <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> On May 21, 9:12?pm, Ben Finney wrote: > a... at pythoncraft.com (Aahz) writes: > > In article , > > Patrick Maupin ? wrote: > > > >There are a lot of commercial programs written in Python. ?But any > > >company which thinks it has a lock on some kind of super secret sauce > > >isn't going to use Python, because it's very easy to reverse engineer > > >even compiled Python programs. ? > > > That's not always true. ?Both my employer (Egnyte) and one of our main > > competitors (Dropbox) use Python in our clients. ?We don't care much > > because using our servers is a requirement of the client. > > Doesn't that mean those companies don't fit the above description? That > is, neither of them ?thinks it has a lock on some kind of super secret > sauce? in the programs. So they don't seem to be counter-examples. Just because someone has competition doesn't mean they don't think they have secret sauce. I think Aahz's main point was that in his sub- industry, the secret sauce is guarded by not actually letting the customer have access to executable code, other than through the network. Regards, Pat From moijes12 at gmail.com Sat May 22 03:38:54 2010 From: moijes12 at gmail.com (moijes12) Date: Sat, 22 May 2010 00:38:54 -0700 (PDT) Subject: getting local area connection information through python in windows Message-ID: <4ca22888-4e76-48ee-a7da-884e30b294f0@e34g2000pra.googlegroups.com> Hi I need to get the details of Local Area connection information(network interface) like packets sent,packets recieved,duration etc. I have to do this in Windows using python. I tried looking under the socket module and also googling,but did not find anything that I could use for windows,though I did find something for linux.I have to somehow use the socket module for this. Please help me in cracking this. Regards Moses From sturla at molden.no Sat May 22 03:43:09 2010 From: sturla at molden.no (sturlamolden) Date: Sat, 22 May 2010 00:43:09 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: On 21 Mai, 20:20, Patrick Maupin wrote: > There are a lot of commercial programs written in Python. ?But any > company which thinks it has a lock on some kind of super secret sauce > isn't going to use Python, because it's very easy to reverse engineer > even compiled Python programs. Decompiling Java or .NET bytecode isn't rocket science either. > Also, any company in a competitive > market where execution speed is extremely important might choose some > other language because, frankly, the fact that a development tool is > highly productive is not something that the end user directly cares > about. ? That only applies to CPU bound program code (most program code is I/O bound), and only to computational bottlenecks (usually less than 5% of the code) in the CPU bound programs. Today, most programs are I/O bound: You don't get a faster network connection or harddrive by using C. In this case, performance depends on other factors than choice of language. That is why Mercurial (written in Python) can be much faster than SVN (written in C). For computational bottlenecks we might want to try high-performance numerical libraries first. If that does not help, we can try to replace some Python with C. Python as "glue" does not mean Python is inferior to C. It just means it is a PITA to write C or Fortran all the time. I value my own time a lot more than a few extra CPU cycles. Who cares about speed where it is not needed? There are also a lot of uneducated FUD about the GIL: First, for I/O bound programs the GIL is not an issue, as threads that are blocked and waiting for I/O do not compete for the GIL. (That should be rather obvious, but my guesstimate is that most programmers do not understand this.) Second, for CPU bound programs the GIL is not an issue either: Fine-grained parallelization is done elsewhere than Python, e.g. hidden inside numerical libraries or implemented with OpenMP pragmas in C code. Course-grained parallelization can be done in Python using Python threads, as the GIL can be released in C using a couple of macros (or using ctypes.CDLL). In practice, the GIL rarely impairs anything, but create a lot of FUD form persons who do not understand the problem. From sturla at molden.no Sat May 22 04:12:56 2010 From: sturla at molden.no (sturlamolden) Date: Sat, 22 May 2010 01:12:56 -0700 (PDT) Subject: getting local area connection information through python in windows References: <4ca22888-4e76-48ee-a7da-884e30b294f0@e34g2000pra.googlegroups.com> Message-ID: <5669d4b6-6a4e-4da0-9357-01a298acf0f1@j27g2000vbp.googlegroups.com> On 22 Mai, 09:38, moijes12 wrote: > I need to get the details of Local Area connection information(network > interface) like packets sent,packets recieved,duration etc. I have to > do this in Windows using python. >>> import subprocess as sp >>> p = sp.Popen("netstat -s", shell=False, bufsize=4096, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE) >>> print ''.join(p.stdout.readlines()) >>> p.terminate() There are other switches for the netstat command as well. From moijes12 at gmail.com Sat May 22 04:17:50 2010 From: moijes12 at gmail.com (moijes12) Date: Sat, 22 May 2010 01:17:50 -0700 (PDT) Subject: getting local area connection information through python in windows References: <4ca22888-4e76-48ee-a7da-884e30b294f0@e34g2000pra.googlegroups.com> <5669d4b6-6a4e-4da0-9357-01a298acf0f1@j27g2000vbp.googlegroups.com> Message-ID: On May 22, 1:12?pm, sturlamolden wrote: > On 22 Mai, 09:38, moijes12 wrote: > > > I need to get the details of Local Area connection information(network > > interface) like packets sent,packets recieved,duration etc. I have to > > do this in Windows using python. > >>> import subprocess as sp > >>> p = sp.Popen("netstat -s", shell=False, bufsize=4096, > > ? ? ? ? ? ? ? stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE) > > >>> print ''.join(p.stdout.readlines()) > >>> p.terminate() > > There are other switches for the netstat command as well. Thanks Moses From michele.simionato at gmail.com Sat May 22 04:49:39 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 22 May 2010 01:49:39 -0700 (PDT) Subject: help with the Python 3 version of the decorator module Message-ID: I have finally decided to port the decorator module to Python 3. Changing the module was zero effort (2to3 worked) but changing the documentation was quite an effort, since I had to wait for docutils/ pygements to support Python 3 and to change all my custom build process. Also, I am relying on distribute for installing on Python 3. I would welcome feedback for people using Python 3 on various platforms (including Windows) to see if they can install the module and how much of effort it is. Here is the tarball: http://micheles.googlecode.com/files/decorator-3.2beta.tar.gz Here is the documentation: http://micheles.googlecode.com/hg/decorator/index.html The installation process should work for Python 2.4, 2.5, 2.6, 2.7, 3.0, 3.1 and all platforms were Python runs, but I have only tested it on Linux for Python 2.6 and 3.1. The module has no relevant changes, so I expect problems only from the building process, if any. I am not sure of what will happen if you do not have distribute or if you have a previous version of the module, or if you use pip or something else (even in Python 2.X). The packaging in Python has become a real mess! TIA for you help, Michele Simionato From dragonlordnld at gmail.com Sat May 22 05:43:17 2010 From: dragonlordnld at gmail.com (Dragon Lord) Date: Sat, 22 May 2010 02:43:17 -0700 (PDT) Subject: Urllib2: Only a partial page retrieved Message-ID: <77019685-3bf4-4d0c-9fd7-13ed8e84e102@y12g2000vbg.googlegroups.com> I am trying to download a few IEEE pages by using urllib2, but with certain pages I get only the first part of the page. With other pages from the same server and url (just another pageID) I get the right results. The difference between these pages seems to be the date the paper for which the page is was published. Any papers from before 2000 end just before the date, pages from 2000 and later and at <\html>. Two example URLs: Does not work: http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=517048 Does work: http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=854728 I tried both urlopen and urlretrieve and tried both urllib and urllib2. With urlopen I tried both .read() and .read(10000) to make sure I got the whole page, but nothing helped. Sample code: import urllib2 response = urllib2.urlopen("http://ieeexplore.ieee.org/xpl/ freeabs_all.jsp?arnumber=517048") html = response.read() print html The cutoff is allways at the same location: just after the label "Meeting date" and before the date itself. Could it be that something is interpreted as and eof command or something like that? example of the cutoff point with a bad page:
Meeting Date: example of the cutoff point with a good page:
Meeting Date: 13 jun 2000 The bad pages do continue after this point btw. if you use a webbrowser, it does not seem to be a server problem. From doctoresam at gmail.com Sat May 22 05:44:57 2010 From: doctoresam at gmail.com (Deep_Feelings) Date: Sat, 22 May 2010 02:44:57 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: thank you very much ,your reply guys are very nice and informative. hope you best luck in your life From sanamsingh at hotmail.com Sat May 22 05:50:15 2010 From: sanamsingh at hotmail.com (sanam singh) Date: Sat, 22 May 2010 09:50:15 +0000 Subject: help req setting breakpoints in gdb Message-ID: Hi, I am using wingide to debug my python code. To debug my c code when i attach wingide to ddd. It is all done successfully. However when i try to set a beak point in gdb i get following error : (gdb) break /home/sa/mygr/gnuradio-core/src/lib/general/gr_gr_deinterleave.cc:13 No source file named /home/sa/mygr/gnuradio-core/src/lib/general/gr_gr_deinterleave.cc. however the file really exists there. Secondly, when after attach i simply give the command : (gdb) break 13 Breakpoint 4 at 0x805a0f5: file ./Modules/python.c, line 13. where as i am running my program from a different folder. Please help me. Cheers. _________________________________________________________________ Hotmail: Trusted email with powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Sat May 22 06:00:54 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 22 May 2010 03:00:54 -0700 (PDT) Subject: Another "Go is Python-like" article. References: Message-ID: On May 21, 4:20?pm, Grant Edwards wrote: > > What about Go, exactly, do people see as Python-like? The philosophy of keeping things simple. I find the concurrency mechanism quite Pythonic. Moreover Go interfaces are quite akin to Python duck typing, but better. There also things which are quite different from Python e.g. the attitude towards exceptions. In theory Go should be akin to C, but my gut feeling is that in practice programming in it should not feel too much different from programming in Python (but I do not have first hand experience). Michele Simionato From timoverbeek10 at gmail.com Sat May 22 06:06:33 2010 From: timoverbeek10 at gmail.com (timo verbeek) Date: Sat, 22 May 2010 03:06:33 -0700 (PDT) Subject: creating addon system References: Message-ID: Is there not an other way to create a fast addon system? A module or something like that From inigoserna at gmail.com Sat May 22 06:16:38 2010 From: inigoserna at gmail.com (=?UTF-8?B?ScOxaWdvIFNlcm5h?=) Date: Sat, 22 May 2010 12:16:38 +0200 Subject: ANN: lfm v2.2 Message-ID: Hi, after 6 months of laziness while code was complete in my computer but didn't have enough time, I'm releasing a new version of lfm now. Description: ========= Last File Manager is a simple but powerful file manager for the UNIX console. It's written in Python, using curses module. Licensed under GNU Public License version 3. Some of the features you could find in lfm: - console-based file manager for UNIX platforms - 1-pane or 2-pane view - tabs - bookmarks - history - vfs for compressed files - dialogs with entry completion - fast access to the shell - direct integration of find/grep, df and other tools - color files by extension - fast file viewer with text and binary modes - ...and many others Download it from: ============= http://inigo.katxi.org/devel/lfm (home server) or http://code.google.com/p/lfm/ or from http://www.terra.es/personal7/inigoserna/lfm when crap ISP updates its cache. Changes since last version: ==================== + New features - use 2 progress bars in copy/move/delete dialog, one for files count and other for files size - added recursive chmod chown chgrp - faster cursor movement . Ctrl-l: center cursor in panel, so now edit-link is in 'L' . Ctrl-cursor_up, Ctrl-P: move cursor 1/4th of page up . Ctrl-cursor_down, Ctrl-N: move cursor 1/4th of page down . P: move cursor 1/4th of page up in other panel . N: move cursor 1/4th of page down in other panel - file_menu new feature: a -> backup file. You can specify the extension to use in .lfmrc - added support for .xz compressed files - Unicode & Encodings . rewrite all internals to use unicode strings, but employ terminal encoding (f.e. utf-8) to interact with the user or to display contents in ncurses functions or to run commands in shell . when lfm detects a file with invalid encoding name it asks the user to convert it (can be automatic with the proper option in the configuration, automatic_file_encoding_conversion, default 0 (ask)). If not converted, lfm will display the file but won't operate on it. . try more encodings when we get a filename with strange characters . lfm will check and require a valid encoding before running - Pyview: . completely rewritten. Code is shorter and more beautiful now Uses a new FileCache class to accelerate the retrieving of file lines . displays contents between 2 and 4 times faster . new command line flag -s/--stdin to force reading from stdin. Now pyview doesn't wait for stdin input by default, so it starts much faster. eg. $ ps efax | pyview -s + Minor changes - add color entries for directories and exe_files - expand ~ to user home - make Tree follow .dotfiles behaviour, new keybinding Ctrl-H - dialogs are bigger now - show filesystem info rewritten - show file info rewritten, now it shows correctly information from fuse-mounted volumes - added new "ebook" category, filetypes and formats + About the code - since python v2.6+, popen* is deprecated, so make lfm check python version and use popen* or subprocess accordingly - correct some python idioms - clean code + Documentation - Added "Files Name Encoding" and "FAQ" sections - Added information about keybindings in permissions window - Updated some other minor changes: wide char support, vfs, thanks + lots of bugs fixed: - file system information was not showed correctly sometimes - devices major and minor numbers were not showed correctly - crash in goto_dir if there aren't any historic entries - crash in a void EntryLine after pressing BACKSPACE on some platforms - unzip => overwrite files without prompting ("unzip -o" option) to avoid ethernal waiting, as messages can not be seen by user - fix make_dir error message - recompressing a vfs compressed file leave some garbage on temporary dir - don't try to copy fifo/socket/block-dev/char-dev files - crash when we don't have enough permissions to write to dest - show_dirs_size: don't show in stderr if we don't have perms for a dir - can't browse /home/ as root if .gvfs is present - EntryLine: non-ascii chars are not showed correctly - lfm crashes with invalid encoding filenames - increment owner and group space to avoid ugly look in 1-pane view - when moving files, don't delete source if some error or if we don't overwrite destination Of course, all comments, suggestions, etc. are welcome. Best regards, I?igo Serna From python.list at tim.thechases.com Sat May 22 07:28:36 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 22 May 2010 06:28:36 -0500 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <4BF7BFE4.3090806@tim.thechases.com> On 05/22/2010 02:43 AM, sturlamolden wrote: > That only applies to CPU bound program code (most program code is I/O > bound), and only to computational bottlenecks (usually less than 5% of > the code) in the CPU bound programs. Today, most programs are I/O > bound: You don't get a faster network connection or harddrive by using > C. In this case, performance depends on other factors than choice of > language. That is why Mercurial (written in Python) can be much faster > than SVN (written in C). > > For computational bottlenecks we might want to try high-performance > numerical libraries first. If that does not help, we can try to > replace some Python with C. Just as an aside, last I checked, mercurial had some core code in C for speed. But that doesn't negate your line of reasoning, rather it cements it -- they found it was most productive to work in Python, but needed the core bits to improve in speed so rewrote them in C. I'd also include that a change in algorithm can be a big help for speeding up CPU-bound code. It doesn't matter much if you're using Python or hand-coding that inner loop in C/ASM, if you're using a O(2^N) algorithm. I find it easier to write good/speedy algorithms in Python because I have a toolkit of built-in data-types (sets, dicts, lists, etc) that I can reach for, without making sure I've added-on certain C libraries. -tkc From fabiofz at gmail.com Sat May 22 09:03:19 2010 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sat, 22 May 2010 10:03:19 -0300 Subject: Do any debuggers support "edit and continue?" In-Reply-To: References: Message-ID: On Wed, May 12, 2010 at 2:42 PM, Joel Koltner wrote: > Just curious... in Microsoft's Visual Studio (and I would presume some other > tools), for many languages (both interpreted and compiled!) there's an "edit > and conitnue" option that, when you hit a breakpoint, allows you to modify a > line of code before it's actually executed. > > Does any Python debugger support this feature? ?Being an interpreted > language it doesn't seem like it would necessarily be too onerous to > support? ?It'd be quite handy in that, especially if you hit a breakpoint > due to the interpreter throwing an error, you could fix just the line in > question and keep going, rather than having to stop the entire program, fix > the line, and then run again and potentially kill a bunch of time getting > the program back into the same "state." Just for the record, Pydev had that from 1.4.8 to 1.5.5, but it was removed because it could be a bit unpredictable (it relied on xreload.py). So, now what you can still do is change your variables / write any code in the console / use the jump to re-execute something (in the interface it's Run > Run to line -- or Ctrl+R) which is what you usually need when experimenting (I still think the edit and continue would be a nice feature, but the current state of xreload is not really good for that -- and I'm not sure if it'll ever be -- although I do have some alternatives in mind that would improve that support greatly, some things could never be really fixed, such as changing the value of an int constant that's been already assigned to somewhere else -- anyways, I've got my hands on some other things right now, so, there's currently no plan for that being supported (again)). Cheers, Fabio p.s.: I think I'd be able to do it before reaching the whole $ 500,000 in funding :) From victorsubervi at gmail.com Sat May 22 09:51:04 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 22 May 2010 09:51:04 -0400 Subject: Another Strange MySQL Problem In-Reply-To: <4BF6D3B1.2070605@tim.thechases.com> References: <4BF6D3B1.2070605@tim.thechases.com> Message-ID: On Fri, May 21, 2010 at 2:40 PM, Tim Chase wrote: > On 05/21/2010 12:31 PM, Victor Subervi wrote: > >> cursor.execute('insert into Baggage values (Null, %s, %s, %s, >> %s)', (flight_id, customer_id, weight, ticket_no)) >> > > You're trying to insert stuff... > > > OperationalError: (1452, 'Cannot add or update a child row: a foreign >> key constraint fails (`seaflight/Baggage`, CONSTRAINT `Baggage_ibfk_2` >> FOREIGN KEY (`customer_id`) REFERENCES `Customers` (`id`))') >> > > But the value you're giving for the customer_id doesn't exist in the > Customers table (as mandated by the FK). Or perhaps the column-order for > Baggage isn't what you think it is. I always specify it explicitly: > > INSERT INTO Baggage ( > something, flight_id, customer_id, weight, ticket_no > ) VALUES (Null, %s, %s, %s, %s) > > just in case the table column-order ever changes during a database update. > As it turns out, my error was confusing my tables Customers and Passengers. I was calling customer_id when I should have been calling passenger_id, which is why MySQL couldn't find the correct values <:-} beno > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Sat May 22 09:55:25 2010 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 May 2010 15:55:25 +0200 Subject: creating addon system In-Reply-To: References: Message-ID: Am 22.05.2010 12:06, schrieb timo verbeek: > Is there not an other way to create a fast addon system? > A module or something like that How fancy are your requirements? People have written numerous plugin systems, from simple to use ones like CherryPy's tool system up to a complex component architecture like zope.component. I recommend against exec() and execfile(). It makes debugging and testing harder and it has security concern, too. Christian From bryanjugglercryptographer at yahoo.com Sat May 22 10:18:33 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sat, 22 May 2010 07:18:33 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <85l509Fpe7U1@mid.individual.net> <6025dfa5-bc54-412d-98e2-71d2ad4540a6@11g2000prv.googlegroups.com> Message-ID: <041e63e5-8d83-4286-ae2d-7c38f18d8139@s13g2000prc.googlegroups.com> I wrote: > I came up with a recursive memo-izing algorithm that > handles 100-digit n's. [...] I made a couple improvements. Code below. -Bryan #--------------------- _nds = {} def ndsums(m, d): """ Count d-digit ints with digits suming to m. """ assert m >= 0 and d >= 0 m = min(m, d * 9 - m) # exploit symmetry if m < 0: return 0 if m == 0 or d == 1: return 1 if (m, d) not in _nds: _nds[(m, d)] = sum(ndsums(m - i, d - 1) for i in range(min(10, m + 1))) return _nds[(m, d)] def prttn(m, n): assert m >= 0 and n > 0 count = 0 dls = [int(c) for c in reversed(str(n))] while dls: msd = dls.pop() count += sum(ndsums(m - d, len(dls)) for d in range(min(msd, m + 1))) m -= msd return count #---------------------- # Testing from bisect import bisect_right def slow_prttn(m, n): return sum(1 for k in range(m % 9, n, 9) if sum(int(i) for i in str(k)) == m) _sums = [0, {}] def tab_prttn(m, n): upto, sums = _sums if n >= upto: for i in range(upto, n): dsum = sum(int(c) for c in str(i)) sums.setdefault(dsum, []).append(i) _sums[0] = n if m not in sums: return 0 return bisect_right(sums[m], n - 1) for n in range(1, 1234567): digits = [int(c) for c in str(n)] for m in range(9 * len(digits)): count = tab_prttn(m, n) assert prttn(m, n) == count if n < 500: assert slow_prttn(m, n) == count if count == 0: break if n % 1000 == 0: print('Tested to:', n) From victorsubervi at gmail.com Sat May 22 10:25:56 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 22 May 2010 10:25:56 -0400 Subject: Just To Be Sure...MySQL Message-ID: Hi; A lister recently responded to my post concerning mysl commands of the following type: cursor.execute('insert into foo values (%s, %s)' % (bar, something)) stating that I need to eliminate the "%" to prevent injection attacks, thus: cursor.execute('insert into foo values (%s, %s)', (bar, something)) My question is simply this: Is that advice good for *all* mysql commands? Or are there some where the "%" is necessary and a comma would fail? I need to update lots of mysql commands. If I can do it without harmful consequences, I'll do it across the board. Otherwise, I'll have to test each one. TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sat May 22 11:09:05 2010 From: aahz at pythoncraft.com (Aahz) Date: 22 May 2010 08:09:05 -0700 Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: In article , Tim Chase wrote: > >I'd also include that a change in algorithm can be a big help for >speeding up CPU-bound code. It doesn't matter much if you're using >Python or hand-coding that inner loop in C/ASM, if you're using a >O(2^N) algorithm. Rewriting an algorithm also helps I/O-bound code when you're doing something stupid like querying a DB multiple times for each record instead of caching the result. Also, rewriting your algorithm to just pull the entire DB into RAM helps, too. (If you know your dataset must fit into RAM, anyway, in order to process your algorithm.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From sturla at molden.no Sat May 22 11:21:56 2010 From: sturla at molden.no (sturlamolden) Date: Sat, 22 May 2010 08:21:56 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <266505bb-30dc-4a37-9eea-d309f91087a6@p17g2000vbe.googlegroups.com> On 22 Mai, 17:09, a... at pythoncraft.com (Aahz) wrote: > Rewriting an algorithm also helps I/O-bound code Yes it does, if it involves how we do I/O. Algorithms are just as important for I/O bound as they are for compute bound code. But implementing an algorithm in C as opposed to Python would not improve nearly as much for I/O bound as it could do for compute bound code. From lists at cheimes.de Sat May 22 12:06:30 2010 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 May 2010 18:06:30 +0200 Subject: Just To Be Sure...MySQL In-Reply-To: References: Message-ID: > A lister recently responded to my post concerning mysl commands of the > following type: > > cursor.execute('insert into foo values (%s, %s)' % (bar, something)) > > stating that I need to eliminate the "%" to prevent injection attacks, thus: > > cursor.execute('insert into foo values (%s, %s)', (bar, something)) > > My question is simply this: Is that advice good for *all* mysql commands? Or > are there some where the "%" is necessary and a comma would fail? I need to > update lots of mysql commands. If I can do it without harmful consequences, > I'll do it across the board. Otherwise, I'll have to test each one. > TIA, > beno You *MUST NOT* use string formatting for SQL commands unless you carefully quote and validate the strings. Otherwise your SQL application is vulnerable to SQL injection attacks. SQL injections are one of the most common and devastating attacks for web applications these days. Example: "Select * from Users where uid = %s" % uid uid = "1; DROP Table users;" Guess what happens here ... So yes, you must use the special syntax for all your commands. The DBA takes care of quoting. But you can't use the % replacement character for anything than the variable part of a DQL or DML statement. Variable parts are the right side of a WHERE, HAVING, SET and (IIRC) ORDER BY clause and the body of a VALUES block. But you can't do "Select * FROM %". Christian From awilliam at whitemice.org Sat May 22 12:09:18 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Sat, 22 May 2010 12:09:18 -0400 Subject: Just To Be Sure...MySQL In-Reply-To: References: Message-ID: <1274544558.10069.1.camel@linux-yu4c.site> On Sat, 2010-05-22 at 18:06 +0200, Christian Heimes wrote: > > A lister recently responded to my post concerning mysl commands of the > > following type: > > > > cursor.execute('insert into foo values (%s, %s)' % (bar, something)) > > > > stating that I need to eliminate the "%" to prevent injection attacks, thus: > > > > cursor.execute('insert into foo values (%s, %s)', (bar, something)) > > > > My question is simply this: Is that advice good for *all* mysql commands? Or > > are there some where the "%" is necessary and a comma would fail? I need to > > update lots of mysql commands. If I can do it without harmful consequences, > > I'll do it across the board. Otherwise, I'll have to test each one. > > TIA, > > beno > > You *MUST NOT* use string formatting for SQL commands unless you +1 And they are hideous code. Use an ORM: > carefully quote and validate the strings. Otherwise your SQL application > is vulnerable to SQL injection attacks. SQL injections are one of the > most common and devastating attacks for web applications these days. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From lists at cheimes.de Sat May 22 12:18:36 2010 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 May 2010 18:18:36 +0200 Subject: Just To Be Sure...MySQL In-Reply-To: <1274544558.10069.1.camel@linux-yu4c.site> References: <1274544558.10069.1.camel@linux-yu4c.site> Message-ID: Am 22.05.2010 18:09, schrieb Adam Tauno Williams: > On Sat, 2010-05-22 at 18:06 +0200, Christian Heimes wrote: >>> A lister recently responded to my post concerning mysl commands of the >>> following type: >>> >>> cursor.execute('insert into foo values (%s, %s)' % (bar, something)) >>> >>> stating that I need to eliminate the "%" to prevent injection attacks, thus: >>> >>> cursor.execute('insert into foo values (%s, %s)', (bar, something)) >>> >>> My question is simply this: Is that advice good for *all* mysql commands? Or >>> are there some where the "%" is necessary and a comma would fail? I need to >>> update lots of mysql commands. If I can do it without harmful consequences, >>> I'll do it across the board. Otherwise, I'll have to test each one. >>> TIA, >>> beno >> >> You *MUST NOT* use string formatting for SQL commands unless you > > +1 > > And they are hideous code. > > Use an ORM: How about using a proper RDBMS that supports SQL standards, triggers, foreign keys and functions first? :) From dragonlordnld at gmail.com Sat May 22 12:24:32 2010 From: dragonlordnld at gmail.com (Dragon Lord) Date: Sat, 22 May 2010 09:24:32 -0700 (PDT) Subject: Urllib2: Only a partial page retrieved References: <77019685-3bf4-4d0c-9fd7-13ed8e84e102@y12g2000vbg.googlegroups.com> Message-ID: Oops, het "Good" page is alos handled wrongly. The papers from 2000 are handled wrong too so a real example of a well performing page: http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=5206867 On May 22, 11:43?am, Dragon Lord wrote: > I am trying to download a few IEEE pages by using urllib2, but with > certain pages I get only the first part of the page. With other pages > from the same server and url (just another pageID) I get the right > results. The difference between these pages seems to be the date the > paper for which the page is was published. Any papers from before 2000 > end just before the date, pages from 2000 and later and at <\html>. > > Two example URLs: > > Does not work:http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=517048 > Does work:http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=854728 > > I tried both urlopen and urlretrieve and tried both urllib and > urllib2. With urlopen I tried both .read() and .read(10000) to make > sure I got the whole page, but nothing helped. > Sample code: > > import urllib2 > response = urllib2.urlopen("http://ieeexplore.ieee.org/xpl/ > freeabs_all.jsp?arnumber=517048") > html = response.read() > print html > > The cutoff is allways at the same location: just after the label > "Meeting date" and before the date itself. Could it be that something > is interpreted as and eof command or something like that? > > example of the cutoff point with a bad page: >
Meeting Date: > > example of the cutoff point with a good page: >
Meeting Date: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 13 jun 2000 > > The bad pages do continue after this point btw. if you use a > webbrowser, it does not seem to be a server problem. From ntwrkd at gmail.com Sat May 22 14:01:35 2010 From: ntwrkd at gmail.com (ntwrkd) Date: Sat, 22 May 2010 11:01:35 -0700 Subject: bash-style auto completion in command line program. use rlcomplete? Message-ID: I am trying to create a bash-style auto completion in a simple command-line and script-based program i created using cmd. I saw http://docs.python.org/library/rlcompleter.html, which I'm thinking is the way to go for my program to intercept the tab key. Would anyone have thoughts on this? I wish cmd or cmd2 had this functionality built-in. Thanks in advance. From pmaupin at gmail.com Sat May 22 14:45:51 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 22 May 2010 11:45:51 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <9584607c-1aea-42b1-9671-19a2b51a5e17@l6g2000vbo.googlegroups.com> On May 22, 2:43?am, sturlamolden wrote: > On 21 Mai, 20:20, Patrick Maupin wrote: > > Also, any company in a competitive > > market where execution speed is extremely important might choose some > > other language because, frankly, the fact that a development tool is > > highly productive is not something that the end user directly cares > > about. ? > > That only applies to CPU bound program code (most program code is I/O > bound), and only to computational bottlenecks (usually less than 5% of > the code) in the CPU bound programs. Today, most programs are I/O > bound: You don't get a faster network connection or harddrive by using > C. In this case, performance depends on other factors than choice of > language. That is why Mercurial (written in Python) can be much faster > than SVN (written in C). > > For computational bottlenecks we might want to try high-performance > numerical libraries first. If that does not help, we can try to > replace some Python with C. Python as "glue" does not mean Python is > inferior to C. It just means it is a PITA to write C or Fortran all > the time. I value my own time a lot more than a few extra CPU cycles. > Who cares about speed where it is not needed? I think we're in violent agreement here -- you neglected to quote the part where I said "(But the up-front choice of another language simply for speed, rather than prototyping with Python and then recoding the slow bits, would probably be a decision borne of ignorance.)" Regards, Pat From tjreedy at udel.edu Sat May 22 14:49:26 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 May 2010 14:49:26 -0400 Subject: where are the program that are written in python? In-Reply-To: <4bf749ef@dnews.tpgi.com.au> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> Message-ID: On 5/21/2010 11:03 PM, Lie Ryan wrote: > On 05/22/10 04:47, Terry Reedy wrote: >> On 5/21/2010 6:21 AM, Deep_Feelings wrote: >>> python is not a new programming language ,it has been there for the >>> last .... 15+ years or so ? right ? >>> >>> however by having a look at this page >>> http://wiki.python.org/moin/Applications >>> i could not see many programs written in python (i will be interested >>> more in COMMERCIAL programs written in python ). and to be honest ,i >> >> There are two kinds of 'commercial' programs. >> 1. The vast majority are proprietary programs kept within a company for >> its own use. As long as these work as intended, they are mostly >> invisible to the outside world. >> 2. Programs sold to anyone who wants them. >> >> Python trades programmer speed for execution speed. If a successful >> Python program is going to be run millions of times, it makes economic >> sense to convert time-hogging parts to (for instance) C. In fact, this >> is a consideration in deciding what functions should be builtin and >> which stdlib modules are written or rewritten in C. >> >> Programs being sold tend to be compared to competitors on speed with >> perhaps more weight than they rationally should. Speed is easier to >> measure than, for instance, lack of bugs. > > doubting python's speed? The is a somewhat bizarre response to me. I have been promoting Python for about 13 years, since I dubbed it 'executable pseudocode', which is to say, easy to write, read, understand, and improve. I am also a realist. Any fixed (C)Python program can be sped up, at least a bit, and possibly more, by recoding in C. At minimum, the bytecodes can be replaced by the C code and C-API calls that they get normally get translated into. Ints can be unboxed. Etcetera. This tend to freeze a program, which is fine when development is finished. I believe Raymond wrote each itertool (or at least most) in Python first, then rewrote each in C for speed, since they are intented to be repeatedly used components of other Python programs. He is not 'doubting Python's speed', just being realistic. > Look at Mercurial vs. SVN; Neither are being sold, as far as I know. > Mercurial is written in Python while SVN in C. > Mercurial beats SVN in speed by several orders > of magnitude. Because, as I said, and as you explain further, Python favors programmer speed, including speed of testing new algorithms, over raw execution speed of current algorithms. (Current) speed is (also) easier to test than improvability and hence possible speed improvements. > > One of Mercurial's design goal was to be faster than SVN, if the > programmers have naively believed that choice of language would matter > to program's speed, they'd choose to write Mercurial in assembly instead > (the same argument applies to Git, written in shell scripts). > > Now, you may think this is an unfair comparison, since Mercurial is hype > and new, SVN is antiquated and old. But it shows that in real-life, the > language being inherently slow often dosn't matter. What matters more > are the choice of data structure and algorithm, I/O speed, network > latency, and development speed. If and when mercurial deveopment slows down, some of its developers might consider whether any of the utility functions written in Python might usefully be rewritten in C. One of the intentional virtues of Python is that one can transparently convert part or all of a module *without changing* the import and use of the module. Terry Jan Reedy From pmaupin at gmail.com Sat May 22 15:13:30 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 22 May 2010 12:13:30 -0700 (PDT) Subject: Another "Go is Python-like" article. References: Message-ID: <7c1d7e0e-eb2b-411d-bc7c-7e12a247ee8b@e21g2000vbl.googlegroups.com> On May 22, 5:00?am, Michele Simionato wrote: > On May 21, 4:20?pm, Grant Edwards wrote: > > > What about Go, exactly, do people see as Python-like? > > The philosophy of keeping things simple. I find the concurrency > mechanism quite Pythonic. That's nice. > Moreover Go interfaces are quite akin to Python duck typing, but > better. That's nice too. > There also things which are quite different from Python e.g. > the attitude towards exceptions. That's a biggie. One of the beautiful things about Python is how it lets me incrementally deal with incompletely specified problems -- "here's some source data -- go do something useful with it". The FAQ discusses why the go language deliberately leaves out assert -- the developers rightly view assert statements as problematic in achieving 5 nines in a server environment, and they (somewhat incorrectly IMO) view them as problematic when testing things. Looking at their rationale, it is appears that one or more of the primary go developers had to deal way too often with people who overuse and abuse exceptions, so they are reverting to an almost childish "I'll fix their little red wagon! When they have to use *my* language, they won't be able to do that anymore!" kind of mentality. Another possibility is that they viewed the complexity of exceptions as interfering with their primary goals, and felt it necessary to rationalize their absence after the fact. For some kinds of programming, the lack of exceptions wouldn't keep me from programming Pythonically, but for huge classes of problems, it would. That's a big deal for me personally -- although I like to have lots of tools in my toolbox, the one I reach for when doing exploratory programming is probably going to have exceptions. And guess what? If the exploratory programming winds up being "good enough" (as often happens), then no recoding is required. > In theory Go should be akin to C, > but my gut feeling is that in practice programming in it should not > feel too much different from > programming in Python (but I do not have first hand experience). For well-specified problems, I might be able to agree with you, but I'm not sure. Even then, sometimes I build stuff incrementally, trying out various kinds of internal interfaces. During that development process, exceptions are a valuable mechanism for ensuring that both sides of an interface agree on the contract. (Obviously, unit testing is useful in this as well, but premature unit testing can add friction that makes it difficult to converge on an optimal design -- it's no fun to be continually rearchitecting unit tests because of other design decisions.) What will be interesting to see is if a culture develops inside google where people prototype in Python or some other language and then implement the final cut in go. If this happens often enough and the cost of recoding the final implementation is deemed high enough, then the natural question will be "What can we add to go to make it a better prototyping language?" Regards, Pat From pmaupin at gmail.com Sat May 22 15:39:27 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 22 May 2010 12:39:27 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> Message-ID: On May 22, 1:49?pm, Terry Reedy wrote: > Because, as I said, and as you explain further, Python favors programmer > speed, including speed of testing new algorithms, over raw execution > speed of current algorithms. (Current) speed is (also) easier to test > than improvability and hence possible speed improvements. First of all, I don't think you and Lie have any basic disagreements. The key realization is that the quantitative difference in programmer speed you mention is so large (orders of magnitude) that, for many classes of problems, it is not just *possible*, but actually *probable*, that a Python implementation *will be faster* than a C implementation. Yes, you are absolutely correct that most Python programs can be made faster by adding a bit of C, but that doesn't negate the fact that if I can throw 'x' man-hours at a problem, for lots of real-world values of 'x' and of 'the problem', a pure Python implementation will run rings around a pure C implementation, assuming the C implementation even works by the time I've burned through 'x' hours. I discussed this a bit on this newsgroup over five years ago, and the points are still pertinent: http://groups.google.com/group/comp.lang.python/msg/910a54ddec946567 > If and when mercurial deveopment slows down, some of its developers > might consider whether any of the utility functions written in Python > might usefully be rewritten in C. One of the intentional virtues of > Python is that one can transparently convert part or all of a module > *without changing* the import and use of the module. I don't even think that Mercurial development has to slow down to decide to recode a few things in C. A tiny bit of C at the right place can often provide more than enough leverage to be worthwhile, and be small enough to throw away if need be. Regards, Pat From pmaupin at gmail.com Sat May 22 15:40:36 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 22 May 2010 12:40:36 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> Message-ID: On May 21, 10:30?pm, Chris Rebert wrote: > Erm, in fairness, I recall hearing that some speed-critical bits of hg > are written in C. It does lend credence to the "Python as glue > language" argument though; I doubt hg's extensibility and friendly > interface would have been as easy to implement it C (particularly the > slick instant-server feature). Is C viewed as a "glue language" in those environments where it is the primary tool and sometimes some small bits are recoded into assembly language for speed? Regards, Pat From thudfoo at opensuse.us Sat May 22 15:57:43 2010 From: thudfoo at opensuse.us (member thudfoo) Date: Sat, 22 May 2010 12:57:43 -0700 Subject: bash-style auto completion in command line program. use rlcomplete? In-Reply-To: References: Message-ID: On Sat, May 22, 2010 at 11:01 AM, ntwrkd wrote: > I am trying to create a bash-style auto completion in a simple > command-line and script-based program i created using cmd. > I saw http://docs.python.org/library/rlcompleter.html, which I'm > thinking is the way to go for my program to intercept the tab key. > Would anyone have thoughts on this? > > I wish cmd or cmd2 had this functionality built-in. > It is built in. Check the cmd documentation for complete_* method of Cmd class. Following is an example of it use for a command called "open": def complete_open(self, text, line, begidx, endidx): asmfiles = glob('%s/*.asm' % ASMDIR) matches = [] for path in asmfiles: fname = os.path.basename(path) if fname.startswith(text): matches.append(fname) return matches From aahz at pythoncraft.com Sat May 22 16:34:44 2010 From: aahz at pythoncraft.com (Aahz) Date: 22 May 2010 13:34:44 -0700 Subject: Just To Be Sure...MySQL References: Message-ID: In article , Christian Heimes wrote: > >You *MUST NOT* use string formatting for SQL commands unless you >carefully quote and validate the strings. Otherwise your SQL application >is vulnerable to SQL injection attacks. SQL injections are one of the >most common and devastating attacks for web applications these days. > >Example: >"Select * from Users where uid = %s" % uid >uid = "1; DROP Table users;" > >Guess what happens here ... http://xkcd.com/327/ (Just in case there are newbies here.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From awilliam at whitemice.org Sat May 22 16:35:29 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Sat, 22 May 2010 16:35:29 -0400 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <1274560529.10069.7.camel@linux-yu4c.site> On Fri, 2010-05-21 at 11:20 -0700, Patrick Maupin wrote: > On May 21, 5:21 am, Deep_Feelings wrote: > > 2- python is high productivity language : why there are no commercial > > programs written in python ? > There are a lot of commercial programs written in Python. But any > company which thinks it has a lock on some kind of super secret sauce > isn't going to use Python, Is it [only] the aspect of being "sold" that makes software "commercial"? A better question would be is how many Python applications, in house or not, are used to facilitate commerce. Answer: a lot. I have an Open Source project with >100,000 lines of Python code [which I think qualifies as a 'real' application] . But that it is Open Source makes it non-commercial? I doubt anyone would use it outside of a commercial environment, and one of its principle goals is to serve as the backend for CRM systems [essentially commercial] and facilitate automation of business processes [essentially commercial]. The 'secret sauce' isn't the code [which is MIT licenses] but what you do with it. But since the framework is essentially general purpose - why not publish the code? I think of my Open Source code as "commercial". -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From steve at REMOVE-THIS-cybersource.com.au Sat May 22 19:14:56 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 May 2010 23:14:56 GMT Subject: Another "Go is Python-like" article. References: <7c1d7e0e-eb2b-411d-bc7c-7e12a247ee8b@e21g2000vbl.googlegroups.com> Message-ID: <4bf86570$0$27861$c3e8da3@news.astraweb.com> On Sat, 22 May 2010 12:13:30 -0700, Patrick Maupin wrote about the lack of exceptions in Go: > Looking at their rationale, it is appears that one or more of the > primary go developers had to deal way too often with people who overuse > and abuse exceptions, so they are reverting to an almost childish "I'll > fix their little red wagon! When they have to use *my* language, they > won't be able to do that anymore!" kind of mentality. Another > possibility is that they viewed the complexity of exceptions as > interfering with their primary goals, and felt it necessary to > rationalize their absence after the fact. That's two possible explanations. A third is that they genuinely believe that exceptions lead to poor programming practice and left them out, just as the designers of many other languages believe that goto leads to poor practice and leave it out as well. I don't think there's necessarily anything "childish" about choosing to leave out a language feature that you think is bad from a language you design. Indeed, when I design my killer language, the identifiers "foo" and "bar" will be reserved words, never used, and not even mentioned in the reference manual. Any program using one will simply dump core without comment. Multitudes will rejoice. -- Tim Peters, 29 Apr 1998 -- Steven From lan.rogers.book at gmail.com Sat May 22 20:16:40 2010 From: lan.rogers.book at gmail.com (Lanny) Date: Sat, 22 May 2010 17:16:40 -0700 (PDT) Subject: Help (I can't think of a better title) Message-ID: The answer may be right infront of me but I really can't figure this out. I'm trying to build a interactive fiction kind of game, silly I know but I am a fan of the genre. I'm trying to build up an index of all the rooms in the game from an outside file called roomlist.txt. The only problem is that every room ends up having four exits. Here's the code. class room() : room_id = 'room_id' name = 'room' description = 'description' item_list = exits = {} visits = 0 def leave(self, direction) global roomlist global player_current_room if direction not in player_current_room.exitskeys() : print 'There is no exit in that direction.' return 1 roomlist[self.room_id] = self player_current_room = roomlist[player_current_room.exits[direction]] print player_current_room.name if player_current_room.visits < 1 : print player_current_room.description if player_current_room.item_list != [] : stdout.write('You can see ') for item in player_current_room.item_list : stdout.write('a') if item.display_name[0] in ['a','e','i','o','u'] : stdout.write('n ' + item.display_name + ',') else : stdout.write(item.display_name + ',') pass print print 'Exits:', for way in player_current_room.exits : print way.capitalize(), print player_current_room.visits += 1 pass else : player_current_room.visits += 1 pass pass def build_rooms(room_file) : global roomlist rfile = open(room_file) tmp_builder = '' for line in rfile : tmp_builder = tmp_builder + line[:-1] pass for location in tmp_builder.rsplit('::') : if location.rsplit(';')[-1] == '' : location = location[:-1] if len(location.rsplit(';')) != 5 : if '-dev' or '-v' in argv : print location.rsplit(';')[0], 'had', len(location.rsplit(';')), 'values in it, 5 expected' for value in location.rsplit(';') : print; print value foobar.append(value) print 'A room failed to initalize due to either too much or not enough values being present in the build file' pass pass else : roomlist[location.rsplit(';')[0]] = room() roomlist[location.rsplit(';')[0]].room_id = location.rsplit(';')[0] roomlist[location.rsplit(';')[0]].name = location.rsplit(';')[1] roomlist[location.rsplit(';')[0]].description = location.rsplit(';')[2] if location.rsplit(';')[3] != 'none' : pass tmp_var = location.rsplit(';')[4] print location.rsplit(';')[0], roomlist[location.rsplit(';')[0]].exits, 'before' for way in tmp_var.rsplit(',') : roomlist[location.rsplit(';')[0]].exits[way.rsplit(':') [0]] = way.rsplit(':')[1] roomlist = {} build_rooms('room_list.txt') And here is the roomlist.txt file : start_room; Starting Room; This is the starting room, if you can read this text it means that at least one part of this beta is working.; none; north:second_room,west:aux_room; :: second_room; Second Room; Yo, Yo! This is the second room, if you can see this text a substantitally greater amount of the game is running than would have been if you didn't see this text.; apple; south:start_room; :: aux_room; Auxillary Room; No, there aren't any barbarian conscripts here, but there is a table!; none; east:start_room; Ideally roomlist['start_room'].exits would equal {'aux_room' : 'west', 'second_room' : 'north'} but it doesn't. Sorry if this is unclear or too long, but I'm really stumped why it is giving bad output From python at mrabarnett.plus.com Sat May 22 20:39:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 May 2010 01:39:25 +0100 Subject: Help (I can't think of a better title) In-Reply-To: References: Message-ID: <4BF8793D.5050605@mrabarnett.plus.com> Lanny wrote: > The answer may be right infront of me but I really can't figure this > out. > I'm trying to build a interactive fiction kind of game, silly I know > but I > am a fan of the genre. I'm trying to build up an index of all the > rooms in > the game from an outside file called roomlist.txt. The only problem is > that > every room ends up having four exits. Here's the code. > > > class room() : > room_id = 'room_id' > name = 'room' > description = 'description' > item_list = > exits = {} > visits = 0 These attributes are being defined as belonging to the class, so they will be shared by all the instances of the class. This isn't a problem for immutable items such as strings, but is for mutable items such as dicts. In short, all the rooms share the same 'exits' dict. You should really define the instance attributes (variables) in the '__init__' method. > def leave(self, direction) > global roomlist > global player_current_room > if direction not in player_current_room.exitskeys() : > print 'There is no exit in that direction.' > return 1 > roomlist[self.room_id] = self > player_current_room = > roomlist[player_current_room.exits[direction]] > print player_current_room.name > if player_current_room.visits < 1 : > print player_current_room.description > if player_current_room.item_list != [] : > stdout.write('You can see ') > for item in player_current_room.item_list : > stdout.write('a') > if item.display_name[0] in ['a','e','i','o','u'] : > stdout.write('n ' + item.display_name > + > ',') > else : > stdout.write(item.display_name + ',') > pass > > print > print 'Exits:', > for way in player_current_room.exits : > print way.capitalize(), > print > player_current_room.visits += 1 > pass > else : > player_current_room.visits += 1 > pass > pass > > def build_rooms(room_file) : > global roomlist > rfile = open(room_file) > tmp_builder = '' > for line in rfile : > tmp_builder = tmp_builder + line[:-1] > pass > for location in tmp_builder.rsplit('::') : > if location.rsplit(';')[-1] == '' : > location = location[:-1] > if len(location.rsplit(';')) != 5 : > if '-dev' or '-v' in argv : > print location.rsplit(';')[0], 'had', > len(location.rsplit(';')), 'values in it, 5 expected' > for value in location.rsplit(';') : > print; print value > foobar.append(value) > print 'A room failed to initalize due to either too > much or > not enough values being present in the build file' > pass > pass > else : > roomlist[location.rsplit(';')[0]] = room() > roomlist[location.rsplit(';')[0]].room_id = > location.rsplit(';')[0] > roomlist[location.rsplit(';')[0]].name = > location.rsplit(';')[1] > roomlist[location.rsplit(';')[0]].description = > location.rsplit(';')[2] > if location.rsplit(';')[3] != 'none' : > pass > tmp_var = location.rsplit(';')[4] > print location.rsplit(';')[0], > roomlist[location.rsplit(';')[0]].exits, 'before' > for way in tmp_var.rsplit(',') : > roomlist[location.rsplit(';')[0]].exits[way.rsplit(':') > [0]] > = way.rsplit(':')[1] > > roomlist = {} > build_rooms('room_list.txt') > > And here is the roomlist.txt file : > > start_room; > Starting Room; > This is the starting room, if you can read this text it means that at > least > one part of this beta is working.; > none; > north:second_room,west:aux_room; > :: > second_room; > Second Room; > Yo, Yo! This is the second room, if you can see this text a > substantitally > greater amount of the game is running than would have been if you > didn't see > this text.; > apple; > south:start_room; > :: > aux_room; > Auxillary Room; > No, there aren't any barbarian conscripts here, but there is a table!; > none; > east:start_room; > > Ideally roomlist['start_room'].exits would equal {'aux_room' : > 'west', > 'second_room' : 'north'} but it doesn't. Sorry if this is unclear or > too > long, but I'm really stumped why it is giving bad output From mehgcap at gmail.com Sat May 22 20:53:30 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 22 May 2010 20:53:30 -0400 Subject: Help (I can't think of a better title) In-Reply-To: <4BF8793D.5050605@mrabarnett.plus.com> References: <4BF8793D.5050605@mrabarnett.plus.com> Message-ID: On 5/22/10, MRAB wrote: > Lanny wrote: >> The answer may be right infront of me but I really can't figure this >> out. >> I'm trying to build a interactive fiction kind of game, silly I know >> but I >> am a fan of the genre. I'm trying to build up an index of all the >> rooms in >> the game from an outside file called roomlist.txt. The only problem is >> that >> every room ends up having four exits. Here's the code. >> >> >> class room() : >> room_id = 'room_id' >> name = 'room' >> description = 'description' >> item_list = >> exits = {} > > visits = 0 > > These attributes are being defined as belonging to the class, so they > will be shared by all the instances of the class. This isn't a problem > for immutable items such as strings, but is for mutable items such as > dicts. In short, all the rooms share the same 'exits' dict. > > You should really define the instance attributes (variables) in the > '__init__' method. I just ran into something similar to this in my Battleship game. I had a Craft class, which defined attributes for any craft (a recon plane, a submarine, a battleship, and so on). One such attribute was a weapons list, much like your exits dictionary; I would assign a couple weapons to a battleship, but suddenly all my ships and airplanes had those same weapons. What the great people on this list said to do was something like this: class Room(): def __init__(self, exits): if exits==None: self.exits={} else: self.exits=exits In this way, you can create a new Room object with exits, r=Room(exits_dict) or you can create a Room with no exits, and add them later: r2=Room() r2.exits["exit1"]="doorway" but the code in the __init__ method, which will get called as soon as you create a new Room object, ensures that passing an exits dictionary will set that instance's exits to what was passed in, while passing nothing will create a room with an empty dictionary (the if statement). I hope this made some sense! > >> def leave(self, direction) >> global roomlist >> global player_current_room >> if direction not in player_current_room.exitskeys() : >> print 'There is no exit in that direction.' >> return 1 >> roomlist[self.room_id] = self >> player_current_room = >> roomlist[player_current_room.exits[direction]] >> print player_current_room.name >> if player_current_room.visits < 1 : >> print player_current_room.description >> if player_current_room.item_list != [] : >> stdout.write('You can see ') >> for item in player_current_room.item_list : >> stdout.write('a') >> if item.display_name[0] in ['a','e','i','o','u'] : >> stdout.write('n ' + item.display_name >> + >> ',') >> else : >> stdout.write(item.display_name + ',') >> pass >> >> print >> print 'Exits:', >> for way in player_current_room.exits : >> print way.capitalize(), >> print >> player_current_room.visits += 1 >> pass >> else : >> player_current_room.visits += 1 >> pass >> pass >> >> def build_rooms(room_file) : >> global roomlist >> rfile = open(room_file) >> tmp_builder = '' >> for line in rfile : >> tmp_builder = tmp_builder + line[:-1] >> pass >> for location in tmp_builder.rsplit('::') : >> if location.rsplit(';')[-1] == '' : >> location = location[:-1] >> if len(location.rsplit(';')) != 5 : >> if '-dev' or '-v' in argv : >> print location.rsplit(';')[0], 'had', >> len(location.rsplit(';')), 'values in it, 5 expected' >> for value in location.rsplit(';') : >> print; print value >> foobar.append(value) >> print 'A room failed to initalize due to either too >> much or >> not enough values being present in the build file' >> pass >> pass >> else : >> roomlist[location.rsplit(';')[0]] = room() >> roomlist[location.rsplit(';')[0]].room_id = >> location.rsplit(';')[0] >> roomlist[location.rsplit(';')[0]].name = >> location.rsplit(';')[1] >> roomlist[location.rsplit(';')[0]].description = >> location.rsplit(';')[2] >> if location.rsplit(';')[3] != 'none' : >> pass >> tmp_var = location.rsplit(';')[4] >> print location.rsplit(';')[0], >> roomlist[location.rsplit(';')[0]].exits, 'before' >> for way in tmp_var.rsplit(',') : >> roomlist[location.rsplit(';')[0]].exits[way.rsplit(':') >> [0]] >> = way.rsplit(':')[1] >> >> roomlist = {} >> build_rooms('room_list.txt') >> >> And here is the roomlist.txt file : >> >> start_room; >> Starting Room; >> This is the starting room, if you can read this text it means that at >> least >> one part of this beta is working.; >> none; >> north:second_room,west:aux_room; >> :: >> second_room; >> Second Room; >> Yo, Yo! This is the second room, if you can see this text a >> substantitally >> greater amount of the game is running than would have been if you >> didn't see >> this text.; >> apple; >> south:start_room; >> :: >> aux_room; >> Auxillary Room; >> No, there aren't any barbarian conscripts here, but there is a table!; >> none; >> east:start_room; >> >> Ideally roomlist['start_room'].exits would equal {'aux_room' : >> 'west', >> 'second_room' : 'north'} but it doesn't. Sorry if this is unclear or >> too >> long, but I'm really stumped why it is giving bad output > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From pmaupin at gmail.com Sat May 22 20:58:42 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 22 May 2010 17:58:42 -0700 (PDT) Subject: Another "Go is Python-like" article. References: <7c1d7e0e-eb2b-411d-bc7c-7e12a247ee8b@e21g2000vbl.googlegroups.com> <4bf86570$0$27861$c3e8da3@news.astraweb.com> Message-ID: <82a5452f-a129-477b-8a2f-26ffa65aa190@w3g2000vbd.googlegroups.com> On May 22, 6:14?pm, Steven D'Aprano wrote: > On Sat, 22 May 2010 12:13:30 -0700, Patrick Maupin wrote about the lack > of exceptions in Go: > > > Looking at their rationale, it is appears that one or more of the > > primary go developers had to deal way too often with people who overuse > > and abuse exceptions, so they are reverting to an almost childish "I'll > > fix their little red wagon! ?When they have to use *my* language, they > > won't be able to do that anymore!" kind of mentality. Another > > possibility is that they viewed the complexity of exceptions as > > interfering with their primary goals, and felt it necessary to > > rationalize their absence after the fact. > > That's two possible explanations. A third is that they genuinely believe > that exceptions lead to poor programming practice and left them out, just > as the designers of many other languages believe that goto leads to poor > practice and leave it out as well. > > I don't think there's necessarily anything "childish" about choosing to > leave out a language feature that you think is bad from a language you > design. While I admit that "childish" is an inflammatory simplification, other than that, I think that your possible explanation is, essentially, identical to my first possibility -- why would you think exceptions were bad if you didn't have first-hand evidence of that? Regards, Pat From greg.ewing at canterbury.ac.nz Sat May 22 21:49:06 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 23 May 2010 13:49:06 +1200 Subject: where are the program that are written in python? In-Reply-To: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <85rfa9Fv65U1@mid.individual.net> Deep_Feelings wrote: > i will be interested more in COMMERCIAL programs written in python I came across a game on Big Fish Games recently (it was "The Moonstone" IIRC) that appeared to have been built using Python and py2app. -- Greg From greg.ewing at canterbury.ac.nz Sat May 22 22:21:12 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 23 May 2010 14:21:12 +1200 Subject: Reading data from a Microsoft Access 2003 database In-Reply-To: References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> <4bf3eeeb$0$31263$607ed4bc@cv.net> <3c40f8d8-b29c-484f-b5b3-6dff0f68a032@m21g2000vbr.googlegroups.com> <16c9daac-293a-4cb6-b847-489e696682bd@c11g2000vbe.googlegroups.com> Message-ID: <85rh6gF8ceU1@mid.individual.net> >>On Thu, 20 May 2010 02:45:10 -0700 (PDT), Jimoid >> declaimed the following in >>gmane.comp.python.general: >> >>>I've now had a closer look at both pyODBC and mxODBC and it seems to >>>me that they both require the database to be running to be able to >>>query it. Is this correct? If you mean that an instance of MS Access has to be running, no, I don't think so. The ODBC driver for Access databases knows how to open .mdb files itself. I've done this myself recently, and it seems to work fine without having Access running anywhere. -- Greg From sturla at molden.no Sun May 23 01:18:50 2010 From: sturla at molden.no (sturlamolden) Date: Sat, 22 May 2010 22:18:50 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <9584607c-1aea-42b1-9671-19a2b51a5e17@l6g2000vbo.googlegroups.com> Message-ID: On 22 Mai, 20:45, Patrick Maupin wrote: > I think we're in violent agreement here -- you neglected to quote the > part where I said "(But the up-front choice of another language simply > for speed, rather than prototyping with Python and then recoding the > slow bits, would probably be a decision borne of ignorance.)" I'm not arguing against you. You're argument is almost that which Donald Knuth attributes to C.A.R. Hoare: "Premature optimization is the root of all evil in computer programming." It's very true though. From sturla at molden.no Sun May 23 01:35:42 2010 From: sturla at molden.no (sturlamolden) Date: Sat, 22 May 2010 22:35:42 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> Message-ID: <471f9246-26e9-4e70-b0f6-288f373c9c2c@p17g2000vbe.googlegroups.com> On 22 Mai, 13:28, Tim Chase wrote: > Just as an aside, last I checked, mercurial had some core code in > C for speed. ? I've been writing scrintific software for over 10 years. I always find myself writing small pieces of C now and then. It is usally because header files are too complicated to expose to Python. I will e.g. make OpenGL calls from C, and then call the rendering routine from Python with ctypes. It saves me the work of exposing OpenGL (or whatever) to Python. There are already header files that make the API available to C. Yes I know about PyOpenGL, but then there is the speed argument: From C I can make epeated calls to functions like glVertex4f with minial loss of efficacy. Calling glVertex4f from Python (e.g. PyOpenGL) would give me the Python (and possibly ctypes) overhead for each call, which is considerable. So there is the two arguments for using C now and then: (1) Save programming time by not having to repeat header files and (2) make programs run faster by avoiding the Python overhead. Some times it matters, some times it don't. But it does not make sense to write C or C++ all the time, nor does it help to use C or C++ for I/O bound problems. From contact at xavierho.com Sun May 23 01:49:05 2010 From: contact at xavierho.com (Xavier Ho) Date: Sun, 23 May 2010 15:49:05 +1000 Subject: where are the program that are written in python? In-Reply-To: <471f9246-26e9-4e70-b0f6-288f373c9c2c@p17g2000vbe.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <471f9246-26e9-4e70-b0f6-288f373c9c2c@p17g2000vbe.googlegroups.com> Message-ID: On Sun, May 23, 2010 at 3:35 PM, sturlamolden wrote: > Yes I know about PyOpenGL, but then there is the speed argument: From > C I can make epeated calls to functions like glVertex4f with minial > loss of efficacy. Calling glVertex4f from Python (e.g. PyOpenGL) would > give me the Python (and possibly ctypes) overhead for each call, which > is considerable. > Not to counter your arguement, but I would just like to point out that calling glVertex*() repeatedly is always not as efficient as using a VBO or a display list. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From bieffe62 at gmail.com Sun May 23 03:50:43 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sun, 23 May 2010 00:50:43 -0700 (PDT) Subject: First Tkinter script: requesting comments References: <87d3wokjnr.fsf@kasterma.Colorado.EDU> Message-ID: <02f43218-98b9-4d75-bb5f-bad847d8bf3c@40g2000vbr.googlegroups.com> On 21 Mag, 23:51, Bart Kastermans wrote: > I wrote a first script using Tkinter. ?As I am new to its > use, I am only just feeling my way around. ?I would very > much like comments on the design of the script (and in fact > any other comments on my code would also be very welcome). > > I have it posted (with syntax coloring) at: > > http://kasterma.wordpress.com/2010/05/21/first-experiments-with-tkinter/ > > But will also include it here for convenience. > > Thanks for any help, > > Best, > Bart > > *********************** > > #!/usr/bin/env python > # > # Getting a list of students and grades displayed so that grades can > # be updated, and we poll these changes (so that in the future we can > # act on it). > # > # Bart Kastermans,www.bartk.nl > > """ > Design of the window > > ? ? ? +-------------------------------------------------------------+ > ? ? ? | ?root ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | > ? ? ? | ?+------------------------------------------------------+ ? | > ? ? ? | ?| title_frame ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?| ?+------------------------------+ ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?| ?| Label(title) ? ? ? ? ? ? ? ? | ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?| ?| ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?| ?+------------------------------+ ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?+------------------------------------------------------+ ? | > ? ? ? | ?+------------------------------------------------------+ ? | > ? ? ? | ?| exam_grades_frames ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | ? | > ? ? ? | ?| ?+-------------------------------------------------+ | ? | > ? ? ? | ?| ?| Frame(ex) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | | ? | > ? ? ? | ?| ?| +--------------------+ ?+---------------------+ | | ? | > ? ? ? | ?| ?| | Entry(name) ? ? ? ?| ?| Entry(grade) ? ? ? ?| | | ? | > ? ? ? | ?| ?| | ? ? ? ? ? ? ? ? ? ?| ?| ? ? ? ? ? ? ? ? ? ? | | | ? | > ? ? ? | ?| ?| +--------------------+ ?+---------------------+ | | ? | > ? ? ? | ?| ?+-------------------------------------------------+ | ? | > ? ? ? | ?| ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| ? | > ? ? ? | ?+------------------------------------------------------+ ? | > ? ? ? | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | > ? ? ? | ? ? ? ? ? ? ? ? +---------------------+ ? ? ? ? ? ? ? ? ? ? | > ? ? ? | ? ? ? ? ? ? ? ? | quit_button ? ? ? ? | ? ? ? ? ? ? ? ? ? ? | > ? ? ? | ? ? ? ? ? ? ? ? | ? ? ? ? ? ? ? ? ? ? | ? ? ? ? ? ? ? ? ? ? | > ? ? ? | ? ? ? ? ? ? ? ? +---------------------+ ? ? ? ? ? ? ? ? ? ? | > ? ? ? +-------------------------------------------------------------+ > > """ > > from Tkinter import * > > # global info for this specific example > > # four students > no_stud = 4 > exam_grades = [1,2,3,4] > names = ["Ben", "Jim", "James", "Mel"] > # upper bound for name length > max_name_len = max (map (len, names)) > > # set up root window > root = Tk() > root.geometry ("400x400") > > exam_grades_string = map (lambda x: StringVar (root,str (x)), exam_grades) > > names_string = map (lambda x: StringVar (root, x), names) > > def setup (): > ? ? """ setup the window with the list of students. > > ? ? This is test-code to figure out what the app finally should look > ? ? like. > ? ? """ > > ? ? # title frame, with title Grade Correction in it > ? ? title_frame = Frame(root) > ? ? title_frame.pack (fill=X) > > ? ? w = Label (title_frame, text = "Grade Correction", font = ("Helvetica", 25)) > ? ? w.pack (side=LEFT) > > ? ? # from to hold the list of grades > ? ? exam_grades_frame = Frame (root) > ? ? exam_grades_frame.pack (fill=BOTH) > > ? ? exam_label = Label (exam_grades_frame, text="EXAMS") > ? ? exam_label.pack () > > ? ? # set up the list of grades > ? ? for i in range (0,no_stud): > ? ? ? ? # a frame per student > ? ? ? ? ex = Frame (exam_grades_frame) > ? ? ? ? ex.pack () > ? ? ? ? # name on the left > ? ? ? ? name = Entry (ex, textvariable=names_string[i], width=max_name_len+2) > ? ? ? ? name.config (state=DISABLED) > ? ? ? ? name.pack (side=LEFT) > ? ? ? ? # grade next to it > ? ? ? ? grade = Entry (ex, textvariable=exam_grades_string [i], width=4) > ? ? ? ? grade.pack (side=LEFT) > > ? ? # button to quit the application > ? ? qb = Button (root) > ? ? qb ['text'] = "quit" > ? ? qb ['command'] = root.quit > ? ? qb.pack () > > def to_int (st): > ? ? """ helper function to convert strings to integers. > > ? ? Empty string represents 0. > ? ? """ > ? ? if len (st) == 0: > ? ? ? ? return 0 > ? ? else: > ? ? ? ? return int (st) > > def get_curr_grades (): > ? ? """ extract the grades from exam_grades_string. > > ? ? exam_grades_string consists of StringVar that get updated when the > ? ? fields are updated in the GUI. > ? ? """ > ? ? grades = [] > ? ? for i in range (0, no_stud): > ? ? ? ? grades.append (exam_grades_string [i].get()) > ? ? return grades > > # get the current grades > curr_grades = map (to_int, get_curr_grades ()) > > def poll_exams (): > ? ? """ function that keeps polling the current grades, looking for changes""" > ? ? global curr_grades > ? ? new_grades = map (to_int, get_curr_grades ()) > ? ? if new_grades != curr_grades: > ? ? ? ? print new_grades > ? ? ? ? curr_grades = new_grades > ? ? root.after( 250, poll_exams) > > # window setup > setup () > > # start the polling > poll_exams () > > # start the eventloop > root.mainloop () > > # do cleanup > root.destroy () > sys.exit () It looks fine to me, except that I would do it a bit more OOP-style (can't stand the globals very much). Also, I would use labels instead of disabled text fields for student names, since they don't need to be edited. Add maybe tray to align the name and grade widgets in a 2x4 matrix using .grid() instead of .pack() ( see http://effbot.org/tkinterbook/grid.htm ) One thing I don't understand, is why you need to 'poll' continuously for changes, except for demo purpose. If this is supposed to be a window for user to enter data into the program, the standard practice is to have a separate window (not the main one), with apply and cancel buttons, where both buttons close the window but only the apply button register the change. So you need to do the stuff you do in the poll_exams function only in the callback of the apply button. On the python side, you don't need no_stud variable since you can do len(names_string). And maybe have single list of (name, grade) pairs, so youl loop would become something like: for i, (name, grade) in enumerate( names_and_grades_list ) : # use name instead of names_string[i] # use grade instead of exam_grades_string[i] Although this could slightly complicate the upgrade of grades. The usage of a small class StudentData could be in order, too. Ciao ------- FB From lie.1296 at gmail.com Sun May 23 04:19:57 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 23 May 2010 18:19:57 +1000 Subject: where are the program that are written in python? In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> Message-ID: <4bf8e592$1@dnews.tpgi.com.au> On 05/23/10 04:49, Terry Reedy wrote: > On 5/21/2010 11:03 PM, Lie Ryan wrote: >> On 05/22/10 04:47, Terry Reedy wrote: >>> On 5/21/2010 6:21 AM, Deep_Feelings wrote: >>>> python is not a new programming language ,it has been there for the >>>> last .... 15+ years or so ? right ? >>>> >>>> however by having a look at this page >>>> http://wiki.python.org/moin/Applications >>>> i could not see many programs written in python (i will be interested >>>> more in COMMERCIAL programs written in python ). and to be honest ,i >>> >>> There are two kinds of 'commercial' programs. >>> 1. The vast majority are proprietary programs kept within a company for >>> its own use. As long as these work as intended, they are mostly >>> invisible to the outside world. >>> 2. Programs sold to anyone who wants them. >>> >>> Python trades programmer speed for execution speed. If a successful >>> Python program is going to be run millions of times, it makes economic >>> sense to convert time-hogging parts to (for instance) C. In fact, this >>> is a consideration in deciding what functions should be builtin and >>> which stdlib modules are written or rewritten in C. >>> >>> Programs being sold tend to be compared to competitors on speed with >>> perhaps more weight than they rationally should. Speed is easier to >>> measure than, for instance, lack of bugs. >> >> doubting python's speed? > > The is a somewhat bizarre response to me. I have been promoting Python > for about 13 years, since I dubbed it 'executable pseudocode', which is > to say, easy to write, read, understand, and improve. I am also a > realist. Any fixed (C)Python program can be sped up, at least a bit, and > possibly more, by recoding in C. At minimum, the bytecodes can be > replaced by the C code and C-API calls that they get normally get > translated into. Ints can be unboxed. Etcetera. This tend to freeze a > program, which is fine when development is finished. I'm not claiming Python is faster than C, but I'm just being a realists, when I say that in real life 9 out of 10 writing a program in a slow language doesn't really matter to actual program speed. I used Mercurial as an example where the developers choose an initially irrational decision of using a slow language (python) to beat the speed of a fast language (C). Of course, you can always point out the 1 case out of 10. In this cases, python can still cope with C extension, Psyco, Numpy-and-friends, Cython, or even dumping python and using full C all the way. But the point still hold, that in real life, often the language's raw speed doesn't really limit the program's speed. From nobody at nowhere.com Sun May 23 04:39:27 2010 From: nobody at nowhere.com (Nobody) Date: Sun, 23 May 2010 09:39:27 +0100 Subject: Help (I can't think of a better title) References: Message-ID: On Sat, 22 May 2010 17:16:40 -0700, Lanny wrote: > Ideally roomlist['start_room'].exits would equal {'aux_room' : 'west', > 'second_room' : 'north'} but it doesn't. Sorry if this is unclear or too > long, but I'm really stumped why it is giving bad output Just to condense a point which the other responses don't (IMHO) make particularly clear: Unlike most other OO languages, Python doesn't make instance members appear as variables within methods; you have to explicitly access them as members of "self", i.e. "self.exits" for the "exits" member of the current instance ("self"). From cournape at gmail.com Sun May 23 04:47:50 2010 From: cournape at gmail.com (David Cournapeau) Date: Sun, 23 May 2010 17:47:50 +0900 Subject: where are the program that are written in python? In-Reply-To: <4bf8e592$1@dnews.tpgi.com.au> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> <4bf8e592$1@dnews.tpgi.com.au> Message-ID: On Sun, May 23, 2010 at 5:19 PM, Lie Ryan wrote: > But the point still hold, that in real life, often the language's raw > speed doesn't really limit the program's speed. I would rather say that Python vs C does not matter until it does, and it generally does when constants factor matter (which is one way to draw the line between system programming and "general" programming). It totally depends on the applications, I don't think you can draw general arguments. David From __peter__ at web.de Sun May 23 05:18:03 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 May 2010 11:18:03 +0200 Subject: First Tkinter script: requesting comments References: <87d3wokjnr.fsf@kasterma.Colorado.EDU> <02f43218-98b9-4d75-bb5f-bad847d8bf3c@40g2000vbr.googlegroups.com> Message-ID: Francesco Bochicchio wrote: > One thing I don't understand, is why you need to 'poll' continuously > for changes, except for demo purpose. You can give the user immediate feedback on changes he makes. I'd argue that e. g. an "auto-apply" dialog with a revert button is much more usable and am surprised that this style hasn't caught on. > If this is supposed to be a window for user to enter data into the > program, the standard practice is to have a > separate window (not the main one), with apply and cancel buttons, > where both buttons close the window but only > the apply button register the change. So you need to do the stuff you > do in the poll_exams function only in the > callback of the apply button. If you want live updates you can also use StringVar.trace() instead of polling: from functools import partial def grade_changed(name, index, var, *args): new_grade = to_int(var.get()) if new_grade != exam_grades[index]: exam_grades[index] = new_grade print name, "-->", new_grade pairs = zip(names, exam_grades_string) for index, (name, var) in enumerate(pairs): var.trace("w", partial(grade_changed, name, index, var)) See also http://effbot.org/tkinterbook/variable.htm Peter From hpsmouse at gmail.com Sun May 23 05:19:40 2010 From: hpsmouse at gmail.com (hpsMouse) Date: Sun, 23 May 2010 02:19:40 -0700 (PDT) Subject: Urllib2: Only a partial page retrieved References: <77019685-3bf4-4d0c-9fd7-13ed8e84e102@y12g2000vbg.googlegroups.com> Message-ID: On 5?22?, ??5?43?, Dragon Lord wrote: > The cutoff is allways at the same location: just after the label > "Meeting date" and before the date itself. Could it be that something > is interpreted as and eof command or something like that? > > example of the cutoff point with a bad page: >
Meeting Date: > > example of the cutoff point with a good page: >
Meeting Date: I checked TCP packages, and found that the remote HTTP server send a data package with flag "PUSH", causing the client to close connection. That is exactly where the "Meeting Date: " appears. This seems not to be a bug for python, because Qt and telnet both failed in my test, so did the wget program... Most browsers use keep-alive HTTP, so the connection won't be closed. I think that's why a browser show the page correctly. From hpsmouse at gmail.com Sun May 23 05:42:04 2010 From: hpsmouse at gmail.com (hpsMouse) Date: Sun, 23 May 2010 02:42:04 -0700 (PDT) Subject: Urllib2: Only a partial page retrieved References: <77019685-3bf4-4d0c-9fd7-13ed8e84e102@y12g2000vbg.googlegroups.com> Message-ID: I know what the problem is. Server checks client's locale setting to determine how the date should be displayed. Python don't send locale information by default. So server fails at that point. If you add the following field in the HTTP request, the response will be correct: Accept-Language: en From sturla at molden.no Sun May 23 06:22:22 2010 From: sturla at molden.no (sturlamolden) Date: Sun, 23 May 2010 03:22:22 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <4bf749ef@dnews.tpgi.com.au> <4bf8e592$1@dnews.tpgi.com.au> Message-ID: On 23 Mai, 10:47, David Cournapeau wrote: > I would rather say that Python vs C does not matter until it does, I disagree. C matters because it is portable assembly code. Which means it is tedious and error prone to use, so avoiding it actually matters. Hence C matters. Knowing when and when not to use C matters a lot. From dragonlordnld at gmail.com Sun May 23 07:34:53 2010 From: dragonlordnld at gmail.com (Dragon Lord) Date: Sun, 23 May 2010 04:34:53 -0700 (PDT) Subject: Urllib2: Only a partial page retrieved References: <77019685-3bf4-4d0c-9fd7-13ed8e84e102@y12g2000vbg.googlegroups.com> Message-ID: <1eb593bc-ce04-479e-b012-53c5b55ba181@b21g2000vbh.googlegroups.com> Thanks, that works perfectly! (oh and I learnt something new too, because I tried using telnet to connect to the server :) ) On May 23, 11:42?am, hpsMouse wrote: > I know what the problem is. > > Server checks client's locale setting to determine how the date should > be displayed. Python don't send locale information by default. So > server fails at that point. > > If you add the following field in the HTTP request, the response will > be correct: > Accept-Language: en From dg1sbg at googlemail.com Sun May 23 09:46:48 2010 From: dg1sbg at googlemail.com (Frank GOENNINGER) Date: Sun, 23 May 2010 15:46:48 +0200 Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' Message-ID: Hi all: Being completely new to Python still (just about a week into it now) I tried to follow the Python 2.6.5 version documemtation aiming at setting up a logger as follows: import logging global gPIBLogger class PIBLogger(object): ''' TODO: classdocs ''' def __init__(self, logFileName): ''' Constructor ''' self.logFileName = logFileName self.logger = logging.getLogger('PIBLogger') self.logger.setLevel(logging.DEBUG) handler = logging.handlers.RotatingFileHandler(self.logFileName, maxBytes=1000000, backupCount=9) self.logger.addHandler(handler) gPIBLogger = self.logger def main(): mylogger = PIBLogger('/tmp/pib.log') gPIBLogger.debug(' Hi ') if __name__ == "__main__": main() When trying to execute main() I get: Traceback (most recent call last): File "/.../src/pib/logging.py", line 37, in main() File "/.../src/pib/logging.py", line 33, in main mylogger = PIBLogger('/tmp/pib.log') File "/...src/pib/logging.py", line 23, in __init__ self.logger = logging.getLogger('PIBLogger') AttributeError: 'module' object has no attribute 'getLogger' I double checked and yes, getLogger is there. Why is the interpreter asking for an "attribute" here ? Any hints on what I am doing wrong ? TIA! Regards Frank From simon at brunningonline.net Sun May 23 10:04:01 2010 From: simon at brunningonline.net (Simon Brunning) Date: Sun, 23 May 2010 15:04:01 +0100 Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' In-Reply-To: References: Message-ID: On 23 May 2010 14:46, Frank GOENNINGER wrote: > Traceback (most recent call last): > ?File "/.../src/pib/logging.py", line 37, in > ? ?main() Here's a clue - looks like your own module is called logging. That's what's getting imported by your import. Try naming your module something else, and you should be golden. -- Cheers, Simon B. From duncan.booth at invalid.invalid Sun May 23 10:06:22 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 May 2010 14:06:22 GMT Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' References: Message-ID: Frank GOENNINGER wrote: > > When trying to execute main() I get: > > Traceback (most recent call last): > File "/.../src/pib/logging.py", line 37, in > main() > File "/.../src/pib/logging.py", line 33, in main > mylogger = PIBLogger('/tmp/pib.log') > File "/...src/pib/logging.py", line 23, in __init__ > self.logger = logging.getLogger('PIBLogger') > AttributeError: 'module' object has no attribute 'getLogger' > > I double checked and yes, getLogger is there. Why is the interpreter > asking for an "attribute" here ? Any hints on what I am doing wrong ? > You're source file appears to be called logging.py, so when you do 'import logging' it just imports itself. The system logging.py has a getLogger function, but *your* logging.py doesn't. From philip at semanchuk.com Sun May 23 10:07:12 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 23 May 2010 10:07:12 -0400 Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' In-Reply-To: References: Message-ID: <565789B5-AB23-41C1-82CD-3434AFE3E39E@semanchuk.com> On May 23, 2010, at 9:46 AM, Frank GOENNINGER wrote: > > Hi all: > > Being completely new to Python still (just about a week into it now) I > tried to follow the Python 2.6.5 version documemtation aiming at > setting > up a logger as follows: > > > > import logging > > global gPIBLogger > > class PIBLogger(object): > ''' > TODO: classdocs > ''' > > def __init__(self, logFileName): > ''' > Constructor > ''' > self.logFileName = logFileName > self.logger = logging.getLogger('PIBLogger') > self.logger.setLevel(logging.DEBUG) > handler = > logging.handlers.RotatingFileHandler(self.logFileName, > > maxBytes=1000000, > backupCount=9) > self.logger.addHandler(handler) > gPIBLogger = self.logger > > > def main(): > mylogger = PIBLogger('/tmp/pib.log') > gPIBLogger.debug(' Hi ') > > if __name__ == "__main__": > main() > > > > When trying to execute main() I get: > > Traceback (most recent call last): > File "/.../src/pib/logging.py", line 37, in > main() > File "/.../src/pib/logging.py", line 33, in main > mylogger = PIBLogger('/tmp/pib.log') > File "/...src/pib/logging.py", line 23, in __init__ > self.logger = logging.getLogger('PIBLogger') > AttributeError: 'module' object has no attribute 'getLogger' > > I double checked and yes, getLogger is there. Why is the interpreter > asking for an "attribute" here ? Any hints on what I am doing wrong ? Short answer: Change the name of src/pib/logging.py to something else. Long answer: When Python hits the line "import logging", it first looks in the current directory and imports logging.py, which in this case is the file it's already executing. It never finds the standard library's logging module. One way you could have figured this out would be to add this as the first line of main(): print dir(logging) That would have told you what Python thought the logging module looked like, and would have perhaps recognized it as your own. Cheers Philip From filipe.bvr at gmail.com Sun May 23 11:13:54 2010 From: filipe.bvr at gmail.com (Filipe) Date: Sun, 23 May 2010 08:13:54 -0700 (PDT) Subject: |help| python 3.12 Message-ID: I'm with a problem I'm doing a program in python, it sends the following error message: File "C:/Documents and Settings/Filipe Vinicius/Desktop/Filipe/Cefet/ LP/Python/trab.sistema.academico/sistemaacademico.2010.5.23.c.py", line 40, in administrador lp = pickle.load(f) File "D:\Arquivos De Programa\Python31\lib\pickle.py", line 1365, in load encoding=encoding, errors=errors).load() EOFError What you need to do to repair this error? in my program at the part where the error is find is that: def administrador(): f = open('professores.dat', 'rb') lp = pickle.load(f) f.close() ... Note: i had already imported the pikcle library THX From buzzard at urubu.freeserve.co.uk Sun May 23 11:57:54 2010 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Sun, 23 May 2010 16:57:54 +0100 Subject: Help (I can't think of a better title) In-Reply-To: References: <4BF8793D.5050605@mrabarnett.plus.com> Message-ID: Alex Hall wrote: > On 5/22/10, MRAB wrote: >> Lanny wrote: >>> The answer may be right infront of me but I really can't figure this >>> out. >>> I'm trying to build a interactive fiction kind of game, silly I know >>> but I >>> am a fan of the genre. I'm trying to build up an index of all the >>> rooms in >>> the game from an outside file called roomlist.txt. The only problem is >>> that >>> every room ends up having four exits. Here's the code. >>> >>> >>> class room() : >>> room_id = 'room_id' >>> name = 'room' >>> description = 'description' >>> item_list = >>> exits = {} >> > visits = 0 >> >> These attributes are being defined as belonging to the class, so they >> will be shared by all the instances of the class. This isn't a problem >> for immutable items such as strings, but is for mutable items such as >> dicts. In short, all the rooms share the same 'exits' dict. >> >> You should really define the instance attributes (variables) in the >> '__init__' method. > > I just ran into something similar to this in my Battleship game. I had > a Craft class, which defined attributes for any craft (a recon plane, > a submarine, a battleship, and so on). One such attribute was a > weapons list, much like your exits dictionary; I would assign a couple > weapons to a battleship, but suddenly all my ships and airplanes had > those same weapons. What the great people on this list said to do was > something like this: > > class Room(): > def __init__(self, exits): > if exits==None: > self.exits={} > else: > self.exits=exits > > In this way, you can create a new Room object with exits, > r=Room(exits_dict) > or you can create a Room with no exits, and add them later: > r2=Room() > r2.exits["exit1"]="doorway" > > but the code in the __init__ method, which will get called as soon as > you create a new Room object, ensures that passing an exits dictionary > will set that instance's exits to what was passed in, while passing > nothing will create a room with an empty dictionary (the if > statement). I hope this made some sense! [snip] It does when when you want 'exits' to take a default value which is a mutable type (and you don't want it shared by all instances). class Room: def __init__(self, exits=None): if exits is None: self.exits = {} else: self.exits = exits Otherwise, you're fine without the if ... else. Duncan From albert at spenarnc.xs4all.nl Sun May 23 12:07:44 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 23 May 2010 16:07:44 GMT Subject: Ugly modification of a class, can it be done better ? References: <4BF5D02A.9070600@gmail.com> <4bf5e19e$0$27861$c3e8da3@news.astraweb.com> Message-ID: In article <4bf5e19e$0$27861$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >Sorry for breaking threading, but Stef's original post has not come >through to me. > >> On Thu, May 20, 2010 at 8:13 PM, Stef Mientki >> wrote: > >>> So I want to change the behavior of the class dynamically. I've done it >>> by adding a global variable (Base_Grid_Double_Click) in the module, >>> initial set to None, >>> but can be changed by the main program to some callback function. (see >>> the code below) > >How is this supposed to work? If you have *one* global, then *every* >instance will see the same setting. To change it dynamically, you enter a >nightmare world of having to save the global, modify it, then restore it, >every single time. Trust me, I've been there, this is the *worst* way of >programming. This is why object oriented inheritance was invented, to >escape this nonsense! > >The first thing is to make the callback specific to the class, not >global. Why does your printing code need access to the callback that >handles double-clicking on a grid? It doesn't! So don't give it that >access (at least, not easy access). Put the callback in the class. > >class MyClass: > callback = None > def method(self, *args): > if self.callback is None: > behaviour_with_no_callback() > else: > behaviour_with_callback() > > >Now if you want to apply a callback to some instances, and not others, it >is totally simple: > > >red = MyClass() >blue = MyClass() >red.callback = my_callback_function > >and you're done. Don't go overboard in complication. Python can handle variable functions just fine, if that is the proper solution to your problem. (In c they are called function pointers and they are unruly.) def a(b,c): return b+c def p(q,r): return q*r x=a x(3,5) 8 x=p x(3,5) 15 >-- >Steven Sorry, but couldn't respond to the original message. My newsserver doesn't have it anymore. Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From gherron at islandtraining.com Sun May 23 12:38:28 2010 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 23 May 2010 09:38:28 -0700 Subject: |help| python 3.12 In-Reply-To: References: Message-ID: <4BF95A04.5040500@islandtraining.com> On 05/23/2010 08:13 AM, Filipe wrote: > I'm with a problem I'm doing a program in python, it sends the > following error message: > > File "C:/Documents and Settings/Filipe Vinicius/Desktop/Filipe/Cefet/ > LP/Python/trab.sistema.academico/sistemaacademico.2010.5.23.c.py", > line 40, in administrador > lp = pickle.load(f) > File "D:\Arquivos De Programa\Python31\lib\pickle.py", line 1365, in > load > encoding=encoding, errors=errors).load() > EOFError > > What you need to do to repair this error? in my program at the part > where the error is find is that: > > def administrador(): > f = open('professores.dat', 'rb') > lp = pickle.load(f) > f.close() > ... > > Note: i had already imported the pikcle library > THX > EOFError means "End Of File". The file you are reading in 'professores.dat' must not contain a valid pickle -- perhaps it is empty, or created incorrectly. But that's where to look. Show us how you created that file. Gary Herron From miki.tebeka at gmail.com Sun May 23 17:30:13 2010 From: miki.tebeka at gmail.com (Miki) Date: Sun, 23 May 2010 14:30:13 -0700 (PDT) Subject: How to show the current line number with pdb.set_trace() References: Message-ID: <688562d2-93c6-4c33-b28d-73a2eda6b736@6g2000prg.googlegroups.com> Hello, > After starting pdb.set_trace(), python doens't show line number. Could > you let me know how to print the number by default so that I know > where the current line is? When you get the PDB prompt, just type "l". It'll show some code with an error on the current line. You can also type "?" for help. HTH, -- Miki From ith140 at gmail.com Sun May 23 18:30:25 2010 From: ith140 at gmail.com (Ian Hoffman) Date: Sun, 23 May 2010 15:30:25 -0700 (PDT) Subject: MySQL, Python, NumPy and formatted read Message-ID: Hello, I'm having significant Python difficulties (and I'm new to Python). I'm trying to read BLOB ASCII (numerical) data from a MySQL database using MySQLdb in a formatted fashion. The BLOB data is a sequence of numbers separated by newlines (\n), like this: 5 6 10 45 etc. When I read the data using the fetchone() command I get a single tuple. What I'd like is to somehow put the tuple into a NumPy array with each value as one element. Then I can continue to do some numerical processing. Any advice/help? From landimatte at gmail.com Sun May 23 18:54:47 2010 From: landimatte at gmail.com (Matteo Landi) Date: Mon, 24 May 2010 00:54:47 +0200 Subject: MySQL, Python, NumPy and formatted read In-Reply-To: References: Message-ID: I know anything about mysqldb and fetchone method, but it's easy to create a numpy array, given a tuple of data: >>> import numpy >>> >>> t = ('1', '2', '3') >>> numpy.array(t, int) array([1, 2, 3]) >>> I made the assumption that mysqldb.fetchone return a tuple of strings, so we need to create an array by specifying the type of the needed values. On Mon, May 24, 2010 at 12:30 AM, Ian Hoffman wrote: > Hello, > > I'm having significant Python difficulties (and I'm new to Python). > I'm trying to read BLOB ASCII (numerical) data from a MySQL database > using MySQLdb in a formatted fashion. ?The BLOB data is a sequence of > numbers separated by newlines (\n), like this: > 5 > 6 > 10 > 45 > etc. > > When I read the data using the fetchone() command I get a single > tuple. ?What I'd like is to somehow put the tuple into a NumPy array > with each value as one element. ?Then I can continue to do some > numerical processing. > > Any advice/help? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From highcar at gmail.com Sun May 23 19:56:02 2010 From: highcar at gmail.com (ken) Date: Sun, 23 May 2010 16:56:02 -0700 (PDT) Subject: python urllib mechanize post problem Message-ID: <44c348a1-aea3-423c-816e-f5492c60d993@v29g2000prb.googlegroups.com> hello ALL im making some simple python post script but it not working well. there is 2 part to have to login. first login is using 'http://mybuddy.buddybuddy.co.kr/userinfo/ UserInfo.asp' this one. and second login is using 'http://user.buddybuddy.co.kr/usercheck/ UserCheckPWExec.asp' i can login first login page, but i couldn't login second page website. and return some error 'illegal access' such like . i heard this is related with some cooke but i don't know how to implement to resolve this problem. if anyone can help me much appreciated!! Thanks! import re,sys,os,mechanize,urllib,time import datetime,socket params = urllib.urlencode({'ID':'ph896011', 'PWD':'pk1089' }) rq = mechanize.Request("http://mybuddy.buddybuddy.co.kr/userinfo/ UserInfo.asp", params) rs = mechanize.urlopen(rq) data = rs.read() logged_fail = r';history.back();' in data if not logged_fail: print 'login success' try: params = urllib.urlencode({'PASSWORD':'pk1089'}) rq = mechanize.Request("http://user.buddybuddy.co.kr/usercheck/ UserCheckPWExec.asp", params ) rs = mechanize.urlopen(rq) data = rs.read() print data except: print 'error' From andrew.tan614 at gmail.com Sun May 23 23:06:33 2010 From: andrew.tan614 at gmail.com (Andrew) Date: Sun, 23 May 2010 20:06:33 -0700 (PDT) Subject: Extended deadline (15 July 2010): CACS Singapore [EI Compendex,ISTP,IEEE Xplore] Message-ID: [ Please forward to those who may be interested. Thanks. ] ================================================================== 2010 International Congress on Computer Applications and Computational Science CACS 2010 http://irast.org/conferences/CACS/2010 4-6 December 2010, Singapore ================================================================== CACS 2010 aims to bring together researchers and scientists from academia, industry, and government laboratories to present new results and identify future research directions in computer applications and computational science. Topics of interest include, but are not limited to: Agent and Autonomous Systems Computational Biology and Bioinformatics Computer-Aided Design and Manufacturing Computer Architecture and VLSI Computer Control and Robotics Computer Graphics, Animation and Virtual Reality Computers in Education & Learning technology Computer Modeling and Simulations Computer Networks and Communications Computer Security and Privacy Computer Vision and Pattern Recognition Data Mining and Data Engineering Distributed and Services Computing Energy and Power Systems Intelligent Systems Internet and Web Systems Nano Technologies Real-Time and Embedded Systems Scientific Computing and Applications Signal, Image and Multimedia Processing Software Engineering Test Technologies CACS 2010 conference proceedings will be published by CPS which will include the conference proceedings in IEEE Xplore and submit the proceedings to Ei Compendex and ISTP for indexing. Singapore's cultural diversity reflects its colonial history and Chinese, Malay, Indian and Arab ethnicities. English is the dominant official language, which is convenient for foreign visitors. Places of interest, such as the Orchard Road district, Singapore Zoo, Night Safari, and Sentosa, attract millions of visitors a year. Singapore is a paradise for shopping, dinning, entertainment, and nightlife, with two new integrated resorts. Conference Contact: CACS at irast.org Paper Submission Deadline with Extended: 15 July 2010 Review Decision Notifications: 15 August 2010 Final Papers and Author Registration Deadline: 9 September 2010 From ith140 at gmail.com Mon May 24 00:44:30 2010 From: ith140 at gmail.com (Ian Hoffman) Date: Sun, 23 May 2010 21:44:30 -0700 (PDT) Subject: MySQL, Python, NumPy and formatted read References: Message-ID: On May 23, 6:54?pm, Matteo Landi wrote: > I know anything about mysqldb and fetchone method, but it's easy to > create a numpy array, given a tuple of data: > > > > >>> import numpy > > >>> t = ('1', '2', '3') > >>> numpy.array(t, int) > array([1, 2, 3]) > > I made the assumption that mysqldb.fetchone return a tuple of strings, > so we need to create an array by specifying the type of the needed > values. > > > > On Mon, May 24, 2010 at 12:30 AM, Ian Hoffman wrote: > > Hello, > > > I'm having significant Python difficulties (and I'm new to Python). > > I'm trying to read BLOB ASCII (numerical) data from a MySQL database > > using MySQLdb in a formatted fashion. ?The BLOB data is a sequence of > > numbers separated by newlines (\n), like this: > > 5 > > 6 > > 10 > > 45 > > etc. > > > When I read the data using the fetchone() command I get a single > > tuple. ?What I'd like is to somehow put the tuple into a NumPy array > > with each value as one element. ?Then I can continue to do some > > numerical processing. > > > Any advice/help? > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Matteo Landihttp://www.matteolandi.net/ The problem is the tuple is contained in a single value separated by newlines (only a[0] has a record), otherwise I could do as you suggest... Isn From wuwei23 at gmail.com Mon May 24 01:29:12 2010 From: wuwei23 at gmail.com (alex23) Date: Sun, 23 May 2010 22:29:12 -0700 (PDT) Subject: where are the program that are written in python? References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <85rfa9Fv65U1@mid.individual.net> Message-ID: <1c5ea366-a909-4da7-ab7a-fe30542ebfab@a27g2000prj.googlegroups.com> Gregory Ewing wrote: > I came across a game on Big Fish Games recently (it was > "The Moonstone" IIRC) that appeared to have been built using > Python and py2app. Python tends to be used more for scripting internal game logic than for every aspect of a game (which is, IMO, the right way to go about it). It's not a huge list of commercial games that does this[1], but it's a fairly classy one :) 1: http://en.wikipedia.org/wiki/Category:Python-scripted_video_games From rowinggolfer*no_spam* at googlemail.com Mon May 24 04:29:37 2010 From: rowinggolfer*no_spam* at googlemail.com (Neil Wallace) Date: Mon, 24 May 2010 08:29:37 GMT Subject: Help with PyQt4 tabwidget setup References: Message-ID: On Fri, 21 May 2010 08:03:43 +0200, dpalmboom wrote: > I am creating an application and I'm busy designing the main layout on > the main window. What I would like to do is the following: > > Create a QTabWidget with a QVBoxLayout already inside it and also a > scrollbar inside it. When a user triggers a menu item, a QDockWidget > must be created and inserted into the QVBoxLayout, but it must not > stretch to the bottom of the QTabWidget. The QDockWidget must keep a set > size in the QVBoxLayout. When the user triggers another menu item, the > next QDockWidget must go above or below the existing QDockWidgets in the > QVBoxLayout. > > I currently have the following code for the QTabWidget: > > class PaneTabWidget(PyQt4.QtGui.QTabWidget): > > def __init__(self, tabs, parent=None): > > """ > A tabwidget to go inside a Pane. > """ > > super(PaneTabWidget, self).__init__(parent) > > for tab in tabs: > > if tab == "Properties": > self.propertiesBin() > elif tab == "Schedule": > self.scheduleBin() > elif tab == "Pricelist": > self.pricelistBin() > > def setLayoutAndScrollBar(self, page): > pass > > def addPanel(self, panel, type): > self.addTab(panel, type) > > def propertiesBin(self): > self.page = PyQt4.QtGui.QWidget() > self.addTab(self.page, "Properties") > self.setLayoutAndScrollBar(self.page) > > Right now, the dockwidget gets put into a new tab in the tab widget, but > I would like to put it into an existing QVBoxLayout. I currently have a > blank QWidget as a "placeholder" page of the tabwidget. > > If anyone can help me with this, it would be greatly appreciated. > > Thanks Hi, not 100% sure what you are after, but perhaps a standard tabWidget, with a customised Scrollarea forming the panel is one way? from PyQt4 import QtGui class TabPane(QtGui.QScrollArea): def __init__(self, parent=None): super(TabPane, self).__init__(parent) frame = QtGui.QFrame(self) frame.setFixedSize(300,200) self.setWidget(frame) self.layout = QtGui.QVBoxLayout(frame) def addDock(self, title): dw = QtGui.QDockWidget(title, self) self.layout.addWidget(dw) if __name__ == "__main__": app = QtGui.QApplication([]) tab_widget = QtGui.QTabWidget() for heading in ["Properties", "Schedule", "Pricelist"]: pane = TabPane() pane.addDock("Hello World") pane.addDock("Hello Galaxy") pane.addDock("Hello Universe") tab_widget.addTab(pane , heading) tab_widget.show() app.exec_() From dg1sbg at googlemail.com Mon May 24 05:55:46 2010 From: dg1sbg at googlemail.com (Frank GOENNINGER) Date: Mon, 24 May 2010 11:55:46 +0200 Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' References: Message-ID: Simon Brunning writes: > On 23 May 2010 14:46, Frank GOENNINGER wrote: >> Traceback (most recent call last): >> ?File "/.../src/pib/logging.py", line 37, in >> ? ?main() > > Here's a clue - looks like your own module is called logging. That's > what's getting imported by your import. Try naming your module > something else, and you should be golden. Yep. That was it. Thanks !! Cheers Frank From dg1sbg at googlemail.com Mon May 24 06:00:46 2010 From: dg1sbg at googlemail.com (Frank GOENNINGER) Date: Mon, 24 May 2010 12:00:46 +0200 Subject: logging: AttributeError: 'module' object has no attribute 'getLogger' References: Message-ID: Philip Semanchuk writes: > On May 23, 2010, at 9:46 AM, Frank GOENNINGER wrote: >> >> I double checked and yes, getLogger is there. Why is the interpreter >> asking for an "attribute" here ? Any hints on what I am doing wrong ? > > > Short answer: Change the name of src/pib/logging.py to something else. Done. > Long answer: When Python hits the line "import logging", it first > looks in the current directory and imports logging.py, which in this > case is the file it's already executing. It never finds the standard > library's logging module. > > One way you could have figured this out would be to add this as the > first line of main(): > print dir(logging) > > That would have told you what Python thought the logging module looked > like, and would have perhaps recognized it as your own. Thanks - learned a lot from your post. > > Cheers > Philip Cheers Frank From avinash.magar at gmail.com Mon May 24 07:33:37 2010 From: avinash.magar at gmail.com (adm) Date: Mon, 24 May 2010 04:33:37 -0700 (PDT) Subject: launching vi/vim from console Message-ID: <24fdad90-8c7f-412f-bb4b-23bb6592c858@a16g2000prg.googlegroups.com> I am newbie to python. Is there a way to launch vi/vim or any other editor from python console? I find editing in console very limiting. I can either have a console which launches vi and remembers it's content and then executes or invoke python interpreter from vim. Since I could not find anything I wrote this: http://python.pastebin.com/MFTHxuLe Please suggest if there is any better alternative for this. I tried googling for this but could not find anything interesting. Thanks, Adm From dirknbr at googlemail.com Mon May 24 07:56:40 2010 From: dirknbr at googlemail.com (dirknbr) Date: Mon, 24 May 2010 04:56:40 -0700 (PDT) Subject: Email in 2.6.4 Message-ID: I am trying to run from email.mime.text import MIMEText but I get an ImportError: No module named mime.text Since email was pre-installed how do I fix this? Dirk From jeanmichel at sequans.com Mon May 24 07:59:34 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 May 2010 13:59:34 +0200 Subject: launching vi/vim from console In-Reply-To: <24fdad90-8c7f-412f-bb4b-23bb6592c858@a16g2000prg.googlegroups.com> References: <24fdad90-8c7f-412f-bb4b-23bb6592c858@a16g2000prg.googlegroups.com> Message-ID: <4BFA6A26.4000708@sequans.com> adm wrote: > I am newbie to python. > Is there a way to launch vi/vim or any other editor from python > console? I find editing in console very limiting. I can either have a > console which launches vi and remembers it's content and then executes > or invoke python interpreter from vim. > > Since I could not find anything I wrote this: http://python.pastebin.com/MFTHxuLe > Please suggest if there is any better alternative for this. > I tried googling for this but could not find anything interesting. > > Thanks, > Adm > import os os.system.('vi') or you can start an ipython shell and start vi using !vi From steve at REMOVE-THIS-cybersource.com.au Mon May 24 08:13:59 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 May 2010 12:13:59 GMT Subject: Can upper() or lower() ever change the length of a string? Message-ID: <4bfa6d87$0$27861$c3e8da3@news.astraweb.com> Do unicode.lower() or unicode.upper() ever change the length of the string? The Unicode standard allows for case conversions that change length, e.g. sharp-S in German should convert to SS: http://unicode.org/faq/casemap_charprop.html#6 but I see that Python doesn't do that: >>> s = "Pa?stra?e" >>> s.upper() 'PA?STRA?E' The more I think about this, the more I think that upper/lower/title case conversions should change length (at least sometimes) and if Python doesn't do so, that's a bug. Any thoughts? -- Steven From dickinsm at gmail.com Mon May 24 08:20:18 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 24 May 2010 05:20:18 -0700 (PDT) Subject: Can upper() or lower() ever change the length of a string? References: <4bfa6d87$0$27861$c3e8da3@news.astraweb.com> Message-ID: On May 24, 1:13?pm, Steven D'Aprano wrote: > Do unicode.lower() or unicode.upper() ever change the length of the > string? >From looking at the source, in particular the fixupper and fixlower functions in Objects/unicode.c [1], it looks like not: they do a simple character-by-character replacement. [1] http://svn.python.org/view/python/trunk/Objects/unicodeobject.c?view=markup -- Mark From avinash.magar at gmail.com Mon May 24 08:31:58 2010 From: avinash.magar at gmail.com (adm) Date: Mon, 24 May 2010 05:31:58 -0700 (PDT) Subject: launching vi/vim from console References: <24fdad90-8c7f-412f-bb4b-23bb6592c858@a16g2000prg.googlegroups.com> Message-ID: <8e0c42d8-ad52-42ea-b091-0d13cd2003f7@g1g2000pro.googlegroups.com> On May 24, 4:59?pm, Jean-Michel Pichavant wrote: > adm wrote: > > I am newbie to python. > > Is there a way to launch vi/vim or any other editor from python > > console? I find editing in console very limiting. I can either have a > > console which launches vi and remembers it's content and then executes > > or invoke python interpreter from vim. > > > Since I could not find anything I wrote this:http://python.pastebin.com/MFTHxuLe > > Please suggest if there is any better alternative for this. > > I tried googling for this but could not find anything interesting. > > > Thanks, > > Adm > > import os > os.system.('vi') > > or you can start an ipython shell > ?and start vi using > !vi Thanks. I wanted something like ipython. I will give it a try. From dickinsm at gmail.com Mon May 24 08:44:21 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 24 May 2010 05:44:21 -0700 (PDT) Subject: Can upper() or lower() ever change the length of a string? References: <4bfa6d87$0$27861$c3e8da3@news.astraweb.com> Message-ID: <32fa918a-0d5a-4a4b-b0cb-d69b4ad33ab9@y21g2000vba.googlegroups.com> On May 24, 1:13?pm, Steven D'Aprano wrote: > Do unicode.lower() or unicode.upper() ever change the length of the > string? > > The Unicode standard allows for case conversions that change length, e.g. > sharp-S in German should convert to SS: > > http://unicode.org/faq/casemap_charprop.html#6 > > but I see that Python doesn't do that: > > >>> s = "Pa?stra?e" > >>> s.upper() > > 'PA?STRA?E' > > The more I think about this, the more I think that upper/lower/title case > conversions should change length (at least sometimes) and if Python > doesn't do so, that's a bug. Any thoughts? Digging a bit deeper, it looks like these methods are using the Simple_{Upper,Lower,Title}case_Mapping functions described at http://www.unicode.org/Public/5.1.0/ucd/UCD.html fields 12, 13 and 14 of the unicode data; you can see this in the source in Tools/unicode/ makeunicodedata.py, which is the Python code that generates the database of unicode properties. It contains code like: if record[12]: upper = int(record[12], 16) else: upper = char if record[13]: lower = int(record[13], 16) else: lower = char if record[14]: title = int(record[14], 16) ... and so on. I agree that it might be desirable for these operations to product the multicharacter equivalents. That idea looks like a tough sell, though: apart from backwards compatibility concerns (which could probably be worked around somehow), it looks as though it would require significant effort to implement. -- Mark From jeanmichel at sequans.com Mon May 24 09:19:33 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 May 2010 15:19:33 +0200 Subject: Email in 2.6.4 In-Reply-To: References: Message-ID: <4BFA7CE5.60000@sequans.com> dirknbr wrote: > I am trying to run > > from email.mime.text import MIMEText > > but I get an > > ImportError: No module named mime.text > > Since email was pre-installed how do I fix this? > > Dirk > Did you make sure you didn't hide the standard email module by one of your own. Check print email.__file__ /usr/lib/python2.5/email/__init__.pyc If the path is correct, you may want to look in the code, or if anything has changed in 2.6, I guess it is documented somewhere. JM From eknath.iyer at gmail.com Mon May 24 09:43:26 2010 From: eknath.iyer at gmail.com (Eknath Venkataramani) Date: Mon, 24 May 2010 19:13:26 +0530 Subject: extracting unicode text from pdfs Message-ID: I have around 45 pdfs to convert into raw text containing text in _HINDI_ . When I use the xpdf package, the generated text is very weird, so I'd like to write a program which would convert the pdf text into Unicode text as it is. The fonts used in the pdfs: name type emb sub uni object ID ------------------------------------ ----------------- --- --- --- --------- APKAPP+Usha-Bold Type 1C yes yes yes 72 0 APKBBB+Agenda-Light Type 1C yes yes yes 77 0 APKBGF+Usha Type 1C yes yes yes 41 0 APKBKJ+Agenda-Medium Type 1C yes yes yes 46 0 APKBON+Agenda-Bold Type 1C yes yes yes 49 0 For eg. in the pdf: ???? ??????? ?? when I use pdftotext, I get some very weird symbols: '... .......' while i'd like '???? ??????? ??' to be the output -- Eknath Venkataramani -------------- next part -------------- An HTML attachment was scrubbed... URL: From dirknbr at googlemail.com Mon May 24 09:59:24 2010 From: dirknbr at googlemail.com (dirknbr) Date: Mon, 24 May 2010 06:59:24 -0700 (PDT) Subject: Email in 2.6.4 References: Message-ID: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> I have now easy_installled email and I still get errors. It doesn't error on 'import email' but does on call to MimeText. import email msg = MIMEText('test') NameError: name 'MIMEText' is not defined What should I do? From python at rcn.com Mon May 24 10:14:43 2010 From: python at rcn.com (Raymond Hettinger) Date: Mon, 24 May 2010 07:14:43 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: On May 19, 12:58?pm, superpollo wrote: > ... how many positive integers less than n have digits that sum up to m: > > In [197]: def prttn(m, n): > ? ? ?tot = 0 > ? ? ?for i in range(n): > ? ? ? ? ?s = str(i) > ? ? ? ? ?sum = 0 > ? ? ? ? ?for j in range(len(s)): > ? ? ? ? ? ? ?sum += int(s[j]) > ? ? ? ? ?if sum == m: > ? ? ? ? ? ? ?tot += 1 > ? ? ?return tot > ? ? .....: > > In [207]: prttn(25, 10000) > Out[207]: 348 > > any suggestion for pythonizin' it? Your code is readable and does the job just fine. Not sure it is an improvement to reroll it into a one-liner: def prttn(m, n): return sum(m == sum(map(int, str(x))) for x in range(n)) >>> prttn(25, 10000) 348 Some people find the functional style easier to verify because of fewer auxilliary variables and each step is testable independently. The m==sum() part is not very transparent because it relies on True==1, so it's only readable if it becomes a common idiom (which it could when you're answering questions of the form "how many numbers have property x"). If speed is important, the global lookups can be localized: def prttn(m, n, map=itertools.imap, int=int, str=str, range=range): return sum(m == sum(map(int, str(x))) for x in range(n)) Raymond From simon at brunningonline.net Mon May 24 10:21:56 2010 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 24 May 2010 15:21:56 +0100 Subject: Email in 2.6.4 In-Reply-To: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> References: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> Message-ID: On 24 May 2010 14:59:24 UTC+1, dirknbr wrote: > It doesn't error on 'import email' but does on call to MimeText. > > import email > msg = MIMEText('test') > > NameError: name 'MIMEText' is not defined Here you want: msg = email.MIMEText('test') -- Cheers, Simon B. From dhananjay.nene at gmail.com Mon May 24 10:21:57 2010 From: dhananjay.nene at gmail.com (Dhananjay Nene) Date: Mon, 24 May 2010 19:51:57 +0530 Subject: [BangPypers] extracting unicode text from pdfs In-Reply-To: References: Message-ID: You may want to try out pdfminer. Its very similar to xpdf in structure and should give you the parsed data into unicode directly. On Mon, May 24, 2010 at 7:13 PM, Eknath Venkataramani wrote: > I have around 45 pdfs to convert into raw text containing text in _HINDI_ . > When I use the xpdf package, the generated text is very weird, so I'd like > to write a program which would convert the pdf text into Unicode text as it > is. > > The fonts used in the pdfs: > name type emb sub uni object > ID > ------------------------------------ ----------------- --- --- --- > --------- > APKAPP+Usha-Bold Type 1C yes yes yes 72 > 0 > APKBBB+Agenda-Light Type 1C yes yes yes 77 > 0 > APKBGF+Usha Type 1C yes yes yes 41 > 0 > APKBKJ+Agenda-Medium Type 1C yes yes yes 46 > 0 > APKBON+Agenda-Bold Type 1C yes yes yes 49 > 0 > > For eg. in the pdf: ???? ??????? ?? > when I use pdftotext, I get some very weird symbols: '... > .......' > while i'd like '???? ??????? ??' to be the output > > > -- > Eknath Venkataramani > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > http://mail.python.org/mailman/listinfo/bangpypers > -- -------------------------------------------------------- blog: http://blog.dhananjaynene.com twitter: http://twitter.com/dnene -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Mon May 24 10:22:00 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 May 2010 16:22:00 +0200 Subject: Email in 2.6.4 In-Reply-To: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> References: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> Message-ID: <4BFA8B88.4050108@sequans.com> dirknbr wrote: > I have now easy_installled email and I still get errors. > > It doesn't error on 'import email' but does on call to MimeText. > > import email > msg = MIMEText('test') > > NameError: name 'MIMEText' is not defined > > What should I do? > Using easy_install will not prevent the standard lib to be shadowed by another (user) module. did you print email.__file__ to verify the path ? Can you show us the output ? To give you an example, on a lenny python 2.5 distrib, the MIMEText class is in /usr/lib/python2.5/email/mime/text.py JM From breamoreboy at yahoo.co.uk Mon May 24 10:35:39 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 May 2010 15:35:39 +0100 Subject: Email in 2.6.4 In-Reply-To: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> References: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> Message-ID: On 24/05/2010 14:59, dirknbr wrote: > I have now easy_installled email and I still get errors. I've done this as well, but don't see why I have to. Is this a documentation bug, an installation bug or what? > > It doesn't error on 'import email' but does on call to MimeText. > > import email > msg = MIMEText('test') > > NameError: name 'MIMEText' is not defined > > What should I do? Give the fully qualified name i.e. email.mime.text.MIMEText. Regards. Mark Lawrence. From dirknbr at googlemail.com Mon May 24 10:36:59 2010 From: dirknbr at googlemail.com (Dirk Nachbar) Date: Mon, 24 May 2010 15:36:59 +0100 Subject: Email in 2.6.4 In-Reply-To: <4BFA8B88.4050108@sequans.com> References: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> <4BFA8B88.4050108@sequans.com> Message-ID: Sorry guys, I had named my file email.py and hence the error. On 24 May 2010 15:22, Jean-Michel Pichavant wrote: > dirknbr wrote: > >> I have now easy_installled email and I still get errors. >> >> >> It doesn't error on 'import email' but does on call to MimeText. >> >> import email >> msg = MIMEText('test') >> >> NameError: name 'MIMEText' is not defined >> >> What should I do? >> >> > Using easy_install will not prevent the standard lib to be shadowed by > another (user) module. > > did you print email.__file__ to verify the path ? > Can you show us the output ? > > To give you an example, on a lenny python 2.5 distrib, the MIMEText class > is in > /usr/lib/python2.5/email/mime/text.py > > JM > -- http://dirknbr.googlepages.com http://maximum-likely.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Mon May 24 10:42:06 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 24 May 2010 15:42:06 +0100 Subject: Can upper() or lower() ever change the length of a string? In-Reply-To: <32fa918a-0d5a-4a4b-b0cb-d69b4ad33ab9@y21g2000vba.googlegroups.com> References: <4bfa6d87$0$27861$c3e8da3@news.astraweb.com> <32fa918a-0d5a-4a4b-b0cb-d69b4ad33ab9@y21g2000vba.googlegroups.com> Message-ID: <4BFA903E.7060401@mrabarnett.plus.com> Mark Dickinson wrote: > On May 24, 1:13 pm, Steven D'Aprano cybersource.com.au> wrote: >> Do unicode.lower() or unicode.upper() ever change the length of the >> string? >> >> The Unicode standard allows for case conversions that change length, e.g. >> sharp-S in German should convert to SS: >> >> http://unicode.org/faq/casemap_charprop.html#6 >> >> but I see that Python doesn't do that: >> >>>>> s = "Pa?stra?e" >>>>> s.upper() >> 'PA?STRA?E' >> >> The more I think about this, the more I think that upper/lower/title case >> conversions should change length (at least sometimes) and if Python >> doesn't do so, that's a bug. Any thoughts? > > Digging a bit deeper, it looks like these methods are using the > Simple_{Upper,Lower,Title}case_Mapping functions described at > http://www.unicode.org/Public/5.1.0/ucd/UCD.html fields 12, 13 and 14 > of the unicode data; you can see this in the source in Tools/unicode/ > makeunicodedata.py, which is the Python code that generates the > database of unicode properties. It contains code like: > > if record[12]: > upper = int(record[12], 16) > else: > upper = char > if record[13]: > lower = int(record[13], 16) > else: > lower = char > if record[14]: > title = int(record[14], 16) > > ... and so on. > > I agree that it might be desirable for these operations to product the > multicharacter equivalents. That idea looks like a tough sell, > though: apart from backwards compatibility concerns (which could > probably be worked around somehow), it looks as though it would > require significant effort to implement. > If we were to make such a change, I think we should also cater for locale-specific case changes (passing the locale to 'upper', 'lower' and 'title'). For example, normally "i".upper() returns "I", but in Turkish "i".upper() should return "?" (the uppercase version of lowercase dotted i is uppercase dotted I). From jeanmichel at sequans.com Mon May 24 10:50:09 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 May 2010 16:50:09 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4BFA9221.3080905@sequans.com> Jerry Hill wrote: > On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: > >> ... how many positive integers less than n have digits that sum up to m: >> > ... > >> any suggestion for pythonizin' it? >> > > This is how I would do it: > > def prttn(m, n): > """How many positive integers less than n have digits that sum up to m""" > total = 0 > for testval in range(n): > sumofdigits = sum(int(char) for char in str(testval)) > if sumofdigits == m: > total += 1 > return total > > I added a docstring to the function, saying what it does, and what the > arguments are supposed to represent. I also moved the > convert-to-string-and-sum-the-digits logic into a single generator > expression that's passed to the builtin sum function. Oh, and I tried > to use slightly more expressive variable names. > > my favorite solutio nso far. @ OP What means prttn ? is it any Dutch word :D ? m & n are also very poors argument names. I will be difficult to name properly the function, as it is doing something ... I don't find the word, something like un-intuitive. Sounds like homework. def how_many_positive_integers_less_than_n_have_digits_that_sum_up_to_m(m, n) :o) JM PS : read http://tottinge.blogsome.com/meaningfulnames/ From landimatte at gmail.com Mon May 24 10:51:16 2010 From: landimatte at gmail.com (Matteo Landi) Date: Mon, 24 May 2010 16:51:16 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: What about avoiding the string conversion and use mod/div operations in order to create a list of digits for a number? Now that you have the sequences it's easy to count which sums up to m. On Mon, May 24, 2010 at 4:14 PM, Raymond Hettinger wrote: > On May 19, 12:58 pm, superpollo wrote: >> ... how many positive integers less than n have digits that sum up to m: >> >> In [197]: def prttn(m, n): >> tot = 0 >> for i in range(n): >> s = str(i) >> sum = 0 >> for j in range(len(s)): >> sum += int(s[j]) >> if sum == m: >> tot += 1 >> return tot >> .....: >> >> In [207]: prttn(25, 10000) >> Out[207]: 348 >> >> any suggestion for pythonizin' it? > > Your code is readable and does the job just fine. > Not sure it is an improvement to reroll it into a one-liner: > > def prttn(m, n): > return sum(m == sum(map(int, str(x))) for x in range(n)) >>>> prttn(25, 10000) > 348 > > Some people find the functional style easier to verify because of > fewer auxilliary variables and each step is testable independently. > The m==sum() part is not very transparent because it relies on > True==1, so it's only readable if it becomes a common idiom (which it > could when you're answering questions of the form "how many numbers > have property x"). > > If speed is important, the global lookups can be localized: > > def prttn(m, n, map=itertools.imap, int=int, str=str, range=range): > return sum(m == sum(map(int, str(x))) for x in range(n)) > > Raymond > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Matteo Landi http://www.matteolandi.net/ From jeanmichel at sequans.com Mon May 24 10:55:41 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 May 2010 16:55:41 +0200 Subject: Email in 2.6.4 In-Reply-To: References: <2ddd8e93-6b72-459b-ae69-e79ef3cc3dba@m21g2000vbr.googlegroups.com> <4BFA8B88.4050108@sequans.com> Message-ID: <4BFA936D.2060902@sequans.com> Dirk Nachbar wrote: > Sorry guys, I had named my file email.py and hence the error. > > > > On 24 May 2010 15:22, Jean-Michel Pichavant > wrote: > > dirknbr wrote: > > I have now easy_installled email and I still get errors. > > > It doesn't error on 'import email' but does on call to MimeText. > > import email > msg = MIMEText('test') > > NameError: name 'MIMEText' is not defined > > What should I do? > > > Using easy_install will not prevent the standard lib to be > shadowed by another (user) module. > > did you print email.__file__ to verify the path ? > Can you show us the output ? > > To give you an example, on a lenny python 2.5 distrib, the > MIMEText class is in > /usr/lib/python2.5/email/mime/text.py > > JM > > > > Classic error, you're not the first one, and my guess is that you won't be the last. JM From anand.shashwat at gmail.com Mon May 24 10:59:48 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Mon, 24 May 2010 20:29:48 +0530 Subject: launching vi/vim from console In-Reply-To: <8e0c42d8-ad52-42ea-b091-0d13cd2003f7@g1g2000pro.googlegroups.com> References: <24fdad90-8c7f-412f-bb4b-23bb6592c858@a16g2000prg.googlegroups.com> <8e0c42d8-ad52-42ea-b091-0d13cd2003f7@g1g2000pro.googlegroups.com> Message-ID: or in a reverse way you can open vim and use ':shell' followed by python. I prefer it that way generally On Mon, May 24, 2010 at 6:01 PM, adm wrote: > On May 24, 4:59 pm, Jean-Michel Pichavant > wrote: > > adm wrote: > > > I am newbie to python. > > > Is there a way to launch vi/vim or any other editor from python > > > console? I find editing in console very limiting. I can either have a > > > console which launches vi and remembers it's content and then executes > > > or invoke python interpreter from vim. > > > > > Since I could not find anything I wrote this: > http://python.pastebin.com/MFTHxuLe > > > Please suggest if there is any better alternative for this. > > > I tried googling for this but could not find anything interesting. > > > > > Thanks, > > > Adm > > > > import os > > os.system.('vi') > > > > or you can start an ipython shell > > and start vi using > > !vi > > Thanks. I wanted something like ipython. > I will give it a try. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nathan.alexander.rice at gmail.com Mon May 24 12:56:44 2010 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Mon, 24 May 2010 12:56:44 -0400 Subject: Most reliable/pythonic way to tell if an instance comes from a class implemented in C/etc? Message-ID: I'm trying to do some fairly deep introspection and instrumentation of instances and classes at runtime, and in order for everything to be properly behaved I need to have radically different behavior in the event that the thing passed to me is a wrapped class/instance. Is there a really good way, given an instance of a class, to determine if it is wrapped or native? Currently I check to see if it has __slots__ then try to setattr a dummy variable but I imagine there is probably a cleaner way. Nathan -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Mon May 24 13:37:58 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 24 May 2010 13:37:58 -0400 Subject: A Quick MySQL Question Message-ID: Hi; I have the following: # sql = 'alter table %s alter column %s set default "%%s";' % (store, col) # cursor.execute(sql, colValue) cursor.execute('alter table %s alter column %s set default "%s";' % (store, col, colValue)) database.commit() Now I don't like that third line, so I tried the commented out lines, but I got an MySQLdb.OperationalError that the suggested default value could not be inserted. However, when I printed it out and tried to insert directly, no problem, and the 3rd line works fine. What gives? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon May 24 14:01:59 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 May 2010 14:01:59 -0400 Subject: Can upper() or lower() ever change the length of a string? In-Reply-To: <4BFA903E.7060401@mrabarnett.plus.com> References: <4bfa6d87$0$27861$c3e8da3@news.astraweb.com> <32fa918a-0d5a-4a4b-b0cb-d69b4ad33ab9@y21g2000vba.googlegroups.com> <4BFA903E.7060401@mrabarnett.plus.com> Message-ID: On 5/24/2010 10:42 AM, MRAB wrote: > Mark Dickinson wrote: >> Digging a bit deeper, it looks like these methods are using the >> Simple_{Upper,Lower,Title}case_Mapping functions described at >> http://www.unicode.org/Public/5.1.0/ucd/UCD.html fields 12, 13 and 14 >> of the unicode data; you can see this in the source in Tools/unicode/ >> makeunicodedata.py, which is the Python code that generates the >> database of unicode properties. It contains code like: >> >> if record[12]: >> upper = int(record[12], 16) >> else: >> upper = char >> if record[13]: >> lower = int(record[13], 16) >> else: >> lower = char >> if record[14]: >> title = int(record[14], 16) >> >> ... and so on. >> >> I agree that it might be desirable for these operations to product the >> multicharacter equivalents. That idea looks like a tough sell, >> though: apart from backwards compatibility concerns (which could >> probably be worked around somehow), it looks as though it would >> require significant effort to implement. >> > If we were to make such a change, I think we should also cater for > locale-specific case changes (passing the locale to 'upper', 'lower' and > 'title'). > > For example, normally "i".upper() returns "I", but in Turkish > "i".upper() should return "?" (the uppercase version of lowercase dotted > i is uppercase dotted I). Given that the current (siimple) functions implement standard-defined functions, I think any change should be to *add* new 'complex-case-change' functions. Terry Jan Reedy From tjreedy at udel.edu Mon May 24 14:30:18 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 May 2010 14:30:18 -0400 Subject: Most reliable/pythonic way to tell if an instance comes from a class implemented in C/etc? In-Reply-To: References: Message-ID: On 5/24/2010 12:56 PM, Nathan Rice wrote: > I'm trying to do some fairly deep introspection and instrumentation of > instances and classes at runtime, and in order for everything to be > properly behaved I need to have radically different behavior in the > event that the thing passed to me is a wrapped class/instance. Is there > a really good way, given an instance of a class, to determine if it is > wrapped or native? Currently I check to see if it has __slots__ then > try to setattr a dummy variable but I imagine there is probably a > cleaner way. I am not sure what you mean by 'wrapped'. Your subject line says something different. In any case, is your universe *all* Python objects or some subset? Builtin classes, named or not, do not have dotted names >>> 1 .__class__ >>> class C: pass I believe all others do, including C-coded extension classes. >>> C().__class__ tjr From 3006nol at gmail.com Mon May 24 14:50:03 2010 From: 3006nol at gmail.com (narcissus) Date: Mon, 24 May 2010 11:50:03 -0700 (PDT) Subject: Chatroom Message-ID: Hello , I want to create a program that is one chatroom and everyone has this program can Enter into that chatroom. how can i do this? and i want gui for it too (GTK) From jessemcdonnell at verizon.net Mon May 24 14:52:39 2010 From: jessemcdonnell at verizon.net (Jesse McDonnell) Date: Mon, 24 May 2010 13:52:39 -0500 (CDT) Subject: TypeError: _new_() takes exactly 3 arguments (2 given) - what does it mean? Message-ID: <2061601704.535865.1274727159418.JavaMail.root@vms244.mailsrvcs.net> An HTML attachment was scrubbed... URL: From martin.hellwig at dcuktec.org Mon May 24 14:59:45 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 24 May 2010 19:59:45 +0100 Subject: Chatroom In-Reply-To: References: Message-ID: On 05/24/10 19:50, narcissus wrote: > Hello , I want to create a program that is one chatroom and everyone > has this program can Enter into that chatroom. how can i do this? > > and i want gui for it too (GTK) What have you tried so far? -- mph From darragh.ssa at gmail.com Mon May 24 15:04:44 2010 From: darragh.ssa at gmail.com (Kruptein) Date: Mon, 24 May 2010 12:04:44 -0700 (PDT) Subject: D-CM IDE Message-ID: <1ad60739-6e39-4883-bef8-4005dbe80373@z17g2000vbd.googlegroups.com> I'm developing an "IDE" in python (wxPython toolkit). it's an application that combines a file-manager,text-editor,sql-manager,ftp- manager and more in one simple to use GUI. I'm releasing a new version soon and I hoped that there were some folks in here that would like to test if it worked well.. It is a linux program and can be found here: https://launchpad.net/d-cm the windows version (is some releases behind the linux version) can be found here: https://launchpad.net/d-cm-win From duncan.booth at invalid.invalid Mon May 24 16:12:36 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 May 2010 20:12:36 GMT Subject: Most reliable/pythonic way to tell if an instance comes from a class implemented in C/etc? References: Message-ID: Terry Reedy wrote: > Builtin classes, named or not, do not have dotted names > > >>> 1 .__class__ > > >>> class C: pass > > I believe all others do, including C-coded extension classes. > > >>> C().__class__ > > Not quite all. Classes created by calling the type constructor directly don't have to follow that rule: >>> C = type('Fred', (object,), {}) >>> C.__name__ 'Fred' From subhakolkata1234 at gmail.com Mon May 24 16:15:01 2010 From: subhakolkata1234 at gmail.com (joy99) Date: Mon, 24 May 2010 13:15:01 -0700 (PDT) Subject: Question on Python Function Message-ID: Dear Group, I have a small question on function. If I write two functions like the following: IDLE 2.6.5 >>> def function1(n): element1=5 element2=6 add=element1+element2 print "PRINT THE ADDITION",add >>> def function2(n): element3=7 element4=22 mult=element3*element4 print "PRINT THE MULTIPLICATION",mult Can I now write a third function where the above two functions can be passed as argument or parameter? Best Regards, Subhabrata. NB: As I copied the code from IDLE to MS-Word befor posting here, codes may have slight indentation errors. From utente at esempio.net Mon May 24 16:34:18 2010 From: utente at esempio.net (superpollo) Date: Mon, 24 May 2010 22:34:18 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> Jean-Michel Pichavant ha scritto: > Jerry Hill wrote: >> On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: >> >>> ... how many positive integers less than n have digits that sum up to m: >>> >> ... >> >>> any suggestion for pythonizin' it? >>> >> >> This is how I would do it: >> >> def prttn(m, n): >> """How many positive integers less than n have digits that sum up >> to m""" >> total = 0 >> for testval in range(n): >> sumofdigits = sum(int(char) for char in str(testval)) >> if sumofdigits == m: >> total += 1 >> return total >> >> I added a docstring to the function, saying what it does, and what the >> arguments are supposed to represent. I also moved the >> convert-to-string-and-sum-the-digits logic into a single generator >> expression that's passed to the builtin sum function. Oh, and I tried >> to use slightly more expressive variable names. >> >> > my favorite solutio nso far. > > @ OP > > What means prttn ? i already answered this downthreads... > something ... I don't find the word, something like un-intuitive. Sounds > like homework. it is not. From alister.ware at ntlworld.com Mon May 24 16:45:42 2010 From: alister.ware at ntlworld.com (Alister) Date: Mon, 24 May 2010 20:45:42 GMT Subject: Question on Python Function References: Message-ID: On Mon, 24 May 2010 13:15:01 -0700, joy99 wrote: > Dear Group, > > I have a small question on function. > > If I write two functions like the following: > > IDLE 2.6.5 >>>> def function1(n): > element1=5 > element2=6 > add=element1+element2 > print "PRINT THE ADDITION",add > > >>>> def function2(n): > element3=7 > element4=22 > mult=element3*element4 > print "PRINT THE MULTIPLICATION",mult > > Can I now write a third function where the above two functions can be > passed as argument or parameter? > > Best Regards, > Subhabrata. > > NB: As I copied the code from IDLE to MS-Word befor posting here, codes > may have slight indentation errors. I don't quite see the point of your functions as they do not use their parameters in any way, but you need to set a return value IDLE 2.6.5 >>> def function1(n): element1=5 element2=6 add=element1+element2 return add >>> def function2(n): element3=7 element4=22 mult=element3*element4 return mult >>> def function3(x,y): print "add= %s mult=%s" % (x , y) >>>function3(function1(1),funtcion2(2)) -- Your digestive system is your body's Fun House, whereby food goes on a long, dark, scary ride, taking all kinds of unexpected twists and turns, being attacked by vicious secretions along the way, and not knowing until the last minute whether it will be turned into a useful body part or ejected into the Dark Hole by Mister Sphincter. We Americans live in a nation where the medical-care system is second to none in the world, unless you count maybe 25 or 30 little scuzzball countries like Scotland that we could vaporize in seconds if we felt like it. -- Dave Barry, "Stay Fit & Healthy Until You're Dead" From vlastimil.brom at gmail.com Mon May 24 16:56:34 2010 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 24 May 2010 22:56:34 +0200 Subject: Question on Python Function In-Reply-To: References: Message-ID: 2010/5/24 joy99 : > > > Dear Group, > > I have a small question on function. > > If I write two functions like the following: > > IDLE 2.6.5 >>>> def function1(n): > ? ? ? ?element1=5 > ? ? ? ?element2=6 > ? ? ? ?add=element1+element2 > ? ? ? ?print "PRINT THE ADDITION",add > > >>>> def function2(n): > ? ? ? ?element3=7 > ? ? ? ?element4=22 > ? ? ? ?mult=element3*element4 > ? ? ? ?print "PRINT THE MULTIPLICATION",mult > > Can I now write a third function where the above two functions can be > passed as argument or parameter? > > Best Regards, > Subhabrata. > > NB: As I copied the code from IDLE to MS-Word befor posting here, > codes may have slight indentation errors. > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, while it is quite unclear to me, what you are trying to achieve (what are the passed n arguments supposed to do?), you can well pass an already defined function as an argument to another function; if you want to select a function for the needed operation, if can be e.g.: def compute(arg1, arg2, fn): fn(arg1, arg2) - supposing you don't want to "return" the result but just print it as your functions do; is it what you were after or did I miss something more complex? hth vbr From alister.ware at ntlworld.com Mon May 24 17:08:14 2010 From: alister.ware at ntlworld.com (Alister) Date: Mon, 24 May 2010 21:08:14 GMT Subject: Question on Python Function References: Message-ID: <2VBKn.101377$Lg1.29534@newsfe17.ams2> On Mon, 24 May 2010 22:56:34 +0200, Vlastimil Brom wrote: > 2010/5/24 joy99 : >> >> >> Dear Group, >> >> I have a small question on function. >> >> If I write two functions like the following: >> >> IDLE 2.6.5 >>>>> def function1(n): >> ? ? ? ?element1=5 >> ? ? ? ?element2=6 >> ? ? ? ?add=element1+element2 >> ? ? ? ?print "PRINT THE ADDITION",add >> >> >>>>> def function2(n): >> ? ? ? ?element3=7 >> ? ? ? ?element4=22 >> ? ? ? ?mult=element3*element4 >> ? ? ? ?print "PRINT THE MULTIPLICATION",mult >> >> Can I now write a third function where the above two functions can be >> passed as argument or parameter? >> >> Best Regards, >> Subhabrata. >> >> NB: As I copied the code from IDLE to MS-Word befor posting here, codes >> may have slight indentation errors. -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > Hi, > while it is quite unclear to me, what you are trying to achieve (what > are the passed n arguments supposed to do?), you can well pass an > already defined function as an argument to another function; if you want > to select a function for the needed operation, if can be e.g.: > > def compute(arg1, arg2, fn): > fn(arg1, arg2) > > - supposing you don't want to "return" the result but just print it as > your functions do; > is it what you were after or did I miss something more complex? > > hth > vbr I did not realise you could pass a function like this, I am sure it could lead to some interesting programming. I am still new to OOP & the light is only just starting to switch on. analysing your examples I now realise that all function parameters are Objects & EVERYTHING(well almost anyway) is an object. It just goes to show that even when you know 1 answer to the original question You can still learn by looking at others -- "And, of course, you have the commercials where savvy businesspeople Get Ahead by using their MacIntosh computers to create the ultimate American business product: a really sharp-looking report." -- Dave Barry From subhakolkata1234 at gmail.com Mon May 24 17:39:09 2010 From: subhakolkata1234 at gmail.com (joy99) Date: Mon, 24 May 2010 14:39:09 -0700 (PDT) Subject: Question on Python Function References: Message-ID: <6ae2891c-0e15-4852-a082-4b9d8cd6f3af@t34g2000prd.googlegroups.com> On May 25, 1:56?am, Vlastimil Brom wrote: > 2010/5/24 joy99 : > > > > > > > > > Dear Group, > > > I have a small question on function. > > > If I write two functions like the following: > > > IDLE 2.6.5 > >>>> def function1(n): > > ? ? ? ?element1=5 > > ? ? ? ?element2=6 > > ? ? ? ?add=element1+element2 > > ? ? ? ?print "PRINT THE ADDITION",add > > >>>> def function2(n): > > ? ? ? ?element3=7 > > ? ? ? ?element4=22 > > ? ? ? ?mult=element3*element4 > > ? ? ? ?print "PRINT THE MULTIPLICATION",mult > > > Can I now write a third function where the above two functions can be > > passed as argument or parameter? > > > Best Regards, > > Subhabrata. > > > NB: As I copied the code from IDLE to MS-Word befor posting here, > > codes may have slight indentation errors. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Hi, > while it is quite unclear to me, what you are trying to achieve (what > are the passed n arguments supposed to do?), you can well pass an > already defined function as an argument to another function; if you > want to select a function for the needed operation, if can be e.g.: > > def compute(arg1, arg2, fn): > ? ? fn(arg1, arg2) > > - supposing you don't want to "return" the result but just print it as > your functions do; > is it what you were after or did I miss something more complex? > > hth > ? vbr- Hide quoted text - > > - Show quoted text - Dear Vlastimil, You are right. Your approach will do to me. I was trying Python Doc either I do not know where to check, or I could not find. I am trying to work out. Numbers I can pass, I was checking the last example in Python Docs with "def cheeseshop(kind, *arguments, **keywords):" if that gives me any clue. If you can kindly try. Best Regards, Subhabrata. From subhakolkata1234 at gmail.com Mon May 24 18:08:48 2010 From: subhakolkata1234 at gmail.com (joy99) Date: Mon, 24 May 2010 15:08:48 -0700 (PDT) Subject: Question on Python Function References: Message-ID: On May 25, 1:56?am, Vlastimil Brom wrote: > 2010/5/24 joy99 : > > > > > > > > > Dear Group, > > > I have a small question on function. > > > If I write two functions like the following: > > > IDLE 2.6.5 > >>>> def function1(n): > > ? ? ? ?element1=5 > > ? ? ? ?element2=6 > > ? ? ? ?add=element1+element2 > > ? ? ? ?print "PRINT THE ADDITION",add > > >>>> def function2(n): > > ? ? ? ?element3=7 > > ? ? ? ?element4=22 > > ? ? ? ?mult=element3*element4 > > ? ? ? ?print "PRINT THE MULTIPLICATION",mult > > > Can I now write a third function where the above two functions can be > > passed as argument or parameter? > > > Best Regards, > > Subhabrata. > > > NB: As I copied the code from IDLE to MS-Word befor posting here, > > codes may have slight indentation errors. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Hi, > while it is quite unclear to me, what you are trying to achieve (what > are the passed n arguments supposed to do?), you can well pass an > already defined function as an argument to another function; if you > want to select a function for the needed operation, if can be e.g.: > > def compute(arg1, arg2, fn): > ? ? fn(arg1, arg2) > > - supposing you don't want to "return" the result but just print it as > your functions do; > is it what you were after or did I miss something more complex? > > hth > ? vbr- Hide quoted text - > > - Show quoted text - Dear Vlastimir, As pointed out by Alister, I can print the values of function1 and function2 with the help of another function3, but my target is to call the "add" value of function1 and "mult" value of function2 in a third function or the values and parameters of the third function in fourth function. While calling, I am looking not only to print, but to use them or manipulate them. I hope I am bit clear now. Best Regards, Subhabrata. From pavlovevidence at gmail.com Mon May 24 18:30:37 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 24 May 2010 15:30:37 -0700 (PDT) Subject: Most reliable/pythonic way to tell if an instance comes from a class implemented in C/etc? References: Message-ID: <20a5ca44-82b5-472d-8221-acbc86f7279f@g1g2000pro.googlegroups.com> [Following up to Terry Reedy's post since I don't see the original] On May 24, 11:30?am, Terry Reedy wrote: > On 5/24/2010 12:56 PM, Nathan Rice wrote: > > > I'm trying to do some fairly deep introspection and instrumentation of > > instances and classes at runtime, and in order for everything to be > > properly behaved I need to have radically different behavior in the > > event that the thing passed to me is a wrapped class/instance. ?Is there > > a really good way, given an instance of a class, to determine if it is > > wrapped or native? ?Currently I check to see if it has __slots__ then > > try to setattr a dummy variable but I imagine there is probably a > > cleaner way. There is no foolproof way, but the simplest and most reliable way is to check the __flags__ attribute to see if it's a heap type, which all Python new-style classes are and almost all C-defined types aren't: cls.__flags__ & 512 # Py_TPFLAGS_HEAPTYPE However, in Python 2.x, old-style classes aren't types and so don't have a __flags__ attribute, so to cover that case you should check if it's a classobj. isinstance(cls,types.ClassType) So a complete function would look something like this: def is_probably_python_class(cls): return isinstance(cls,types.ClassType) \ or (isinstance(cls,type) and cls.__flags__ & 512) It's not foolproof for a couple reasons: it's possible to define heap types in C, and it's possible to define a metatype that does things differently, but I would suppose these cases are rare. Incidentally, depending on your use case, you might find it helpful also to know whether a type is a base type (meaning that it can be subclassed). You can check that with cls.__flags__ & 1024. A complete list of flags is in the include file object.h. Note that, in order to be subclassable, a type defined in C has to behave like a Python class to a certain extent. Thus you can assume a little bit more about it. Carl Banks From ian.g.kelly at gmail.com Mon May 24 18:31:13 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 24 May 2010 16:31:13 -0600 Subject: Generator expressions vs. comprehensions Message-ID: Hi all, I just ran into an interesting but rather subtle little wart today. The following expressions are not functionally equivalent, even in Python 3: tuple(iterator.next() for i in xrange(n)) tuple([iterator.next() for i in xrange(n)]) In the first case, if iterator.next() raises a StopIteration, the exception is swallowed by the generator expression. The expression evaluates to a truncated tuple, and the StopIteration is not propagated. In the second case, the StopIteration exception is propagated as expected by the list comprehension. Set and dict comprehensions also behave this way in Python 3. Is this distinction generally known? The generator expression behavior is understandable since a generator would do the same thing, but I'm disappointed that the inconsistency exists and wasn't fixed in Python 3 when we had the chance. Cheers, Ian From pavlovevidence at gmail.com Mon May 24 18:47:32 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 24 May 2010 15:47:32 -0700 (PDT) Subject: Generator expressions vs. comprehensions References: Message-ID: On May 24, 3:31?pm, Ian Kelly wrote: > Hi all, > > I just ran into an interesting but rather subtle little wart today. > The following expressions are not functionally equivalent, even in > Python 3: > > tuple(iterator.next() for i in xrange(n)) > > tuple([iterator.next() for i in xrange(n)]) > > In the first case, if iterator.next() raises a StopIteration, the > exception is swallowed by the generator expression. ?The expression > evaluates to a truncated tuple, and the StopIteration is not > propagated. > > In the second case, the StopIteration exception is propagated as > expected by the list comprehension. ?Set and dict comprehensions also > behave this way in Python 3. > > Is this distinction generally known? ?The generator expression > behavior is understandable since a generator would do the same thing, > but I'm disappointed that the inconsistency exists and wasn't fixed in > Python 3 when we had the chance. As a general rule you shouldn't call the next() method/function without arranging to catch StopIteration, unless you know the iterator will never raise StopIteration (such as it if it itertools.count()). The problem is that if a StopIteration "leaks", as it does with the generator examples, another iterator further up the stack might catch it and exit. The situation here is known. It can't be corrected, even in Python 3, without modifying iterator protocol to tie StopIteration to a specific iterator. This is possible and might be worth it to avoid hard-to- diagnose bugs but it would complicate iterator protocol, which becomes less useful as it becomes more complex. Carl Banks From pengyu.ut at gmail.com Mon May 24 18:52:13 2010 From: pengyu.ut at gmail.com (Peng Yu) Date: Mon, 24 May 2010 17:52:13 -0500 Subject: python command line manual Message-ID: I mainly check online python manual. But I feel that it would be nice if there is command line manual available (just like perl command line manual). Could you please let me know if such command line manual available? -- Regards, Peng From clp2 at rebertia.com Mon May 24 19:10:47 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 24 May 2010 16:10:47 -0700 Subject: python command line manual In-Reply-To: References: Message-ID: On Mon, May 24, 2010 at 3:52 PM, Peng Yu wrote: > I mainly check online python manual. But I feel that it would be nice > if there is command line manual available (just like perl command line > manual). Could you please let me know if such command line manual > available? 98% sure that there isn't. You could instead use a text-based console web browser such as lynx to view the online docs to much the same effect though. Cheers, Chris From python at bdurham.com Mon May 24 19:34:59 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 24 May 2010 19:34:59 -0400 Subject: Internationalizing an application via Babel Message-ID: <1274744099.30953.1376705173@webmail.messagingengine.com> I'm evaluating Babel 0.9.5 [1] under Windows (Python 2.6) and have the following questions that I haven't been able to solve through reading the documentation or googling. 1. I would like to use an _ like abbreviation for ungettext. Is there a concencus on whether one should use n_ or N_ for this? n_ does not appear to work. Babel does not extract text. N_ appears to partially work. Babel extracts text like it does for gettext, but does not format for ngettext (missing plural argument and msgstr[ n ].) 2. Is there a way to set the initial msgstr fields like the following when creating a POT file? I suspect there may be a way to do this via Babel cfg files, but I've been unable to find documentation on the Babel cfg file format. "Project-Id-Version: PROJECT VERSION\n" "Language-Team: en_US \n" 3. Is there a way to preserve 'obsolete' msgid/msgstr's in our PO files? When I use the Babel update command, newly created obsolete strings are marked with #~ prefixes, but existing obsolete message strings get deleted. Thanks, Malcolm [1] http://babel.edgewall.org/ From robin at alldunn.com Mon May 24 19:38:45 2010 From: robin at alldunn.com (Robin Dunn) Date: Mon, 24 May 2010 16:38:45 -0700 Subject: wxPython 2.8.11.0 release Message-ID: <4BFB0E05.1090101@alldunn.com> Announcing ---------- The 2.8.11.0 release of wxPython is now available for download at http://wxpython.org/download.php. This release adds Python 2.7 builds, PySlices, new pubsub implementation, lots of updates to AGW, and lots of bugs fixed. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. Source code is available as a tarball and a source RPM, as well as binaries for Python 2.5, 2.6 and 2.7, for Windows and Mac, as well some packages for various Linux distributions. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit and 64-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+. In most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.11.0 ------------------- Lots of bug fixes in both wxWidgets and wxPython. Added the context manager protocol methods to some wx classes so they can be used with the new Python 'with' statement. (The with statement is always available starting in Python 2.6, and can also be used in Python 2.5 with a __future__ import statement.) There are several wx classes where this is a natural fit, such as wx.BusyInfo. The __enter__ and __exit__ methods have also been added to wx.Dialog where it will do the dialog.Destroy() call for you. This means that you can use code like this:: with MyDialog(self, foo, bar) as dlg: if dlg.ShowModal() == wx.ID_OK: # do something with dlg values The list of wx classes that can now be used as context managers is: * wx.Dialog * wx.BusyInfo * wx.BusyCursor * wx.WindowDisabler * wx.LogNull * wx.DCTextColourChanger * wx.DCPenChanger * wx.DCBrushChanger * wx.DCClipper A new class has been added that is also a context manager, called wx.FrozenWindow. It will freeze the window passed to it upon entry to the context, and will thaw the window upon exit from the context. Applied the final version of patch #10959 to the PyCrust code. It adds many enhancements to the Py suite, inlcuding the ability to edit blocks of code (called slices) as a whole before executing them, and also the ability to execute some simple shell commands. Replaced the wx.lib.pubsub module with the new pubsub package from http://pubsub.sf.net. By default it is backwards compatible with the old pubsub module, but it also has a more advanced API available that can be switched on at import time. See the pubsub web site for more details. The wx.Effects class is deprecated. Added Python 2.7 builds for Windows and Mac. Added Debian package builds for Ubuntu 9.10 and 10.4. Many fixes and enhancements for the wx.lib.agw pacakge, including the addition of pybusyinfo, ribbon, ultimatelistctrl and zoombar. -- Robin Dunn Software Craftsman http://wxPython.org From solipsis at pitrou.net Mon May 24 19:50:48 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Tue, 25 May 2010 01:50:48 +0200 Subject: Generator expressions vs. comprehensions References: Message-ID: <20100525015048.5e0e1e8b@pitrou.net> On Mon, 24 May 2010 15:47:32 -0700 (PDT) Carl Banks wrote: > > > > Is this distinction generally known? Yes, it is. > >?The generator expression > > behavior is understandable since a generator would do the same thing, > > but I'm disappointed that the inconsistency exists and wasn't fixed in > > Python 3 when we had the chance. Why don't you use itertools.islice()? From steve at REMOVE-THIS-cybersource.com.au Mon May 24 20:06:17 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 May 2010 00:06:17 GMT Subject: python command line manual References: Message-ID: <4bfb1479$0$27861$c3e8da3@news.astraweb.com> On Mon, 24 May 2010 17:52:13 -0500, Peng Yu wrote: > I mainly check online python manual. But I feel that it would be nice if > there is command line manual available (just like perl command line > manual). Could you please let me know if such command line manual > available? >From the shell, you can call: python --help If you are using Linux, your distro probably has also installed the Python man pages, which you access with either of: man python info python And from inside the Python interactive interpreter, you can call help(obj) to get help on any object, or just help() to enter an interactive help session. -- Steven From ith140 at gmail.com Mon May 24 21:23:37 2010 From: ith140 at gmail.com (Ian Hoffman) Date: Mon, 24 May 2010 18:23:37 -0700 (PDT) Subject: MySQL, Python, NumPy and formatted read References: Message-ID: <5a958c88-38ce-4bed-9e3c-03258f8fe9ed@o12g2000vba.googlegroups.com> On May 24, 2:11?am, Dennis Lee Bieber wrote: > On Sun, 23 May 2010 21:44:30 -0700 (PDT), Ian Hoffman > declaimed the following in gmane.comp.python.general: > > > The problem is the tuple is contained in a single value separated by > > newlines (only a[0] has a record), otherwise I could do as you > > suggest... > > >>> blob = "1\n2\n3\n4\n" > >>> tple = (blob,) > >>> tple > ('1\n2\n3\n4\n',) > >>> values = [int(f) for f in tple[0].split()] > >>> values > [1, 2, 3, 4] > > -- > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ Perfect! Thanks for your help. When I tried to do what you did, I had explictly tried to for it as an array by using the array keyword in from of the loop. Everything works, and now I can move on to my next problem. Ian From wuwei23 at gmail.com Mon May 24 21:31:09 2010 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 May 2010 18:31:09 -0700 (PDT) Subject: Chatroom References: Message-ID: "Martin P. Hellwig" wrote: > What have you tried so far? Alternatively, how much is it worth to you? From afriere at yahoo.co.uk Mon May 24 21:48:13 2010 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 24 May 2010 18:48:13 -0700 (PDT) Subject: python command line manual References: Message-ID: <66be3c90-adcd-4ddd-9f1c-5054a06e8e98@40g2000pry.googlegroups.com> On May 25, 8:52?am, Peng Yu wrote: > I mainly check online python manual. But I feel that it would be nice > if there is command line manual available (just like perl command line > manual). Could you please let me know if such command line manual > available? > > -- > Regards, > Peng It's not really a manual, but if you want the documentation written into a module try 'pydoc '. This is gives you the same output as you get running help() in the python shell. From anand.shashwat at gmail.com Mon May 24 21:52:56 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Tue, 25 May 2010 07:22:56 +0530 Subject: Chatroom In-Reply-To: References: Message-ID: seems like an academic project which is worth grades On Tue, May 25, 2010 at 7:01 AM, alex23 wrote: > "Martin P. Hellwig" wrote: > > What have you tried so far? > > Alternatively, how much is it worth to you? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon May 24 22:08:40 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 25 May 2010 03:08:40 +0100 Subject: Chatroom In-Reply-To: References: Message-ID: On 24/05/2010 19:50, narcissus wrote: > Hello , I want to create a program that is one chatroom and everyone > has this program can Enter into that chatroom. how can i do this? > > and i want gui for it too (GTK) Use your favourite editor and/or IDE to create your program, run it and when you run into problems ask here or on the Python tutor ng/ml. Regards. Mark Lawrence From michele.simionato at gmail.com Tue May 25 00:12:54 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 24 May 2010 21:12:54 -0700 (PDT) Subject: Generator expressions vs. comprehensions References: Message-ID: <86661397-d5bd-487c-9132-ae1e620fb0bf@v37g2000vbv.googlegroups.com> On May 25, 12:47?am, Carl Banks wrote: > The situation here is known. ?It can't be corrected, even in Python 3, > without modifying iterator protocol to tie StopIteration to a specific > iterator. ?This is possible and might be worth it to avoid hard-to- > diagnose bugs but it would complicate iterator protocol, which becomes > less useful as it becomes more complex. The situation here is a known and could be corrected by changing the meaning of list comprehension, for instance by having [x for x in iterable] to be an alias for list(x for x in iterable). In such a way the StopIteration exception would be always swallowed and there would be consistency with generator expressions (by construction). However, the list comprehension would become non-equivalent to the corresponding for-loop with an .append, so somebody would be un happy anyway :-/ From michele.simionato at gmail.com Tue May 25 00:15:06 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 24 May 2010 21:15:06 -0700 (PDT) Subject: help with the Python 3 version of the decorator module References: Message-ID: <1ec7ecb1-ab6d-4b88-8851-f944e7e50b60@z17g2000vbd.googlegroups.com> On May 22, 10:49?am, Michele Simionato wrote: > I have finally decided to port the decorator module to Python 3. > Changing the module was zero effort (2to3 worked) but changing the > documentation was quite an effort, since I had to wait for docutils/ > pygements to support Python 3 and to change all my custom build > process. Also, I am relying on distribute for installing on Python 3. > I would welcome feedback for people using Python 3 on various > platforms (including Windows) to see if > they can install the module and how much of effort it is. > > Here is the tarball:http://micheles.googlecode.com/files/decorator-3.2beta.tar.gz > Here is the documentation:http://micheles.googlecode.com/hg/decorator/index.html > > The installation process should work for Python 2.4, 2.5, 2.6, 2.7, > 3.0, 3.1 and all platforms were Python runs, but I have only tested it > on Linux for Python 2.6 and 3.1. The module has no relevant changes, > so I expect problems only from the building process, if any. I am not > sure of what will happen if you do not have distribute or if you have > a previous version of the module, or if you use pip or something else > (even in Python 2.X). The packaging in Python has become a real mess! > > TIA for you help, > > ? ?Michele Simionato decorator-3.2.0 has been released on PyPI: http://pypi.python.org/pypi/decorator From john.d.perkins at gmail.com Tue May 25 00:34:25 2010 From: john.d.perkins at gmail.com (Six) Date: Mon, 24 May 2010 21:34:25 -0700 (PDT) Subject: Drilling down in a dict with "complex" objects Message-ID: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> I am trying to access an objects sub-object attributes. I can boil the code I am working with down to this problem section: (snip) class Pt: x = None y = None def __init__(self, x, y): self.x, self.y = x, y pass class Pts: curr_point = None next_point = None def __init__(self, n, m): self.next_point = Pt(n, m) def update(self, point): self.curr_point = self.next_point self.next_point = point class PtManage: points = {} def __init__(self): pass point = Pts(3,5) pman = PtManage() pman.points["odds"] = point print dir(pman) print pman["odds"].next_point.x (snip) It's this last line that doesn't work. What am I doing wrong? Is this a failure of the design or am I missing something obvious? How do I get down and see that "Pt" classes x attribute within the PtManage dict? From zak.mc.kraken at libero.it Tue May 25 01:15:36 2010 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Tue, 25 May 2010 07:15:36 +0200 Subject: python command line manual References: Message-ID: Peng Yu wrote: > I mainly check online python manual. But I feel that it would be nice > if there is command line manual available (just like perl command line > manual). Could you please let me know if such command line manual > available? pydoc? -- By ZeD From half.italian at gmail.com Tue May 25 01:17:46 2010 From: half.italian at gmail.com (Sean DiZazzo) Date: Mon, 24 May 2010 22:17:46 -0700 (PDT) Subject: Drilling down in a dict with "complex" objects References: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> Message-ID: <0c8b6296-9c10-491f-a630-59c857b5a8d7@y18g2000prn.googlegroups.com> On May 24, 9:34?pm, Six wrote: > I am trying to access an objects sub-object attributes. I can boil the > code I am working with down to this problem section: > (snip) > class Pt: > ? x = None > ? y = None > ? def __init__(self, x, y): > ? ? self.x, self.y = x, y > ? pass > > class Pts: > ? curr_point = None > ? next_point = None > ? def __init__(self, n, m): > ? ? self.next_point = Pt(n, m) > ? def update(self, point): > ? ? self.curr_point = self.next_point > ? ? self.next_point = point > > class PtManage: > ? points = {} > ? def __init__(self): > ? ? pass > > point = Pts(3,5) > pman = PtManage() > pman.points["odds"] = point > print dir(pman) > > print pman["odds"].next_point.x > > (snip) > > It's this last line that doesn't work. What am I doing wrong? Is this > a failure of the design or am I missing something obvious? How do I > get down and see that "Pt" classes x attribute within the PtManage > dict? Don't you mean? pman.points["odds"].next_point.x From benjamin.kaplan at case.edu Tue May 25 01:25:52 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 24 May 2010 22:25:52 -0700 Subject: Drilling down in a dict with "complex" objects In-Reply-To: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> References: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> Message-ID: On Mon, May 24, 2010 at 9:34 PM, Six wrote: > I am trying to access an objects sub-object attributes. I can boil the > code I am working with down to this problem section: > (snip) > class Pt: > ?x = None > ?y = None > ?def __init__(self, x, y): > ? ?self.x, self.y = x, y > ?pass > > class Pts: > ?curr_point = None > ?next_point = None First of all, don't do this. Python doesn't have variable declarations, only assignments. So this creates a variable called curr_point for the *class*, not for the instance. What Java calls static variables. It doesn't matter here but... > ?def __init__(self, n, m): > ? ?self.next_point = Pt(n, m) > ?def update(self, point): > ? ?self.curr_point = self.next_point > ? ?self.next_point = point > > class PtManage: > ?points = {} Here you have a single mutable dict shared by all instances of PtManage. a = PtManage() b = PtManage() a.points["a"] = Pts(3,2) print b.points > ?def __init__(self): > ? ?pass > > point = Pts(3,5) > pman = PtManage() > pman.points["odds"] = point > print dir(pman) > > print pman["odds"].next_point.x PtManage doesn't define __getitem__, so pman["odds"] won't work. pman.points["odds"] should. > > (snip) > > It's this last line that doesn't work. What am I doing wrong? Is this > a failure of the design or am I missing something obvious? How do I > get down and see that "Pt" classes x attribute within the PtManage > dict? > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Tue May 25 01:27:53 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 May 2010 01:27:53 -0400 Subject: Drilling down in a dict with "complex" objects In-Reply-To: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> References: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> Message-ID: On 5/25/2010 12:34 AM, Six wrote: > [snip] > It's this last line that doesn't work. What am I doing wrong? When posting such questios, print the traceback if there is one or otherwise describe 'does not work' in much more detail. From clp2 at rebertia.com Tue May 25 01:33:44 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 24 May 2010 22:33:44 -0700 Subject: Drilling down in a dict with "complex" objects In-Reply-To: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> References: <09c310be-b809-476c-aa0e-38cfa9702cfd@v29g2000prb.googlegroups.com> Message-ID: On Mon, May 24, 2010 at 9:34 PM, Six wrote: > I am trying to access an objects sub-object attributes. I can boil the > code I am working with down to this problem section: > (snip) > class Pt: > ?x = None > ?y = None > ?def __init__(self, x, y): > ? ?self.x, self.y = x, y > ?pass > > class Pts: > ?curr_point = None > ?next_point = None > ?def __init__(self, n, m): > ? ?self.next_point = Pt(n, m) > ?def update(self, point): > ? ?self.curr_point = self.next_point > ? ?self.next_point = point > > class PtManage: > ?points = {} > ?def __init__(self): > ? ?pass > > point = Pts(3,5) > pman = PtManage() > pman.points["odds"] = point > print dir(pman) > > print pman["odds"].next_point.x > > (snip) > > It's this last line that doesn't work. What am I doing wrong? Is this > a failure of the design or am I missing something obvious? How do I > get down and see that "Pt" classes x attribute within the PtManage > dict? I suggest you read the part of Python's tutorial concerning classes (http://docs.python.org/tutorial/classes.html ). Note that "curr_point = None" and similar at the class level *does not* declare an object field, because Python does not have instance variable declarations. Here is a fixed and normalized version of the classes in your example: class Pt(object): def __init__(self, x, y): self.x, self.y = x, y class Pts(object): def __init__(self, n, m): self.curr_point = None self.next_point = Pt(n, m) def update(self, point): self.curr_point = self.next_point self.next_point = point class PtManage(object): def __init__(self): self.points = {} As for why your last line fails: > print pman["odds"].next_point.x As Sean said, you're missing a ".points": print pman.points["odds"].next_point.x Also, is there any reason for PtManage over just using a `points` dictionary directly? Cheers, Chris -- http://blog.rebertia.com From kushal.kumaran+python at gmail.com Tue May 25 02:30:58 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 25 May 2010 12:00:58 +0530 Subject: Question on Python Function In-Reply-To: References: Message-ID: On Tue, May 25, 2010 at 3:38 AM, joy99 wrote: > > > Dear Vlastimir, > > As pointed out by Alister, I can print the values of function1 and > function2 with the help of another function3, but my target is to call > the "add" value of function1 and "mult" value of function2 in a third > function or the values and parameters of the third function in fourth > function. While calling, I am looking not only to print, but to use > them or manipulate them. > > I hope I am bit clear now. > If you need to use the values in another function, you need a way to let that function get its hands on the values. Your function1 and function2 should return the values they compute instead of printing them out. -- regards, kushal From __peter__ at web.de Tue May 25 03:08:56 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 May 2010 09:08:56 +0200 Subject: Generator expressions vs. comprehensions References: <86661397-d5bd-487c-9132-ae1e620fb0bf@v37g2000vbv.googlegroups.com> Message-ID: Michele Simionato wrote: > On May 25, 12:47 am, Carl Banks wrote: >> The situation here is known. It can't be corrected, even in Python 3, >> without modifying iterator protocol to tie StopIteration to a specific >> iterator. This is possible and might be worth it to avoid hard-to- >> diagnose bugs but it would complicate iterator protocol, which becomes >> less useful as it becomes more complex. > > The situation here is a known and could be corrected by changing the > meaning of list comprehension, > for instance by having [x for x in iterable] to be an alias for list(x > for x in iterable). In such a way the StopIteration exception would be > always swallowed and there would be consistency with generator > expressions (by construction). However, the list comprehension would > become non-equivalent to the corresponding for-loop with an .append, > so somebody would be un happy anyway :-/ But the list comprehension is already non-equivalent to the for loop as the loop variable isn't leaked anymore. We do have three similar constructs with subtle differences. I think not turning the list-comp into syntactic sugar for list(genexp) in py3 is a missed opportunity. Peter From __peter__ at web.de Tue May 25 03:18:15 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 May 2010 09:18:15 +0200 Subject: Question on Python Function References: Message-ID: Kushal Kumaran wrote: > On Tue, May 25, 2010 at 3:38 AM, joy99 wrote: >> >> >> Dear Vlastimir, >> >> As pointed out by Alister, I can print the values of function1 and >> function2 with the help of another function3, but my target is to call >> the "add" value of function1 and "mult" value of function2 in a third >> function or the values and parameters of the third function in fourth >> function. While calling, I am looking not only to print, but to use >> them or manipulate them. >> >> I hope I am bit clear now. >> > > If you need to use the values in another function, you need a way to > let that function get its hands on the values. Your function1 and > function2 should return the values they compute instead of printing > them out. For example: >>> def add(x, y): ... return x + y ... >>> def mul(x, y): ... return x * y ... >>> def sum_of_squares(x, y): ... return add(mul(x, x), mul(y, y)) ... >>> sum_of_squares(3, 4) 25 OP: If that addresses your question I suggest that you work through some introductory text about python. The python wiki has a few suggestions, see http://wiki.python.org/moin/BeginnersGuide Peter From michele.simionato at gmail.com Tue May 25 03:26:18 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 25 May 2010 00:26:18 -0700 (PDT) Subject: Generator expressions vs. comprehensions References: <86661397-d5bd-487c-9132-ae1e620fb0bf@v37g2000vbv.googlegroups.com> Message-ID: <2fbbec16-0070-4284-b78b-f8f11a676dd3@a16g2000vbr.googlegroups.com> On May 25, 9:08?am, Peter Otten <__pete... at web.de> wrote: > But the list comprehension is already non-equivalent to the for loop as the > loop variable isn't leaked anymore. We do have three similar constructs with > subtle differences. > > I think not turning the list-comp into syntactic sugar for list(genexp) in > py3 is a missed opportunity. Actually I do agree with the feeling, and this is not the only missed opportunity in Python 3 :-/ From jeanmichel at sequans.com Tue May 25 04:24:07 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 25 May 2010 10:24:07 +0200 Subject: function that counts... In-Reply-To: <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> Message-ID: <4BFB8927.8050006@sequans.com> superpollo wrote: > Jean-Michel Pichavant ha scritto: >> Jerry Hill wrote: >>> On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: >>> >>>> ... how many positive integers less than n have digits that sum up >>>> to m: >>>> >>> ... >>> >>>> any suggestion for pythonizin' it? >>>> >>> >>> This is how I would do it: >>> >>> def prttn(m, n): >>> """How many positive integers less than n have digits that sum >>> up to m""" >>> total = 0 >>> for testval in range(n): >>> sumofdigits = sum(int(char) for char in str(testval)) >>> if sumofdigits == m: >>> total += 1 >>> return total >>> >>> I added a docstring to the function, saying what it does, and what the >>> arguments are supposed to represent. I also moved the >>> convert-to-string-and-sum-the-digits logic into a single generator >>> expression that's passed to the builtin sum function. Oh, and I tried >>> to use slightly more expressive variable names. >>> >>> >> my favorite solutio nso far. >> >> @ OP >> >> What means prttn ? > > i already answered this downthreads... > >> something ... I don't find the word, something like un-intuitive. >> Sounds like homework. > > it is not. My apologies then, for both statements. I still don't see "how many positive integers less than n have digits that sum up to m" makes it a "partition" though if that what prttn means. Surely because I miss the context. JM From kaklis at gmail.com Tue May 25 04:42:06 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 25 May 2010 01:42:06 -0700 (PDT) Subject: asyncore loop and cmdloop problem Message-ID: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> Hi to all, i'm creating a command line application using asyncore and cmd. At if __name__ == '__main__': import socket args = sys.argv[1:] if not args: print "Usage: %s querystring" % sys.argv[0] sys.exit(0) address = ('localhost', 0) # let the kernel give us a port server = EchoServer(address) ip, port = server.address # find out what port we were given asyncore.loop() CmdClass().cmdloop() what i want is that the above commands asyncore.loop() and CmdClass().cmdloop() running at the same time. Meaning that while the application is in cmd mode with the cmdloop(), it is still able to listen for incoming messages? What should i do? thanks in advance A.K. From farina.ch at gmail.com Tue May 25 04:50:16 2010 From: farina.ch at gmail.com (fari) Date: Tue, 25 May 2010 01:50:16 -0700 (PDT) Subject: how to run brill tagger on urdu corpus? Message-ID: I like to run brill demo function with urdu pos tagged i have urdu corpus reader and a POS tagged file can you help me. 1) how and where i need to define templates for urdu . Is template dat are given with nltk(brill) are compatible to run with urdu. 2) If i want to run brill demo function on urdu tag what should i do ? waiting for reply plzzzzz. From salilgk at gmail.com Tue May 25 04:54:20 2010 From: salilgk at gmail.com (Salil GK) Date: Tue, 25 May 2010 14:24:20 +0530 Subject: Help regarding XML file manipulation Message-ID: Hello I need to make a quick prototype to process some xml file. I found xml.dom.minidom much handy and I can get information from the xml file. But I need to update a filed in the xml file and save the file. I couldn't find a way to do that. Could some one please help me on this. Basically this is what I want to do Hari 102010 201010 Rama 102010 201010 Here I want to read the Engineer information and then change the NextLeave information to a new value and save to the same file. How do we do this - can some one please help me with some sample code for the same. Thanks ~S -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Tue May 25 04:55:30 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 25 May 2010 01:55:30 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> Message-ID: <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> On May 25, 10:42?am, "kak... at gmail.com" wrote: > Hi to all, > i'm creating a command line application using asyncore and cmd. At > > if __name__ == '__main__': > ? ? import socket > > ? ? args = sys.argv[1:] > ? ? if not args: > ? ? ? ? print "Usage: %s querystring" % sys.argv[0] > ? ? ? ? sys.exit(0) > > ? ? address = ('localhost', 0) # let the kernel give us a port > ? ? server = EchoServer(address) > ? ? ip, port = server.address # find out what port we were given > > ? ? asyncore.loop() > ? ? CmdClass().cmdloop() > > what i want is that the above commands asyncore.loop() and > CmdClass().cmdloop() > running at the same time. Meaning that while the application is in cmd > mode > with the cmdloop(), it is still able to listen for incoming messages? > What should i do? > > thanks in advance > A.K. cmd.Cmd is blocking, so the only way it to run the cmdloop in a separated thread. Once for fun I rewrote the cmd module to be non-blocking but if you want to stick with the standard library you need to use a thread. From jimmy.cullen at gmail.com Tue May 25 05:00:30 2010 From: jimmy.cullen at gmail.com (Jimoid) Date: Tue, 25 May 2010 02:00:30 -0700 (PDT) Subject: Reading data from a Microsoft Access 2003 database References: <533faaee-1d55-4e39-9300-6547d29dcc4a@d12g2000vbr.googlegroups.com> <4bf3d419$0$31275$607ed4bc@cv.net> <4bf3eeeb$0$31263$607ed4bc@cv.net> <3c40f8d8-b29c-484f-b5b3-6dff0f68a032@m21g2000vbr.googlegroups.com> <16c9daac-293a-4cb6-b847-489e696682bd@c11g2000vbe.googlegroups.com> <85rh6gF8ceU1@mid.individual.net> Message-ID: <6d054b62-e79e-40c2-936e-540a61a9a50d@v37g2000vbv.googlegroups.com> This is perfect if the python ODBC driver can read the .mdb without the need for it to be running elsewhere. Thanks all for your help. From shashank.sunny.singh at gmail.com Tue May 25 05:29:12 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Tue, 25 May 2010 14:59:12 +0530 Subject: Help regarding XML file manipulation In-Reply-To: References: Message-ID: On Tue, May 25, 2010 at 2:24 PM, Salil GK wrote: > Hello > > I need to make a quick prototype to process some xml file. I found > xml.dom.minidom much handy and I can get information from the xml file. But > I need to update a filed in the xml file and save the file. I couldn't find > a way to do that. Could some one please help me on this. > > Basically this is what I want to do > > > > > Hari > 102010 > 201010 > > Rama > 102010 > 201010 > > > > > Here I want to read the Engineer information and then change the NextLeave > information to a new value and save to the same file. How do we do this - > can some one please help me with some sample code for the same. > have a look at the xml.dom.minidom module. You can access nodes by getElementsByTagName("Engineer") Access value of the text node by node.nodeValue To modify the xml, you will have to set the node value to the desired value node.nodeValue = newValue Note that to you will have to write the modified dom object back to the file to save the changes, just setting the value of nodes will not automatically do that. HTH -S > > Thanks > ~S > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From kaklis at gmail.com Tue May 25 05:53:12 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 25 May 2010 02:53:12 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> Message-ID: <57fb8b26-d327-4a93-8d14-78f6905e39ac@y21g2000vba.googlegroups.com> On May 25, 4:55?am, Michele Simionato wrote: > On May 25, 10:42?am, "kak... at gmail.com" wrote: > > > > > Hi to all, > > i'm creating a command line application using asyncore and cmd. At > > > if __name__ == '__main__': > > ? ? import socket > > > ? ? args = sys.argv[1:] > > ? ? if not args: > > ? ? ? ? print "Usage: %s querystring" % sys.argv[0] > > ? ? ? ? sys.exit(0) > > > ? ? address = ('localhost', 0) # let the kernel give us a port > > ? ? server = EchoServer(address) > > ? ? ip, port = server.address # find out what port we were given > > > ? ? asyncore.loop() > > ? ? CmdClass().cmdloop() > > > what i want is that the above commands asyncore.loop() and > > CmdClass().cmdloop() > > running at the same time. Meaning that while the application is in cmd > > mode > > with the cmdloop(), it is still able to listen for incoming messages? > > What should i do? > > > thanks in advance > > A.K. > > cmd.Cmd is blocking, so the only way it to run the cmdloop in a > separated thread. Once for fun > I rewrote the cmd module to be non-blocking but if you want to stick > with the standard library you need to use a thread. Thank you so much. Is there a way that i can find that version of cmd? Antonis From g.rodola at gmail.com Tue May 25 06:03:22 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Tue, 25 May 2010 12:03:22 +0200 Subject: asyncore loop and cmdloop problem In-Reply-To: <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> Message-ID: 2010/5/25 Michele Simionato : > On May 25, 10:42?am, "kak... at gmail.com" wrote: >> Hi to all, >> i'm creating a command line application using asyncore and cmd. At >> >> if __name__ == '__main__': >> ? ? import socket >> >> ? ? args = sys.argv[1:] >> ? ? if not args: >> ? ? ? ? print "Usage: %s querystring" % sys.argv[0] >> ? ? ? ? sys.exit(0) >> >> ? ? address = ('localhost', 0) # let the kernel give us a port >> ? ? server = EchoServer(address) >> ? ? ip, port = server.address # find out what port we were given >> >> ? ? asyncore.loop() >> ? ? CmdClass().cmdloop() >> >> what i want is that the above commands asyncore.loop() and >> CmdClass().cmdloop() >> running at the same time. Meaning that while the application is in cmd >> mode >> with the cmdloop(), it is still able to listen for incoming messages? >> What should i do? >> >> thanks in advance >> A.K. > > cmd.Cmd is blocking, so the only way it to run the cmdloop in a > separated thread. Once for fun > I rewrote the cmd module to be non-blocking but if you want to stick > with the standard library you need to use a thread. > -- > http://mail.python.org/mailman/listinfo/python-list > Too bad cmdloop() doesn't provide an argument to return immediately. Why don't you submit this patch on the bug tracker? --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From michele.simionato at gmail.com Tue May 25 06:20:29 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 25 May 2010 03:20:29 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> Message-ID: <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> On May 25, 12:03?pm, Giampaolo Rodol? wrote: > Too bad cmdloop() doesn't provide an argument to return immediately. > Why don't you submit this patch on the bug tracker? > > --- Giampaolohttp://code.google.com/p/pyftpdlibhttp://code.google.com/p/psutil Because it is not a bug, cmd was designed to be blocking. It would be a feature request. I wrote a cmd2 module a few years ago, which was intended as a replacement for cmd with various additional features (including the non blocking behavior). We are using it in production, but I have never published it (I intended to but, you know, a days has only 24 hours ;) I should put together the code in a single file and publish it, but I cannot guarantee if and when I will have the time to do so. From g.rodola at gmail.com Tue May 25 06:48:40 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Tue, 25 May 2010 12:48:40 +0200 Subject: asyncore loop and cmdloop problem In-Reply-To: <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> Message-ID: 2010/5/25 Michele Simionato : > On May 25, 12:03?pm, Giampaolo Rodol? wrote: >> Too bad cmdloop() doesn't provide an argument to return immediately. >> Why don't you submit this patch on the bug tracker? >> >> --- Giampaolohttp://code.google.com/p/pyftpdlibhttp://code.google.com/p/psutil > > Because it is not a bug, cmd was designed to be blocking. It would be > a feature request. Sure, a feature request, but it would be nice to have anyway. =) The OP question shown how this can be desirable in certain circumstances.. --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From tom.browder at gmail.com Tue May 25 07:17:53 2010 From: tom.browder at gmail.com (Tom Browder) Date: Tue, 25 May 2010 06:17:53 -0500 Subject: [wxPython-users] wxPython 2.8.11.0 release In-Reply-To: <4BFB0E05.1090101@alldunn.com> References: <4BFB0E05.1090101@alldunn.com> Message-ID: On Mon, May 24, 2010 at 18:38, Robin Dunn wrote: ... > The 2.8.11.0 release of wxPython is now available for download at > http://wxpython.org/download.php. This release adds Python 2.7 builds, > PySlices, new pubsub implementation, lots of updates to AGW, and lots > of bugs fixed. ?A summary of changes is listed below and also at > http://wxpython.org/recentchanges.php. Has the port to python 3 problem been solved in the development line, or is help still looked for there? See this Nov 19, 2009 msg: http://groups.google.com/group/wxpython-users/browse_thread/thread/86f8b2513941d0f4/6d77c3d4ebd0e919?lnk=gst&q=python+3#6d77c3d4ebd0e919 Thanks, -Tom From utente at esempio.net Tue May 25 07:28:22 2010 From: utente at esempio.net (superpollo) Date: Tue, 25 May 2010 13:28:22 +0200 Subject: function that counts... In-Reply-To: References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> Message-ID: <4bfbb456$0$18992$4fafbaef@reader5.news.tin.it> Jean-Michel Pichavant ha scritto: > superpollo wrote: >> Jean-Michel Pichavant ha scritto: >>> Jerry Hill wrote: >>>> On Wed, May 19, 2010 at 3:58 PM, superpollo wrote: >>>> >>>>> ... how many positive integers less than n have digits that sum up >>>>> to m: >>>>> >>>> ... >>>> >>>>> any suggestion for pythonizin' it? >>>>> >>>> >>>> This is how I would do it: >>>> >>>> def prttn(m, n): >>>> """How many positive integers less than n have digits that sum >>>> up to m""" >>>> total = 0 >>>> for testval in range(n): >>>> sumofdigits = sum(int(char) for char in str(testval)) >>>> if sumofdigits == m: >>>> total += 1 >>>> return total >>>> >>>> I added a docstring to the function, saying what it does, and what the >>>> arguments are supposed to represent. I also moved the >>>> convert-to-string-and-sum-the-digits logic into a single generator >>>> expression that's passed to the builtin sum function. Oh, and I tried >>>> to use slightly more expressive variable names. >>>> >>>> >>> my favorite solutio nso far. >>> >>> @ OP >>> >>> What means prttn ? >> >> i already answered this downthreads... >> >>> something ... I don't find the word, something like un-intuitive. >>> Sounds like homework. >> >> it is not. > My apologies then, for both statements. > I still don't see "how many positive integers less than n have digits > that sum up to m" makes it a "partition" though if that what prttn > means. Surely because I miss the context. > > JM ok, this is the mistery. it was inspired by a question on e.c.m.: http://groups.google.it/group/es.ciencia.matematicas/msg/f8f09672bd8a052a the first question is (somewhat) an instance of: http://en.wikipedia.org/wiki/Partition_(number_theory) bye From kaklis at gmail.com Tue May 25 08:56:02 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 25 May 2010 05:56:02 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> Message-ID: <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> On May 25, 6:48?am, Giampaolo Rodol? wrote: > 2010/5/25 Michele Simionato : > > > On May 25, 12:03?pm, Giampaolo Rodol? wrote: > >> Too bad cmdloop() doesn't provide an argument to return immediately. > >> Why don't you submit this patch on the bug tracker? > > >> --- Giampaolohttp://code.google.com/p/pyftpdlibhttp://code.google.com/p/psutil > > > Because it is not a bug, cmd was designed to be blocking. It would be > > a feature request. > > Sure, a feature request, but it would be nice to have anyway. =) > The OP question shown how this can be desirable in certain circumstances.. > > --- Giampaolohttp://code.google.com/p/pyftpdlibhttp://code.google.com/p/psutil Could you please provide me with a simple example how to do this with threads. I don't know where to put the cmdloop(). Please help, i' m so confused! Thank you From victorsubervi at gmail.com Tue May 25 09:30:13 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 25 May 2010 09:30:13 -0400 Subject: A Quick MySQL Question In-Reply-To: References: Message-ID: On Tue, May 25, 2010 at 3:50 AM, Dennis Lee Bieber wrote: > On Mon, 24 May 2010 13:37:58 -0400, Victor Subervi > declaimed the following in > Parameterized queries process the parameters to ensure that they are > safe for use in the SQL statement. > > In the case of the MySQLdb adapter (written to be compatible with > pre-version 5 of MySQL) this means that the parameters are converted to > a string representation (if not already a string), characters in the > parameter that are significant to the MySQL dialect of SQL are safely > escaped, AND the resulting string is WRAPPED in quote marks. > > k. That worked. Thanks! > I suggest you study the SQL standard "like" comparison, and the use > of wildcards with it. Consider a "card catalog" application and how one > would formulate a query in which the author's last name is "Norton", and > the title of the book contains the word "Witch" (the word could be > anywhere within the title). > I understand how to do "like" queries and use wildcards. I didn't understand what you were doing over there, something with %values% or some such. If you care to pick up that thread, fine, otherwise, until the next time. Thanks you as always, Dennis :) beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From cde3 at live.com Tue May 25 09:49:46 2010 From: cde3 at live.com (Sandy Ydnas) Date: Tue, 25 May 2010 18:49:46 +0500 Subject: to prevent reveres engineering for Python In-Reply-To: <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com>, , <87mxvsfzvh.fsf@benfinney.id.au>, <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: Agree, reveres engineering is crucial issuer for programming language but every executable file can be cracked, for example by using disassembler!!! For each weapon there is antiweapon, so is it possible to prevent reveres engineering when customer have access to executable made from Python code??? Regards Sandy > From: pmaupin at gmail.com > Subject: Re: where are the program that are written in python? > Date: Fri, 21 May 2010 23:29:37 -0700 > To: python-list at python.org > > On May 21, 9:12 pm, Ben Finney wrote: > > a... at pythoncraft.com (Aahz) writes: > > > In article , > > > Patrick Maupin wrote: > > > > > >There are a lot of commercial programs written in Python. But any > > > >company which thinks it has a lock on some kind of super secret sauce > > > >isn't going to use Python, because it's very easy to reverse engineer > > > >even compiled Python programs. > > > > > That's not always true. Both my employer (Egnyte) and one of our main > > > competitors (Dropbox) use Python in our clients. We don't care much > > > because using our servers is a requirement of the client. > > > > Doesn't that mean those companies don't fit the above description? That > > is, neither of them ?thinks it has a lock on some kind of super secret > > sauce? in the programs. So they don't seem to be counter-examples. > > Just because someone has competition doesn't mean they don't think > they have secret sauce. I think Aahz's main point was that in his sub- > industry, the secret sauce is guarded by not actually letting the > customer have access to executable code, other than through the > network. > > Regards, > Pat > -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Hotmail: Trusted email with Microsoft?s powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Tue May 25 10:23:58 2010 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 25 May 2010 07:23:58 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> Message-ID: <1fc2db40-42c3-40d7-ab92-b29c6c039345@u7g2000vbq.googlegroups.com> On May 25, 2:56?pm, "kak... at gmail.com" wrote: > Could you please provide me with a simple example how to do this with > threads. > I don't know where to put the cmdloop(). > Please help, i' m so confused! > Thank you What are you trying to do? Do you really need to use the standard library? Likely what you want to accomplish is already implemented in Twisted; I remember there was something like that in their examples directory. From kaklis at gmail.com Tue May 25 10:47:06 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 25 May 2010 07:47:06 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> <1fc2db40-42c3-40d7-ab92-b29c6c039345@u7g2000vbq.googlegroups.com> Message-ID: On May 25, 5:23?pm, Michele Simionato wrote: > On May 25, 2:56?pm, "kak... at gmail.com" wrote: > > > Could you please provide me with a simple example how to do this with > > threads. > > I don't know where to put the cmdloop(). > > Please help, i' m so confused! > > Thank you > > What are you trying to do? Do you really need to use the standard > library? Likely what you want to accomplish is already implemented in > Twisted; I remember there was something like that in their examples > directory. Thank you, and sorry for the mistake i did before with my post. Antonis From awilliam at whitemice.org Tue May 25 11:09:03 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 25 May 2010 11:09:03 -0400 Subject: to prevent reveres engineering for Python In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> , , <87mxvsfzvh.fsf@benfinney.id.au> , <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: <1274800143.9273.31.camel@linux-yu4c.site> On Tue, 2010-05-25 at 18:49 +0500, Sandy Ydnas wrote: > Agree, reveres engineering is crucial issuer for programming > language > but every executable file can be cracked, for example by using > disassembler!!! > For each weapon there is antiweapon, so > is it possible to prevent reveres engineering when customer have > access to executable made from Python code??? No. But you can make it hard. Store a GPG encrypted blob in your program that contains you secret sauce, is decrypted to memory, executed, and then discarded. Setup some kind of license manager like dongle or application to perform the key management. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From kaklis at gmail.com Tue May 25 12:31:03 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Tue, 25 May 2010 09:31:03 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> <1fc2db40-42c3-40d7-ab92-b29c6c039345@u7g2000vbq.googlegroups.com> Message-ID: <0123253e-f628-471b-a343-0ad2588b1a20@m33g2000vbi.googlegroups.com> On May 25, 5:47?pm, "kak... at gmail.com" wrote: > On May 25, 5:23?pm, Michele Simionato > wrote: > > > On May 25, 2:56?pm, "kak... at gmail.com" wrote: > > > > Could you please provide me with a simple example how to do this with > > > threads. > > > I don't know where to put the cmdloop(). > > > Please help, i' m so confused! > > > Thank you > > > What are you trying to do? Do you really need to use the standard > > library? Likely what you want to accomplish is already implemented in > > Twisted; I remember there was something like that in their examples > > directory. > > Thank you, > and sorry for the mistake i did before with my post. > > Antonis hi again. i installed twisted, but since i m not familiar with it, do you remember which example you have in mind? What i want to accomplish is something like "asterisk". while you send commands from the asterisk cli, at the same time the underlying protocol sends you notifications to the console. without exiting the application. thanks From tjreedy at udel.edu Tue May 25 13:09:23 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 May 2010 13:09:23 -0400 Subject: Generator expressions vs. comprehensions In-Reply-To: References: <86661397-d5bd-487c-9132-ae1e620fb0bf@v37g2000vbv.googlegroups.com> Message-ID: On 5/25/2010 3:08 AM, Peter Otten wrote: > Michele Simionato wrote: > I think not turning the list-comp into syntactic sugar for list(genexp) in > py3 is a missed opportunity. Implementing it that way was tried but was much slower than the current implementation. If one uses StopIteration as it is intended to be used (and is so documented), then, I believe, they are equivalent. There was a conscious decision to not slow comprehensions for the many to cater to the very few. Terry Jan Reedy From tjreedy at udel.edu Tue May 25 13:16:02 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 May 2010 13:16:02 -0400 Subject: to prevent reveres engineering for Python In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com>, , <87mxvsfzvh.fsf@benfinney.id.au>, <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: On 5/25/2010 9:49 AM, Sandy Ydnas wrote: > is it possible to prevent reveres engineering when customer have access > to executable made from Python code??? If there is, it is a trade secrets that you will not be able to reverse engineer ;-). From tjreedy at udel.edu Tue May 25 13:19:50 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 May 2010 13:19:50 -0400 Subject: Generator expressions vs. comprehensions In-Reply-To: References: <86661397-d5bd-487c-9132-ae1e620fb0bf@v37g2000vbv.googlegroups.com> Message-ID: On 5/25/2010 1:09 PM, Terry Reedy wrote: > On 5/25/2010 3:08 AM, Peter Otten wrote: >> Michele Simionato wrote: > >> I think not turning the list-comp into syntactic sugar for >> list(genexp) in >> py3 is a missed opportunity. > > Implementing it that way was tried but was much slower than the current > implementation. If one uses StopIteration as it is intended to be used > (and is so documented), then, I believe, they are equivalent. There was > a conscious decision to not slow comprehensions for the many to cater to > the very few. And those few can always write list(genexp) instead of [genexp] (or set...) when the minute difference actually matters. > Terry Jan Reedy > From chambon.pascal at wanadoo.fr Tue May 25 13:46:56 2010 From: chambon.pascal at wanadoo.fr (Pascal Chambon) Date: Tue, 25 May 2010 19:46:56 +0200 Subject: Troubles with python internationalization Message-ID: <4BFC0D10.4060002@wanadoo.fr> Hello I'm studying the migration of my website (mixed english and french languages...) to a properly localized architecture. From what I've read so far, using translation "tags" (or quick phrases) in the code, and translating them to every target language (including english) sounds a better approach than using, for example, final english wordings as translation tags. The setup is longer via the first way, but at least if you change english wordings later, you don't break all other translations at the same time. However, I still have problems with some aspects of internationalization: * code safety : it seems default python string formatting technics (% operator, .format() method) are normally used when one needs to substitute placeholders in translated strings. But the thing is : I DONT want my view to raise an exception simply because one of the translations has forgotten a damn "%(myvar)s" placeholder. The only quick fix I can think of, is to always use substitution through defaultdicts instances (and still, exceptions could occur if abnormal "%s" placeholders are found in the translated string). Are there some utilities in python, or frameworks like django, to allow a safe string substitution (which might, for example, simply log an error if a buggy string si found) ? Python's template strings' "safe_substitute()" won't fit, because it swallows errors without any notice... * unknown translatable strings : I have in different data files (eg. yaml), strings which will need translation, but that can't be detected by gettext and co, since they only appear in the code as variable i.e "_(yamlvar)". The easiest, I guess, would be to replace them by specific tags (like "TR_HOMEPAGE_TITLE"), and to have a tool browse the code to extract them and add them to the standard gettext translation chain. Such a tool shouldn't be too hard to code, but I'd rather know : doesn't such a tool already exist somewhere ? I've seen no such mention in gettext or babel tools, only recogniztion via function calls ( _(), tr()... ). * I have seen nowhere mention of how to remove deprecated/unused strings from gettext files - only merging translations seems to interest people. However, having a translation file which slowly fills itself with outdated data doesn't sound cool to me. Does anyone know tools/program flags which would list/extract translations that don't seem used anymore ? Thanks for you help, regards, Pascal From victorsubervi at gmail.com Tue May 25 14:45:16 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 25 May 2010 14:45:16 -0400 Subject: Another Little MySQL Problem Message-ID: Hi; I have this code: clientCursor.execute('select ID from %s' % (personalDataTable)) upds = [itm[0] for itm in clientCursor] print "" % upds The problem is that the values passed are 1L, 2L.... When I retrieve them on the other end and try to convert them to integers, guess what happens? So how do I get rid of that "L"? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From picture017 at gmail.com Tue May 25 15:00:54 2010 From: picture017 at gmail.com (Minhaz Rahman) Date: Tue, 25 May 2010 12:00:54 -0700 (PDT) Subject: Legal Point Dhaka bangladesh Message-ID: <0e1e6d28-fedb-4d43-9f02-7019cb88859b@k31g2000vbu.googlegroups.com> http://www.advocatemizan.com From zasaconsulting at gmail.com Tue May 25 15:05:53 2010 From: zasaconsulting at gmail.com (Alexzive) Date: Tue, 25 May 2010 12:05:53 -0700 (PDT) Subject: speed up a numpy code with huge array Message-ID: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> Hello Pythonguys! is there a way to improve the performance of the attached code ? it takes about 5 h on a dual-core (using only one core) when len(V) ~1MIL. V is an array which is supposed to store all the volumes of tetrahedral elements of a grid whose coord. are stored in NN (accessed trough the list of tetraelements --> EL) Thanks in advance! Alex #### print 'start ' + nameodb #path = '/windows/D/SIM-MM/3D/E_ortho/' + nameodb + '.odb' path = pt + nameodb + '.odb' odb = openOdb(path) N = odb.rootAssembly.instances['PART-1-1'].nodes if loadV==1: pathV=pt+vtet V=numpy.loadtxt(pathV) VTOT = V[0] L3 = V[1] print 'using ' + vtet else: NN=[] B=[0,0,0,0] for i in range(len(N)): B[0] = N[i].label B[1] = N[i].coordinates[0] B[2] = N[i].coordinates[1] B[3] = N[i].coordinates[2] NN = append(NN,B) NN=NN.reshape(-1,4) EL = odb.rootAssembly.instances['PART-1-1'].elements L1 = max(NN[:,1])-min(NN[:,1]) L2 = max(NN[:,2])-min(NN[:,2]) L3 = max(NN[:,3])-min(NN[:,3]) VTOT=L1*L2*L3 print 'VTOT: [mm?]' + str(VTOT) V = array([]) print 'calculating new Vtet ' V = range(len(EL)+2) V[0] = VTOT V[1] = L3 for j in range(0,len(EL)): Va = EL[j].connectivity[0] Vb = EL[j].connectivity[1] Vc = EL[j].connectivity[2] Vd = EL[j].connectivity[3] ix = where(NN[:,0] == Va) Xa = NN[ix,1][0][0] Ya = NN[ix,2][0][0] Za = NN[ix,3][0][0] ix = where(NN[:,0] == Vb) Xb = NN[ix,1][0][0] Yb = NN[ix,2][0][0] Zb = NN[ix,3][0][0] ix = where(NN[:,0] == Vc) Xc = NN[ix,1][0][0] Yc = NN[ix,2][0][0] Zc = NN[ix,3][0][0] ix = where(NN[:,0] == Vd) Xd = NN[ix,1][0][0] Yd = NN[ix,2][0][0] Zd = NN[ix,3][0][0] a = [Xa,Ya,Za] b = [Xb,Yb,Zb] c = [Xc,Yc,Zc] d = [Xd,Yd,Zd] aa = numpy.diff([b,a],axis=0)[0] bb = numpy.diff([c,b],axis=0)[0] cc = numpy.diff([d,c],axis=0)[0] D=array([aa,bb,cc]) det=numpy.linalg.det(D) V[j+2] = abs(det)/6 pathV = pt + vtet savetxt(pathV, V, fmt='%.3e') ### From magnus.moraberg at gmail.com Tue May 25 15:13:55 2010 From: magnus.moraberg at gmail.com (Barry) Date: Tue, 25 May 2010 12:13:55 -0700 (PDT) Subject: UnicodeDecodeError having fetch web page Message-ID: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Hi, The code below is giving me the error: Traceback (most recent call last): File "C:\Users\Administrat??r\Desktop\test.py", line 4, in UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: unexpected code byte What am i doing wrong? Thanks, Barry request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ baby',headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/ 20071127 Firefox/2.0.0.11'} ) response = urllib.request.urlopen(request) html = response.read().decode('utf-8') From vincent at vincentdavis.net Tue May 25 15:25:16 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 25 May 2010 13:25:16 -0600 Subject: speed up a numpy code with huge array In-Reply-To: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> Message-ID: It makes me think you are filling you available memory and using the disk as cache. If this happens things will get real slow. You might take a look at your system resources when this is running. I don't have much else to offer and could be completely wrong. Vincent On Tue, May 25, 2010 at 1:05 PM, Alexzive wrote: > Hello Pythonguys! > > is there a way to improve the performance of the attached code ? it > takes about 5 h on a dual-core (using only one core) when len(V) > ~1MIL. V is an array which is supposed to store all the volumes of > tetrahedral elements of a grid whose coord. are stored in NN (accessed > trough the list of tetraelements --> EL) > > > Thanks in advance! > Alex > > #### > print 'start ' + nameodb > #path = '/windows/D/SIM-MM/3D/E_ortho/' + nameodb + '.odb' > path = pt + nameodb + '.odb' > odb = openOdb(path) > > N = odb.rootAssembly.instances['PART-1-1'].nodes > if loadV==1: > pathV=pt+vtet > V=numpy.loadtxt(pathV) > VTOT = V[0] > L3 = V[1] > print 'using ' + vtet > else: > NN=[] > B=[0,0,0,0] > for i in range(len(N)): > B[0] = N[i].label > B[1] = N[i].coordinates[0] > B[2] = N[i].coordinates[1] > B[3] = N[i].coordinates[2] > NN = append(NN,B) > > NN=NN.reshape(-1,4) > EL = odb.rootAssembly.instances['PART-1-1'].elements > > L1 = max(NN[:,1])-min(NN[:,1]) > L2 = max(NN[:,2])-min(NN[:,2]) > L3 = max(NN[:,3])-min(NN[:,3]) > VTOT=L1*L2*L3 > print 'VTOT: [mm?]' + str(VTOT) > > V = array([]) > > print 'calculating new Vtet ' > V = range(len(EL)+2) > V[0] = VTOT > V[1] = L3 > for j in range(0,len(EL)): > Va = EL[j].connectivity[0] > Vb = EL[j].connectivity[1] > Vc = EL[j].connectivity[2] > Vd = EL[j].connectivity[3] > ix = where(NN[:,0] == Va) > Xa = NN[ix,1][0][0] > Ya = NN[ix,2][0][0] > Za = NN[ix,3][0][0] > ix = where(NN[:,0] == Vb) > Xb = NN[ix,1][0][0] > Yb = NN[ix,2][0][0] > Zb = NN[ix,3][0][0] > ix = where(NN[:,0] == Vc) > Xc = NN[ix,1][0][0] > Yc = NN[ix,2][0][0] > Zc = NN[ix,3][0][0] > ix = where(NN[:,0] == Vd) > Xd = NN[ix,1][0][0] > Yd = NN[ix,2][0][0] > Zd = NN[ix,3][0][0] > a = [Xa,Ya,Za] > b = [Xb,Yb,Zb] > c = [Xc,Yc,Zc] > d = [Xd,Yd,Zd] > aa = numpy.diff([b,a],axis=0)[0] > bb = numpy.diff([c,b],axis=0)[0] > cc = numpy.diff([d,c],axis=0)[0] > D=array([aa,bb,cc]) > det=numpy.linalg.det(D) > V[j+2] = abs(det)/6 > pathV = pt + vtet > savetxt(pathV, V, fmt='%.3e') > ### > -- > http://mail.python.org/mailman/listinfo/python-list > *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Tue May 25 15:39:03 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 25 May 2010 15:39:03 -0400 Subject: UnicodeDecodeError having fetch web page In-Reply-To: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Message-ID: <23F0D49F-FF28-45B6-8628-CEBCA3FE0E16@semanchuk.com> On May 25, 2010, at 3:13 PM, Barry wrote: > Hi, > > The code below is giving me the error: > > Traceback (most recent call last): > File "C:\Users\Administrat??r\Desktop\test.py", line 4, in > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: > unexpected code byte > > > What am i doing wrong? > > Thanks, > > Barry > > request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ > baby',headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/ > 20071127 Firefox/2.0.0.11'} ) > > response = urllib.request.urlopen(request) > html = response.read().decode('utf-8') Well, for starters you're assuming that the response content is in UTF-8. You need to examine the Content-Type header to see what the encoding is. If it's not UTF-8, there's your problem. HTH P From lie.1296 at gmail.com Tue May 25 15:40:43 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 26 May 2010 05:40:43 +1000 Subject: to prevent reveres engineering for Python In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> , , <87mxvsfzvh.fsf@benfinney.id.au> , <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: <4bfc282a$1@dnews.tpgi.com.au> On 05/26/10 01:09, Adam Tauno Williams wrote: > On Tue, 2010-05-25 at 18:49 +0500, Sandy Ydnas wrote: >> Agree, reveres engineering is crucial issuer for programming >> language >> but every executable file can be cracked, for example by using >> disassembler!!! >> For each weapon there is antiweapon, so >> is it possible to prevent reveres engineering when customer have >> access to executable made from Python code??? > > No. But you can make it hard. > > Store a GPG encrypted blob in your program that contains you secret > sauce, is decrypted to memory, executed, and then discarded. Setup > some kind of license manager like dongle or application to perform the > key management. That merely gives a false sense of security. If the program is decrypted in memory, you can easily make a memory dump to get the unencrypted program. If I am a competitor that can make economic advantage by cracking your secret sauce, it wouldn't be difficult for me to do that. From darcy at druid.net Tue May 25 15:57:12 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 25 May 2010 15:57:12 -0400 Subject: to prevent reveres engineering for Python In-Reply-To: <4bfc282a$1@dnews.tpgi.com.au> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <87mxvsfzvh.fsf@benfinney.id.au> <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> <4bfc282a$1@dnews.tpgi.com.au> Message-ID: <20100525155712.d177b9e9.darcy@druid.net> On Wed, 26 May 2010 05:40:43 +1000 Lie Ryan wrote: > That merely gives a false sense of security. If the program is decrypted > in memory, you can easily make a memory dump to get the unencrypted > program. If I am a competitor that can make economic advantage by > cracking your secret sauce, it wouldn't be difficult for me to do that. Yes, in fact the only people inconvenienced are your paying clients. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From magnus.moraberg at gmail.com Tue May 25 16:00:23 2010 From: magnus.moraberg at gmail.com (Barry) Date: Tue, 25 May 2010 13:00:23 -0700 (PDT) Subject: UnicodeDecodeError having fetch web page References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Message-ID: <089cbe25-2f32-4b9a-90a5-8be952b602f6@l6g2000vbo.googlegroups.com> On 25 Maj, 21:39, Philip Semanchuk wrote: > On May 25, 2010, at 3:13 PM, Barry wrote: > > > > > Hi, > > > The code below is giving me the error: > > > Traceback (most recent call last): > > ?File "C:\Users\Administrat?r\Desktop\test.py", line 4, in > > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: > > unexpected code byte > > > What am i doing wrong? > > > Thanks, > > > Barry > > > request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ > > baby',headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/ > > 20071127 Firefox/2.0.0.11'} ) > > > response = urllib.request.urlopen(request) > > html = response.read().decode('utf-8') > > Well, for starters you're assuming that the response content is in ? > UTF-8. You need to examine the Content-Type header to see what the ? > encoding is. If it's not UTF-8, there's your problem. > > HTH > P The content type is utf-8: Date: Wed, 19 May 2010 19:17:39 GMT Server: Apache Cache-Control: private, s-maxage=0, max-age=0, must-revalidate Content-Language: en Vary: Accept-Encoding,Cookie Last-Modified: Wed, 19 May 2010 10:10:34 GMT Content-Encoding: gzip Content-Length: 25247 Content-Type: text/html; charset=utf-8 X-Cache: HIT from sq61.wikimedia.org X-Cache-Lookup: HIT from sq61.wikimedia.org:3128 Age: 520549 X-Cache: HIT from amssq32.esams.wikimedia.org X-Cache-Lookup: HIT from amssq32.esams.wikimedia.org:3128 X-Cache: MISS from amssq37.esams.wikimedia.org X-Cache-Lookup: MISS from amssq37.esams.wikimedia.org:80 Connection: close Can it be that the page is corrupt? If so, how can I make the best of the situation? Many other pages from this server work without problem. Thanks! Barry From ian.g.kelly at gmail.com Tue May 25 16:01:19 2010 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 25 May 2010 14:01:19 -0600 Subject: Python-list Digest, Vol 80, Issue 223 In-Reply-To: References: Message-ID: On Tue, May 25, 2010 at 1:10 PM, wrote: > ---------- Forwarded message ---------- > From:?Terry Reedy > To:?python-list at python.org > Date:?Tue, 25 May 2010 13:09:23 -0400 > Subject:?Re: Generator expressions vs. comprehensions > On 5/25/2010 3:08 AM, Peter Otten wrote: >> >> Michele Simionato wrote: > >> I think not turning the list-comp into syntactic sugar for list(genexp) in >> py3 is a missed opportunity. > > Implementing it that way was tried but was much slower than the current implementation. If one uses StopIteration as it is intended to be used (and is so documented), then, I believe, they are equivalent. There was a conscious decision to not slow comprehensions for the many to cater to the very few. I thought that I was using it as intended. The full function that I was working with when I ran into the problem was: def tuples(iterable, n=2): """Make an iterator that returns elements from iterable in tuples of n. If the number of elements from the iterable is not a multiple of n, any trailing elements will be truncated. tuples('ABCDEFG', n=2) --> ('A', 'B') ('C', 'D') ('E', 'F') """ iterator = iter(iterable) while True: yield tuple(iterator.next() for i in xrange(n)) The intention being that if iterator.next() raised a StopIteration, it would propagate out and signal no further values for the tuples generator. Instead, the generator expression results in empty tuples once the iterator has run out, and the tuples generator never runs out. This has since been fixed by replacing the generator expression with a for loop, but if you don't mind my asking, how does this violate the documented usage pattern? Is the recommendation to use an explicit try-except around every call of iterator.next()? Off-topic, does anybody know of a better name for this function? Cheers, Ian From invalid at invalid.invalid Tue May 25 16:04:16 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 25 May 2010 20:04:16 +0000 (UTC) Subject: to prevent reveres engineering for Python References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <87mxvsfzvh.fsf@benfinney.id.au> <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> <4bfc282a$1@dnews.tpgi.com.au> Message-ID: On 2010-05-25, D'Arcy J.M. Cain wrote: > On Wed, 26 May 2010 05:40:43 +1000 > Lie Ryan wrote: > >> That merely gives a false sense of security. If the program is >> decrypted in memory, you can easily make a memory dump to get the >> unencrypted program. If I am a competitor that can make economic >> advantage by cracking your secret sauce, it wouldn't be difficult for >> me to do that. > > Yes, in fact the only people inconvenienced are your paying clients. After several bad experiences over the years, I'm now willing go to quite a bit of effort to avoid using products that require dongles, node-locked licenses or license servers. -- Grant Edwards grant.b.edwards Yow! Hold the MAYO & pass at the COSMIC AWARENESS ... gmail.com From __peter__ at web.de Tue May 25 16:10:38 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 May 2010 22:10:38 +0200 Subject: UnicodeDecodeError having fetch web page References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> <089cbe25-2f32-4b9a-90a5-8be952b602f6@l6g2000vbo.googlegroups.com> Message-ID: Barry wrote: > On 25 Maj, 21:39, Philip Semanchuk wrote: >> On May 25, 2010, at 3:13 PM, Barry wrote: >> >> >> >> > Hi, >> >> > The code below is giving me the error: >> >> > Traceback (most recent call last): >> > File "C:\Users\Administrat?r\Desktop\test.py", line 4, in >> > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: >> > unexpected code byte >> >> > What am i doing wrong? >> >> > Thanks, >> >> > Barry >> >> > request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ >> > baby',headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/ >> > 20071127 Firefox/2.0.0.11'} ) >> >> > response = urllib.request.urlopen(request) >> > html = response.read().decode('utf-8') >> >> Well, for starters you're assuming that the response content is in >> UTF-8. You need to examine the Content-Type header to see what the >> encoding is. If it's not UTF-8, there's your problem. >> >> HTH >> P > > The content type is utf-8: > > Date: Wed, 19 May 2010 19:17:39 GMT > Server: Apache > Cache-Control: private, s-maxage=0, max-age=0, must-revalidate > Content-Language: en > Vary: Accept-Encoding,Cookie > Last-Modified: Wed, 19 May 2010 10:10:34 GMT > Content-Encoding: gzip But the data is gzipped. You have to uncompress it before decoding. Peter From rtw at rtw.me.uk Tue May 25 16:12:18 2010 From: rtw at rtw.me.uk (Rob Williscroft) Date: Tue, 25 May 2010 20:12:18 +0000 (UTC) Subject: UnicodeDecodeError having fetch web page References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Message-ID: Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3 @m21g2000vbr.googlegroups.com in gmane.comp.python.general: > Hi, > > The code below is giving me the error: > > Traceback (most recent call last): > File "C:\Users\Administrat??r\Desktop\test.py", line 4, in > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: > unexpected code byte > > > What am i doing wrong? It may not be you, en.wiktionary.org is sending gzip encoded content back, it seems to do this even if you set the Accept header as in: request.add_header( "Accept", "text/html" ) But maybe I'm not doing it correctly. #encoding: utf-8 import urllib import urllib.request request = urllib.request.Request (url='http://en.wiktionary.org/wiki/baby',headers={'User- Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11'} ) response = urllib.request.urlopen(request) info = response.info() enc = info[ 'Content-Encoding' ] print( "Encoding: " + enc ) from io import BytesIO import gzip buf = BytesIO( response.read() ) unziped = gzip.GzipFile( "wahatever", mode = 'rb', fileobj = buf ) html = unziped.read().decode('utf-8') print( html.encode( "ascii", "backslashreplace" ) ) Rob. From clp2 at rebertia.com Tue May 25 16:14:36 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 25 May 2010 13:14:36 -0700 Subject: Python-list Digest, Vol 80, Issue 223 In-Reply-To: References: Message-ID: On Tue, May 25, 2010 at 1:01 PM, Ian Kelly wrote: > On Tue, May 25, 2010 at 1:10 PM, ? wrote: >> ---------- Forwarded message ---------- >> From:?Terry Reedy >> To:?python-list at python.org >> Date:?Tue, 25 May 2010 13:09:23 -0400 >> Subject:?Re: Generator expressions vs. comprehensions >> On 5/25/2010 3:08 AM, Peter Otten wrote: >>> >>> Michele Simionato wrote: >> >>> I think not turning the list-comp into syntactic sugar for list(genexp) in >>> py3 is a missed opportunity. >> >> Implementing it that way was tried but was much slower than the current implementation. If one uses StopIteration as it is intended to be used (and is so documented), then, I believe, they are equivalent. There was a conscious decision to not slow comprehensions for the many to cater to the very few. > > I thought that I was using it as intended. ?The full function that I > was working with when I ran into the problem was: > > def tuples(iterable, n=2): > ? ?"""Make an iterator that returns elements from iterable in tuples of n. ?If > ? ?the number of elements from the iterable is not a multiple of n, any > ? ?trailing elements will be truncated. > > ? ?tuples('ABCDEFG', n=2) --> ('A', 'B') ('C', 'D') ('E', 'F') > ? ?""" > ? ?iterator = iter(iterable) > ? ?while True: > ? ? ? ?yield tuple(iterator.next() for i in xrange(n)) > > The intention being that if iterator.next() raised a StopIteration, it > would propagate out and signal no further values for the tuples > generator. ?Instead, the generator expression results in empty tuples > once the iterator has run out, and the tuples generator never runs > out. ?This has since been fixed by replacing the generator expression > with a for loop, but if you don't mind my asking, how does this > violate the documented usage pattern? ?Is the recommendation to use an > explicit try-except around every call of iterator.next()? > > Off-topic, does anybody know of a better name for this function? truncating_grouper() ? from itertools import izip def truncating_grouper(n, iterable): "truncating_grouper(3, 'ABCDEFG') --> ABC DEF" args = [iter(iterable)] * n return izip(*args) Implementation adapted from itertools's docs's "Recipes" section. Also, avoid replying to digests in the future; it messes up conversation threading. Cheers, Chris -- http://blog.rebertia.com From philip at semanchuk.com Tue May 25 16:23:19 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 25 May 2010 16:23:19 -0400 Subject: UnicodeDecodeError having fetch web page In-Reply-To: <089cbe25-2f32-4b9a-90a5-8be952b602f6@l6g2000vbo.googlegroups.com> References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> <089cbe25-2f32-4b9a-90a5-8be952b602f6@l6g2000vbo.googlegroups.com> Message-ID: On May 25, 2010, at 4:00 PM, Barry wrote: > On 25 Maj, 21:39, Philip Semanchuk wrote: >> On May 25, 2010, at 3:13 PM, Barry wrote: >> >> >> >>> Hi, >> >>> The code below is giving me the error: >> >>> Traceback (most recent call last): >>> File "C:\Users\Administrat?r\Desktop\test.py", line 4, in >>> UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in >>> position 1: >>> unexpected code byte >> >>> What am i doing wrong? >> >>> Thanks, >> >>> Barry >> >>> request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ >>> baby',headers={'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/ >>> 20071127 Firefox/2.0.0.11'} ) >> >>> response = urllib.request.urlopen(request) >>> html = response.read().decode('utf-8') >> >> Well, for starters you're assuming that the response content is in >> UTF-8. You need to examine the Content-Type header to see what the >> encoding is. If it's not UTF-8, there's your problem. >> >> HTH >> P > > The content type is utf-8: > > Date: Wed, 19 May 2010 19:17:39 GMT > Server: Apache > Cache-Control: private, s-maxage=0, max-age=0, must-revalidate > Content-Language: en > Vary: Accept-Encoding,Cookie > Last-Modified: Wed, 19 May 2010 10:10:34 GMT > Content-Encoding: gzip > Content-Length: 25247 > Content-Type: text/html; charset=utf-8 > X-Cache: HIT from sq61.wikimedia.org > X-Cache-Lookup: HIT from sq61.wikimedia.org:3128 > Age: 520549 > X-Cache: HIT from amssq32.esams.wikimedia.org > X-Cache-Lookup: HIT from amssq32.esams.wikimedia.org:3128 > X-Cache: MISS from amssq37.esams.wikimedia.org > X-Cache-Lookup: MISS from amssq37.esams.wikimedia.org:80 > Connection: close Looks like the content is gzipped. Have you unzipped it? Also, from where are you getting those headers? The server might well send different headers to your browser than to a urllib request. Have you examined the raw content in a hex editor on in the debugger? That would probably answer a lot of questions. > Can it be that the page is corrupt? Of course that's always possible, but personally whenever I have to decide whether bits are being flipped at random or my code is buggy, it's almost always the latter. > If so, how can I make the best of the situation? Depends on what you're trying to accomplish. bye Philip From awilliam at whitemice.org Tue May 25 16:43:34 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 25 May 2010 16:43:34 -0400 Subject: to prevent reveres engineering for Python In-Reply-To: <4bfc282a$1@dnews.tpgi.com.au> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> , , <87mxvsfzvh.fsf@benfinney.id.au> , <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> <4bfc282a$1@dnews.tpgi.com.au> Message-ID: <1274820214.21250.4.camel@linux-yu4c.site> On Wed, 2010-05-26 at 05:40 +1000, Lie Ryan wrote: > On 05/26/10 01:09, Adam Tauno Williams wrote: > > On Tue, 2010-05-25 at 18:49 +0500, Sandy Ydnas wrote: > >> Agree, reveres engineering is crucial issuer for programming > >> language > >> but every executable file can be cracked, for example by using > >> disassembler!!! > >> For each weapon there is antiweapon, so > >> is it possible to prevent reveres engineering when customer have > >> access to executable made from Python code??? > > No. But you can make it hard. > > Store a GPG encrypted blob in your program that contains you secret > > sauce, is decrypted to memory, executed, and then discarded. Setup > > some kind of license manager like dongle or application to perform the > > key management. > That merely gives a false sense of security. There is no "true" sense of security. There is only degrees of obfuscation, hence the first sentence: "No. But you can make it hard" > If the program is decrypted > in memory, you can easily make a memory dump Easily? Really? You vastly over estimate the majority of computer users. If someone who knows how to read the memory of a running process wants your secret sauce - they are going to get it. > to get the unencrypted > program. If I am a competitor that can make economic advantage by > cracking your secret sauce, it wouldn't be difficult for me to do that. True. That is pretty much always true. The only effective solution is to have your app call a web service [or some kind of RPC] to a server where you keep the secret sauce hidden away. From fetchinson at googlemail.com Tue May 25 18:07:17 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 26 May 2010 00:07:17 +0200 Subject: to prevent reveres engineering for Python In-Reply-To: References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <87mxvsfzvh.fsf@benfinney.id.au> <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: >> is it possible to prevent reveres engineering when customer have access >> to executable made from Python code??? The only secure way of protecting your code is if you expose it as a web service or some such. (Yes, people can still crack your web server, but that's nitpicking :)) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From ben+python at benfinney.id.au Tue May 25 18:14:34 2010 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 May 2010 08:14:34 +1000 Subject: to prevent reveres engineering for Python References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com> <87mxvsfzvh.fsf@benfinney.id.au> <4813c607-1079-4aff-b5fa-f5211721a648@y12g2000vbr.googlegroups.com> Message-ID: <87ocg37ho5.fsf@benfinney.id.au> Terry Reedy writes: > On 5/25/2010 9:49 AM, Sandy Ydnas wrote: > > > is it possible to prevent reveres engineering when customer have > > access to executable made from Python code??? > > If there is, it is a trade secrets that you will not be able to > reverse engineer ;-). +1 QOTW -- \ ?The best way to get information on Usenet is not to ask a | `\ question, but to post the wrong information.? ?Aahz | _o__) | Ben Finney From exarkun at twistedmatrix.com Tue May 25 19:03:55 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Tue, 25 May 2010 23:03:55 -0000 Subject: asyncore loop and cmdloop problem In-Reply-To: <0123253e-f628-471b-a343-0ad2588b1a20@m33g2000vbi.googlegroups.com> References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> <1fc2db40-42c3-40d7-ab92-b29c6c039345@u7g2000vbq.googlegroups.com> <0123253e-f628-471b-a343-0ad2588b1a20@m33g2000vbi.googlegroups.com> Message-ID: <20100525230355.1872.1949927971.divmod.xquotient.1@localhost.localdomain> On 04:31 pm, kaklis at gmail.com wrote: >On May 25, 5:47?pm, "kak... at gmail.com" wrote: >>On May 25, 5:23?pm, Michele Simionato >>wrote: >> >> > On May 25, 2:56?pm, "kak... at gmail.com" wrote: >> >> > > Could you please provide me with a simple example how to do this >>with >> > > threads. >> > > I don't know where to put the cmdloop(). >> > > Please help, i' m so confused! >> > > Thank you >> >> > What are you trying to do? Do you really need to use the standard >> > library? Likely what you want to accomplish is already implemented >>in >> > Twisted; I remember there was something like that in their examples >> > directory. >> >>Thank you, >>and sorry for the mistake i did before with my post. >> >>Antonis > >hi again. i installed twisted, but since i m not familiar with it, do >you remember which example you have in mind? >What i want to accomplish is something like "asterisk". while you send >commands from the asterisk cli, at the same time >the underlying protocol sends you notifications to the console. >without exiting the application. >thanks You can find a couple simple examples here: http://twistedmatrix.com/documents/current/core/examples/ Search for "stdin" and "stdio". Jean-Paul From bryanjugglercryptographer at yahoo.com Tue May 25 19:40:26 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 25 May 2010 16:40:26 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: <32c8bb68-75f6-4c80-9c22-36b69e1a5b93@y6g2000pra.googlegroups.com> Raymond Hettinger wrote: > If speed is important, the global lookups can be localized: > > def prttn(m, n, map=itertools.imap, int=int, str=str, range=range): > ? ? return sum(m == sum(map(int, str(x))) for x in range(n)) That's just silly. "If speed is important," we abandon the naive algorithm. -- --Bryan From bryanjugglercryptographer at yahoo.com Tue May 25 21:04:45 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 25 May 2010 18:04:45 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> Message-ID: <498a76fd-4e4b-4d09-86c3-16800a4e3d87@s4g2000prh.googlegroups.com> Jean-Michel Pichavant wrote: > I still don't see "how many positive integers less than n have digits > that sum up to m" makes it a "partition" though if that what prttn > means. Surely because I miss the context. A partition of a positive integer m is an unordered collection of positive integers that sum to m. [1, 1, 2, 5] is a partition of 9. The problem at issue here is not that of counting partitions. My algorithm for our prttn separated out the 'ndsums' sub-problem: Count d-digit ints with digits summing to m. I found a generalization of that problem stated in the /CRC Handbook of Discrete and Combinatorial Mathematics/ (2000 edition, section 2.1) among "counting problems" as: Solutions to x_1 + ... x_n = k 0 <= x_i <= a_i for one or more i Alas, the handbook does not provide a formula or algorithm. It refers to the inclusion/exclusion principle, which I did not see how to turn into an efficient algorithm. My recursive memoizing method for ndsums() was initially a shot in the dark and I was surprised how well it worked. Thinking about it more, I can argue that it is polynomial-time based on the size of the memo- table and the work per entry. My prttn() calls ndsums() once for each digit, so the whole thing is polynomial in the number of digits. -- --Bryan From ptmcg at austin.rr.com Tue May 25 21:45:59 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 25 May 2010 18:45:59 -0700 (PDT) Subject: Need some Python 3 help Message-ID: I was teetering on the brink of releasing Pyparsing 1.5.3 (with some nice new examples and goodies), when I saw that I had recently introduced a bug in the Python 3 compatible version. Here is the stacktrace as reported on SF: Traceback (most recent call last): File "testcase.py", line 11, in result = exp.parseFile("./pyparsing_py3.py") File "/data/projekte/parsing/pyparsing/pyparsing_py3.py", line 1426, in parseFile return self.parseString(file_contents, parseAll) File "/data/projekte/parsing/pyparsing/pyparsing_py3.py", line 1068, in parseString loc, tokens = self._parse( instring, 0 ) File "/data/projekte/parsing/pyparsing/pyparsing_py3.py", line 935, in _parseNoCache preloc = self.preParse( instring, loc ) File "/data/projekte/parsing/pyparsing/pyparsing_py3.py", line 893, in preParse while loc < instrlen and instring[loc] in wt: TypeError: 'in ' requires string as left operand, not int In this section of code, instring is a string, loc is an int, and wt is a string. Any clues why instring[loc] would be evaluating as int? (I am unfortunately dependent on the kindness of strangers when it comes to testing my Python 3 code, as I don't have a Py3 environment installed.) Thanks, -- Paul From bryanjugglercryptographer at yahoo.com Tue May 25 21:56:53 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 25 May 2010 18:56:53 -0700 (PDT) Subject: Need some Python 3 help References: Message-ID: Paul McGuire wrote: [...] > while loc < instrlen and instring[loc] in wt: > TypeError: 'in ' requires string as left operand, not int > > In this section of code, instring is a string, loc is an int, In Python 3, lots of things that used to return str now return bytes, and the elements of a bytes object are ints. Something to check. -- --Bryan From benjamin at python.org Tue May 25 21:58:47 2010 From: benjamin at python.org (Benjamin Peterson) Date: Wed, 26 May 2010 01:58:47 +0000 (UTC) Subject: Need some Python 3 help References: Message-ID: Paul McGuire austin.rr.com> writes: > In this section of code, instring is a string, loc is an int, and wt > is a string. Any clues why instring[loc] would be evaluating as int? > (I am unfortunately dependent on the kindness of strangers when it > comes to testing my Python 3 code, as I don't have a Py3 environment > installed.) Indexing bytes in Python 3 gives an integer. From ptmcg at austin.rr.com Tue May 25 22:04:07 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 25 May 2010 19:04:07 -0700 (PDT) Subject: Need some Python 3 help References: Message-ID: <97dbf3c7-e2f5-4237-8a7b-a04cf3a7f0ee@o15g2000vbb.googlegroups.com> On May 25, 8:58?pm, Benjamin Peterson wrote: > Paul McGuire austin.rr.com> writes: > > > In this section of code, instring is a string, loc is an int, and wt > > is a string. ?Any clues why instring[loc] would be evaluating as int? > > (I am unfortunately dependent on the kindness of strangers when it > > comes to testing my Python 3 code, as I don't have a Py3 environment > > installed.) > > Indexing bytes in Python 3 gives an integer. Hrmm, I had a sneaking hunch this might be the issue. But then I don't know how this code *ever* worked in Python 3, as it is chock full of indexed references into the string being parsed. And yet, I've had other folks test and confirm that pyparsing_py3 *does* work on Python 3. It is a puzzle. -- Paul From bryanjugglercryptographer at yahoo.com Tue May 25 22:46:37 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Tue, 25 May 2010 19:46:37 -0700 (PDT) Subject: Need some Python 3 help References: <97dbf3c7-e2f5-4237-8a7b-a04cf3a7f0ee@o15g2000vbb.googlegroups.com> Message-ID: Paul McGuire wrote: > Hrmm, I had a sneaking hunch this might be the issue. ?But then I > don't know how this code *ever* worked in Python 3, as it is chock > full of indexed references into the string being parsed. ?And yet, > I've had other folks test and confirm that pyparsing_py3 *does* work > on Python 3. ?It is a puzzle. I suspect in most cases you use bytes consistently. You got the exception from: instring[loc] in wt If instring and wt are both bytes, that's fine. If they're both str, also fine. If one is bytes and one is str, exception. -- --Bryan From amyoldwatch1800 at gmail.com Tue May 25 23:08:44 2010 From: amyoldwatch1800 at gmail.com (amy) Date: Wed, 26 May 2010 11:08:44 +0800 Subject: Good deal for Cartier Watches online Message-ID: Good deal for Cartier Watches online It is amazing, the Ballon Bleu de Cartier Replica Watches at http://www.swizwatch.com/ are perfect, cheap and high quality. Ballon Bleu de Cartier Watches Collection: http://www.swizwatch.com/ballon-bleu-de-cartier-replica-watches.html Replica Cartier Ballon Bleu de Cartier Two-Tone Ladies Watch W69007Z3 http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Two-Tone-Ladies-Watch-W69007Z3-.html Replica Cartier Ballon Bleu de Cartier 18K Yellow Gold Leather Strap Mens Watch W6900551 http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-18K-Yellow-Gold-Leather-Strap-Mens-Watch-W6900551.html Replica Cartier Ballon Bleu de Cartier Two-Tone Mens Watch W69009Z3 http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Two-Tone-Mens-Watch-W69009Z3.html Replica Cartier Ballon Bleu de Cartier 18K Rose Gold Mens Watch W69006Z2 http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-18K-Rose-Gold-Mens-Watch-W69006Z2.html Replica Cartier Ballon Bleu de Cartier Mens Gold Watch W69013Z2 http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Mens-Gold-Watch-W69013Z2.html Buy more Cartier replica watches at low price by click: http://www.swizwatch.com/cartier-replica-watches.html From godson.g at gmail.com Tue May 25 23:22:48 2010 From: godson.g at gmail.com (Godson Gera) Date: Wed, 26 May 2010 08:52:48 +0530 Subject: [wxPython-users] wxPython 2.8.11.0 release In-Reply-To: <4BFB0E05.1090101@alldunn.com> References: <4BFB0E05.1090101@alldunn.com> Message-ID: On Tue, May 25, 2010 at 5:08 AM, Robin Dunn wrote: > Announcing > ---------- > > The 2.8.11.0 release of wxPython is now available for download at > http://wxpython.org/download.php. This release adds Python 2.7 builds, > PySlices, new pubsub implementation, lots of updates to AGW, and lots > of bugs fixed. A summary of changes is listed below and also at > http://wxpython.org/recentchanges.php. > > Thanks for the great work ! -- Thanks & Regards, Godson Gera IVR India -------------- next part -------------- An HTML attachment was scrubbed... URL: From hnassrat at gmail.com Tue May 25 23:41:08 2010 From: hnassrat at gmail.com (Pykler) Date: Tue, 25 May 2010 20:41:08 -0700 (PDT) Subject: PEP 3119 ABC - And how I learned to love the Abstract Bomb References: Message-ID: <50455a03-4c47-47f3-9d46-8ba2e8629dd4@w3g2000vbd.googlegroups.com> On May 13, 9:30?am, Lawrence D'Oliveiro wrote: > You?re looking at it wrong. If you want to force people to do things in a > certain way, use Java. Python is about enabling things, not forcing them. LoL :-) > Don?t use subclassing. Instead, let the caller pass you a duck-typed object > that implements the methods you need. I totally agree. in my code I do not force the object to be an instance of a subclass of the ABC, they certainly can duck-type as they please. The ABC is simply there to give them an idea of what methods they need to implement. It is kind of self documenting structure if you may. However, I had this problem described earlier which does not let me complete this self documenting structure without adding a thorough doc-string explaining that they still need to implement one or two more methods. From draco.parvus at gmail.com Wed May 26 00:02:03 2010 From: draco.parvus at gmail.com (draco parvus) Date: Tue, 25 May 2010 21:02:03 -0700 (PDT) Subject: speed up a numpy code with huge array References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> Message-ID: <1c498c3f-a635-4799-803f-9c62556bf50b@j36g2000prj.googlegroups.com> On May 26, 7:05?am, Alexzive wrote: > Hello Pythonguys! > > is there a way to improve the performance of the attached code ? it > takes about 5 h on a dual-core (using only one core) when len(V) > ~1MIL. V is an array which is supposed to store all the volumes of > tetrahedral elements of a grid whose coord. are stored in NN (accessed > trough the list of tetraelements --> EL) > > Thanks in advance! > Alex > > #### > print 'start ' + nameodb > #path = '/windows/D/SIM-MM/3D/E_ortho/' + nameodb + '.odb' > path = pt + nameodb + '.odb' > odb = openOdb(path) > > N = odb.rootAssembly.instances['PART-1-1'].nodes > if loadV==1: > ? pathV=pt+vtet > ? V=numpy.loadtxt(pathV) > ? VTOT = V[0] > ? L3 = V[1] > ? print 'using ' + vtet > else: > ? NN=[] > ? B=[0,0,0,0] > ? for i in range(len(N)): > ? ? ? ? B[0] = N[i].label > ? ? ? ? B[1] = N[i].coordinates[0] > ? ? ? ? B[2] = N[i].coordinates[1] > ? ? ? ? B[3] = N[i].coordinates[2] > ? ? ? ? NN = append(NN,B) > > ? NN=NN.reshape(-1,4) > ? EL = odb.rootAssembly.instances['PART-1-1'].elements > > ? L1 = max(NN[:,1])-min(NN[:,1]) > ? L2 = max(NN[:,2])-min(NN[:,2]) > ? L3 = max(NN[:,3])-min(NN[:,3]) > ? VTOT=L1*L2*L3 > ? print 'VTOT: [mm?]' + str(VTOT) > > ? V = array([]) > > ? print 'calculating new Vtet ' > ? V = range(len(EL)+2) > ? V[0] = VTOT > ? V[1] = L3 > ? for j in range(0,len(EL)): > ? ? ? ? Va = EL[j].connectivity[0] > ? ? ? ? Vb = EL[j].connectivity[1] > ? ? ? ? Vc = EL[j].connectivity[2] > ? ? ? ? Vd = EL[j].connectivity[3] > ? ? ? ? ix = where(NN[:,0] == Va) > ? ? ? ? Xa = NN[ix,1][0][0] > ? ? ? ? Ya = NN[ix,2][0][0] > ? ? ? ? Za = NN[ix,3][0][0] > ? ? ? ? ix = where(NN[:,0] == Vb) > ? ? ? ? Xb = NN[ix,1][0][0] > ? ? ? ? Yb = NN[ix,2][0][0] > ? ? ? ? Zb = NN[ix,3][0][0] > ? ? ? ? ix = where(NN[:,0] == Vc) > ? ? ? ? Xc = NN[ix,1][0][0] > ? ? ? ? Yc = NN[ix,2][0][0] > ? ? ? ? Zc = NN[ix,3][0][0] > ? ? ? ? ix = where(NN[:,0] == Vd) > ? ? ? ? Xd = NN[ix,1][0][0] > ? ? ? ? Yd = NN[ix,2][0][0] > ? ? ? ? Zd = NN[ix,3][0][0] > ? ? ? ? a = ?[Xa,Ya,Za] > ? ? ? ? b = ?[Xb,Yb,Zb] > ? ? ? ? c = ?[Xc,Yc,Zc] > ? ? ? ? d = ?[Xd,Yd,Zd] > ? ? ? ? aa = numpy.diff([b,a],axis=0)[0] > ? ? ? ? bb = numpy.diff([c,b],axis=0)[0] > ? ? ? ? cc = numpy.diff([d,c],axis=0)[0] > ? ? ? ? D=array([aa,bb,cc]) > ? ? ? ? det=numpy.linalg.det(D) > ? ? ? ? V[j+2] = abs(det)/6 > ? pathV = pt + vtet > ? savetxt(pathV, V, fmt='%.3e') > ### Main problem you've got is quadratic behaviour. For each vertex of each of your million tets, you go through the entire node list to find its coordinates. You should use a dict instead, such as: allnodes = {} for node in N: allnodes[node.label] = node.coordinates And later, instead of using numpy.where, directly use: Xa, Ya, Za = allnodes[Va] # with Va = EL[j].connectivity[0] ... Should speed things up a bit. But manipulating odb files is never very fast. d. From stefan_ml at behnel.de Wed May 26 02:14:21 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 26 May 2010 08:14:21 +0200 Subject: speed up a numpy code with huge array In-Reply-To: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> Message-ID: Alexzive, 25.05.2010 21:05: > is there a way to improve the performance of the attached code ? it > takes about 5 h on a dual-core (using only one core) when len(V) > ~1MIL. V is an array which is supposed to store all the volumes of > tetrahedral elements of a grid whose coord. are stored in NN (accessed > trough the list of tetraelements --> EL) Consider using Cython for your algorithm. It has direct support for NumPy arrays and translates to fast C code. Stefan From sjmachin at lexicon.net Wed May 26 03:04:23 2010 From: sjmachin at lexicon.net (John Machin) Date: Wed, 26 May 2010 07:04:23 +0000 (UTC) Subject: UnicodeDecodeError having fetch web page References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Message-ID: Rob Williscroft rtw.me.uk> writes: > > Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3 > @m21g2000vbr.googlegroups.com in gmane.comp.python.general: > > > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: > > unexpected code byte > > It may not be you, en.wiktionary.org is sending gzip > encoded content back, It sure is; here's where the offending 0x8b comes from: """ID1 (IDentification 1) ID2 (IDentification 2) These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213), to identify the file as being in gzip format.""" (from http://www.faqs.org/rfcs/rfc1952.html) From bryanjugglercryptographer at yahoo.com Wed May 26 04:03:13 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Wed, 26 May 2010 01:03:13 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> <498a76fd-4e4b-4d09-86c3-16800a4e3d87@s4g2000prh.googlegroups.com> Message-ID: <487ba222-ea1d-4049-b520-1fab5df3c318@n37g2000prc.googlegroups.com> I wrote: > My prttn() calls ndsums() once for each > digit, so the whole thing is polynomial in the number of digits. Correction: my prttn() function calls ndsums() at most 9 times per digit of n. That still provides run time polynomial in the length of the input. -- --Bryan From kaklis at gmail.com Wed May 26 04:29:31 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Wed, 26 May 2010 01:29:31 -0700 (PDT) Subject: asyncore loop and cmdloop problem References: <30969625-745c-45e8-ad19-580569bb5f76@o39g2000vbd.googlegroups.com> <578f1268-836a-4eec-97cf-fb70e330f972@c22g2000vbb.googlegroups.com> <97cc11d7-8bd0-4c79-a1b0-3fa9f022ef1e@a20g2000vbc.googlegroups.com> <44d0d4aa-57f6-4ea6-bf3c-da896fbe53a6@k31g2000vbu.googlegroups.com> <1fc2db40-42c3-40d7-ab92-b29c6c039345@u7g2000vbq.googlegroups.com> <0123253e-f628-471b-a343-0ad2588b1a20@m33g2000vbi.googlegroups.com> Message-ID: On May 26, 2:03?am, exar... at twistedmatrix.com wrote: > On 04:31 pm, kak... at gmail.com wrote: > > > > >On May 25, 5:47?pm, "kak... at gmail.com" wrote: > >>On May 25, 5:23?pm, Michele Simionato > >>wrote: > > >> > On May 25, 2:56?pm, "kak... at gmail.com" wrote: > > >> > > Could you please provide me with a simple example how to do this > >>with > >> > > threads. > >> > > I don't know where to put the cmdloop(). > >> > > Please help, i' m so confused! > >> > > Thank you > > >> > What are you trying to do? Do you really need to use the standard > >> > library? Likely what you want to accomplish is already implemented > >>in > >> > Twisted; I remember there was something like that in their examples > >> > directory. > > >>Thank you, > >>and sorry for the mistake i did before with my post. > > >>Antonis > > >hi again. i installed twisted, but since i m not familiar with it, do > >you remember which example you have in mind? > >What i want to accomplish is something like "asterisk". while you send > >commands from the asterisk cli, at the same time > >the underlying protocol sends you notifications to the console. > >without exiting the application. > >thanks > > You can find a couple simple examples here: > > ?http://twistedmatrix.com/documents/current/core/examples/ > > Search for "stdin" and "stdio". > > Jean-Paul Thank you so much, i'll check them!!! Antonis From bryanjugglercryptographer at yahoo.com Wed May 26 04:30:22 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Wed, 26 May 2010 01:30:22 -0700 (PDT) Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <85l509Fpe7U1@mid.individual.net> <6025dfa5-bc54-412d-98e2-71d2ad4540a6@11g2000prv.googlegroups.com> <041e63e5-8d83-4286-ae2d-7c38f18d8139@s13g2000prc.googlegroups.com> Message-ID: <53122f59-1e37-4ec3-9106-dd129577276f@q39g2000prh.googlegroups.com> I wrote: > > I came up with a recursive memo-izing algorithm that > > handles 100-digit n's. Oops. I missed Richard Thomas's post. He posted the same algorithm a couple days before. -- --Bryan From lex at from.hell Wed May 26 05:21:32 2010 From: lex at from.hell (Lex Lebedeff) Date: Wed, 26 May 2010 09:21:32 +0000 (UTC) Subject: Kohonen neural network Message-ID: Hello! Has anyone tried to build an implementation of subject in Python? Any help is appreciated! --- news://freenews.netfront.net/ - complaints: news at netfront.net --- From durumdara at gmail.com Wed May 26 05:30:41 2010 From: durumdara at gmail.com (Durumdara) Date: Wed, 26 May 2010 11:30:41 +0200 Subject: MySQLDB - server has gone on blob insertion... Message-ID: Hi! I want to test my program that coded into PGSQL, and PySQLite. With these DBs I have problem on many blob deletion (2 hours) and compact/vacuum (1 hours)... So I'm trying to port my program, and before that making a test to check, which time needs to delete 1 GB of blobs. I installed MySQLDb from the exe (Py2.6, from stackoverflow version), set all parameters, etc. import MySQLdb conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "", db = "db") cursor = conn.cursor () cursor.execute ("SELECT VERSION()") cursor.execute('delete from blobs;') s = time.time() for i in range(200): k = str(i) xbuffer = chr(65 + (i % 26)) xbuffer = xbuffer * 1024 * 1024 b = MySQLdb.escape_string(xbuffer) print len(b) cursor.execute('''insert into blobs (blob_id, file_id, size, ext, data) values (%s, %s, %s, %s, %s)''', (i, i, -1, 'org', b)) conn.commit() e = time.time() t = e - s print t sys.exit() When I tried to start this, I got error: _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') I read that server have some parameter, that limit the Query length. Then I decreased the blob size to 1M, and then it is working. But: I can insert 800k-1,9 MB blobs. I tried to set this parameter, but nothing changed. My.ini: # SERVER SECTION # ---------------------------------------------------------------------- # # The following options will be read by the MySQL Server. Make sure that # you have installed the server correctly (see above) so it reads this # file. # [mysqld] max_allowed_packet = 16M # The TCP/IP Port the MySQL Server will listen on port=3306 What is the problem? What I do wrong? Thanks for your help: dd -------------- next part -------------- An HTML attachment was scrubbed... URL: From tom.browder at gmail.com Wed May 26 07:26:01 2010 From: tom.browder at gmail.com (Tom) Date: Wed, 26 May 2010 04:26:01 -0700 (PDT) Subject: Vote to Add Python Package "pubsub" to the Python Standard Library Message-ID: <6b9d2898-4166-40b4-9016-dc55dee77d00@q33g2000vbt.googlegroups.com> I vote for adding the Python package "pubsub" to the Python standard library. It has recently been added to wxpython (replacing the old wx.lib.pubsub package), but it has application to non-gui programs as well. For more information see: . From nilly16 at yahoo.com Wed May 26 07:36:50 2010 From: nilly16 at yahoo.com (Jimbo) Date: Wed, 26 May 2010 04:36:50 -0700 (PDT) Subject: [WxPython] Advice on Temperature Application Method & Structure Message-ID: <1baa040f-0a2c-476a-8b78-26a599452895@k17g2000pro.googlegroups.com> Hello I have made a simple application using WxPython that is a temperature converter. This is my first application made in WxPython, the only other apps I have made were in Win32 c++ so I am new to widgets in general. I am looking for advice & criticism on when you should use classes in GUI widget apps (& where) & other general advice: - Structure of a wxPython script/code - Should every window be in its own class? - whats the best way to refer to a control (by window name or ID) - Should a group of controls that are related be in a class For example should I make a Celsius class that handles the celsius editbox, static & button & the button action function(convert_to_fahrenheit())? - Errors, bad things I have done in my code - When & why use a Validator?? Temperature Converter Application: """ Temperature Application Description: This application uses WxPython to create a simple windows app to convert temperature from celsius to fahrenheit & visa versa. Looking for advice on everything to do with wxPython: For example: - Structure of a wxPython script/code - Should every window be in its own class? - whats the best way to refer to a control (by window name or ID) - Should a ground of controls that are related be in a class For example should I make a Celsius class that handles the celsius editbox, static & button? - Errors, bad things I have done in my code - When & why use a Validator?? """ import wx ## Constants ## ID_FAHREN = 1 ID_CELSIUS = 2 class Controller(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self,parent,id,"Temperature Converter", size=(247,186)) # Create Controls panel = wx.Panel(self) self.create_controls( panel, wx.Validator() ) self.fah_edit.SetValue(str(32)) self.cel_edit.SetValue(str(0)) # Define actions self.Bind_Events() def create_controls(self, panel, val): """ Create all the controls we will need for the temperature conversion """ self.bmp_static = wx.StaticText(panel, -1, "Bitmap pic will be here", (10,5), (150,40)) self.fah_static = wx.StaticText(panel, -1, "Fahrenheit: ", (10,70), (-1,-1)) self.cel_static = wx.StaticText(panel, -1,"Celsius: ", (140,70), (-1,-1)) self.fah_edit = wx.TextCtrl(panel,ID_FAHREN, pos=(70,65), size=(40,25), style=0, validator=val, name='a') self.cel_edit = wx.TextCtrl(panel,ID_CELSIUS, pos=(180,65), size=(40,25), style=0, validator=val, name='b') self.to_fah_button = wx.Button(panel,label="To Fahrenheit", pos=(145,95),size=(80,25)) self.to_cel_button = wx.Button(panel,label="To Celsius", pos=(35,95),size=(80,25)) self.exit_button = wx.Button(panel,label="Exit",pos=(157,123), size=(70,25)) def Bind_Events(self): """ Bind application events to class functions """ self.Bind(wx.EVT_BUTTON,self.close_button, self.exit_button) self.Bind(wx.EVT_CLOSE,self.close_window) self.Bind(wx.EVT_BUTTON,self.convert_to_celsius, self.to_fah_button) self.Bind(wx.EVT_BUTTON,self.convert_to_fahrenheit, self.to_cel_button) def close_button(self, event): self.Close(True) def close_window(self, event): self.Destroy() def error_check(self, string): """ Check for valid input in editboxes. Valid input includes float & integer values only """ if string.isalpha() or len(string) <= 0: return False return True def convert_to_fahrenheit(self, event): """ Convert the value in fahrenheit window to celsius & display in our window/edit box """ # Algorithm # - Get number from fahrenheit editbox # - convert fahrenheit value to celsius # - change value in Celsius Window to # Step 1: fahren_value = self.fah_edit.GetValue() if not self.error_check( fahren_value ): self.fah_edit.SetValue( "NA" ) return # Step 2: value = (float(fahren_value) - 32) * 5/9 # Step 3: self.cel_edit.SetValue( str(value) ) def convert_to_celsius(self, event): """ Convert the value in celcius window/editbox to fahrenheit & display in our window/editbox """ # Algorithm # - Get number from celsius editbox # - convert celsius value to fahrenheit # - change value in fahrenheit Window # Step 1: celsius_value = self.cel_edit.GetValue() if not self.error_check( celsius_value ): self.cel_edit.SetValue( "NA" ) return # Step 2: value = (float( celsius_value ) * 9/5) + 32 # Step 3: self.fah_edit.SetValue( str(value) ) if __name__ == "__main__": app = wx.PySimpleApp() frame = Controller(parent=None,id=-1) frame.Show() app.MainLoop() From zasaconsulting at gmail.com Wed May 26 07:43:24 2010 From: zasaconsulting at gmail.com (Alexzive) Date: Wed, 26 May 2010 04:43:24 -0700 (PDT) Subject: speed up a numpy code with huge array References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> Message-ID: <704eeb6e-4939-43f0-986e-42460c88b738@k31g2000vbu.googlegroups.com> thank you all for the tips. I 'll try them soon. I also notice another bottleneck, when python tries to access some array data stored in the odb files (---> in text below), even before starting the algoritm: ### EPS_nodes = range(len(frames)) for f in frames: ... sum = 0 ---> UN = F[f].fieldOutputs['U'].getSubset(region=TOP).values <--- ... EPS_nodes[f] = UN[10].data[Scomp-1]/L3 ### unfortunately I don't have time to learn cython. Using dictionaries sounds promising. Thanks! Alex On May 26, 8:14?am, Stefan Behnel wrote: > Alexzive, 25.05.2010 21:05: > > > is there a way to improve the performance of the attached code ? it > > takes about 5 h on a dual-core (using only one core) when len(V) > > ~1MIL. V is an array which is supposed to store all the volumes of > > tetrahedral elements of a grid whose coord. are stored in NN (accessed > > trough the list of tetraelements --> ?EL) > > Consider using Cython for your algorithm. It has direct support for NumPy > arrays and translates to fast C code. > > Stefan From zasaconsulting at gmail.com Wed May 26 07:48:00 2010 From: zasaconsulting at gmail.com (Alexzive) Date: Wed, 26 May 2010 04:48:00 -0700 (PDT) Subject: speed up a numpy code with huge array References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> <704eeb6e-4939-43f0-986e-42460c88b738@k31g2000vbu.googlegroups.com> Message-ID: sorry it was just bullshit what I wrote about the second bottleneck, it seemed to hang up but it was just me forgetting to double-enter during debugging after "for cycle". On May 26, 1:43?pm, Alexzive wrote: > thank you all for the tips. > I 'll try them soon. > > I also notice another bottleneck, when python tries to access some > array data stored in the odb files (---> in text below), even before > starting the algoritm: > > ### > EPS_nodes = range(len(frames)) > for f in frames: > ... ? ? sum = 0 > ---> ? ?UN = F[f].fieldOutputs['U'].getSubset(region=TOP).values <--- > ... ? ? EPS_nodes[f] = UN[10].data[Scomp-1]/L3 > > ### > > unfortunately I don't have time to learn cython. Using dictionaries > sounds promising. > Thanks! > Alex > > On May 26, 8:14?am, Stefan Behnel wrote: > > > > > Alexzive, 25.05.2010 21:05: > > > > is there a way to improve the performance of the attached code ? it > > > takes about 5 h on a dual-core (using only one core) when len(V) > > > ~1MIL. V is an array which is supposed to store all the volumes of > > > tetrahedral elements of a grid whose coord. are stored in NN (accessed > > > trough the list of tetraelements --> ?EL) > > > Consider using Cython for your algorithm. It has direct support for NumPy > > arrays and translates to fast C code. > > > Stefan From wuwei23 at gmail.com Wed May 26 08:26:56 2010 From: wuwei23 at gmail.com (alex23) Date: Wed, 26 May 2010 05:26:56 -0700 (PDT) Subject: Kohonen neural network References: Message-ID: <260cd874-fe51-4bdd-b112-f64ff7ef3050@a27g2000prj.googlegroups.com> On May 26, 7:21?pm, Lex Lebedeff wrote: > Has anyone tried to build an implementation of subject in Python? > Any help is appreciated! http://www.dia.fi.upm.es/~jamartin/download.htm Seriously, though, any reason why you couldn't just type "kohonen neural network python" into Google? You would've found it a lot easier to wade through the results before your question & it's many mirrors. It would've been the 2nd entry, immediately after the wikipedia article on Kohonen SOMs. From victorsubervi at gmail.com Wed May 26 08:29:21 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 26 May 2010 08:29:21 -0400 Subject: A Quick MySQL Question In-Reply-To: References: Message-ID: On Wed, May 26, 2010 at 2:42 AM, Dennis Lee Bieber wrote: > I was, for that example, assuming that the user input "values" was > being used in a select query and hence wrapped it with wildcard markers > so that the phrase would match anywhere in the data field. > In said thread you wrote the following: clauses = [] for nm in nameList: clauses.append(nm + " like %s") where = " and ".join(clauses) #could be " or " valueList = ["%%s%" % vl for vl in valueList] SQL = "select * from table where " + where cur.execute(SQL, valueList) Ok, so let's assume we have a name list of: ["name1", "name2", "name3"] and a value list of: ["value1", "value2", "value3"] Therefore: clauses = ["name1 like %s", "name2 like %s", "name3 like %s"] where = "name1 like %s and name2 like %s and name3 like %s" SQL = "select * from table where name1 like %s and name2 like %s and name3 like %s" valueList = ("%value1", "%value2", "%value3") cur.execute("select * from table where name1 like %s and name2 like %s and name3 like %s", ("%value1", "%value2", "%value3")) Why do the values have that extra "%"? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Wed May 26 08:34:06 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 26 May 2010 08:34:06 -0400 Subject: [WxPython] Advice on Temperature Application Method & Structure In-Reply-To: <1baa040f-0a2c-476a-8b78-26a599452895@k17g2000pro.googlegroups.com> References: <1baa040f-0a2c-476a-8b78-26a599452895@k17g2000pro.googlegroups.com> Message-ID: On May 26, 2010, at 7:36 AM, Jimbo wrote: > Hello > > I have made a simple application using WxPython that is a temperature > converter. This is my first application made in WxPython, the only > other apps I have made were in Win32 c++ so I am new to widgets in > general. > > > I am looking for advice & criticism on when you should use classes in > GUI widget apps (& where) & other general advice: Hi Jimbo, The first piece of advice I have is to post on the wxPython mailing list where you'll reach a more focused audience. > - Should every window be in its own class? That works for me. > - whats the best way to refer to a control (by window name or ID) ID. Uniqueness is not enforced among window names. > - Should a group of controls that are related be in a class > For example should I make a Celsius class that handles the > celsius editbox, static & button & the button action > function(convert_to_fahrenheit())? When and where to use a class is not wxPython-specific, and is partly a matter of taste. For instance, I would not put a convert_to_fahrenheit() function inside a class, because it doesn't need any class-related info. Make it a module-level function and it will be easier to re-use. I wouldn't do what you suggested (grouping controls into a class) because it doesn't seem to serve any purpose other than documentation, which can be accomplished just as well with a comment. Ask yourself this -- what problem would grouping them into a class solve? > - When & why use a Validator?? I'm ambivalent about Validators. Before I used them I had all of my init code in one place, and in the on_ok_clicked() event I had all of my teardown code and it was easy to see what control got assigned to which variable. Now that information is scattered through a bunch of classes which are fairly verbose. Also, Validators are great for validating individual controls, but not so great with groups. E.g. when control A can only be blank if B is too. A & B have to know about one another and the Validator starts to get messy. OTOH it's nice to group the code that knows everything that needs to be know about the relationship between a control and the variable to which is assigned. We call the validator when the control loses focus (to let users know if they've entered something invalid) and when OK is clicked. It's nice to be able to simply call the validators in that case. Good luck with your app Philip > Temperature Converter Application: > """ > Temperature Application > > Description: This application uses WxPython to create a simple > windows app to convert temperature from celsius > to fahrenheit & visa versa. > > Looking for advice on everything to do with wxPython: > For example: > - Structure of a wxPython script/code > - Should every window be in its own class? > - whats the best way to refer to a control (by window name or ID) > - Should a ground of controls that are related be in a class > For example should I make a Celsius class that handles the > celsius editbox, static & button? > - Errors, bad things I have done in my code > - When & why use a Validator?? > """ > > > import wx > > > ## Constants ## > ID_FAHREN = 1 > ID_CELSIUS = 2 > > > class Controller(wx.Frame): > > > def __init__(self, parent, id): > > wx.Frame.__init__(self,parent,id,"Temperature Converter", > size=(247,186)) > > # Create Controls > panel = wx.Panel(self) > self.create_controls( panel, wx.Validator() ) > > self.fah_edit.SetValue(str(32)) > self.cel_edit.SetValue(str(0)) > > # Define actions > self.Bind_Events() > > > def create_controls(self, panel, val): > """ Create all the controls we will need for the temperature > conversion """ > > self.bmp_static = wx.StaticText(panel, -1, "Bitmap pic will be here", > (10,5), (150,40)) > > self.fah_static = wx.StaticText(panel, -1, "Fahrenheit: ", > (10,70), (-1,-1)) > > self.cel_static = wx.StaticText(panel, -1,"Celsius: ", > (140,70), (-1,-1)) > > self.fah_edit = wx.TextCtrl(panel,ID_FAHREN, pos=(70,65), > size=(40,25), style=0, validator=val, > name='a') > > self.cel_edit = wx.TextCtrl(panel,ID_CELSIUS, pos=(180,65), > size=(40,25), style=0, validator=val, > name='b') > > self.to_fah_button = wx.Button(panel,label="To Fahrenheit", > pos=(145,95),size=(80,25)) > > self.to_cel_button = wx.Button(panel,label="To Celsius", > pos=(35,95),size=(80,25)) > > self.exit_button = wx.Button(panel,label="Exit",pos=(157,123), > size=(70,25)) > > > > def Bind_Events(self): > """ Bind application events to class functions """ > > self.Bind(wx.EVT_BUTTON,self.close_button, > self.exit_button) > > self.Bind(wx.EVT_CLOSE,self.close_window) > > self.Bind(wx.EVT_BUTTON,self.convert_to_celsius, > self.to_fah_button) > > self.Bind(wx.EVT_BUTTON,self.convert_to_fahrenheit, > self.to_cel_button) > > > def close_button(self, event): > > self.Close(True) > > > def close_window(self, event): > > self.Destroy() > > > def error_check(self, string): > """ Check for valid input in editboxes. Valid input > includes float & integer values only """ > > if string.isalpha() or len(string) <= 0: > > return False > > return True > > > def convert_to_fahrenheit(self, event): > """ Convert the value in fahrenheit window to celsius & > display in our window/edit box """ > > # Algorithm > # - Get number from fahrenheit editbox > # - convert fahrenheit value to celsius > # - change value in Celsius Window to > > # Step 1: > fahren_value = self.fah_edit.GetValue() > > if not self.error_check( fahren_value ): > > self.fah_edit.SetValue( "NA" ) > return > > # Step 2: > value = (float(fahren_value) - 32) * 5/9 > > # Step 3: > self.cel_edit.SetValue( str(value) ) > > > def convert_to_celsius(self, event): > """ Convert the value in celcius window/editbox to > fahrenheit & display in our window/editbox """ > > # Algorithm > # - Get number from celsius editbox > # - convert celsius value to fahrenheit > # - change value in fahrenheit Window > > # Step 1: > celsius_value = self.cel_edit.GetValue() > > if not self.error_check( celsius_value ): > > self.cel_edit.SetValue( "NA" ) > return > > # Step 2: > value = (float( celsius_value ) * 9/5) + 32 > > # Step 3: > self.fah_edit.SetValue( str(value) ) > > > > if __name__ == "__main__": > > app = wx.PySimpleApp() > > frame = Controller(parent=None,id=-1) > frame.Show() > app.MainLoop() > -- > http://mail.python.org/mailman/listinfo/python-list From r3831110n at gmail.com Wed May 26 08:49:37 2010 From: r3831110n at gmail.com (Rebel Lion) Date: Wed, 26 May 2010 05:49:37 -0700 (PDT) Subject: Inheritable Slots Metaclass Message-ID: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> I made a metaclass to inherit __slots__ automatically. I think this feature should be included in builtin object's metaclass. You can now write: class Foo(object): __metaclass__ = SlotMetaclass @slot def foo(): pass class Bar(Foo): @slot def bar(): pass foo = Foo() foo.foo = 1 bar = Bar() bar.bar = 1 bar.foo = 1 try: bar.baz = 1 # this should fall except AttributeError, e: print 'yeah', e Instead of class Foo(object): __slots__ = ['foo'] class Bar(Foo) __slots__ = ['foo', 'bar'] Please discuss the pros & cons for this feature. Here is the metaclass: class slot(object): """Slot Decorator""" def __init__(self, func): pass class SlotMetaclass(type): """Inheritable Slots Metaclass""" def __new__(cls, name, bases, attrs): # make a normal class, and get its attributes to decide which ones are slots tmpcls = type.__new__(cls, name, bases, attrs) slots = [] for k in dir(tmpcls): v = getattr(tmpcls, k) if isinstance(v, slot): slots.append(k) # clean up del tmpcls for x in slots: del attrs[x] # create the real class with __slots__ attrs['__slots__'] = slots return type.__new__(cls, name, bases, attrs) From steveo at syslang.net Wed May 26 08:52:44 2010 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 26 May 2010 08:52:44 -0400 Subject: Looking for matlab to python converter. Message-ID: <4BFD199C.3050103@syslang.net> I found something on sourceforge called mat2py, but there's nothing there. (It seems to be just a placeholder.) I figure that if anyone would know of something useful, this would be the place to try. TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From aahz at pythoncraft.com Wed May 26 08:56:16 2010 From: aahz at pythoncraft.com (Aahz) Date: 26 May 2010 05:56:16 -0700 Subject: LJ.com top article Message-ID: I'm finally getting around to reading my copy of Linux Journal 8/2009 (picked up at OSCON last year), and on page 17, they list the most popular articles from linuxjournal.com. Given that I'm posting here, I'm sure all long-time readers already know what that article is: Eric Raymond's "Why Python?", now ten years old. http://www.linuxjournal.com/article/3882 -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From wuwei23 at gmail.com Wed May 26 09:24:40 2010 From: wuwei23 at gmail.com (alex23) Date: Wed, 26 May 2010 06:24:40 -0700 (PDT) Subject: Looking for matlab to python converter. References: Message-ID: On May 26, 10:52?pm, "Steven W. Orr" wrote: > I found something on sourceforge called mat2py, but there's nothing there. (It > seems to be just a placeholder.) I figure that if anyone would know of something > useful, this would be the place to try. http://sourceforge.net/projects/libermate/ Google is amazing. From rolf.oltmans at gmail.com Wed May 26 09:43:47 2010 From: rolf.oltmans at gmail.com (Oltmans) Date: Wed, 26 May 2010 06:43:47 -0700 (PDT) Subject: Does pickled objects work fine between different OS? Message-ID: If I dump a Python dictionary into a file named "data.pkl" using Pickle module on a Linux operating system, will the data contained in "data.pkl" load fine in a Windows OS? I mean will I be able to load the dictionary data contained in "data.pkl" just fine on Windows XP? I could have tested it but don't have immediate access to a *nix based system so please enlighten me. All help will be appreciated. From aahz at pythoncraft.com Wed May 26 09:50:00 2010 From: aahz at pythoncraft.com (Aahz) Date: 26 May 2010 06:50:00 -0700 Subject: python command line manual References: Message-ID: In article , Chris Rebert wrote: >On Mon, May 24, 2010 at 3:52 PM, Peng Yu wrote: >> >> I mainly check online python manual. But I feel that it would be nice >> if there is command line manual available (just like perl command line >> manual). Could you please let me know if such command line manual >> available? > >98% sure that there isn't. You could instead use a text-based console >web browser such as lynx to view the online docs to much the same >effect though. ...after downloading them locally so that you're not dependent on an Internet connection. At least, that's what I've been doing for about a decade... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From mail at timgolden.me.uk Wed May 26 09:59:35 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 26 May 2010 14:59:35 +0100 Subject: python command line manual In-Reply-To: References: Message-ID: <4BFD2947.6030507@timgolden.me.uk> On 26/05/2010 14:50, Aahz wrote: > In article, > Chris Rebert wrote: >> On Mon, May 24, 2010 at 3:52 PM, Peng Yu wrote: >>> >>> I mainly check online python manual. But I feel that it would be nice >>> if there is command line manual available (just like perl command line >>> manual). Could you please let me know if such command line manual >>> available? >> >> 98% sure that there isn't. You could instead use a text-based console >> web browser such as lynx to view the online docs to much the same >> effect though. > > ...after downloading them locally so that you're not dependent on an > Internet connection. At least, that's what I've been doing for about a > decade... Wow. That's a slow internet connection you've got there... TJG From breamoreboy at yahoo.co.uk Wed May 26 10:12:18 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 26 May 2010 15:12:18 +0100 Subject: Python-URL! archives Message-ID: According to http://www.python.org/community/lists/ these are archived here http://www.equi4.com/wikis/urls/82. As the latter hasn't been updated since 2000-07-20 isn't it time to change the former :) Regards. Mark Lawrence From breamoreboy at yahoo.co.uk Wed May 26 10:15:50 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 26 May 2010 15:15:50 +0100 Subject: python command line manual In-Reply-To: <4BFD2947.6030507@timgolden.me.uk> References: <4BFD2947.6030507@timgolden.me.uk> Message-ID: On 26/05/2010 14:59, Tim Golden wrote: > On 26/05/2010 14:50, Aahz wrote: >> In article, >> Chris Rebert wrote: >>> On Mon, May 24, 2010 at 3:52 PM, Peng Yu wrote: >>>> >>>> I mainly check online python manual. But I feel that it would be nice >>>> if there is command line manual available (just like perl command line >>>> manual). Could you please let me know if such command line manual >>>> available? >>> >>> 98% sure that there isn't. You could instead use a text-based console >>> web browser such as lynx to view the online docs to much the same >>> effect though. >> >> ...after downloading them locally so that you're not dependent on an >> Internet connection. At least, that's what I've been doing for about a >> decade... > > Wow. That's a slow internet connection you've got there... > > TJG +1 LOTW From albert at spenarnc.xs4all.nl Wed May 26 10:32:50 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 26 May 2010 14:32:50 GMT Subject: function that counts... References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> Message-ID: In article <4bf442cd$0$31377$4fafbaef at reader1.news.tin.it>, superpollo wrote: >... how many positive integers less than n have digits that sum up to m: > >In [197]: def prttn(m, n): > tot = 0 > for i in range(n): > s = str(i) > sum = 0 > for j in range(len(s)): > sum += int(s[j]) > if sum == m: > tot += 1 > return tot > .....: > >In [207]: prttn(25, 10000) >Out[207]: 348 > >any suggestion for pythonizin' it? I don't like the excursion to string and back. def x(i) : return x(i/10)+i%10 if i else 0 or if you can't stand recursion: def x(i): s= 0 while i: s += i%10 i /= 10 return s (All untested but you get the idea.) > >bye -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From icanbob at gmail.com Wed May 26 10:52:48 2010 From: icanbob at gmail.com (bobicanprogram) Date: Wed, 26 May 2010 07:52:48 -0700 (PDT) Subject: speed up a numpy code with huge array References: <729e2cea-b961-4d83-bf7a-1b133f426330@u7g2000vbq.googlegroups.com> <704eeb6e-4939-43f0-986e-42460c88b738@k31g2000vbu.googlegroups.com> Message-ID: On May 26, 7:43 am, Alexzive wrote: > thank you all for the tips. > I 'll try them soon. > > I also notice another bottleneck, when python tries to access some > array data stored in the odb files (---> in text below), even before > starting the algoritm: > > ### > EPS_nodes = range(len(frames)) > for f in frames: > ... sum = 0 > ---> UN = F[f].fieldOutputs['U'].getSubset(region=TOP).values <--- > ... EPS_nodes[f] = UN[10].data[Scomp-1]/L3 > > ### > > unfortunately I don't have time to learn cython. Using dictionaries > sounds promising. > Thanks! > Alex > > On May 26, 8:14 am, Stefan Behnel wrote: > > > Alexzive, 25.05.2010 21:05: > > > > is there a way to improve the performance of the attached code ? it > > > takes about 5 h on a dual-core (using only one core) when len(V) > > > ~1MIL. V is an array which is supposed to store all the volumes of > > > tetrahedral elements of a grid whose coord. are stored in NN (accessed > > > trough the list of tetraelements --> EL) > > > Consider using Cython for your algorithm. It has direct support for NumPy > > arrays and translates to fast C code. > > > Stefan The SIMPL toolkit (http://www.icanprogram.com/06py/lesson1/ lesson1.html) might be a simpler way to offload some processing to faster C code. bob From kushal.kumaran at gmail.com Wed May 26 11:25:51 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Wed, 26 May 2010 20:55:51 +0530 Subject: Another Little MySQL Problem In-Reply-To: References: Message-ID: <1274887551.2339.11.camel@nitrogen> On Tue, 2010-05-25 at 14:45 -0400, Victor Subervi wrote: > Hi; > I have this code: > > clientCursor.execute('select ID from %s' % (personalDataTable)) > upds = [itm[0] for itm in clientCursor] > print "" % upds > > The problem is that the values passed are 1L, 2L.... When I retrieve > them on the other end and try to convert them to integers, guess what > happens? So how do I get rid of that "L"? You could build a list of ints instead of a list of longs, like this: upds = [int(itm[0]) for itm in clientCursor] I'm not sure if the result of applying str() on lists is guaranteed not to change, though. -- regards, kushal From fetchinson at googlemail.com Wed May 26 11:40:35 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 26 May 2010 17:40:35 +0200 Subject: Does pickled objects work fine between different OS? In-Reply-To: References: Message-ID: > If I dump a Python dictionary into a file named "data.pkl" using > Pickle module on a Linux operating system, will the data contained in > "data.pkl" load fine in a Windows OS? Yes. > I mean will I be able to load the dictionary data contained in "data.pkl" > just fine on Windows XP? Yes. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From kushal.kumaran at gmail.com Wed May 26 11:59:24 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Wed, 26 May 2010 21:29:24 +0530 Subject: UnicodeDecodeError having fetch web page In-Reply-To: References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> Message-ID: <1274889564.2339.16.camel@nitrogen> On Tue, 2010-05-25 at 20:12 +0000, Rob Williscroft wrote: > Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3 > @m21g2000vbr.googlegroups.com in gmane.comp.python.general: > > > Hi, > > > > The code below is giving me the error: > > > > Traceback (most recent call last): > > File "C:\Users\Administrat?r\Desktop\test.py", line 4, in > > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: > > unexpected code byte > > > > > > What am i doing wrong? > > It may not be you, en.wiktionary.org is sending gzip > encoded content back, it seems to do this even if you set > the Accept header as in: > > request.add_header( "Accept", "text/html" ) > > But maybe I'm not doing it correctly. > You need the Accept-Encoding: identity header. http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html -- regards, kushal From rridge at csclub.uwaterloo.ca Wed May 26 12:02:27 2010 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 26 May 2010 12:02:27 -0400 Subject: Does pickled objects work fine between different OS? References: Message-ID: Oltmans wrote: >If I dump a Python dictionary into a file named "data.pkl" using >Pickle module on a Linux operating system, will the data contained in >"data.pkl" load fine in a Windows OS? I mean will I be able to load >the dictionary data contained in "data.pkl" just fine on Windows XP? That will work just fine. The only thing that may be a problem is that if you choose to use the newer pickle format, it won't work with versions of Python before 2.3. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From invalid at invalid.invalid Wed May 26 12:23:48 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 26 May 2010 16:23:48 +0000 (UTC) Subject: Does pickled objects work fine between different OS? References: Message-ID: On 2010-05-26, Oltmans wrote: > If I dump a Python dictionary into a file named "data.pkl" using > Pickle module on a Linux operating system, will the data contained in > "data.pkl" load fine in a Windows OS? That depends on the data and the version of Python. Older versions didn't handle some floating point values (NAN, INF) in a portable manner, and loading the pickled data would fail when such a value was encountered. -- Grant Edwards grant.b.edwards Yow! It's the RINSE CYCLE!! at They've ALL IGNORED the gmail.com RINSE CYCLE!! From ktenney at gmail.com Wed May 26 12:51:22 2010 From: ktenney at gmail.com (Kent Tenney) Date: Wed, 26 May 2010 11:51:22 -0500 Subject: question Message-ID: In a docutils svn checkout. [docutils/trunk/docutils]$ python setup.py install --root /tmp OK [docutils/trunk/docutils]$ python setup.py install_data --root /tmp distutils.errors.DistutilsFileError: could not delete '/usr/local/lib/python2.6/dist-packages/docutils/parsers/rst/include/README.txt': Permission denied Am I missing something? If it works for you, I suppose it's somewhere in my versioning. I have bull in a china shop tendencies when it comes to installing stuff. Thanks, Kent From strombrg at gmail.com Wed May 26 12:55:25 2010 From: strombrg at gmail.com (Dan Stromberg) Date: Wed, 26 May 2010 09:55:25 -0700 (PDT) Subject: Troubles with python internationalization References: Message-ID: <083708a3-b496-4aeb-8f19-bf77eb578888@v37g2000vbv.googlegroups.com> On May 25, 10:46?am, Pascal Chambon wrote: > * code safety : it seems default python string formatting technics (% > operator, .format() method) are normally used when one needs to > substitute placeholders in translated strings. But the thing is : I DONT > want my view to raise an exception simply because one of the > translations has forgotten a damn "%(myvar)s" placeholder. The only > quick fix I can think of, is to always use substitution through > defaultdicts instances (and still, exceptions could occur if abnormal > "%s" placeholders are found in the translated string). > Are there some utilities in python, or frameworks like django, > ? to allow a safe string substitution (which might, > for example, simply log an error if a buggy string si found) ?? Python's > template strings' "safe_substitute()" won't fit, because it swallows > errors without any notice... For this one, you might check into pylint. I've just recently started using it, but I'm loving it. I pretty much don't check things in without first running them through pylint (and some unit tests) first now. From magguri.devi at gmail.com Wed May 26 13:28:21 2010 From: magguri.devi at gmail.com (devi) Date: Wed, 26 May 2010 10:28:21 -0700 (PDT) Subject: uk girls Message-ID: <1e947034-5afb-4361-8ccb-79d0b52e4a7f@a27g2000prj.googlegroups.com> we are write here uk girls body language uk girls clture and that feature what about this last man visit in earth. visit www.ukgirlsbody.blogspot.com From magguri.devi at gmail.com Wed May 26 13:31:47 2010 From: magguri.devi at gmail.com (devi) Date: Wed, 26 May 2010 10:31:47 -0700 (PDT) Subject: uk girls Message-ID: we are write here uk girls body language uk girls clture and that feature what about this last man visit in earth. visit www.onlineairlinesjobs.blogspot.com From xcr4cx at googlemail.com Wed May 26 13:32:42 2010 From: xcr4cx at googlemail.com (christian schulze) Date: Wed, 26 May 2010 10:32:42 -0700 (PDT) Subject: Yet Another Configuration Parser Module Message-ID: <3e5f012a-1ecd-4cd0-91de-0b1d78c5e48a@m4g2000vbl.googlegroups.com> Hey folks, I've written a small configuration parser for a recent project. I think it's pretty usefull and not that "fat" or "complex" as the regular python configuration modules like ConfigParser. The file contains everything you need to know. http://crac.pcriot.com/dl/config.py If you have any suggestions I'd be glad if you'd contact me. From victorsubervi at gmail.com Wed May 26 13:37:29 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 26 May 2010 13:37:29 -0400 Subject: Another Little MySQL Problem In-Reply-To: <1274887551.2339.11.camel@nitrogen> References: <1274887551.2339.11.camel@nitrogen> Message-ID: On Wed, May 26, 2010 at 11:25 AM, Kushal Kumaran wrote: > On Tue, 2010-05-25 at 14:45 -0400, Victor Subervi wrote: > > Hi; > > I have this code: > > > > clientCursor.execute('select ID from %s' % (personalDataTable)) > > upds = [itm[0] for itm in clientCursor] > > print "" % upds > > > > The problem is that the values passed are 1L, 2L.... When I retrieve > > them on the other end and try to convert them to integers, guess what > > happens? So how do I get rid of that "L"? > > You could build a list of ints instead of a list of longs, like this: > > upds = [int(itm[0]) for itm in clientCursor] > Oh, geez. That should have been obvious to me! Thanks! beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From william.miner at enig.com Wed May 26 13:48:42 2010 From: william.miner at enig.com (William Miner) Date: Wed, 26 May 2010 13:48:42 -0400 Subject: Error Message-ID: I?m relative new to python and I puzzled by the following strange (to me) behavior. I was taking pieces from two old scripts to build a new one. When I began to debug it I got the following error message: Traceback (most recent call last): File "/Users/williamminer/ex2gen/ex2gen-3.0.5/src/ScriptDev/run_ex2gen_scan.py", line 38, in if re.search('varm',line): AttributeError: 'function' object has no attribute 'search' This had worked in the previous script but not the new one. I noticed that the new script had an additional line at the beginning (line 3) #!/usr/bin/env python import sys, math, os, shutil, commands, re, mpmath from mpmath import * When I deleted this line, the script ran. Why did the line from mpmath import * Trash the search function fro the regular expression module? I?m running Python 2.6.2 on Mac running OS 10.6.3. Thanks! Buff Miner -- Enig Associates, Inc. Suite 500, Bethesda Crescent Bldg. 4600 East West Hwy Bethesda, Maryland 20814 Tel:(301)680-8600 Fax:(301)680-8100 This message is intended only for the use of the intended recipient(s), and it may be privileged and confidential. If you are not the intended recipient, you are hereby notified that any review, retransmission, conversion to hard copy, copying, circulation or other use of this message is strictly prohibited and may be illegal. If you are not the intended recipient, please notify the sender immediately by return e-mail, and delete this message from your system. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Wed May 26 13:59:06 2010 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 26 May 2010 19:59:06 +0200 Subject: Ugly modification of a class, can it be done better ? In-Reply-To: <4bf5e19e$0$27861$c3e8da3@news.astraweb.com> References: <4BF5D02A.9070600@gmail.com> <4bf5e19e$0$27861$c3e8da3@news.astraweb.com> Message-ID: <4BFD616A.3010009@gmail.com> On 21-05-2010 03:27, Steven D'Aprano wrote: > Sorry for breaking threading, but Stef's original post has not come > through to me. > > >> On Thu, May 20, 2010 at 8:13 PM, Stef Mientki >> wrote: >> > >>> So I want to change the behavior of the class dynamically. I've done it >>> by adding a global variable (Base_Grid_Double_Click) in the module, >>> initial set to None, >>> but can be changed by the main program to some callback function. (see >>> the code below) >>> > How is this supposed to work? If you have *one* global, then *every* > instance will see the same setting. But that's exactly what I need ;-) The problem is a little more complicated, I've several "frame-works", that searches for specific modules (applications) in a specific directory. The frame work should determine what should happen (e.g. on a doubleclick of a grid cell) in these modules (application), but the frame work has no idea what kind of instances are in these modules. The same module can be used in different frame-works (or even stand-alone) and the behavior of e.g. a doubleclick, can differ, depending on the frame work. Describing the situation above, I realize that the concept is already spaghetti in itself ;-) but for a modular system this works like a charm. So for the moment I'll stick to the orginal solution. thank you all for the responses. cheers, Stef Mientki > To change it dynamically, you enter a > nightmare world of having to save the global, modify it, then restore it, > every single time. Trust me, I've been there, this is the *worst* way of > programming. This is why object oriented inheritance was invented, to > escape this nonsense! > > The first thing is to make the callback specific to the class, not > global. Why does your printing code need access to the callback that > handles double-clicking on a grid? It doesn't! So don't give it that > access (at least, not easy access). Put the callback in the class. > > class MyClass: > callback = None > def method(self, *args): > if self.callback is None: > behaviour_with_no_callback() > else: > behaviour_with_callback() > > > Now if you want to apply a callback to some instances, and not others, it > is totally simple: > > > red = MyClass() > blue = MyClass() > red.callback = my_callback_function > > and you're done. > > > If you have lots of instances that use the same callback? Make a subclass. > > class MyDottedClass(MyClass): > pass > > red = MyClass() > blue = MyClass() > red_with_green_dots = MyDottedClass() > blue_with_green_dots = MyDottedClass() > > MyDottedClass.callback = dotted_callback > > And now all the dot instances will use the same callback without > effecting the undotted instances. What to change them all to use a > different behaviour? > > MyDottedClass.callback = something_different > > and now they all change, again without effecting the undotted instances. > > > > > >>> Is this a valid construction ( sorry I'm not a programmer), or are >>> there better ways to accomplish similar dynamic behavior ? >>> > Of course you're a programmer! You're writing programs, aren't you? > > > > > From clp2 at rebertia.com Wed May 26 14:09:58 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 May 2010 11:09:58 -0700 Subject: Error In-Reply-To: References: Message-ID: On Wed, May 26, 2010 at 10:48 AM, William Miner wrote: > I?m relative new to python and I puzzled by the following strange (to me) > behavior. I was taking pieces from two old scripts to build a new one. When > I began to debug it I got the following error message: > > Traceback (most recent call last): > ??File > "/Users/williamminer/ex2gen/ex2gen-3.0.5/src/ScriptDev/run_ex2gen_scan.py", > line 38, in > ????if re.search('varm',line): > AttributeError: 'function' object has no attribute 'search' > > This had worked in the previous script but not the new one. I noticed that > the new script had an additional line at the beginning (line 3) > > #!/usr/bin/env python > import sys, math, os, shutil, commands, re, mpmath > from mpmath import * > > When I deleted this line, the script ran. Why did the line > > from mpmath import * > > Trash the search function fro the regular expression module? mpmath defines a function named re() which returns the real part of a complex number. Because you used "import *", the existing value of the global variable "re", which was the regular expression module, gets clobbered with mpmath's re() function. Thus, you get that error when you try to call the "search" method on what is now a function object. This is precisely why using the `from foo import *` syntax is discouraged. Cheers, Chris -- http://blog.rebertia.com From rtw at rtw.me.uk Wed May 26 14:10:15 2010 From: rtw at rtw.me.uk (Rob Williscroft) Date: Wed, 26 May 2010 18:10:15 +0000 (UTC) Subject: UnicodeDecodeError having fetch web page References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> <1274889564.2339.16.camel@nitrogen> Message-ID: Kushal Kumaran wrote in news:1274889564.2339.16.camel at nitrogen in gmane.comp.python.general: > On Tue, 2010-05-25 at 20:12 +0000, Rob Williscroft wrote: >> Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3 >> @m21g2000vbr.googlegroups.com in gmane.comp.python.general: >> >> > Hi, >> > >> > The code below is giving me the error: >> > >> > Traceback (most recent call last): >> > File "C:\Users\Administrat??r\Desktop\test.py", line 4, in >> > >> > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position >> > 1: unexpected code byte >> > >> > >> > What am i doing wrong? >> >> It may not be you, en.wiktionary.org is sending gzip >> encoded content back, it seems to do this even if you set >> the Accept header as in: >> >> request.add_header( "Accept", "text/html" ) >> >> But maybe I'm not doing it correctly. >> > You need the Accept-Encoding: identity header. > http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html Thanks, following this I did change the line to be: request.add_header( "Accept-Encoding", "identity" ) but it made no difference to en.wiktionary.org it just sent the back a gzip encoded response. Rob. From python at mrabarnett.plus.com Wed May 26 14:13:05 2010 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 May 2010 19:13:05 +0100 Subject: Error In-Reply-To: References: Message-ID: <4BFD64B1.2050205@mrabarnett.plus.com> William Miner wrote: > I?m relative new to python and I puzzled by the following strange (to > me) behavior. I was taking pieces from two old scripts to build a new > one. When I began to debug it I got the following error message: > > Traceback (most recent call last): > File > "/Users/williamminer/ex2gen/ex2gen-3.0.5/src/ScriptDev/run_ex2gen_scan.py", > line 38, in > if re.search('varm',line): > AttributeError: 'function' object has no attribute 'search' > > This had worked in the previous script but not the new one. I noticed > that the new script had an additional line at the beginning (line 3) > > #!/usr/bin/env python > import sys, math, os, shutil, commands, re, mpmath > from mpmath import * > > When I deleted this line, the script ran. Why did the line > > from mpmath import * > > Trash the search function fro the regular expression module? > > I?m running Python 2.6.2 on Mac running OS 10.6.3. > When you write: from mpmath import * you're importing all the 'public' names (by which I mean those not starting with '_') from the mpmath module. The mpmath module happens to contain a function called 're', so 're' will now refer to that function instead of the re module. That's why using "import *" is usually a bad idea. From darcy at druid.net Wed May 26 14:14:52 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 26 May 2010 14:14:52 -0400 Subject: Error In-Reply-To: References: Message-ID: <20100526141452.0f004cba.darcy@druid.net> On Wed, 26 May 2010 13:48:42 -0400 William Miner wrote: > #!/usr/bin/env python > import sys, math, os, shutil, commands, re, mpmath > from mpmath import * > > When I deleted this line, the script ran. Why did the line > > from mpmath import * > > Trash the search function fro the regular expression module? What is mpmath? It isn't in the standard distribution. My guess is that it has an object called "re" that is overwriting the re module. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From tjreedy at udel.edu Wed May 26 14:30:21 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 May 2010 14:30:21 -0400 Subject: TypeError: _new_() takes exactly 3 arguments (2 given) - what does it mean? In-Reply-To: <2061601704.535865.1274727159418.JavaMail.root@vms244.mailsrvcs.net> References: <2061601704.535865.1274727159418.JavaMail.root@vms244.mailsrvcs.net> Message-ID: On 5/24/2010 2:52 PM, Jesse McDonnell wrote: > I'm attempting to install Powerline http://code.google.com/p/powerline/, > a computer reservation software based on CherryPy/Python using a MYSql > database, at my local library and I've run up against an error that I > cannot google my way out of! The google groups for the application is > inactive so I'm posting on here in the hope that I can get some pointers > to get me beyond this issue. Any suggestions/pointers will be greatly > appreciated. Honestly, unless you find a Python+Powerline expert who will help, I suggest that you delete Powerline and look for something else. The most recent release is an alpha release over 2 years old. Except for the Feb 2010 wiki updates, the project appears to be dead. Even if someone helped you past this, there is no evidence that the fix would applied back to the codebase. And what about the next bug or problem? Otherwise, sign in and submit a new issue on the project tracker, with just your command line, empty config response, and traceback (if allowed, I do not know) and see if you get a response. Terry Jan Reedy From gherron at islandtraining.com Wed May 26 14:40:38 2010 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 26 May 2010 11:40:38 -0700 Subject: Error In-Reply-To: References: Message-ID: <4BFD6B26.5070609@islandtraining.com> On 05/26/2010 10:48 AM, William Miner wrote: > I'm relative new to python and I puzzled by the following strange (to > me) behavior. I was taking pieces from two old scripts to build a new > one. When I began to debug it I got the following error message: > > Traceback (most recent call last): > File > "/Users/williamminer/ex2gen/ex2gen-3.0.5/src/ScriptDev/run_ex2gen_scan.py", > line 38, in > if re.search('varm',line): > AttributeError: 'function' object has no attribute 'search' > > This had worked in the previous script but not the new one. I noticed > that the new script had an additional line at the beginning (line 3) > > #!/usr/bin/env python > import sys, math, os, shutil, commands, re, mpmath > from mpmath import * > > When I deleted this line, the script ran. Why did the line > > from mpmath import * Just a guess, (since I don;t have mpmath on hand), but if mpmath has a definition for something named re, it would overwrite any previous definition of re. So general advice says don't use the "from xxx import *" unless you really *know* what is in the module, and need *all* of it imported. Either: from mpmath import x,y,z,whatever or import re import mpmath ... re.search ... ... mpmath.whatever ... Gary Herron > > Trash the search function fro the regular expression module? > > I'm running Python 2.6.2 on Mac running OS 10.6.3. > > Thanks! > > Buff Miner > -- > Enig Associates, Inc. > Suite 500, Bethesda Crescent Bldg. > 4600 East West Hwy > Bethesda, Maryland 20814 > Tel:(301)680-8600 > Fax:(301)680-8100 > > This message is intended only for the use of the intended > recipient(s), and > it may be privileged and confidential. If you are not the intended > recipient, you are hereby notified that any review, retransmission, > conversion to hard copy, copying, circulation or other use of this message > is strictly prohibited and may be illegal. If you are not the intended > recipient, please notify the sender immediately by return e-mail, and > delete > this message from your system. Thank you. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From a_jtim at bellsouth.net Wed May 26 14:47:06 2010 From: a_jtim at bellsouth.net (Tim Arnold) Date: Wed, 26 May 2010 11:47:06 -0700 (PDT) Subject: multiprocessing and accessing server's stdout Message-ID: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Hi, I'm using multiprocessing's BaseManager to create a server on one machine and a client on another. The client fires a request and the server does some work, the result of which ends up on a shared file system that both the client and server can see. However, I need the client machine to see the stdout of the process running on the server. Not sure this is doable--I've been unable to google anything useful on this one. thanks, --Tim Arnold From pavlovevidence at gmail.com Wed May 26 15:04:53 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 May 2010 12:04:53 -0700 (PDT) Subject: TypeError: _new_() takes exactly 3 arguments (2 given) - what does it mean? References: <2061601704.535865.1274727159418.JavaMail.root@vms244.mailsrvcs.net> Message-ID: [Again, can't see the original, sorry] On May 26, 11:30?am, Terry Reedy wrote: > On 5/24/2010 2:52 PM, Jesse McDonnell wrote: > > > I'm attempting to install Powerlinehttp://code.google.com/p/powerline/, > > a computer reservation software based on CherryPy/Python using a MYSql > > database, at my local library and I've run up against an error that I > > cannot google my way out of! The google groups for the application is > > inactive so I'm posting on here in the hope that I can get some pointers > > to get me beyond this issue. Any suggestions/pointers will be greatly > > appreciated. The most common reason for this message is trying to subclass a module. (Very easy mistake when a module has the same name as a class, which is part of why I don't like the practice, though the modern PEP 8 reduces the issue.) IOW, someone did something like this: import foo class bar(foo): pass when they should have done this: from foo import foo class bar(foo): pass Carl Banks From magnus.moraberg at gmail.com Wed May 26 15:12:03 2010 From: magnus.moraberg at gmail.com (Barry) Date: Wed, 26 May 2010 12:12:03 -0700 (PDT) Subject: Fetching a gzipped webpage Message-ID: <3e151334-d5e8-4a1a-9628-d039a2e50dfd@y12g2000vbr.googlegroups.com> Hi, Here's my attempt at petching a webpage which is gzip encoded - import urllib.request import gzip import io request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ baby',headers={'Accept': 'text/html','User-Agent':'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3'} ) response = urllib.request.urlopen(request) data = response.read() compressedstream = io.StringIO(data) gzipper = gzip.GzipFile(fileobj=compressedstream) data = gzipper.read() print(data) However it gives the error: Traceback (most recent call last): File "test.py", line 9, in TypeError: initial_value must be str or None, not bytes How should I be doing this for Python 3? Thanks Barry From __peter__ at web.de Wed May 26 15:41:02 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 May 2010 21:41:02 +0200 Subject: Fetching a gzipped webpage References: <3e151334-d5e8-4a1a-9628-d039a2e50dfd@y12g2000vbr.googlegroups.com> Message-ID: Barry wrote: > Here's my attempt at petching a webpage which is gzip encoded - > > import urllib.request > import gzip > import io > > request = urllib.request.Request(url='http://en.wiktionary.org/wiki/ > baby',headers={'Accept': 'text/html','User-Agent':'Mozilla/5.0 > (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 > (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3'} ) > response = urllib.request.urlopen(request) > data = response.read() > > compressedstream = io.StringIO(data) > > gzipper = gzip.GzipFile(fileobj=compressedstream) > data = gzipper.read() > print(data) > > > However it gives the error: > > Traceback (most recent call last): > File "test.py", line 9, in > TypeError: initial_value must be str or None, not bytes > > How should I be doing this for Python 3? Use io.BytesIO instead of io.StringIO, as Rob Williscroft showed you yesterday. Peter From nagle at animats.com Wed May 26 15:43:29 2010 From: nagle at animats.com (John Nagle) Date: Wed, 26 May 2010 12:43:29 -0700 Subject: Another Little MySQL Problem In-Reply-To: References: Message-ID: <4bfd7436$0$1611$742ec2ed@news.sonic.net> Kushal Kumaran wrote: > On Tue, 2010-05-25 at 14:45 -0400, Victor Subervi wrote: >> Hi; >> I have this code: >> >> clientCursor.execute('select ID from %s' % (personalDataTable)) >> upds = [itm[0] for itm in clientCursor] >> print "" % upds >> >> The problem is that the values passed are 1L, 2L.... When I retrieve >> them on the other end and try to convert them to integers, guess what >> happens? So how do I get rid of that "L"? What's the table definition? John Nagle From shashank.sunny.singh at gmail.com Wed May 26 15:48:46 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Thu, 27 May 2010 01:18:46 +0530 Subject: Fastest way to apply a function to an iterable Message-ID: What is the most efficient way of applying a function to all the elements of an iterable while discarding the result (i.e. operations are done only for side-effects). For example if I want to save all elements in a list of items (and am not interested in what save() returns), the simplest way is: itemlist = [i1, i2, i3....] for item in itemlist: item.save() It might be squeezing too much but is it possible to do it more efficiently by pushing the looping inside the C code and achieve some gains as is done by using map in place of a for loop when the return values need to be saved? Any suggestions will be appreciated. TIA -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Wed May 26 15:53:30 2010 From: nagle at animats.com (John Nagle) Date: Wed, 26 May 2010 12:53:30 -0700 Subject: MySQL, Python, NumPy and formatted read In-Reply-To: References: Message-ID: <4bfd7690$0$1666$742ec2ed@news.sonic.net> Ian Hoffman wrote: > Hello, > > I'm having significant Python difficulties (and I'm new to Python). > I'm trying to read BLOB ASCII (numerical) data from a MySQL database > using MySQLdb in a formatted fashion. The BLOB data is a sequence of > numbers separated by newlines (\n), like this: > 5 > 6 > 10 > 45 > etc. Note that a BLOB is not ASCII. If you're storing ASCII text, use type TEXT in SQL, not type BLOB. Don't lie to the database. It doesn't like that. And if you're going to store numbers, store numbers, not text. SQL has the usual integer and floating point types. When you read a BLOB from MySQLdb, you do not get a string. You get an object of type "bytes". This is not a Python string. Python strings can be ASCII or Unicode in Python 2.x, and in 3.x, are always Unicode. John Nagle From alister.ware at ntlworld.com Wed May 26 16:11:21 2010 From: alister.ware at ntlworld.com (Alister) Date: Wed, 26 May 2010 20:11:21 GMT Subject: Error References: Message-ID: On Wed, 26 May 2010 11:09:58 -0700, Chris Rebert wrote: > On Wed, May 26, 2010 at 10:48 AM, William Miner > wrote: >> I?m relative new to python and I puzzled by the following strange (to >> me) behavior. I was taking pieces from two old scripts to build a new >> one. When I began to debug it I got the following error message: >> >> Traceback (most recent call last): >> ??File >> "/Users/williamminer/ex2gen/ex2gen-3.0.5/src/ScriptDev/ run_ex2gen_scan.py", >> line 38, in >> ????if re.search('varm',line): >> AttributeError: 'function' object has no attribute 'search' >> >> This had worked in the previous script but not the new one. I noticed >> that the new script had an additional line at the beginning (line 3) >> >> #!/usr/bin/env python >> import sys, math, os, shutil, commands, re, mpmath from mpmath import * >> >> When I deleted this line, the script ran. Why did the line >> >> from mpmath import * >> >> Trash the search function fro the regular expression module? > > mpmath defines a function named re() which returns the real part of a > complex number. Because you used "import *", the existing value of the > global variable "re", which was the regular expression module, gets > clobbered with mpmath's re() function. Thus, you get that error when you > try to call the "search" method on what is now a function object. > > This is precisely why using the `from foo import *` syntax is > discouraged. > > Cheers, > Chris I am fairly new to Python but had already decided to opt a style that would always use import XXX rather than the from XXX import * syntax. It is nice to know that at least one of my decisions on best practice is good as an old programmer (8 bit assembler for micro controller applications) picking up the baton again for fun I have to say Python is great (I find C to be so low level I might just as well go back to assembler!). -- "Linux doesn't support any sub-32-bit computers, and despite the occasional deranged people interested in retro-computing (ie Alan Cox) I doubt it seriously will.." - Linus Torvalds From william.miner at enig.com Wed May 26 16:13:27 2010 From: william.miner at enig.com (William Miner) Date: Wed, 26 May 2010 16:13:27 -0400 Subject: Indentation Message-ID: I have a script which I would now put inside a loop. Is there any way to ?automatically? indent the old script so it can be put inside the new loop. Doing it by hand seems so inelegant and time consuming. By the way, thanks for the answer to my previous question. Thanks! Buff Miner -- Enig Associates, Inc. Suite 500, Bethesda Crescent Bldg. 4600 East West Hwy Bethesda, Maryland 20814 Tel:(301)680-8600 Fax:(301)680-8100 This message is intended only for the use of the intended recipient(s), and it may be privileged and confidential. If you are not the intended recipient, you are hereby notified that any review, retransmission, conversion to hard copy, copying, circulation or other use of this message is strictly prohibited and may be illegal. If you are not the intended recipient, please notify the sender immediately by return e-mail, and delete this message from your system. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alister.ware at ntlworld.com Wed May 26 16:17:02 2010 From: alister.ware at ntlworld.com (Alister) Date: Wed, 26 May 2010 20:17:02 GMT Subject: Another Little MySQL Problem References: <4bfd7436$0$1611$742ec2ed@news.sonic.net> Message-ID: <2lfLn.104252$Qg5.19019@newsfe06.ams2> On Wed, 26 May 2010 12:43:29 -0700, John Nagle wrote: > Kushal Kumaran wrote: >> On Tue, 2010-05-25 at 14:45 -0400, Victor Subervi wrote: >>> Hi; >>> I have this code: >>> >>> clientCursor.execute('select ID from %s' % (personalDataTable)) >>> upds = [itm[0] for itm in clientCursor] print ">> type='hidden' name='upds' value='%s' />" % upds >>> >>> The problem is that the values passed are 1L, 2L.... When I retrieve >>> them on the other end and try to convert them to integers, guess what >>> happens? So how do I get rid of that "L"? > > What's the table definition? > > John Nagle I think you should probably also write your execuete diferently: >>> clientCursor.execute('select ID from %s' , (personalDataTable,)) this ensures the parameters are correctly escaped to prevent mysql injection attacks,the "," after personalDataTable is necessary to ensure the parameter is passed as a tupple However I am fairly new so could be mistaken on exactly what your code does. -- If you analyse anything, you destroy it. -- Arthur Miller From awilliam at whitemice.org Wed May 26 16:17:56 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Wed, 26 May 2010 16:17:56 -0400 Subject: Indentation In-Reply-To: References: Message-ID: <1274905076.19105.1.camel@linux-yu4c.site> On Wed, 2010-05-26 at 16:13 -0400, William Miner wrote: > I have a script which I would now put inside a loop. Is there any way > to ?automatically? indent the old script so it can be put inside the > new loop. Doing it by hand seems so inelegant and time consuming. Open script in MonoDevelop Highlight text, right-click, click "Indent Selection" in context menu. Or any decent IDE should provide the same kind of thing. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From no.email at please.post Wed May 26 16:19:47 2010 From: no.email at please.post (kj) Date: Wed, 26 May 2010 20:19:47 +0000 (UTC) Subject: atexit/signal for non-interactive jobs Message-ID: I want to implement clean-up functions for scripts to be run on a Linux cluster (through LSF). The goal is to make sure that a minimal wrap-up sequence (print diagnostic info, flush buffers, etc.) gets executed if the job is terminated for some reason. (The most common reason for premature termination is a SIGUSR2 signal, sent to the process by LSF when the job has taken longer than the time limit for the job's LSF queue.) No matter what I try, I can't get this wrap-up sequence to work when the script runs non-interactively. The latest I have looks something like this: import signal import atexit def set_handlers(handler): atexit.register(handler) for sig in dir(signal): if sig.startswith('SIG') and not '_' in sig: signal(getattr(signal, sig), handler) def wrapup(*args): # etc, etc def main(): # ... set_handlers(wrapup) run() main() If I start the script interactively and after a few seconds (i.e. before it terminates) I hit Ctrl-C (which sends a TERM signal to the process), the wrapup function gets called as desired (although this action appears to be triggered by atexit, and not by the handler for SIGTERM, which apparently never gets called). But if instead I background the script after starting it, and then use kill to explicitly send a TERM signal to its process, the script terminates, but the wrapup code does not execute. It makes no sense to me. If someone cares to explain it, I'd be very grateful. (Is my code doing something wrong?) But more to the point, what must I do to get this to work in the non-interactive case? TIA! ~k From lex at from.hell Wed May 26 16:21:47 2010 From: lex at from.hell (Lex Lebedeff) Date: Wed, 26 May 2010 20:21:47 +0000 (UTC) Subject: Kohonen neural network References: <260cd874-fe51-4bdd-b112-f64ff7ef3050@a27g2000prj.googlegroups.com> Message-ID: On Wed, 26 May 2010 05:26:56 -0700, alex23 wrote: > On May 26, 7:21?pm, Lex Lebedeff wrote: >> Has anyone tried to build an implementation of subject in Python? Any >> help is appreciated! > > http://www.dia.fi.upm.es/~jamartin/download.htm > > Seriously, though, any reason why you couldn't just type "kohonen neural > network python" into Google? You would've found it a lot easier to wade > through the results before your question & it's many mirrors. It > would've been the 2nd entry, immediately after the wikipedia article on > Kohonen SOMs. Thanx, I've already googled this stuff. Rather unreadable and freaky code. --- news://freenews.netfront.net/ - complaints: news at netfront.net --- From python at bdurham.com Wed May 26 16:24:28 2010 From: python at bdurham.com (python at bdurham.com) Date: Wed, 26 May 2010 16:24:28 -0400 Subject: Using Babel: How to protect translator comments (and old translations) in GNU gettext PO files? Message-ID: <1274905468.22843.1377075711@webmail.messagingengine.com> We're using the Python based Babel gettext utilities. Is there any technique we can use to make sure that translator comments and old ("obsolete") translations (marked with #~) in PO files are preserved across PO file updates? Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Wed May 26 16:26:34 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 26 May 2010 22:26:34 +0200 Subject: Fastest way to apply a function to an iterable In-Reply-To: References: Message-ID: Shashank Singh, 26.05.2010 21:48: > What is the most efficient way of applying a function to all the elements of > an iterable while discarding the > result (i.e. operations are done only for side-effects). > > For example if I want to save all elements in a list of items (and am not > interested in what save() returns), the > simplest way is: > > itemlist = [i1, i2, i3....] > for item in itemlist: item.save() > > It might be squeezing too much but is it possible to do it more efficiently > by pushing the looping inside the C code > and achieve some gains as is done by using map in place of a for loop when > the return values need to be saved? If all items have the exact same type, you can get away with an unbound method: class MyType(object): ... def safe(self): ... itemlist = [ MyType() for i in range(20) ] # this is what you want: from itertools import imap for _ in imap(MyType.save, itemlist): pass But some people may consider this too ugly to actually use in real code. Stefan From pavlovevidence at gmail.com Wed May 26 16:50:37 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 May 2010 13:50:37 -0700 (PDT) Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> Message-ID: <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> On May 26, 5:49?am, Rebel Lion wrote: > I made a metaclass to inherit __slots__ automatically. > > I think this feature should be included in builtin object's metaclass. I'd be ok with a metatype in the standard library that makes slots more transparent, but since slots are intended as an optimization, it doesn't really need (and might be detrimental to have) transparency for ordinary objects. However, Aahz will be by shortly to tell you never to use slots. > You can now write: > > ? ? class Foo(object): > ? ? ? ? __metaclass__ = SlotMetaclass > > ? ? ? ? @slot > ? ? ? ? def foo(): > ? ? ? ? ? ? pass > > ? ? class Bar(Foo): > > ? ? ? ? @slot > ? ? ? ? def bar(): > ? ? ? ? ? ? pass > > ? ? foo = Foo() > ? ? foo.foo = 1 > ? ? bar = Bar() > ? ? bar.bar = 1 > ? ? bar.foo = 1 > ? ? try: > ? ? ? ? bar.baz = 1 # this should fall > ? ? except AttributeError, e: > ? ? ? ? print 'yeah', e > > Instead of > > ? ? class Foo(object): > ? ? ? ? ? __slots__ = ['foo'] > ? ? class Bar(Foo) > ? ? ? ? ? __slots__ = ['foo', 'bar'] > > Please discuss the pros & cons for this feature. It seems like a good approach, but the use of decorators to define slots is hideous. I'd recommend creating slots with simple assignment instead: slot = object() class Foo(): __metaclass__ = SlotsMetaclass foo = slot class Bar(): bar = slot Then replace "isinstance(v,slot)" with "v is slot" in the metaclass. > Here is the metaclass: > > class slot(object): > ? ? """Slot Decorator""" > > ? ? def __init__(self, func): > ? ? ? ? pass > > class SlotMetaclass(type): > ? ? """Inheritable Slots Metaclass""" > > ? ? def __new__(cls, name, bases, attrs): > ? ? ? ? # make a normal class, and get its attributes to decide which > ones are slots > ? ? ? ? tmpcls = type.__new__(cls, name, bases, attrs) > ? ? ? ? slots = [] > ? ? ? ? for k in dir(tmpcls): > ? ? ? ? ? ? v = getattr(tmpcls, k) > ? ? ? ? ? ? if isinstance(v, slot): > ? ? ? ? ? ? ? ? slots.append(k) > ? ? ? ? # clean up > ? ? ? ? del tmpcls > ? ? ? ? for x in slots: > ? ? ? ? ? ? del attrs[x] > ? ? ? ? # create the real class with __slots__ > ? ? ? ? attrs['__slots__'] = slots > ? ? ? ? return type.__new__(cls, name, bases, attrs) You don't need to create a temporary class here; you should loop through the base classes and inspect their slots. Also, you don't need to recreate slots that exist in base classes, so you could just get all the new slots from the class dict. You should consider corner cases if you think it should be standard. For instance, what if a derived class defined the same slot as a a base class--it'll create a new slot in yours but it shouldn't. What if you want to create a subclass that does have a dict? Can't do it in your version. You need to consider stuff like that. Carl Banks From awilliam at whitemice.org Wed May 26 16:52:52 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Wed, 26 May 2010 16:52:52 -0400 Subject: multiprocessing and accessing server's stdout In-Reply-To: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: <1274907172.19105.8.camel@linux-yu4c.site> On Wed, 2010-05-26 at 11:47 -0700, Tim Arnold wrote: > Hi, > I'm using multiprocessing's BaseManager to create a server on one > machine and a client on another. The client fires a request and the > server does some work, the result of which ends up on a shared file > system that both the client and server can see. > However, I need the client machine to see the stdout of the process > running on the server. Not sure this is doable--I've been unable to > google anything useful on this one. Nope, it isn't. Don't use stdout, use an IPC mechanism to communicate between the client and the server if you need feedback. -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From python.list at tim.thechases.com Wed May 26 16:54:25 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 26 May 2010 15:54:25 -0500 Subject: Indentation In-Reply-To: References: Message-ID: <4BFD8A81.50006@tim.thechases.com> On 05/26/2010 03:13 PM, William Miner wrote: > I have a script which I would now put inside a loop. Is there > any way to ?automatically? indent the old script so it can be > put inside the new loop. Doing it by hand seems so inelegant > and time consuming. It's usually a function of your editor -- most good editors allow you to indent/exdent a block of code. In vim (my editor of choice), you can use the ">" and "<" operators with a motion or visual block to indent one 'shiftwidth' (which uses spaces or tabs based on your 'expandtab' setting, and can mix-and-match if your 'tabstop' isn't the same as your 'shiftwidth'). Adam already demonstrated how to do it in MonoDevelop, and I think in Visual Studio (a long time since I've had to touch that beast) you can just highlight a block and press or to indent/exdent. Likely an emacs user will chime in on this thread with how to do it there too. If you're stuck with a bogus editor but are on a *nix platform, you can indent with sed: sed 's/^/ /' original.py > out.py (that's 4 spaces after the 2nd slash; adjust accordingly to your tastes) and then just copy the contents of out.py into your script. If you're on Win32 without a good editor, go get a good editor ;-) -tkc From __peter__ at web.de Wed May 26 17:09:39 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 May 2010 23:09:39 +0200 Subject: Fastest way to apply a function to an iterable References: Message-ID: Stefan Behnel wrote: > Shashank Singh, 26.05.2010 21:48: >> What is the most efficient way of applying a function to all the elements >> of an iterable while discarding the >> result (i.e. operations are done only for side-effects). >> >> For example if I want to save all elements in a list of items (and am not >> interested in what save() returns), the >> simplest way is: >> >> itemlist = [i1, i2, i3....] >> for item in itemlist: item.save() >> >> It might be squeezing too much but is it possible to do it more >> efficiently by pushing the looping inside the C code >> and achieve some gains as is done by using map in place of a for loop >> when the return values need to be saved? > > If all items have the exact same type, you can get away with an unbound > method: > > class MyType(object): > ... > def safe(self): > ... > > itemlist = [ MyType() for i in range(20) ] > > # this is what you want: > > from itertools import imap > for _ in imap(MyType.save, itemlist): pass > > > But some people may consider this too ugly to actually use in real code. Which doesn't mean it can't get worse: >>> from sys import maxint >>> from operator import attrgetter >>> from itertools import imap, islice >>> class I: ... def __init__(self, i): ... self.i = i ... def save(self): ... print "saving", self.i ... >>> items = [I(i) for i in range(5)] >>> next(islice(imap(apply, imap(attrgetter("save"), items)), maxint, maxint), None) saving 0 saving 1 saving 2 saving 3 saving 4 See also the following thread: http://mail.python.org/pipermail/python-list/2010-January/1233307.html Most real-world applications should spend significantly more time inside the save() methods than in the enclosing loop, so I'd expect the effect of this kind of optimization on the speed of your program to be negligable. Peter From shashank.sunny.singh at gmail.com Wed May 26 17:16:20 2010 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Thu, 27 May 2010 02:46:20 +0530 Subject: Fastest way to apply a function to an iterable In-Reply-To: References: Message-ID: On Thu, May 27, 2010 at 1:56 AM, Stefan Behnel wrote: > If all items have the exact same type, you can get away with an unbound > method: > > class MyType(object): > ... > def safe(self): > ... > > itemlist = [ MyType() for i in range(20) ] > > # this is what you want: > from itertools import imap > for _ in imap(MyType.save, itemlist): pass > Thanks Stefan, I probably didn't state the problem properly. I was assuming the availability of a static method that could be passed on to map based solution (or imap for that matter). The question was, if one wants to apply a function on each member of list and discard the return value, is it possible to do it more efficiently than having a for loop in python and applying the function of each of the members? Take this run: from itertools import imap from timeit import Timer def save(x): 2 * x from itertools import imap from timeit import Timer def save(x): 2 * x def f1(): map(save, range(1000)) #simple map def f2(): for _ in imap(save, range(1000)): pass #imap def f3(): for x in range(1000):save(x) #simple iteration t1 = Timer("f1()", "from __main__ import f1") print "f1", t1.timeit(number=1000) t2 = Timer("f2()", "from __main__ import f2") print "f2", t2.timeit(number=1000) t3 = Timer("f3()", "from __main__ import f3") print "f3", t3.timeit(number=1000) The output for one run was: f1 0.393015034034 f2 0.476230638252 f3 0.376324923978 => simple for loop performs better than map/imap. Another problem with map/imap is that the memory cost is dependent on the length of the list (because of the intermediate mapped list stored) which is not the case for simple for loop. I hope I have explained it better this time. -- Regards Shashank Singh Senior Undergraduate, Department of Computer Science and Engineering Indian Institute of Technology Bombay shashank.sunny.singh at gmail.com http://www.cse.iitb.ac.in/~shashanksingh -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Wed May 26 17:26:05 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 26 May 2010 23:26:05 +0200 Subject: Fastest way to apply a function to an iterable In-Reply-To: References: Message-ID: Shashank Singh, 26.05.2010 23:16: > I probably didn't state the problem properly. I was assuming the > availability of a static method that could be passed on to map based > solution (or imap for that matter). > > The question was, if one wants to apply a function on each member of list > and discard the return value, is it possible to do it more efficiently than > having a for loop in python and applying the function of each of the > members? > > Take this run: > > from itertools import imap > from timeit import Timer > > > def save(x): 2 * x > > from itertools import imap > from timeit import Timer > > > def save(x): 2 * x > > def f1(): map(save, range(1000)) #simple map > > def f2(): > for _ in imap(save, range(1000)): pass #imap > > def f3(): > for x in range(1000):save(x) #simple iteration > > t1 = Timer("f1()", "from __main__ import f1") > print "f1", t1.timeit(number=1000) > > t2 = Timer("f2()", "from __main__ import f2") > print "f2", t2.timeit(number=1000) > > t3 = Timer("f3()", "from __main__ import f3") > print "f3", t3.timeit(number=1000) > > The output for one run was: > > f1 0.393015034034 > f2 0.476230638252 > f3 0.376324923978 > > => simple for loop performs better than map/imap. Interesting. So you've found the fastest solution already. If a simple for loop is both the most readable and the fastest way to do it, it sounds to me like you have solved your problem yourself. > Another problem with > map/imap is that the memory cost is dependent on the length of the list > (because of the intermediate mapped list stored) which is not the case for > simple for loop. ... neither is it the case for the imap() solution - but that still proves to be slower in your timings. BTW, assuming that you are using Python 2, you'd better use xrange() in benchmarks. The list creation of range() can easily spoil your timings. Stefan From debatem1 at gmail.com Wed May 26 17:51:45 2010 From: debatem1 at gmail.com (geremy condra) Date: Wed, 26 May 2010 14:51:45 -0700 Subject: Inheritable Slots Metaclass In-Reply-To: <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: On Wed, May 26, 2010 at 1:50 PM, Carl Banks wrote: > On May 26, 5:49?am, Rebel Lion wrote: >> I made a metaclass to inherit __slots__ automatically. >> >> I think this feature should be included in builtin object's metaclass. > > I'd be ok with a metatype in the standard library that makes slots > more transparent, but since slots are intended as an optimization, it > doesn't really need (and might be detrimental to have) transparency > for ordinary objects. > > However, Aahz will be by shortly to tell you never to use slots. Ok, I'll bite: why? Geremy Condra From lists at cheimes.de Wed May 26 18:24:04 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 27 May 2010 00:24:04 +0200 Subject: Another Little MySQL Problem In-Reply-To: <4bfd9b4e$0$1667$742ec2ed@news.sonic.net> References: <4bfd7436$0$1611$742ec2ed@news.sonic.net> <2lfLn.104252$Qg5.19019@newsfe06.ams2> <4bfd9b4e$0$1667$742ec2ed@news.sonic.net> Message-ID: > Actually, no. The names of tables are not quoted in SQL. > One writes > > SELECT ID FROM mytable; > > not > > SELECT ID FROM "mytable"; nit picking mode: Some RDBMS support case sensitive table names. You have to quote the table name if you using the feature. Yeah I know, it's pretty bad idea but it's possible. Christian From nagle at animats.com Wed May 26 18:30:16 2010 From: nagle at animats.com (John Nagle) Date: Wed, 26 May 2010 15:30:16 -0700 Subject: Another Little MySQL Problem In-Reply-To: <2lfLn.104252$Qg5.19019@newsfe06.ams2> References: <4bfd7436$0$1611$742ec2ed@news.sonic.net> <2lfLn.104252$Qg5.19019@newsfe06.ams2> Message-ID: <4bfd9b4e$0$1667$742ec2ed@news.sonic.net> Alister wrote: > I think you should probably also write your execute differently: > >>>> clientCursor.execute('select ID from %s' , (personalDataTable,)) > > this ensures the parameters are correctly escaped to prevent mysql > injection attacks,the "," after personalDataTable is necessary to ensure > the parameter is passed as a tuple Actually, no. The names of tables are not quoted in SQL. One writes SELECT ID FROM mytable; not SELECT ID FROM "mytable"; so you don't want to run table names through the quoting and escaping function. If the table name is a variable, you need to be very careful about where it comes from. On the other hand, if you're specifying a data value, a field that's normally quoted, as in SELECT ID from mytable WHERE mykey="foo"; you write cursor.execute("SELECT ID FROM mytable WHERE mykey=%s", (mykeyval,)) to get proper escaping. Don't put quote marks around the %s; MySQLdb does that. Also, if you're selecting every entry in a database, without a WHERE or ORDER BY clause, you will get the entries in more or less random order. John Nagle From cs at zip.com.au Wed May 26 18:35:05 2010 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 27 May 2010 08:35:05 +1000 Subject: atexit/signal for non-interactive jobs In-Reply-To: References: Message-ID: <20100526223505.GA2647@cskk.homeip.net> On 26May2010 20:19, kj wrote: | If I start the script interactively and after a few seconds (i.e. | before it terminates) I hit Ctrl-C (which sends a TERM signal to | the process), the wrapup function gets called as desired (although | this action appears to be triggered by atexit, and not by the | handler for SIGTERM, which apparently never gets called). I hate to tell you this, but ^C sends SIGINT, not SIGTERM. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ To have no errors Would be life without meaning No struggle, no joy - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html From pavlovevidence at gmail.com Wed May 26 18:42:43 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 May 2010 15:42:43 -0700 (PDT) Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: <39b6ff82-f3ae-433c-bc13-64215a81e0d5@40g2000vbr.googlegroups.com> On May 26, 2:51?pm, geremy condra wrote: > On Wed, May 26, 2010 at 1:50 PM, Carl Banks wrote: > > On May 26, 5:49?am, Rebel Lion wrote: > >> I made a metaclass to inherit __slots__ automatically. > > >> I think this feature should be included in builtin object's metaclass. > > > I'd be ok with a metatype in the standard library that makes slots > > more transparent, but since slots are intended as an optimization, it > > doesn't really need (and might be detrimental to have) transparency > > for ordinary objects. > > > However, Aahz will be by shortly to tell you never to use slots. > > Ok, I'll bite: why? I was just razzing him a bit. Carl Banks From !nospam!astrochelonian at gmail.com Wed May 26 21:01:06 2010 From: !nospam!astrochelonian at gmail.com (Eduardo Alvarez) Date: Wed, 26 May 2010 21:01:06 -0400 Subject: confusing error with nntplib Message-ID: When trying to use nntplib to connect to the news server nntp.aioe.org, a bizarre sequence of events occurs: 1) I import the module, and create an instance, as follows: s = nntplib.NNTP('nntp.aioe.org') I get no errors, which leads me to believe all went well. The I try fetching info on a newsgroup (in this case, comp.lang.python): s.group('comp.lang.python') I then get the following error: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/nntplib.py", line 345, in group resp = self.shortcmd('GROUP ' + name) File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd return self.getresp() File "/usr/lib/python2.6/nntplib.py", line 214, in getresp resp = self.getline() File "/usr/lib/python2.6/nntplib.py", line 206, in getline if not line: raise EOFError EOFError Running this a *second* time, gives me the following, different error: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/nntplib.py", line 345, in group resp = self.shortcmd('GROUP ' + name) File "/usr/lib/python2.6/nntplib.py", line 258, in shortcmd self.putcmd(line) File "/usr/lib/python2.6/nntplib.py", line 198, in putcmd self.putline(line) File "/usr/lib/python2.6/nntplib.py", line 193, in putline self.sock.sendall(line) File "", line 1, in sendall socket.error: [Errno 32] Broken pipe As this is a broken pipe, I reconnect to the server, the same way as before. When I *then* retrieving the newsgroup's info, I get no errors. I'm pretty baffled by this. It might be an issue with the server itself, but still, any input would be very appreciated. yours, -- Eduardo Alvarez "Stercus, Stercus, Stercus, moriturus sum" -- Rincewind The Wizzard From r3831110n at gmail.com Wed May 26 23:33:41 2010 From: r3831110n at gmail.com (Rebel Lion) Date: Wed, 26 May 2010 20:33:41 -0700 (PDT) Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: > I'd be ok with a metatype in the standard library that makes slots > more transparent, but since slots are intended as an optimization, it > doesn't really need (and might be detrimental to have) transparency > for ordinary objects. > But why there is __slots__ if it's not indeed needed. we should make it more usable instead of a hack, which it now looks like. > However, Aahz will be by shortly to tell you never to use slots. Obviously he didn't work on graphs, at least huge graphs. > It seems like a good approach, but the use of decorators to define > slots is hideous. ?I'd recommend creating slots with simple assignment > instead: > > slot = object() > > class Foo(): > ? ? __metaclass__ = SlotsMetaclass > ? ? foo = slot > > class Bar(): > ? ? bar = slot > > Then replace > > "isinstance(v,slot)" with "v is slot" > > in the metaclass. > This is a style not a problem. My way intents to keep the consistency with @property > You don't need to create a temporary class here; you should loop > through the base classes and inspect their slots. ? As you can see, I'm very lazy. If we got some decision here, we can surely make a better implementation that this hack. > Also, you don't > need to recreate slots that exist in base classes, so you could just > get all the new slots from the class dict. > > You should consider corner cases if you think it should be standard. > For instance, what if a derived class defined the same slot as a a > base class--it'll create a new slot in yours but it shouldn't. ?What > if you want to create a subclass that does have a dict? ?Can't do it > in your version. ?You need to consider stuff like that. > The most arguable point here. I raise this post inorder to make slot inheritable. In most cases, if a class uses slots, it is designed to be heavily used. Ans subclass of it should be heavily used too, but in this case you want to create __slots__, you have to manually lookup __slots__ of bases. But your corner is considerable. We can offer a __no_slots__ to disable slots. In conclusion, my point is: If you don't want to use slots in common days, you can subclass a class which doesn't use slots(in most cases) If you want to use slots, you need inherit parent classes' slots(in a few cases) If you don't want to use slots when you are subclassing a class which uses slots(in few cases): use a __noslots__ magic Regards, From alister.ware at ntlworld.com Thu May 27 00:10:40 2010 From: alister.ware at ntlworld.com (Alister) Date: Thu, 27 May 2010 04:10:40 GMT Subject: Another Little MySQL Problem References: <4bfd7436$0$1611$742ec2ed@news.sonic.net> <2lfLn.104252$Qg5.19019@newsfe06.ams2> <4bfd9b4e$0$1667$742ec2ed@news.sonic.net> Message-ID: <4hmLn.55618$vl7.47083@newsfe07.ams2> On Wed, 26 May 2010 15:30:16 -0700, John Nagle wrote: > Alister wrote: >> I think you should probably also write your execute differently: >> >>>>> clientCursor.execute('select ID from %s' , (personalDataTable,)) >> >> this ensures the parameters are correctly escaped to prevent mysql >> injection attacks,the "," after personalDataTable is necessary to >> ensure the parameter is passed as a tuple > > Actually, no. The names of tables are not quoted in SQL. > One writes > > SELECT ID FROM mytable; > > not > > SELECT ID FROM "mytable"; > > so you don't want to run table names through the quoting and escaping > function. If the table name is a variable, you need to be very careful > about where it comes from. > > On the other hand, if you're specifying a data value, a field that's > normally quoted, as in > > SELECT ID from mytable WHERE mykey="foo"; > > you write > > cursor.execute("SELECT ID FROM mytable WHERE mykey=%s", (mykeyval,)) > > to get proper escaping. Don't put quote marks around the %s; MySQLdb > does that. > > Also, if you're selecting every entry in a database, without a > WHERE or ORDER BY clause, you will get the entries in more or less > random order. > > John Nagle Thanks i hadn't read the search string fully. in this case if personalDataTable is generated by user input it should be carefully checked as it will still be a possible source of attack. The golden rule with user input is trust nothing. -- QOTD: "I won't say he's untruthful, but his wife has to call the dog for dinner." From nagle at animats.com Thu May 27 00:19:46 2010 From: nagle at animats.com (John Nagle) Date: Wed, 26 May 2010 21:19:46 -0700 Subject: Inheritable Slots Metaclass In-Reply-To: References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: <4bfded38$0$1644$742ec2ed@news.sonic.net> Rebel Lion wrote: >> I'd be ok with a metatype in the standard library that makes slots >> more transparent, but since slots are intended as an optimization, it >> doesn't really need (and might be detrimental to have) transparency >> for ordinary objects. >> > > But why there is __slots__ if it's not indeed needed. we should make > it more usable instead of a hack, which it now looks like. > >> However, Aahz will be by shortly to tell you never to use slots. I'd argue that "slotting" of classes should be automatic, unless a class 1) defines "__setattr__" or 2) performs an operation which visibly creates a class attribute, like "self[foo] = ...". This would handle the common use cases. Only classes to which attributes are added from outside the class would be affected. And really, if you're going to do that, you should subclass. John Nagle From pavlovevidence at gmail.com Thu May 27 00:55:54 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 May 2010 21:55:54 -0700 (PDT) Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: <381f0994-3a14-4247-862e-bc24d1d5a6bf@j36g2000prj.googlegroups.com> On May 26, 8:33?pm, Rebel Lion wrote: > > I'd be ok with a metatype in the standard library that makes slots > > more transparent, but since slots are intended as an optimization, it > > doesn't really need (and might be detrimental to have) transparency > > for ordinary objects. > > But why there is __slots__ if it's not indeed needed. we should make > it more usable instead of a hack, which it now looks like. It is needed--for optimization. The thinking is that for most uses it is not a good idea to defeat Python's dynamicsm, therefore making it too easy to add slots would be detrimental to the community because it would encourage people to use slots even when not needed. I more or less agree with this, and would be very -1 on any attempt to mske slots the "default", so to speak; however I don't think it would make slots dangerously accessible to have a user import a module and explicitly set the metaclass, for the benefit of getting rid of their weirdness. > > However, Aahz will be by shortly to tell you never to use slots. > > Obviously he didn't work on graphs, at least huge graphs. There's no need to be presumptuous. You can state your use case with accusing him of anything. > > It seems like a good approach, but the use of decorators to define > > slots is hideous. ?I'd recommend creating slots with simple assignment > > instead: > > > slot = object() > > > class Foo(): > > ? ? __metaclass__ = SlotsMetaclass > > ? ? foo = slot > > > class Bar(): > > ? ? bar = slot > > > Then replace > > > "isinstance(v,slot)" with "v is slot" > > > in the metaclass. > > This is a style not a problem. My way intents to keep the consistency > with @property It's a problem if you think this metaclass ought to be in the standard library. This "style" will never, ever make it to the standard library, ever. I guarantee you. Frankly, you're observing a pattern where there is none. You see decorator syntax and you think "Ah, that's the standard way to define attributes that affect the behavior of a class". It's not. Descriptor syntax is syntax sugar to make it less unwieldy to apply a function to a function or class. That's it, that's all it is. If you don't have a function, there is no reason for a decorator. You're entitled to your own preferred style, of course, but I'm just telling you it'll never fly with most people. > > You don't need to create a temporary class here; you should loop > > through the base classes and inspect their slots. ? > > As you can see, I'm very lazy. If we got some decision here, we can > surely make a better implementation that this hack. No, sorry, it doesn't work that way. Unless you're a known genius and/ or a long time contributor, you better have some pretty worked out code and some persuasive use cases if you want any consideration. Ideas are cheap. (If you want some inspiration, go read PEP 389.) > > Also, you don't > > need to recreate slots that exist in base classes, so you could just > > get all the new slots from the class dict. > > > You should consider corner cases if you think it should be standard. > > For instance, what if a derived class defined the same slot as a a > > base class--it'll create a new slot in yours but it shouldn't. ?What > > if you want to create a subclass that does have a dict? ?Can't do it > > in your version. ?You need to consider stuff like that. > > The most arguable point here. I raise this post inorder to make slot > inheritable. Slots already are inheritable, as I pointed out. It's just weird and complicated how they affect things. class A(object): __slots__ = ['a'] class B(A): __slots__ = ['b'] B().a = 1 # this will work > In most cases, if a class uses slots, it is designed to be heavily > used. > Ans subclass of it should be heavily used too, but in this case you > want to create __slots__, > you have to manually lookup __slots__ of bases. You don't have to, unless you want to work around some of those other corner cases I spoke of. > But your corner is considerable. We can offer a __no_slots__ to > disable slots. > > In conclusion, my point is: > > If you don't want to use slots in common days, you can subclass a > class which doesn't use slots(in most cases) > If you want to use slots, you need inherit parent classes' slots(in a > few cases) > If you don't want to use slots when you are subclassing a class which > uses slots(in few cases): > ? use a __noslots__ magic That seems like a reasonable way to handle it. I don't want to sound to pessimistic about it, I really wouldn't mind a metaclass that makes slots more normal; but you have work to do. Carl Banks From kushal.kumaran+python at gmail.com Thu May 27 01:00:14 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 10:30:14 +0530 Subject: UnicodeDecodeError having fetch web page In-Reply-To: References: <83dc485a-5a20-403b-99ee-c8c627bdbab3@m21g2000vbr.googlegroups.com> <1274889564.2339.16.camel@nitrogen> Message-ID: On Wed, May 26, 2010 at 11:40 PM, Rob Williscroft wrote: > Kushal Kumaran wrote in news:1274889564.2339.16.camel at nitrogen in > gmane.comp.python.general: > >> On Tue, 2010-05-25 at 20:12 +0000, Rob Williscroft wrote: >>> Barry wrote in news:83dc485a-5a20-403b-99ee-c8c627bdbab3 >>> @m21g2000vbr.googlegroups.com in gmane.comp.python.general: >>> >>> > Hi, >>> > >>> > The code below is giving me the error: >>> > >>> > Traceback (most recent call last): >>> > ? File "C:\Users\Administrat?r\Desktop\test.py", line 4, in >>> > ? >>> > UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position >>> > 1: unexpected code byte >>> > >>> > >>> > What am i doing wrong? >>> >>> It may not be you, en.wiktionary.org is sending gzip >>> encoded content back, it seems to do this even if you set >>> the Accept header as in: >>> >>> request.add_header( "Accept", "text/html" ) >>> >>> But maybe I'm not doing it correctly. >>> >> You need the Accept-Encoding: identity header. >> http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html > > Thanks, following this I did change the line to be: > > request.add_header( "Accept-Encoding", "identity" ) > > but it made no difference to en.wiktionary.org it just sent the > back a gzip encoded response. > A known problem, I guess... https://bugzilla.wikimedia.org/show_bug.cgi?id=7098 You'll just have to handle the gzipped data. -- regards, kushal From pavlovevidence at gmail.com Thu May 27 01:16:16 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 May 2010 22:16:16 -0700 (PDT) Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> <381f0994-3a14-4247-862e-bc24d1d5a6bf@j36g2000prj.googlegroups.com> Message-ID: <21eb799f-f7ff-4d94-966d-d4a69a419583@a39g2000prb.googlegroups.com> On May 26, 9:55?pm, Carl Banks wrote: > I don't want to sound to pessimistic about it, I really wouldn't mind > a metaclass that makes slots more normal; but you have work to do. Just as a minor followup, I'll mention that slots and inheritance have some issues that aren't going to be resolvable to everyone's satisfaction, and that's another reason why I don't think slots should be accessible by default. For instance, some might assume that deriving from a class with slots automatically grants the derived class the same optimization that the base class has. Others will not even consider that the base class has slots and will assume that their derived class has dynamic attributes like most other Python classes. Who's right? I'd go with the former, for the same reason you gave, but the latter is not unreasonable. type does the latter. The best answer might be to always insist on an explicit declaration one way or another, but that makes it prone to other problems like forward compatibility issues. Point is, it's not a simple thing. Carl Banks From wuwei23 at gmail.com Thu May 27 01:16:35 2010 From: wuwei23 at gmail.com (alex23) Date: Wed, 26 May 2010 22:16:35 -0700 (PDT) Subject: Kohonen neural network References: <260cd874-fe51-4bdd-b112-f64ff7ef3050@a27g2000prj.googlegroups.com> Message-ID: <2006f79a-3d52-4dcc-b099-3ef3b3904c3a@a16g2000prg.googlegroups.com> Lex Lebedeff wrote: > Thanx, I've already googled this stuff. Rather unreadable and freaky code. Then please remember to mention what you've already seen & tried when asking in the future, it saves us all from wasting each others time. From kse.listed.co1 at gmail.com Thu May 27 01:37:29 2010 From: kse.listed.co1 at gmail.com (Naeem) Date: Wed, 26 May 2010 22:37:29 -0700 (PDT) Subject: "AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION" Message-ID: "AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION""AUSTRALIAN LEADERSHIP AWARDS SCHOLARSHIPS FOR THE YEAR 2010 - 2011" on http://scholarships-education.blogspot.com/2010/05/australian-leadership-awards.html "SCHOLARSHIPS IN AUSTRALIA, UK, CANADA, PAKISTAN, AMERICA, EUROPEAN UNION" From mail at timgolden.me.uk Thu May 27 03:39:11 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 May 2010 08:39:11 +0100 Subject: Another Little MySQL Problem In-Reply-To: References: <4bfd7436$0$1611$742ec2ed@news.sonic.net> <2lfLn.104252$Qg5.19019@newsfe06.ams2> <4bfd9b4e$0$1667$742ec2ed@news.sonic.net> Message-ID: <4BFE219F.4020006@timgolden.me.uk> On 26/05/2010 23:24, Christian Heimes wrote: >> Actually, no. The names of tables are not quoted in SQL. >> One writes >> >> SELECT ID FROM mytable; >> >> not >> >> SELECT ID FROM "mytable"; > > nit picking mode: > > Some RDBMS support case sensitive table names. You have to quote the > table name if you using the feature. Yeah I know, it's pretty bad idea > but it's possible. Also -- at least in MSSQL -- if the table name contains spaces (and probably certain other characters which I can't be bothered to research at this moment). TJG From alfps at start.no Thu May 27 06:43:17 2010 From: alfps at start.no (Alf P. Steinbach) Date: Thu, 27 May 2010 12:43:17 +0200 Subject: confusing error with nntplib In-Reply-To: References: Message-ID: * Eduardo Alvarez, on 27.05.2010 03:01: > When trying to use nntplib to connect to the news server nntp.aioe.org, > a bizarre sequence of events occurs: > > 1) I import the module, and create an instance, as follows: > > s = nntplib.NNTP('nntp.aioe.org') > > I get no errors, which leads me to believe all went well. The I try > fetching info on a newsgroup (in this case, comp.lang.python): > > s.group('comp.lang.python') > > I then get the following error: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/nntplib.py", line 345, in group > resp = self.shortcmd('GROUP ' + name) > File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd > return self.getresp() > File "/usr/lib/python2.6/nntplib.py", line 214, in getresp > resp = self.getline() > File "/usr/lib/python2.6/nntplib.py", line 206, in getline > if not line: raise EOFError > EOFError This sounds like a time-out. > Running this a *second* time, gives me the following, different error: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/nntplib.py", line 345, in group > resp = self.shortcmd('GROUP ' + name) > File "/usr/lib/python2.6/nntplib.py", line 258, in shortcmd > self.putcmd(line) > File "/usr/lib/python2.6/nntplib.py", line 198, in putcmd > self.putline(line) > File "/usr/lib/python2.6/nntplib.py", line 193, in putline > self.sock.sendall(line) > File "", line 1, in sendall > socket.error: [Errno 32] Broken pipe When you say "running this", do you mean running a Python program a second time, or issuing the same command in the interpreter a second time? For the latter the result would be more or less expected. After all, you've had an End of File on the connection. > As this is a broken pipe, I reconnect to the server, the same way as > before. When I *then* retrieving the newsgroup's info, I get no errors. > > I'm pretty baffled by this. It might be an issue with the server itself, > but still, any input would be very appreciated. Check if there's any way to specify time-outs. Check if there's any way to trace the actual commands and responses. Cheers & hth., - Alf -- blog at From timoverbeek10 at gmail.com Thu May 27 07:16:11 2010 From: timoverbeek10 at gmail.com (timo verbeek) Date: Thu, 27 May 2010 04:16:11 -0700 (PDT) Subject: type error raise Message-ID: <592e4b41-d00d-4e33-a913-fa0dc42f8b4a@c22g2000vbb.googlegroups.com> what is the problem with this code? _base={"repeat":False,"string":"Progres has failed","works":True} print _base class dictreturn(_base):pass this error Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\Documents and Settings\Owner\Desktop\Python\assistent new \user\dictreturn.py", line 4, in class dictreturn(_base):pass TypeError: Error when calling the metaclass bases From clp2 at rebertia.com Thu May 27 07:22:25 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 May 2010 04:22:25 -0700 Subject: type error raise In-Reply-To: <592e4b41-d00d-4e33-a913-fa0dc42f8b4a@c22g2000vbb.googlegroups.com> References: <592e4b41-d00d-4e33-a913-fa0dc42f8b4a@c22g2000vbb.googlegroups.com> Message-ID: On Thu, May 27, 2010 at 4:16 AM, timo verbeek wrote: > what is the problem with this code? > > _base={"repeat":False,"string":"Progres has failed","works":True} > print _base > class dictreturn(_base):pass You can't subclass a dictionary object, you can only subclass other classes. What on earth are you trying to do? Cheers, Chris -- http://blog.rebertia.com From martin.hellwig at dcuktec.org Thu May 27 07:25:11 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 27 May 2010 12:25:11 +0100 Subject: confusing error with nntplib In-Reply-To: References: Message-ID: On 05/27/10 02:01, Eduardo Alvarez wrote: > When trying to use nntplib to connect to the news server nntp.aioe.org, > a bizarre sequence of events occurs: > > 1) I import the module, and create an instance, as follows: > > s = nntplib.NNTP('nntp.aioe.org') > > I get no errors, which leads me to believe all went well. The I try > fetching info on a newsgroup (in this case, comp.lang.python): > > s.group('comp.lang.python') > > I then get the following error: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/nntplib.py", line 345, in group > resp = self.shortcmd('GROUP ' + name) > File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd > return self.getresp() > File "/usr/lib/python2.6/nntplib.py", line 214, in getresp > resp = self.getline() > File "/usr/lib/python2.6/nntplib.py", line 206, in getline > if not line: raise EOFError > EOFError > > Running this a *second* time, gives me the following, different error: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/nntplib.py", line 345, in group > resp = self.shortcmd('GROUP ' + name) > File "/usr/lib/python2.6/nntplib.py", line 258, in shortcmd > self.putcmd(line) > File "/usr/lib/python2.6/nntplib.py", line 198, in putcmd > self.putline(line) > File "/usr/lib/python2.6/nntplib.py", line 193, in putline > self.sock.sendall(line) > File "", line 1, in sendall > socket.error: [Errno 32] Broken pipe > > As this is a broken pipe, I reconnect to the server, the same way as > before. When I *then* retrieving the newsgroup's info, I get no errors. > > I'm pretty baffled by this. It might be an issue with the server itself, > but still, any input would be very appreciated. > > yours, > Here is how I approached it: # Lets see first if the server is available [martin at aspire8930 /usr/home/martin]$ telnet nntp.aioe.org nntp Trying 94.75.214.90... Connected to nntp.aioe.org. Escape character is '^]'. 200 nntp.aioe.org InterNetNews NNRP server INN 2.5.1 ready (posting ok) ^] telnet> quit Connection closed. # Okidoki seems fine # lets fire up python [martin at aspire8930 /usr/home/martin]$ python Python 2.6.4 (r264:75706, Apr 9 2010, 12:45:45) [GCC 4.2.1 20070719 [FreeBSD]] on freebsd8 Type "help", "copyright", "credits" or "license" for more information. >>> import nntplib >>> s = nntplib.NNTP('nntp.aioe.org') >>> s.group('comp.lang.python') Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.6/nntplib.py", line 345, in group resp = self.shortcmd('GROUP ' + name) File "/usr/local/lib/python2.6/nntplib.py", line 259, in shortcmd return self.getresp() File "/usr/local/lib/python2.6/nntplib.py", line 214, in getresp resp = self.getline() File "/usr/local/lib/python2.6/nntplib.py", line 206, in getline if not line: raise EOFError EOFError # Ah yes the same error, good at least the same problem. # Lets see what the docs has to say about it. >>> help(nntplib.NNTP) Help on class NNTP in module nntplib: class NNTP | # The class itself | | Methods defined here: | | __init__(self, host, port=119, user=None, password=None, readermode=None, usenetrc=True) | Initialize an instance. Arguments: | - host: hostname to connect to | - port: port to connect to (default the standard NNTP port) | - user: username to authenticate with | - password: password to use with username | - readermode: if true, send 'mode reader' command after | connecting. | | readermode is sometimes necessary if you are connecting to an | NNTP server on the local machine and intend to call | reader-specific comamnds, such as `group'. If you get | unexpected NNTPPermanentErrors, you might need to set | readermode. | # readermode seems to be worth a shot: >>> s = nntplib.NNTP('nntp.aioe.org', readermode=True) >>> s.group('comp.lang.python') ('211 2444 50405 52862 comp.lang.python', '2444', '50405', '52862', 'comp.lang.python') >>> # okidoki got something, but I have no idea why, perhaps need to have # a look at the source to see what that mode actually does. # But then again I think it would be better if you would do # that and if you are feeling generous might contribute back # to this thread what your findings where. -- mph From __peter__ at web.de Thu May 27 07:27:45 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 May 2010 13:27:45 +0200 Subject: confusing error with nntplib References: Message-ID: Eduardo Alvarez wrote: > When trying to use nntplib to connect to the news server nntp.aioe.org, > a bizarre sequence of events occurs: > > 1) I import the module, and create an instance, as follows: > > s = nntplib.NNTP('nntp.aioe.org') > > I get no errors, which leads me to believe all went well. The I try > fetching info on a newsgroup (in this case, comp.lang.python): > > s.group('comp.lang.python') > > I then get the following error: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/nntplib.py", line 345, in group > resp = self.shortcmd('GROUP ' + name) > File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd > return self.getresp() > File "/usr/lib/python2.6/nntplib.py", line 214, in getresp > resp = self.getline() > File "/usr/lib/python2.6/nntplib.py", line 206, in getline > if not line: raise EOFError > EOFError > I'm pretty baffled by this. It might be an issue with the server itself, > but still, any input would be very appreciated. I tried your example and got the EOFError, too. >>> import nntplib >>> s = nntplib.NNTP("nntp.aioe.org") >>> s.group("comp.lang.python") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/nntplib.py", line 345, in group resp = self.shortcmd('GROUP ' + name) File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd return self.getresp() File "/usr/lib/python2.6/nntplib.py", line 214, in getresp resp = self.getline() File "/usr/lib/python2.6/nntplib.py", line 206, in getline if not line: raise EOFError EOFError >>> s = nntplib.NNTP("nntp.aioe.org", readermode=True) >>> s.group("comp.lang.python") ('211 2445 50405 52863 comp.lang.python', '2445', '50405', '52863', 'comp.lang.python') nntplib.NNTP(host, readermode=True) seems to fix the problem (if it wasn't sheer luck). Peter From henrikho at gmail.com Thu May 27 08:22:55 2010 From: henrikho at gmail.com (HH) Date: Thu, 27 May 2010 05:22:55 -0700 (PDT) Subject: if, continuation and indentation Message-ID: I have a question about best practices when it comes to line wrapping/ continuation and indentation, specifically in the case of an if statement. When I write an if statement with many conditions, I prefer to use a parenthesis around the whole block and get the implicit continuation, rather than ending each line with an escape character. Thus, using the example from the style guide (http://www.python.org/dev/peps/ pep-0008/) I would write: if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") The problem should be obvious -- it's not easy to see where the conditional ends and the statement begins since they have the same indentation. Part of the problem, I suppose, is that Emacs indents 'height' and the other lines in the conditional to 4 spaces (because of the parenthesis). How do people deal with this situation? Thanks, Henrik From victorsubervi at gmail.com Thu May 27 08:34:48 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 08:34:48 -0400 Subject: Yet Another MySQL Problem Message-ID: Hi; I have this code: sql = "insert into %s (%s) values ('%%s');" % (personalDataTable, string.join(cols[1:], ', ')) # cursor.execute(sql, string.join(vals[1:], "', '")) cursor.execute('insert into %s (%s) values ("%s");' % (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '", "'))) Now, if I uncomment the 2nd line and comment the third, the command fails because, apparently, that "');" at the tail end of sql (1st line) gets chopped off. Why?? TIA, beno (Note to self: enterPeople3.py) -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric.brunel.pragmadev at gmail.com Thu May 27 08:37:36 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Thu, 27 May 2010 05:37:36 -0700 (PDT) Subject: Minor annoyances with properties Message-ID: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Hello all, I've been using Python properties quite a lot lately and I've found a few things that are a bit annoying about them in some cases. I wondered if I missed something or if anybody else has this kind of problems too, and if there are better solutions than the ones I'm using ATM. The first annoyance is when I want to specialize a property in a subclass. This happens quite often actually, and it is even sometimes the reason why a plain attribute is turned into a property: a subclass needs to do more things than the superclass when the property is updated for example. So, of course, my first try was: class A(object): def __init__(self): self._p = None def _get_p(self): return self._p def _set_p(self, p): self._p = p p = property(_get_p, _set_p) class B(A): def _set_p(self, p): ## Additional things here? super(B, self)._set_p(p) And of course, it doesn't work: the property has been bound to A._set_p in A, so any new definition of _set_p in any subclass does not replace the set method for the property. So I always have to add a line: p = property(A._get_p, _set_p) in the subclass too. This is a bit awkward to me, since I have to specify the superclass's name (super(?) can't be used, since it should take B as an argument, and B isn't defined yet?). Do I miss something? Is this the way to do it, or is there a better one? The second annoyance is when I have a property that is a list of something. I often have to do something when the contents of the list is modified. So basically, I often end up doing the following: def C(object): def __init__(self): self._l = [] def _get_l(self): return list(self._l) def _set_l(self, l): self._l = list(l) l = property(_get_l, _set_l) But then, I have to do: o = C() l = o.l l.append(42) o.l = l instead of just doing: o.l.append(42) which would seem much more natural IMHO. Is there any not too complicated way to have o.l.append(?) call something in C? And the same for o.l.remove(?), o.l[i] = ?, and everything else updating the list contents? Thanks! - Eric - From contact at xavierho.com Thu May 27 08:48:01 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 May 2010 22:48:01 +1000 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: On 27 May 2010 22:22, HH wrote: > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") > I've gotta say - I've bumped into this problem before, and I'm sure many other have - this is a valid question. It just hasn't bothered me enough to ask... Correct me if I'm wrong, but I think the following is equivalent, and looks better. Although this won't fix all ugly cases in that problem. if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or highlight > 100: raise ValueError("sorry, you lose") Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.hellwig at dcuktec.org Thu May 27 08:54:08 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 27 May 2010 13:54:08 +0100 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: On 05/27/10 13:22, HH wrote: > I have a question about best practices when it comes to line wrapping/ > continuation and indentation, specifically in the case of an if > statement. > > When I write an if statement with many conditions, I prefer to use a > parenthesis around the whole block and get the implicit continuation, > rather than ending each line with an escape character. Thus, using > the example from the style guide (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100): > raise ValueError("sorry, you lose") > > The problem should be obvious -- it's not easy to see where the > conditional ends and the statement begins since they have the same > indentation. Part of the problem, I suppose, is that Emacs indents > 'height' and the other lines in the conditional to 4 spaces (because > of the parenthesis). How do people deal with this situation? > > Thanks, > Henrik Well style guide aside (if pylint is happy with it, so am I) it depends on what I want to emphasize. For example if it is really one long line with every item in it being equally important I do this: if width == 0 and height == 0 and color == 'red' and emphasis == 'strong' \ or highlight > 100: raise ValueError("sorry, you lose") In case it doesn't display correctly, I break up the line to nearest 80th character and align the remaining part on the next line to the right to the 80th character. If I want to emphasize visually a certain part I would do something like this: if width == 0 and height == 0 and color == 'red' \ and emphasis == 'strong' or highlight > 100: raise ValueError("sorry, you lose") But these are my preference, and since it is most likely that I have to read again what I have written I write it in a way that it is most readable to me within the constraints of pylint. -- mph From jeanmichel at sequans.com Thu May 27 08:57:54 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 27 May 2010 14:57:54 +0200 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: <4BFE6C52.1060202@sequans.com> HH wrote: > I have a question about best practices when it comes to line wrapping/ > continuation and indentation, specifically in the case of an if > statement. > > When I write an if statement with many conditions, I prefer to use a > parenthesis around the whole block and get the implicit continuation, > rather than ending each line with an escape character. Thus, using > the example from the style guide (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") > > The problem should be obvious -- it's not easy to see where the > conditional ends and the statement begins since they have the same > indentation. Part of the problem, I suppose, is that Emacs indents > 'height' and the other lines in the conditional to 4 spaces (because > of the parenthesis). How do people deal with this situation? > > Thanks, > Henrik > One possible solution if ( width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100 ): raise ValueError("sorry, you lose") JM From neilc at norwich.edu Thu May 27 09:14:05 2010 From: neilc at norwich.edu (Neil Cerutti) Date: 27 May 2010 13:14:05 GMT Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Message-ID: <8679gtFdj4U1@mid.individual.net> On 2010-05-27, eb303 wrote: > I've been using Python properties quite a lot lately and I've > found a few things that are a bit annoying about them in some > cases. I wondered if I missed something or if anybody else has > this kind of problems too, and if there are better solutions > than the ones I'm using ATM. > The first annoyance is when I want to specialize a property in a > subclass. See: URI:http://infinitesque.net/articles/2005/enhancing%20Python%27s%20property.xhtml -- Neil Cerutti *** You found a dead moose-rat. You sell the hide for $200. *** From contact at xavierho.com Thu May 27 09:14:49 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 May 2010 23:14:49 +1000 Subject: if, continuation and indentation In-Reply-To: <4BFE6C52.1060202@sequans.com> References: <4BFE6C52.1060202@sequans.com> Message-ID: On 27 May 2010 22:57, Jean-Michel Pichavant wrote: > One possible solution > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100 > ): > raise ValueError("sorry, you lose") > > But... but you have a sad face in one line! :( Good trick. -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Thu May 27 09:24:36 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 27 May 2010 15:24:36 +0200 Subject: Minor annoyances with properties In-Reply-To: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Message-ID: > Do I miss something? > Is this the way to do it, or is there a better one? A better way was introduced in Python 2.6. See http://docs.python.org/library/functions.html?highlight=property#property I have a Python only version around if you are still using Python 2.5. Christian From contact at xavierho.com Thu May 27 09:26:54 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 May 2010 23:26:54 +1000 Subject: if, continuation and indentation In-Reply-To: References: <4BFE6C52.1060202@sequans.com> Message-ID: On 27 May 2010 22:57, Jean-Michel Pichavant wrote: > One possible solution >> >> if ( >> width == 0 and >> height == 0 and >> color == 'red' and >> emphasis == 'strong' or >> highlight > 100 >> ): >> raise ValueError("sorry, you lose") >> > Oh, one minor optimisation. You can put the last condition first: if ( highlight > 100 or width == 0 and height == 0 and color == 'red' and emphasis == 'strong' ): raise ValueError("sorry, you lose") -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Thu May 27 09:34:04 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 09:34:04 -0400 Subject: Yet Another MySQL Problem In-Reply-To: References: Message-ID: On Thu, May 27, 2010 at 8:34 AM, Victor Subervi wrote: > Hi; > I have this code: > > sql = "insert into %s (%s) values ('%%s');" % (personalDataTable, > string.join(cols[1:], ', ')) > # cursor.execute(sql, string.join(vals[1:], "', '")) > cursor.execute('insert into %s (%s) values ("%s");' % > (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '", > "'))) > > Now, if I uncomment the 2nd line and comment the third, the command fails > because, apparently, that "');" at the tail end of sql (1st line) gets > chopped off. Why?? > > (Note to self: enterPeople3.py) > ...and here's another one: print 'insert into categories (Store, Category, Parent) values("%s", "%s", Null)'% (store, cat) # cursor.execute('insert into categories (Store, Category, Parent) values("%s", "%s", Null)', (store, cat)) If I print out and manually insert, all goes well. If I uncomment the 2nd line, it inserts store and cat with single quote marks and screws everything up! mysql> select * from categories; +----+------------+------------+--------+ | ID | Store | Category | Parent | +----+------------+------------+--------+ | 1 | 'products' | 'prodCat1' | NULL | | 2 | 'products' | 'prodCat2' | NULL | +----+------------+------------+--------+ as opposed to mysql> select * from categories; +----+------------+------------+--------+ | ID | Store | Category | Parent | +----+------------+------------+--------+ | 1 | products | prodCat1 | NULL | | 2 | products | prodCat2 | NULL | +----+------------+------------+--------+ TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Thu May 27 09:35:13 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 May 2010 23:35:13 +1000 Subject: if, continuation and indentation In-Reply-To: References: <4BFE6C52.1060202@sequans.com> Message-ID: On 27 May 2010 23:26, Xavier Ho wrote: > Oh, one minor optimisation. You can put the last condition first > I take that back. You really can't, without using more parans or ifs. Apologies. -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Thu May 27 10:10:55 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 27 May 2010 09:10:55 -0500 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: <4BFE7D6F.1070203@tim.thechases.com> On 05/27/2010 07:22 AM, HH wrote: > When I write an if statement with many conditions, I prefer to use a > parenthesis around the whole block and get the implicit continuation, > rather than ending each line with an escape character. Thus, using > the example from the style guide (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100): > raise ValueError("sorry, you lose") While it's not PEP material, I tend to use the coding standards I learned working for Computer Sciences Corporation (10 yrs ago, so things may have changed) that mandated 2 levels of indentation for continued lines, turning the above into if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight> 100): # or the closing "):" on this line, # aligned with the previous line raise ValueError("sorry, you lose") which is fairly close to Jean-Michel's proposal. -tkc From kushal.kumaran at gmail.com Thu May 27 10:17:53 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 19:47:53 +0530 Subject: Yet Another MySQL Problem In-Reply-To: References: Message-ID: <1274969873.2411.4.camel@nitrogen> On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote: > Hi; > I have this code: > > sql = "insert into %s (%s) values ('%%s');" % (personalDataTable, > string.join(cols[1:], ', ')) > # cursor.execute(sql, string.join(vals[1:], "', '")) > cursor.execute('insert into %s (%s) values ("%s");' % > (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], > '", "'))) > > Now, if I uncomment the 2nd line and comment the third, the command > fails because, apparently, that "');" at the tail end of sql (1st > line) gets chopped off. Why?? That's not why it is failing. The second argument to cursor.execute must be a tuple of values that will be escaped and interpolated into the query. You are passing in a string instead. Also, you'll need as many %s in the values clause as the number of columns you have. Basically, the query needs to be something like: insert into tablename (col1, col2, col3) values (%s, %s, %s) and the tuple argument to cursor.execute will have to have three values. Also, lose the single quotes around the %s. -- regards, kushal From kushal.kumaran at gmail.com Thu May 27 10:19:35 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 19:49:35 +0530 Subject: Yet Another MySQL Problem In-Reply-To: References: Message-ID: <1274969975.2411.6.camel@nitrogen> On Thu, 2010-05-27 at 09:34 -0400, Victor Subervi wrote: > On Thu, May 27, 2010 at 8:34 AM, Victor Subervi > wrote: > Hi; > I have this code: > > sql = "insert into %s (%s) values ('%%s');" % > (personalDataTable, string.join(cols[1:], ', ')) > # cursor.execute(sql, string.join(vals[1:], "', '")) > cursor.execute('insert into %s (%s) values ("%s");' % > (personalDataTable, string.join(cols[1:], ', '), > string.join(vals[1:], '", "'))) > > Now, if I uncomment the 2nd line and comment the third, the > command fails because, apparently, that "');" at the tail end > of sql (1st line) gets chopped off. Why?? > > (Note to self: enterPeople3.py) > > ...and here's another one: > > print 'insert into categories (Store, Category, Parent) > values("%s", "%s", Null)'% (store, cat) > # cursor.execute('insert into categories (Store, Category, > Parent) values("%s", "%s", Null)', (store, cat)) > Lose the quotes around the %s. I'm pretty sure somebody mentioned this in the previous MySQL problem thread. -- regards, kushal From victorsubervi at gmail.com Thu May 27 10:30:53 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 10:30:53 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <1274969873.2411.4.camel@nitrogen> References: <1274969873.2411.4.camel@nitrogen> Message-ID: On Thu, May 27, 2010 at 10:17 AM, Kushal Kumaran wrote: > On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote: > > Hi; > > I have this code: > > > > sql = "insert into %s (%s) values ('%%s');" % (personalDataTable, > > string.join(cols[1:], ', ')) > > # cursor.execute(sql, string.join(vals[1:], "', '")) > > cursor.execute('insert into %s (%s) values ("%s");' % > > (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], > > '", "'))) > > > > Now, if I uncomment the 2nd line and comment the third, the command > > fails because, apparently, that "');" at the tail end of sql (1st > > line) gets chopped off. Why?? > > That's not why it is failing. > > The second argument to cursor.execute must be a tuple of values that > will be escaped and interpolated into the query. You are passing in a > string instead. > So I tried this: sql = "insert into %s (%s) values (%%s);" % (personalDataTable, string.join(cols[1:], ', ')) cursor.execute(sql, vals[1:]) and got this: A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /var/www/html/angrynates.com/cart/enterPeople3.py 85 print "Enter more personal data?
" % personalDataTable 86 print "Enter products?" 87 print '\n' 88 89 enterPeople3() enterPeople3 = /var/www/html/angrynates.com/cart/enterPeople3.py in enterPeople3() 42 # We will not include the ID column 43 sql = "insert into %s (%s) values (%%s);" % (personalDataTable, string.join(cols[1:], ', ')) 44 cursor.execute(sql, vals[1:]) 45 # cursor.execute(sql, string.join(vals[1:], "', '")) 46 # cursor.execute('insert into %s (%s) values ("%s");' % (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '", "'))) cursor = , cursor.execute = >, sql = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email, PW, State, ShippingState) values (%s);', vals = ['Null', 'prescriptions', 'Beno', 'Candelon', '123', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR'] /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in execute(self=, query='insert into doctorsPersonalData (Store, FirstNam...OB, Email, PW, State, ShippingState) values (%s);', args=['prescriptions', 'Beno', 'Candelon', '123', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR']) 146 query = query.encode(charset) 147 if args is not None: 148 query = query % db.literal(args) 149 try: 150 r = self._query(query) query = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email, PW, State, ShippingState) values (%s);', db = , db.literal = >, args = ['prescriptions', 'Beno', 'Candelon', '123', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR'] TypeError: not all arguments converted during string formatting args = ('not all arguments converted during string formatting',) You sure about not converting to string?? Also, lose the single quotes around the %s. > Well, sure, if not converting to string. Otherwise it's needed. Dennis advised not using quotes, but what he meant was not using double quotes. Single quotes, I have found by experimentation, do work. TIA beno > > -- > regards, > kushal > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu May 27 10:32:53 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 May 2010 15:32:53 +0100 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: <4BFE8295.2090307@mrabarnett.plus.com> HH wrote: > I have a question about best practices when it comes to line wrapping/ > continuation and indentation, specifically in the case of an if > statement. > > When I write an if statement with many conditions, I prefer to use a > parenthesis around the whole block and get the implicit continuation, > rather than ending each line with an escape character. Thus, using > the example from the style guide (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") > > The problem should be obvious -- it's not easy to see where the > conditional ends and the statement begins since they have the same > indentation. Part of the problem, I suppose, is that Emacs indents > 'height' and the other lines in the conditional to 4 spaces (because > of the parenthesis). How do people deal with this situation? > I would probably use half-indentation: if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100): raise ValueError("sorry, you lose") Try doing that with tabs! :-) From kushal.kumaran at gmail.com Thu May 27 11:17:04 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 20:47:04 +0530 Subject: Yet Another MySQL Problem In-Reply-To: References: <1274969873.2411.4.camel@nitrogen> Message-ID: <1274973424.2411.13.camel@nitrogen> On Thu, 2010-05-27 at 10:30 -0400, Victor Subervi wrote: > On Thu, May 27, 2010 at 10:17 AM, Kushal Kumaran > wrote: > > On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote: > > Hi; > > I have this code: > > > > sql = "insert into %s (%s) values ('%%s');" % > (personalDataTable, > > string.join(cols[1:], ', ')) > > # cursor.execute(sql, string.join(vals[1:], "', '")) > > cursor.execute('insert into %s (%s) values ("%s");' % > > (personalDataTable, string.join(cols[1:], ', '), > string.join(vals[1:], > > '", "'))) > > > > Now, if I uncomment the 2nd line and comment the third, the > command > > fails because, apparently, that "');" at the tail end of sql > (1st > > line) gets chopped off. Why?? > > > That's not why it is failing. > > The second argument to cursor.execute must be a tuple of > values that > will be escaped and interpolated into the query. You are > passing in a > string instead. > > So I tried this: > > sql = "insert into %s (%s) values (%%s);" % (personalDataTable, > string.join(cols[1:], ', ')) > cursor.execute(sql, vals[1:]) > > and got this: > > > query = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email, > PW, State, ShippingState) values (%s);', db = 0x2b4c17e707e0 to Connection>, db.literal = Connection.literal of <_mysql.connection open to 'localhost' at > e6b08c0>>, args = ['prescriptions', 'Beno', 'Candelon', '123', '456', > '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', > '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR'] > > TypeError: not all arguments converted during string formatting > args = ('not all arguments converted during string > formatting',) > > > You sure about not converting to string?? > Yep, pretty sure. You still need to have as many %s in the query string as the number of values. Since you seem to be passing in 19 values (by a rough count), the query string must be like this: insert into doctorsPersonalData (Store, FirstNam.....) values (%s, %s, %s, ...19 of these) not insert into doctorsPersonalData (Store, FirstNam.....) values (%s) The exception with the "not all arguments converted" message says you have too few %s. > > > Also, lose the single quotes around the %s. > > Well, sure, if not converting to string. Otherwise it's needed. Dennis > advised not using quotes, but what he meant was not using double > quotes. Single quotes, I have found by experimentation, do work. You seem to have a strange definition of "work". -- regards, kushal From harald.luessen at gmx.de Thu May 27 11:34:46 2010 From: harald.luessen at gmx.de (Harald Luessen) Date: Thu, 27 May 2010 17:34:46 +0200 Subject: if, continuation and indentation References: Message-ID: <114tv5pu0ou7auj9kkpakqmhjcsuj38a10@4ax.com> On Thu, 27 May 2010 HH wrote: >I have a question about best practices when it comes to line wrapping/ >continuation and indentation, specifically in the case of an if >statement. > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") My solution would probably look like this: if ( width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100 ): raise ValueError("sorry, you lose") Harald From a_jtim at bellsouth.net Thu May 27 11:36:45 2010 From: a_jtim at bellsouth.net (Tim Arnold) Date: Thu, 27 May 2010 08:36:45 -0700 (PDT) Subject: multiprocessing and accessing server's stdout References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: On May 26, 4:52?pm, Adam Tauno Williams wrote: > On Wed, 2010-05-26 at 11:47 -0700, Tim Arnold wrote: > > Hi, > > I'm using multiprocessing's BaseManager to create a server on one > > machine and a client on another. The client fires a request and the > > server does some work, the result of which ends up on a shared file > > system that both the client and server can see. > > However, I need the client machine to see the stdout of the process > > running on the server. Not sure this is doable--I've been unable to > > google anything useful on this one. > > Nope, it isn't. ?Don't use stdout, use an IPC mechanism to communicate > between the client and the server if you need feedback. > -- > Adam Tauno Williams LPIC-1, Novell CLA > > OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba Thanks for that info, it saves me some time. This is a new area for me though: do you redirect stdout on the server to a socket and have the client listen and somehow pipe the sockets contents to the client stdout? Interestingly, the RPYc package manages it--that is, the client gets the stdout of the server process, so I'll dig into that code to get an idea. In the meantime, are there any recipes or other docs that would be helpful? I've been googling but without much luck. thanks, --Tim From alain at dpt-info.u-strasbg.fr Thu May 27 11:37:30 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 27 May 2010 17:37:30 +0200 Subject: if, continuation and indentation References: Message-ID: <87typtl5j9.fsf@dpt-info.u-strasbg.fr> HH writes: > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") I prefer to see the "and" at the beginning of continuation lines, and usually group related items. I never mix operators without putting explicit parentheses. Something like: if ( width == 0 and height == 0 and color == 'red' and ( emphasis == 'strong' or highlight > 100 ) ): raise ValueError("sorry, you lose") Anyway, choose your style and stick to it. > The problem should be obvious -- it's not easy to see where the > conditional ends and the statement begins since they have the same > indentation. Part of the problem, I suppose, is that Emacs indents > 'height' and the other lines in the conditional to 4 spaces (because > of the parenthesis). Emacs aligns "height" with "width", not with the parenthesis. You can put as many spaces as you want before "(" or between "(" and "width", and the following lines will follow. At least that's what happens with my stock emacs-snapshot on ubuntu, with python.el. If you use a backslashes at the end of line, emacs will double-indent the following lines, but I think you said you prefer paretheses... -- Alain. From jeanmichel at sequans.com Thu May 27 11:46:21 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 27 May 2010 17:46:21 +0200 Subject: if, continuation and indentation In-Reply-To: <4BFE8295.2090307@mrabarnett.plus.com> References: <4BFE8295.2090307@mrabarnett.plus.com> Message-ID: <4BFE93CD.3010408@sequans.com> MRAB wrote: > HH wrote: >> I have a question about best practices when it comes to line wrapping/ >> continuation and indentation, specifically in the case of an if >> statement. >> >> When I write an if statement with many conditions, I prefer to use a >> parenthesis around the whole block and get the implicit continuation, >> rather than ending each line with an escape character. Thus, using >> the example from the style guide (http://www.python.org/dev/peps/ >> pep-0008/) I would write: >> >> if (width == 0 and >> height == 0 and >> color == 'red' and >> emphasis == 'strong' or >> highlight > 100): >> raise ValueError("sorry, you lose") >> >> The problem should be obvious -- it's not easy to see where the >> conditional ends and the statement begins since they have the same >> indentation. Part of the problem, I suppose, is that Emacs indents >> 'height' and the other lines in the conditional to 4 spaces (because >> of the parenthesis). How do people deal with this situation? >> > I would probably use half-indentation: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") > > Try doing that with tabs! :-) if (width ==0 and ' \\ // ' and height == 0 and ' \\// ' and color == 'red' and ' /OO\ ' and emphasis == 'strong' and ' \> 100): raise ValueError("sorry, you lose") Try doing this with spaces !! :p JM From kushal.kumaran at gmail.com Thu May 27 12:11:34 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 21:41:34 +0530 Subject: Yet Another MySQL Problem In-Reply-To: <1274973424.2411.13.camel@nitrogen> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> Message-ID: <1274976694.2411.17.camel@nitrogen> On Thu, 2010-05-27 at 20:47 +0530, Kushal Kumaran wrote: > On Thu, 2010-05-27 at 10:30 -0400, Victor Subervi wrote: > > On Thu, May 27, 2010 at 10:17 AM, Kushal Kumaran > > wrote: > > > > On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote: > > > Hi; > > > I have this code: > > > > > > sql = "insert into %s (%s) values ('%%s');" % > > (personalDataTable, > > > string.join(cols[1:], ', ')) > > > # cursor.execute(sql, string.join(vals[1:], "', '")) > > > cursor.execute('insert into %s (%s) values ("%s");' % > > > (personalDataTable, string.join(cols[1:], ', '), > > string.join(vals[1:], > > > '", "'))) > > > > > > Now, if I uncomment the 2nd line and comment the third, the > > command > > > fails because, apparently, that "');" at the tail end of sql > > (1st > > > line) gets chopped off. Why?? > > > > > > That's not why it is failing. > > > > The second argument to cursor.execute must be a tuple of > > values that > > will be escaped and interpolated into the query. You are > > passing in a > > string instead. > > > > So I tried this: > > > > sql = "insert into %s (%s) values (%%s);" % (personalDataTable, > > string.join(cols[1:], ', ')) > > cursor.execute(sql, vals[1:]) > > > > and got this: > > > > > > > > query = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email, > > PW, State, ShippingState) values (%s);', db = > 0x2b4c17e707e0 to Connection>, db.literal = > Connection.literal of <_mysql.connection open to 'localhost' at > > e6b08c0>>, args = ['prescriptions', 'Beno', 'Candelon', '123', '456', > > '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', > > '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR'] > > > > TypeError: not all arguments converted during string formatting > > args = ('not all arguments converted during string > > formatting',) > > > > > > You sure about not converting to string?? > > > > Yep, pretty sure. You still need to have as many %s in the query string > as the number of values. Since you seem to be passing in 19 values (by > a rough count), the query string must be like this: > > insert into doctorsPersonalData (Store, FirstNam.....) values > (%s, %s, %s, ...19 of these) > > not > > insert into doctorsPersonalData (Store, FirstNam.....) values > (%s) > > The exception with the "not all arguments converted" message says you > have too few %s. > > > > > > > Also, lose the single quotes around the %s. > > > > Well, sure, if not converting to string. Otherwise it's needed. Dennis > > advised not using quotes, but what he meant was not using double > > quotes. Single quotes, I have found by experimentation, do work. > > You seem to have a strange definition of "work". > Since I'm in a good mood today, here's a little present: def insert(cursor, table, columns, values): """Insert a row into a table. columns must be a list of column names. values must be a list of values for the new row. The columns and values must correspond.""" assert len(columns) == len(values) stmt = """ insert into %s (%s) values (%s) """ % (table, ', '.join(columns), ', '.join('%s' * len(values))) logging.debug('stmt: %s, values: %s' % (stmt, values)) cursor.execute(stmt, values) Hope it helps. -- regards, kushal From topherw6 at hotmail.com Thu May 27 12:27:22 2010 From: topherw6 at hotmail.com (speedy66) Date: Thu, 27 May 2010 09:27:22 -0700 (PDT) Subject: matplotlib: show xticks only for discrete times Message-ID: <28696606.post@talk.nabble.com> I am plotting data that depends on time and height using pcolor. The data is collected every 30 minutes, so there will be data at 1PM and again at 1:30PM for instance. My question deals with how to get xticks to show up only for time values that actually exist in the dataset. As an example, ticks will currently appear at a time that corresponds to 1:24PM which is not a time where data exists. These values change as I zoom in also. I'm using matplotlib.pyplot. I've tried searching around for the answer, but have not been successful. Thanks in advance. -- View this message in context: http://old.nabble.com/matplotlib%3A-show-xticks-only-for-discrete-times-tp28696606p28696606.html Sent from the Python - python-list mailing list archive at Nabble.com. From victorsubervi at gmail.com Thu May 27 12:32:54 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 12:32:54 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <1274976694.2411.17.camel@nitrogen> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> Message-ID: On Thu, May 27, 2010 at 12:11 PM, Kushal Kumaran wrote: > Since I'm in a good mood today, here's a little present: > > def insert(cursor, table, columns, values): > """Insert a row into a table. columns must be a list of column > names. values must be a list of values for the new row. The > columns and values must correspond.""" > assert len(columns) == len(values) > > stmt = """ > insert into %s (%s) values (%s) > """ % (table, > ', '.join(columns), > ', '.join('%s' * len(values))) > logging.debug('stmt: %s, values: %s' % (stmt, values)) > > cursor.execute(stmt, values) > > Glad you're in a good mood :) First, I got an error because logging isn't defined. What should I import? I commented out that line. Here's my original code, which is now commented out: ## cursor.execute('insert into %s (%s) values ("%s");' % (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '", "'))) I ran this with your code: insert(cursor, personalDataTable, cols[1:], vals[1:]) and got this error: /var/www/html/angrynates.com/cart/enterPeople3.py 97 print "Enter more personal data?
" % personalDataTable 98 print "Enter products?" 99 print '\n' 100 101 enterPeople3() enterPeople3 = /var/www/html/angrynates.com/cart/enterPeople3.py in enterPeople3() 51 if whatDo == 'insert': 52 # We will not include the ID column 53 insert(cursor, personalDataTable, cols[1:], vals[1:]) 54 # sql = "insert into %s (%s) values (%%s);" % (personalDataTable, string.join(cols[1:], ', ')) 55 # cursor.execute(sql, vals[1:]) global insert = , cursor = , personalDataTable = 'doctorsPersonalData', cols = ['ID', 'Store', 'FirstName', 'LastName', 'Phone', 'Cell', 'Fax', 'Address1', 'Address2', 'City', 'Zip', 'ShippingAddress1', 'ShippingAddress2', 'ShippingCity', 'ShippingZip', 'DOB', 'Email', 'PW', 'State', 'ShippingState'], vals = ['Null', 'prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK'] /var/www/html/angrynates.com/cart/enterPeople3.py in insert(cursor=, table='doctorsPersonalData', columns=['Store', 'FirstName', 'LastName', 'Phone', 'Cell', 'Fax', 'Address1', 'Address2', 'City', 'Zip', 'ShippingAddress1', 'ShippingAddress2', 'ShippingCity', 'ShippingZip', 'DOB', 'Email', 'PW', 'State', 'ShippingState'], values=['prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK']) 19 ', '.join('%s' * len(values))) 20 # logging.debug('stmt: %s, values: %s' % (stmt, values)) 21 cursor.execute(stmt, values) 22 23 def enterPeople3(): cursor = , cursor.execute = >, stmt = '\ninsert into doctorsPersonalData (Store, FirstNa... %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s)\n', values = ['prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK'] /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in execute(self=, query='\ninsert into doctorsPersonalData (Store, FirstNa... %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s)\n', args=['prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK']) 146 query = query.encode(charset) 147 if args is not None: 148 query = query % db.literal(args) 149 try: 150 r = self._query(query) query = '\ninsert into doctorsPersonalData (Store, FirstNa... %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s)\n', db = , db.literal = >, args = ['prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK'] ValueError: unsupported format character ',' (0x2c) at index 221 args = ("unsupported format character ',' (0x2c) at index 221",) It appears to be separating the '%' from the 's' in your assert of '%s', but since I don't know anything about asserts, I'm hoping you can help me here. TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From henrikho at gmail.com Thu May 27 12:45:55 2010 From: henrikho at gmail.com (HH) Date: Thu, 27 May 2010 09:45:55 -0700 (PDT) Subject: if, continuation and indentation References: <87typtl5j9.fsf@dpt-info.u-strasbg.fr> Message-ID: <45063f53-e811-4d5a-97de-c81c9038b801@e21g2000vbl.googlegroups.com> On May 27, 11:37?am, Alain Ketterlin wrote: > HH writes: > > ? ? if (width == 0 and > > ? ? ? ? height == 0 and > > ? ? ? ? color == 'red' and > > ? ? ? ? emphasis == 'strong' or > > ? ? ? ? highlight > 100): > > ? ? ? ? raise ValueError("sorry, you lose") > > I prefer to see the "and" at the beginning of continuation lines, and > usually group related items. I never mix operators without putting > explicit parentheses. Something like: > > ? ? ?if ?( ?width == 0 and height == 0 > ? ? ? ? ? ? and color == 'red' > ? ? ? ? ? ? and ( emphasis == 'strong' or highlight > 100 ) ): > ? ? ? ? ?raise ValueError("sorry, you lose") Thanks for all suggestions! I like this solution a lot. I agree with your statement about mixed operators and explicit parentheses -- expecially since the eye/brain parser often does it wrong, and I believe you demonstrated that above... In [29]: print(False and (False or True)) False In [30]: print(False and False or True) True > If you use a backslashes at the end of line, emacs will double-indent > the following lines, but I think you said you prefer paretheses... Yes, I much prefer the parentheses -- partly because PEP-8 suggests it but mostly because the escapes get lost too easily. HH From python at mrabarnett.plus.com Thu May 27 12:56:41 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 May 2010 17:56:41 +0100 Subject: Yet Another MySQL Problem In-Reply-To: <1274976694.2411.17.camel@nitrogen> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> Message-ID: <4BFEA449.2010105@mrabarnett.plus.com> Kushal Kumaran wrote: [snip] > Since I'm in a good mood today, here's a little present: > > def insert(cursor, table, columns, values): > """Insert a row into a table. columns must be a list of column > names. values must be a list of values for the new row. The > columns and values must correspond.""" > assert len(columns) == len(values) > > stmt = """ > insert into %s (%s) values (%s) > """ % (table, > ', '.join(columns), > ', '.join('%s' * len(values))) That should be: ', '.join(['%s'] * len(values))) > logging.debug('stmt: %s, values: %s' % (stmt, values)) > > cursor.execute(stmt, values) > > Hope it helps. > From jjposner at optimum.net Thu May 27 13:10:46 2010 From: jjposner at optimum.net (John Posner) Date: Thu, 27 May 2010 13:10:46 -0400 Subject: Minor annoyances with properties In-Reply-To: <8679gtFdj4U1@mid.individual.net> References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> <8679gtFdj4U1@mid.individual.net> Message-ID: <4BFEA796.5080902@optimum.net> On 5/27/2010 9:14 AM, Neil Cerutti wrote: > On 2010-05-27, eb303 wrote: >> I've been using Python properties quite a lot lately and I've >> found a few things that are a bit annoying about them in some >> cases. I wondered if I missed something or if anybody else has >> this kind of problems too, and if there are better solutions >> than the ones I'm using ATM. > >> The first annoyance is when I want to specialize a property in a >> subclass. > > See: > > URI:http://infinitesque.net/articles/2005/enhancing%20Python%27s%20property.xhtml > Very nice idea, but I think this solution works too hard and not quite correctly. In Python 2.6.5, checking the name of the OProperty object's "fget" method: if self.fget.__name__ == '' or not self.fget.__name__: ... doesn't distinguish between the original class's get-the-value method and the derived class's. (Did something change between 2005-11-02 and now?) Moreover, you don't *need* to perform this check -- just let *getattr* do the work of finding the right method. These method defs work fine for me: def __get__(self, obj, objtype): if self.fget: return getattr(obj, self.fget.__name__)() else: raise AttributeError, "unreadable attribute" def __set__(self, obj, value): if self.fset: getattr(obj, self.fset.__name__)(value) else: raise AttributeError, "can't set attribute" -John From kushal.kumaran at gmail.com Thu May 27 13:12:56 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 27 May 2010 22:42:56 +0530 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEA449.2010105@mrabarnett.plus.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> Message-ID: <1274980376.4183.0.camel@nitrogen> On Thu, 2010-05-27 at 17:56 +0100, MRAB wrote: > Kushal Kumaran wrote: > [snip] > > Since I'm in a good mood today, here's a little present: > > > > def insert(cursor, table, columns, values): > > """Insert a row into a table. columns must be a list of column > > names. values must be a list of values for the new row. The > > columns and values must correspond.""" > > assert len(columns) == len(values) > > > > stmt = """ > > insert into %s (%s) values (%s) > > """ % (table, > > ', '.join(columns), > > ', '.join('%s' * len(values))) > > That should be: > > ', '.join(['%s'] * len(values))) My bad. Tested with sqlite using '?' as the placeholder, then simply replaced with '%s'. -- regards, kushal From sed at thechases.com Thu May 27 13:15:16 2010 From: sed at thechases.com (Tim Chase) Date: Thu, 27 May 2010 12:15:16 -0500 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEA449.2010105@mrabarnett.plus.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> Message-ID: <4BFEA8A4.2040202@thechases.com> On 05/27/2010 11:56 AM, MRAB wrote: > Kushal Kumaran wrote: >> ', '.join('%s' * len(values))) > > That should be: > > ', '.join(['%s'] * len(values))) Or as I've done in the past: ', '.join('%s' for _ in values) -tkc From victorsubervi at gmail.com Thu May 27 13:56:01 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 13:56:01 -0400 Subject: A Quick MySQL Question In-Reply-To: References: Message-ID: On Thu, May 27, 2010 at 1:37 PM, Dennis Lee Bieber wrote: > On Wed, 26 May 2010 08:29:21 -0400, Victor Subervi > declaimed the following in > gmane.comp.python.general: > > > valueList = ("%value1", "%value2", "%value3") > > If I'd coded it correctly, there should have been a % on both sides > (I didn't actually test the statement, was coding from memory -- might > have needed to double up the % to escape them) > > > cur.execute("select * from table where name1 like %s and name2 like %s > and > > name3 like %s", ("%value1", "%value2", "%value3")) > > > > Why do the values have that extra "%"? > > Wild card -- match zero or more characters > > %value1% will match "value1" /anywhere/ in the field name1; useful > if doing keyword searches on text fields. > > To use my card catalog example: > > BOOK(title, author) > "Witch World", "Andre Norton" > "A Mankind Witch", "Dave Freer" > "Three Against the Witch World", "Andre Norton" > "The Jargoon Pard", "Andre Norton" > > names = ["author", "title"] > values = ["Norton", "Witch"] > > The final SQL statement should become > > select * from BOOK > where author like "%Norton%" > and title like "%Witch%" > > and that statement will find the first and third book listed. > Ok. Now I understand. Thank you! beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Thu May 27 14:00:15 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 14:00:15 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEA449.2010105@mrabarnett.plus.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> Message-ID: On Thu, May 27, 2010 at 12:56 PM, MRAB wrote: > Kushal Kumaran wrote: > [snip] > > Since I'm in a good mood today, here's a little present: >> >> def insert(cursor, table, columns, values): >> """Insert a row into a table. columns must be a list of column >> names. values must be a list of values for the new row. The >> columns and values must correspond.""" >> assert len(columns) == len(values) >> >> stmt = """ >> insert into %s (%s) values (%s) >> """ % (table, >> ', '.join(columns), >> ', '.join('%s' * len(values))) >> > > That should be: > > > ', '.join(['%s'] * len(values))) > > logging.debug('stmt: %s, values: %s' % (stmt, values)) >> >> cursor.execute(stmt, values) >> >> Hope it helps. >> >> Yes it did. Thanks. Also figured out the "import logging" :-} beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Thu May 27 14:07:02 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 May 2010 19:07:02 +0100 Subject: matplotlib: show xticks only for discrete times In-Reply-To: <28696606.post@talk.nabble.com> References: <28696606.post@talk.nabble.com> Message-ID: On 27/05/2010 17:27, speedy66 wrote: > > I am plotting data that depends on time and height using pcolor. The data is > collected every 30 minutes, so there will be data at 1PM and again at 1:30PM > for instance. > > My question deals with how to get xticks to show up only for time values > that actually exist in the dataset. As an example, ticks will currently > appear at a time that corresponds to 1:24PM which is not a time where data > exists. These values change as I zoom in also. I'm using > matplotlib.pyplot. > > I've tried searching around for the answer, but have not been successful. > > Thanks in advance. > > See http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks matplotlib also has it's own mailing list. HTH Mark Lawrence From victorsubervi at gmail.com Thu May 27 14:16:10 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 14:16:10 -0400 Subject: Some More MySQL Message-ID: Hi; But what about this? sql = "select pic%d from %s where ID='%%s';" % (pic, store) cursor.execute(sql % id) If I try and rewrite the last line like this: cursor.execute(sql, id) it doesn't work. What do? How about this one: cursor.execute("insert into categories (Store, Category, Parent) values('%s', '%s', Null)", (store, cat)) For some reason it puts single quotes around my variables! This doesn't happen if I change that comma for a percent sign! What do? How about this one: sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + opTable[1:]) # cursor.execute(sql, id) cursor.execute('select * from options%s where ID=%s' % (opTable[0].upper() + opTable[1:], id)) The last one works, but if I comment it out and uncomment the middle line, it doesn't. Same here: sql = "update options%s set PriceDiff='%%s' where Field='%%s' and ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:]) # cursor.execute(sql, (value, opName, id, store)) cursor.execute('update options%s set PriceDiff="%s" where Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:], value, opName, id, store)) Please help. TIA, beno TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From decklar at googlemail.com Thu May 27 14:41:35 2010 From: decklar at googlemail.com (ledpepper) Date: Thu, 27 May 2010 11:41:35 -0700 (PDT) Subject: First script. Need some help Message-ID: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> #Enter in firstname.lastname (bob.smith) #Count the amount of letters(x) and vowels(y) #Then work out if bob is > but not equal to 6 letters #If firstname is less than 6 print firstnamesurnamexy #If firstname is equal to or greater than 6 print firstnamexy #Copy result to clipboard http://codepad.org/Emzpix3H I think you can see what i'm trying to do here. I will definitely elaborate if anyone needs me to. Thanks From python at mrabarnett.plus.com Thu May 27 14:54:43 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 May 2010 19:54:43 +0100 Subject: Some More MySQL In-Reply-To: References: Message-ID: <4BFEBFF3.6040909@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > But what about this? > > sql = "select pic%d from %s where ID='%%s';" % (pic, store) > cursor.execute(sql % id) > > If I try and rewrite the last line like this: > > cursor.execute(sql, id) > > it doesn't work. What do? > > How about this one: > > cursor.execute("insert into categories (Store, Category, Parent) > values('%s', '%s', Null)", (store, cat)) > > For some reason it puts single quotes around my variables! This doesn't > happen if I change that comma for a percent sign! What do? > > How about this one: > > sql = 'select * from options%s where ID=%%s', (opTable[0].upper() > + opTable[1:]) > # cursor.execute(sql, id) > cursor.execute('select * from options%s where ID=%s' % > (opTable[0].upper() + opTable[1:], id)) > > The last one works, but if I comment it out and uncomment the middle > line, it doesn't. Same here: > > sql = "update options%s set PriceDiff='%%s' where Field='%%s' > and ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:]) > # cursor.execute(sql, (value, opName, id, store)) > cursor.execute('update options%s set PriceDiff="%s" where > Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + > opTable[1:], value, opName, id, store)) > As has already been explained, when working with SQL in Python there are 2 forms of placeholder: 1. Python's %s placeholder, replaced by Python's % operator. 2. SQL's %s placeholder, replaced by the .execute method. SQL might not let you use its %s placeholder for table or column names, but they are normally hidden from the user and fixed by the application. For user-supplied values there's the risk of SQL-injection attacks. There are 2 ways of approaching that: 1. The hard way: check the values and add any necessary quoting or escaping before using Python's % operator, then pass the fully-formed SQL statement to result to .execute. 2. The easy way: pass the SQL statement to .execute with a %s for each value and let the method substitute the values itself (it'll add whatever quoting or escaping is necessary). From bieffe62 at gmail.com Thu May 27 14:56:29 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Thu, 27 May 2010 11:56:29 -0700 (PDT) Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Message-ID: On 27 Mag, 14:37, eb303 wrote: > Hello all, > > I've been using Python properties quite a lot lately and I've found a > few things that are a bit annoying about them in some cases. I > wondered if I missed something or if anybody else has this kind of > problems too, and if there are better solutions than the ones I'm > using ATM. > > The first annoyance is when I want to specialize a property in a > subclass. This happens quite often actually, and it is even sometimes > the reason why a plain attribute is turned into a property: a subclass > needs to do more things than the superclass when the property is > updated for example. So, of course, my first try was: > > class A(object): > ? def __init__(self): > ? ? self._p = None > ? def _get_p(self): > ? ? return self._p > ? def _set_p(self, p): > ? ? self._p = p > ? p = property(_get_p, _set_p) > class B(A): > ? def _set_p(self, p): > ? ? ## Additional things here? > ? ? super(B, self)._set_p(p) > > And of course, it doesn't work: the property has been bound to > A._set_p in A, so any new definition of _set_p in any subclass does > not replace the set method for the property. So I always have to add a > line: > p = property(A._get_p, _set_p) > in the subclass too. This is a bit awkward to me, since I have to > specify the superclass's name (super(?) can't be used, since it should > take B as an argument, and B isn't defined yet?). Do I miss something? > Is this the way to do it, or is there a better one? > Don't know if is better, but you could add a level of indirection to solve it class A(object): def __init__(self): self._p = None def _get_p(self): return self._p def _set_p(self, p): self._p = p def _virtual_get_p (self): _get_p(self) def _virtual_set_p (self,v): _set_p(self, v) p = property(_virtual_get_p, _virtual_set_p) At this point, the subclasses of A can reimplement _get_p and _set_p as they like (I think) Ciao ----- FB From victorsubervi at gmail.com Thu May 27 15:36:46 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 15:36:46 -0400 Subject: Some More MySQL In-Reply-To: <4BFEBFF3.6040909@mrabarnett.plus.com> References: <4BFEBFF3.6040909@mrabarnett.plus.com> Message-ID: On Thu, May 27, 2010 at 2:54 PM, MRAB wrote: > Victor Subervi wrote: > >> Hi; >> But what about this? >> >> sql = "select pic%d from %s where ID='%%s';" % (pic, store) >> cursor.execute(sql % id) >> >> If I try and rewrite the last line like this: >> >> cursor.execute(sql, id) >> >> it doesn't work. What do? >> >> How about this one: >> >> cursor.execute("insert into categories (Store, Category, Parent) >> values('%s', '%s', Null)", (store, cat)) >> >> For some reason it puts single quotes around my variables! This doesn't >> happen if I change that comma for a percent sign! What do? >> >> How about this one: >> >> sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + >> opTable[1:]) >> # cursor.execute(sql, id) >> cursor.execute('select * from options%s where ID=%s' % >> (opTable[0].upper() + opTable[1:], id)) >> >> The last one works, but if I comment it out and uncomment the middle line, >> it doesn't. Same here: >> >> sql = "update options%s set PriceDiff='%%s' where Field='%%s' and >> ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:]) >> # cursor.execute(sql, (value, opName, id, store)) >> cursor.execute('update options%s set PriceDiff="%s" where >> Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:], >> value, opName, id, store)) >> >> As has already been explained, when working with SQL in Python there are > 2 forms of placeholder: > > 1. Python's %s placeholder, replaced by Python's % operator. > > 2. SQL's %s placeholder, replaced by the .execute method. > > SQL might not let you use its %s placeholder for table or column names, > but they are normally hidden from the user and fixed by the application. > > For user-supplied values there's the risk of SQL-injection attacks. > There are 2 ways of approaching that: > > 1. The hard way: check the values and add any necessary quoting or > escaping before using Python's % operator, then pass the fully-formed > SQL statement to result to .execute. > > 2. The easy way: pass the SQL statement to .execute with a %s for each > value and let the method substitute the values itself (it'll add > whatever quoting or escaping is necessary). > > > Ok, so you're telling me I'm trying to do it the hard way. That's because I still don't have my head wrapped around the easy way. I was able to follow what Kushal Kumaran supplied; however I must still be lost on how that applies to the above examples. Could you illustrate with the first and let me try and figure out the rest? TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu May 27 15:41:18 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 May 2010 20:41:18 +0100 Subject: First script. Need some help In-Reply-To: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> References: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> Message-ID: <4BFECADE.4040906@mrabarnett.plus.com> ledpepper wrote: > #Enter in firstname.lastname (bob.smith) > #Count the amount of letters(x) and vowels(y) > #Then work out if bob is > but not equal to 6 letters > #If firstname is less than 6 print firstnamesurnamexy > #If firstname is equal to or greater than 6 print firstnamexy > #Copy result to clipboard > > http://codepad.org/Emzpix3H > > I think you can see what i'm trying to do here. I will definitely > elaborate if anyone needs me to. > You need to download and install the Windows-specific extensions: http://sourceforge.net/projects/pywin32/ I'm assuming you're using Python 2.6 on Windows. From breamoreboy at yahoo.co.uk Thu May 27 15:42:51 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 May 2010 20:42:51 +0100 Subject: First script. Need some help In-Reply-To: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> References: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> Message-ID: On 27/05/2010 19:41, ledpepper wrote: > #Enter in firstname.lastname (bob.smith) > #Count the amount of letters(x) and vowels(y) > #Then work out if bob is> but not equal to 6 letters > #If firstname is less than 6 print firstnamesurnamexy > #If firstname is equal to or greater than 6 print firstnamexy > #Copy result to clipboard > > http://codepad.org/Emzpix3H > > I think you can see what i'm trying to do here. I will definitely > elaborate if anyone needs me to. > > Thanks Have you installed the Win32 extensions? From http://www.devx.com/opensource/Article/37233/0/page/3 "Author's Note: the win32clipboard module is not part of the standard Python distribution on Windows. You can get it (along with lots of other comprehensive Python bindings to Win32 APIs) as part of the Win32 extensions project on SourceForge. Alternatively, the module is also bundled with the ActivePython distribution for Windows." HTH. Mark Lawrence From ethan at stoneleaf.us Thu May 27 15:45:58 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 May 2010 12:45:58 -0700 Subject: dbf files and indexes Message-ID: <4BFECBF6.10006@stoneleaf.us> Let's say I have two tables: CatLovers DogLovers ------------------- ------------------- | name | age | | name | age | |-----------------| |-----------------| | Allen | 42 | | Alexis | 7 | | Jerod | 29 | | Michael | 21 | | Samuel | 17 | | Samuel | 17 | | Nickalaus | 55 | | Lawrence | 63 | | Frederick | 34 | | Frederick | 34 | ------------------- ------------------- NumberOfPets --------------------------- | name | cats | dogs | --------------------------- | Allen | 2 | 0 | | Alexis | 0 | 3 | | Michael | 0 | 1 | | Samuel | 1 | 2 | | Jerod | 3 | 0 | | Nickalaus | 5 | 0 | | Lawrence | 0 | 1 | | Frederick | 3 | 2 | --------------------------- (I know, I know -- coming up with examples has never been my strong point. ;) catlovers = dbf.Table('CatLovers') doglovers = dbf.Table('DogLovers') petcount = dbf.Table('NumberOfPets') For the sake of this highly contrived example, let's say I'm printing a report that I would like in alphabetical order of those who love both cats and dogs... def names(record): return record.name c_idx = catlovers.create_index(key=names) d_idx = doglovers.create_index(key=names) p_idx = petcount.create_index(key=names) # method 1 for record in c_idx: if record in d_idx: print record.name, record.age, \ p_idx[record].cats, p_idx[record].dogs *or* # method 2 for record in c_idx: if d_idx.key(record) in d_idx: # or if names(record) in d_idx: print record.name, record.age \ p_idx[record].cats, p_idx[record].dogs Which is better (referring to the _in_ statement)? Part of the issue revolves around the question of is _any_ record in the CatLovers table really in the DogLovers index? Obviously no -- so if you are asking the question in code you are really asking if a record from CatLovers has a matching key value in DogLovers, which means either the __contains__ code can apply the key function to the record (implicit, as in method 1 above) or the calling code can do it (explicit, as in method 2 above). I'm leaning towards method 1, even though the key function is then called behind the scenes, because I think it makes the calling code cleaner. Opinions? ~Ethan~ From wcardoen at gmail.com Thu May 27 15:46:35 2010 From: wcardoen at gmail.com (Wim R. Cardoen) Date: Thu, 27 May 2010 13:46:35 -0600 Subject: On the installation of external Python modules Message-ID: Hello, In the past I installed different versions of python (using gcc) e.g. 2.5.4, 2.6.4 at the following places: /wim/pkg/python/2.5.4 /wim/pkg/python/2.6.4 I installed the numpy, scipy, matplotlib, dadi modules using the command: /wim/pkg/python/2.5.4/bin/python setup.py install --prefix=/wim/pkg/python/2.5.4 As a result the working modules got installed under: /wim/pkg/python/.5.4/lib/python2.5/site-packages/dadi /wim/pkg/python/.5.4/lib/python2.5/site-packages/numpy /wim/pkg/python/.5.4/lib/python2.5/site-packages/scipy /wim/pkg/python/.5.4/lib/python2.5/site-packages/matplotlib Question 1: Is it correct when I state that the above scipy, numpy, modules can only be used by the python2.5.4 executable or can I also use in python2.6.4 if I modify the PYTHONHOME and PYTHONPATH variables? Does one have to recompile all its external libraries for use with an updated python version? (assuming that the glibc is identical) I also tried to install the external libraries (e.g. numpy) in different directories than the main python directories by specifying e.g. --prefix=/wim/pkg/pylib/ (in the case of using python2.6.5)* *I noticed that the suffix was still of the form "lib/pythonx.y/site-packages/numpy" Therefore, I wonder: a. How can one (elegantly) force numpy to be installed under (using python 2.6.2 and python2.6.5): /wim/pkg/pylib/lib/python2.6.4/. /wim/pkg/pylib/lib/python2.6.5 b. How can one (elegantly) install different versions of the same package using the same python binary (2.6.4) as e.g: /wim/pkg/pylib/lib/python2.6/site-packages/numpy0.70 /wim/pkg/pylib/lib/python2.6/site-packages/numpy0.71 or is this the wrong approach? Thanks, Wim -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Thu May 27 16:04:45 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 27 May 2010 16:04:45 -0400 Subject: dbf files and indexes In-Reply-To: <4BFECBF6.10006@stoneleaf.us> References: <4BFECBF6.10006@stoneleaf.us> Message-ID: <20100527160445.30081fd3.darcy@druid.net> On Thu, 27 May 2010 12:45:58 -0700 Ethan Furman wrote: > Let's say I have two tables: > > CatLovers DogLovers > ------------------- ------------------- > | name | age | | name | age | > |-----------------| |-----------------| [...] > > NumberOfPets > --------------------------- > | name | cats | dogs | > --------------------------- [...] First problem is learning to count. :-) Second (first real) problem is that you database is not normalized. If all of the cat lovers and dog lovers are in NumberOfPets then move the age into that. Probably should rename it as well. Finally, are these SQL databases? The best way of getting information is with SQL. SELECT * FROM NumberOfPets WHERE name IN (SELECT name FROM CatLovers) OR name IN (SELECT name FROM DogLovers) ORDER BY name; > catlovers = dbf.Table('CatLovers') > doglovers = dbf.Table('DogLovers') > petcount = dbf.Table('NumberOfPets') I guess you should tell us what dbf is. It doesn't seem to be a standard module and it doesn't look like DB-API. It's hard to answer your question without knowing what these functions do. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From ethan at stoneleaf.us Thu May 27 16:06:18 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 May 2010 13:06:18 -0700 Subject: dbf files and indexes In-Reply-To: <4BFECBF6.10006@stoneleaf.us> References: <4BFECBF6.10006@stoneleaf.us> Message-ID: <4BFED0BA.3000106@stoneleaf.us> Ethan Furman wrote: > Let's say I have two tables: Okay, let's say I have three tables instead. ;p From davea at ieee.org Thu May 27 16:11:24 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 27 May 2010 16:11:24 -0400 Subject: First script. Need some help In-Reply-To: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> References: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> Message-ID: <4BFED1EC.2070609@ieee.org> ledpepper wrote: > #Enter in firstname.lastname (bob.smith) > #Count the amount of letters(x) and vowels(y) > #Then work out if bob is > but not equal to 6 letters > #If firstname is less than 6 print firstnamesurnamexy > #If firstname is equal to or greater than 6 print firstnamexy > #Copy result to clipboard > > http://codepad.org/Emzpix3H > > I think you can see what i'm trying to do here. I will definitely > elaborate if anyone needs me to. > > Thanks > > Why bother using codepad for this? The problem occurs parsing the 3rd line, so you only needed that and the traceback. Have you installed the Win32 extensions? If you think you have, can you find the file ? C:\ProgFiles\Python26\Lib\site-packages\win32\win32clipboard.pyd Naturally, your install directory may be different. But it should be in the site-packages directory, which is where add-ons are installed. DaveA From lists at cheimes.de Thu May 27 16:27:44 2010 From: lists at cheimes.de (Christian Heimes) Date: Thu, 27 May 2010 22:27:44 +0200 Subject: dbf files and indexes In-Reply-To: <20100527160445.30081fd3.darcy@druid.net> References: <4BFECBF6.10006@stoneleaf.us> <20100527160445.30081fd3.darcy@druid.net> Message-ID: > Finally, are these SQL databases? The best way of getting information > is with SQL. > > SELECT * FROM NumberOfPets > WHERE name IN (SELECT name FROM CatLovers) OR > name IN (SELECT name FROM DogLovers) > ORDER BY name; A good way is to use SQL with JOINs instead of horrible nested selects. Although SQL is declarative, you shouldn't make the work of the query optimizer so hard. Christian From cedric.krier at b2ck.com Thu May 27 16:31:53 2010 From: cedric.krier at b2ck.com (ced) Date: Thu, 27 May 2010 13:31:53 -0700 (PDT) Subject: Tryton 1.6 series is out Message-ID: <68f9d2bc-9f31-4c88-9234-013dca7c4392@m21g2000vbr.googlegroups.com> Tryton is a three-tiers high-level general purpose application platform under the license GPL-3 written in Python and using PostgreSQL as main database engine. It is the core base of a complete business solution providing modularity, scalability and security. This new release comes with the support of MySQL and various improvements and polishing of the framework. As always database migration is ensured from any previous version. This release also marks the end of support for the 1.0 series. The most noteworthy new features are: - The add of MySQL support as DBMS - Some new modules: - Calendar Scheduling - Dashboard - Project Plan - The Russian translation - The security enforcement with fingerprint and CA checks for SSL - The introduction of PYSON[1] for dynamic domain - The add of JSON-RPC protocol - The lazy load of fields in Export/Import windows - The usage of python-dateutil instead of egenix-mx-base - A versioned configuration directory for the client - A bundle of Neso (standalone version of Tryton) for MacOSX - The digits validation on numeric fields[2] - The usage of singleton model[3] for various sequences configuration - Some speed improvements of the report engine A more complete list of the new features on: http://www.tryton.org/news.html#d2010-05-17 :Homepage: http://www.tryton.org/ :Downloads: http://www.tryton.org/downloads.html :Screenshots: http://www.tryton.org/screenshots.html :Demo: http://www.tryton.org/demo.html [1] http://doc.tryton.org/1.6/trytond/doc/topics/pyson.html [2] http://doc.tryton.org/1.6/trytond/doc/ref/models/fields.html#numeric [3] http://doc.tryton.org/1.6/trytond/doc/ref/models/models.html#trytond.model.ModelSingleton] From victorsubervi at gmail.com Thu May 27 16:32:24 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 27 May 2010 16:32:24 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEA8A4.2040202@thechases.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> <4BFEA8A4.2040202@thechases.com> Message-ID: On Thu, May 27, 2010 at 1:15 PM, Tim Chase wrote: > On 05/27/2010 11:56 AM, MRAB wrote: > >> Kushal Kumaran wrote: >> >>> ', '.join('%s' * len(values))) >>> >> >> That should be: >> >> ', '.join(['%s'] * len(values))) >> > > Or as I've done in the past: > > ', '.join('%s' for _ in values) > Huh? Can you describe that underscore to me? Fascinating! beno > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Thu May 27 16:33:59 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 May 2010 13:33:59 -0700 Subject: dbf files and indexes In-Reply-To: <20100527160445.30081fd3.darcy@druid.net> References: <4BFECBF6.10006@stoneleaf.us> <20100527160445.30081fd3.darcy@druid.net> Message-ID: <4BFED737.3050906@stoneleaf.us> D'Arcy J.M. Cain wrote: > On Thu, 27 May 2010 12:45:58 -0700 > Ethan Furman wrote: >> Let's say I have two tables: >> >> CatLovers DogLovers >> ------------------- ------------------- >> | name | age | | name | age | >> |-----------------| |-----------------| > [...] >> NumberOfPets >> --------------------------- >> | name | cats | dogs | >> --------------------------- > [...] > > First problem is learning to count. :-) Heh -- like I said, I'm terrible at making examples. Originally it was two tables, then I threw in a third so I could show using an index as a dictionary. > Second (first real) problem is that you database is not normalized. > If all of the cat lovers and dog lovers are in NumberOfPets then move > the age into that. Probably should rename it as well. The actual tables that I would be using are different versions of mailing tables, with one table not having as many records as the other, and wanting to do something with the records that are in common between the two. > Finally, are these SQL databases? The best way of getting information > is with SQL. The format of these tables is either dBase III or Visual FoxPro 6, and dbf is a module I have coded (still working on SQL support for it... getting closer!). A slightly out-of-date version of it is available on PyPI. My question centers around the __contains__ method of the Index object that I am writing, and whether it should call the key function of the index when passed a record, or if I should make the calling code do that. Hope this helps. ~Ethan~ From subhakolkata1234 at gmail.com Thu May 27 16:50:29 2010 From: subhakolkata1234 at gmail.com (joy99) Date: Thu, 27 May 2010 13:50:29 -0700 (PDT) Subject: Question on Python Function References: Message-ID: <14b47fde-d257-41ba-9480-6e8307d3d8a5@z15g2000prh.googlegroups.com> On May 25, 12:18?pm, Peter Otten <__pete... at web.de> wrote: > Kushal Kumaran wrote: > > On Tue, May 25, 2010 at 3:38 AM,joy99 wrote: > >> > > >> Dear Vlastimir, > > >> As pointed out by Alister, I can print the values of function1 and > >> function2 with the help of another function3, but my target is to call > >> the "add" value of function1 and "mult" value of function2 in a third > >> function or the values and parameters of the third function in fourth > >> function. While calling, I am looking not only to print, but to use > >> them or manipulate them. > > >> I hope I am bit clear now. > > > If you need to use the values in another function, you need a way to > > let that function get its hands on the values. ?Your function1 and > > function2 should return the values they compute instead of printing > > them out. > > For example: > > ?>>> def add(x, y): > ... ? ? return x + y > ...>>> def mul(x, y): > > ... ? ? return x * y > ...>>> def sum_of_squares(x, y): > > ... ? ? return add(mul(x, x), mul(y, y)) > ...>>> sum_of_squares(3, 4) > > 25 > > OP: If that addresses your question I suggest that you work through some > introductory text about python. The python wiki has a few suggestions, see > > http://wiki.python.org/moin/BeginnersGuide > > Peter Hi Peter and Other Kind Contributors of the Group, I got lot of insights from the discussion in the group. Though I did not get the exact answer but from Peter's link I could work them out. Thank you, Peter, for kindly referring me the link. I like to thank others of the group also for kindly spending their valuable time. I wanted to define one function and call the value of that function to be used by another function. If I misquoted the problem, I am sorry. Wishing You all a Great Day Ahead, Best Regards, Subhabrata. From nganon at gmail.com Thu May 27 16:58:43 2010 From: nganon at gmail.com (nganon tj) Date: Thu, 27 May 2010 23:58:43 +0300 Subject: PyQt4 QThread - passing arguments to thread methods Message-ID: Hi, I am trying to figure out how to implement a QThread class that will handle GUI event while keeping the GUI responsive. I want to call thread's methods by their names and start() the thread from inside that method. My problem is with passing methods their arguments since start() wont take any argument. So I thought I could keep a global variable self.invoker which holds the name of currently called method and start the thread accordingly as follows: class Counter(QThread): def __init__(self, parent=None): super(Counter, self).__init__(parent) self.reset() def __del__(self): self.exiting = True self.wait() try: self.reset() # is not instantiated except TypeError: return def stop(self): self.__del__() def reset(self): self.exiting = False def countup(self, till): if not self.isRunning(): self.invoker = [self.countup, till] self.start() else: n = 0 while not self.exiting and n < till: n += 1 self.emit(SIGNAL("ticktock(int)", n)) def run(self): self.invoker[0](self.invoker[1], self.invoker[2]) But I cant always know the number of arguments the invoker has, can I? So can you please suggest me a better way of doing this please? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rbrt.somerville at gmail.com Thu May 27 17:31:59 2010 From: rbrt.somerville at gmail.com (robert somerville) Date: Thu, 27 May 2010 14:31:59 -0700 Subject: re ElemenTree producing and reading examples needed : Message-ID: does anybody have some working code that they can point me to so i could see ElemenTtree in action (especially writing XML files) ??? Thanks Robert Somerville -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Thu May 27 17:47:39 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 27 May 2010 16:47:39 -0500 Subject: Yet Another MySQL Problem In-Reply-To: References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> <4BFEA8A4.2040202@thechases.com> Message-ID: <4BFEE87B.1030302@tim.thechases.com> On 05/27/2010 03:32 PM, Victor Subervi wrote: > On Thu, May 27, 2010 at 1:15 PM, Tim Chase wrote: >>> That should be: >>> >>> ', '.join(['%s'] * len(values))) >> >> Or as I've done in the past: >> >> ', '.join('%s' for _ in values) > > Huh? Can you describe that underscore to me? Fascinating! The underscore is a valid variable-name, idiomatically used for "I don't care about this", often seen in places like tuple assignment: a,_,_,d = some_4_element_tuple So in my above case, it could also have been written as ', '.join('%s' for value in values) ', '.join('%s' for dont_care_about_the_value in values) but the "_" idiom means "I'm iterating over 'values' but I'm not actually using the values I get from it" -tkc From python at mrabarnett.plus.com Thu May 27 18:22:24 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 May 2010 23:22:24 +0100 Subject: Some More MySQL In-Reply-To: References: <4BFEBFF3.6040909@mrabarnett.plus.com> Message-ID: <4BFEF0A0.2040800@mrabarnett.plus.com> Victor Subervi wrote: > On Thu, May 27, 2010 at 2:54 PM, MRAB > wrote: > > Victor Subervi wrote: > > Hi; > But what about this? > > sql = "select pic%d from %s where ID='%%s';" % (pic, store) > cursor.execute(sql % id) > > If I try and rewrite the last line like this: > > cursor.execute(sql, id) > > it doesn't work. What do? > > How about this one: > > cursor.execute("insert into categories (Store, Category, > Parent) values('%s', '%s', Null)", (store, cat)) > > For some reason it puts single quotes around my variables! This > doesn't happen if I change that comma for a percent sign! What do? > > How about this one: > > sql = 'select * from options%s where ID=%%s', > (opTable[0].upper() + opTable[1:]) > # cursor.execute(sql, id) > cursor.execute('select * from options%s where ID=%s' % > (opTable[0].upper() + opTable[1:], id)) > > The last one works, but if I comment it out and uncomment the > middle line, it doesn't. Same here: > > sql = "update options%s set PriceDiff='%%s' where > Field='%%s' and ID=%%s and Store='%%s'" % (opTable[0].upper() + > opTable[1:]) > # cursor.execute(sql, (value, opName, id, store)) > cursor.execute('update options%s set PriceDiff="%s" where > Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + > opTable[1:], value, opName, id, store)) > > As has already been explained, when working with SQL in Python there are > 2 forms of placeholder: > > 1. Python's %s placeholder, replaced by Python's % operator. > > 2. SQL's %s placeholder, replaced by the .execute method. > > SQL might not let you use its %s placeholder for table or column names, > but they are normally hidden from the user and fixed by the application. > > For user-supplied values there's the risk of SQL-injection attacks. > There are 2 ways of approaching that: > > 1. The hard way: check the values and add any necessary quoting or > escaping before using Python's % operator, then pass the fully-formed > SQL statement to result to .execute. > > 2. The easy way: pass the SQL statement to .execute with a %s for each > value and let the method substitute the values itself (it'll add > whatever quoting or escaping is necessary). > > > Ok, so you're telling me I'm trying to do it the hard way. That's > because I still don't have my head wrapped around the easy way. I was > able to follow what Kushal Kumaran supplied; however I must still be > lost on how that applies to the above examples. Could you illustrate > with the first and let me try and figure out the rest? > First build the SQL statement with placeholder(s) for the values: sql = "select pic%d from %s where ID=%%s;" % (pic, store) Then execute the SQL statement, passing the value(s) so that .execute performs the substitution itself: cursor.execute(sql, id) Placeholders which are handled by .execute shouldn't be wrapped in quotes, even is the value is a string, because .execute will handle that (and any other details) itself. From rbrt.somerville at gmail.com Thu May 27 19:52:17 2010 From: rbrt.somerville at gmail.com (robert somerville) Date: Thu, 27 May 2010 16:52:17 -0700 Subject: ElementTree write creates large one line XML file .... Message-ID: Hi I am using Ubuntu 9.10 and Python 2.6.4 .. when I create an ElementTree object and the write it out using: xml.etree.ElementTree.write() , I get one single long single line files, instead of something that looks reasonable , what gives ??? (and is it important ??) eg: I get : OneTwo instead of : One Two i found this example at: ( Listing 4 ) http://www.learningpython.com/2008/05/07/elegant-xml-parsing-using-the-elementtree-module/#Listing1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Thu May 27 20:13:02 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 27 May 2010 20:13:02 -0400 Subject: ElementTree write creates large one line XML file .... In-Reply-To: References: Message-ID: On 5/27/10 7:52 PM, robert somerville wrote: > Hi I am using Ubuntu 9.10 and Python 2.6.4 .. > > when I create an ElementTree object and the write it out using: > > xml.etree.ElementTree.write() , I get one single long single line > files, instead of something that looks reasonable , what gives ??? (and > is it important ??) ElementTree writes exactly what you tell it to. In XML, whitespace is significant. If you want newlines and/or indentation to make it pretty-looking, then you need to add those to your elements. Fredrik provides an example function for doing this: http://effbot.org/zone/element-lib.htm#prettyprint -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nagle at animats.com Thu May 27 20:37:44 2010 From: nagle at animats.com (John Nagle) Date: Thu, 27 May 2010 17:37:44 -0700 Subject: MySQLDB - server has gone on blob insertion... In-Reply-To: References: Message-ID: <4bff0aae$0$1592$742ec2ed@news.sonic.net> Dennis Lee Bieber wrote: > On Wed, 26 May 2010 11:30:41 +0200, Durumdara > declaimed the following in gmane.comp.python.general: > >> cursor.execute('delete from blobs;') >> > Since that statement will delete EVERY record from the table > "blobs", I believe it is common practice to replace it with > > drop table blobs > create table blobs (whatever definition it had originally) No, it's not "common practice". Actually, the proper way to clear a table is "TRUNCATE TABLE tablename;" Note that deleting a table referenced by other tables using FOREIGN KEY can be rejected by the database. John Nagle > >> When I tried to start this, I got error: >> >> _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') >> >> I read that server have some parameter, that limit the Query length. >> >> Then I decreased the blob size to 1M, and then it is working. >> > What is the table definition? In MySQL 4 (and likely not changed in > v5 -- I've got the old brown tree book handy, hence the mention of v4) > field type BLOB is limited to a length of 2^16 (64kB), MEDIUMBLOB is > 2^24, and LONGBLOB is 2^32 (if the system is using unsigned integers > internally, that should support 4GB... But do you have enough memory to > pass such an argument? ). From ipatrol6010 at yahoo.com Thu May 27 21:03:52 2010 From: ipatrol6010 at yahoo.com (ipatrol6010 at yahoo.com) Date: Thu, 27 May 2010 18:03:52 -0700 (PDT) Subject: Tkinter error Message-ID: <247190.10596.qm@web45414.mail.sp1.yahoo.com> I run a program (important parts at http://paste.pocoo.org/show/219148/) and all I get is this error: warning: callback failed in WindowList : invalid command name ".45328424.windows" Why? P.S.: Please CC all replies to me, I don't watch the list -------------- next part -------------- An HTML attachment was scrubbed... URL: From jyoung79 at kc.rr.com Thu May 27 22:00:59 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Fri, 28 May 2010 2:00:59 +0000 Subject: pythonMagick question Message-ID: <20100528020059.HINJ0.617899.root@cdptpa-web25-z02> Hello, I'm wanting to try out pythonMagick, but am pretty lost with this whole thing. What I'm wanting to do is view EPS and PDF files with Python and be able to zoom into the images to see smaller detail. I downloaded PythonMagick-0.9.1.tar and have been looking through that folder. The README file says: ------------- Requists for installation is: boost boost-python python 2.5 Magick++ (>= 6.2) and for building: pkg-config libtool make and for generation build scripts is defined in autogen.pl Building: ./configure make make install ------------- What's this 'boost' stuff and Magick++? Do I need to install more things to make this work? I was going to run '.configure', then 'make' and then 'make install' from the command-line, but want to make sure I know what I'm doing before installing something (especially if it won't work). Can anyone give me more info about pythonMagick or send me a link to a site(s) that has more info? Thanks! Jay From sbassi at clubdelarazon.org Thu May 27 22:19:37 2010 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Thu, 27 May 2010 23:19:37 -0300 Subject: ElementTree write creates large one line XML file .... In-Reply-To: References: Message-ID: On Thu, May 27, 2010 at 9:13 PM, Robert Kern wrote: > ElementTree writes exactly what you tell it to. In XML, whitespace is > significant. If you want newlines and/or indentation to make it > pretty-looking, then you need to add those to your elements. This is not always true. Let me quote an XML tutorial (by Oracle): "What is XML Whitespace? XML considers four characters to be whitespace: the carriage return (\r or ch(13)), the linefeed (\n or ch(10)), the tab(\t), and the spacebar (' '). In XML documents, there are two types of whitespace: Significant whitespace is part of the document content and should be preserved. Insignificant whitespace is used when editing XML documents for readability. These whitespaces are typically not intended for inclusion in the delivery of the document. Usually without DTD or XML schema definition, all whitespaces are significant whitespaces and should be preserved. However, with DTD or XML schema definitions, only the whitespaces in the content are significant as follows: ------------------ John Smith Product Manager Example.com -------------------- " From clp2 at rebertia.com Thu May 27 22:24:21 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 May 2010 19:24:21 -0700 Subject: pythonMagick question In-Reply-To: <20100528020059.HINJ0.617899.root@cdptpa-web25-z02> References: <20100528020059.HINJ0.617899.root@cdptpa-web25-z02> Message-ID: On Thu, May 27, 2010 at 7:00 PM, wrote: > Hello, > > I'm wanting to try out pythonMagick, but am pretty lost with this whole thing. > What I'm wanting to do is view EPS and PDF files with Python and be able to > zoom into the images to see smaller detail. > > I downloaded PythonMagick-0.9.1.tar and have been looking through that > folder. ?The README file says: > > ------------- > Requists for installation is: > boost > boost-python > python 2.5 > Magick++ (>= 6.2) > > and for building: > pkg-config > libtool > make > > and for generation build scripts is defined in autogen.pl > > Building: > ./configure > make > make install > ------------- > > What's this 'boost' stuff and Magick++? ?Do I need to install > more things to make this work? Yes: http://www.imagemagick.org/Magick++/ http://www.boost.org/ For what `make` et. al do: http://www.tuxfiles.org/linuxhelp/softinstall.html Cheers, Chris -- http://blog.rebertia.com From sbassi at clubdelarazon.org Thu May 27 22:45:19 2010 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Thu, 27 May 2010 23:45:19 -0300 Subject: Free chapter about Python and databases (MySQL and SQLite) Message-ID: Hello, I want to announce that the publisher of "Python for Bioinformatis" (CRC Press) allowed me to publish a chapter from my book. I decided to publish the chapter about "Python and databases". I think it may be useful for somebody. The official announcement and download link is here: http://py4bio.com/2010/05/28/python_databases_mysql_sqlite/ For more information about the book: www.tinyurl.com/biopython Best, SB. -- Sebasti?n Bassi. Lic. en Biotecnologia. Curso de Python en un d?a: http://bit.ly/cursopython Non standard disclaimer: READ CAREFULLY. By reading this email, you agree, on behalf of your employer, to release me from all obligations and waivers arising from any and all NON-NEGOTIATED agreements, licenses, terms-of-service, shrinkwrap, clickwrap, browsewrap, confidentiality, non-disclosure, non-compete and acceptable use policies ("BOGUS AGREEMENTS") that I have entered into with your employer, its partners, licensors, agents and assigns, in perpetuity, without prejudice to my ongoing rights and privileges. You further represent that you have the authority to release me from any BOGUS AGREEMENTS on behalf of your employer. From john at castleamber.com Thu May 27 23:37:52 2010 From: john at castleamber.com (John Bokma) Date: Thu, 27 May 2010 22:37:52 -0500 Subject: Free chapter about Python and databases (MySQL and SQLite) References: Message-ID: <87vda8ofvz.fsf@castleamber.com> Sebastian Bassi writes: > Hello, I want to announce that the publisher of "Python for > Bioinformatis" (CRC Press) allowed me to publish a chapter from my > book. > I decided to publish the chapter about "Python and databases". I think > it may be useful for somebody. > The official announcement and download link is here: > http://py4bio.com/2010/05/28/python_databases_mysql_sqlite/ > For more information about the book: www.tinyurl.com/biopython I feel more than uncomfortable with example code that uses: user="root" (e.g. p291). I never get why people write a short (IMO) /bad/ intro to databases while there are books out there that do a way better job. To me such chapters are just a way to get more pages :-(. (=make the book more expensive = less money to buy a /good/ book on databases) I would love to see more technical books that start at page 1 with the topic, not with an introduction to the language (170+ pages) and some other stuff that IMO shouldn't be there (MySQL introduction, XML, etc.). What I would expect, based on the title is: p 175-222 p 315-456 p 539-552 This would probably make the book a bit cheaper, so one can buy a good book on MySQL, a good book on XML, and a good book on Python. (Or maybe one already has those, like me). IMO, YMMV -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From sbassi at clubdelarazon.org Fri May 28 00:17:35 2010 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Fri, 28 May 2010 01:17:35 -0300 Subject: Free chapter about Python and databases (MySQL and SQLite) In-Reply-To: <87vda8ofvz.fsf@castleamber.com> References: <87vda8ofvz.fsf@castleamber.com> Message-ID: On Fri, May 28, 2010 at 12:37 AM, John Bokma wrote: > I feel more than uncomfortable with example code that uses: user="root" What's wrong with this? It is just an example of connection string. The reader will use his/her user/pass/dbname according to their own settings. > (e.g. p291). I never get why people write a short (IMO) /bad/ intro to > databases while there are books out there that do a way better The intended audience of this book are biologist who may be not familiarized with relational databases. Most of my colleagues (at least from the bio camp) don't even know that behind most dynamic web pages there are databases and I think that most of them will find the intro section useful. You can always skip what you know and go to the point you want. > job. To me such chapters are just a way to get more pages :-(. (=make > the book more expensive = less money to buy a /good/ book on databases) I am not sure that price in this kind of book are tied to the number of pages. There must be some relation, but this is not the main factor affecting price. > I would love to see more technical books that start at page 1 with the > topic, not with an introduction to the language (170+ pages) and some ... I see where you go, it seems you are not the target audience for this book. Anyway I appreciate your feedback. Best, SB From decklar at googlemail.com Fri May 28 02:17:15 2010 From: decklar at googlemail.com (ledpepper) Date: Thu, 27 May 2010 23:17:15 -0700 (PDT) Subject: First script. Need some help References: <546e1b04-ae78-4f72-984f-dc136a4022cf@z13g2000prh.googlegroups.com> Message-ID: <7e67baf2-6c00-40dd-80dc-4f12befe70fc@o12g2000vba.googlegroups.com> Thanks Everyone. I followed your instructions and my script is successfully copying the result to the clipboard. Now for the fun. To work out the rest of the script :) I use the IDLE IDE and not codepad.org. I just thought that was the standard for pasting scripts here in this group. Thanks all. From kse.listed.co1 at gmail.com Fri May 28 04:59:01 2010 From: kse.listed.co1 at gmail.com (Naeem) Date: Fri, 28 May 2010 01:59:01 -0700 (PDT) Subject: "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com Message-ID: <81b20491-6ad6-45aa-b4c3-84fc4cc4a8fd@u7g2000vbq.googlegroups.com> "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com "Hansika Motwani IN DENIM JEANS" "Hansika Motwani BEAUTIFUL BELLY" "Hansika Motwani as college GIRL" "Hansika Motwani in GYM in RED BRA" "Hansika Motwani in GREEN SAREE BELLY" "BOLLYWOOD GIRLS" on http://hollywood-bollywood-pics.blogspot.com From eric.brunel.pragmadev at gmail.com Fri May 28 05:31:49 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Fri, 28 May 2010 02:31:49 -0700 (PDT) Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Message-ID: <4d9e0aff-c013-43ea-81e2-cd674149a05a@z33g2000vbb.googlegroups.com> On May 27, 3:24?pm, Christian Heimes wrote: > > ?Do I miss something? > > Is this the way to do it, or is there a better one? > > A better way was introduced in Python 2.6. Seehttp://docs.python.org/library/functions.html?highlight=property#prop... > I have a Python only version around if you are still using Python 2.5. > > Christian Mmmm, I might still miss something. OK, I can replace my initial property using @property and @p.setter, but it doesn't seem to work in subclasses: class A(object): @property def p(self): return self._p @p.setter def _set_p(self, p): self._p = p class B(A): @p.setter def _set_p(self, p): ? results in: Traceback (most recent call last): File "toto.py", line 8, in class B(A): File "toto.py", line 9, in B @p.setter NameError: name 'p' is not defined From eric.brunel.pragmadev at gmail.com Fri May 28 05:36:39 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Fri, 28 May 2010 02:36:39 -0700 (PDT) Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> Message-ID: On May 27, 8:56?pm, Francesco Bochicchio wrote: > On 27 Mag, 14:37, eb303 wrote: > > > > > Hello all, > > > I've been using Python properties quite a lot lately and I've found a > > few things that are a bit annoying about them in some cases. I > > wondered if I missed something or if anybody else has this kind of > > problems too, and if there are better solutions than the ones I'm > > using ATM. > > > The first annoyance is when I want to specialize a property in a > > subclass. This happens quite often actually, and it is even sometimes > > the reason why a plain attribute is turned into a property: a subclass > > needs to do more things than the superclass when the property is > > updated for example. So, of course, my first try was: > > > class A(object): > > ? def __init__(self): > > ? ? self._p = None > > ? def _get_p(self): > > ? ? return self._p > > ? def _set_p(self, p): > > ? ? self._p = p > > ? p = property(_get_p, _set_p) > > class B(A): > > ? def _set_p(self, p): > > ? ? ## Additional things here? > > ? ? super(B, self)._set_p(p) > > > And of course, it doesn't work: the property has been bound to > > A._set_p in A, so any new definition of _set_p in any subclass does > > not replace the set method for the property. So I always have to add a > > line: > > p = property(A._get_p, _set_p) > > in the subclass too. This is a bit awkward to me, since I have to > > specify the superclass's name (super(?) can't be used, since it should > > take B as an argument, and B isn't defined yet?). Do I miss something? > > Is this the way to do it, or is there a better one? > > Don't know if is better, but you could add a level of indirection to > solve it > > ?class A(object): > ? ?def __init__(self): > ? ? ?self._p = None > ? ?def _get_p(self): > ? ? ?return self._p > ? ?def _set_p(self, p): > ? ? ?self._p = p > ? ?def _virtual_get_p (self): _get_p(self) > ? ?def _virtual_set_p (self,v): _set_p(self, v) > ? ?p = property(_virtual_get_p, _virtual_set_p) > > At this point, the subclasses of A can reimplement _get_p and _set_p > as they like (I think) > > Ciao > ----- > FB Well, I've thought about that too and it should work, but that makes 2 function calls instead of one for every property access? I'd really like to avoid that. By the way, I think your 'virtual' methods should be written as: def _virtual_get_p (self): return self._get_p() def _virtual_set_p (self,v): self._set_p(v) Thanks anyway. - Eric - From eric.brunel.pragmadev at gmail.com Fri May 28 05:46:36 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Fri, 28 May 2010 02:46:36 -0700 (PDT) Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> <8679gtFdj4U1@mid.individual.net> Message-ID: <77f68c71-e73f-4721-9ba8-a4524c41ee86@w3g2000vbd.googlegroups.com> On May 27, 3:14?pm, Neil Cerutti wrote: > On 2010-05-27, eb303 wrote: > > > I've been using Python properties quite a lot lately and I've > > found a few things that are a bit annoying about them in some > > cases. I wondered if I missed something or if anybody else has > > this kind of problems too, and if there are better solutions > > than the ones I'm using ATM. > > The first annoyance is when I want to specialize a property in a > > subclass. > > See: > > URI:http://infinitesque.net/articles/2005/enhancing%20Python%27s%20proper... > > -- > Neil Cerutti > *** You found a dead moose-rat. You sell the hide for $200. *** Thanks for the suggestion, but it looks a bit heavy? Performing the name lookup on the specialized object each time the property is accessed seems a bit overkill. I'd really just like a simple way to tell in the subclass: now, the setter methof for property p is this one, only that? Thanks again anyway. - Eric - From lists at cheimes.de Fri May 28 05:50:56 2010 From: lists at cheimes.de (Christian Heimes) Date: Fri, 28 May 2010 11:50:56 +0200 Subject: Minor annoyances with properties In-Reply-To: <4d9e0aff-c013-43ea-81e2-cd674149a05a@z33g2000vbb.googlegroups.com> References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> <4d9e0aff-c013-43ea-81e2-cd674149a05a@z33g2000vbb.googlegroups.com> Message-ID: Am 28.05.2010 11:31, schrieb eb303: > On May 27, 3:24 pm, Christian Heimes wrote: >>> Do I miss something? >>> Is this the way to do it, or is there a better one? >> >> A better way was introduced in Python 2.6. Seehttp://docs.python.org/library/functions.html?highlight=property#prop... >> I have a Python only version around if you are still using Python 2.5. >> >> Christian > > Mmmm, I might still miss something. OK, I can replace my initial > property using @property and @p.setter, but it doesn't seem to work in > subclasses: > > class A(object): > @property > def p(self): > return self._p > @p.setter > def _set_p(self, p): > self._p = p > class B(A): > @p.setter > def _set_p(self, p): > ? > > results in: > > Traceback (most recent call last): > File "toto.py", line 8, in > class B(A): > File "toto.py", line 9, in B > @p.setter > NameError: name 'p' is not defined It doesn't work because "p" is not in the scope of B's body while B is created. You have to write class B(A): # access the "p" property from class A @A.p.setter def p(self, p): pass # once p is in the class body scope, you must not use A.p again @p.deleter def p(self): pass Christian From tartley at tartley.com Fri May 28 05:54:31 2010 From: tartley at tartley.com (Jonathan Hartley) Date: Fri, 28 May 2010 02:54:31 -0700 (PDT) Subject: if, continuation and indentation References: Message-ID: On May 27, 1:57?pm, Jean-Michel Pichavant wrote: > HH wrote: > > I have a question about best practices when it comes to line wrapping/ > > continuation and indentation, specifically in the case of an if > > statement. > > > When I write an if statement with many conditions, I prefer to use a > > parenthesis around the whole block and get the implicit continuation, > > rather than ending each line with an escape character. ?Thus, using > > the example from the style guide (http://www.python.org/dev/peps/ > > pep-0008/) I would write: > > > ? ? if (width == 0 and > > ? ? ? ? height == 0 and > > ? ? ? ? color == 'red' and > > ? ? ? ? emphasis == 'strong' or > > ? ? ? ? highlight > 100): > > ? ? ? ? raise ValueError("sorry, you lose") > > > The problem should be obvious -- it's not easy to see where the > > conditional ends and the statement begins since they have the same > > indentation. ?Part of the problem, I suppose, is that Emacs indents > > 'height' and the other lines in the conditional to 4 spaces (because > > of the parenthesis). ?How do people deal with this situation? > > > Thanks, > > Henrik > > One possible solution > > ? ? if ( > ? ? ? ? ? ? width == 0 and > ? ? ? ? ? ? height == 0 and > ? ? ? ? ? ? color == 'red' and > ? ? ? ? ? ? emphasis == 'strong' or > ? ? ? ? ? ? highlight > 100 > ? ? ? ?): > ? ? ? ? raise ValueError("sorry, you lose") > > JM ? I've always liked this, or even: if ( width == 0 and height == 0 and color == 'red' and emphasis == 'strong' or highlight > 100 ): raise ValueError("sorry, you lose") but my co-workers have uniformly gone bananas whenever I try it. From jeanmichel at sequans.com Fri May 28 06:34:54 2010 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 28 May 2010 12:34:54 +0200 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: <4BFF9C4E.1020208@sequans.com> Jonathan Hartley wrote: > On May 27, 1:57 pm, Jean-Michel Pichavant > wrote: > >> HH wrote: >> >>> I have a question about best practices when it comes to line wrapping/ >>> continuation and indentation, specifically in the case of an if >>> statement. >>> >>> When I write an if statement with many conditions, I prefer to use a >>> parenthesis around the whole block and get the implicit continuation, >>> rather than ending each line with an escape character. Thus, using >>> the example from the style guide (http://www.python.org/dev/peps/ >>> pep-0008/) I would write: >>> >>> if (width == 0 and >>> height == 0 and >>> color == 'red' and >>> emphasis == 'strong' or >>> highlight > 100): >>> raise ValueError("sorry, you lose") >>> >>> The problem should be obvious -- it's not easy to see where the >>> conditional ends and the statement begins since they have the same >>> indentation. Part of the problem, I suppose, is that Emacs indents >>> 'height' and the other lines in the conditional to 4 spaces (because >>> of the parenthesis). How do people deal with this situation? >>> >>> Thanks, >>> Henrik >>> >> One possible solution >> >> if ( >> width == 0 and >> height == 0 and >> color == 'red' and >> emphasis == 'strong' or >> highlight > 100 >> ): >> raise ValueError("sorry, you lose") >> >> JM >> > > I've always liked this, or even: > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100 > ): > raise ValueError("sorry, you lose") > > > but my co-workers have uniformly gone bananas whenever I try it. > I tried to give a layout that fits the OP way of doing, but I would not use what I described above, so I can understand why your co workers go bananas :) when it comes to extended conditions in if statement I prefer to write something like if self.haveLost(): raise ValueError("sorry, you lose") It drastically improves the reading because it splits the notion of what to do in which case, and how do you identify the cases (i.e. what should I do when I've lost, and how do I know that I've lost). If you don't want to pollute your upper namespace you can embed the function that way: def foo(): width = 0 height = 0 color = 'red' emphasis = 'strong' def haveLost(): return not width and not height and color == 'red' and emphasis =='strong' if haveLost(): raise ValueError("sorry you lose") It has the cool side effect to name your condition as well, that helps debugging the condition *a lot*. JM From tartley at tartley.com Fri May 28 06:48:59 2010 From: tartley at tartley.com (Jonathan Hartley) Date: Fri, 28 May 2010 11:48:59 +0100 Subject: if, continuation and indentation In-Reply-To: <4BFF9C4E.1020208@sequans.com> References: <4BFF9C4E.1020208@sequans.com> Message-ID: <4BFF9F9B.40103@tartley.com> On 28/05/2010 11:34, Jean-Michel Pichavant wrote: > Jonathan Hartley wrote: >> On May 27, 1:57 pm, Jean-Michel Pichavant >> wrote: >>> HH wrote: >>>> I have a question about best practices when it comes to line wrapping/ >>>> continuation and indentation, specifically in the case of an if >>>> statement. >>>> When I write an if statement with many conditions, I prefer >>>> to use a >>>> parenthesis around the whole block and get the implicit continuation, >>>> rather than ending each line with an escape character. Thus, using >>>> the example from the style guide (http://www.python.org/dev/peps/ >>>> pep-0008/) I would write: >>>> if (width == 0 and >>>> height == 0 and >>>> color == 'red' and >>>> emphasis == 'strong' or >>>> highlight > 100): >>>> raise ValueError("sorry, you lose") >>>> The problem should be obvious -- it's not easy to see where the >>>> conditional ends and the statement begins since they have the same >>>> indentation. Part of the problem, I suppose, is that Emacs indents >>>> 'height' and the other lines in the conditional to 4 spaces (because >>>> of the parenthesis). How do people deal with this situation? >>>> Thanks, >>>> Henrik >>> One possible solution >>> >>> if ( >>> width == 0 and >>> height == 0 and >>> color == 'red' and >>> emphasis == 'strong' or >>> highlight > 100 >>> ): >>> raise ValueError("sorry, you lose") >>> >>> JM >> >> I've always liked this, or even: >> >> if ( >> width == 0 and >> height == 0 and >> color == 'red' and >> emphasis == 'strong' or >> highlight > 100 >> ): >> raise ValueError("sorry, you lose") >> >> >> but my co-workers have uniformly gone bananas whenever I try it. > I tried to give a layout that fits the OP way of doing, but I would > not use what I described above, so I can understand why your co > workers go bananas :) > > when it comes to extended conditions in if statement I prefer to write > something like > > if self.haveLost(): > raise ValueError("sorry, you lose") > > It drastically improves the reading Good point. +1 for naming the condition, hooray for self-documenting code. Sometime last year at my workplace, we started referring to comments as 'lies', we now always try to use techniques like this instead of comments. -- Jonathan Hartley Made of meat. http://tartley.com tartley at tartley.com +44 7737 062 225 twitter/skype: tartley From kaklis at gmail.com Fri May 28 07:50:21 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 28 May 2010 04:50:21 -0700 (PDT) Subject: Sockets and xml problem Message-ID: <0ee7b377-66af-4b77-aa7f-3e5ef3b2b1ef@q33g2000vbt.googlegroups.com> Hi in the following code class MyClientHandler(SocketServer.BaseRequestHandler): def handle(self): print self.client_address, now( ) time.sleep(5) while True: xmltxt = self.request.recv(1024) <--is this ok - enough? if not xmltxt: break doc = minidom.parseString(data) <--- it also fails for parse(data) rootNode = doc.documentElement level = 0 walk(rootNode, outFile, level) <---just a function to print the xml self.request.send('Echo=>%s at %s' % (data, now( ))) rootNode = doc.documentElement level = 0 walk(rootNode, outFile, level) self.request.send('Echo=>%s at %s' % (data, now( ))) self.request.close( ) # make a threaded server, listen/handle clients forever myaddr = (myHost, myPort) server = SocketServer.ThreadingTCPServer(myaddr, MyClientHandler) server.serve_forever( ) I want to send XML messages from my client. The server sends back the XML it receives but the parser exits with error codes. What am i doing wrong. Thanks in advance From victorsubervi at gmail.com Fri May 28 08:06:10 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 28 May 2010 08:06:10 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEE87B.1030302@tim.thechases.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> <4BFEA8A4.2040202@thechases.com> <4BFEE87B.1030302@tim.thechases.com> Message-ID: On Thu, May 27, 2010 at 5:47 PM, Tim Chase wrote: > On 05/27/2010 03:32 PM, Victor Subervi wrote: > > On Thu, May 27, 2010 at 1:15 PM, Tim Chase wrote: >> >>> That should be: >>>> >>>> ', '.join(['%s'] * len(values))) >>>> >>> >>> Or as I've done in the past: >>> >>> ', '.join('%s' for _ in values) >>> >> >> Huh? Can you describe that underscore to me? Fascinating! >> > > The underscore is a valid variable-name, idiomatically used for "I don't > care about this", often seen in places like tuple assignment: > > a,_,_,d = some_4_element_tuple > > So in my above case, it could also have been written as > > ', '.join('%s' for value in values) > ', '.join('%s' for dont_care_about_the_value in values) > > but the "_" idiom means "I'm iterating over 'values' but I'm not actually > using the values I get from it" > I should have known. Thanks! beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Fri May 28 08:16:09 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 28 May 2010 08:16:09 -0400 Subject: Some More MySQL In-Reply-To: References: <4BFEBFF3.6040909@mrabarnett.plus.com> <4BFEF0A0.2040800@mrabarnett.plus.com> Message-ID: On Fri, May 28, 2010 at 2:17 AM, Dennis Lee Bieber wrote: > On Thu, 27 May 2010 23:22:24 +0100, MRAB > declaimed the following in gmane.comp.python.general: > > > > > Placeholders which are handled by .execute shouldn't be wrapped in > > quotes, even is the value is a string, because .execute will handle that > > (and any other details) itself. > > Even more internal details -- the MySQLdb placeholder is %s because > the adapter, internally, converts ALL parameters to strings, applies > escapes to them, and THEN wraps them with quotes before using Python > string interpolation to make the query that gets submitted to the > server. > > This is why you can not use, say %d as a placeholder for a numeric > parameter... MySQLdb will convert that numeric to a string, and then > Python will choke when it tries to use a %d formatter and is given a > string value. > > > All of your and MRAB's comments were very helpful. However, I don't see how these two problems are addressed: sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + opTable[1:]) # cursor.execute(sql, id) cursor.execute('select * from options%s where ID=%s' % (opTable[0].upper() + opTable[1:], id)) The last one works, but if I comment it out and uncomment the middle line, it doesn't. Same here: sql = "update options%s set PriceDiff='%%s' where Field='%%s' and ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:]) # cursor.execute(sql, (value, opName, id, store)) cursor.execute('update options%s set PriceDiff="%s" where Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:], value, opName, id, store)) TIA, beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From awilliam at whitemice.org Fri May 28 08:17:44 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 28 May 2010 08:17:44 -0400 Subject: multiprocessing and accessing server's stdout In-Reply-To: References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: <1275049064.7612.4.camel@linux-yu4c.site> On Thu, 2010-05-27 at 08:36 -0700, Tim Arnold wrote: > On May 26, 4:52 pm, Adam Tauno Williams > wrote: > > On Wed, 2010-05-26 at 11:47 -0700, Tim Arnold wrote: > > > Hi, > > > I'm using multiprocessing's BaseManager to create a server on one > > > machine and a client on another. The client fires a request and the > > > server does some work, the result of which ends up on a shared file > > > system that both the client and server can see. > > > However, I need the client machine to see the stdout of the process > > > running on the server. Not sure this is doable--I've been unable to > > > google anything useful on this one. > > > > Nope, it isn't. Don't use stdout, use an IPC mechanism to communicate > > between the client and the server if you need feedback. > Thanks for that info, it saves me some time. This is a new area for me > though: do you redirect stdout on the server to a socket and have the > client listen and somehow pipe the sockets contents to the client > stdout? No, I close stdin, stderr, and stdout on the server processes and attach them to /dev/null. Just don't use stdout. > Interestingly, the RPYc package manages it--that is, the client gets > the stdout of the server process, so I'll dig into that code to get an > idea. In the meantime, are there any recipes or other docs that would > be helpful? I've been googling but without much luck. Closing stdout and attaching it to any other file descriptor is pretty simple. sys.stdout = open('/dev/null', 'w') You should be able to point it any any file-like object. But, again, why? If you have the data in the process why send it to stdout and redirect it. Why not just send the data to the client directly? -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From stefan_ml at behnel.de Fri May 28 08:23:22 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 28 May 2010 14:23:22 +0200 Subject: Sockets and xml problem In-Reply-To: <0ee7b377-66af-4b77-aa7f-3e5ef3b2b1ef@q33g2000vbt.googlegroups.com> References: <0ee7b377-66af-4b77-aa7f-3e5ef3b2b1ef@q33g2000vbt.googlegroups.com> Message-ID: kaklis at gmail.com, 28.05.2010 13:50: > Hi in the following code > > class MyClientHandler(SocketServer.BaseRequestHandler): > def handle(self): > print self.client_address, now( ) > time.sleep(5) > while True: > xmltxt = self.request.recv(1024)<--is this ok - > enough? Depends. If your messages are never larger than 1K, this is enough. Otherwise, you have to collect the data, instead of parsing each chunk separately. I suggest using the incremental parser in xml.etree.ElementTree, which allows you to push more data into the parser as it comes in. When done, call it's .close() method to retrieve the result. http://docs.python.org/library/xml.etree.elementtree.html#xmltreebuilder-objects > I want to send XML messages from my client. The server sends back the > XML it receives but the parser exits with error codes. You should also rethink your approach one more time. Are you sure that a raw socket is a good protocol for sending your messages? In many cases, a proper higher-level transport protocol like HTTP is much better suited. If you provide more details about what you are trying to do, others may be able to help you further. Stefan From kaklis at gmail.com Fri May 28 08:40:25 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 28 May 2010 05:40:25 -0700 (PDT) Subject: Sockets and xml problem References: <0ee7b377-66af-4b77-aa7f-3e5ef3b2b1ef@q33g2000vbt.googlegroups.com> Message-ID: <650933f4-0db2-4a42-a0a3-0a92d15fd6f0@o4g2000vbo.googlegroups.com> On May 28, 3:23?pm, Stefan Behnel wrote: > kak... at gmail.com, 28.05.2010 13:50: > > > Hi in the following code > > > class MyClientHandler(SocketServer.BaseRequestHandler): > > ? ? ?def handle(self): > > ? ? ? ? ?print self.client_address, now( ) > > ? ? ? ? ?time.sleep(5) > > ? ? ? ? ?while True: > > ? ? ? ? ? ? ?xmltxt = self.request.recv(1024)<--is this ok - > > enough? > > Depends. If your messages are never larger than 1K, this is enough. > Otherwise, you have to collect the data, instead of parsing each chunk > separately. > > I suggest using the incremental parser in xml.etree.ElementTree, which > allows you to push more data into the parser as it comes in. When done, > call it's .close() method to retrieve the result. > > http://docs.python.org/library/xml.etree.elementtree.html#xmltreebuil... > > > I want to send XML messages from my client. The server sends back the > > XML it receives but the parser exits with error codes. > > You should also rethink your approach one more time. Are you sure that a > raw socket is a good protocol for sending your messages? In many cases, a > proper higher-level transport protocol like HTTP is much better suited. If > you provide more details about what you are trying to do, others may be > able to help you further. > > Stefan Stefan first of all thank you for your response. I don't want anything fancy. Just a simple server that accepts xml messages from multple clients in xml, parses the XML and show it in a console. Antonis From tino at wildenhain.de Fri May 28 08:41:54 2010 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 28 May 2010 14:41:54 +0200 Subject: Free chapter about Python and databases (MySQL and SQLite) In-Reply-To: References: Message-ID: <4BFFBA12.6050004@wildenhain.de> Hi, Am 28.05.2010 04:45, schrieb Sebastian Bassi: > Hello, I want to announce that the publisher of "Python for > Bioinformatis" (CRC Press) allowed me to publish a chapter from my > book. > I decided to publish the chapter about "Python and databases". I think > it may be useful for somebody. > The official announcement and download link is here: > http://py4bio.com/2010/05/28/python_databases_mysql_sqlite/ > For more information about the book: www.tinyurl.com/biopython > Best, > SB. This is nice! Congrats! Did you consider adding a part dealing with postgresql too? (Especially interesting in the way you can write stored functions in python there) Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3254 bytes Desc: S/MIME Cryptographic Signature URL: From kushal.kumaran+python at gmail.com Fri May 28 08:58:29 2010 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Fri, 28 May 2010 18:28:29 +0530 Subject: Some More MySQL In-Reply-To: References: <4BFEBFF3.6040909@mrabarnett.plus.com> <4BFEF0A0.2040800@mrabarnett.plus.com> Message-ID: On Fri, May 28, 2010 at 5:46 PM, Victor Subervi wrote: > On Fri, May 28, 2010 at 2:17 AM, Dennis Lee Bieber > wrote: >> >> On Thu, 27 May 2010 23:22:24 +0100, MRAB >> declaimed the following in gmane.comp.python.general: >> >> > >> > Placeholders which are handled by .execute shouldn't be wrapped in >> > quotes, even is the value is a string, because .execute will handle that >> > (and any other details) itself. >> >> ? ? ? ?Even more internal details -- the MySQLdb placeholder is %s because >> the adapter, internally, converts ALL parameters to strings, applies >> escapes to them, and THEN wraps them with quotes before using Python >> string interpolation to make the query that gets submitted to the >> server. >> >> ? ? ? ?This is why you can not use, say %d as a placeholder for a numeric >> parameter... MySQLdb will convert that numeric to a string, and then >> Python will choke when it tries to use a %d formatter and is given a >> string value. >> >> > All of your and MRAB's comments were very helpful. However, I don't see how > these two problems are addressed: > > ????? sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + > opTable[1:]) > #????? cursor.execute(sql, id) > ????? cursor.execute('select * from options%s where ID=%s' % > (opTable[0].upper() + opTable[1:], id)) > The second argument to cursor.execute needs to be a tuple. Change the call to this: cursor.execute(sql, (id,)) > The last one works, but if I comment it out and uncomment the middle line, > it doesn't. Same here: > > ??????? sql = "update options%s set PriceDiff='%%s' where Field='%%s' and > ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:]) > #??????? cursor.execute(sql, (value, opName, id, store)) > ??????? cursor.execute('update options%s set PriceDiff="%s" where Field="%s" > and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:], value, > opName, id, store)) > Lose the quotes around the %s. You are replying to a post that describes why this is important. -- regards, kushal From martin.hellwig at dcuktec.org Fri May 28 10:41:27 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 28 May 2010 15:41:27 +0100 Subject: multiprocessing and accessing server's stdout In-Reply-To: References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: On 05/28/10 13:17, Adam Tauno Williams wrote: > > You should be able to point it any any file-like object. But, again, > why? > > If you have the data in the process why send it to stdout and redirect > it. Why not just send the data to the client directly? Well you might want to multiplex it to more then one client, not saying that this is the case here, just something I imagine possible. -- mph From eric.brunel.pragmadev at gmail.com Fri May 28 11:01:29 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Fri, 28 May 2010 08:01:29 -0700 (PDT) Subject: Minor annoyances with properties References: <207c8a79-2904-4478-b77a-32a7b7a923e4@q8g2000vbm.googlegroups.com> <4d9e0aff-c013-43ea-81e2-cd674149a05a@z33g2000vbb.googlegroups.com> Message-ID: <846debaa-dfb6-4ba4-a421-8c202a1b7756@o15g2000vbb.googlegroups.com> On May 28, 11:50?am, Christian Heimes wrote: > Am 28.05.2010 11:31, schrieb eb303: > > > > > On May 27, 3:24 pm, Christian Heimes wrote: > >>> ?Do I miss something? > >>> Is this the way to do it, or is there a better one? > > >> A better way was introduced in Python 2.6. Seehttp://docs.python.org/library/functions.html?highlight=property#prop... > >> I have a Python only version around if you are still using Python 2.5. > > >> Christian > > > Mmmm, I might still miss something. OK, I can replace my initial > > property using @property and @p.setter, but it doesn't seem to work in > > subclasses: > > > class A(object): > > ? @property > > ? def p(self): > > ? ? return self._p > > ? @p.setter > > ? def _set_p(self, p): > > ? ? self._p = p > > class B(A): > > ? @p.setter > > ? def _set_p(self, p): > > ? ? ? > > > results in: > > > Traceback (most recent call last): > > ? File "toto.py", line 8, in > > ? ? class B(A): > > ? File "toto.py", line 9, in B > > ? ? @p.setter > > NameError: name 'p' is not defined > > It doesn't work because "p" is not in the scope of B's body while B is > created. You have to write > > class B(A): > ? ? # access the "p" property from class A > ? ? @A.p.setter > ? ? def p(self, p): > ? ? ? ? pass > > ? ? # once p is in the class body scope, you must not use A.p again > ? ? @p.deleter > ? ? def p(self): > ? ? ? ? pass > > Christian Well, I still have to explicitely specify the superclass's name then, so IMHO it's not a big improvement over repeating: p = property(A._get_p, _set_p) Thanks anyway? - Eric - From sbassi at clubdelarazon.org Fri May 28 11:12:55 2010 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Fri, 28 May 2010 12:12:55 -0300 Subject: Free chapter about Python and databases (MySQL and SQLite) In-Reply-To: <4BFFBA12.6050004@wildenhain.de> References: <4BFFBA12.6050004@wildenhain.de> Message-ID: On Fri, May 28, 2010 at 9:41 AM, Tino Wildenhain wrote: > Did you consider adding a part dealing with postgresql too? > (Especially interesting in the way you can write stored functions > in python there) That is a good idea for the next version/edition. But meanwhile I could write something in my blog at www.py4bio.com Best, SB From xcr4cx at googlemail.com Fri May 28 11:17:11 2010 From: xcr4cx at googlemail.com (christian schulze) Date: Fri, 28 May 2010 08:17:11 -0700 (PDT) Subject: http post References: <44b9686b-36d6-4aef-b20c-01b909e2ea53@q33g2000vbt.googlegroups.com> Message-ID: <6c0ada45-fa7e-45f6-8d4a-b92fd89e6548@v18g2000vbc.googlegroups.com> On 28 Mai, 16:47, yqyq22 wrote: > Hy, i would like to create a little script to reproduce this one > below: > Do you have suggestion? > > POST /folder/path/upload.exe?/dir HTTP/1.1 > Host: 192.168.100.1:8080 > User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: > 1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/ > *;q=0.8 > Accept-Language: en-us,en;q=0.5 > Accept-Encoding: gzip,deflate > Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 > Keep-Alive: 115 > Proxy-Connection: keep-alive > Referer:http://192.168.1.100:8080/dir1 > Content-Type: multipart/form-data; > boundary=---------------------------7075104567331 > Content-Length: 539 > Connection: close > > -----------------------------7075104567331 > Content-Disposition: form-data; name="F1"; filename="file.txt" > Content-Type: application/octet-stream > > -----------------------------7075104567331 > Content-Disposition: form-data; name="p4" > > -----------------------------7075104567331-- > > THANKS A LOT Just send it via a socket? Or use urllib, afair you can send custom HTTP headers. From yqyq22 at hotmail.com Fri May 28 11:20:53 2010 From: yqyq22 at hotmail.com (yqyq22) Date: Fri, 28 May 2010 08:20:53 -0700 (PDT) Subject: http post References: <44b9686b-36d6-4aef-b20c-01b909e2ea53@q33g2000vbt.googlegroups.com> <6c0ada45-fa7e-45f6-8d4a-b92fd89e6548@v18g2000vbc.googlegroups.com> Message-ID: <43b79db3-1b2d-48f8-8fe3-95a91fbc447c@a16g2000vbr.googlegroups.com> On May 28, 5:17?pm, christian schulze wrote: > On 28 Mai, 16:47, yqyq22 wrote: > > > > > > > Hy, i would like to create a little script to reproduce this one > > below: > > Do you have suggestion? > > > POST /folder/path/upload.exe?/dir HTTP/1.1 > > Host: 192.168.100.1:8080 > > User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: > > 1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) > > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/ > > *;q=0.8 > > Accept-Language: en-us,en;q=0.5 > > Accept-Encoding: gzip,deflate > > Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 > > Keep-Alive: 115 > > Proxy-Connection: keep-alive > > Referer:http://192.168.1.100:8080/dir1 > > Content-Type: multipart/form-data; > > boundary=---------------------------7075104567331 > > Content-Length: 539 > > Connection: close > > > -----------------------------7075104567331 > > Content-Disposition: form-data; name="F1"; filename="file.txt" > > Content-Type: application/octet-stream > > > -----------------------------7075104567331 > > Content-Disposition: form-data; name="p4" > > > -----------------------------7075104567331-- > > > THANKS A LOT > > Just send it via a socket? Or use urllib, afair you can send custom > HTTP headers.- Hide quoted text - > > - Show quoted text - If i understood right i would use only socket.. is it possible? thanks From xcr4cx at googlemail.com Fri May 28 11:23:18 2010 From: xcr4cx at googlemail.com (christian schulze) Date: Fri, 28 May 2010 08:23:18 -0700 (PDT) Subject: Free chapter about Python and databases (MySQL and SQLite) References: <4BFFBA12.6050004@wildenhain.de> Message-ID: <75097175-6f22-4eaa-aa69-c93df86227c5@o4g2000vbo.googlegroups.com> On 28 Mai, 17:12, Sebastian Bassi wrote: > On Fri, May 28, 2010 at 9:41 AM, Tino Wildenhain wrote: > > Did you consider adding a part dealing with postgresql too? > > (Especially interesting in the way you can write stored functions > > in python there) > > That is a good idea for the next version/edition. But meanwhile I > could write something in my blog atwww.py4bio.com > Best, > SB Indeed a style like > user="root" is not that nice. I had no look at the chapter but recommend you to read the PEP 8 - Python style guides (code conventions for python). Imo a book have to be kinda exemplary. And bad style sucks anyway ... PS: > user = 'root' or user = "root" ... would be much more beautyful. From kaklis at gmail.com Fri May 28 11:24:21 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 28 May 2010 08:24:21 -0700 (PDT) Subject: Omit the headers from XML message Message-ID: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Hi i have the following xml message i want to omit the headers, any hints? POST /test/pcp/Listener HTTP/1.1 User-Agent: Jakarta Commons-HttpClient/3.1 Host: 127.0.0.1:50002 Content-Length: 547 scvdcvsdv sdfv Antonis Kaklis away testing the new client jlkdjf android From xcr4cx at googlemail.com Fri May 28 11:24:28 2010 From: xcr4cx at googlemail.com (christian schulze) Date: Fri, 28 May 2010 08:24:28 -0700 (PDT) Subject: http post References: <44b9686b-36d6-4aef-b20c-01b909e2ea53@q33g2000vbt.googlegroups.com> <6c0ada45-fa7e-45f6-8d4a-b92fd89e6548@v18g2000vbc.googlegroups.com> <43b79db3-1b2d-48f8-8fe3-95a91fbc447c@a16g2000vbr.googlegroups.com> Message-ID: <6fce9505-229f-4086-bc51-290369da474b@k31g2000vbu.googlegroups.com> On 28 Mai, 17:20, yqyq22 wrote: > On May 28, 5:17?pm, christian schulze wrote: > > > > > On 28 Mai, 16:47, yqyq22 wrote: > > > > Hy, i would like to create a little script to reproduce this one > > > below: > > > Do you have suggestion? > > > > POST /folder/path/upload.exe?/dir HTTP/1.1 > > > Host: 192.168.100.1:8080 > > > User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: > > > 1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) > > > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/ > > > *;q=0.8 > > > Accept-Language: en-us,en;q=0.5 > > > Accept-Encoding: gzip,deflate > > > Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 > > > Keep-Alive: 115 > > > Proxy-Connection: keep-alive > > > Referer:http://192.168.1.100:8080/dir1 > > > Content-Type: multipart/form-data; > > > boundary=---------------------------7075104567331 > > > Content-Length: 539 > > > Connection: close > > > > -----------------------------7075104567331 > > > Content-Disposition: form-data; name="F1"; filename="file.txt" > > > Content-Type: application/octet-stream > > > > -----------------------------7075104567331 > > > Content-Disposition: form-data; name="p4" > > > > -----------------------------7075104567331-- > > > > THANKS A LOT > > > Just send it via a socket? Or use urllib, afair you can send custom > > HTTP headers.- Hide quoted text - > > > - Show quoted text - > > If i understood right i would use only socket.. is it possible? > thanks Yeah i think so, but i am not quite sure. Just test it :) From yqyq22 at hotmail.com Fri May 28 11:28:45 2010 From: yqyq22 at hotmail.com (yqyq22) Date: Fri, 28 May 2010 08:28:45 -0700 (PDT) Subject: http post References: <44b9686b-36d6-4aef-b20c-01b909e2ea53@q33g2000vbt.googlegroups.com> <6c0ada45-fa7e-45f6-8d4a-b92fd89e6548@v18g2000vbc.googlegroups.com> <43b79db3-1b2d-48f8-8fe3-95a91fbc447c@a16g2000vbr.googlegroups.com> <6fce9505-229f-4086-bc51-290369da474b@k31g2000vbu.googlegroups.com> Message-ID: <323e9d46-09ec-44b4-94d0-e3241579c284@v18g2000vbc.googlegroups.com> On May 28, 5:24?pm, christian schulze wrote: > On 28 Mai, 17:20, yqyq22 wrote: > > > > > > > On May 28, 5:17?pm, christian schulze wrote: > > > > On 28 Mai, 16:47, yqyq22 wrote: > > > > > Hy, i would like to create a little script to reproduce this one > > > > below: > > > > Do you have suggestion? > > > > > POST /folder/path/upload.exe?/dir HTTP/1.1 > > > > Host: 192.168.100.1:8080 > > > > User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: > > > > 1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729) > > > > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/ > > > > *;q=0.8 > > > > Accept-Language: en-us,en;q=0.5 > > > > Accept-Encoding: gzip,deflate > > > > Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 > > > > Keep-Alive: 115 > > > > Proxy-Connection: keep-alive > > > > Referer:http://192.168.1.100:8080/dir1 > > > > Content-Type: multipart/form-data; > > > > boundary=---------------------------7075104567331 > > > > Content-Length: 539 > > > > Connection: close > > > > > -----------------------------7075104567331 > > > > Content-Disposition: form-data; name="F1"; filename="file.txt" > > > > Content-Type: application/octet-stream > > > > > -----------------------------7075104567331 > > > > Content-Disposition: form-data; name="p4" > > > > > -----------------------------7075104567331-- > > > > > THANKS A LOT > > > > Just send it via a socket? Or use urllib, afair you can send custom > > > HTTP headers.- Hide quoted text - > > > > - Show quoted text - > > > If i understood right i would use only socket.. is it possible? > > thanks > > Yeah i think so, but i am not quite sure. Just test it :)- Hide quoted text - > > - Show quoted text - Do u have an example/link "closed" to my need? thanks From mgreene at bdurham.com Fri May 28 11:32:45 2010 From: mgreene at bdurham.com (Malcolm Greene) Date: Fri, 28 May 2010 11:32:45 -0400 Subject: Yet Another MySQL Problem In-Reply-To: <4BFEE87B.1030302@tim.thechases.com> References: <1274969873.2411.4.camel@nitrogen> <1274973424.2411.13.camel@nitrogen> <1274976694.2411.17.camel@nitrogen> <4BFEA449.2010105@mrabarnett.plus.com> <4BFEA8A4.2040202@thechases.com> <4BFEE87B.1030302@tim.thechases.com> Message-ID: <1275060765.5732.1377397625@webmail.messagingengine.com> Tim, > The underscore is a valid variable-name, idiomatically used for "I don't care about this", often seen in places like tuple assignment: The underscore is also used as an alias for gettext.gettext or gettext.ugettext so you may want to use another variable-name. Malcolm From victorsubervi at gmail.com Fri May 28 11:39:24 2010 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 28 May 2010 11:39:24 -0400 Subject: Some More MySQL In-Reply-To: References: <4BFEBFF3.6040909@mrabarnett.plus.com> <4BFEF0A0.2040800@mrabarnett.plus.com> Message-ID: I still have this code: sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + opTable[1:]) cursor.execute(sql, (id,)) which throws this error: /var/www/html/angrynates.com/cart/enterOptionsPrices2.py 70 print 'All options prices have been successfully updated.' 71 print '\n' 72 73 enterOptionsPrices2() 74 enterOptionsPrices2 = /var/www/html/angrynates.com/cart/enterOptionsPrices2.py in enterOptionsPrices2() 58 id = form.getfirst('%sID' % option) 59 sql = 'select * from options%s where ID=%%s', (opTable[0].upper() + opTable[1:]) 60 cursor.execute(sql, (id,)) 61 # cursor.execute('select * from options%s where ID=%s' % (opTable[0].upper() + opTable[1:], id)) 62 if cursor.fetchone() is not None: cursor = , cursor.execute = >, sql = ('select * from options%s where ID=%%s', 'Sizes'), id = '0.00' /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in execute(self=, query=('select * from options%s where ID=%%s', 'Sizes'), args=('0.00',)) 144 db = self._get_db() 145 charset = db.character_set_name() 146 query = query.encode(charset) 147 if args is not None: 148 query = query % db.literal(args) query = ('select * from options%s where ID=%%s', 'Sizes'), query.encode undefined, charset = 'latin1' AttributeError: 'tuple' object has no attribute 'encode' args = ("'tuple' object has no attribute 'encode'",) Please advise. TIA beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From joncle at googlemail.com Fri May 28 11:45:41 2010 From: joncle at googlemail.com (Jon Clements) Date: Fri, 28 May 2010 08:45:41 -0700 (PDT) Subject: Omit the headers from XML message References: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Message-ID: On 28 May, 16:24, "kak... at gmail.com" wrote: > Hi i have the following xml message i want to omit the headers, any > hints? > > POST /test/pcp/Listener HTTP/1.1 > User-Agent: Jakarta Commons-HttpClient/3.1 > Host: 127.0.0.1:50002 > Content-Length: 547 > > > ? > ? ? > ? ? ? > ? ? ? ? scvdcvsdv > ? ? ? ? sdfv > ? ? ? ? Antonis Kaklis > ? ? ? ? away > ? ? ? ? testing the new client > ? ? ? ? jlkdjf > ? ? ? ? android > ? ? ? > ? ? > ? > Assuming the header is separated by a blank line, something like: list(islice(dropwhile(bool, s.split('\n')), 1, None)) From __peter__ at web.de Fri May 28 12:09:02 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2010 18:09:02 +0200 Subject: Free chapter about Python and databases (MySQL and SQLite) References: <4BFFBA12.6050004@wildenhain.de> <75097175-6f22-4eaa-aa69-c93df86227c5@o4g2000vbo.googlegroups.com> Message-ID: christian schulze wrote: > On 28 Mai, 17:12, Sebastian Bassi wrote: >> On Fri, May 28, 2010 at 9:41 AM, Tino Wildenhain >> wrote: >> > Did you consider adding a part dealing with postgresql too? >> > (Especially interesting in the way you can write stored functions >> > in python there) >> >> That is a good idea for the next version/edition. But meanwhile I >> could write something in my blog atwww.py4bio.com >> Best, >> SB > > Indeed a style like >> user="root" > is not that nice. > > I had no look at the chapter but recommend you to read the PEP 8 - > Python style guides (code conventions for python). > > Imo a book have to be kinda exemplary. And bad style sucks anyway ... > > PS: >> user = 'root' or user = "root" > ... would be much more beautyful. My crystal ball says that the post you are not quoting is concerned about the security implications of accessing a database as the superuser rather than about spaces surrounding the assignment operator. My crystal ball then starts nitpicking and adds that in the sample chapter user="root" occurs within an argument list where its format is actually required by the PEP: """ - Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value. Yes: def complex(real, imag=0.0): return magic(r=real, i=imag) """ Cheers, Peter From kaklis at gmail.com Fri May 28 12:38:23 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 28 May 2010 09:38:23 -0700 (PDT) Subject: Omit the headers from XML message References: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Message-ID: <5288770c-bfdf-41e3-a2a6-f38587f07802@q13g2000vbm.googlegroups.com> On 28 ?????, 18:45, Jon Clements wrote: > On 28 May, 16:24, "kak... at gmail.com" wrote: > > > > > > > Hi i have the following xml message i want to omit the headers, any > > hints? > > > POST /test/pcp/Listener HTTP/1.1 > > User-Agent: Jakarta Commons-HttpClient/3.1 > > Host: 127.0.0.1:50002 > > Content-Length: 547 > > > > > ? > > ? ? > > ? ? ? > > ? ? ? ? scvdcvsdv > > ? ? ? ? sdfv > > ? ? ? ? Antonis Kaklis > > ? ? ? ? away > > ? ? ? ? testing the new client > > ? ? ? ? jlkdjf > > ? ? ? ? android > > ? ? ? > > ? ? > > ? > > > > Assuming the header is separated by a blank line, something like: > > list(islice(dropwhile(bool, s.split('\n')), 1, None)) Thank you!!! Antonis From python at mrabarnett.plus.com Fri May 28 12:39:32 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 May 2010 17:39:32 +0100 Subject: Some More MySQL In-Reply-To: References: <4BFEBFF3.6040909@mrabarnett.plus.com> <4BFEF0A0.2040800@mrabarnett.plus.com> Message-ID: <4BFFF1C4.3030901@mrabarnett.plus.com> Victor Subervi wrote: > I still have this code: > > sql = 'select * from options%s where ID=%%s', (opTable[0].upper() > + opTable[1:]) > cursor.execute(sql, (id,)) > > which throws this error: > > /var/www/html/angrynates.com/cart/enterOptionsPrices2.py > > 70 print 'All options prices have been successfully updated.' > 71 print '\n' > 72 > 73 enterOptionsPrices2() > 74 > enterOptionsPrices2 = > /var/www/html/angrynates.com/cart/enterOptionsPrices2.py > in enterOptionsPrices2() > 58 id = form.getfirst('%sID' % option) > 59 sql = 'select * from options%s where ID=%%s', > (opTable[0].upper() + opTable[1:]) > 60 cursor.execute(sql, (id,)) > 61 # cursor.execute('select * from options%s where ID=%s' % > (opTable[0].upper() + opTable[1:], id)) > 62 if cursor.fetchone() is not None: > cursor = , cursor.execute = Cursor.execute of >, sql = ('select * > from options%s where ID=%%s', 'Sizes'), id = '0.00' > /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in > execute(self=, query=('select * from > options%s where ID=%%s', 'Sizes'), args=('0.00',)) > 144 db = self._get_db() > 145 charset = db.character_set_name() > 146 query = query.encode(charset) > 147 if args is not None: > 148 query = query % db.literal(args) > query = ('select * from options%s where ID=%%s', 'Sizes'), query.encode > undefined, charset = 'latin1' > > AttributeError: 'tuple' object has no attribute 'encode' > args = ("'tuple' object has no attribute 'encode'",) > > > Please advise. > On line 59 you're making a tuple. From stefan_ml at behnel.de Fri May 28 12:46:54 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 28 May 2010 18:46:54 +0200 Subject: Omit the headers from XML message In-Reply-To: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> References: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Message-ID: kaklis at gmail.com, 28.05.2010 17:24: > Hi i have the following xml message i want to omit the headers, any > hints? > > POST /test/pcp/Listener HTTP/1.1 > User-Agent: Jakarta Commons-HttpClient/3.1 > Host: 127.0.0.1:50002 > Content-Length: 547 > > > > > > scvdcvsdv > sdfv > Antonis Kaklis > away > testing the new client > jlkdjf > android > > > > Use the HTTP server that comes with Python, instead of the plain socket server. Stefan From __peter__ at web.de Fri May 28 12:48:27 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2010 18:48:27 +0200 Subject: Omit the headers from XML message References: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Message-ID: Jon Clements wrote: > On 28 May, 16:24, "kak... at gmail.com" wrote: >> Hi i have the following xml message i want to omit the headers, any >> hints? > Assuming the header is separated by a blank line, something like: > > list(islice(dropwhile(bool, s.split('\n')), 1, None)) Making the same assumptions, but giving a single string instead of a list of lines: s.partition("\n\n")[-1] Peter From rbrt.somerville at gmail.com Fri May 28 12:55:46 2010 From: rbrt.somerville at gmail.com (robert somerville) Date: Fri, 28 May 2010 09:55:46 -0700 Subject: ElementTree write creates large one line XML file .... Message-ID: Thanks Robert Kern : "prettyprint" ; indent() does the trick ;-) >ElementTree writes exactly what you tell it to. In XML, whitespace is >significant. If you want newlines and/or indentation to make it pretty-looking, >then you need to add those to your elements. > >Fredrik provides an example function for doing this: > > http://effbot.org/zone/element-lib.htm#prettyprint -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.rodola at gmail.com Fri May 28 13:08:01 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Fri, 28 May 2010 19:08:01 +0200 Subject: Like __getattr__ but with args and kwargs as well Message-ID: I know, the title doesn't say much, but I had no better ideas. =) I have a class within a serie of redundant methods, which looks like this: class MixedAuthorizer: def __init__(self, *args): # expected a list of class instances self.authorizers = args def get_home(self, user): for auth in self.authorizers: if not auth.has_user(user): continue return auth.get_home(user) return "" def get_password(self, user): for auth in self.authorizers: if not auth.has_user(user): continue return auth.get_password(user) return "" # follows a long list of get_* methods as above ... Considering that I always do the same thing (iterate over a list of objects -> call obj.has_user() -> call obj.get_*()) I would like to know if there's a more compact way to do that. What I basically need is something like __getattr__ but which provides the arguments and eventually the keyword arguments a method has been called with, other than just its name. Actually I'm not even sure whether Python can reach such a level of dynamism but I wanted to give it a try anyway. Is there a way to do such a thing? --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From cjwilliams43 at gmail.com Fri May 28 13:37:14 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Fri, 28 May 2010 13:37:14 -0400 Subject: if, continuation and indentation In-Reply-To: References: Message-ID: On 28-May-10 05:54 AM, Jonathan Hartley wrote: > On May 27, 1:57 pm, Jean-Michel Pichavant > wrote: >> HH wrote: >>> I have a question about best practices when it comes to line wrapping/ >>> continuation and indentation, specifically in the case of an if >>> statement. >> >>> When I write an if statement with many conditions, I prefer to use a >>> parenthesis around the whole block and get the implicit continuation, >>> rather than ending each line with an escape character. Thus, using >>> the example from the style guide (http://www.python.org/dev/peps/ >>> pep-0008/) I would write: >> >>> if (width == 0 and >>> height == 0 and >>> color == 'red' and >>> emphasis == 'strong' or >>> highlight> 100): >>> raise ValueError("sorry, you lose") >> >>> The problem should be obvious -- it's not easy to see where the >>> conditional ends and the statement begins since they have the same >>> indentation. Part of the problem, I suppose, is that Emacs indents >>> 'height' and the other lines in the conditional to 4 spaces (because >>> of the parenthesis). How do people deal with this situation? >> >>> Thanks, >>> Henrik >> >> One possible solution >> >> if ( >> width == 0 and >> height == 0 and >> color == 'red' and >> emphasis == 'strong' or >> highlight> 100 >> ): >> raise ValueError("sorry, you lose") >> >> JM > > I've always liked this, or even: > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100 > ): > raise ValueError("sorry, you lose") > > > but my co-workers have uniformly gone bananas whenever I try it. I liked: On 27-May-10 08:48 AM, Xavier Ho wrote: > On 27 May 2010 22:22, HH > wrote: > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight > 100): > raise ValueError("sorry, you lose") > > > I've gotta say - I've bumped into this problem before, and I'm sure many > other have - this is a valid question. It just hasn't bothered me enough > to ask... > > Correct me if I'm wrong, but I think the following is equivalent, and > looks better. Although this won't fix all ugly cases in that problem.. > > if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or > highlight > 100: > raise ValueError("sorry, you lose") > > Cheers, > Xav but nobody commented. Colin W. From miki.tebeka at gmail.com Fri May 28 13:39:51 2010 From: miki.tebeka at gmail.com (Miki) Date: Fri, 28 May 2010 10:39:51 -0700 (PDT) Subject: Like __getattr__ but with args and kwargs as well References: Message-ID: <1f67b366-9a2a-41b8-9cad-6f4dcc4b2b21@s1g2000prf.googlegroups.com> class MixedAuthorizer: def __init__(self, *args): # expected a list of class instances self.authorizers = args self._set_methods() def _set_methods(self): for attr in ("home", "password"): def fn(user): return self._get_attr(user, attr) setattr(self, "get_%s" % attr, fn) def _get_attr(self, user, attr): auths = [auth for auth in self.authorizers if auth.has_user(user)] if not auths: return "" method_name = "get_%s" % attr method = getattr(auths[0], method_name, None) if not fn: raise ValueError("Unknown attribute - %s" % method_name) return fn(user) HTH, -- Miki http://pythonwise.blogspot.com From miki.tebeka at gmail.com Fri May 28 13:41:31 2010 From: miki.tebeka at gmail.com (Miki) Date: Fri, 28 May 2010 10:41:31 -0700 (PDT) Subject: Like __getattr__ but with args and kwargs as well References: <1f67b366-9a2a-41b8-9cad-6f4dcc4b2b21@s1g2000prf.googlegroups.com> Message-ID: <4ab734a2-c522-4a0e-b2e2-00e8f403ae65@p5g2000pri.googlegroups.com> > ? ? ? ? method = getattr(auths[0], method_name, None) Should be fn = getattr(auths[0], method_name, None) From clp2 at rebertia.com Fri May 28 13:43:33 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 28 May 2010 10:43:33 -0700 Subject: Like __getattr__ but with args and kwargs as well In-Reply-To: References: Message-ID: On Fri, May 28, 2010 at 10:08 AM, Giampaolo Rodol? wrote: > I know, the title doesn't say much, but I had no better ideas. =) > I have a class within a serie of redundant methods, which looks like this: > > class MixedAuthorizer: > > ? ?def __init__(self, *args): > ? ? ? ?# expected a list of class instances > ? ? ? ?self.authorizers = args > > ? ?def get_home(self, user): > ? ? ? ?for auth in self.authorizers: > ? ? ? ? ? ?if not auth.has_user(user): > ? ? ? ? ? ? ? ?continue > ? ? ? ? ? ?return auth.get_home(user) > ? ? ? ?return "" > > ? ?def get_password(self, user): > ? ? ? ?for auth in self.authorizers: > ? ? ? ? ? ?if not auth.has_user(user): > ? ? ? ? ? ? ? ?continue > ? ? ? ? ? ?return auth.get_password(user) > ? ? ? ?return "" > > ? ? # follows a long list of get_* methods as above > ? ? ... > > > Considering that I always do the same thing (iterate over a list of > objects -> call obj.has_user() -> call obj.get_*()) I would like to > know if there's a more compact way to do that. > What I basically need is something like __getattr__ but which provides > the arguments and eventually the keyword arguments a method has been > called with, other than just its name. > Actually I'm not even sure whether Python can reach such a level of > dynamism but I wanted to give it a try anyway. > Is there a way to do such a thing? There's no such "?ber-__getattr__", but with some indirection we can achieve much the same effect: #Note: Completely untested from functools import partial class Whatever(object): def _getter(self, _name, user, *args, **kwds): # I assume your actual code will use the *args and **kwds for auth in self.authorizers: if not auth.has_user(user): continue return getattr(auth, _name)(user) return "" def __getattr__(self, name): if name.startswith("get_"): return partial(self._getter, _name=name) else: raise AttributeError Cheers, Chris -- http://blog.rebertia.com From __peter__ at web.de Fri May 28 13:52:08 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2010 19:52:08 +0200 Subject: Like __getattr__ but with args and kwargs as well References: Message-ID: Giampaolo Rodol? wrote: > I know, the title doesn't say much, but I had no better ideas. =) > I have a class within a serie of redundant methods, which looks like this: > > class MixedAuthorizer: > > def __init__(self, *args): > # expected a list of class instances > self.authorizers = args > > def get_home(self, user): > for auth in self.authorizers: > if not auth.has_user(user): > continue > return auth.get_home(user) > return "" > > def get_password(self, user): > for auth in self.authorizers: > if not auth.has_user(user): > continue > return auth.get_password(user) > return "" > > # follows a long list of get_* methods as above > ... > > > Considering that I always do the same thing (iterate over a list of > objects -> call obj.has_user() -> call obj.get_*()) I would like to > know if there's a more compact way to do that. > What I basically need is something like __getattr__ but which provides > the arguments and eventually the keyword arguments a method has been > called with, other than just its name. > Actually I'm not even sure whether Python can reach such a level of > dynamism but I wanted to give it a try anyway. > Is there a way to do such a thing? Yes, and for the above example it is easier to implement than you think: class MA(object): def __init__(self, authorizers): self.authorizers = authorizers def __getattr__(self, name): def get(self, user): for auth in self.authorizers: if auth.has_user(user): return getattr(auth, name)(user) return get.__get__(self) You can modify it to pass along arbitrary keyword arguments: class MA(object): def __init__(self, authorizers): self.authorizers = authorizers def __getattr__(self, name): def get(self, **kw): for auth in self.authorizers: if auth.has_user(kw["user"]): return getattr(auth, name)(**kw) return get.__get__(self) Peter From g.rodola at gmail.com Fri May 28 14:29:51 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Fri, 28 May 2010 20:29:51 +0200 Subject: Like __getattr__ but with args and kwargs as well In-Reply-To: References: Message-ID: 2010/5/28 Peter Otten <__peter__ at web.de>: > Giampaolo Rodol? wrote: > >> I know, the title doesn't say much, but I had no better ideas. =) >> I have a class within a serie of redundant methods, which looks like this: >> >> class MixedAuthorizer: >> >> ? ? def __init__(self, *args): >> ? ? ? ? # expected a list of class instances >> ? ? ? ? self.authorizers = args >> >> ? ? def get_home(self, user): >> ? ? ? ? for auth in self.authorizers: >> ? ? ? ? ? ? if not auth.has_user(user): >> ? ? ? ? ? ? ? ? continue >> ? ? ? ? ? ? return auth.get_home(user) >> ? ? ? ? return "" >> >> ? ? def get_password(self, user): >> ? ? ? ? for auth in self.authorizers: >> ? ? ? ? ? ? if not auth.has_user(user): >> ? ? ? ? ? ? ? ? continue >> ? ? ? ? ? ? return auth.get_password(user) >> ? ? ? ? return "" >> >> ? ? ?# follows a long list of get_* methods as above >> ? ? ?... >> >> >> Considering that I always do the same thing (iterate over a list of >> objects -> call obj.has_user() -> call obj.get_*()) I would like to >> know if there's a more compact way to do that. >> What I basically need is something like __getattr__ but which provides >> the arguments and eventually the keyword arguments a method has been >> called with, other than just its name. >> Actually I'm not even sure whether Python can reach such a level of >> dynamism but I wanted to give it a try anyway. >> Is there a way to do such a thing? > > Yes, and for the above example it is easier to implement than you think: > > class MA(object): > ? ?def __init__(self, authorizers): > ? ? ? ?self.authorizers = authorizers > ? ?def __getattr__(self, name): > ? ? ? ?def get(self, user): > ? ? ? ? ? ?for auth in self.authorizers: > ? ? ? ? ? ? ? ?if auth.has_user(user): > ? ? ? ? ? ? ? ? ? ?return getattr(auth, name)(user) > ? ? ? ?return get.__get__(self) > > You can modify it to pass along arbitrary keyword arguments: > > class MA(object): > ? ?def __init__(self, authorizers): > ? ? ? ?self.authorizers = authorizers > ? ?def __getattr__(self, name): > ? ? ? ?def get(self, **kw): > ? ? ? ? ? ?for auth in self.authorizers: > ? ? ? ? ? ? ? ?if auth.has_user(kw["user"]): > ? ? ? ? ? ? ? ? ? ?return getattr(auth, name)(**kw) > ? ? ? ?return get.__get__(self) > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks, this has been helpful. I managed to write this monster: =) class MixedAuthorizer(object): def __init__(self, *authorizers): self.authorizers = authorizers def __getattr__(self, name): def get(self, user, *args, **kwargs): for auth in self.authorizers: if auth.has_user(user): method = getattr(auth, name) return method(user, *args, **kwargs) # if we reached this point no user was found if name == "validate_authentication": return False if name.startswith("get"): return "" if name.startswith("has"): return False return get.__get__(self) --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil From python at mrabarnett.plus.com Fri May 28 14:42:45 2010 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 May 2010 19:42:45 +0100 Subject: Like __getattr__ but with args and kwargs as well In-Reply-To: References: Message-ID: <4C000EA5.2000200@mrabarnett.plus.com> Giampaolo Rodol? wrote: > I know, the title doesn't say much, but I had no better ideas. =) > I have a class within a serie of redundant methods, which looks like this: > > class MixedAuthorizer: > > def __init__(self, *args): > # expected a list of class instances > self.authorizers = args > > def get_home(self, user): > for auth in self.authorizers: > if not auth.has_user(user): > continue > return auth.get_home(user) > return "" > > def get_password(self, user): > for auth in self.authorizers: > if not auth.has_user(user): > continue > return auth.get_password(user) > return "" > > # follows a long list of get_* methods as above > ... > > > Considering that I always do the same thing (iterate over a list of > objects -> call obj.has_user() -> call obj.get_*()) I would like to > know if there's a more compact way to do that. > What I basically need is something like __getattr__ but which provides > the arguments and eventually the keyword arguments a method has been > called with, other than just its name. > Actually I'm not even sure whether Python can reach such a level of > dynamism but I wanted to give it a try anyway. > Is there a way to do such a thing? > Here's a way (mis)using a decorator (written in Python 3): def locate(func): def lookup(self, user): for auth in self.authorizers: if auth.has_user(user): return getattr(auth, func.__name__)() return "" return lookup class Authorizer: def __init__(self, user): self.user = user def has_user(self, user): return self.user == user def get_home(self): return "{}-HOME".format(self.user) def get_password(self): return "{}-PASSWORD".format(self.user) class MixedAuthorizer: def __init__(self, *authorizers): self.authorizers = authorizers # The following methods are used only as placeholders. @locate def get_home(self): pass @locate def get_password(self): pass a1 = Authorizer("USER1") a2 = Authorizer("USER2") m = MixedAuthorizer(a1, a2) print(m.get_home("USER1")) print(m.get_password("USER2")) From kaklis at gmail.com Fri May 28 14:58:15 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Fri, 28 May 2010 11:58:15 -0700 (PDT) Subject: Omit the headers from XML message References: <96132cef-2ad7-46d9-a724-b3c4d316bc95@y21g2000vba.googlegroups.com> Message-ID: On May 28, 7:48?pm, Peter Otten <__pete... at web.de> wrote: > Jon Clements wrote: > > On 28 May, 16:24, "kak... at gmail.com" wrote: > >> Hi i have the following xml message i want to omit the headers, any > >> hints? > > Assuming the header is separated by a blank line, something like: > > > list(islice(dropwhile(bool, s.split('\n')), 1, None)) > > Making the same assumptions, but giving a single string instead of a list of > lines: > > s.partition("\n\n")[-1] > > Peter Thank you all for your responses! Antonis From dickinsm at gmail.com Fri May 28 16:44:43 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 28 May 2010 13:44:43 -0700 (PDT) Subject: A Friday Python Programming Pearl: random sampling Message-ID: For a lazy Friday evening, here's a Python algorithm that seemed so cute that I just had to share it with everyone. I'm sure it's well known to many here, but it was new to me. Skip directly to the 'sample2' function to see the algorithm and avoid the commentary... Suppose that you want to select a number of elements, k, say, from a population, without replacement. E.g., selecting 3 elements from range(30) might give you: [13, 3, 27] Order matters, so the above is considered distinct from [3, 13, 27]. And you want to be sure that each possible selection has equal probability of occurring (to within the limits of the underlying PRNG). One solution is to select elements from the population one-by-one, keep track of the indices of already-selected elements in a set, and if you end up selecting something that's already in your set, simply try again. Something like this (code stolen and adapted from Random.sample in Python's standard library 'random' module): from random import randrange def sample1(population, k): n = len(population) result = [None] * k selected = set() for i in range(k): j = randrange(n) # retry until we get something that's not already selected while j in selected: j = randrange(n) selected.add(j) result[i] = population[j] return result N.B. The above is Python 3 code; for Python 2, replace range with xrange. All that's required of 'population' here is that it implements __len__ and __getitem__. The method works well for k significantly smaller than n, but as k approaches n the number of reselections required increases. So for larger k, Random.sample uses a different method: roughly, make a copy of 'population', do a partial in-place shuffle of that copy that randomizes the first k elements, and return those. This second method isn't so great when k is small and n is huge, since it ends up being O(n) from the list copy, but it works out that the two methods complement each other nicely. Looking at the above code, I was idly wondering whether there was a way to alter 'sample1' to avoid the need for resampling, thus giving a single algorithm that works reasonably efficiently regardless of the population size and requested sample size. And it turns out that there is. The code below is similar to 'sample1' above, except that instead of using a set to keep track of indices of already-selected members of the population, it uses a dict; for an index i (corresponding to a member of the population), d[i] gives the position that population[i] will occupy in the resulting sample. from random import randrange def sample2(population, k): n = len(population) d = {} for i in reversed(range(k)): j = randrange(i, n) if j in d: d[i] = d[j] d[j] = i result = [None] * k for j, i in d.items(): result[i] = population[j] return result Note that no resampling is required, and that there's no copying of the population list. The really clever bit is the 'if j in d: ...' block. If you stare at the algorithm for long enough (and it does take some staring), you can convince yourself that after the first 'for' loop, d can be any of the n*(n-1)*...*(n-k+1) mappings-with-no-repeated-elements from some set of k elements of range(n) to range(k), and that each one of these mappings is equally likely to occur. In a sense, this d is the inverse of the desired sample, which would be a map with no repetitions from range(k) to range(n). So inverting d, and replacing d's keys by the corresponding population elements, gives the random sample. N.B. I don't claim any originality for the algorithm; only for the implementation: the algorithm is based on an algorithm attributed to Robert Floyd, and appearing in Jon Bentley's 'Programming Pearls' book (though that algorithm produces a set, so doesn't worry about the ordering of the sample). But I was struck by its beauty and simplicity, and thought it deserved to be better known. Happy Friday! -- Mark From awilliam at whitemice.org Fri May 28 16:44:53 2010 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Fri, 28 May 2010 16:44:53 -0400 Subject: multiprocessing and accessing server's stdout In-Reply-To: References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: <1275079493.7612.6.camel@linux-yu4c.site> On Fri, 2010-05-28 at 15:41 +0100, Martin P. Hellwig wrote: > On 05/28/10 13:17, Adam Tauno Williams wrote: > > > You should be able to point it any any file-like object. But, again, > > why? > > If you have the data in the process why send it to stdout and redirect > > it. Why not just send the data to the client directly? > Well you might want to multiplex it to more then one client, not saying > that this is the case here, just something I imagine possible. That still doesn't make sense. Why 'multiplex stdout'? Why not just multiplex the data into proper IPC channels in the first place? -- Adam Tauno Williams LPIC-1, Novell CLA OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba From jessemcdonnell at verizon.net Fri May 28 17:02:04 2010 From: jessemcdonnell at verizon.net (Jesse McDonnell) Date: Fri, 28 May 2010 17:02:04 -0400 Subject: TypeError: _new_() takes exactly 3 arguments (2 given) - what does it mean? In-Reply-To: References: <2061601704.535865.1274727159418.JavaMail.root@vms244.mailsrvcs.net> Message-ID: <20100528170204.4da8292e.jessemcdonnell@verizon.net> On Wed, 26 May 2010 14:30:21 -0400 Terry Reedy wrote: > On 5/24/2010 2:52 PM, Jesse McDonnell wrote: > > I'm attempting to install Powerline http://code.google.com/p/powerline/, > > a computer reservation software based on CherryPy/Python using a MYSql > > database, at my local library and I've run up against an error that I > > > > Honestly, unless you find a Python+Powerline expert who will help, I > suggest that you delete Powerline and look for something else. The most > recent release is an alpha release over 2 years old. Except for the Feb > 2010 wiki updates, the project appears to be dead. Even if someone > helped you past this, there is no evidence that the fix would applied > back to the codebase. And what about the next bug or problem? > Terry Jan Reedy > and On Wed, 26 May 2010 12:04:53 -0700 (PDT) Carl Banks wrote: > [Again, can't see the original, sorry] > > On May 26, 11:30?am, Terry Reedy wrote: > > On 5/24/2010 2:52 PM, Jesse McDonnell wrote: > > The most common reason for this message is trying to subclass a > module. (Very easy mistake when a module has the same name as a > class, which is part of why I don't like the practice, though the > modern PEP 8 reduces the issue.) > > IOW, someone did something like this: > > import foo > class bar(foo): pass > > when they should have done this: > > from foo import foo > class bar(foo): pass > Terry and Carl, Thanks for your replies. I got a response from the guy who coded Powerline through the google group for the app and upgrading dbwrap resolved this particular error. He also helped me work through some python-genshi issues and I now have a working web interface. Thanks again for your help. Jesse From martin.hellwig at dcuktec.org Fri May 28 19:47:18 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 29 May 2010 00:47:18 +0100 Subject: multiprocessing and accessing server's stdout In-Reply-To: References: <0c6dd70f-ec1b-4fe7-9e1d-82dbeab2f390@z33g2000vbb.googlegroups.com> Message-ID: On 05/28/10 21:44, Adam Tauno Williams wrote: > On Fri, 2010-05-28 at 15:41 +0100, Martin P. Hellwig wrote: >> On 05/28/10 13:17, Adam Tauno Williams wrote: >> >>> You should be able to point it any any file-like object. But, again, >>> why? >>> If you have the data in the process why send it to stdout and redirect >>> it. Why not just send the data to the client directly? >> Well you might want to multiplex it to more then one client, not saying >> that this is the case here, just something I imagine possible. > > That still doesn't make sense. Why 'multiplex stdout'? Why not just > multiplex the data into proper IPC channels in the first place? I am going on a stretch here, I mostly agree with you, just trying to illustrate that there could be corner cases where this is sensible. The current situation could be that there is a client/server program (binary only perhaps) which is not multi-user safe. Python can be used as a wrapper around the server to make it multi-client, by emulating the exact behavior towards the client, the client program does not have to be changed. -- mph From lie.1296 at gmail.com Fri May 28 20:23:41 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 29 May 2010 10:23:41 +1000 Subject: function that counts... In-Reply-To: <498a76fd-4e4b-4d09-86c3-16800a4e3d87@s4g2000prh.googlegroups.com> References: <4bf442cd$0$31377$4fafbaef@reader1.news.tin.it> <4bfae2cb$0$18996$4fafbaef@reader5.news.tin.it> <498a76fd-4e4b-4d09-86c3-16800a4e3d87@s4g2000prh.googlegroups.com> Message-ID: <4c005ef6$1@dnews.tpgi.com.au> On 05/26/10 11:04, Bryan wrote: > Jean-Michel Pichavant wrote: >> I still don't see "how many positive integers less than n have digits >> that sum up to m" makes it a "partition" though if that what prttn >> means. Surely because I miss the context. > > A partition of a positive integer m is an unordered collection of > positive integers that sum to m. [1, 1, 2, 5] is a partition of 9. The > problem at issue here is not that of counting partitions. > > My algorithm for our prttn separated out the 'ndsums' sub-problem: > Count d-digit ints with digits summing to m. I found a generalization > of that problem stated in the /CRC Handbook of Discrete and > Combinatorial Mathematics/ (2000 edition, section 2.1) among "counting > problems" as: > > Solutions to x_1 + ... x_n = k > 0 <= x_i <= a_i for one or more i > > Alas, the handbook does not provide a formula or algorithm. It refers > to the inclusion/exclusion principle, which I did not see how to turn > into an efficient algorithm. superpollo posted this question in comp.programming (http://groups.google.com/group/comp.programming/browse_thread/thread/e3b10346db8ebd0a/579ca67f8b9b5a8c; http://groups.google.com/group/comp.programming/msg/f7323d6e6942e883; http://groups.google.com/group/comp.programming/browse_thread/thread/e3b10346db8ebd0a/dc4cd1e2feb89500 ) I went through the mathematical foundation of using partition/distribution and inclusion-exclusion, and have written some code that solves a subset of the problem, feel free if you or superpollo are interested in continuing my answer (I won't be able to continue it until next week, have been a little bit busy here) copying the code here for convenience: # memoization would be very useful here def fact(n): """ factorial function (i.e. n! = n * (n-1) * ... * 2 * 1) """ return n * fact(n - 1) if n != 0 else 1 def C(n, r): """ regular Combination (nCr) """ return fact(n) / (fact(n - r) * fact(r)) def D(M, N): """ Distribution aka Partitioning """ return C(M + N - 1, M) def partition10(M, i): """ Count how many integer < N sums to M where N = 10**int(i) """ s = 0 sign = 1 for j in range(i + 1): s += sign * D(M, i) * C(i, j) # flip the sign for inclusion-exclusion sign *= -1 # if M = 32, then 32, 22, 12, 2, -8 M -= 10 return s # still need to write: # def partitionN10(...): -- applies a "restriction"/"boundary" to # the most significant digit # then make it recurse. # assuming factorials calculation is constant time (hint: memoization) # the resulting code should work in O(n**2) # an improvement over the naive method which is O(10**n) # where n is the number of digits in N # DISCLAIMER: the big-O is a quick guess, not really calculated From john at castleamber.com Fri May 28 22:05:42 2010 From: john at castleamber.com (John Bokma) Date: Fri, 28 May 2010 21:05:42 -0500 Subject: Free chapter about Python and databases (MySQL and SQLite) References: <87vda8ofvz.fsf@castleamber.com> Message-ID: <87hblrv4w9.fsf@castleamber.com> Sebastian Bassi writes: > On Fri, May 28, 2010 at 12:37 AM, John Bokma wrote: >> I feel more than uncomfortable with example code that uses: user="root" > > What's wrong with this? It is just an example of connection string. > The reader will use his/her user/pass/dbname according to their own > settings. A bit down you're contradicting yourself: your audience is not familiar with databases, yet you assume that they will use their own settings? >> (e.g. p291). I never get why people write a short (IMO) /bad/ intro to >> databases while there are books out there that do a way better > > The intended audience of this book are biologist who may be not > familiarized with relational databases. Most of my colleagues (at > least from the bio camp) don't even know that behind most dynamic web > pages there are databases and I think that most of them will find the > intro section useful. You can always skip what you know and go to the > point you want. My point is that the intro I (speed) read is weak at best. You say you're doing your audience a favor, but I don't agree. > I am not sure that price in this kind of book are tied to the number > of pages. There must be some relation, but this is not the main factor > affecting price. Even if it's just a few bucks, it's still money saved [0]. On top of that I think it's way better to point your audience to good books on the topic and skip the intro instead of doing a (half hearted IMO) attempt at it yourself. >> I would love to see more technical books that start at page 1 with the >> topic, not with an introduction to the language (170+ pages) and some > ... > > I see where you go, it seems you are not the target audience for this > book. Anyway I appreciate your feedback. You're welcome. And to be honest, if the book didn't have those filler chapters (which they are IMO) I would certainly have been interested in it. Note that I am not trying to convince you to rewrite your book, but my bookcase could have 20% more room if technical writers stopped to write books that tried to introduce their audience to everything but the kitchen sink [1]. My favourite books are the ones that /don't/ do the everything but the kitchensink gig, but direct me to other high quality books. [0] I've been a technical editor for a book, and got paid by the page. [1] I mean the books that seem to handle a single specific topic. If I buy "Ubuntu up and running" I expect everything, including the kitchensink. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From drobinow at gmail.com Fri May 28 23:41:31 2010 From: drobinow at gmail.com (Robinow) Date: Fri, 28 May 2010 23:41:31 -0400 Subject: Free chapter about Python and databases (MySQL and SQLite) In-Reply-To: <87hblrv4w9.fsf@castleamber.com> References: <87vda8ofvz.fsf@castleamber.com> <87hblrv4w9.fsf@castleamber.com> Message-ID: <34894370-9E3B-4C21-80DE-A6FF26A7B669@gmail.com> wrote: > Sebastian Bassi writes: > >> On Fri, May 28, 2010 at 12:37 AM, John Bokma >> wrote: > > Even if it's just a few bucks, it's still money saved [0]. On top of > that I think it's way better to point your audience to good books on > the > topic and skip the intro instead of doing a (half hearted IMO) attempt > at it yourself. >> > OK, John. What book do you recommend? From kse.listed.co1 at gmail.com Sat May 29 01:42:03 2010 From: kse.listed.co1 at gmail.com (Naeem) Date: Fri, 28 May 2010 22:42:03 -0700 (PDT) Subject: "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ Message-ID: <4d75ce9d-f29d-4bf9-a515-133bf6783098@l6g2000vbo.googlegroups.com> "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ "Neha Dhupia IN WATER" "Neha Dhupia" IN BIKINI " "SEXY "Neha Dhupia SEXY BELLY" "Neha Dhupia IN YELLOW BIKINI" "Neha Dhupia IN WHITE BIKINI" "Neha Dhupia" AS MISS WORLD" "BOLLYWOOD BIKINI" on http://hollywood-bollywood-pics.blogspot.com/ From contact at xavierho.com Sat May 29 05:33:56 2010 From: contact at xavierho.com (Xavier Ho) Date: Sat, 29 May 2010 19:33:56 +1000 Subject: A Friday Python Programming Pearl: random sampling In-Reply-To: References: Message-ID: On 29 May 2010 06:44, Mark Dickinson wrote: > But I was struck by its beauty and > simplicity, and thought it deserved to be better known. > Wow, that took me at least 2 minutes to see its beauty as well. Nice find, Mark. Thanks for sharing. (Also, it's nice to see another SOer on Python-List as well!) Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From googler.1.webmaster at spamgourmet.com Sat May 29 08:34:56 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Sat, 29 May 2010 05:34:56 -0700 (PDT) Subject: Py_single_input and the side-effects... Message-ID: Hi at all, I have a small problem with Py_single_input, that I dont really know what it actually does. I created my own interactive interpreter loop and when I create objects like p = TestObject() this instance is just deleted on Py_Finalize() even I delete the entire console scope long time before. It seems that Py_single_input stores the references somewhere else. Could anyone explain me a little bit what is actually going on here? Thanks a lot! Cheers, moerchendiser2k3 From pradeepbpin at gmail.com Sat May 29 09:09:35 2010 From: pradeepbpin at gmail.com (Pradeep B) Date: Sat, 29 May 2010 18:39:35 +0530 Subject: Python and Tkinter Programming by John Grayson In-Reply-To: <4B58FCDF.4000402@stoneleaf.us> References: <0738732e-d8df-469d-be4a-3699f4fd5f64@j14g2000yqm.googlegroups.com> <801d251d-ae12-4ce6-95a1-58f594cd2f81@p8g2000yqb.googlegroups.com> <4B4F96D6.2070905@codebykevin.com> <326dc723-3909-4293-9bf6-48a367b9251c@e16g2000yqc.googlegroups.com> <4B58FCDF.4000402@stoneleaf.us> Message-ID: On Fri, Jan 22, 2010 at 6:48 AM, Ethan Furman wrote: > Peter wrote: >> >> On Jan 15, 9:12 am, Kevin Walzer wrote: >>>> >>>> On Jan 15, 6:24 am, Mark Roseman ?wrote: >>>>> >>>>> ?Peter ?wrote: >>>>>> >>>>>> Besides, the book is mainly about using Python with Tkinter - and >>>>>> Tkinter hasn't changed that much since 2000, so I believe it is just >>>>>> as relevant today as it was back then. > >>>>> I'd say that Tkinter has substantially changed - with the introduction >>>>> of the 'ttk' themed widgets. ?I cover these in my tutorial >>>>> athttp://www.tkdocs.com > >>> Another book I've found very helpful for learning Tkinter is Programming >>> Python by Mark Lutz--a lot of coverage there of GUI development. >>> >> >> Another possible consideration when choosing a GUI to learn Python - >> will you want to print from within your GUI application? > > Excellent point. > > Many thanks to all who responded, especially for the reminder of the gui > sections in Programming Python (forgot I had that book!). ?I'll start by > going over that again, and we'll see how confident I feel afterwards. ?;) > > ~Ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > Is printing from GUI still a 'not-happening' thing with Tkinter ? I have just started learning it. -- |_|0|_| |_|_|0| |0|0|0| http://picasaweb.google.com/pradeepbpin From pradeepbpin at gmail.com Sat May 29 09:11:24 2010 From: pradeepbpin at gmail.com (Pradeep B) Date: Sat, 29 May 2010 18:41:24 +0530 Subject: Tkinter library reference Message-ID: Do we have a standard reference library for Tkinter available? -- Pradeep From astley.lejasper at gmail.com Sat May 29 09:24:49 2010 From: astley.lejasper at gmail.com (Astley Le Jasper) Date: Sat, 29 May 2010 06:24:49 -0700 (PDT) Subject: Creating a single list Message-ID: This is probably a really silly question but, given the example code at the bottom, how would I get a single list? What I currently get is: ('id', 20, 'integer') ('companyname', 50, 'text') [('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, 'text'), ('puma', 30, 'text')] ('contact', 50, 'text') ('email', 50, 'text') what I would like is: ('id', 20, 'integer') ('companyname', 50, 'text') ('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, 'text'), ('puma', 30, 'text'), ('contact', 50, 'text') ('email', 50, 'text') SAMPLE CODE>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> def getproducts(): temp_list=[] product_list=['focus','fiesta','mondeo','puma'] #usually this would come from a db for p in product_list: temp_list.append((p,30,'text')) return temp_list def createlist(): column_title_list = ( ("id",20,"integer"), ("companyname",50,"text"), getproducts(), ("contact",50,"text"), ("email",50,"text"), ) return column_title_list for item in createlist(): print item >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> From contact at xavierho.com Sat May 29 09:40:48 2010 From: contact at xavierho.com (Xavier Ho) Date: Sat, 29 May 2010 23:40:48 +1000 Subject: Creating a single list In-Reply-To: References: Message-ID: On 29 May 2010 23:24, Astley Le Jasper wrote: > def createlist(): > column_title_list = ( > ("id",20,"integer"), > ("companyname",50,"text"), > getproducts(), > ("contact",50,"text"), > ("email",50,"text"), > ) > return column_title_list > Note that you're creating a Tuple, not a List. They're not the same thing. Try this: column_title_list = [ ("id",20,"integer"), ("companyname",50,"text"), ("contact",50,"text"), ("email",50,"text"), ] # Insert into the list with slicing syntax. column_title_list[2:3} = getproduct() This will not work with tuples, as they are immutable. Lists are. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Sat May 29 09:41:29 2010 From: contact at xavierho.com (Xavier Ho) Date: Sat, 29 May 2010 23:41:29 +1000 Subject: Creating a single list In-Reply-To: References: Message-ID: > # Insert into the list with slicing syntax. > column_title_list[2:3} = getproduct() > Sorry, that should have been [2:3]. Typing a bit too fast. -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From kw at codebykevin.com Sat May 29 10:03:28 2010 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 29 May 2010 10:03:28 -0400 Subject: Python and Tkinter Programming by John Grayson In-Reply-To: References: <0738732e-d8df-469d-be4a-3699f4fd5f64@j14g2000yqm.googlegroups.com> <801d251d-ae12-4ce6-95a1-58f594cd2f81@p8g2000yqb.googlegroups.com> <4B4F96D6.2070905@codebykevin.com> <326dc723-3909-4293-9bf6-48a367b9251c@e16g2000yqc.googlegroups.com> <4B58FCDF.4000402@stoneleaf.us> Message-ID: <81dfc$4c011eaa$4275d90a$28590@FUSE.NET> > Is printing from GUI still a 'not-happening' thing with Tkinter ? I > have just started learning it. Tkinter doesn't wrap native printing API's. There are a few extensions that do it, but they are platform specific and not complete. The usual ways of printing are like this: 1. If you're outputting data from the text widget, write that to a temporary text file and print via lpr. 2. If you're outputting data from the canvas, write that to a temporary postscript file and print via lpr. This is on Unix/MacOS. Not sure what the equivalent API on Windows is. --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From utente at esempio.net Sat May 29 10:10:41 2010 From: utente at esempio.net (superpollo) Date: Sat, 29 May 2010 16:10:41 +0200 Subject: Creating a single list In-Reply-To: References: Message-ID: <4c012062$0$18987$4fafbaef@reader5.news.tin.it> Astley Le Jasper ha scritto: > This is probably a really silly question but, given the example code > at the bottom, how would I get a single list? > > What I currently get is: > > ('id', 20, 'integer') > ('companyname', 50, 'text') > [('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, > 'text'), ('puma', 30, 'text')] > ('contact', 50, 'text') > ('email', 50, 'text') > > what I would like is: > > ('id', 20, 'integer') > ('companyname', 50, 'text') > ('focus', 30, 'text'), > ('fiesta', 30, 'text'), > ('mondeo', 30, 'text'), > ('puma', 30, 'text'), > ('contact', 50, 'text') > ('email', 50, 'text') > > SAMPLE CODE>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > def getproducts(): > temp_list=[] > product_list=['focus','fiesta','mondeo','puma'] #usually this > would come from a db > for p in product_list: > temp_list.append((p,30,'text')) > return temp_list > > def createlist(): > column_title_list = ( > ("id",20,"integer"), > ("companyname",50,"text"), > getproducts(), > ("contact",50,"text"), > ("email",50,"text"), > ) > return column_title_list > > for item in createlist(): > print item >>> def createlist(): ... column_title_list = [ ... ("id",20,"integer"), ... ("companyname",50,"text")] ... column_title_list += getproducts() ... column_title_list += [ ... ("contact",50,"text"), ... ("email",50,"text")] ... return column_title_list ... >>> for item in createlist(): ... print item ... ('id', 20, 'integer') ('companyname', 50, 'text') ('focus', 30, 'text') ('fiesta', 30, 'text') ('mondeo', 30, 'text') ('puma', 30, 'text') ('contact', 50, 'text') ('email', 50, 'text') >>> bye From bryanjugglercryptographer at yahoo.com Sat May 29 10:43:43 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sat, 29 May 2010 07:43:43 -0700 (PDT) Subject: A Friday Python Programming Pearl: random sampling References: Message-ID: Mark Dickinson wrote: > N.B. ?I don't claim any originality for the algorithm; only for the > implementation: the algorithm is based on an algorithm attributed to > Robert Floyd, and appearing in Jon Bentley's 'Programming Pearls' book Actually it is the sequel, /More Programming Pearls/. > (though that algorithm produces a set, so doesn't worry about the > ordering of the sample). Bentley presents a version of the Floyd algorithm that provides random order, but it requires a set data type with some idea of order, as in "insert j in s after t". As Mark Dickinson's version uses a normal dict(), which Bentley had already introduced under the name "associate array", I'd say Mark's version is an improvement. -- --Bryan From andrew at acooke.org Sat May 29 11:04:51 2010 From: andrew at acooke.org (andrew cooke) Date: Sat, 29 May 2010 08:04:51 -0700 (PDT) Subject: Help with Regexp, \b Message-ID: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> This is a bit embarassing, but I seem to be misunderstanding how \b works in regexps. Please can someone explain why the following fails: from re import compile p = compile(r'\bword\b') m = p.match(' word ') assert m My understanding is that \b matches a space at the start or end of a word, and that "word" is a word - http://docs.python.org/library/re.html What am I missing here? I suspect I am doing something very stupid. Thanks, Andrew From anand.shashwat at gmail.com Sat May 29 11:14:33 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sat, 29 May 2010 20:44:33 +0530 Subject: Help with Regexp, \b In-Reply-To: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> References: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> Message-ID: \b is NOT spaces >>> p = re.compile(r'\sword\s') >>> m = p.match(' word ') >>> assert m >>> m.group(0) ' word ' >>> On Sat, May 29, 2010 at 8:34 PM, andrew cooke wrote: > > This is a bit embarassing, but I seem to be misunderstanding how \b > works in regexps. > > Please can someone explain why the following fails: > > from re import compile > > p = compile(r'\bword\b') > m = p.match(' word ') > assert m > > My understanding is that \b matches a space at the start or end of a > word, and that "word" is a word - http://docs.python.org/library/re.html > > What am I missing here? I suspect I am doing something very stupid. > > Thanks, > Andrew > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Sat May 29 11:24:48 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 May 2010 15:24:48 GMT Subject: Help with Regexp, \b References: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> Message-ID: andrew cooke wrote: > Please can someone explain why the following fails: > > from re import compile > > p = compile(r'\bword\b') > m = p.match(' word ') > assert m > > My understanding is that \b matches a space at the start or end of a > word, and that "word" is a word - http://docs.python.org/library/re.html > > What am I missing here? I suspect I am doing something very stupid. > You misunderstand what \b does: it doesn't match a space, it matches a 0 length string on a boundary between a non-word and a word. Try: p.match(' word ', 1).group(0) and you'll see that you are only match the word, not the surrounding puctuation. From anand.shashwat at gmail.com Sat May 29 11:28:28 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sat, 29 May 2010 20:58:28 +0530 Subject: Help with Regexp, \b In-Reply-To: References: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> Message-ID: Also what you are probably looking for is this I guess, >>> p = re.compile(r'\bword\b') >>> m = p.match('word word') >>> assert m >>> m.group(0) 'word' On Sat, May 29, 2010 at 8:44 PM, Shashwat Anand wrote: > \b is NOT spaces > > >>> p = re.compile(r'\sword\s') > >>> m = p.match(' word ') > >>> assert m > >>> m.group(0) > ' word ' > >>> > > > On Sat, May 29, 2010 at 8:34 PM, andrew cooke wrote: > >> >> This is a bit embarassing, but I seem to be misunderstanding how \b >> works in regexps. >> >> Please can someone explain why the following fails: >> >> from re import compile >> >> p = compile(r'\bword\b') >> m = p.match(' word ') >> assert m >> >> My understanding is that \b matches a space at the start or end of a >> word, and that "word" is a word - http://docs.python.org/library/re.html >> >> What am I missing here? I suspect I am doing something very stupid. >> >> Thanks, >> Andrew >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew at acooke.org Sat May 29 11:30:18 2010 From: andrew at acooke.org (andrew cooke) Date: Sat, 29 May 2010 08:30:18 -0700 (PDT) Subject: Help with Regexp, \b References: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> Message-ID: <4b812698-4779-4502-8cdc-bf5c47dd5a0c@o39g2000vbd.googlegroups.com> On May 29, 11:24?am, Duncan Booth wrote: > andrew cooke wrote: > > Please can someone explain why the following fails: > > > ? ? ? ? from re import compile > > > ? ? ? ? p = compile(r'\bword\b') > > ? ? ? ? m = p.match(' word ') > > ? ? ? ? assert m [...] > You misunderstand what \b does: it doesn't match a space, it matches a 0 > length string on a boundary between a non-word and a word. [...] That's what I thought it did... Then I read the docs and confused "empty string" with "space"(!) and convinced myself otherwise. I think I am going senile. Thanks very much! Andrew From godson.g at gmail.com Sat May 29 11:36:31 2010 From: godson.g at gmail.com (Godson Gera) Date: Sat, 29 May 2010 21:06:31 +0530 Subject: Tkinter library reference In-Reply-To: References: Message-ID: Do you mean Tkinter API reference documentation ? If so, this is what I've used years back http://www.nmt.edu/tcc/help/pubs/tkinter.pdf you can also get some info from http://effbot.org/tkinterbook On Sat, May 29, 2010 at 6:41 PM, Pradeep B wrote: > Do we have a standard reference library for Tkinter available? > > -- > Pradeep > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thanks & Regards, Godson Gera IVR India IVR Vendor India -------------- next part -------------- An HTML attachment was scrubbed... URL: From dickinsm at gmail.com Sat May 29 13:06:19 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 29 May 2010 10:06:19 -0700 (PDT) Subject: A Friday Python Programming Pearl: random sampling References: Message-ID: On May 29, 3:43?pm, Bryan wrote: > Mark Dickinson wrote: > > N.B. ?I don't claim any originality for the algorithm; only for the > > implementation: the algorithm is based on an algorithm attributed to > > Robert Floyd, and appearing in Jon Bentley's 'Programming Pearls' book > > Actually it is the sequel, /More Programming Pearls/. Thanks for the correction. I confess that I've yet to read either book; I'll have to try to track them down. > > (though that algorithm produces a set, so doesn't worry about the > > ordering of the sample). > > Bentley presents a version of the Floyd algorithm that provides random > order, but it requires a set data type with some idea of order, as in > "insert j in s after t". Ah, nice. The dict values, of course, exactly provide the necessary idea of order, so I guess this amounts to pretty much the same thing. -- Mark From nagle at animats.com Sat May 29 14:43:29 2010 From: nagle at animats.com (John Nagle) Date: Sat, 29 May 2010 11:43:29 -0700 Subject: Python vs. Fedora and CentOS Message-ID: <4c015aa9$0$1617$742ec2ed@news.sonic.net> The major Red Hat based Linux distros are still shipping with Python 2.4. As a result, almost all hosting providers are running obsolete versions of Python. The big problem seems to be that "cPanel" and "yum" still use older versions of Python, and those programs are more important to distro builders than Python itself. Is anybody trying to do something about this? John Nagle From breamoreboy at yahoo.co.uk Sat May 29 14:46:28 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 29 May 2010 19:46:28 +0100 Subject: xrange issue 7721 Message-ID: Sorry if this is the wrong ng/ml, but thought I'd better flag this up somewhere. I've had an OverflowError using xrange with Python 2.6.5 on Windows. Googling got me to the subject line. msg97928 gives a code snippet to overcome the limitations of xrange, allowing for negative steps, however it doesn't raise a ValueError for a zero step. msg99624 gives a docs change that has been implemented for V2.6, but this doesn't refer to the msg97928 code snippet, rather it refers to a one liner that only works for positive steps. The docs for V2.7 haven't been changed at all. Assuming that I am correct, can I create myself a login on the bugs tracker and re-open the issue to get this sorted? Kindest regards. Mark Lawrence. From no.email at nospam.invalid Sat May 29 14:58:31 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 29 May 2010 11:58:31 -0700 Subject: Python vs. Fedora and CentOS References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> Message-ID: <7xaaripmaw.fsf@ruckus.brouhaha.com> John Nagle writes: > The major Red Hat based Linux distros are still shipping with Python 2.4. Fedora 12 ships with Python 2.6, I think. From wesbrooks at gmail.com Sat May 29 15:03:54 2010 From: wesbrooks at gmail.com (Wesley Brooks) Date: Sat, 29 May 2010 20:03:54 +0100 Subject: Python vs. Fedora and CentOS In-Reply-To: <7xaaripmaw.fsf@ruckus.brouhaha.com> References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <7xaaripmaw.fsf@ruckus.brouhaha.com> Message-ID: I've got Fedora 10 here with 2.5, and 11 at the office with 2.6. On 29 May 2010 19:58, Paul Rubin wrote: > John Nagle writes: >> ? The major Red Hat based Linux distros are still shipping with Python 2.4. > > Fedora 12 ships with Python 2.6, I think. > -- > http://mail.python.org/mailman/listinfo/python-list > From philip at semanchuk.com Sat May 29 15:09:57 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Sat, 29 May 2010 15:09:57 -0400 Subject: Python vs. Fedora and CentOS In-Reply-To: <7xaaripmaw.fsf@ruckus.brouhaha.com> References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <7xaaripmaw.fsf@ruckus.brouhaha.com> Message-ID: On May 29, 2010, at 2:58 PM, Paul Rubin wrote: > John Nagle writes: >> The major Red Hat based Linux distros are still shipping with >> Python 2.4. > > Fedora 12 ships with Python 2.6, I think. Fedora has been shipping with Python 2.6 since F11 release in June of 2009, and Python > 2.4 since F7 released in May 2007. http://distrowatch.com/table.php?distribution=fedora I think the OP is referring to RHEL (Enterprise Linux). Cheers Philip From mfedyk at mikefedyk.com Sat May 29 15:12:10 2010 From: mfedyk at mikefedyk.com (Mike Fedyk) Date: Sat, 29 May 2010 12:12:10 -0700 Subject: Python vs. Fedora and CentOS In-Reply-To: References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <7xaaripmaw.fsf@ruckus.brouhaha.com> Message-ID: On Sat, May 29, 2010 at 12:03 PM, Wesley Brooks wrote: > On 29 May 2010 19:58, Paul Rubin wrote: >> John Nagle writes: >>> ? The major Red Hat based Linux distros are still shipping with Python 2.4. >> >> Fedora 12 ships with Python 2.6, I think. > > I've got Fedora 10 here with 2.5, and 11 at the office with 2.6. > And Fedora 13 that has 2.6 and 3.1. And whatever slows down the upgrade treadmill is good IMO. People should not have to install the latest python just to use your app. From mmanns at gmx.net Sat May 29 15:12:41 2010 From: mmanns at gmx.net (Martin Manns) Date: Sat, 29 May 2010 21:12:41 +0200 Subject: xrange issue 7721 References: Message-ID: <20100529211241.56dc7bc4@Knock> On Sat, 29 May 2010 19:46:28 +0100 Mark Lawrence wrote: > I've had an OverflowError using xrange with Python 2.6.5 on Windows. > Googling got me to the subject line. > > msg97928 gives a code snippet to overcome the limitations of xrange, > allowing for negative steps, however it doesn't raise a ValueError > for a zero step. msg99624 gives a docs change that has been > implemented for V2.6, but this doesn't refer to the msg97928 code > snippet, rather it refers to a one liner that only works for positive > steps. The docs for V2.7 haven't been changed at all. Mark: Thank you for posting. 2.7 is not affected by issue 7721 because itertools.islice behavior is changed. Therefore, the original snippet should work in 2.7 (I have not tested this). I found the msg97928 code pretty obvious when seeing the snippet. If you disagree you may consider re-opening the issue. Martin From john at castleamber.com Sat May 29 15:12:42 2010 From: john at castleamber.com (John Bokma) Date: Sat, 29 May 2010 14:12:42 -0500 Subject: Free chapter about Python and databases (MySQL and SQLite) References: <87vda8ofvz.fsf@castleamber.com> <87hblrv4w9.fsf@castleamber.com> Message-ID: <878w7234k5.fsf@castleamber.com> Robinow writes: > > On May 28, 2010, at 10:05 PM, John Bokma wrote: > >> Sebastian Bassi writes: >> >>> On Fri, May 28, 2010 at 12:37 AM, John Bokma >>> wrote: >> >> Even if it's just a few bucks, it's still money saved [0]. On top of >> that I think it's way better to point your audience to good books on >> the >> topic and skip the intro instead of doing a (half hearted IMO) attempt >> at it yourself. >>> >> > OK, John. What book do you recommend? Since it's not clear on what topic in the book you want recommendations, I do them all. Note that I only can recommend books I have either in my possession or browsed through that are still on my wish list. I am not new to programming, so the books listed under Python are not books for beginners per se, except the Programming in Python 3, which is on top of that one of the best learning a programming language books I've read (so far). Python: Programming in Python 3 /2nd edition/ If you have some experience with programming: Dive into Python 2 (*) Dive into Python 3 (*) If you already have a book on learning Python and want a good extra reference: Python Essential Reference (4th edition) Subversion: Version Control with Subversion (O'Reilly) (*) Database: The Definitive Guide to SQLite MySQL (4th Edition) by Paul Dubois I also strongly suggest to read 1 or 2 books by Joe Celko before you even start to make your own databases (wish I would had), for example: Data and Databases: Concepts in Practice (**) SQL Programming Style SQL for smarties IMO Joe writes a bit "in your face" and calls a lot of people dumb, but don't let that get in the way ;-). I own also a copy of "MySQL cookbook" but haven't used it much. Still, I recommend to browse this book if you already have book(s) on MySQL and decide for yourself if it's something you want. In my experience most cookbook books by O'Reilly are good or very good. Can't recommend a good book on XML, I don't have one (***). I do have a book on XSLT (XSLT 2.0, O'Reilly) which is IMO very good, and does have, from the top of my head, a good XML introduction. Personally, I think it's good that if you work with XML that at least you have some idea of what XSLT is. Another XSLT book I have is XSLT 2.0 and XPath 2.0, but I haven't used that very often yet. (*) Also available as free download (**) Based on my experience with the other excellent books by Celko (***) A good book on XML would probably be 50 pages or less :-D. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From nagle at animats.com Sat May 29 16:22:49 2010 From: nagle at animats.com (John Nagle) Date: Sat, 29 May 2010 13:22:49 -0700 Subject: Python vs. Fedora and CentOS In-Reply-To: References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <7xaaripmaw.fsf@ruckus.brouhaha.com> Message-ID: <4C017799.6070804@animats.com> Philip Semanchuk wrote: > > On May 29, 2010, at 2:58 PM, Paul Rubin wrote: > >> John Nagle writes: >>> The major Red Hat based Linux distros are still shipping with Python >>> 2.4. >> >> Fedora 12 ships with Python 2.6, I think. > > Fedora has been shipping with Python 2.6 since F11 release in June of > 2009, and Python > 2.4 since F7 released in May 2007. > > http://distrowatch.com/table.php?distribution=fedora The "enterprise ready" versions are much further behind. http://distrowatch.com/table.php?distribution=centos CentOS 5.5 (May 2010) - Python: 2.4.3 http://distrowatch.com/table.php?distribution=redhat RHEL 5.5 (March 2010) - Python 2.4.3 RHEL 6-Beta - Python 2.6.2 However, if 2.6.2 is going into RHEL, the others will follow, and that's probably the production Python on servers for the next few years. John Nagle From bryanjugglercryptographer at yahoo.com Sat May 29 16:45:37 2010 From: bryanjugglercryptographer at yahoo.com (Bryan) Date: Sat, 29 May 2010 13:45:37 -0700 (PDT) Subject: dbf files and indexes References: <4BFECBF6.10006@stoneleaf.us> <20100527160445.30081fd3.darcy@druid.net> Message-ID: <036564ec-ebb1-422f-904b-2b58d2fcbd12@z13g2000prh.googlegroups.com> Christian Heimes wrote: [D'Arcy J.M. Cain had written:] > > SELECT * FROM NumberOfPets > > WHERE name IN (SELECT name FROM CatLovers) OR > > ? ?name IN (SELECT name FROM DogLovers) > > ORDER BY name; > > A good way is to use SQL with JOINs instead of horrible nested > selects. Do show us your join that makes D'Arcy's nested select horrible by comparison. > Although SQL is declarative, you shouldn't make the work of the query > optimizer so hard. You're not doing the query optimizer any favors. It can normalize the query to the same thing either way, so we might as well write it to be readable by people. I can read D'Arcy's at a glance. -- --Bryan Olson From johan.lans at apspektakel.com Sat May 29 16:51:39 2010 From: johan.lans at apspektakel.com (Johan Lans) Date: Sat, 29 May 2010 13:51:39 -0700 (PDT) Subject: tkinter function outout to text widget Message-ID: Hi I'm totally new on python and I'm doing an assignement where I'm doing a class that manipulates a text. The program is also supposed to have a GUI, for which I have used tkinter. So far I have entry widgets for file names and buttons, its all working like I want it to. What is missing is a way to output the changes to the text. I was thinking that a text-widget would be suitable. Is there a reasonably easy way to do this? I tried inserting a string to the textwidget and letting the class method change this string, but the inserted string isn't updated in the text-widget. Would be very happy for any hints. From texaspeso26 at gmail.com Sat May 29 17:42:27 2010 From: texaspeso26 at gmail.com (KAJAL AGARWAL) Date: Sat, 29 May 2010 14:42:27 -0700 (PDT) Subject: PLAY CAR RACE GAMES Message-ID: PLAY CAR RACE GAMES:- PLAY CAR RACE GAMES ON MY WEB SITE AND ENJOY UR MIND FRESH AND U CAN DOWN LOAD ALSO MY GAMES VISIT http://andhraonlinegames.blogspot,com From alfps at start.no Sat May 29 18:11:09 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 30 May 2010 00:11:09 +0200 Subject: tkinter function outout to text widget In-Reply-To: References: Message-ID: * Johan Lans, on 29.05.2010 22:51: > Hi > I'm totally new on python and I'm doing an assignement where I'm doing > a class that manipulates a text. The program is also supposed to have > a GUI, for which I have used tkinter. > So far I have entry widgets for file names and buttons, its all > working like I want it to. > What is missing is a way to output the changes to the text. I was > thinking that a text-widget would be suitable. Is there a reasonably > easy way to do this? > I tried inserting a string to the textwidget and letting the class > method change this string, but the inserted string isn't updated in > the text-widget. If that is a direct Python string, then you're not changing the string. Python strings are immutable. So, then you're at most changing which string a variable or attribute is referring to. However, if it is some Tkinter thing (I seem to recall that Tkinter offers some automatic update magic via something-something), then I don't know. > Would be very happy for any hints. Just update the widget whenever you change the text. Cheers & hth., - Alf -- blog at From darcy at druid.net Sat May 29 18:55:22 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 29 May 2010 18:55:22 -0400 Subject: Python vs. Fedora and CentOS In-Reply-To: <4c015aa9$0$1617$742ec2ed@news.sonic.net> References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> Message-ID: <20100529185522.0a4bb452.darcy@druid.net> On Sat, 29 May 2010 11:43:29 -0700 John Nagle wrote: > The major Red Hat based Linux distros are still shipping with Python 2.4. > > Is anybody trying to do something about this? Other than not running Linux on our hosting server? My ISP (http://www.Vex.Net) runs FreeBSD. Linux is for the desktop. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From darcy at druid.net Sat May 29 19:00:14 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 29 May 2010 19:00:14 -0400 Subject: dbf files and indexes In-Reply-To: <036564ec-ebb1-422f-904b-2b58d2fcbd12@z13g2000prh.googlegroups.com> References: <4BFECBF6.10006@stoneleaf.us> <20100527160445.30081fd3.darcy@druid.net> <036564ec-ebb1-422f-904b-2b58d2fcbd12@z13g2000prh.googlegroups.com> Message-ID: <20100529190014.969cdb57.darcy@druid.net> On Sat, 29 May 2010 13:45:37 -0700 (PDT) Bryan wrote: > You're not doing the query optimizer any favors. It can normalize the > query to the same thing either way, so we might as well write it to be > readable by people. I can read D'Arcy's at a glance. Assuming that you are running a decent *cough* PostgreSQL *cough* database engine. Readable is good. If you have a problem with your queries chances are that reorganizing your data or adding proper indexes will do more for you than contorted SQL will. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From breamoreboy at yahoo.co.uk Sat May 29 19:49:11 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 30 May 2010 00:49:11 +0100 Subject: xrange issue 7721 In-Reply-To: <20100529211241.56dc7bc4@Knock> References: <20100529211241.56dc7bc4@Knock> Message-ID: Hi Martin, thanks for the response, please see below. On 29/05/2010 20:12, Martin Manns wrote: > On Sat, 29 May 2010 19:46:28 +0100 > Mark Lawrence wrote: > >> I've had an OverflowError using xrange with Python 2.6.5 on Windows. >> Googling got me to the subject line. >> >> msg97928 gives a code snippet to overcome the limitations of xrange, >> allowing for negative steps, however it doesn't raise a ValueError >> for a zero step. msg99624 gives a docs change that has been >> implemented for V2.6, but this doesn't refer to the msg97928 code >> snippet, rather it refers to a one liner that only works for positive >> steps. The docs for V2.7 haven't been changed at all. > > Mark: > > Thank you for posting. > > 2.7 is not affected by issue 7721 because itertools.islice behavior is > changed. Therefore, the original snippet should work in 2.7 (I have not > tested this). From http://docs.python.org/dev/library/itertools.html "Unlike regular slicing, islice() does not support negative values for start, stop, or step." Rule 1 of programming never assume anything, particularly wrt testing. I assume that you are ok with this. :) Dreadful I know :) > > I found the msg97928 code pretty obvious when seeing the snippet. > If you disagree you may consider re-opening the issue. Try running this on Python 2.6.5 in file irange.py from itertools import takewhile, count def irange(start, stop, step): if step < 0: cond = lambda x: x > stop else: cond = lambda x: x < stop return takewhile(cond, (start + i * step for i in count())) if __name__=='__main__': for i in irange(0, 10, 0): print i My output from the command line c:\Users\Mark\python>irange 0 0 etc etc etc I trust that you get my point regarding the failure to raise a ValueError :) Or am I wearing my extremely stupid hat today? > > Martin > Kindest regards. Mark Lawrence. From gnujohn at gmail.com Sat May 29 20:23:23 2010 From: gnujohn at gmail.com (john) Date: Sat, 29 May 2010 17:23:23 -0700 (PDT) Subject: if, continuation and indentation References: Message-ID: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> On May 28, 10:37?am, "Colin J. Williams" wrote: > On 28-May-10 05:54 AM, Jonathan Hartley wrote: > > > On May 27, 1:57 pm, Jean-Michel Pichavant > > wrote: > >> HH wrote: > >>> I have a question about best practices when it comes to line wrapping/ > >>> continuation and indentation, specifically in the case of an if > >>> statement. > > >>> When I write an if statement with many conditions, I prefer to use a > >>> parenthesis around the whole block and get the implicit continuation, > >>> rather than ending each line with an escape character. ?Thus, using > >>> the example from the style guide (http://www.python.org/dev/peps/ > >>> pep-0008/) I would write: > > >>> ? ? ?if (width == 0 and > >>> ? ? ? ? ?height == 0 and > >>> ? ? ? ? ?color == 'red' and > >>> ? ? ? ? ?emphasis == 'strong' or > >>> ? ? ? ? ?highlight> ?100): > >>> ? ? ? ? ?raise ValueError("sorry, you lose") > > >>> The problem should be obvious -- it's not easy to see where the > >>> conditional ends and the statement begins since they have the same > >>> indentation. ?Part of the problem, I suppose, is that Emacs indents > >>> 'height' and the other lines in the conditional to 4 spaces (because > >>> of the parenthesis). ?How do people deal with this situation? > > >>> Thanks, > >>> Henrik > > >> One possible solution > > >> ? ? ?if ( > >> ? ? ? ? ? ? ?width == 0 and > >> ? ? ? ? ? ? ?height == 0 and > >> ? ? ? ? ? ? ?color == 'red' and > >> ? ? ? ? ? ? ?emphasis == 'strong' or > >> ? ? ? ? ? ? ?highlight> ?100 > >> ? ? ? ? ): > >> ? ? ? ? ?raise ValueError("sorry, you lose") > > >> JM > > > I've always liked this, or even: > > > ? ?if ( > > ? ? ? ?width == 0 and > > ? ? ? ?height == 0 and > > ? ? ? ?color == 'red' and > > ? ? ? ?emphasis == 'strong' or > > ? ? ? ?highlight> ?100 > > ? ?): > > ? ? ? ?raise ValueError("sorry, you lose") > > > but my co-workers have uniformly gone bananas whenever I try it. > > I liked: > > On 27-May-10 08:48 AM, Xavier Ho wrote: > ?> On 27 May 2010 22:22, HH > wrote: > > ?> > ?> ? ? ? ? if (width == 0 and > ?> ? ? ? ? ? ? height == 0 and > ?> ? ? ? ? ? ? color == 'red' and > ?> ? ? ? ? ? ? emphasis == 'strong' or > ?> ? ? ? ? ? ? highlight > 100): > ?> ? ? ? ? ? ? raise ValueError("sorry, you lose") > ?> > ?> > ?> I've gotta say - I've bumped into this problem before, and I'm sure many > ?> other have - this is a valid question. It just hasn't bothered me enough > ?> to ask... > ?> > ?> Correct me if I'm wrong, but I think the following is equivalent, and > ?> looks better. Although this won't fix all ugly cases in that problem.. > ?> > ?> if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or > ?> highlight > 100: > ?> ? ? ?raise ValueError("sorry, you lose") > ?> > ?> Cheers, > ?> Xav > > but nobody commented. > > Colin W. Colin: Sure, you can do it that way. IMO, though, the OP was wrong, and so is the PEP. Source code is meant to communicate. So it must transmit the correct information to the computer; it also must inform your coworkers. That means that you have a responsibility to care what they think, though you privately have your opinions. Another reason the PEP is faulty in this circumstance is that a misplaced backslash, or a missing one, is easily found and fixed. A misplaced parentheses, or just one of a pair, will transform your source code into something which may compile and then give faulty results: a disaster. So keep it simple, and make it legible. Yours, John From breamoreboy at yahoo.co.uk Sat May 29 20:59:39 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 30 May 2010 01:59:39 +0100 Subject: if, continuation and indentation In-Reply-To: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> Message-ID: On 30/05/2010 01:23, john wrote: > On May 28, 10:37 am, "Colin J. Williams" > wrote: >> On 28-May-10 05:54 AM, Jonathan Hartley wrote: >> >>> On May 27, 1:57 pm, Jean-Michel Pichavant >>> wrote: >>>> HH wrote: >>>>> I have a question about best practices when it comes to line wrapping/ >>>>> continuation and indentation, specifically in the case of an if >>>>> statement. >> >>>>> When I write an if statement with many conditions, I prefer to use a >>>>> parenthesis around the whole block and get the implicit continuation, >>>>> rather than ending each line with an escape character. Thus, using >>>>> the example from the style guide (http://www.python.org/dev/peps/ >>>>> pep-0008/) I would write: >> >>>>> if (width == 0 and >>>>> height == 0 and >>>>> color == 'red' and >>>>> emphasis == 'strong' or >>>>> highlight> 100): >>>>> raise ValueError("sorry, you lose") >> >>>>> The problem should be obvious -- it's not easy to see where the >>>>> conditional ends and the statement begins since they have the same >>>>> indentation. Part of the problem, I suppose, is that Emacs indents >>>>> 'height' and the other lines in the conditional to 4 spaces (because >>>>> of the parenthesis). How do people deal with this situation? >> >>>>> Thanks, >>>>> Henrik >> >>>> One possible solution >> >>>> if ( >>>> width == 0 and >>>> height == 0 and >>>> color == 'red' and >>>> emphasis == 'strong' or >>>> highlight> 100 >>>> ): >>>> raise ValueError("sorry, you lose") >> >>>> JM >> >>> I've always liked this, or even: >> >>> if ( >>> width == 0 and >>> height == 0 and >>> color == 'red' and >>> emphasis == 'strong' or >>> highlight> 100 >>> ): >>> raise ValueError("sorry, you lose") >> >>> but my co-workers have uniformly gone bananas whenever I try it. >> >> I liked: >> >> On 27-May-10 08:48 AM, Xavier Ho wrote: >> > On 27 May 2010 22:22, HH > wrote: >> >> > >> > if (width == 0 and >> > height == 0 and >> > color == 'red' and >> > emphasis == 'strong' or >> > highlight> 100): >> > raise ValueError("sorry, you lose") >> > >> > >> > I've gotta say - I've bumped into this problem before, and I'm sure many >> > other have - this is a valid question. It just hasn't bothered me enough >> > to ask... >> > >> > Correct me if I'm wrong, but I think the following is equivalent, and >> > looks better. Although this won't fix all ugly cases in that problem.. >> > >> > if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or >> > highlight> 100: >> > raise ValueError("sorry, you lose") >> > >> > Cheers, >> > Xav >> >> but nobody commented. >> >> Colin W. > > Colin: > Sure, you can do it that way. IMO, though, the OP was wrong, and so > is the PEP. Source code is meant to communicate. So it must transmit > the correct information to the computer; it also must inform your > coworkers. That means that you have a responsibility to care what > they think, though you privately have your opinions. Another reason > the PEP is faulty in this circumstance is that a misplaced backslash, > or a missing one, is easily found and fixed. A misplaced parentheses, > or just one of a pair, will transform your source code into something > which may compile and then give faulty results: a disaster. > So keep it simple, and make it legible. > Yours, > John IMHO complete garbage, if your editor doesn't show misplaced or missing parenthesis by highlighting you're using the wrong editor :) Regards. Mark Lawrence. From jyoung79 at kc.rr.com Sat May 29 21:13:22 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Sun, 30 May 2010 1:13:22 +0000 Subject: GUI programs Message-ID: <20100530011322.HBM34.9984.root@cdptpa-web23-z02> Just curious if anyone would be willing to share their thoughts about different Python GUI programming modules. I've been doing a bit of research and am trying to find something that: 1. Is portable. Would like to be able to send the module along with the main python file that would be able to run a GUI window. Would be sending this to multiple machines. Currently I'd like it to work on OS X machines, but it'd be nice if it worked on Windows machines, etc. Probably be using Python 2.5 or 2.6. 2. Can show an image (that is zoomable) as well as add GUI controls like text fields, popup menues, etc. as well as send information back to the program from the text fields, etc. For now, I'm really looking for something that can display EPS (postscript) and PDF images. In my research, here's some GUI modules/programs I've been looking at. I haven't gone real in-depth with these, but did just a little testing: 1. wxPython - This looks very good, although I'm not sure how to set up portability with this. Other machines that would run the Python code probably wouldn't have the Developer Tools or wxPython installed. I think I could use Py2App for OS X to create a Package App but I'm not real familiar with how that would all work. 2. Pyglet - This is a pretty cool program. I was able to display a window with an image? but I don't think it has GUI controls like text fields, drop down menues, etc. 3. ImageMagick - This one looks cool but I can't figure out how to install it correctly on OS X (Snow Leopard). Not sure if it would give me the GUI tools either. 4. PyGui - This one looks very interesting. Just found it last night so haven't looked at it too closely. Looks like it needs PyObjC on the machine for OS X. I'm assuming that comes pre-installed on Snow Leopard machines, but not sure about Leopard or Tiger machines. Anyone have more info about this? 5. NodeBox - This is an incredible application! Don't think I can use it's libraries for what I'm wanting to do, but what a cool program! I will definitely spend some time working with this! 6. TkInter - Does this module come standard on all machines that have Python? Haven't worked with this one much, but if I send Python code to other machines would TkInter work? Would love to hear anyones thoughts about GUI programming and what they use. Would also like to hear pros/cons with the different modules/apps. Thanks for looking at my questions. Jay From fordhaivat at gmail.com Sun May 30 00:05:46 2010 From: fordhaivat at gmail.com (Someone Something) Date: Sun, 30 May 2010 00:05:46 -0400 Subject: Python vs. Fedora and CentOS In-Reply-To: References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <20100529185522.0a4bb452.darcy@druid.net> Message-ID: Redhat as always believed in (sorry if this offends anyone): "Use legacy stuff that works, we don't really give a flying hoot if the rest of the world has moved on" On Sat, May 29, 2010 at 6:55 PM, D'Arcy J.M. Cain wrote: > On Sat, 29 May 2010 11:43:29 -0700 > John Nagle wrote: > > The major Red Hat based Linux distros are still shipping with Python > 2.4. > > > > Is anybody trying to do something about this? > > Other than not running Linux on our hosting server? My ISP > (http://www.Vex.Net) runs FreeBSD. Linux is for the desktop. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Sun May 30 00:15:15 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 29 May 2010 21:15:15 -0700 Subject: Python vs. Fedora and CentOS In-Reply-To: References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <20100529185522.0a4bb452.darcy@druid.net> Message-ID: And since they're "using legacy stuff that works" from 3 years ago (no one upgrades major versions of software in a minor release- hence Win XP SP3 still coming with IE 6), it's no wonder that they're still on 2.4. On Sat, May 29, 2010 at 9:05 PM, Someone Something wrote: > > Redhat as always believed in (sorry if this offends anyone): "Use legacy > stuff that works, we don't really give a flying hoot if the rest of the > world has moved on" > > On Sat, May 29, 2010 at 6:55 PM, D'Arcy J.M. Cain wrote: >> >> On Sat, 29 May 2010 11:43:29 -0700 >> John Nagle wrote: >> > ? ?The major Red Hat based Linux distros are still shipping with Python >> > 2.4. >> > >> > ? ?Is anybody trying to do something about this? >> >> Other than not running Linux on our hosting server? ?My ISP >> (http://www.Vex.Net) runs FreeBSD. ?Linux is for the desktop. >> >> -- >> D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolves >> http://www.druid.net/darcy/ ? ? ? ? ? ? ? ?| ?and a sheep voting on >> +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From nathan.alexander.rice at gmail.com Sun May 30 01:50:02 2010 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Sun, 30 May 2010 01:50:02 -0400 Subject: if, continuation and indentation In-Reply-To: References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> Message-ID: I prefer to just break such things into multiple lines. You're doing that already anyhow, it's not much of a speed hit, and it makes exactly what you're testing explicit. If I break a statement onto multiple lines I only use parenthesis, and that is as a last resort. In my opinion there's almost always some combination of variable assignments and lambda expressions that uses fewer lines and is clearer. is_correct_style = width == 0 and height == 0 and color == 'red' if (is_correct_style and emphasis == 'strong') or highlight > 100: On Sat, May 29, 2010 at 8:59 PM, Mark Lawrence wrote: > On 30/05/2010 01:23, john wrote: > >> On May 28, 10:37 am, "Colin J. Williams" >> wrote: >> >>> On 28-May-10 05:54 AM, Jonathan Hartley wrote: >>> >>> On May 27, 1:57 pm, Jean-Michel Pichavant >>>> wrote: >>>> >>>>> HH wrote: >>>>> >>>>>> I have a question about best practices when it comes to line wrapping/ >>>>>> continuation and indentation, specifically in the case of an if >>>>>> statement. >>>>>> >>>>> >>> When I write an if statement with many conditions, I prefer to use a >>>>>> parenthesis around the whole block and get the implicit continuation, >>>>>> rather than ending each line with an escape character. Thus, using >>>>>> the example from the style guide (http://www.python.org/dev/peps/ >>>>>> pep-0008/) I would write: >>>>>> >>>>> >>> if (width == 0 and >>>>>> height == 0 and >>>>>> color == 'red' and >>>>>> emphasis == 'strong' or >>>>>> highlight> 100): >>>>>> raise ValueError("sorry, you lose") >>>>>> >>>>> >>> The problem should be obvious -- it's not easy to see where the >>>>>> conditional ends and the statement begins since they have the same >>>>>> indentation. Part of the problem, I suppose, is that Emacs indents >>>>>> 'height' and the other lines in the conditional to 4 spaces (because >>>>>> of the parenthesis). How do people deal with this situation? >>>>>> >>>>> >>> Thanks, >>>>>> Henrik >>>>>> >>>>> >>> One possible solution >>>>> >>>> >>> if ( >>>>> width == 0 and >>>>> height == 0 and >>>>> color == 'red' and >>>>> emphasis == 'strong' or >>>>> highlight> 100 >>>>> ): >>>>> raise ValueError("sorry, you lose") >>>>> >>>> >>> JM >>>>> >>>> >>> I've always liked this, or even: >>>> >>> >>> if ( >>>> width == 0 and >>>> height == 0 and >>>> color == 'red' and >>>> emphasis == 'strong' or >>>> highlight> 100 >>>> ): >>>> raise ValueError("sorry, you lose") >>>> >>> >>> but my co-workers have uniformly gone bananas whenever I try it. >>>> >>> >>> I liked: >>> >>> On 27-May-10 08:48 AM, Xavier Ho wrote: >>> > On 27 May 2010 22:22, HH >> henri... at gmail.com>> wrote: >>> >>> > >>> > if (width == 0 and >>> > height == 0 and >>> > color == 'red' and >>> > emphasis == 'strong' or >>> > highlight> 100): >>> > raise ValueError("sorry, you lose") >>> > >>> > >>> > I've gotta say - I've bumped into this problem before, and I'm sure >>> many >>> > other have - this is a valid question. It just hasn't bothered me >>> enough >>> > to ask... >>> > >>> > Correct me if I'm wrong, but I think the following is equivalent, and >>> > looks better. Although this won't fix all ugly cases in that >>> problem.. >>> > >>> > if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or >>> > highlight> 100: >>> > raise ValueError("sorry, you lose") >>> > >>> > Cheers, >>> > Xav >>> >>> but nobody commented. >>> >>> Colin W. >>> >> >> Colin: >> Sure, you can do it that way. IMO, though, the OP was wrong, and so >> is the PEP. Source code is meant to communicate. So it must transmit >> the correct information to the computer; it also must inform your >> coworkers. That means that you have a responsibility to care what >> they think, though you privately have your opinions. Another reason >> the PEP is faulty in this circumstance is that a misplaced backslash, >> or a missing one, is easily found and fixed. A misplaced parentheses, >> or just one of a pair, will transform your source code into something >> which may compile and then give faulty results: a disaster. >> So keep it simple, and make it legible. >> Yours, >> John >> > > IMHO complete garbage, if your editor doesn't show misplaced or missing > parenthesis by highlighting you're using the wrong editor :) > > Regards. > > Mark Lawrence. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Sun May 30 02:06:47 2010 From: nagle at animats.com (John Nagle) Date: Sat, 29 May 2010 23:06:47 -0700 Subject: Where does "make altinstall" put stuff? Message-ID: <4c01facf$0$1600$742ec2ed@news.sonic.net> I know that one is supposed to use "make altinstall" to install versions of Python that won't be the "primary" version. But what directory names does it use for packages and other support files? Is this documented somewhere? I want to make sure that no part of the existing Python installation on Fedora Core is overwritten by an "altinstall" of 2.6. John Nagle From prologic at shortcircuit.net.au Sun May 30 02:21:30 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sun, 30 May 2010 16:21:30 +1000 Subject: Where does "make altinstall" put stuff? In-Reply-To: <4c01facf$0$1600$742ec2ed@news.sonic.net> References: <4c01facf$0$1600$742ec2ed@news.sonic.net> Message-ID: On Sun, May 30, 2010 at 4:06 PM, John Nagle wrote: > I know that one is supposed to use "make altinstall" to install > versions of Python that won't be the "primary" version. ?But what > directory names does it use for packages and other support files? > Is this documented somewhere? > > ?I want to make sure that no part of the existing Python installation > on Fedora Core is overwritten by an "altinstall" of 2.6. Check the generated Makefile (created by ./configure) --James From casevh at gmail.com Sun May 30 02:31:06 2010 From: casevh at gmail.com (casevh) Date: Sat, 29 May 2010 23:31:06 -0700 (PDT) Subject: Where does "make altinstall" put stuff? References: <4c01facf$0$1600$742ec2ed@news.sonic.net> Message-ID: <56b3f785-1135-4a99-b6b9-5646031447d7@6g2000prg.googlegroups.com> On May 29, 11:06?pm, John Nagle wrote: > ? ?I know that one is supposed to use "make altinstall" to install > versions of Python that won't be the "primary" version. ?But what > directory names does it use for packages and other support files? > Is this documented somewhere? > > ? ?I want to make sure that no part of the existing Python installation > on Fedora Core is overwritten by an "altinstall" of 2.6. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle It's placed in the directory specified by --prefix. If --prefix is not specified, /usr/local is used by default. casevh From steve at REMOVE-THIS-cybersource.com.au Sun May 30 02:55:14 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 May 2010 06:55:14 GMT Subject: xrange issue 7721 References: Message-ID: <4c020bd1$0$27827$c3e8da3@news.astraweb.com> On Sat, 29 May 2010 19:46:28 +0100, Mark Lawrence wrote: > I've had an OverflowError using xrange with Python 2.6.5 on Windows. > Googling got me to the subject line. It is considered best practice (or at least sensible practice) to include a relevant URL in your post. This will maximise the number of people who click through to the bug tracker while minimising the number who say "if the poster can't be bothered to copy and paste a URL, he obviously doesn't care that much about the issue, so why should I google for it?". http://bugs.python.org/issue7721 [...] > Assuming that I am correct, can I create myself a login on the bugs > tracker and re-open the issue to get this sorted? You can try, but I don't think that a code snippet is meant as a full- blown replacement for xrange, just as a, well, snippet to get you started. If you need a full replacement, you'll end up with something like this: _xrange = xrange def xrange(a, b=None, step=1): try: return _xrange(a, b, step) except OverflowError: if b is None: start, end = 0, a else: start, end = a, b if step > 0: from operator import lt as cmp elif step < 0: from operator import gt as cmp else: raise ValueError("xrange() arg 3 must not be zero") from itertools import count, takewhile return takewhile( lambda n: cmp(n, end), (start + i*step for i in count())) This should give you a larger range while still avoiding any significant overhead when you don't need it. -- Steven From nagle at animats.com Sun May 30 02:56:39 2010 From: nagle at animats.com (John Nagle) Date: Sat, 29 May 2010 23:56:39 -0700 Subject: MySQLdb install vs. "setuptools" Message-ID: <4c020680$0$1581$742ec2ed@news.sonic.net> MySQLdb won't install as non-root on Python 2.6 because its "setup.py" file requires "setuptools". "setuptools", unlike "distutils", isn't part of the Python 2.6 distribution. IMPORTANT PACKAGES SHOULD NOT USE "setuptools". Use the standard "distutils". "setuptools" and "eggs" create more problems than they solve. "setuptools" has many built-in assumptions about where things are supposed to be, and they're usually wrong. There's an "ez_setup.py" available for MySQLdb. This tries to obtain and install "setuptools". But it wants too many privileges just to do a "build": The following error occurred while trying to add or remove files in the installation directory: [Errno 2] No such file or directory: '/usr/local/lib/python2.6/site-packages/test-easy-install-22015.write-test' That's because "setuptools" has a built-in ego trip of insisting that it should be installed globally. I'm running a freshly-built, but not "installed" version of Python 2.6. I'm trying to install a test version of Python2.6 with some packages without running as root on a live server. It's not just MySQLdb that's broken by "setuptools". See these examples of other installation problems created by "setuptools": http://blog.awarelabs.com/2008/installing-mysqldb-without-python-egg-problems/ http://mail.python.org/pipermail/pythonmac-sig/2009-March/021148.html http://plone.org/documentation/error/permission-denied-python-eggs As soon as "setuptools" becomes involved, unnecessary headaches appear. DO NOT USE SETUPTOOLS. Either use "distutils", or go all the way and provide a RPM for Linux and a .exe for Windows. John Nagle From kobe824ouchao at gmail.com Sun May 30 05:15:04 2010 From: kobe824ouchao at gmail.com (Ou Chao) Date: Sun, 30 May 2010 17:15:04 +0800 Subject: How to use dbstore in google app engine Message-ID: Hi all: I have a question. How GEA save a file as simulates the App Engine datastore in local computer? where is the file? thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From detlev at die-offenbachs.de Sun May 30 05:23:17 2010 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 30 May 2010 11:23:17 +0200 Subject: GUI programs References: Message-ID: I would recommend PyQt. I've done a lot of programming with it (http://eric-ide.python-projects.org) and am amazed about the platform neutrality it offers. Regards, Detlev jyoung79 at kc.rr.com wrote: > Just curious if anyone would be willing to share their thoughts > about different Python GUI programming modules. I've been > doing a bit of research and am trying to find something that: > > 1. Is portable. Would like to be able to send the module along > with the main python file that would be able to run a GUI > window. Would be sending this to multiple machines. > Currently I'd like it to work on OS X machines, but it'd be nice > if it worked on Windows machines, etc. Probably be using > Python 2.5 or 2.6. > > 2. Can show an image (that is zoomable) as well as add GUI > controls like text fields, popup menues, etc. as well as send > information back to the program from the text fields, etc. > For now, I'm really looking for something that can display > EPS (postscript) and PDF images. > > In my research, here's some GUI modules/programs I've been > looking at. I haven't gone real in-depth with these, but did > just a little testing: > > 1. wxPython - This looks very good, although I'm not sure > how to set up portability with this. Other machines that would > run the Python code probably wouldn't have the Developer > Tools or wxPython installed. I think I could use Py2App for > OS X to create a Package App but I'm not real familiar with > how that would all work. > > 2. Pyglet - This is a pretty cool program. I was able to display > a window with an image? but I don't think it has GUI controls > like text fields, drop down menues, etc. > > 3. ImageMagick - This one looks cool but I can't figure out how > to install it correctly on OS X (Snow Leopard). Not sure if it would > give me the GUI tools either. > > 4. PyGui - This one looks very interesting. Just found it last night > so haven't looked at it too closely. Looks like it needs PyObjC on > the machine for OS X. I'm assuming that comes pre-installed on > Snow Leopard machines, but not sure about Leopard or Tiger > machines. Anyone have more info about this? > > 5. NodeBox - This is an incredible application! Don't think I can > use it's libraries for what I'm wanting to do, but what a cool > program! I will definitely spend some time working with this! > > 6. TkInter - Does this module come standard on all machines > that have Python? Haven't worked with this one much, but if I > send Python code to other machines would TkInter work? > > Would love to hear anyones thoughts about GUI programming > and what they use. Would also like to hear pros/cons with the > different modules/apps. > > Thanks for looking at my questions. > > Jay -- Detlev Offenbach detlev at die-offenbachs.de From googler.1.webmaster at spamgourmet.com Sun May 30 06:17:40 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Sun, 30 May 2010 03:17:40 -0700 (PDT) Subject: Py_single_input and the side-effects... References: Message-ID: <71e9afe5-f64e-4c2a-9c25-d814d13c7d46@t14g2000prm.googlegroups.com> Hi, any idea? From peterwfh2000 at gmail.com Sun May 30 06:21:04 2010 From: peterwfh2000 at gmail.com (PETER WONG F H (+971 50 8320722)) Date: Sun, 30 May 2010 03:21:04 -0700 (PDT) Subject: This is the way i make my dream and monthly income Message-ID: Hi, This is the way i make my dream and monthly income Making money online takes "hard work" but... The "$10 Per month" Power Formula Will Make Any Business Grow Without You Doing The Work! For every 5 affiliates you refer, we pay you a US100 cash bonus. There is no limit! Website : http://www.dubaiproperty.ws/ to explore more Best Regards Peter wong Dubai Mob : +971 50 ? 8320722 Malaysia Mob : +6012 ? 2956466 Peterwfh2000 at gmail.com From solipsis at pitrou.net Sun May 30 06:22:28 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 30 May 2010 12:22:28 +0200 Subject: MySQLdb install vs. "setuptools" References: <4c020680$0$1581$742ec2ed@news.sonic.net> Message-ID: <20100530122228.53c8e8a9@pitrou.net> Really, this shouldn't happen if you really are using a non-root version of Python: > [Errno 2] No such file or directory: > '/usr/local/lib/python2.6/site-packages/test-easy-install-22015.write-test' I don't think setuptools is dumb enough to hardcode things like "/usr/local/lib/python2.6/", so the error is probably yours here. Perhaps you should double-check you did everything fine before posting such a rant. Of course, if by "freshly-built version of Python", you mean you didn't run "make install" in any way, then it's your problem. Give "./configure" an appropriate non-root prefix and don't forget to run "make install" at the end. From philip at semanchuk.com Sun May 30 08:22:55 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 30 May 2010 08:22:55 -0400 Subject: GUI programs In-Reply-To: <20100530011322.HBM34.9984.root@cdptpa-web23-z02> References: <20100530011322.HBM34.9984.root@cdptpa-web23-z02> Message-ID: On May 29, 2010, at 9:13 PM, wrote: > Just curious if anyone would be willing to share their thoughts > about different Python GUI programming modules. I've been > doing a bit of research and am trying to find something that: > > 1. Is portable. Would like to be able to send the module along > with the main python file that would be able to run a GUI > window. Would be sending this to multiple machines. > Currently I'd like it to work on OS X machines, but it'd be nice > if it worked on Windows machines, etc. Probably be using > Python 2.5 or 2.6. Hi Jay, wxPython, pyQT and Tkinter are all portable in that they'll run under OS X, Windows, Gnome and KDE. Getting them installed there in some sane fashion is another matter. There are programs like py2exe and py2app that you've found, but Python doesn't lend itself to being bundled this way. It can work, but may be a fair amount of trouble depending on what modules you're trying to use and how diverse your target machines are. > 6. TkInter - Does this module come standard on all machines > that have Python? Haven't worked with this one much, but if I > send Python code to other machines would TkInter work? That's my understanding. I haven't used it. I gather that Tkinter is useful in a pinch, but that it isn't appropriate for applications with much more than a minimalist GUI. > Would love to hear anyones thoughts about GUI programming > and what they use. Would also like to hear pros/cons with the > different modules/apps. There's lots of discussion on this topic in the archives of this mailing list and others. These modules haven't changed dramatically over the past few years, so any recent-ish conversation is relevant. Good luck Philip PS - we use wxPython From 1000lane04 at gmail.com Sun May 30 08:57:37 2010 From: 1000lane04 at gmail.com (yan) Date: Sun, 30 May 2010 05:57:37 -0700 (PDT) Subject: $Wholesale Sports Shoes Clear Air Force One AAA++quality Message-ID: <985d98ba-6ae8-4e5e-9ed0-0876474b692b@p5g2000pri.googlegroups.com> $Wholesale Sports Shoes Clear Air Force One AAA++quality please kindly visite our website: http://www.8000trade.com supply sports shoes. The brand Sports shoes basketball shoes, Boot, walling shoes, Athletic shoes, Jogging shoes, running shoes, leather shoes, football, shoe sports shoe Footwear Sneaker, Shox Max Rift T- shirts, womens t-shirts, Clothing womens clothing, wear hats Caps Jersey jeans Sock Jacks, Watches, wallet, handbags, and Jeans Lady Clothing and so on. Please contact us by email to get more information. our price $33shoes,$15tshirt,15sunglasess, $13cap,$33jean,$35bag please kindly visite our website: http://www.8000trade.com From invalid at invalid.invalid Sun May 30 10:12:20 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 30 May 2010 14:12:20 +0000 (UTC) Subject: GUI programs References: Message-ID: On 2010-05-30, wrote: > 1. wxPython - This looks very good, although I'm not sure > how to set up portability with this. I'm not sure what you mean by "set up portability". If you follow the wxPython API documentation, then wxPython code is fairly portable. > Other machines that would run the Python code probably wouldn't have > the Developer Tools or wxPython installed. I think I could use > Py2App for OS X to create a Package App but I'm not real familiar > with how that would all work. I've used py2exe with success. It's fairly simple to use for simple programs, but can require some configuration tweaking if you use a log of libraries (wxPython numeric Python, scientific Python, etc.). > 6. TkInter - Does this module come standard on all machines > that have Python? Not all, but it's a lot more common than wxPython. > Haven't worked with this one much, but if I send Python code to other > machines would TkInter work? Generally yes, if the machines have TkInter installed. > Would love to hear anyones thoughts about GUI programming and what > they use. Would also like to hear pros/cons with the different > modules/apps. This question comes up about once a week, so Google should be able to find plenty of recent threads. -- Grant From nikunj257 at gmail.com Sun May 30 10:12:55 2010 From: nikunj257 at gmail.com (nikks) Date: Sun, 30 May 2010 07:12:55 -0700 (PDT) Subject: making $$$$ was never so easier..... Message-ID: <9ff37169-9815-464a-9d8b-d90f495a69fd@v12g2000prb.googlegroups.com> Build your own GeoString! and get paid............. http://www.geostring.com/en/?1155577 The longer you make your GeoString... the more free cash we'll put in your pockets! We'll give you $10.00 free money just for starting your own GeoString. Furthermore, we'll pay you every time you add length to your GeoString. It's Fun and it's Free! click below and earn... http://www.geostring.com/en/?1155577 From cournape at gmail.com Sun May 30 10:43:04 2010 From: cournape at gmail.com (David Cournapeau) Date: Sun, 30 May 2010 23:43:04 +0900 Subject: MySQLdb install vs. "setuptools" In-Reply-To: <4c020680$0$1581$742ec2ed@news.sonic.net> References: <4c020680$0$1581$742ec2ed@news.sonic.net> Message-ID: On Sun, May 30, 2010 at 3:56 PM, John Nagle wrote: > ? MySQLdb won't install as non-root on Python 2.6 because > its "setup.py" file requires "setuptools". ?"setuptools", > unlike "distutils", isn't part of the Python 2.6 distribution. > > ? IMPORTANT PACKAGES SHOULD NOT USE "setuptools". ?Use the > standard "distutils". ?"setuptools" and "eggs" create more > problems than they solve. ?"setuptools" has many built-in > assumptions about where things are supposed to be, and they're > usually wrong. Yes, setuptools is often a pain. The magic incantation you want is something like python setup.py install --prefix=someprefix --single-version-externally-managed --record=/dev/null. I myself have a small script which detects whether setup.py uses setuptools or not, and add the necessary options in setuptools case for a sane behavior. David From alfps at start.no Sun May 30 11:21:32 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 30 May 2010 17:21:32 +0200 Subject: GUI programs In-Reply-To: References: Message-ID: * jyoung79 at kc.rr.com, on 30.05.2010 03:13: > Just curious if anyone would be willing to share their thoughts > about different Python GUI programming modules. I've been > doing a bit of research and am trying to find something that: > > 1. Is portable. Would like to be able to send the module along > with the main python file that would be able to run a GUI > window. Would be sending this to multiple machines. > Currently I'd like it to work on OS X machines, but it'd be nice > if it worked on Windows machines, etc. Probably be using > Python 2.5 or 2.6. > > 2. Can show an image (that is zoomable) as well as add GUI > controls like text fields, popup menues, etc. as well as send > information back to the program from the text fields, etc. > For now, I'm really looking for something that can display > EPS (postscript) and PDF images. A GUI library may contain such functionality, but it's more properly the domain of a special purpose library. The question then boils down to which GUI libraries your image/rich text library is compatible with. Perhaps if someone else has handled that combination they'll chime in. Cheers & hth., - Alf PS: Tkinter on its own does not provide image resizing and does not on its own support common image formats like JPEG or PNG (it does support GIF). For Tkinter I think you can do that by adding the PIL library, if I remember the name correctly. But as far as I know PIL doesn't yet support Python 3.x, and doesn't support EPS or PDF, which are not image formats but rich text formats. -- blog at From sitecontactus at gmail.com Sun May 30 12:13:02 2010 From: sitecontactus at gmail.com (pythonista) Date: Sun, 30 May 2010 09:13:02 -0700 (PDT) Subject: strptime dilemma with Python 2.5 Message-ID: Hello, I have a date string looking like the following: "Sun May 30 07:25:17 2010" With Python 2.6, the %f is supported (it parses the microseconds), so that this statement works: dt = datetime.strptime(s, "%a %b %d %H:%M:%f %Y") However, with Python 2.5, (which is supported on the live Webfaction server I'm using), %f is not supported. Is there a straightforward way to simply ignore the :17 microseconds in the original string? Maybe force it to "00" ? - but without having to actually change the original string by removing the ":17" ? If I simply leave out the ":%f" in the strptime call, I get back a " ValueError: time data did not match format: data=Sun May 30 19:33:54 2010 fmt=%a %b %d %H:%M %Y Hoping for a simple solution that someone is familiar with Thanks Steve From nagle at animats.com Sun May 30 12:49:35 2010 From: nagle at animats.com (John Nagle) Date: Sun, 30 May 2010 09:49:35 -0700 Subject: MySQLdb install vs. "setuptools" In-Reply-To: References: <4c020680$0$1581$742ec2ed@news.sonic.net> Message-ID: <4c029178$0$1592$742ec2ed@news.sonic.net> David Cournapeau wrote: > On Sun, May 30, 2010 at 3:56 PM, John Nagle wrote: >> MySQLdb won't install as non-root on Python 2.6 because >> its "setup.py" file requires "setuptools". "setuptools", >> unlike "distutils", isn't part of the Python 2.6 distribution. >> >> IMPORTANT PACKAGES SHOULD NOT USE "setuptools". Use the >> standard "distutils". "setuptools" and "eggs" create more >> problems than they solve. "setuptools" has many built-in >> assumptions about where things are supposed to be, and they're >> usually wrong. > > Yes, setuptools is often a pain. > > The magic incantation you want is something like python setup.py > install --prefix=someprefix --single-version-externally-managed > --record=/dev/null. I myself have a small script which detects whether > setup.py uses setuptools or not, and add the necessary options in > setuptools case for a sane behavior. > > David The "setup.py" file for MySQLdb has, as its first Python line, "from setuptools import ...". No combination of options will get around that. John Nagle From nagle at animats.com Sun May 30 13:10:00 2010 From: nagle at animats.com (John Nagle) Date: Sun, 30 May 2010 10:10:00 -0700 Subject: MySQLdb install vs. "setuptools" In-Reply-To: References: <4c020680$0$1581$742ec2ed@news.sonic.net> Message-ID: <4c029641$0$1619$742ec2ed@news.sonic.net> Antoine Pitrou wrote: > Really, this shouldn't happen if you really are using a > non-root version of Python: > >> [Errno 2] No such file or directory: >> '/usr/local/lib/python2.6/site-packages/test-easy-install-22015.write-test' > > I don't think setuptools is dumb enough to hardcode things like > "/usr/local/lib/python2.6/", so the error is probably yours here. > Perhaps you should double-check you did everything fine before posting > such a rant. > > Of course, if by "freshly-built version of Python", you mean you didn't > run "make install" in any way, then it's your problem. Give > "./configure" an appropriate non-root prefix and don't forget to run > "make install" at the end. Actually, a "built" but "uninstalled" Python works fine. If it didn't, "make test" wouldn't work. "sys.path" correctly points to the library directories created during "build". On the other hand, options to "./configure" apparently don't work right in Python 2.6 through 3.x. "--libdir" and "--bindir" don't actually do anything. See "http://bugs.python.org/issue858809" (an open bug). So custom "configure" is currently broken. The real problem here remains the unnecessary use of "setuptools". It's Debian distro policy not to use "setuptools": http://www.debian.org/doc/packaging-manuals/python-policy/ap-packaging_tools.html Also read "Setuptools is not a decent software package management". http://workaround.org/easy-install-debian The fundamental problem is that "setuptools" is more than an installer but less than a widely-supported system-wide package manager like "yum". Now, how to get the dependency on "setuptools" out of MySQLdb? John Nagle From candide at free.invalid Sun May 30 13:38:23 2010 From: candide at free.invalid (candide) Date: Sun, 30 May 2010 19:38:23 +0200 Subject: Address of an immutable object Message-ID: <4c02a295$0$22392$426a74cc@news.free.fr> Suppose a Python program defines an integer object with value 42. The object has an "address" we can capture with the built-in function id() : >>> a=42 >>> id(a) 152263540 >>> Now I was wondering if any integer object with value 42 will be refered at the same adress with the above id. Some experiments tend to show that it may be the case, for instance : >>> a=42 >>> id(a) 152263540 >>> id(42) 152263540 >>> b=2*21 >>> id(b) 152263540 >>> c=0b101010 >>> id(c) 152263540 >>> d={"foo":42, "bar":"foo"} >>> id(d["foo"]) 152263540 >>> L=["foo",(51,([14,42],5)),"bar"] >>> id(L[1][1][0][1]) 152263540 >>> del a >>> id(L[1][1][0][1]) 152263540 >>> zzz=range(1000) >>> id(zzz[42]) 152263540 >>> Even you can't make a deep copy : >>> from copy import deepcopy >>> a=42 >>> from copy import deepcopy >>> z=deepcopy(a) >>> id(a), id(z) (152263540, 152263540) >>> So is the following true : Two non mutable objects with the same value shall be allocated at a constant and unique address ? From python at mrabarnett.plus.com Sun May 30 13:39:55 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 30 May 2010 18:39:55 +0100 Subject: strptime dilemma with Python 2.5 In-Reply-To: References: Message-ID: <4C02A2EB.6000400@mrabarnett.plus.com> pythonista wrote: > Hello, > I have a date string looking like the following: > > "Sun May 30 07:25:17 2010" > > With Python 2.6, the %f is supported (it parses the microseconds), so > that this statement works: > > dt = datetime.strptime(s, "%a %b %d %H:%M:%f %Y") > > However, with Python 2.5, (which is supported on the live Webfaction > server I'm using), %f is not supported. > > Is there a straightforward way to simply ignore the :17 microseconds > in the original string? > > Maybe force it to "00" ? - but without having to actually change the > original string by removing the ":17" ? > > If I simply leave out the ":%f" in the strptime call, I get back a " > ValueError: time data did not match format: data=Sun May 30 > 19:33:54 2010 fmt=%a %b %d %H:%M %Y > > > Hoping for a simple solution that someone is familiar with The date string looks like it has hours, minutes and seconds, not hours, minutes and microseconds. From alfps at start.no Sun May 30 13:44:09 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 30 May 2010 19:44:09 +0200 Subject: Address of an immutable object In-Reply-To: <4c02a295$0$22392$426a74cc@news.free.fr> References: <4c02a295$0$22392$426a74cc@news.free.fr> Message-ID: * candide, on 30.05.2010 19:38: > Suppose a Python program defines an integer object with value 42. The > object has an "address" we can capture with the built-in function id() : > > >>> a=42 > >>> id(a) > 152263540 > >>> > > Now I was wondering if any integer object with value 42 will be refered > at the same adress with the above id. > > Some experiments tend to show that it may be the case, for instance : > > >>> a=42 > >>> id(a) > 152263540 > >>> id(42) > 152263540 > >>> b=2*21 > >>> id(b) > 152263540 > >>> c=0b101010 > >>> id(c) > 152263540 > >>> d={"foo":42, "bar":"foo"} > >>> id(d["foo"]) > 152263540 > >>> L=["foo",(51,([14,42],5)),"bar"] > >>> id(L[1][1][0][1]) > 152263540 > >>> del a > >>> id(L[1][1][0][1]) > 152263540 > >>> zzz=range(1000) > >>> id(zzz[42]) > 152263540 > >>> > > Even you can't make a deep copy : > > > >>> from copy import deepcopy > >>> a=42 > >>> from copy import deepcopy > >>> z=deepcopy(a) > >>> id(a), id(z) > (152263540, 152263540) > >>> > > So is the following true : > > Two non mutable objects with the same value shall be allocated at a > constant and unique address ? No. First, id() doesn't generally provide an address. It does that in CPython, but more generally it just provides a unique integer identifying the reference. You can think of it as the "reference value" if you want; it's what's copied by an assignment to a variable. Second, the reason that you get the same id for various 42 objects is that CPython uses a cache of "small integer" objects. As I recall the cache ranges from -5 to some 127 or so (or perhaps it was double that). Any value outside that cached range you'll see different id's for the same value. Cheers & hth., - Alf -- blog at From simon at brunningonline.net Sun May 30 14:36:21 2010 From: simon at brunningonline.net (Simon Brunning) Date: Sun, 30 May 2010 19:36:21 +0100 Subject: Address of an immutable object In-Reply-To: <4c02a295$0$22392$426a74cc@news.free.fr> References: <4c02a295$0$22392$426a74cc@news.free.fr> Message-ID: On 30 May 2010 18:38:23 UTC+1, candide wrote: > Two non mutable objects with the same value shall be allocated at a constant and unique address ? Nope. >>> a = 999 >>> b = 999 >>> id(a) == id(b) False Your statement will be the case for small integers, but this in an implementation detail. Indeed, this used to be the case for integers up to 100 (IIRC) or thereabouts, but it's now the case up to 256: >>> a = 256 >>> b = 256 >>> id(a) == id(b) True >>> a = 257 >>> a = 257 >>> id(a) == id(b) False Some identifier-like strings are also interned like this: >>> a = 'foo' >>> b = 'foo' >>> id(a) == id(b) True >>> a = 'two words' >>> b = 'two words' >>> id(a) == id(b) False But again, it's an implementation detail, and shouldn't be relied upon. This same issue also comes up with people noticing that they can compare small integers with the 'is' operator, and getting a surprise when bigger numbers come along: >>> a = 256 >>> b = 256 >>> a is b True >>> a = 257 >>> b = 257 >>> a is b False -- Cheers, Simon B. From nagle at animats.com Sun May 30 14:56:22 2010 From: nagle at animats.com (John Nagle) Date: Sun, 30 May 2010 11:56:22 -0700 Subject: MySQLdb install vs. "setuptools" In-Reply-To: <4c029178$0$1592$742ec2ed@news.sonic.net> References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029178$0$1592$742ec2ed@news.sonic.net> Message-ID: <4c02af2f$0$1597$742ec2ed@news.sonic.net> John Nagle wrote: > David Cournapeau wrote: >> On Sun, May 30, 2010 at 3:56 PM, John Nagle wrote: >>> MySQLdb won't install as non-root on Python 2.6 because >>> its "setup.py" file requires "setuptools". "setuptools", >>> unlike "distutils", isn't part of the Python 2.6 distribution. >>> >>> IMPORTANT PACKAGES SHOULD NOT USE "setuptools". Use the >>> standard "distutils". "setuptools" and "eggs" create more >>> problems than they solve. "setuptools" has many built-in >>> assumptions about where things are supposed to be, and they're >>> usually wrong. I tried this change on MySQLdb's "setup.py": diff setup.py setup-nodistutils.py 5c5 < from setuptools import setup, Extension --- > from distutils.core import setup, Extension The build then runs. The resulting MySQLdb runs under the uninstalled Python and connects to the database properly. There's no need for "setuptools" here at all. It just gets in the way. John Nagle From martin at hvidberg.net Sun May 30 14:58:29 2010 From: martin at hvidberg.net (Martin Hvidberg) Date: Sun, 30 May 2010 20:58:29 +0200 Subject: Returning value from home made unit - how to? Message-ID: Dear A may-bee beginner?s question I have a Python program, which has until now, been running in command line mode only. I wish to add a GUI. I would like to develop (and maintain) the GUI part in a separate module, i.e. in its own .py file, and then ?import? that into the old main program. I jumped into wxPython, as it seems to be the right GUI for me, and downloaded some examples that I took apart and joined. Now the basic GUI is running, though neither beautiful nor complete. The main task for my GUI is to allow the user to point to an input file. It can now obtain a filename from a file selection dialog, but I can?t figure out how to get the filename, i.e. the string variable containing the file name, send back to the main program I attach the two .py files hereunder. My question is: How do I get the information from variable strSequenceFile, back to the main module in file jacxl.py ? Best Regards Martin Hvidberg # ====== File jacxl.py ============= import jacXlgui if __name__ == "__main__": print "Hello World - from Main"; result = jacXlgui.app.MainLoop() print 'Result:',result # ====== End of jacxl.py ============= # ====== File jacXlgui.py ============= #---------------------------------------------------------------------- # A very simple wxPython GUI. # To go with JakXl.py #---------------------------------------------------------------------- import wx, os class JacXlFrame(wx.Frame): """ This is a Frame. It just shows a few controls on a wxPanel, and has a simple menu. """ def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, pos=(150, 150), size=(350, 350)) # Create the menubar menuBar = wx.MenuBar() # and some menus filemenu = wx.Menu() helpmenu = wx.Menu() # add an item to the menu filemenu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Leave without running anything ...") helpmenu.Append(wx.ID_ABOUT, "&About"," Information about this program") # bind the menu event to an event handler self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT) self.Bind(wx.EVT_MENU, self.OnShowAbout, id=wx.ID_ABOUT) # and put the menu on the menubar menuBar.Append(filemenu, "&File") menuBar.Append(helpmenu, "&Help") self.SetMenuBar(menuBar) # Status bar self.CreateStatusBar() # Now create the Panel to put the other controls on. panel = wx.Panel(self) # A text... text = wx.StaticText(panel, -1, "Please select a \"Sequence\" file") text.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)) # , wx.BOLD text.SetSize(text.GetBestSize()) # Where is the Sequence file ? self.txcI = wx.TextCtrl(panel, -1, "", size=(300, -1)) # Some buttons btnFileFind = wx.Button(panel, -1, "Browse for file") btnClose = wx.Button(panel, -1, "Exit") btnRun = wx.Button(panel, -1, "Run") # bind the button events to handlers self.Bind(wx.EVT_BUTTON, self.OnFindFileButton, btnFileFind) self.Bind(wx.EVT_BUTTON, self.OnRunButton, btnRun) self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, btnClose) # Use a sizer to layout the controls, stacked vertically and with # a 10 pixel border around each sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(text, 0, wx.ALL, 10) sizer.Add(self.txcI, 0, wx.ALL, 10) sizer.Add(btnFileFind, 0, wx.ALL, 10) sizer.Add(btnRun, 0, wx.ALL, 10) sizer.Add(btnClose, 0, wx.ALL, 10) panel.SetSizer(sizer) panel.Layout() def OnFindFileButton(self, evt): strReturn = '' wildcard = "Sequence Log (*.LOG)|*.LOG|" \ "All files (*.*)|*.*" dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", wildcard, wx.OPEN) if dialog.ShowModal() == wx.ID_OK: strSequenceFile = dialog.GetPath() self.txcI.ChangeValue(strSequenceFile) # Copying filename to text box dialog.Destroy() print 'Found file:',strSequenceFile return strSequenceFile def OnShowAbout(self, evt): print "About this program ..." def OnRunButton(self, evt): """Event handler for the button click.""" print 'Run :',self.txcI.GetValue() return self.txcI.GetValue() def OnTimeToClose(self, evt): """Event handler for the button click.""" print "See ya later!" self.Close() class JacXlApp(wx.App): def OnInit(self): frame = JacXlFrame(None, "JacXl - converting ... to eXcel") self.SetTopWindow(frame) print "Print statements go to this stdout window by default." frame.Show(True) return True app = JacXlApp(redirect=False) # ====== End of jacXlgui.py ============= From kaklis at gmail.com Sun May 30 15:07:04 2010 From: kaklis at gmail.com (kaklis at gmail.com) Date: Sun, 30 May 2010 12:07:04 -0700 (PDT) Subject: Threads with Cmd and socket server combination Message-ID: hi, I have implement a command line app using Python's cmd library module and it works fine. I 've also create a simple threaded socket server. How can i merge the two ones, so that the console app, is also a listening server? How can i achieve that with threads? I'm trying for days and i can't make it work! I know it can be done with Twisted but i want to understand how thread works. The console: class BM(CmdBase): """Simple custom command processor""" def do_acmd(self): pass if __name__ == '__main__': BM().cmdloop() and the Server: class MyClientHandler(SocketServer.BaseRequestHandler): def handle(self): pass server = SocketServer.ThreadingTCPServer(myaddr, MyClientHandler) server.serve_forever( ) Thanks in advance Threads can be so difficult A.K. From cjwilliams43 at gmail.com Sun May 30 15:10:23 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Sun, 30 May 2010 15:10:23 -0400 Subject: if, continuation and indentation In-Reply-To: References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> Message-ID: <4C02B81F.20509@gmail.com> On 30-May-10 01:50 AM, Nathan Rice wrote: > I prefer to just break such things into multiple lines. You're doing > that already anyhow, it's not much of a speed hit, and it makes exactly > what you're testing explicit. If I break a statement onto multiple > lines I only use parenthesis, and that is as a last resort. In my > opinion there's almost always some combination of variable assignments > and lambda expressions that uses fewer lines and is clearer. > > is_correct_style = width == 0 and height == 0 and color == 'red' > if (is_correct_style and emphasis == 'strong') or highlight > 100: > > > On Sat, May 29, 2010 at 8:59 PM, Mark Lawrence > wrote: > > On 30/05/2010 01:23, john wrote: > > On May 28, 10:37 am, "Colin J. Williams" > > wrote: > > On 28-May-10 05:54 AM, Jonathan Hartley wrote: > > On May 27, 1:57 pm, Jean-Michel > Pichavant > > wrote: > > HH wrote: > > I have a question about best practices when it > comes to line wrapping/ > continuation and indentation, specifically in > the case of an if > statement. > > > When I write an if statement with many > conditions, I prefer to use a > parenthesis around the whole block and get the > implicit continuation, > rather than ending each line with an escape > character. Thus, using > the example from the style guide > (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100): > raise ValueError("sorry, you lose") > > > The problem should be obvious -- it's not easy > to see where the > conditional ends and the statement begins since > they have the same > indentation. Part of the problem, I suppose, is > that Emacs indents > 'height' and the other lines in the conditional > to 4 spaces (because > of the parenthesis). How do people deal with > this situation? > > > Thanks, > Henrik > > > One possible solution > > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100 > ): > raise ValueError("sorry, you lose") > > > JM > > > I've always liked this, or even: > > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100 > ): > raise ValueError("sorry, you lose") > > > but my co-workers have uniformly gone bananas whenever I > try it. > > > I liked: > > On 27-May-10 08:48 AM, Xavier Ho wrote: > > On 27 May 2010 22:22, HH > >> wrote: > > > > > if (width == 0 and > > height == 0 and > > color == 'red' and > > emphasis == 'strong' or > > highlight> 100): > > raise ValueError("sorry, you lose") > > > > > > I've gotta say - I've bumped into this problem before, > and I'm sure many > > other have - this is a valid question. It just hasn't > bothered me enough > > to ask... > > > > Correct me if I'm wrong, but I think the following is > equivalent, and > > looks better. Although this won't fix all ugly cases in > that problem.. > > > > if (width, height, color, emphasis) == (0, 0, 'red', > 'strong') or > > highlight> 100: > > raise ValueError("sorry, you lose") > > > > Cheers, > > Xav > > but nobody commented. > > Colin W. > > > Colin: > Sure, you can do it that way. IMO, though, the OP was wrong, > and so > is the PEP. Source code is meant to communicate. So it must > transmit > the correct information to the computer; it also must inform your > coworkers. That means that you have a responsibility to care what > they think, though you privately have your opinions. Another reason > the PEP is faulty in this circumstance is that a misplaced > backslash, > or a missing one, is easily found and fixed. A misplaced > parentheses, > or just one of a pair, will transform your source code into > something > which may compile and then give faulty results: a disaster. > So keep it simple, and make it legible. > Yours, > John > > > IMHO complete garbage, if your editor doesn't show misplaced or > missing parenthesis by highlighting you're using the wrong editor :) > > Regards. > > Mark Lawrence. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Perhaps the arrangement below shows the matching a little better than the Xav suggestion. The main point is that, to me, the tuple shows the item by item matching better than a series of and clauses: # tif.py (width, height, color, emphasis)= 0, 0, 'red', 'strong' highlight= 99 if (width, height, color, emphasis) == \ ( 0, 0, 'red', 'strong') or highlight> 100: raise ValueError("sorry, you lose") Colin W. From cjwilliams43 at gmail.com Sun May 30 15:10:23 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Sun, 30 May 2010 15:10:23 -0400 Subject: if, continuation and indentation In-Reply-To: References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> Message-ID: <4C02B81F.20509@gmail.com> On 30-May-10 01:50 AM, Nathan Rice wrote: > I prefer to just break such things into multiple lines. You're doing > that already anyhow, it's not much of a speed hit, and it makes exactly > what you're testing explicit. If I break a statement onto multiple > lines I only use parenthesis, and that is as a last resort. In my > opinion there's almost always some combination of variable assignments > and lambda expressions that uses fewer lines and is clearer. > > is_correct_style = width == 0 and height == 0 and color == 'red' > if (is_correct_style and emphasis == 'strong') or highlight > 100: > > > On Sat, May 29, 2010 at 8:59 PM, Mark Lawrence > wrote: > > On 30/05/2010 01:23, john wrote: > > On May 28, 10:37 am, "Colin J. Williams" > > wrote: > > On 28-May-10 05:54 AM, Jonathan Hartley wrote: > > On May 27, 1:57 pm, Jean-Michel > Pichavant > > wrote: > > HH wrote: > > I have a question about best practices when it > comes to line wrapping/ > continuation and indentation, specifically in > the case of an if > statement. > > > When I write an if statement with many > conditions, I prefer to use a > parenthesis around the whole block and get the > implicit continuation, > rather than ending each line with an escape > character. Thus, using > the example from the style guide > (http://www.python.org/dev/peps/ > pep-0008/) I would write: > > > if (width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100): > raise ValueError("sorry, you lose") > > > The problem should be obvious -- it's not easy > to see where the > conditional ends and the statement begins since > they have the same > indentation. Part of the problem, I suppose, is > that Emacs indents > 'height' and the other lines in the conditional > to 4 spaces (because > of the parenthesis). How do people deal with > this situation? > > > Thanks, > Henrik > > > One possible solution > > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100 > ): > raise ValueError("sorry, you lose") > > > JM > > > I've always liked this, or even: > > > if ( > width == 0 and > height == 0 and > color == 'red' and > emphasis == 'strong' or > highlight> 100 > ): > raise ValueError("sorry, you lose") > > > but my co-workers have uniformly gone bananas whenever I > try it. > > > I liked: > > On 27-May-10 08:48 AM, Xavier Ho wrote: > > On 27 May 2010 22:22, HH > >> wrote: > > > > > if (width == 0 and > > height == 0 and > > color == 'red' and > > emphasis == 'strong' or > > highlight> 100): > > raise ValueError("sorry, you lose") > > > > > > I've gotta say - I've bumped into this problem before, > and I'm sure many > > other have - this is a valid question. It just hasn't > bothered me enough > > to ask... > > > > Correct me if I'm wrong, but I think the following is > equivalent, and > > looks better. Although this won't fix all ugly cases in > that problem.. > > > > if (width, height, color, emphasis) == (0, 0, 'red', > 'strong') or > > highlight> 100: > > raise ValueError("sorry, you lose") > > > > Cheers, > > Xav > > but nobody commented. > > Colin W. > > > Colin: > Sure, you can do it that way. IMO, though, the OP was wrong, > and so > is the PEP. Source code is meant to communicate. So it must > transmit > the correct information to the computer; it also must inform your > coworkers. That means that you have a responsibility to care what > they think, though you privately have your opinions. Another reason > the PEP is faulty in this circumstance is that a misplaced > backslash, > or a missing one, is easily found and fixed. A misplaced > parentheses, > or just one of a pair, will transform your source code into > something > which may compile and then give faulty results: a disaster. > So keep it simple, and make it legible. > Yours, > John > > > IMHO complete garbage, if your editor doesn't show misplaced or > missing parenthesis by highlighting you're using the wrong editor :) > > Regards. > > Mark Lawrence. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Perhaps the arrangement below shows the matching a little better than the Xav suggestion. The main point is that, to me, the tuple shows the item by item matching better than a series of and clauses: # tif.py (width, height, color, emphasis)= 0, 0, 'red', 'strong' highlight= 99 if (width, height, color, emphasis) == \ ( 0, 0, 'red', 'strong') or highlight> 100: raise ValueError("sorry, you lose") Colin W. From cjwilliams43 at gmail.com Sun May 30 15:20:43 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Sun, 30 May 2010 15:20:43 -0400 Subject: GUI programs In-Reply-To: References: <20100530011322.HBM34.9984.root@cdptpa-web23-z02> Message-ID: On 30-May-10 08:22 AM, Philip Semanchuk wrote: > > On May 29, 2010, at 9:13 PM, > wrote: > >> Just curious if anyone would be willing to share their thoughts >> about different Python GUI programming modules. I've been >> doing a bit of research and am trying to find something that: >> >> 1. Is portable. Would like to be able to send the module along >> with the main python file that would be able to run a GUI >> window. Would be sending this to multiple machines. >> Currently I'd like it to work on OS X machines, but it'd be nice >> if it worked on Windows machines, etc. Probably be using >> Python 2.5 or 2.6. > > Hi Jay, > wxPython, pyQT and Tkinter are all portable in that they'll run under OS > X, Windows, Gnome and KDE. Getting them installed there in some sane > fashion is another matter. There are programs like py2exe and py2app > that you've found, but Python doesn't lend itself to being bundled this > way. It can work, but may be a fair amount of trouble depending on what > modules you're trying to use and how diverse your target machines are. > >> 6. TkInter - Does this module come standard on all machines >> that have Python? Haven't worked with this one much, but if I >> send Python code to other machines would TkInter work? > > That's my understanding. I haven't used it. I gather that Tkinter is > useful in a pinch, but that it isn't appropriate for applications with > much more than a minimalist GUI. > >> Would love to hear anyones thoughts about GUI programming >> and what they use. Would also like to hear pros/cons with the >> different modules/apps. > > There's lots of discussion on this topic in the archives of this mailing > list and others. These modules haven't changed dramatically over the > past few years, so any recent-ish conversation is relevant. > > > Good luck > Philip > > PS - we use wxPython I am just starting with PyQt4. It has an IDE, Eric4, which seems flexible and is about to be fully geared up for Windows. There is also a Screen Designer, that I haven't used yet. Colin W. From sitecontactus at gmail.com Sun May 30 15:43:10 2010 From: sitecontactus at gmail.com (pythonista) Date: Sun, 30 May 2010 12:43:10 -0700 (PDT) Subject: strptime dilemma with Python 2.5 References: Message-ID: <48661a90-25ec-40e7-b1a6-d22f61476b90@p5g2000pri.googlegroups.com> You know why it looks like it has seconds and not microseconds? Because it does, and I'm on something. Thank you > > The date string looks like it has hours, minutes and seconds, not hours, > minutes and microseconds. From solipsis at pitrou.net Sun May 30 15:55:25 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 30 May 2010 21:55:25 +0200 Subject: MySQLdb install vs. "setuptools" References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029641$0$1619$742ec2ed@news.sonic.net> Message-ID: <20100530215525.6bb1b5ef@pitrou.net> On Sun, 30 May 2010 10:10:00 -0700 John Nagle wrote: > > Actually, a "built" but "uninstalled" Python works fine. > If it > didn't, "make test" wouldn't work. That's a completely unrelated thing. The main reason "make test" works with an uninstalled Python is simply so that the core developers' life is easier. It doesn't mean all Python functionalities work in that context. > On the other hand, options to "./configure" apparently don't work > right in Python 2.6 through 3.x. "--libdir" and "--bindir" don't actually > do anything. You can use "--prefix" instead, it works. > The real problem here remains the unnecessary use of "setuptools". No, again, the real problem is just that you are trying to install modules for an uninstalled Python. You may hate setuptools with a passion, but it's unconstructive and useless to put the blame on it without any solid argument. Do yourself a favour: pass the proper options to "./configure", and install Python. Regards Antoine. From candide at free.invalid Sun May 30 16:07:15 2010 From: candide at free.invalid (candide) Date: Sun, 30 May 2010 22:07:15 +0200 Subject: Address of an immutable object In-Reply-To: <4c02a295$0$22392$426a74cc@news.free.fr> References: <4c02a295$0$22392$426a74cc@news.free.fr> Message-ID: <4c02c57a$0$12648$426a74cc@news.free.fr> Thanks for your responses, I should do more experiments ! From candide at free.invalid Sun May 30 16:08:49 2010 From: candide at free.invalid (candide) Date: Sun, 30 May 2010 22:08:49 +0200 Subject: Address of an immutable object In-Reply-To: References: <4c02a295$0$22392$426a74cc@news.free.fr> Message-ID: <4c02c5d7$0$12648$426a74cc@news.free.fr> Alf P. Steinbach a ?crit : > * candide, on 30.05.2010 19:38: >> Suppose a Python program defines an integer object with value 42. The >> object has an "address" we can capture with the built-in function id() : > First, id() doesn't generally provide an address. I talked about a quote unquote "address" ;) but according to "The Python Language Reference" it's not very far from the truth : -------------------- 3.1 Objects, values and types (...) An object?s identity never changes once it has been created; you may think of it as the object?s _address_ in memory. The ?is? operator compares the identity of two objects; the id() function returns an integer representing its identity (currently implemented as its _address_). -------------------- (emphasizing is mine) From mmanns at gmx.net Sun May 30 17:11:56 2010 From: mmanns at gmx.net (Martin Manns) Date: Sun, 30 May 2010 23:11:56 +0200 Subject: xrange issue 7721 References: <20100529211241.56dc7bc4@Knock> Message-ID: <20100530231156.313d748c@Knock> On Sun, 30 May 2010 00:49:11 +0100 Mark Lawrence wrote: > From http://docs.python.org/dev/library/itertools.html > "Unlike regular slicing, islice() does not support negative values > for start, stop, or step." > > Rule 1 of programming never assume anything, particularly wrt > testing. I assume that you are ok with this. :) Dreadful I know :) Right, never post before reading the fine manual :) > > I found the msg97928 code pretty obvious when seeing the snippet. > > If you disagree you may consider re-opening the issue. > I trust that you get my point regarding the failure to raise a > ValueError :) Or am I wearing my extremely stupid hat today? Since you seem to find this issue important, are you going to re-open the issue? Cheers Martin From scalesjordan at gmail.com Sun May 30 17:45:44 2010 From: scalesjordan at gmail.com (prezjordan) Date: Sun, 30 May 2010 14:45:44 -0700 (PDT) Subject: GUI programs References: <20100530011322.HBM34.9984.root@cdptpa-web23-z02> Message-ID: <1eabbe7c-78d8-4cda-90f7-2e60b45a22e8@w3g2000vbd.googlegroups.com> How does GTK compare to Qt? From electronixtar at gmail.com Sun May 30 17:49:19 2010 From: electronixtar at gmail.com (est) Date: Sun, 30 May 2010 14:49:19 -0700 (PDT) Subject: What's the largest python/django powered website in the world? Message-ID: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> Hi list, just curious, what's the largest python powered website in the world? and what's the largest django powered website in the world? Is it disqus.com? From fetchinson at googlemail.com Sun May 30 18:09:00 2010 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 31 May 2010 00:09:00 +0200 Subject: What's the largest python/django powered website in the world? In-Reply-To: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> References: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> Message-ID: > just curious, what's the largest python powered website in the world? I'm afraid you'll need to define what you mean by "python powered". If the server side of a web application is written in 3 or more languages and one of them is python, does that count? If yes, then probably google and youtube are the "largest python powered websites". Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From solipsis at pitrou.net Sun May 30 18:11:45 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Mon, 31 May 2010 00:11:45 +0200 Subject: MySQLdb install vs. "setuptools" References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029641$0$1619$742ec2ed@news.sonic.net> <4c02de23$0$1603$742ec2ed@news.sonic.net> Message-ID: <20100531001145.73e16360@pitrou.net> On Sun, 30 May 2010 15:16:42 -0700 John Nagle wrote: > > It's nice that some of the options work. Note that someone who > used "--bindir", expecting it to work, might end up overwriting their > existing Python installation unintentionally, which would break system > administration tools like cPanel and "yum". Well, usually you don't type "sudo" unintentionally... > The ongoing low quality of Python distribution mechanisms, and the > denial of that fact, is a major part of why Python, after 20 years, is far > less available than Perl. "Far less available"? How so? > The latest production versions of Red Hat > Enterprise Linux and CentOS, the major server distributions, still ship > with Python 2.4.3, a five year old version of Python. And of course nothing in this is Python's or setuptools' fault, since it's just Redhat's policy, so I wonder what you're trying to tell us. (not to mention that it doesn't have anything to do with the original topic anymore, either) From nagle at animats.com Sun May 30 18:16:42 2010 From: nagle at animats.com (John Nagle) Date: Sun, 30 May 2010 15:16:42 -0700 Subject: MySQLdb install vs. "setuptools" In-Reply-To: References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029641$0$1619$742ec2ed@news.sonic.net> Message-ID: <4c02de23$0$1603$742ec2ed@news.sonic.net> Antoine Pitrou wrote: > On Sun, 30 May 2010 10:10:00 -0700 > John Nagle wrote: >> Actually, a "built" but "uninstalled" Python works fine. >> If it >> didn't, "make test" wouldn't work. > > That's a completely unrelated thing. The main reason "make test" works > with an uninstalled Python is simply so that the core developers' life > is easier. It doesn't mean all Python functionalities work in that > context. > >> On the other hand, options to "./configure" apparently don't work >> right in Python 2.6 through 3.x. "--libdir" and "--bindir" don't actually >> do anything. > > You can use "--prefix" instead, it works. It's nice that some of the options work. Note that someone who used "--bindir", expecting it to work, might end up overwriting their existing Python installation unintentionally, which would break system administration tools like cPanel and "yum". cPanel support recommends against installing a new Python other than through "yum". http://forums.cpanel.net/f5/mailman-breaks-stable-upcp-due-python-upgrade-126453.html http://forums.cpanel.net/f5/upgrade-python-whm-113593.html They don't trust other install mechanisms. With good cause. >> The real problem here remains the unnecessary use of "setuptools". > > No, again, the real problem is just that you are trying to install > modules for an uninstalled Python. > You may hate setuptools with a passion, but it's unconstructive and > useless to put the blame on it without any solid argument. > Do yourself a favour: pass the proper options to "./configure", and > install Python. > > Regardssetu > > Antoine. Having demonstrated in a previous post that 1) the use of "setuptools" was completely unnecessary, and 2) it's quite possible to load and use MySQLdb in an "uninstalled" Python, we can dismiss the above argument. The ongoing low quality of Python distribution mechanisms, and the denial of that fact, is a major part of why Python, after 20 years, is far less available than Perl. The latest production versions of Red Hat Enterprise Linux and CentOS, the major server distributions, still ship with Python 2.4.3, a five year old version of Python. John Nagle From mwilson at the-wire.com Sun May 30 18:22:04 2010 From: mwilson at the-wire.com (Mel) Date: Sun, 30 May 2010 18:22:04 -0400 Subject: Returning value from home made unit - how to? References: Message-ID: Martin Hvidberg wrote: > I have a Python program, which has until now, been running in command line > mode only. I wish to add a GUI. > > I would like to develop (and maintain) the GUI part in a separate module, > i.e. in its own .py file, and then ?import? that into the old main > program. > > I jumped into wxPython, as it seems to be the right GUI for me, and > downloaded some examples that I took apart and joined. Now the basic GUI > is running, though neither beautiful nor complete. > > The main task for my GUI is to allow the user to point to an input file. > It can now obtain a filename from a file selection dialog, but I can?t > figure out how to get the filename, i.e. the string variable containing > the file name, send back to the main program > > I attach the two .py files hereunder. > > My question is: > How do I get the information from variable strSequenceFile, back to the > main module in file jacxl.py ? AFAIK, typically, you don't -- the way it is here. Returning a value from a Button handler, or any event handler generally, won't have any effect. The event handlers are called from deep in wx code by routines that don't deal with anything specific to the data-processing side of the program. What I think you might do is to make strSequenceFile an attribute of your Frame, so that OnFindFile button does ``self.strSequenceFile = dialog.GetPath()'' rather than returning that value. Then your main level can do ``jacXlgui.app.GetTopWindow().strSequenceFile'' . There are probably refinements to be added to this, but I think it's a good beginning strategy. The first new place I would take the whole program would be to remove the command-line controls from the command line program, so you're left with a sort of "business model" that contains only the data processing. Then you can write a new GUI program based on jacXlgui that imports the data processing module and calls computations and reports results from the model. Mel. From cournape at gmail.com Sun May 30 18:49:40 2010 From: cournape at gmail.com (David Cournapeau) Date: Mon, 31 May 2010 07:49:40 +0900 Subject: MySQLdb install vs. "setuptools" In-Reply-To: <4c02de23$0$1603$742ec2ed@news.sonic.net> References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029641$0$1619$742ec2ed@news.sonic.net> <4c02de23$0$1603$742ec2ed@news.sonic.net> Message-ID: On Mon, May 31, 2010 at 7:16 AM, John Nagle wrote: > ? ?It's nice that some of the options work. ?Note that someone who > used "--bindir", expecting it to work, might end up overwriting their > existing Python installation unintentionally, which would break system > administration tools like cPanel and "yum". > > ? ?cPanel support recommends against installing a new Python other > than through "yum". > > http://forums.cpanel.net/f5/mailman-breaks-stable-upcp-due-python-upgrade-126453.html > http://forums.cpanel.net/f5/upgrade-python-whm-113593.html > > ? ?They don't trust other install mechanisms. ?With good cause. This has absolutely nothing to do with how python is installed. It is common sense that you should upgrade an installed package through the package manager mechanism (here yum), and is true for any software, python or not. >?The latest production versions of Red Hat > Enterprise Linux and CentOS, the major server distributions, still ship > with Python 2.4.3, a five year old version of Python. Yes, by definition RHEL ships softwares that does not change for a long time. By your argument, the linux kernel and gcc are broken because they are 4 years old on RHEL 5 (linux 2.6.18. gcc 4.0.*). That does not make any sense. cheers, David From martin at v.loewis.de Sun May 30 18:54:16 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 31 May 2010 00:54:16 +0200 Subject: xrange issue 7721 In-Reply-To: References: Message-ID: <4C02EC98.9020507@v.loewis.de> > Assuming that I am correct, can I create myself a login on the bugs > tracker and re-open the issue to get this sorted? Definitely not. The issue you are looking at has been fixed; whatever your issue is (you didn't state it clearly), it must be a different one. So if you are going to report anything, please submit a new bug report instead. For the record, the issue you were looking at was a complaint that the documentation is incorrect. This had been fixed by correcting the documentation. Please structure bug reports as follows: 1. this is what you did 2. this is what happened 3. this is what you had expected/wanted to happen instead Regards, Martin From benjamin.kaplan at case.edu Sun May 30 18:57:17 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 30 May 2010 15:57:17 -0700 Subject: MySQLdb install vs. "setuptools" In-Reply-To: <4c02de23$0$1603$742ec2ed@news.sonic.net> References: <4c020680$0$1581$742ec2ed@news.sonic.net> <4c029641$0$1619$742ec2ed@news.sonic.net> <4c02de23$0$1603$742ec2ed@news.sonic.net> Message-ID: On Sun, May 30, 2010 at 3:16 PM, John Nagle wrote: > Antoine Pitrou wrote: > >> On Sun, 30 May 2010 10:10:00 -0700 >> John Nagle wrote: >> >>> Actually, a "built" but "uninstalled" Python works fine. >>> If it >>> didn't, "make test" wouldn't work. >>> >> >> That's a completely unrelated thing. The main reason "make test" works >> with an uninstalled Python is simply so that the core developers' life >> is easier. It doesn't mean all Python functionalities work in that >> context. >> > > > >> On the other hand, options to "./configure" apparently don't work >>> right in Python 2.6 through 3.x. "--libdir" and "--bindir" don't >>> actually >>> do anything. >>> >> >> You can use "--prefix" instead, it works. >> > > It's nice that some of the options work. Note that someone who > used "--bindir", expecting it to work, might end up overwriting their > existing Python installation unintentionally, which would break system > administration tools like cPanel and "yum". > > cPanel support recommends against installing a new Python other > than through "yum". > > > http://forums.cpanel.net/f5/mailman-breaks-stable-upcp-due-python-upgrade-126453.html > http://forums.cpanel.net/f5/upgrade-python-whm-113593.html > > They don't trust other install mechanisms. With good cause. > > The real problem here remains the unnecessary use of "setuptools". >>> >> >> No, again, the real problem is just that you are trying to install >> modules for an uninstalled Python. >> You may hate setuptools with a passion, but it's unconstructive and >> useless to put the blame on it without any solid argument. >> Do yourself a favour: pass the proper options to "./configure", and >> install Python. >> >> Regardssetu >> >> Antoine. >> > > Having demonstrated in a previous post that 1) the use of "setuptools" > was completely unnecessary, and 2) it's quite possible to load and use > MySQLdb in an "uninstalled" Python, we can dismiss the above argument. > > The ongoing low quality of Python distribution mechanisms, and the > denial of that fact, is a major part of why Python, after 20 years, is far > less available than Perl. The latest production versions of Red Hat > Enterprise Linux and CentOS, the major server distributions, still ship > with Python 2.4.3, a five year old version of Python. > > John Nagle > > Based on a quick search, CentOS 5.5 ships with Perl 5.8.8. I would assume that it uses the same version as RHEL. Based on another quick search, Perl 5.8.8 shipped in February 2006, one month before Python 2.4.3. What does this have to do with distribution mechanisms again? And last time I checked, Python is now preinstalled on every OS worth speaking of except for Windows. Last time I checked, Perl was preinstalled on every OS worth speaking of except for Windows. With IronPython putting Python on the .NET Framework, one could argue that, if anything, Python is more available than Perl. Particularly if Microsoft ever gets around to giving IronPython and IronRuby first class status in Visual Studio. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun May 30 19:19:13 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 May 2010 23:19:13 GMT Subject: Address of an immutable object References: <4c02a295$0$22392$426a74cc@news.free.fr> <4c02c5d7$0$12648$426a74cc@news.free.fr> Message-ID: <4c02f271$0$14140$c3e8da3@news.astraweb.com> On Sun, 30 May 2010 22:08:49 +0200, candide wrote: > Alf P. Steinbach a ?crit : >> * candide, on 30.05.2010 19:38: >>> Suppose a Python program defines an integer object with value 42. The >>> object has an "address" we can capture with the built-in function id() >>> : > >> First, id() doesn't generally provide an address. > > I talked about a quote unquote "address" ;) but according to "The Python > Language Reference" it's not very far from the truth : > > -------------------- > 3.1 Objects, values and types > (...) > An object?s identity never changes > once it has been created; you may think of it as the object?s _address_ > in memory. The ?is? operator compares the identity of two objects; the > id() function returns an integer representing its identity (currently > implemented as its _address_). > -------------------- > > (emphasizing is mine) Which is a weakness of the documentation, since in Jython object ids are 1, 2, 3, 4, ... rather than addresses in memory. Of course, if you want to think of 1, 2, 3, 4, ... as addresses, who's going to stop you? :-) -- Steven From electronixtar at gmail.com Sun May 30 19:27:27 2010 From: electronixtar at gmail.com (est) Date: Sun, 30 May 2010 16:27:27 -0700 (PDT) Subject: What's the largest python/django powered website in the world? References: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> Message-ID: > I'm afraid you'll need to define what you mean by "python powered". Except database, presentation layer, major business logic is done by python. Except Google/youtube, what's next? From steve at REMOVE-THIS-cybersource.com.au Sun May 30 19:34:19 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 May 2010 23:34:19 GMT Subject: xrange issue 7721 References: <4C02EC98.9020507@v.loewis.de> Message-ID: <4c02f5fa$0$14140$c3e8da3@news.astraweb.com> On Mon, 31 May 2010 00:54:16 +0200, Martin v. Loewis wrote: >> Assuming that I am correct, can I create myself a login on the bugs >> tracker and re-open the issue to get this sorted? > > Definitely not. The issue you are looking at has been fixed; whatever > your issue is (you didn't state it clearly), it must be a different one. > So if you are going to report anything, please submit a new bug report > instead. > > For the record, the issue you were looking at was a complaint that the > documentation is incorrect. This had been fixed by correcting the > documentation. I think Mark's point is that the code snippet given isn't a full replacement for xrange, since it doesn't support negative step sizes, nor does it raise an exception on step=0. I can see why somebody might argue that the documentation is wrong. The given snippet *isn't* a replacement for xrange, but merely an example of how you might get xrange-like behaviour over a restricted domain. Since the docs are read by people with vastly different levels of experience, skill and nous, I think it's a reasonable complaint to make. I am sure that there will be plenty of people who will take the docs literally and be surprised when their code fails because the xrange replacement fails. I'd suggest fixing the docs to make it clear that the snippet is a simplified example rather than a replacement, rather than trying to complicate the snippet to cover all cases xrange deals with. In my opinion, all it takes is the addition of two words: If a larger range is needed, an alternate version can be crafted using the itertools module, for example: takewhile(lambda x: x References: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> Message-ID: On Mon, May 31, 2010 at 9:27 AM, est wrote: > Except Google/youtube, what's next? bitbucket (1) is mostly implemented in Python cheers James 1. http://bitbucket.org/ -- -- "Problems are solved by method" From benjamin.kaplan at case.edu Sun May 30 20:14:23 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 30 May 2010 17:14:23 -0700 Subject: What's the largest python/django powered website in the world? In-Reply-To: References: <3798c49c-6350-4766-81e5-1206a77c5786@42g2000prb.googlegroups.com> Message-ID: On Sun, May 30, 2010 at 4:27 PM, est wrote: > > > I'm afraid you'll need to define what you mean by "python powered". > > Except database, presentation layer, major business logic is done by > python. > > Except Google/youtube, what's next? > -- > http://mail.python.org/mailman/listinfo/python-list http://www.reddit.com http://github.com/reddit/reddit I believe they recently said that they're at 7.5 million users and 270 million page views per month. And the repo is 71% Python with most of the rest as Javascript. From pavlovevidence at gmail.com Sun May 30 21:31:11 2010 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 30 May 2010 18:31:11 -0700 (PDT) Subject: Py_single_input and the side-effects... References: <71e9afe5-f64e-4c2a-9c25-d814d13c7d46@t14g2000prm.googlegroups.com> Message-ID: <0d5415fc-d59b-42a2-99da-d1fd49c7a401@11g2000prv.googlegroups.com> On May 30, 3:17?am, moerchendiser2k3 wrote: > Hi, any idea? Python doesn't guarantee that objects will be deleted at a specific time. There are different reasons why an object might not be deleted. In command line mode Python keeps a reference to the most recent result. I don't know if it happens in general for any Py_single_input, but you could try to execute a few dummy commands with Py_single_input to see if it helps. But if you're relying on that behavior you really need to consider rethinking your problem. The only foolproof way to ensure that an object has been finalized is to do it manually (i.e., provide a finalize method to releases resources). Carl Banks From jyoung79 at kc.rr.com Sun May 30 23:29:55 2010 From: jyoung79 at kc.rr.com (jyoung79 at kc.rr.com) Date: Mon, 31 May 2010 3:29:55 +0000 Subject: GUI programs Message-ID: <20100531032955.CIMZB.277363.root@cdptpa-web08-z02> Just want to say thank you to all those who responded with their thoughts so far. Really appreciate you taking the time to share. This list has always been incredibly helpful and insightful! I do have another quick question. Has anyone had any luck getting PyGUI working on Snow Leopard? I can't seem to get the blobedit example to work. -- >> 1. wxPython - This looks very good, although I'm not sure >> how to set up portability with this. > I'm not sure what you mean by "set up portability". If you follow the > wxPython API documentation, then wxPython code is fairly portable. By portable, I mean I want to send code out to other machines (right now just OS X machines) that don't already have wxPython. It'd be nice to be able to package the appropriate module/library with my Python script. For example, I include the xlrd module and Python file inside of an AppleScript droplet which works perfect as a stand-alone droplet on numerous machines. -- >> Would love to hear anyones thoughts about GUI programming and what >> they use. Would also like to hear pros/cons with the different >> modules/apps. > This question comes up about once a week, so Google should be able > to find plenty of recent threads. I've been googling this subject for quite some time. Have found a lot of good results but would like to find more detail - especially more specific to displaying zoomable images like EPS, etc. From xcr4cx at googlemail.com Mon May 31 04:22:10 2010 From: xcr4cx at googlemail.com (christian schulze) Date: Mon, 31 May 2010 01:22:10 -0700 (PDT) Subject: Free chapter about Python and databases (MySQL and SQLite) References: <4BFFBA12.6050004@wildenhain.de> <75097175-6f22-4eaa-aa69-c93df86227c5@o4g2000vbo.googlegroups.com> Message-ID: <41f36471-cfeb-4fc9-9353-f0dd32c72687@j9g2000vbp.googlegroups.com> On 28 Mai, 18:09, Peter Otten <__pete... at web.de> wrote: > christian schulze wrote: > > On 28 Mai, 17:12, Sebastian Bassi wrote: > >> On Fri, May 28, 2010 at 9:41 AM, Tino Wildenhain > >> wrote: > >> > Did you consider adding a part dealing with postgresql too? > >> > (Especially interesting in the way you can write stored functions > >> > in python there) > > >> That is a good idea for the next version/edition. But meanwhile I > >> could write something in my blog atwww.py4bio.com > >> Best, > >> SB > > > Indeed a style like > >> user="root" > > is not that nice. > > > I had no look at the chapter but recommend you to read the PEP 8 - > > Python style guides (code conventions for python). > > > Imo a book have to be kinda exemplary. And bad style sucks anyway ... > > > PS: > >> user = 'root' or user = "root" > > ... would be much more beautyful. > > My crystal ball says that the post you are not quoting is concerned about > the security implications of accessing a database as the superuser rather > than about spaces surrounding the assignment operator. > > My crystal ball then starts nitpicking and adds that in the sample chapter > user="root" occurs within an argument list where its format is actually > required by the PEP: > > """ > - Don't use spaces around the '=' sign when used to indicate a > ? ? ? keyword argument or a default parameter value. > > ? ? ? Yes: > > ? ? ? ? ? def complex(real, imag=0.0): > ? ? ? ? ? ? ? return magic(r=real, i=imag) > """ > > Cheers, > Peter Oh, I'm sorry. As I said, i didn't even had a look on the chapter. I assumed it was a regular variable declaration. So just ignore what I said :P best regards From martin at v.loewis.de Mon May 31 04:22:35 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 31 May 2010 10:22:35 +0200 Subject: xrange issue 7721 In-Reply-To: <4c02f5fa$0$14140$c3e8da3@news.astraweb.com> References: <4C02EC98.9020507@v.loewis.de> <4c02f5fa$0$14140$c3e8da3@news.astraweb.com> Message-ID: <4C0371CB.401@v.loewis.de> >> For the record, the issue you were looking at was a complaint that the >> documentation is incorrect. This had been fixed by correcting the >> documentation. > > I think Mark's point is that the code snippet given isn't a full > replacement for xrange, since it doesn't support negative step sizes, nor > does it raise an exception on step=0. Still, that issue is different from 7721. 7721 was about a completely-nonworking example in the documentation. This error has been fully corrected. So this issue *is* fixed, reopining it would be inappropriate. There may be another issue with this example, which should be reported separately. > Since the docs are read by people with vastly different levels of > experience, skill and nous, I think it's a reasonable complaint to make. That may well be. The proposed approach (reopen the issue) is what I consider unreasonable. Regards, Martin From eric.brunel.pragmadev at gmail.com Mon May 31 04:55:17 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Mon, 31 May 2010 01:55:17 -0700 (PDT) Subject: GUI programs References: Message-ID: <871b2e6c-f716-4627-8bfb-888503cf1b1a@r9g2000vbk.googlegroups.com> On May 30, 5:21?pm, "Alf P. Steinbach" wrote: > PS: Tkinter on its own does not provide image resizing and does not on its own > support common image formats like JPEG or PNG (it does support GIF). "Native" PNG support in tcl/tk and hence Tkinter is planned for the next release (8.6), which is in beta stage, so should be official soon. From eric.brunel.pragmadev at gmail.com Mon May 31 05:07:09 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Mon, 31 May 2010 02:07:09 -0700 (PDT) Subject: tkinter function outout to text widget References: Message-ID: On May 29, 10:51?pm, Johan Lans wrote: > Hi > I'm totally new on python and I'm doing an assignement where I'm doing > a class that manipulates a text. The program is also supposed to have > a GUI, for which I have used tkinter. > So far I have entry widgets for file names and buttons, its all > working like I want it to. > What is missing is a way to output the changes to the text. I was > thinking that a text-widget would be suitable. Is there a reasonably > easy way to do this? > I tried inserting a string to the textwidget and letting the class > method change this string, but the inserted string isn't updated in > the text-widget. > Would be very happy for any hints. You won't be able to do exactly what you want with the text widget. There is a possibility to have to auto-updating in the GUI indeed, but it can only be made via other widgets than the text. Here is an example of what you can do: -------- from Tkinter import * root = Tk() var = StringVar() var.set('aaa') lbl = Label(root, textvariable=var) lbl.pack(side=LEFT) def next(): var.set(''.join(chr(ord(c) + 1) for c in var.get())) Button(root, text='Next', command=next).pack() root.mainloop() -------- As you can see, I'm using a Label here. This should be enough if the text you want to display is read-only. The Label will also adapt its size if there are several lines in your text. The biggest limitation is probably that you can't make it scrollable (not easily, at least?). HTH - Eric - From eric.brunel.pragmadev at gmail.com Mon May 31 05:16:14 2010 From: eric.brunel.pragmadev at gmail.com (eb303) Date: Mon, 31 May 2010 02:16:14 -0700 (PDT) Subject: Tkinter library reference References: Message-ID: <83599fd6-e654-47ec-87fd-33d8bb87eef8@k31g2000vbu.googlegroups.com> On May 29, 3:11?pm, Pradeep B wrote: > Do we have a standard reference library for Tkinter available? > > -- > Pradeep Short answer: no, at least not a complete one for Tkinter itself. However, there is a complete reference for tcl/tk here: http://www.tcl.tk/man/tcl8.5/ Once you're used to converting tcl/tk's commands and options into Tkinter classes and methods, it is the best one around. If you really need Python/Tkinter syntax, there are some good documents here: http://www.tkdocs.com/widgets/index.html http://effbot.org/tkinterbook/ But these are not complete or rather old. However, you can use them as a starting point before diving into the tcl/tk reference above. HTH - Eric - From astley.lejasper at gmail.com Mon May 31 05:24:43 2010 From: astley.lejasper at gmail.com (Astley Le Jasper) Date: Mon, 31 May 2010 02:24:43 -0700 (PDT) Subject: Creating a single list References: <4c012062$0$18987$4fafbaef@reader5.news.tin.it> Message-ID: On May 29, 4:10?pm, superpollo wrote: > Astley Le Jasper ha scritto: > > > > > This is probably a really silly question but, given the example code > > at the bottom, how would I get a single list? > > > What I currently get is: > > > ('id', 20, 'integer') > > ('companyname', 50, 'text') > > [('focus', 30, 'text'), ('fiesta', 30, 'text'), ('mondeo', 30, > > 'text'), ('puma', 30, 'text')] > > ('contact', 50, 'text') > > ('email', 50, 'text') > > > what I would like is: > > > ('id', 20, 'integer') > > ('companyname', 50, 'text') > > ('focus', 30, 'text'), > > ('fiesta', 30, 'text'), > > ('mondeo', 30, 'text'), > > ('puma', 30, 'text'), > > ('contact', 50, 'text') > > ('email', 50, 'text') > > > SAMPLE CODE>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > > def getproducts(): > > ? ? temp_list=[] > > ? ? product_list=['focus','fiesta','mondeo','puma'] #usually this > > would come from a db > > ? ? for p in product_list: > > ? ? ? ? temp_list.append((p,30,'text')) > > ? ? return temp_list > > > def createlist(): > > ? ? column_title_list = ( > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("id",20,"integer"), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("companyname",50,"text"), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? getproducts(), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("contact",50,"text"), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("email",50,"text"), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ) > > ? ? return column_title_list > > > for item in createlist(): > > ? ? print item > > ?>>> def createlist(): > ... ? ? column_title_list = [ > ... ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("id",20,"integer"), > ... ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("companyname",50,"text")] > ... ? ? column_title_list += getproducts() > ... ? ? column_title_list += [ > ... ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("contact",50,"text"), > ... ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("email",50,"text")] > ... ? ? return column_title_list > ... > ?>>> for item in createlist(): > ... ? ? print item > ... > ('id', 20, 'integer') > ('companyname', 50, 'text') > ('focus', 30, 'text') > ('fiesta', 30, 'text') > ('mondeo', 30, 'text') > ('puma', 30, 'text') > ('contact', 50, 'text') > ('email', 50, 'text') > ?>>> > > bye Cheers for that. I was thinking there might be something clever, but as usual, simple is better. From googler.1.webmaster at spamgourmet.com Mon May 31 06:10:52 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Mon, 31 May 2010 03:10:52 -0700 (PDT) Subject: Py_single_input and the side-effects... References: <71e9afe5-f64e-4c2a-9c25-d814d13c7d46@t14g2000prm.googlegroups.com> <0d5415fc-d59b-42a2-99da-d1fd49c7a401@11g2000prv.googlegroups.com> Message-ID: Hi Carl, thanks for your help!! > The only foolproof way to ensure that an object has been finalized is > to do it manually (i.e., provide a finalize method to releases > resources). Yes, you are right, thats what I thought, too. So I wanted to manually delete the reference, but browsing the sources, seems that I cant really free it, because its wrapped somewhere in Py_Finalize() and PyGC_Collect and Py_FreeModules. Any ideas? Thanks a lot! Cheers, moerchendiser2k3 From payal-python at scriptkitchen.com Mon May 31 06:19:46 2010 From: payal-python at scriptkitchen.com (Payal) Date: Mon, 31 May 2010 03:19:46 -0700 Subject: reading help() - newbie question Message-ID: <20100531101946.GA13241@scriptkitchen.com> Hi, I am trying to learn Python (again) and have some basic doubts which I hope someone in the list can address. (English is not my first language and I have no CS background except I can write decent shell scripts) When I type help(something) e.g. help(list), I see many methods like, __methodname__(). Are these something special? How do I use them and why put "__" around them? One more simple query. Many times I see something like this, | D.iteritems() -> an iterator over the (key, value) items of D What is this iterator they are talking about and how do I use these methods because simly saying D.iteritems() does not work? Thanks a lot in advance. With warm regards, -Payal -- From contact at xavierho.com Mon May 31 06:41:54 2010 From: contact at xavierho.com (Xavier Ho) Date: Mon, 31 May 2010 20:41:54 +1000 Subject: reading help() - newbie question In-Reply-To: <20100531101946.GA13241@scriptkitchen.com> References: <20100531101946.GA13241@scriptkitchen.com> Message-ID: On 31 May 2010 20:19, Payal wrote: > Hi, > I am trying to learn Python (again) and have some basic doubts which I > hope someone in the list can address. (English is not my first language and > I > have no CS background except I can write decent shell scripts) > > Welcome (back) to the Python-List! > When I type help(something) e.g. help(list), I see many methods like, > __methodname__(). Are these something special? They're very special. You can think of them as "Python internal functions", and are called internally by other functions. > How do I use them and why > put "__" around them? > You call them as if they were any other function. 99% of the time though, you don't need to call them, as there are better, cleaner ways. > > One more simple query. Many times I see something like this, > | D.iteritems() -> an iterator over the (key, value) items of D > What is this iterator they are talking about <...> > See http://docs.python.org/library/stdtypes.html#iterator-types . Just a peek, nothing big. > and how do I use these > You can use iterators by ... iterating through the items! Like this: >>> for i in [1, 3, 6, 10, 15]: ... print i ... 1 3 6 10 15 and, in your specific example: >>> x = {1: 2, 3: 4} >>> for key, value in x.iteritems(): ... print key, "->", value ... 1 -> 2 3 -> 4 > methods because simly saying D.iteritems() does not work? It does work - it returns you an iterator you can use later: >>> x_items = x.iteritems() >>> for k, v in x_items: ... print k + v ... 3 7 Have fun with Python! Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon May 31 06:47:38 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 31 May 2010 03:47:38 -0700 Subject: reading help() - newbie question In-Reply-To: References: <20100531101946.GA13241@scriptkitchen.com> Message-ID: On Mon, May 31, 2010 at 3:41 AM, Xavier Ho wrote: > On 31 May 2010 20:19, Payal wrote: >> When I type help(something) e.g. help(list), I see many methods like, >> __methodname__(). Are these something special? > > They're very special. You can think of them as "Python internal functions", > and are called internally by other functions. > >> >> How do I use them and why >> put "__" around them? > > You call them as if they were any other function. 99% of the time though, > you don't need to call them, as there are better, cleaner ways. To be a bit more specific, double-underscore methods are called internally by Python to implement various operators. For example, `a + b` is usually equivalent to `a.__add__(b)`, and `len(a)` calls `a.__len__()` internally. For more info, see http://docs.python.org/reference/datamodel.html#special-method-names Cheers, Chris -- http://blog.rebertia.com From cjwilliams43 at gmail.com Mon May 31 06:48:16 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Mon, 31 May 2010 06:48:16 -0400 Subject: reading help() - newbie question In-Reply-To: <20100531101946.GA13241@scriptkitchen.com> References: <20100531101946.GA13241@scriptkitchen.com> Message-ID: On 31-May-10 06:19 AM, Payal wrote: > Hi, > I am trying to learn Python (again) and have some basic doubts which I > hope someone in the list can address. (English is not my first language and I > have no CS background except I can write decent shell scripts) > > When I type help(something) e.g. help(list), I see many methods like, > __methodname__(). Are these something special? How do I use them and why > put "__" around them? > > One more simple query. Many times I see something like this, > | D.iteritems() -> an iterator over the (key, value) items of D > What is this iterator they are talking about and how do I use these > methods because simly saying D.iteritems() does not work? > > Thanks a lot in advance. > With warm regards, > -Payal Here is an extract from the docs for Python 2.6.5. I hope that this clarifies things. Colin W. 2.3.2. Reserved classes of identifiers Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters: _* Not imported by from module import *. The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the __builtin__ module. When not in interactive mode, _ has no special meaning and is not defined. See section The import statement. Note The name _ is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention. __*__ System-defined names. These names are defined by the interpreter and its implementation (including the standard library); applications should not expect to define additional names using this convention. The set of names of this class defined by Python may be extended in future versions. See section Special method names. __* Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between ?private? attributes of base and derived classes. See section Identifiers (Names). From googler.1.webmaster at spamgourmet.com Mon May 31 07:11:25 2010 From: googler.1.webmaster at spamgourmet.com (moerchendiser2k3) Date: Mon, 31 May 2010 04:11:25 -0700 (PDT) Subject: Py_single_input and the side-effects... References: <71e9afe5-f64e-4c2a-9c25-d814d13c7d46@t14g2000prm.googlegroups.com> <0d5415fc-d59b-42a2-99da-d1fd49c7a401@11g2000prv.googlegroups.com> Message-ID: Hi Carl, you are right, Python still holds the last reference. I just set a dummy and thats it :) Can you tell me where did you get the information from? Thanks! From e49eb54c193c5 at poster.grepler.com Mon May 31 07:13:03 2010 From: e49eb54c193c5 at poster.grepler.com (Jason D) Date: 31 May 2010 11:13:03 GMT Subject: Python vs. Fedora and CentOS In-Reply-To: <4c015aa9$0$1617$742ec2ed@news.sonic.net> References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> Message-ID: <3RMMn.125235$y07.3938@news.usenetserver.com> > The major Red Hat based Linux distros are still shipping with >Python 2.4. >As a result, almost all hosting providers are running obsolete >versions of >Python. > > The big problem seems to be that &quot;cPanel&quot; and >&quot;yum&quot; still use older versions >of Python, and those programs are more important to distro builders >than Python >itself. > > Is anybody trying to do something about this? > > John Nagle I am not sure of Fedora, CentOs 5.x ships with Python 2.5 . The version of python depends a lot on everything else that is packed into the system and uses python. e.g. GUI based tools, system scripts etc. There is however never been an issue to locate different version of python in your system as you deem fit without problems. So I dont understand why your concern. regards Jason ---------------------------- posted via Grepler.com -- poster is authenticated. From holmes86 at gmail.com Mon May 31 07:37:58 2010 From: holmes86 at gmail.com (holmes86) Date: Mon, 31 May 2010 04:37:58 -0700 (PDT) Subject: how to generate a csr in python? Message-ID: hi,everyone I want generate a Certificate signing request in python,but I don't how to realize this function.I don't find any method after read the python-openssl manual.Any help will appreciate. From pradeepbpin at gmail.com Mon May 31 08:59:55 2010 From: pradeepbpin at gmail.com (Pradeep B) Date: Mon, 31 May 2010 18:29:55 +0530 Subject: Tkinter library reference In-Reply-To: <83599fd6-e654-47ec-87fd-33d8bb87eef8@k31g2000vbu.googlegroups.com> References: <83599fd6-e654-47ec-87fd-33d8bb87eef8@k31g2000vbu.googlegroups.com> Message-ID: On Mon, May 31, 2010 at 2:46 PM, eb303 wrote: > On May 29, 3:11?pm, Pradeep B wrote: >> Do we have a standard reference library for Tkinter available? >> >> -- >> Pradeep > > Short answer: no, at least not a complete one for Tkinter itself. > > However, there is a complete reference for tcl/tk here: http://www.tcl.tk/man/tcl8.5/ > Once you're used to converting tcl/tk's commands and options into > Tkinter classes and methods, it is the best one around. > > If you really need Python/Tkinter syntax, there are some good > documents here: > http://www.tkdocs.com/widgets/index.html > http://effbot.org/tkinterbook/ > But these are not complete or rather old. However, you can use them as > a starting point before diving into the tcl/tk reference above. > > HTH > ?- Eric - > -- > http://mail.python.org/mailman/listinfo/python-list > I think, generating it using the 'pydoc' seems to be much better. -pradeep -- |_|0|_| |_|_|0| |0|0|0| http://picasaweb.google.com/pradeepbpin From pradeepbpin at gmail.com Mon May 31 09:01:48 2010 From: pradeepbpin at gmail.com (Pradeep B) Date: Mon, 31 May 2010 18:31:48 +0530 Subject: Python and Tkinter Programming by John Grayson In-Reply-To: <81dfc$4c011eaa$4275d90a$28590@FUSE.NET> References: <0738732e-d8df-469d-be4a-3699f4fd5f64@j14g2000yqm.googlegroups.com> <801d251d-ae12-4ce6-95a1-58f594cd2f81@p8g2000yqb.googlegroups.com> <4B4F96D6.2070905@codebykevin.com> <326dc723-3909-4293-9bf6-48a367b9251c@e16g2000yqc.googlegroups.com> <4B58FCDF.4000402@stoneleaf.us> <81dfc$4c011eaa$4275d90a$28590@FUSE.NET> Message-ID: On Sat, May 29, 2010 at 7:33 PM, Kevin Walzer wrote: > Tkinter doesn't wrap native printing API's. There are a few extensions that > do it, but they are platform specific and not complete. > > The usual ways of printing are like this: > > 1. If you're outputting data from the text widget, write that to a temporary > text file and print via lpr. > > 2. If you're outputting data from the canvas, write that to a temporary > postscript file and print via lpr. > > This is on Unix/MacOS. Not sure what the equivalent API on Windows is. > > --Kevin > > -- > Kevin Walzer > Code by Kevin > http://www.codebykevin.com > -- > http://mail.python.org/mailman/listinfo/python-list > Thanx Kevin. Anybody can throw light on how to do the same in Windows ? -pradeep -- |_|0|_| |_|_|0| |0|0|0| http://picasaweb.google.com/pradeepbpin From magawake at gmail.com Mon May 31 09:42:04 2010 From: magawake at gmail.com (Mag Gam) Date: Mon, 31 May 2010 09:42:04 -0400 Subject: parsing question Message-ID: I have a file with bunch of nfsstat -c (on AIX) which has all the hostnames, for example ========r1svr========== Client rpc: Connection oriented calls badcalls badxids timeouts newcreds badverfs timers 0 0 0 0 0 0 0 nomem cantconn interrupts 0 0 0 Connectionless calls badcalls retrans badxids timeouts newcreds badverfs 6553 0 0 0 0 0 0 timers nomem cantsend 0 0 0 Client nfs: calls badcalls clgets cltoomany 6541 0 0 0 Version 2: (6541 calls) null getattr setattr root lookup readlink read 0 0% 590 9% 414 6% 0 0% 2308 35% 0 0% 0 0% wrcache write create remove rename link symlink 0 0% 2482 37% 276 4% 277 4% 147 2% 0 0% 0 0% mkdir rmdir readdir statfs 6 0% 6 0% 30 0% 5 0% Version 3: (0 calls) null getattr setattr lookup access readlink read 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% write create mkdir symlink mknod remove rmdir 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% rename link readdir readdir+ fsstat fsinfo pathconf 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% commit 0 0% ========r2svr========== Client rpc: Connection oriented calls badcalls badxids timeouts newcreds badverfs timers 0 0 0 0 0 0 0 nomem cantconn interrupts 0 0 0 Connectionless calls badcalls retrans badxids timeouts newcreds badverfs 6553 0 0 0 0 0 0 timers nomem cantsend 0 0 0 Client nfs: calls badcalls clgets cltoomany 6541 0 0 0 Version 2: (6541 calls) null getattr setattr root lookup readlink read 0 0% 590 9% 414 6% 0 0% 2308 35% 0 0% 0 0% wrcache write create remove rename link symlink 0 0% 2482 37% 276 4% 277 4% 147 2% 0 0% 0 0% mkdir rmdir readdir statfs 6 0% 6 0% 30 0% 5 0% Version 3: (0 calls) null getattr setattr lookup access readlink read 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% write create mkdir symlink mknod remove rmdir 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% rename link readdir readdir+ fsstat fsinfo pathconf 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% 0 0% commit 0 0% and so on... (http://publib.boulder.ibm.com/infocenter/aix/v6r1/index.jsp?topic=/com.ibm.aix.prftungd/doc/prftungd/nfsstat_c_command.htm) Is there a an easy way to parse this file according to each host? So, r1svr.Connectionless.calls=6553 r1svr.Connectionless.badcalls=0 and so on... I am currently using awk which I am able to get what I need, but curious if in python how people handle block data. From philip at semanchuk.com Mon May 31 09:53:09 2010 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 31 May 2010 09:53:09 -0400 Subject: Python vs. Fedora and CentOS In-Reply-To: <3RMMn.125235$y07.3938@news.usenetserver.com> References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <3RMMn.125235$y07.3938@news.usenetserver.com> Message-ID: On May 31, 2010, at 7:13 AM, Jason D wrote: >> The major Red Hat based Linux distros are still shipping with >> Python 2.4. >> As a result, almost all hosting providers are running obsolete >> versions of >> Python. >> >> The big problem seems to be that &quot;cPanel&quot; and >> &quot;yum&quot; still use older versions >> of Python, and those programs are more important to distro builders >> than Python >> itself. >> >> Is anybody trying to do something about this? >> >> John Nagle > > I am not sure of Fedora, CentOs 5.x ships with Python 2.5 . The > version of python depends a lot on everything else that is packed > into the system and uses python. e.g. GUI based tools, system > scripts etc. Hi Jason, CentOS is based on RHEL SRPMs. How could it ship a more advanced version of Python than RHEL? I have CentOS 5.4 installed, and it only offers Python 2.4.3. And distrowatch.org backs this up -- the latest Python available for Centos 5.x is 2.4: http://distrowatch.com/table.php?distribution=centos Did you perhaps install Python 2.5 on your own by compiling the source tarball? bye Philip From vincent at vincentdavis.net Mon May 31 10:04:53 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 31 May 2010 08:04:53 -0600 Subject: Question about permutations (itertools) Message-ID: As a note I am doing this in py3. I am looking for the most efficient (speed) way to produce an an iterator to of permutations. One of the problem I am having it that neither combinations nor permutations does not exactly what I want directly. For example If I want all possible ordered lists of 0,1 of length 3 (0,0,0) (0,0,1) (0,1,1) (1,1,1) (1,0,1) (1,1,0) (1,0,0) I don't see a way to get this directly from the itertools. But maybe I am missing something. I see ways to get a bigger list and then remove duplicates. >>> list(permutations([0,1], 3)) [] >>> list(combinations_with_replacement('01',3)) ('0', '0', '0') ('0', '0', '1') ('0', '1', '1') ('1', '1', '1') Is it possible to get combinations_with_replacement to return numbers rather than strings? (see above) Thanks Vincent From contact at xavierho.com Mon May 31 10:17:49 2010 From: contact at xavierho.com (Xavier Ho) Date: Tue, 1 Jun 2010 00:17:49 +1000 Subject: Question about permutations (itertools) In-Reply-To: References: Message-ID: > >>> list(combinations_with_replacement('01',3)) > ('0', '0', '0') > ('0', '0', '1') > ('0', '1', '1') > ('1', '1', '1') > > Is it possible to get combinations_with_replacement to return numbers > rather than strings? (see above) > >>> list(combinations_with_replacement(range(0,2), 3)) [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] Hopefully that'll give you some ideas. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon May 31 10:25:26 2010 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 May 2010 16:25:26 +0200 Subject: Question about permutations (itertools) References: Message-ID: Vincent Davis wrote: > As a note I am doing this in py3. > > I am looking for the most efficient (speed) way to produce an an > iterator to of permutations. > One of the problem I am having it that neither combinations nor > permutations does not exactly what I want directly. > For example If I want all possible ordered lists of 0,1 of length 3 > (0,0,0) > (0,0,1) > (0,1,1) > (1,1,1) > (1,0,1) > (1,1,0) > (1,0,0) > I don't see a way to get this directly from the itertools. But maybe I > am missing something. >>> for t in itertools.product([0, 1], repeat=3): ... print(t) ... (0, 0, 0) (0, 0, 1) (0, 1, 0) # Seems you missed one (0, 1, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1) > I see ways to get a bigger list and then remove > duplicates. > >>>> list(permutations([0,1], 3)) > [] > >>>> list(combinations_with_replacement('01',3)) > ('0', '0', '0') > ('0', '0', '1') > ('0', '1', '1') > ('1', '1', '1') > > Is it possible to get combinations_with_replacement to return numbers > rather than strings? (see above) >>> for t in itertools.combinations_with_replacement([0, 1], 3): ... print(t) ... (0, 0, 0) (0, 0, 1) (0, 1, 1) (1, 1, 1) Peter From vincent at vincentdavis.net Mon May 31 10:31:38 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 31 May 2010 08:31:38 -0600 Subject: Question about permutations (itertools) In-Reply-To: References: Message-ID: On Mon, May 31, 2010 at 8:17 AM, Xavier Ho wrote: > >> >>> list(combinations_with_replacement('01',3)) >> ('0', '0', '0') >> ('0', '0', '1') >> ('0', '1', '1') >> ('1', '1', '1') >> >> Is it possible to get combinations_with_replacement to return numbers >> rather than strings? (see above) > >>>> list(combinations_with_replacement(range(0,2), 3)) > [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] Thanks, for some reason I didn't combinations_with_replacement took a list as an argument. > Hopefully that'll give you some ideas. > > Cheers, > Xav From dickinsm at gmail.com Mon May 31 11:03:43 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 31 May 2010 08:03:43 -0700 (PDT) Subject: Question about permutations (itertools) References: Message-ID: <46baf97c-a31d-4e5b-888d-682e8da76153@f13g2000vbm.googlegroups.com> On May 31, 3:04?pm, Vincent Davis wrote: > For example If I want all possible ordered lists of 0,1 of length 3 > (0,0,0) > (0,0,1) > (0,1,1) > (1,1,1) > (1,0,1) > (1,1,0) > (1,0,0) > I don't see a way to get this directly from the itertools. But maybe I > am missing something. In this case, you're missing itertools.product: >>> list(itertools.product([0, 1], repeat=3)) [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] -- Mark From eckhardt at satorlaser.com Mon May 31 11:05:23 2010 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Mon, 31 May 2010 17:05:23 +0200 Subject: Question about permutations (itertools) References: Message-ID: Vincent Davis wrote: > I am looking for the most efficient (speed) way to produce an an > iterator to of permutations. > One of the problem I am having it that neither combinations nor > permutations does not exactly what I want directly. > For example If I want all possible ordered lists of 0,1 of length 3 > (0,0,0) > (0,0,1) > (0,1,1) > (1,1,1) > (1,0,1) > (1,1,0) > (1,0,0) > I don't see a way to get this directly from the itertools. But maybe I > am missing something. I see ways to get a bigger list and then remove > duplicates. You have three digits where each digit can have two values (binary digits, a.k.a. bits), so the number of combinations is 2*2*2 = 8. Even if the possible values where unevenly distributed, you could calculate the number of combinations by multiplying. Then, there are two different approaches: 1. count with an integer and then dissect into digits # Note: Using // for integer division in Python3! digit0 = n % base0 digit1 = (n // base0) % base1 digit2 = (n // base0 // base1) % base2 2. simulate digits and detect overflow Here you simply count up the "ones" and if they overflow, you reset them to zero and count up the "tens". What I don't really understand is what you mean with "ordered lists". Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From python.list at tim.thechases.com Mon May 31 11:07:02 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 May 2010 10:07:02 -0500 Subject: parsing question In-Reply-To: References: Message-ID: <4C03D096.5040204@tim.thechases.com> On 05/31/2010 08:42 AM, Mag Gam wrote: > I have a file with bunch of nfsstat -c (on AIX) which has all the > hostnames, for example ... > Is there a an easy way to parse this file according to each host? > > So, > r1svr.Connectionless.calls=6553 > r1svr.Connectionless.badcalls=0 > > and so on... > > > I am currently using awk which I am able to get what I need, but > curious if in python how people handle block data. Since you already profess to having an awk solution, I felt it was okay to at least take a stab at my implementation (rather than doing your job for you :). Without a complete spec for the output, it's a bit of guesswork, but I got something fairly close to what you want. It uses nested dictionaries which mean the keys and values have to be referenced like servers["r1svr"]["connectionless"]["calls"] and the values are strings (I'm not sure what you want in the case of the data that has both a value and percentage) not ints/floats/percentages/etc. That said, this should get you fairly close to what you describe: ########################################### import re header_finding_re = re.compile(r'\b\w{2,}') version_re = re.compile(r'^Version (\d+):\s*\(.*\)$', re.I) CLIENT_HEADER = 'Client ' CONNECTION_HEADER = 'Connection' servers = {} server = client = orig_client = subtype = None source = file('data.txt') for line in source: line = line.rstrip('\r\n') if not line.strip(): continue if line.startswith('='*5) and line.endswith('='*5): server = line.strip('=') client = orig_client = subtype = None elif line.startswith(CLIENT_HEADER): orig_client = client = line[len(CLIENT_HEADER):-1] subtype = 'all' elif line.startswith(CONNECTION_HEADER): subtype = line.replace(' ', '').lower() else: # it's a version or header row m = version_re.match(line) if m: subtype = "v" + m.group(1) else: if None in (server, client, subtype): print "Missing data", repr((server, client, subtype)) continue dest = servers.setdefault(server, {} ).setdefault(client, {} ).setdefault(subtype, {}) data = source.next() row = header_finding_re.finditer(line) prev = row.next() for header in row: key = prev.group(0) value = data[prev.start():header.start()].strip() prev = header dest[key] = value key = prev.group(0) value = data[prev.start():].strip() dest[key] = value for server, clients in servers.items(): for client, subtypes in clients.items(): for subtype, kv in subtypes.items(): for key, value in kv.items(): print ".".join([server, client, subtype, key]), print '=', value ########################################### Have fun, -tkc From razieh.eskandari at gmail.com Mon May 31 11:56:23 2010 From: razieh.eskandari at gmail.com (eskandari) Date: Mon, 31 May 2010 08:56:23 -0700 (PDT) Subject: writing numbers in binary file Message-ID: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Hi, I am a newbie in python. I have an data.pickle file which is serialized form of an "array of strings", I want to write their offsets in another binary file, so an C++ program can read and analyse them. But when I try to write offset (number) in binary file, it raise exception below in line "offsetfile.write(offset)" "TypeError: argument 1 must be string or read-only buffer, not int" I search the internet, find that all suggest converting number to string ---with str()---and then write string to file. But I shouldn't do this. because the above mentioned C++ function, read file with this assumption that there are numbers in file. So I want to know, Is there any way to produce an binary file containing numbers same as the way C++ does? Can anybody help me? Thanks a lot. From cde3 at live.com Mon May 31 11:58:16 2010 From: cde3 at live.com (Sandy Ydnas) Date: Mon, 31 May 2010 20:58:16 +0500 Subject: where are the program that are written in python? In-Reply-To: <1c5ea366-a909-4da7-ab7a-fe30542ebfab@a27g2000prj.googlegroups.com> References: <0b244d1f-cce9-42e8-8056-1b58a41ff0b5@r9g2000vbk.googlegroups.com>, <85rfa9Fv65U1@mid.individual.net>, <1c5ea366-a909-4da7-ab7a-fe30542ebfab@a27g2000prj.googlegroups.com> Message-ID: http://en.wikipedia.org/wiki/List_of_Python_software List of Python software >From Wikipedia, the free encyclopedia Jump to:navigation, search This article needs additional citations for verification. Please help improve this article by adding reliable references. Unsourced material may be challenged and removed. (March 2008) The Python programming language is actively used by many people, both in industry and academia for a wide variety of purposes. Contents[hide] 1 Integrated development environments 2 Applications 3 Web Applications 4 Video games 5 Web frameworks 6 Graphics frameworks 7 GUI frameworks 8 Scientific packages 9 Mathematical libraries 10 Additional development packages 11 Embedded as a scripting language 12 Commercial uses 13 Python implementations 14 References 15 External links [edit] Integrated development environments Boa Constructor, a cross-platform IDE for Python development EasyEclipse, an open source IDE for Python and other languages Eric, an IDE for Python and Ruby PIDA, open source IDE written in Python capable of embedding other text editors, such as Vim Stani's Python Editor (SPE), a cross-platform IDE for Python development Webware for Python, a suite of programming tools for constructing web-based applications in Python Wing IDE, an IDE for Python NetBeans, is written in Java and runs everywhere where a JVM is installed. [edit] Applications Anki, a spaced repetition flashcard program Bazaar, a free distributed revision control system BitTorrent, original client, along with several derivatives BuildBot, a continuous integration system Calibre, an open source e-book management tool Chandler, a personal information manager including calendar, email, tasks and notes support that is currently under development Decibel Audio Player, an open source audio player Deluge, a BitTorrent client for GNOME emesene, a MSN/WLM substitute Exaile, an open source audio player Gajim, an instant messaging client for the XMPP protocol GRAMPS, an open source genealogy software Gwibber, a microblogging client Impressive (ex. KeyJnote), a presentation software Juice, a popular podcast downloader Mercurial a cross-platform, distributed source management tool Miro, a cross-platform internet television application Morpheus, file-sharing client/server software operated by the company StreamCast MusicBrainz Picard, a cross-platform MusicBrainz tag editor Nicotine, a PyGTK Soulseek client OpenLP, lyrics projection software OpenShot Video Editor PiTiVi, a non-linear video editor Portage, the heart of Gentoo Linux, an advanced package management system based on the BSD-style ports system Quake Army Knife, an environment for developing 3D maps for games based on the Quake engine Resolver One, a spreadsheet Sage (sagemath) combines more than 20 main opensource math packages and provides easy to use web interface with the help of Python SCons, a tool for building software Ubuntu Software Center, a graphical package manager, installed by default in Ubuntu 9.10 and higher Wammu, a mobile phone management utility Wicd, a network manager for Linux YUM, a package management utility for RPM-compatible Linux operating systems [edit] Web Applications ERP5, a powerful open source ERP / CRM used in Aerospace, Apparel, Banking and for e-government GNU Mailman, one of the more popular packages for running email mailing lists MoinMoin, a popular wiki engine Planet, a feed aggregator Plone, a user-friendly and powerful open source content management system Projectplace, Europe?s Leading Online Service for Project Collaboration Roundup, a bug tracking system ViewVC, a web-based interface for browsing CVS and SVN repositories Trac, web-based bug/issue tracking database, wiki, and version control front-end MediaCore Video CMS is an open source media focused content management system. [edit] Video games Civilization IV uses Python for most of its tasks Battlefield 2 uses Python for all of its addons and a lot of its functionality Eve Online uses Stackless Python Freedom Force Frets on Fire uses Python and Pygame The Temple of Elemental Evil, a computer role-playing game based on the classic Greyhawk Dungeons & Dragons campaign setting Vampire: The Masquerade ? Bloodlines, a computer role-playing game based on the World of Darkness campaign setting Vega Strike, an open source space simulator [edit] Web frameworks CherryPy, an object-oriented web application server and framework Django, an MVC (model, view, controller) web framework Pylons, a lightweight web framework emphasizing flexibility and rapid development Quixote, a framework for developing Web applications in Python Topsite Templating System, another Python-powered web framework TurboGears, a web framework combining CherryPy, SQLObject, and Kid web2py, a full-stack enterprise web application framework, following the MVC design Zope, an application server, commonly used to build content management systems [edit] Graphics frameworks Pygame, Python bindings for SDL Pyglet, a cross-platform windowing and multimedia library for Python Python Imaging Library, a module for working with images Python-Ogre, a Python Language binding for the OGRE 3D engine Soya3D, a high-level 3D game engine for Python [edit] GUI frameworks PyGTK, a popular cross-platform GUI library based on GTK+; furthermore, other GNOME libraries also have bindings for Python PyQt, another cross-platform GUI library based on Qt; as above, KDE libraries have bindings too wxPython, a port of wxWidgets and a cross-platform GUI library for Python [edit] Scientific packages Biopython, a Python molecular biology suite SciPy, a library of scientific and numerical routines SimPy, a discrete-event simulation package stsci python, a library library of Python routines and C extensions that has been developed to provide a general astronomical data analysis infrastructure, developed by STScI [edit] Mathematical libraries matplotlib, an extension providing MATLAB-like plotting and mathematical functions NumPy, a language extension that adds support for large and fast, multi-dimensional arrays and matrices PyIMSL Studio is a Python distribution which includes the IMSL math and statistics Libraries from Visual Numerics (a Rogue Wave Software company) Sage Math is a large mathematical software application which integrates the work of nearly 100 free software projects and supports linear algebra, combinatorics, numerical mathematics, calculus, and more. SymPy, a computer algebra system [edit] Additional development packages Cheetah, a Python-powered template engine and code-generation tool IPython, a powerful development shell both written in and designed for Python Jinja, a Python-powered template engine, inspired by Django's template engine mod python, an Apache module allowing direct integration of Python scripts with the Apache web server PYthon Remote Objects, a Distributed Object Technology PyObjC, a Python-Objective C bridge that allows one to write Mac OS X software in Python Twisted, a networking framework for Python [edit] Embedded as a scripting language Python is, or can be used as the scripting language in these software products. Amarok AMESim ArcGIS, a prominent GIS platform, allows extensive modelling using Python Autodesk Softimage (formerly Softimage|XSI) Blender Boxee, a cross-platform home theater PC software Corel Paint Shop Pro DSHub Epiphany EventScripts, plugin for Valve's Source engine gedit GIMP GNAT The GNAT programming chain tool (Ada language implementation in GNU gcc), as a GNATcoll reusable components for the applications (with or without PyGTK) and as a scripting language for the commands in the GPS programming environment Inkscape Autodesk Maya (version 8.5 and newer only) Modo Nuke (compositing for visual effects) Poser, a 3D rendering and animation software program, that uses for scripting a special dialect of Python, called PoserPython PyMOL, a popular molecular viewer that embeds Python for scripting and integration QGIS uses Python for scripting and plugin-development Rhythmbox Scribus SPSS statistical software SPSS Programmability Extension allows users to extend the SPSS command syntax language with Python Totem, a media player for the GNOME desktop environment Vim VisIt WeeChat, a console IRC client [edit] Commercial uses CCP hf uses Stackless Python in both its server and client side applications for its MMO Eve Online[1] Google uses Python for many tasks including the backends of web apps such as Google Groups, Gmail, and Google Maps, as well as for some of its search-engine internals Autodesk Maya, professional 3D modeler allows Python scripting as an alternative to MEL as of version 8.5 NASA is using Python to implement a CAD/CAE/PDM repository and model management, integration, and transformation system which will be the core infrastructure for its next-generation collaborative engineering environment[citation needed] reddit was originally written in Common Lisp, but was rewritten in Python in 2005[2] Yahoo! Groups uses Python "to maintain its discussion groups" YouTube uses Python "to produce maintainable features in record times, with a minimum of developers"[3] [edit] Python implementations CPython - the reference implementation IronPython - Python for .NET and Mono platforms Jython - Python coded in Java Parrot - virtual machine being developed mainly as the runtime for Perl 6, but with the intent to also support dynamic languages like Python, Ruby, Tcl, etc. Psyco - not an implementation, but JIT compiler for CPython PyPy - Python coded in Python Stackless Python - Python with coroutines Unladen Swallow - the Python implementation from the Google team [edit] References ^ http://www.eve-online.com/faq/faq_07.asp ^ http://blog.reddit.com/2005/12/on-lisp.html ^ http://www.python.org/about/quotes > From: wuwei23 at gmail.com > Subject: Re: where are the program that are written in python? > Date: Sun, 23 May 2010 22:29:12 -0700 > To: python-list at python.org > > Gregory Ewing wrote: > > I came across a game on Big Fish Games recently (it was > > "The Moonstone" IIRC) that appeared to have been built using > > Python and py2app. > > Python tends to be used more for scripting internal game logic than > for every aspect of a game (which is, IMO, the right way to go about > it). It's not a huge list of commercial games that does this[1], but > it's a fairly classy one :) > > 1: http://en.wikipedia.org/wiki/Category:Python-scripted_video_games > -- > http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Hotmail: Trusted email with Microsoft?s powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Mon May 31 12:30:25 2010 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 31 May 2010 17:30:25 +0100 Subject: writing numbers in binary file In-Reply-To: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> References: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Message-ID: <4C03E421.3020407@mrabarnett.plus.com> eskandari wrote: > Hi, > I am a newbie in python. I have an data.pickle file which is > serialized form of an "array of strings", I want to write their > offsets in another binary file, so an C++ program can read and analyse > them. > But when I try to write offset (number) in binary file, it raise > exception below in line "offsetfile.write(offset)" > "TypeError: argument 1 must be string or read-only buffer, not int" > > I search the internet, find that all suggest converting number to > string ---with str()---and then write string to file. > But I shouldn't do this. because the above mentioned C++ function, > read file with this assumption that there are numbers in file. > So I want to know, Is there any way to produce an binary file > containing numbers same as the way C++ does? > Can anybody help me? > You can't write ints to a file, but you can write bytestrings ('str' in Python 2, 'bytes' in Python 3). Use the 'struct' module to convert the int to a bytestring, and remember to open the file as a binary file. From nagle at animats.com Mon May 31 12:40:18 2010 From: nagle at animats.com (John Nagle) Date: Mon, 31 May 2010 09:40:18 -0700 Subject: Python vs. Fedora and CentOS In-Reply-To: References: <4c015aa9$0$1617$742ec2ed@news.sonic.net> <3RMMn.125235$y07.3938@news.usenetserver.com> Message-ID: <4c03e090$0$1584$742ec2ed@news.sonic.net> Philip Semanchuk wrote: > Hi Jason, > CentOS is based on RHEL SRPMs. How could it ship a more advanced version > of Python than RHEL? > > I have CentOS 5.4 installed, and it only offers Python 2.4.3. > > And distrowatch.org backs this up -- the latest Python available for > Centos 5.x is 2.4: > http://distrowatch.com/table.php?distribution=centos Shared hosting services mostly run CentOS or RHEL; there's a trend away from running Fedora Core. So if you want to do anything in Python that is intended to run on shared hosting, you have to target Python 2.4. I have a dedicated server for a big site; there I can build and install later Python versions. That's not the problem. It's the little sites, ones not big enough to need their own dedicated server or virtual machine, where it's difficult to run Python. The current RHEL beta has Python 2.6, and that should be out this year. Hosting providers should start cutting over to it in 2011. RHEL and CentOS have a 7-year life cycle. So we can expect mainstream availability of Python 2.6 from 2011 to 2018. John Nagle From python.list at tim.thechases.com Mon May 31 12:42:18 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 May 2010 11:42:18 -0500 Subject: writing numbers in binary file In-Reply-To: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> References: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Message-ID: <4C03E6EA.80602@tim.thechases.com> On 05/31/2010 10:56 AM, eskandari wrote: > But when I try to write offset (number) in binary file, it raise > exception below in line "offsetfile.write(offset)" > "TypeError: argument 1 must be string or read-only buffer, not int" > > I search the internet, find that all suggest converting number to > string ---with str()---and then write string to file. > But I shouldn't do this. because the above mentioned C++ function, > read file with this assumption that there are numbers in file. > So I want to know, Is there any way to produce an binary file > containing numbers same as the way C++ does? Well, you have at least two options: 1) use the pack/unpack functions in the "struct" module to convert a number to a byte representation that you can then write to a file 2) write the number to the file as a string and then use C++ libraries to parse a number from a string. In both cases, you have to consider what happens when the number is outside the bounds of your C++ data-type (you don't mention what you're using...an int, a long, or "long long"; signed vs. unsigned). Additionally in the first case, you have to make sure that your memory-architecture (big-endian vs. little-endian) matches on both sides; or that you marshal the data through a pre-defined format (in libraries, commonly called "network" format). For such reasons, I'd stick with method #2 unless you have a strong reason not to. -tkc From razieh.eskandari at gmail.com Mon May 31 12:43:02 2010 From: razieh.eskandari at gmail.com (eskandari) Date: Mon, 31 May 2010 09:43:02 -0700 (PDT) Subject: writing numbers in binary file References: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Message-ID: On May 31, 12:30?pm, MRAB wrote: > eskandari wrote: > > Hi, > > I am a newbie in python. I have an data.pickle file which is > > serialized form of an "array of strings", I want to write their > > offsets in another binary file, so an C++ program can read and analyse > > them. > > But when I try to write offset (number) in binary file, it raise > > exception below in line ?"offsetfile.write(offset)" > > "TypeError: argument 1 must be string or read-only buffer, not int" > > > I search the internet, find that all suggest converting number to > > string ---with str()---and then write string to file. > > But I shouldn't do this. because the above mentioned C++ function, > > read file with this assumption that there are numbers in file. > > So I want to know, Is there any way to produce an binary file > > containing numbers same as the way C++ does? > > Can anybody help me? > > You can't write ints to a file, but you can write bytestrings ('str' in > Python 2, 'bytes' in Python 3). > > Use the 'struct' module to convert the int to a bytestring, and remember > to open the file as a binary file. Thanks alot, I have an question, if I do so, Will the second program (C++ program) which process this file, encounter any problem while parsing the file? It find number of integers by filelen/4 and ..... (It assumes that file was created as the same way which C++ does) Thanks in advance From ronyekr at gmail.com Mon May 31 13:00:27 2010 From: ronyekr at gmail.com (ekr3d) Date: Mon, 31 May 2010 10:00:27 -0700 (PDT) Subject: Do you want the safety of the computer ? Message-ID: Do you want the safety of the computer? Take this gift Advanced SystemCare Free 3.3.1 http://free-ekramy.blogspot.com From arndt.roger at addcom.de Mon May 31 13:04:42 2010 From: arndt.roger at addcom.de (Arndt Roger Schneider) Date: Mon, 31 May 2010 19:04:42 +0200 Subject: Python and Tkinter Programming by John Grayson References: <0738732e-d8df-469d-be4a-3699f4fd5f64@j14g2000yqm.googlegroups.com> <801d251d-ae12-4ce6-95a1-58f594cd2f81@p8g2000yqb.googlegroups.com> <4B4F96D6.2070905@codebykevin.com> <326dc723-3909-4293-9bf6-48a367b9251c@e16g2000yqc.googlegroups.com> <4B58FCDF.4000402@stoneleaf.us> <81dfc$4c011eaa$4275d90a$28590@FUSE.NET> Message-ID: Pradeep B schrieb: >On Sat, May 29, 2010 at 7:33 PM, Kevin Walzer wrote: > > > >>Tkinter doesn't wrap native printing API's. There are a few extensions that >>do it, but they are platform specific and not complete. >> >>The usual ways of printing are like this: >> >>1. If you're outputting data from the text widget, write that to a temporary >>text file and print via lpr. >> >>2. If you're outputting data from the canvas, write that to a temporary >>postscript file and print via lpr. >> >>This is on Unix/MacOS. Not sure what the equivalent API on Windows is. >> >>--Kevin >> >>-- >>Kevin Walzer >>Code by Kevin >>http://www.codebykevin.com >>-- >>http://mail.python.org/mailman/listinfo/python-list >> >> >> > > >Thanx Kevin. > >Anybody can throw light on how to do the same in Windows ? > >-pradeep > > > > The conventional --crude-- way is to take the bitmap of a window and to stretchDIBBitBlt it onto the printer device in windows and osx. Native printer dialogs do exist for both platforms ... When you do not need a printer dialog: Convert the Tk-GUI to SVG, then wrap it into a fo-xml wrapper --fo accepts inline SVG-- and use fop for printing. This approach works cross-platform, albeit you need a Java intallation (fop is a Java application). You can use http://jeszra.sourceforge.net to generate SVG for a complete Tk-GUI. In addition. there is a python/tkinter SVG export project for the Tk canvas --search the tkinter wiki. -roger From mlsngac at gmail.com Mon May 31 13:16:22 2010 From: mlsngac at gmail.com (M L) Date: Mon, 31 May 2010 10:16:22 -0700 (PDT) Subject: passing external data to web forms Message-ID: <9afd92f6-0780-4773-994c-8db303f64f52@a20g2000vbc.googlegroups.com> (Note: If you just skim this and can tell me how to pass data from an external program to a web form, that's all I need, and the rest is just what I'd like to have.) This is probably extremely simple when you know what you're doing. I figured I'd see if I could find a kind soul who could give me some code samples. Here's what I need to do: 1. Receive email via IMAP-IDLE 2. Parse the email to see if it contains certain text 3. Open a browser window with the following variables based on what that text is a. URL b. username c. password Specifically, I'm needing to login to a particular website, and which username I use varies based on it being specified in the email. I tried to do this with a combination of message filters in Thunderbird and command line arguments in Firefox, but it can't quite do everything I need. My real problem is how to get the username and password passed to the browser. Also, you should know that the server to which I'm connecting is a site to which I subscribe, not my own, so I can't run anything sever-side. Also, if possible, having this just fill whatever the first html form field it comes to with the username and the second with the password would be great, though not necessary if that's significantly more complicated than it filling them based on a specific name. I don't anticipate the site changing the names of those fields, but I'd like to not have to redo the code if it does. Finally, and again just a preference not a requirement, I feel that it would be easier to have an external file that stores the usernames and passwords that could be referenced to load them based on the email contents rather than having the usernames and passwords hardcoded. However, I'm only needing about half a dozen, so if it's significantly simpler, I'll go with that. Thanks for any help! -ML From tjreedy at udel.edu Mon May 31 13:23:15 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 May 2010 13:23:15 -0400 Subject: writing numbers in binary file In-Reply-To: References: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Message-ID: On 5/31/2010 12:43 PM, eskandari wrote: > On May 31, 12:30 pm, MRAB wrote: >> eskandari wrote: >> Use the 'struct' module to convert the int to a bytestring, and remember >> to open the file as a binary file. > > Thanks alot, > I have an question, if I do so, Will the second program (C++ program) > which process this file, encounter any problem while parsing the file? > It find number of integers by filelen/4 and ..... (It assumes that > file was created as the same way which C++ does) Tim Chase pretty well answered this. If you are not familiar with the problem of 'endianess', see http://en.wikipedia.org/wiki/Endianess From pavel.mba.du at gmail.com Mon May 31 13:26:15 2010 From: pavel.mba.du at gmail.com (Pavel Haque) Date: Mon, 31 May 2010 10:26:15 -0700 (PDT) Subject: Windows and Linux Tips Message-ID: Hi Friends, For Windows and Linux Tips, Please Visit: www.windowsandlinuxtips.blogspot.com From gabriele.lanaro at gmail.com Mon May 31 14:47:59 2010 From: gabriele.lanaro at gmail.com (Gabriele Lanaro) Date: Mon, 31 May 2010 20:47:59 +0200 Subject: Problems with relative imports and pep 366 Message-ID: <1275331679.3204.1.camel@eulero-desktop> I've yet asked this question on SO, I'll copy the contents: I have a "canonical file structure" like that (I'm giving sensible names to ease the reading): mainpack/ __main__.py __init__.py - helpers/ __init__.py path.py - network/ __init__.py clientlib.py server.py - gui/ __init__.py mainwindow.py controllers.py In this structure, for example modules contained in each package may want to access the helpers utilities through relative imports in something like: # network/clientlib.py from ..helpers.path import create_dir The program is runned "as a script" using the __main__.py file in this way: python mainpack/ Trying to follow the PEP 366 I've put in __main__.py these lines: ___package___ = "mainpack" from .network.clientlib import helloclient But when running: $ python mainpack Traceback (most recent call last): File "/usr/lib/python2.6/runpy.py", line 122, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.6/runpy.py", line 34, in _run_code exec code in run_globals File "path/mainpack/__main__.py", line 2, in from .network.clientlib import helloclient SystemError: Parent module 'mainpack' not loaded, cannot perform relative import What's wrong? What is the correct way to handle and effectively use relative imports? I've tried also to add the current directory to the PYTHONPATH, nothing changes. link: http://stackoverflow.com/questions/2943847/nightmare-with-relative-imports-how-does-pep-366-work From aahz at pythoncraft.com Mon May 31 14:55:09 2010 From: aahz at pythoncraft.com (Aahz) Date: 31 May 2010 11:55:09 -0700 Subject: Inheritable Slots Metaclass References: <1ef205ed-21e6-4d08-baf2-46949414c810@e34g2000pra.googlegroups.com> <5a3a5737-f1b7-4419-9bb3-088c244a4760@c13g2000vbr.googlegroups.com> Message-ID: In article <5a3a5737-f1b7-4419-9bb3-088c244a4760 at c13g2000vbr.googlegroups.com>, Carl Banks wrote: > >However, Aahz will be by shortly to tell you never to use slots. Please note that there is an important distinction between "don't use slots" and "never use slots" -- if you can locate any instances where I wrote the latter, I will be surprised and issue a retraction. Obviously, slots are an important element of Python, but they should be used only when other approaches have proven impractical. To quote Guido: __slots__ is a terrible hack with nasty, hard-to-fathom side effects that should only be used by programmers at grandmaster and wizard levels. Unfortunately it has gained an enormous undeserved popularity amongst the novices and apprentices, who should know better than to use this magic incantation casually. See also http://www.dalkescientific.com/writings/diary/archive/2006/03/19/class_instantiation_performance.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From naresh.ftp at gmail.com Mon May 31 15:19:08 2010 From: naresh.ftp at gmail.com (Naresh Kumar) Date: Mon, 31 May 2010 12:19:08 -0700 (PDT) Subject: DOWNLOAD FREE PALTALK LIVE VIDEO AND VOICE CHAT SOFTWARE Message-ID: <0a579e7a-042d-49d2-b7f2-3cea619e2107@40g2000pry.googlegroups.com> Download free here - http://bit.ly/auQHjB 4000+ VIDEO CHAT ROOMS 4 Million+ FRIENDLY USERS WORLDWIDE HOST YOUR OWN CAM SHOWS CONNECT WITH YOUR YAHOO/ICQ/AOL BUDDIES Download free here - http://bit.ly/auQHjB Thanks and Regards tony :) From lweberk at gmail.com Mon May 31 16:56:00 2010 From: lweberk at gmail.com (Leonhard Weber) Date: Mon, 31 May 2010 22:56:00 +0200 Subject: Spawning console and piping the stdout into it Message-ID: Hi, I'm stuck at a puzzle for quite some time. Situation: (Linux environment) I have a script that is invoked from an application (running my script as part of embedded python). I have no power over that application, only supply the script it executes. Now for development reasons I want that script to spawn a console and show me the output through there. Though there is the ugly way of writing to file and tailing it, it would be great if someone could come up with a cleaner version. The approach I've been taking is trying to start a child with the subprocess module and pipe the sys.stdoout into the stdin of the child... hummmm. No success so far. Thanks, ~lwk -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Mon May 31 17:15:05 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 01 Jun 2010 07:15:05 +1000 Subject: if, continuation and indentation In-Reply-To: References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> Message-ID: <4c042759$1@dnews.tpgi.com.au> On 05/31/10 05:10, Colin J. Williams wrote: > On 30-May-10 01:50 AM, Nathan Rice wrote: >> On 27-May-10 08:48 AM, Xavier Ho wrote: >> > On 27 May 2010 22:22, HH> > > >> wrote: >> >> > >> > if (width == 0 and >> > height == 0 and >> > color == 'red' and >> > emphasis == 'strong' or >> > highlight> 100): >> > raise ValueError("sorry, you lose") >> > >> > >> > I've gotta say - I've bumped into this problem before, >> and I'm sure many >> > other have - this is a valid question. It just hasn't >> bothered me enough >> > to ask... >> > >> > Correct me if I'm wrong, but I think the following is >> equivalent, and >> > looks better. Although this won't fix all ugly cases in >> that problem.. >> > >> > if (width, height, color, emphasis) == (0, 0, 'red', >> 'strong') or >> > highlight> 100: >> > raise ValueError("sorry, you lose") >> > >> > Cheers, >> > Xav >> >> but nobody commented. >> >> Colin W. >> >> >> Colin: >> Sure, you can do it that way. IMO, though, the OP was wrong, >> and so >> is the PEP. Source code is meant to communicate. So it must >> transmit >> the correct information to the computer; it also must inform your >> coworkers. That means that you have a responsibility to care >> what >> they think, though you privately have your opinions. Another >> reason >> the PEP is faulty in this circumstance is that a misplaced >> backslash, >> or a missing one, is easily found and fixed. A misplaced >> parentheses, >> or just one of a pair, will transform your source code into >> something >> which may compile and then give faulty results: a disaster. >> So keep it simple, and make it legible. >> Yours, >> John >> >> >> IMHO complete garbage, if your editor doesn't show misplaced or >> missing parenthesis by highlighting you're using the wrong editor :) >> >> > > Perhaps the arrangement below shows the matching a little better than > the Xav suggestion. The main point is that, to me, the tuple shows the > item by item matching better than a series of and clauses: > > # tif.py > > (width, height, color, emphasis)= 0, 0, 'red', 'strong' > highlight= 99 > if (width, height, color, emphasis) == \ > ( 0, 0, 'red', 'strong') or highlight> 100: > raise ValueError("sorry, you lose") How about: all(a == b for a,b in ((width, 0), (height, 0), (color, 'red'), (emphasis, 'strong')))) From python.list at tim.thechases.com Mon May 31 17:21:29 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 May 2010 16:21:29 -0500 Subject: passing external data to web forms In-Reply-To: <9afd92f6-0780-4773-994c-8db303f64f52@a20g2000vbc.googlegroups.com> References: <9afd92f6-0780-4773-994c-8db303f64f52@a20g2000vbc.googlegroups.com> Message-ID: <4C042859.5090805@tim.thechases.com> On 05/31/2010 12:16 PM, M L wrote: > Specifically, I'm needing to login to a particular website, > and which username I use varies based on it being specified > in the email. Are you in control of this email generation (that is, can you generate an email with an HTML form within, or is this email coming from a 3rd-party)? Creating an HTML-email with a form to submit the username/password isn't a flawless solution because many folks (self included) configure their mail-reader to only display plain-text and ignore HTML components. > My real problem is how to get the username and password > passed to the browser. If you can't create an HTML form in the source email, then it depends on what the web-server is expecting -- a GET (bad for users, good for you) or a POST (good web practice, but a pain for you). If the web login form is maldesigned and uses a GET submission, you can just parse the email body for the fields and generate a link of the form http://example.com/login?user=jsmith&pass=SeKrEt However, if the website creates expects a POST to login (good design so credentials don't get saved in history, or get bookmarked accidentally), then you have to either 1) do some dark browser-specific hackery, perhaps with a bit of urllib magic to kludge the session into an active browser. Not a particularly inviting solution to implement. 2) generate a temporary HTML file with the prepopulated form in it, point the browser at that page and either (2a) have the user click on the [submit] button, and/or (2b) have a little JavaScript that clicks the [submit] button (or calls form.submit() more likely) after the temp-page is loaded. I'd do both in the event the user has JS turned off in their browser (again, that'd be me, thanks to NoScript). This temporary HTML file could be scraped (via urllib) from the login url itself, or hard-coded if you expect it to be of the same format for each website. My crack at it looks something like ########################## from sys import exit, stderr from tempfile import NamedTemporaryFile import email import imaplib import os import re import time import urllib import webbrowser url_re = re.compile(r'\burl:\s*(http://.*)') user_re = re.compile(r'\buser(?:name)?:\s*(.*)') pass_re = re.compile(r'\bpass(?:word)?:\s*(.*)') class MissingField(Exception): pass IMAP = imaplib.IMAP4_SSL def get_email(host, username, password): # ... for message in messages_I_care_about: yield message def fields(msg): url_m = url_re.search(msg) if not url_m: raise MissingField("No URL") user_m = user_re.search(msg) if not user_m: raise MissingField("No username") pass_m = pass_re.search(msg) if not pass_m: raise MissingField("No password") return [m.group(1).strip() for m in (url_m, user_m, pass_m)] def create_temp_html(url, username, password): f = NamedTemporaryFile(mode='w', suffix='.html') # HTML hard-coded here, but could be # scraped from the site, parsed with BeautifulSoup # searched for the form/uname/pwd values # and more programatically generated # but this is the lazy version you get for free ;-) f.write(""" Some Title Hang on...time to log in...

""" % ( url, urllib.quote_plus(username), urllib.quote_plus(password), ) ) f.flush() return f if __name__ == "__main__": HOST = 'mail.example.com' USER = 'email_username at example.com' PASS = 'SecretEmailPassword' EXPECTED_SENDER = 'somebody at example.net' for message in get_email(HOST, USER, PASS): msg = email.message_from_string(message) # if you don't want to limit the sender # delete/comment the next 3 lines if EXPECTED_SENDER not in msg['from'].lower(): print "Unexpected sender...ignoring %r" % msg['subject'] continue for part in msg.walk(): # you may not want to skip HTML portions or other # MIME-types like attachments, but whatever if part.get_content_type() != 'text/plain': continue try: url, username, password = fields(msg.get_payload()) print url, username, password except MissingField, e: print e continue f = create_temp_html(url, username, password) stderr.write( "Opening %r in %s\n" % (f.name, webbrowser.get().basename.title())) webbrowser.open(f.name) time.sleep(30) # wait for the browser to load the file # otherwise this .close() will delete it # before the web-browser could open it f.close() ########################## Adjust regexps to find your URL/uname/pwd as desired, create the get_email() iterator that finds all the messages in your inbox that match your criteria (such as "not already seen, has XYZ in the subject, etc") I'm not 100% sure of my JavaScript in the form.onload but you can also tweak that if your JS is enabled and you want to tinker with it for auto-login. -tkc From aahz at pythoncraft.com Mon May 31 17:37:53 2010 From: aahz at pythoncraft.com (Aahz) Date: 31 May 2010 14:37:53 -0700 Subject: Vote to Add Python Package "pubsub" to the Python Standard Library References: <6b9d2898-4166-40b4-9016-dc55dee77d00@q33g2000vbt.googlegroups.com> Message-ID: In article <6b9d2898-4166-40b4-9016-dc55dee77d00 at q33g2000vbt.googlegroups.com>, Tom wrote: > >I vote for adding the Python package "pubsub" to the Python standard >library. It has recently been added to wxpython (replacing the old >wx.lib.pubsub package), but it has application to non-gui programs as >well. You should create a ticket on bugs.python.org -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From breamoreboy at yahoo.co.uk Mon May 31 17:38:42 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 31 May 2010 22:38:42 +0100 Subject: xrange issue 7721 In-Reply-To: <4C0371CB.401@v.loewis.de> References: <4C02EC98.9020507@v.loewis.de> <4c02f5fa$0$14140$c3e8da3@news.astraweb.com> <4C0371CB.401@v.loewis.de> Message-ID: On 31/05/2010 09:22, Martin v. Loewis wrote: >>> For the record, the issue you were looking at was a complaint that the >>> documentation is incorrect. This had been fixed by correcting the >>> documentation. >> >> I think Mark's point is that the code snippet given isn't a full >> replacement for xrange, since it doesn't support negative step sizes, nor >> does it raise an exception on step=0. > > Still, that issue is different from 7721. 7721 was about a > completely-nonworking example in the documentation. This error has been > fully > corrected. So this issue *is* fixed, reopining it would be > inappropriate. > > There may be another issue with this example, which should be reported > separately. > >> Since the docs are read by people with vastly different levels of >> experience, skill and nous, I think it's a reasonable complaint to make. > > That may well be. The proposed approach (reopen the issue) is what I > consider unreasonable. > > Regards, > Martin Just forget it, if anyone falls foul of the garbage that has been put into the documentation, you can accept responsibility. Disgusted and offended. Mark Lawrence. From davea at ieee.org Mon May 31 18:39:52 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 31 May 2010 18:39:52 -0400 Subject: writing numbers in binary file In-Reply-To: References: <0d47a9d6-3bae-4a99-a11e-8e76343895a8@f13g2000vbm.googlegroups.com> Message-ID: <4C043AB8.3040500@ieee.org> eskandari wrote: > On May 31, 12:30 pm, MRAB wrote: > >> eskandari wrote: >> >>> Hi, >>> I am a newbie in python. I have an data.pickle file which is >>> serialized form of an "array of strings", I want to write their >>> offsets in another binary file, so an C++ program can read and analyse >>> them. >>> But when I try to write offset (number) in binary file, it raise >>> exception below in line "offsetfile.write(offset)" >>> "TypeError: argument 1 must be string or read-only buffer, not int" >>> >>> I search the internet, find that all suggest converting number to >>> string ---with str()---and then write string to file. >>> But I shouldn't do this. because the above mentioned C++ function, >>> read file with this assumption that there are numbers in file. >>> So I want to know, Is there any way to produce an binary file >>> containing numbers same as the way C++ does? >>> Can anybody help me? >>> >> You can't write ints to a file, but you can write bytestrings ('str' in >> Python 2, 'bytes' in Python 3). >> >> Use the 'struct' module to convert the int to a bytestring, and remember >> to open the file as a binary file. >> > > Thanks alot, > I have an question, if I do so, Will the second program (C++ program) > which process this file, encounter any problem while parsing the file? > It find number of integers by filelen/4 and ..... (It assumes that > file was created as the same way which C++ does) > Thanks in advance > > You talk as if C++ has a single way to write a file, or read a file. It has dozens of possibilities, as does Python. In another message, you refer to four bytes per number, so it's possible you're talking about reading directly from the file into an int variable. If you know that the C++ program is reading a file in mode 'b' directly to an unsigned int, and is compiled in 32 bits, and has the same endian-ness as the Python program, chances are the struct will work correctly, if you're running Python under the same conditions. DaveA From cjwilliams43 at gmail.com Mon May 31 19:34:55 2010 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Mon, 31 May 2010 19:34:55 -0400 Subject: if, continuation and indentation In-Reply-To: <4c042759$1@dnews.tpgi.com.au> References: <0cebbaa4-7294-4716-8368-ac2d0b6227d2@6g2000prg.googlegroups.com> <4c042759$1@dnews.tpgi.com.au> Message-ID: On 31-May-10 17:15 PM, Lie Ryan wrote: > On 05/31/10 05:10, Colin J. Williams wrote: >> On 30-May-10 01:50 AM, Nathan Rice wrote: >>> On 27-May-10 08:48 AM, Xavier Ho wrote: >>> > On 27 May 2010 22:22, HH>> > >> >> wrote: >>> >>> > >>> > if (width == 0 and >>> > height == 0 and >>> > color == 'red' and >>> > emphasis == 'strong' or >>> > highlight> 100): >>> > raise ValueError("sorry, you lose") >>> > >>> > >>> > I've gotta say - I've bumped into this problem before, >>> and I'm sure many >>> > other have - this is a valid question. It just hasn't >>> bothered me enough >>> > to ask... >>> > >>> > Correct me if I'm wrong, but I think the following is >>> equivalent, and >>> > looks better. Although this won't fix all ugly cases in >>> that problem.. >>> > >>> > if (width, height, color, emphasis) == (0, 0, 'red', >>> 'strong') or >>> > highlight> 100: >>> > raise ValueError("sorry, you lose") >>> > >>> > Cheers, >>> > Xav >>> >>> but nobody commented. >>> >>> Colin W. >>> >>> >>> Colin: >>> Sure, you can do it that way. IMO, though, the OP was wrong, >>> and so >>> is the PEP. Source code is meant to communicate. So it must >>> transmit >>> the correct information to the computer; it also must inform your >>> coworkers. That means that you have a responsibility to care >>> what >>> they think, though you privately have your opinions. Another >>> reason >>> the PEP is faulty in this circumstance is that a misplaced >>> backslash, >>> or a missing one, is easily found and fixed. A misplaced >>> parentheses, >>> or just one of a pair, will transform your source code into >>> something >>> which may compile and then give faulty results: a disaster. >>> So keep it simple, and make it legible. >>> Yours, >>> John >>> >>> >>> IMHO complete garbage, if your editor doesn't show misplaced or >>> missing parenthesis by highlighting you're using the wrong editor :) >>> >>> >> >> Perhaps the arrangement below shows the matching a little better than >> the Xav suggestion. The main point is that, to me, the tuple shows the >> item by item matching better than a series of and clauses: >> >> # tif.py >> >> (width, height, color, emphasis)= 0, 0, 'red', 'strong' >> highlight= 99 >> if (width, height, color, emphasis) == \ >> ( 0, 0, 'red', 'strong') or highlight> 100: >> raise ValueError("sorry, you lose") > > How about: > > all(a == b for a,b in ((width, 0), (height, 0), (color, 'red'), > (emphasis, 'strong')))) You need to add "or highlight > 100" From sjmachin at lexicon.net Mon May 31 20:12:09 2010 From: sjmachin at lexicon.net (John Machin) Date: Mon, 31 May 2010 17:12:09 -0700 (PDT) Subject: Help with Regexp, \b References: <44a791af-9654-4444-807a-366c256f95ad@q23g2000vba.googlegroups.com> <4b812698-4779-4502-8cdc-bf5c47dd5a0c@o39g2000vbd.googlegroups.com> Message-ID: <06964c58-d63a-4065-83fb-9b9e32047b3b@y6g2000pra.googlegroups.com> On May 30, 1:30?am, andrew cooke wrote: > > That's what I thought it did... ?Then I read the docs and confused > "empty string" with "space"(!) and convinced myself otherwise. ?I > think I am going senile. Not necessarily. Conflating concepts like "string containing whitespace", "string containing space(s)", "empty aka 0-length string", None, (ASCII) NUL, and (SQL) NULL appears to be an age- independent problem :-) From greg.ewing at canterbury.ac.nz Mon May 31 20:46:01 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 01 Jun 2010 12:46:01 +1200 Subject: GUI programs In-Reply-To: References: Message-ID: <86j303Fih6U1@mid.individual.net> jyoung79 at kc.rr.com wrote: > Has anyone had any luck getting > PyGUI working on Snow Leopard? I can't seem to get the blobedit > example to work. I've received reports that it seems to be problematic on Snow Leopard. Unfortunately I don't have access to a Snow Leopard system at the moment to troubleshoot it. -- Greg From steveo at syslang.net Mon May 31 20:51:02 2010 From: steveo at syslang.net (Steven W. Orr) Date: Mon, 31 May 2010 20:51:02 -0400 Subject: problem with Descriptors Message-ID: <4C045976.9010901@syslang.net> I just discovered descriptors but what I want to do isn't working right. I hope this isn't too long. :-( Here's what I have that works: class C(object): def g(self): print "dir(g):",dir(self.g) def f(self, ss): print "ss = ", ss cc = C() cc.ff = f.__get__(C,cc) cc.ff('Round 3') And when I run it, it prints out: ss = Round 3 That's the part that works. I'm trying to use the above construct to implement a new kind of dict(). The idea is that I want to create a dict that knows about certain values that can have dependencies on other values. If you change a value that is a dependency of another value within the dict, then the target value will automatically recompute itself. In the example below, the value of the key "range" is dependent on the value of the key "stop". When I run the code, the function recalc_range seems to be successfully saved as a bound method. (The save happens in AddDep) But then when I try to invoke the saved bound method, it yells at me that the arg to __getitem__ is of the wrong type. Does anyone see what I did wrong? class BalancedDict(dict): def __init__( self, initval={}, depDesc=None ): dict.__init__(self) self.target = [] self.deplist = [] self.recalc_f = [] self.addDep( depDesc ) if isinstance(initval, dict): dict.update(self, initval) def __setitem__(self, key, value): # setting a keyword dict.__setitem__(self, key, value) for ii, deps in enumerate(self.deplist): if key in deps: print '__setitem__:recalc_f[%d]'%ii,self.recalc_f[ii] print '__setitem__:targ:',self.target[ii] print '__setitem__:deplist:',self.deplist[ii] self.recalc_f[ii](self.target[ii],self.deplist[ii]) def addDep(self, depDesc=None): if not depDesc: return for jj in depDesc: self.target.append(jj[0]) self.deplist.append(jj[1]) self.recalc_f.append(None) idx = len(self.recalc_f) - 1 self.recalc_f[idx] = jj[2].__get__(BalancedDict, self) print 'addDep:self.recalc_f[%d]:'%idx, self.recalc_f[idx] if __name__ == "__main__": import pprint def recalc_range(self, target, deplist): print 'recalc_range:type(self):', type(self), "self:",self print 'recalc_range:target:', target print 'recalc_range:deplist:', deplist stop = None for ii in deplist: if ii == 'stop': print "ii:",ii print "self:", self, type(self) stop = self.__getitem__(ii) if ( isinstance( stop, int ) ): self.__setitem__( self[target], range( stop ) ) pp = pprint.PrettyPrinter() dd = BalancedDict() print 'dd: Init' pp.pprint(dd) dd.addDep([['range', ['stop'], recalc_range]]) dd['stop'] = 40 print 'dd: After start stop and step' pp.pprint(dd) C:\Users\Steve\Documents\PythonSamples>python -i vfunc3.py dd: Init {} addDep:self.recalc_f[0]: > __setitem__:recalc_f[0] > __setitem__:targ: range __setitem__:deplist: ['stop'] recalc_range:type(self): self: recalc_range:target: range recalc_range:deplist: ['stop'] ii: stop self: Traceback (most recent call last): File "vfunc3.py", line 55, in dd['stop'] = 40 File "vfunc3.py", line 20, in __setitem__ self.recalc_f[ii](self.target[ii],self.deplist[ii]) File "vfunc3.py", line 46, in recalc_range stop = self.__getitem__(ii) TypeError: descriptor '__getitem__' requires a 'dict' object but received a 'str' >>> -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From huangqiang.zhou at gmail.com Mon May 31 21:47:59 2010 From: huangqiang.zhou at gmail.com (huangqiang.zhou) Date: Tue, 1 Jun 2010 09:47:59 +0800 Subject: Error building on cygwin Message-ID: <201006010947536718608@gmail.com> Hi All: When i install wxPython on cygwin in windows xp, i get this error and can't continue... my enviroment: $ cygcheck -c cygwin Cygwin Package Information Package Version Status cygwin 1.7.5-1 Incomplete wxPython-src-2.8.11.0 Following the build instructions on www.wxpython.org, before the installing of wxPython i have installed additional packages as : autoconf automake gcc-core gcc-g++ gcc-mingw gcc-mingw-core gcc-mingw-g++ make mingw-runtime mingw-zlib patch w32api // i can't find this package when i am installing cygwin, so it was not be installed Then: i put the sourcecode to /usr/sr/wxPython-src-2.8.11.0 $cd /usr/sr/wxPython-src-2.8.11.0 $CC="gcc -mno-cygwin -mwindows" \ CXX="g++ -mno-cygwin -mwindows" \ LDFLAGS="-mno-cygwin -mwindows" \ ./configure \ --with-msw \ --build=i686-pc-mingw32 \ --prefix=/opt/wx/2.8 \ --enable-unicode \ --enable-debug \ --enable-debug_gdb \ --enable-geometry \ --enable-display \ --enable-shared \ --enable-optimise \ --with-expat=builtin \ --with-regex=builtin \ --with-zlib=builtin $make $* \ && make -C contrib/src/gizmos $* \ && make -C contrib/src/stc $* and then : ./src/msw/utils.cpp: In function ?const wxChar* wxGetHomeDir(wxString*)?: ./src/msw/utils.cpp:392: error: cannot convert ?const char*? to ?const wxChar *? for argument ?1? to ?wxChar* wxGetenv(const wxChar*)? ./src/msw/utils.cpp:408: warning: ?int cygwin_conv_to_full_win32_path(const cha r*, char*)? is deprecated (declared at /usr/include/sys/cygwin.h:52) ./src/msw/utils.cpp:408: error: cannot convert ?wxString? to ?const char*? f or argument ?1? to ?int cygwin_conv_to_full_win32_path(const char*, char*)? ./src/msw/utils.cpp: In function ?wxChar* wxGetUserHome(const wxString&)?: ./src/msw/utils.cpp:472: error: new declaration ?wxChar* wxGetUserHome(const wx String&)? ./include/wx/utils.h:528: error: ambiguates old declaration ?const wxWCharBuffe r wxGetUserHome(const wxString&)? make: *** [basedll_msw_utils.o] Error 1 please help! regards. 2010-06-01 huangqiang.zhou -------------- next part -------------- An HTML attachment was scrubbed... URL: