Re: Tkinter unbinding

2008-12-19 Thread Bad Mutha Hubbard
Roger wrote:

> I've done a lot of googling for this topic and I fear that it's not
> possible.  I have a widget that is overloaded with several bindings.
> I want to be able to unbind one method form the same Event without
> destroying all the other bindings to the same event that's associated
> to the same widget.
>
> For example:
>
> import Tkinter
>
> def test():
> print 'test'
>
> def test2():
> print 'test2'
>
> root = Tkinter.Tk()
> funcid1 = root.bind("<1>", lambda e: test())
> funcid2 = root.bind("<1>", lambda e: test2(), add='+')
> root.unbind("<1>", funcid2)
> root.mainloop()
>
> When run neither <1> binding will exist against the root because the
> unbind will unbind all the functions associated with that event.
> However, in this example, I only want to unbind test2 not test1.
>
> Any help is greatly appreciated.  Thanks!
> Roger.

I believe you've discovered a bug.  Aside from recommending trying
wxWidgets, here's the source of the unbind function in Tkinter.py:

def unbind(self, sequence, funcid=None):
"""Unbind for this widget for event SEQUENCE  the
function identified with FUNCID."""
self.tk.call('bind', self._w, sequence, '')
if funcid:
self.deletecommand(funcid)

---
First, it replaces all bindings for the sequence with the empty string,
i.e., it deletes all bindings for that event unconditionally.  THEN it
calls deletecommand() with the funcid, who knows what that does.  My Tcl
is not so sharp.
I have an idea for a workaround, let me see if it works...
-Chuckk

--
http://mail.python.org/mailman/listinfo/python-list


Re: Minor Typo in doc

2008-12-19 Thread Kurt Mueller
Steve Holden schrieb:
> Kurt Mueller wrote:
>> Hi
>> There is a minor typo in the new doc in:
>> http://www.python.org/doc/2.6/library/signal.html
>> --
>> signal.SIG_DFL¶
>> This is one of two standard signal handling options;
>> it will simply perform the default function for the signal.
>> For example, on most systems the default action for SIGQUIT
>> is to dump core and exit, while the default action for
>> SIGCLD
>> is to simply ignore it.
>> --
>> SIGCLD
>> should be
>> SIGCHLD
>> Should I make a bug report in http://bugs.python.org

> Yes. The documentation give you a link to follow from the bottom of
> each page.
> regards
> Steve

Yesterday evening I made a bug report on bugs.python.org.
(I opened a issue).
This morning it has already been fixed.
(It has been assigned to benjamin.peterson.
 He has fixed it.
 The issue has been closed.)


> Benjamin Peterson  added the comment:
> Thanks for the report! Fixed in r67848.
> --
> nosy: +benjamin.peterson
> resolution: -> fixed
> status: open -> closed

So, that is a great community!
isn't it?
Thanks to all who make this possible.



Grüessli
-- 
Kurt Mueller

-- 
Kurt Müller, m...@problemlos.ch 


--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter unbinding

2008-12-19 Thread Bad Mutha Hubbard
Bad Mutha Hubbard wrote:

> Roger wrote:
>
>> I've done a lot of googling for this topic and I fear that it's not
>> possible.  I have a widget that is overloaded with several bindings.
>> I want to be able to unbind one method form the same Event without
>> destroying all the other bindings to the same event that's associated
>> to the same widget.
>>
>> For example:
>>
>> import Tkinter
>>
>> def test():
>> print 'test'
>>
>> def test2():
>> print 'test2'
>>
>> root = Tkinter.Tk()
>> funcid1 = root.bind("<1>", lambda e: test())
>> funcid2 = root.bind("<1>", lambda e: test2(), add='+')
>> root.unbind("<1>", funcid2)
>> root.mainloop()
>>
>> When run neither <1> binding will exist against the root because the
>> unbind will unbind all the functions associated with that event.
>> However, in this example, I only want to unbind test2 not test1.
>>
>> Any help is greatly appreciated.  Thanks!
>> Roger.
>
> I believe you've discovered a bug.  Aside from recommending trying
> wxWidgets, here's the source of the unbind function in Tkinter.py:
>
> def unbind(self, sequence, funcid=None):
> """Unbind for this widget for event SEQUENCE  the
> function identified with FUNCID."""
> self.tk.call('bind', self._w, sequence, '')
> if funcid:
> self.deletecommand(funcid)
>
> ---
> First, it replaces all bindings for the sequence with the empty string,
> i.e., it deletes all bindings for that event unconditionally.  THEN it
> calls deletecommand() with the funcid, who knows what that does.  My Tcl
> is not so sharp.
> I have an idea for a workaround, let me see if it works...
> -Chuckk

Alas, my workaround doesn't work either.  Tkinter.py also states that
calling bind with only an event sequence will return all bindings for
that sequence; I was thinking I could then remove the function in
question from that list and call bind again with each of the
functions in the remaning list as argument. I had
high hopes. The return value of calling bind with no target function
is just about Tcl nonsense:

#!/usr/bin/env python

import Tkinter

def test(event):
print 'test'

def test2(event):
print 'test2'

root = Tkinter.Tk()
funcid1 = root.bind("<1>", test)
funcid2 = root.bind("<1>", test2, add='+')
print funcid1, funcid2

bound = root.bind('')
print "bound:", bound
#root.unbind("<1>", funcid=funcid2)
root.mainloop()

---
Note that I took out the lambdas and gave event arguments to the
functions; if you did that on purpose, because you need to call the same
functions without events, then just ignore that...
SO, the other workaround, which I've used, is to bind the event to a
generic function, and have that generic function conditionally call
the functions you want. I'll go back and try to make an example from
your example. -Chuckk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for amd64 and mingw-w64

2008-12-19 Thread David Cournapeau
On Fri, Dec 19, 2008 at 3:30 PM, "Martin v. Löwis"  wrote:

>
> It's a mistake if libpython26.a gets included in the Win64 installer
> at all; this library is only provided for 32-bit systems. My copy of
> mingw doesn't support Win64 at all.

Please ignore that last point: it looks like it is generated by our
(numpy) build process, and has nothing to do with python per-se.

David
--
http://mail.python.org/mailman/listinfo/python-list


If programming languages were religions...

2008-12-19 Thread gene
very interesting
http://www.aegisub.net/2008/12/if-programming-languages-were-religions.html

"Python would be Humanism: It's simple, unrestrictive, and all you
need to follow it is common sense. Many of the followers claim to feel
relieved from all the burden imposed by other languages, and that they
have rediscovered the joy of programming. There are some who say that
it is a form of pseudo-code"

compare to
"Perl would be Voodoo - An incomprehensible series of arcane
incantations that involve the blood of goats and permanently corrupt
your soul. Often used when your boss requires you to do an urgent task
at 21:00 on friday night."

and others
--
http://mail.python.org/mailman/listinfo/python-list


Re: eval() and global variables

2008-12-19 Thread Peter Otten
Juan Pablo Romero Méndez wrote:

> The hack given by Peter works fine, except in this case:
> 
 def (fn):
> ... f2 = lambda x,y:(x,y,fn(x,y))
> ... function = type(f2)
> ... f3 = function(f2.func_code,dict())
> ... print f3
> ...
 (lambda x,y:x+y)
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 4, in 
> TypeError: arg 5 (closure) must be tuple

> 
> 
> Strange...

The variable fn must be passed to the lambda somehow. You could return f2()
from (), and f2() would still have to "know" about it. This is called
a "closure".

>>> def f(): pass
...
>>> function = type(f)
>>> print function.__doc__
function(code, globals[, name[, argdefs[, closure]]])

Create a function object from a code object and a dictionary.
The optional name string overrides the name from the code object.
The optional argdefs tuple specifies the default argument values.
The optional closure tuple supplies the bindings for free variables.

In your case we can reuse the closure just like the code:

>>> def outer(fn):
... def inner(x, y): return x + fn(x, y)
... return function(inner.func_code, {}, closure=inner.func_closure)
...
>>> outer(lambda a, b: a*b)(2, 3)
8

While we're at it, let's explore the remaining arguments:

>>> f = outer(lambda a, b: a*b)
>>> g = function(f.func_code, {}, "yadda", (10, 20), f.func_closure)
>>> g

>>> g()
210

Peter

--
http://mail.python.org/mailman/listinfo/python-list


Re: C API and memory allocation

2008-12-19 Thread Stefan Behnel
Aaron Brady wrote:
>>>  Otherwise you can't know its length or change its reference count.
>> The internal representation of Python byte strings is 0 terminated, so
>> strlen() will work.
> 
> As MRAB said, Python strings can contain null bytes,

Sure, they can. Most byte strings I've seen didn't, though. And if you know
that they don't contain any null bytes (UTF-8 serialised XML, for example,
or ASCII encoded text, or ...), 's' is just fine. If you need content *and*
length, use 's#'. Matter of use case, as usual.

Stefan
--
http://mail.python.org/mailman/listinfo/python-list


Online INTERNET JOBS

2008-12-19 Thread hotkatrina4u
Start Your Own INTERNET JOBS AT http://megalinesolutions.googlepages.com/



No Fee Required
--
http://mail.python.org/mailman/listinfo/python-list


ANN: eGenix pyOpenSSL Distribution 0.8.0-0.9.8i-1

2008-12-19 Thread eGenix Team: M.-A. Lemburg


ANNOUNCING

   eGenix.com pyOpenSSL Distribution

Version 0.8.0-0.9.8i-1


 An easy to install and use repackaged distribution
   of the pyOpenSSL Python interface for OpenSSL -
  available on Windows and Unix platforms


This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.8.0-0.9.8i-1-GA.html



INTRODUCTION

The eGenix.com pyOpenSSL Distribution includes everything you need to
get started with SSL in Python. It comes with an easy to use installer
that includes the most recent OpenSSL library versions in pre-compiled
form.

pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/)
that allows writing SSL aware networking applications as well as
certificate management tools.

OpenSSL is an open-source implementation of the SSL protocol
(http://www.openssl.org/).

For more information, please see the product page:

http://www.egenix.com/products/python/pyOpenSSL/



NEWS

This third release of the eGenix.com pyOpenSSL Distribution upgrades
pyOpenSSL to version 0.8, which includes a few bug fixes related to
threading.

Please note that OpenSSL, the underlying SSL engine, does not allow
sharing connections between threads. This is a little known fact which
could in the past cause pyOpenSSL to crash Python. Jean-Paul Calderone,
the maintainer of pyOpenSSL, has added fixes in 0.8 to prevent those
crashes.

We have also fixed several compiler warnings found in the code. The
version of pyOpenSSL you find in the source release has those patches
applied.

Binaries are available for Linux x86 and x64 as well as Windows x86 and
include pyOpenSSL 0.8.0 as well as the OpenSSL 0.9.8i libraries.



DOWNLOADS

The download archives and instructions for installing the package can
be found at:

http://www.egenix.com/products/python/pyOpenSSL/



UPGRADING

Before installing this version of pyOpenSSL, please make sure that
you uninstall any previously installed pyOpenSSL version. Otherwise,
you could end up not using the included OpenSSL libs.

___

SUPPORT

Commercial support for these packages is available from eGenix.com.
Please see

http://www.egenix.com/services/support/

for details about our support offerings.

Enjoy,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Dec 19 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2008-12-02: Released mxODBC.Connect 1.0.0  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/



--
http://mail.python.org/mailman/listinfo/python-list


Re: importing csv file into sqlite

2008-12-19 Thread Peter Otten
James Mills wrote:

> values = ",".join(["\"%s\"" % x for x in line])
> print "INSERT INTO %s %s VALUES (%s);" % (table, fields, values)

http://xkcd.com/327/


--
http://mail.python.org/mailman/listinfo/python-list


List comprehension in if clause of another list comprehension

2008-12-19 Thread
Hi!

In [69]: a = 'a b c'
In [70]: b = 'a b, c d'

In [74]: [i for i in a.split() if i not in b.split()]
Out[74]: ['b']

Everything ok.

In [77]: b.split() == [i for i in b.split()]
Out[77]: True

As expected. Now, put this in the first list comprehension:

In [80]: [i for i in a.split() if i not in [i for i in b.split()] ]
Out[80]: ['d']

H... why is that?

Regards!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generator slower than iterator?

2008-12-19 Thread Raymond Hettinger
> FedericoMoreirawrote:
> > Hi all,
>
> > Im parsing a 4.1GB apache log to have stats about how many times an ip
> > request something from the server.
>
> > The first design of the algorithm was
>
> > for line in fileinput.input(sys.argv[1:]):
> >     ip = line.split()[0]
> >     if match_counter.has_key(ip):
> >         match_counter[ip] += 1
> >     else:
> >         match_counter[ip] = 1
 . . .
> > Should i leave fileinput behind?

Yes.  fileinput is slow because it does a lot more than just read
files.

> > Am i using generators with the wrong aproach?

No need for a generator here.  The time is being lost with fileinput,
split, and the counting code.  Try this instead:

match_counter = collections.defaultdict(int)
for filename in sys.argv[1:]:
for line in open(filename):
ip, sep, rest = line.partition(' ')
match_counter[ip] += 1

If you're on *nix, there's a fast command line approach:

cut -d' ' -f1 filelist | sort | uniq -c






--
http://mail.python.org/mailman/listinfo/python-list


Re: Factoring Polynomials

2008-12-19 Thread Tim Rowe
2008/12/18 Scott David Daniels :

> def quadsolve(a, b, c):
>try:
>discriminant = sqrt(b**2 - 4 * a * c)

The discriminant of a quadratic is more usually just the b**2 - 4 * a
* c part, not the square root of it. Testing that for negative, zero
or positive avoids the need to use an exception for a normal case.

-- 
Tim Rowe
--
http://mail.python.org/mailman/listinfo/python-list


[Pyrex] Compiling via setuptools

2008-12-19 Thread Kless
When I use the next command in my home system:

  $ python setup.py develop

Pyrex compiles the '.pyx' file without any problem. But after of
uploading it to Pypi, and when is installed via 'easy_install' it
doesn't builds any more. (I had to upload the '.c' file compiled on my
system)

You can see here how has been configured:
http://www.bitbucket.org/ares/bcryptwrap/src/tip/setup.py

and here where I had to add any files:
http://www.bitbucket.org/ares/bcryptwrap/src/tip/MANIFEST.in
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-19 Thread Raymond Hettinger
On Dec 12, 7:51 am, Marco Mariani  wrote:
> Filip Gruszczyński wrote:
> > I am not doing it, because I need it. I can as well use "if not elem
> > is None",
>
> I suggest "if elem is not None", which is not quite the same.

They are semantically the same.  In theory, Filip's would run slower
because of the time to negate the is-test, but the peephole optimizer
recognizes the opportunity to make the substitution so it works out
exactly the same:


>>> dis(compile('x is not None', '', 'eval'))
  1   0 LOAD_NAME0 (x)
  3 LOAD_CONST   0 (None)
  6 COMPARE_OP   9 (is not)
  9 RETURN_VALUE
>>> dis(compile('not x is None', '', 'eval'))
  1   0 LOAD_NAME0 (x)
  3 LOAD_CONST   0 (None)
  6 COMPARE_OP   9 (is not)
  9 RETURN_VALUE

Raymond
--
http://mail.python.org/mailman/listinfo/python-list


Re: List comprehension in if clause of another list comprehension

2008-12-19 Thread Peter Otten
Vedran Furac( wrote:

> Hi!
> 
> In [69]: a = 'a b c'
> In [70]: b = 'a b, c d'
> 
> In [74]: [i for i in a.split() if i not in b.split()]
> Out[74]: ['b']
> 
> Everything ok.
> 
> In [77]: b.split() == [i for i in b.split()]
> Out[77]: True
> 
> As expected. Now, put this in the first list comprehension:
> 
> In [80]: [i for i in a.split() if i not in [i for i in b.split()] ]
> Out[80]: ['d']
> 
> H... why is that?

>>> a = "abc"
>>> b = "a b, c d".split()
>>> b
['a', 'b,', 'c', 'd']
>>> [i for i in a if i not in b]
['b']

As expected, so far, but now comes the critical step:

>>> [i for i in a if i not in [i for i in b]]
['d']

The problem is that list comprehensions do not introduce a new namespace. So
the inner and the outer list comp share the same i. You can either rename
the inner i

>>> [i for i in a if i not in [k for k in b]]
['b']

or use a generator expression which does give a new namespace:

>>> list(x for x in "abc")
['a', 'b', 'c']
>>> x
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'x' is not defined

>>> [i for i in a if i not in (i for i in b)]
['b']

Peter

--
http://mail.python.org/mailman/listinfo/python-list


Re: importing csv file into sqlite

2008-12-19 Thread James Mills
On Fri, Dec 19, 2008 at 8:32 PM, Peter Otten <__pete...@web.de> wrote:
> James Mills wrote:
>
>> values = ",".join(["\"%s\"" % x for x in line])
>> print "INSERT INTO %s %s VALUES (%s);" % (table, fields, values)
>
> http://xkcd.com/327/

It's a tool! Not one meant to be used
publicly from untrusted users.

Free feel to submit a patch as is
the Open Source spirit!

--JamesMills
--
http://mail.python.org/mailman/listinfo/python-list


15000$ per month

2008-12-19 Thread sapanapa...@gmail.com
1500$ per month…
MAKE MONEY 24 HOUR,
THE REAL ONLINE JOB,
http://labnol.homestead.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: List comprehension in if clause of another list comprehension

2008-12-19 Thread
Peter Otten wrote:

> The problem is that list comprehensions do not introduce a new namespace. So
> the inner and the outer list comp share the same i. You can either rename
> the inner i
> 
 [i for i in a if i not in [k for k in b]]
> ['b']
> 
> or use a generator expression which does give a new namespace:
> 
 list(x for x in "abc")
> ['a', 'b', 'c']
 x
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'x' is not defined
> 
 [i for i in a if i not in (i for i in b)]
> ['b']

Thanks!
--
http://mail.python.org/mailman/listinfo/python-list


encoding problem

2008-12-19 Thread digisat...@gmail.com
The below snippet code generates UnicodeDecodeError.
#!/usr/bin/env python
#--*-- coding: utf-8 --*--
s = 'äöü'
u = unicode(s)


It seems that the system use the default encoding- ASCII to decode the
utf8 encoded string literal, and thus generates the error.

The question is why the Python interpreter use the default encoding
instead of "utf-8", which I explicitly declared in the source.
--
http://mail.python.org/mailman/listinfo/python-list


Re: importing csv file into sqlite

2008-12-19 Thread klia


John Machin wrote:
> 
> On Dec 18, 6:20 pm, klia  wrote:
>> klia wrote:
>>
>> > hey guys, i have a hug .csv file which i need to insert it into sqlite
>> > database using python.
>> > my csv data looks like this
>> > Birthday2,12/5/2008,HTC,this is my birthday
>> > Sea,12/3/2008,kodak,sea
>> > birthday4,14/3/2009,samsung,birthday
>> > love,17/4/2009,SONY,view of island
>>
>> > can any one give me a head start codes.
>>
>> > thanks in advance
>>
>> guys so far i came out with this but i get this error
>> was...@linux:~/Project2$ python experment.py
>> Traceback (most recent call last):
>>   File "experment.py", line 13, in 
>>     curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item)
>> sqlite3.ProgrammingError: Incorrect number of bindings supplied. The
>> current
>> statement uses 4, and there are 1 supplied.
>>
>> here's the codes
>>
>> import sqlite3
>> import csv
>>
>> f = open('/home/waseem/Project2/photos.txt')
>> csv.field_size_limit(10) #see below!
> 
> I see nothing "below" that looks at all like an attempt to justify
> setting the field size limit to 10 -- why are you doing that?
> Tends to make one suspect a problem with your delimiter and/or your
> line separator.
> 
>> input = csv.reader(f, delimiter='\t')
> 
> Why \t??? Your data examples show commas -- could this be why you are
> getting one field per line (as Peter has pointed out)?
> 
>> conn = sqlite3.connect('/home/waseem/Project2/picutres.db')
> 
> Is it really called "picutres" instead of "pictures", or are you
> typing the code that you ran again from (your) memory?
> 
>> curse = conn.cursor()
>>
>> curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date
>> INTEGER, Make VARCHAR(50), Tag VARCHAR(100))')
> 
> [OT but to save the next question]
> The column named "Date" is defined to be INTEGER but the data from the
> CSV file will be a str object e.g. "12/5/2008" ... I know sqlite
> cheerfully regards column types as vague reminders rather than
> enforceable constraints on your input, but wouldn't you like to
> convert your dates to e.g. "2008-05-12" before you poke them in? You
> may want to use "ORDER BY Date" at some stage, and so that ORDER BY
> isn't whacked and GROUP BY doesn't give ludicrous results, wouldn't it
> be a good idea to crunch 12/5/2008 and 12/05/2008 into a common format
> so that they compare equal?
>>
>> for item in input:
> 
> I strongly suggest that you try to get a clue about exactly what you
> are getting from the csv reader e.g.
> 
> for line_num, item in enumerate(input_renamed_as_suggested_by_anor):
>print line_num, repr(item)
> 
>>         curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item)
>> curse.commit()
>>
> 
> HTH,
> John
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

hey guys
i took all of your suggestion but my goal ain't yet achieved :-((
these are the codes after changes, john i couldn't really catch what do you
mean by renaming input, is it just normal renaming.i am testing the code on
just simple .csv file with few data in as follows before trying on my hug
csv file but still no joy

"Bithday",12-05-08,"HTC","this is my birthday"
"Sea",12-03-08,"kodak","sea"
"girl","14-03-2009","samsung","birthday"
"love","17-04-2009","SONY","view of island"

import sqlite3
import csv

f = open('/home/waseem/Project2/photos.csv')
input = csv.reader(f, delimiter=',')
conn = sqlite3.connect('/home/waseem/Project2/pictures.db')
curse = conn.cursor()

curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date
INTEGER, Make VARCHAR(50), Tag VARCHAR(100))')
for row in input:
curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row')
curse.commit()

this time i got this error

was...@linux:~/Project2$ python experment.py 
Traceback (most recent call last):
  File "experment.py", line 12, in 
curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row')
sqlite3.IntegrityError: column Name is not unique

i removed the primary key and single quotation mark for '*row' to just *row
but i got the old error which is 

was...@linux:~/Project2$ python experment.py 
Traceback (most recent call last):
  File "experment.py", line 11, in 
curse.execute('INSERT INTO photos VALUES (?,?,?,?)', *row)
TypeError: function takes at most 2 arguments (5 given)
 
-- 
View this message in context: 
http://www.nabble.com/importing-csv-file-into-sqlite-tp21067453p21090356.html
Sent from the Python - python-list mailing list archive at Nabble.com.

--
http://mail.python.org/mailman/listinfo/python-list


Re: encoding problem

2008-12-19 Thread Bruno Desthuilliers

digisat...@gmail.com a écrit :

The below snippet code generates UnicodeDecodeError.
#!/usr/bin/env python
#--*-- coding: utf-8 --*--
s = 'äöü'
u = unicode(s)


It seems that the system use the default encoding- ASCII to decode the
utf8 encoded string literal, and thus generates the error.


Indeed. You want:

u = unicode(s, 'utf-8') # or : u = s.decode('utf-8')


The question is why the Python interpreter use the default encoding
instead of "utf-8", which I explicitly declared in the source.


Because there's no reliable way for the interpreter to guess how what's 
passed to unicode has been encoded ?


s = s.decode("utf-8").encode("latin1")
# should unicode try to use utf-8 here ?
try:
  u = unicode(s)
except UnicodeDecodeError:
  print "would have worked better with "u = unicode(s, 'latin1')"


NB : IIRC, the ascii subset is safe whatever the encoding, so I'd say 
it's a sensible default...

--
http://mail.python.org/mailman/listinfo/python-list


Re: List comprehension in if clause of another list comprehension

2008-12-19 Thread bearophileHUGS
Peter Otten:
> The problem is that list comprehensions do not introduce a new namespace.

I think Python3 fixes this bug.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


How to parsing a sequence of integers

2008-12-19 Thread Steven Woody
Hi,

I am a newbie and is reading the python book.  Could anyone tell me,
how to parsing the following string
   "123 100 12 37 ..."
into a list of integers on which I can then apply max()/min()?

In additional to max/min, is there something like average()?

Thanks in advance.

-
narke
--
http://mail.python.org/mailman/listinfo/python-list


Subclassing standard class: how to write my own __init__?

2008-12-19 Thread kpalamartchouk
Dear All,

I am trying to create a class that would extend functionality of
datetime.date by implementing some functions I need, for example an
optional initialisation by (year, day_of_year) instead of (year,
month, day). I would like the class constructor to behave in the
datetime's default way if there are no keyword arguments and do my own
stuff if there are some.

Here is the minimal example:

=
from datetime import date, timedelta

class MyDateTime(date):
def __init__(self, *arg, **kw):
if len(kw):
year = kw['year']
doy = kw['doy']
my_date = date(year=year, month=1, day=1) + timedelta
(days=doy-1)
date.__init__(self, year = my_date.year, month =
my_date.month, day = my_date.day)
else:
date.__init__(self, *arg)

date1 = MyDateTime(2008, 12, 19)
date2 = MyDateTime(year=2008, doy=354)
=

It works fine when I don't supply any keyword arguments. But if I do,
TypeError is happening:

TypeError: function takes exactly 3 arguments (1 given)

Could you help me to understand where I am wrong?

Thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generator slower than iterator?

2008-12-19 Thread Federico Moreira
Great, 2min 34 secs with the open method =)

but why?

ip, sep, rest = line.partition(' ')
   match_counter[ip] += 1

instead of

match_counter[line.strip()[0]] += 1

strip really takes more time than partition?

I'm having the same results with both of them right now.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parsing a sequence of integers

2008-12-19 Thread Bruno Desthuilliers

Steven Woody a écrit :

Hi,

I am a newbie and is reading the python book.  Could anyone tell me,
how to parsing the following string
   "123 100 12 37 ..."

> into a list of integers on which I can then apply max()/min()?

source = "123 100 12 37"
list_of_ints = [int(part) for part in source.strip().split()]



In additional to max/min, is there something like average()?


Not AFAIK, but it's really trivial

def average(lst):
   """ assume lst is a list of numerics """
   return sum(lst) / len(lst)

--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parsing a sequence of integers

2008-12-19 Thread Marc 'BlackJack' Rintsch
On Fri, 19 Dec 2008 21:20:48 +0800, Steven Woody wrote:

> Hi,
> 
> I am a newbie and is reading the python book.  Could anyone tell me, how
> to parsing the following string
>"123 100 12 37 ..."
> into a list of integers on which I can then apply max()/min()?

In [376]: '123 100 12 37'.split()
Out[376]: ['123', '100', '12', '37']

In [377]: map(int, '123 100 12 37'.split())
Out[377]: [123, 100, 12, 37]

In [378]: max(map(int, '123 100 12 37'.split()))
Out[378]: 123

> In additional to max/min, is there something like average()?

No, but it's easy to implement with `sum()`, `len()` and ``/``.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: encoding problem

2008-12-19 Thread Marc 'BlackJack' Rintsch
On Fri, 19 Dec 2008 04:05:12 -0800, digisat...@gmail.com wrote:

> The below snippet code generates UnicodeDecodeError.
> #!/usr/bin/env
> python
> #--*-- coding: utf-8 --*--
> s = 'äöü'
> u = unicode(s)
> 
> 
> It seems that the system use the default encoding- ASCII to decode the
> utf8 encoded string literal, and thus generates the error.
> 
> The question is why the Python interpreter use the default encoding
> instead of "utf-8", which I explicitly declared in the source.

Because the declaration is only for decoding unicode literals in that 
very source file.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: List comprehension in if clause of another list comprehension

2008-12-19 Thread Marc 'BlackJack' Rintsch
On Fri, 19 Dec 2008 04:26:16 -0800, bearophileHUGS wrote:

> Peter Otten:
>> The problem is that list comprehensions do not introduce a new
>> namespace.
> 
> I think Python3 fixes this bug.

Or removes that feature.  ;-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parsing a sequence of integers

2008-12-19 Thread John Machin
On Dec 20, 12:33 am, Bruno Desthuilliers  wrote:
> Steven Woody a écrit :> Hi,
>
> > I am a newbie and is reading the python book.  Could anyone tell me,
> > how to parsing the following string
> >    "123 100 12 37 ..."
>
>  > into a list of integers on which I can then apply max()/min()?
>
> source = "123 100 12 37"
> list_of_ints = [int(part) for part in source.strip().split()]

The purpose of the .strip() would be ...?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parsing a sequence of integers

2008-12-19 Thread Steven Woody
On Fri, Dec 19, 2008 at 9:33 PM, Bruno Desthuilliers
 wrote:
> Steven Woody a écrit :
>>
>> Hi,
>>
>> I am a newbie and is reading the python book.  Could anyone tell me,
>> how to parsing the following string
>>   "123 100 12 37 ..."
>
>> into a list of integers on which I can then apply max()/min()?
>
> source = "123 100 12 37"
> list_of_ints = [int(part) for part in source.strip().split()]
>
>>
>> In additional to max/min, is there something like average()?
>
> Not AFAIK, but it's really trivial
>
> def average(lst):
>   """ assume lst is a list of numerics """
>   return sum(lst) / len(lst)
>

Cool! Thank all of you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: importing csv file into sqlite

2008-12-19 Thread Peter Otten
klia wrote:

> 
> 
> John Machin wrote:
>> 
>> On Dec 18, 6:20 pm, klia  wrote:
>>> klia wrote:
>>>
>>> > hey guys, i have a hug .csv file which i need to insert it into sqlite
>>> > database using python.
>>> > my csv data looks like this
>>> > Birthday2,12/5/2008,HTC,this is my birthday
>>> > Sea,12/3/2008,kodak,sea
>>> > birthday4,14/3/2009,samsung,birthday
>>> > love,17/4/2009,SONY,view of island
>>>
>>> > can any one give me a head start codes.
>>>
>>> > thanks in advance
>>>
>>> guys so far i came out with this but i get this error
>>> was...@linux:~/Project2$ python experment.py
>>> Traceback (most recent call last):
>>> File "experment.py", line 13, in 
>>> curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item)
>>> sqlite3.ProgrammingError: Incorrect number of bindings supplied. The
>>> current
>>> statement uses 4, and there are 1 supplied.
>>>
>>> here's the codes
>>>
>>> import sqlite3
>>> import csv
>>>
>>> f = open('/home/waseem/Project2/photos.txt')
>>> csv.field_size_limit(10) #see below!
>> 
>> I see nothing "below" that looks at all like an attempt to justify
>> setting the field size limit to 10 -- why are you doing that?
>> Tends to make one suspect a problem with your delimiter and/or your
>> line separator.
>> 
>>> input = csv.reader(f, delimiter='\t')
>> 
>> Why \t??? Your data examples show commas -- could this be why you are
>> getting one field per line (as Peter has pointed out)?
>> 
>>> conn = sqlite3.connect('/home/waseem/Project2/picutres.db')
>> 
>> Is it really called "picutres" instead of "pictures", or are you
>> typing the code that you ran again from (your) memory?
>> 
>>> curse = conn.cursor()
>>>
>>> curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date
>>> INTEGER, Make VARCHAR(50), Tag VARCHAR(100))')
>> 
>> [OT but to save the next question]
>> The column named "Date" is defined to be INTEGER but the data from the
>> CSV file will be a str object e.g. "12/5/2008" ... I know sqlite
>> cheerfully regards column types as vague reminders rather than
>> enforceable constraints on your input, but wouldn't you like to
>> convert your dates to e.g. "2008-05-12" before you poke them in? You
>> may want to use "ORDER BY Date" at some stage, and so that ORDER BY
>> isn't whacked and GROUP BY doesn't give ludicrous results, wouldn't it
>> be a good idea to crunch 12/5/2008 and 12/05/2008 into a common format
>> so that they compare equal?
>>>
>>> for item in input:
>> 
>> I strongly suggest that you try to get a clue about exactly what you
>> are getting from the csv reader e.g.
>> 
>> for line_num, item in enumerate(input_renamed_as_suggested_by_anor):
>>print line_num, repr(item)
>> 
>>> curse.execute('INSERT INTO photos VALUES (?,?,?,?)',item)
>>> curse.commit()
>>>
>> 
>> HTH,
>> John
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>> 
>> 
> 
> hey guys
> i took all of your suggestion but my goal ain't yet achieved :-((
> these are the codes after changes, john i couldn't really catch what do
> you mean by renaming input, is it just normal renaming.i am testing the
> code on just simple .csv file with few data in as follows before trying on
> my hug csv file but still no joy
> 
> "Bithday",12-05-08,"HTC","this is my birthday"
> "Sea",12-03-08,"kodak","sea"
> "girl","14-03-2009","samsung","birthday"
> "love","17-04-2009","SONY","view of island"
> 
> import sqlite3
> import csv
> 
> f = open('/home/waseem/Project2/photos.csv')
> input = csv.reader(f, delimiter=',')
> conn = sqlite3.connect('/home/waseem/Project2/pictures.db')
> curse = conn.cursor()
> 
> curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date
> INTEGER, Make VARCHAR(50), Tag VARCHAR(100))')
> for row in input:
> curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row')

This will try to set

Name="*"
Date="r"
Make="o"
Tag="w"

for all records. Can you work out why?

> curse.commit()
> 
> this time i got this error
> 
> was...@linux:~/Project2$ python experment.py
> Traceback (most recent call last):
>   File "experment.py", line 12, in 
> curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row')
> sqlite3.IntegrityError: column Name is not unique
> 
> i removed the primary key and single quotation mark for '*row' to just
> *row but i got the old error which is
> 
> was...@linux:~/Project2$ python experment.py
> Traceback (most recent call last):
>   File "experment.py", line 11, in 
> curse.execute('INSERT INTO photos VALUES (?,?,?,?)', *row)
> TypeError: function takes at most 2 arguments (5 given)

curse.execute('INSERT INTO photos VALUES (?,?,?,?)', row)

(no '*') will work for the sample data you give above. If you get errors
with your real data you have to fix that data. Follow John's advice to
locate the problematic records.

Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Subclassing standard class: how to write my own __init__?

2008-12-19 Thread Bruno Desthuilliers

kpalamartch...@gmail.com a écrit :

Dear All,

I am trying to create a class that would extend functionality of
datetime.date by implementing some functions I need, for example an
optional initialisation by (year, day_of_year) instead of (year,
month, day).


If that's all you want, then you don't need a subclass - just a plain 
function returning a correctly constructed date object.



I would like the class constructor to behave in the
datetime's default way if there are no keyword arguments and do my own
stuff if there are some.

Here is the minimal example:

=
from datetime import date, timedelta

class MyDateTime(date):


Naming it MyDateTime when it's a date is a bit misleading


def __init__(self, *arg, **kw):
if len(kw):


  if kw: # empty dict eval to False


year = kw['year']
doy = kw['doy']


Will raise a KeyError. Either don't use **kw, or catch the KeyError and 
raise a TypeError instead (which is what's expected when calling a 
function with wrong arguments)



my_date = date(year=year, month=1, day=1) + timedelta
(days=doy-1)
date.__init__(self, year = my_date.year, month =
my_date.month, day = my_date.day)
else:
date.__init__(self, *arg)

date1 = MyDateTime(2008, 12, 19)
date2 = MyDateTime(year=2008, doy=354)
=

It works fine when I don't supply any keyword arguments. But if I do,
TypeError is happening:

TypeError: function takes exactly 3 arguments (1 given)

>

Could you help me to understand where I am wrong?


Some classes implements the __new__ method too (the 'proper' 
constructor), and date is one of them.


class MyDate(date):
def __new__(cls, year, month=None, day=None, doy=None):
if doy:
assert month is None and day is None
d = date(year,1, 1) + timedelta(days=doy-1)
month = d.month
day = d.day
return date.__new__(cls, year, month, day)

date1 = MyDate(2008, 12, 19)
date2 = MyDate(2008, doy=365)

HTH
--
http://mail.python.org/mailman/listinfo/python-list


Re: importing csv file into sqlite

2008-12-19 Thread John Machin
On Dec 19, 11:17 pm, klia  wrote:

[ancient screed snipped]

>
> hey guys
> i took all of your suggestion but my goal ain't yet achieved :-((
> these are the codes after changes, john i couldn't really catch what do you
> mean by renaming input, is it just normal renaming.

Somebody else told you not to use "input", choose another name

> i am testing the code on
> just simple .csv file with few data in as follows before trying on my hug
> csv file but still no joy
>
> "Bithday",12-05-08,"HTC","this is my birthday"
> "Sea",12-03-08,"kodak","sea"
> "girl","14-03-2009","samsung","birthday"
> "love","17-04-2009","SONY","view of island"
>
> import sqlite3
> import csv
>
> f = open('/home/waseem/Project2/photos.csv')
> input = csv.reader(f, delimiter=',')
> conn = sqlite3.connect('/home/waseem/Project2/pictures.db')
> curse = conn.cursor()
>
> curse.execute('CREATE TABLE photos (Name VARCHAR(100) PRIMARY KEY, Date
> INTEGER, Make VARCHAR(50), Tag VARCHAR(100))')
> for row in input:
>         curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row')
> curse.commit()
>
> this time i got this error
>
> was...@linux:~/Project2$ python experment.py
> Traceback (most recent call last):
>   File "experment.py", line 12, in 
>     curse.execute('INSERT INTO photos VALUES (?,?,?,?)', '*row')
> sqlite3.IntegrityError: column Name is not unique
>
> i removed the primary key and single quotation mark for '*row' to just *row
> but i got the old error which is
>
> was...@linux:~/Project2$ python experment.py
> Traceback (most recent call last):
>   File "experment.py", line 11, in 
>     curse.execute('INSERT INTO photos VALUES (?,?,?,?)', *row)
> TypeError: function takes at most 2 arguments (5 given)
>

No, the old error was """sqlite3.ProgrammingError: Incorrect number of
bindings supplied. The current statement uses 4, and there are 1
supplied.""" That's quite different.

Secondly you have already been told about the difference between row
and *row ... as the message says, it wants 2 arguments, (1) the SQL
(2) the sequence of values that will be used to replace the ?s in the
SQL. So just lose the *, OK?



--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parsing a sequence of integers

2008-12-19 Thread Bruno Desthuilliers

John Machin a écrit :

On Dec 20, 12:33 am, Bruno Desthuilliers  wrote:

Steven Woody a écrit :> Hi,


I am a newbie and is reading the python book.  Could anyone tell me,
how to parsing the following string
   "123 100 12 37 ..."

 > into a list of integers on which I can then apply max()/min()?

source = "123 100 12 37"
list_of_ints = [int(part) for part in source.strip().split()]


The purpose of the .strip() would be ...?


Err... To check if you were paying attention ?-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parsing a sequence of integers

2008-12-19 Thread Peter Otten
Bruno Desthuilliers wrote:

> Steven Woody a écrit :
>> In additional to max/min, is there something like average()?
> 
> Not AFAIK, but it's really trivial
> 
> def average(lst):
> """ assume lst is a list of numerics """
> return sum(lst) / len(lst)

If you are using Python 2.x:

>>> def average(lst):
... return sum(lst)/len(lst)
...
>>> average([1,2])
1

So you better throw in a float(...):

>>> def average(lst):
... return sum(lst)/float(len(lst))
...
>>> average([1,2])
1.5

Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: importing csv file into sqlite

2008-12-19 Thread John Machin
On Dec 18, 5:17 pm, "James Mills" 
wrote:

>
> def readCSV(file):
>   if type(file) == str:

Stiff cheese if the file path is a unicode object, eh?

>      fd = open(file, "rU")
>   else:
>      fd = file
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter unbinding

2008-12-19 Thread Roger
> Note that I took out the lambdas and gave event arguments to the
> functions; if you did that on purpose, because you need to call the same
> functions without events, then just ignore that...
> SO, the other workaround, which I've used, is to bind the event to a
> generic function, and have that generic function conditionally call
> the functions you want. I'll go back and try to make an example from
> your example. -Chuckk

Thanks Chuckk!  You've done exactly what I did so far.  I went through
the source in Tkinter.py and had an inkling of what the unbind
function was doing.  I believe, and please correct me if I'm wrong,
in: self.tk.call('bind', self._w, sequence, '') , the '' is unbinding
all methods and I believe the self.deletecommand(funcid) is a
workaround for a memory leak otherwise.  Perhaps self.tk.call('bind',
self._w, sequence, funcid) would work but that's a pure guess.  I
would have liked to investigate the tcl source directly to see if I
could develop a workaround through a tk.call() but that was hitting a
wall in terms of any documentation I could research.  I'm interested
in any workaround you may have however!

You now, I really considered going over to wxwidgets, and I definitely
want to try it after the current app I'm developing is complete, but
I've so much experience with Tkinter now after banging my head against
a wall for months (productive months mind you) on various projects,
it's like an old persnickety friend you just can't give up.  =)

Thanks a ton!
Roger.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter unbinding

2008-12-19 Thread Peter Otten
Roger wrote:

>> Note that I took out the lambdas and gave event arguments to the
>> functions; if you did that on purpose, because you need to call the same
>> functions without events, then just ignore that...
>> SO, the other workaround, which I've used, is to bind the event to a
>> generic function, and have that generic function conditionally call
>> the functions you want. I'll go back and try to make an example from
>> your example. -Chuckk
> 
> Thanks Chuckk!  You've done exactly what I did so far.  I went through
> the source in Tkinter.py and had an inkling of what the unbind
> function was doing.  I believe, and please correct me if I'm wrong,
> in: self.tk.call('bind', self._w, sequence, '') , the '' is unbinding
> all methods and I believe the self.deletecommand(funcid) is a
> workaround for a memory leak otherwise.  Perhaps self.tk.call('bind',
> self._w, sequence, funcid) would work but that's a pure guess.  I
> would have liked to investigate the tcl source directly to see if I
> could develop a workaround through a tk.call() but that was hitting a
> wall in terms of any documentation I could research.  I'm interested
> in any workaround you may have however!

The documentation for bind in tcl is here

http://www.tcl.tk/man/tcl8.4/TkCmd/bind.htm

and as far as I understand it doesnt support unbinding selected callbacks,
either. I'd suggest a plain-python workaround along the lines of

import Tkinter

def test(event):
print 'test'

def test2(event):
print 'test2'

root = Tkinter.Tk()
root.geometry("200x100+100+100")

class Multiplexer:
def __init__(self):
self.funcs = []
def __call__(self, event):
for f in self.funcs:
f(event)
def add(self, f):
self.funcs.append(f)
return f
def remove(self, f):
self.funcs.remove(f)

m = Multiplexer()
m.add(test)
m.add(test2)
root.bind("<1>", m)

def unbind():
print "unbind"
m.remove(test2)

button = Tkinter.Button(root, text="unbind test2", command=unbind)
button.pack()

root.mainloop()

Peter
--
http://mail.python.org/mailman/listinfo/python-list


How to read stdout from subprocess as it is being produced

2008-12-19 Thread Alex
Hi,

I have a Pyhon GUI application that launches subprocess.
I would like to read the subprocess' stdout as it is being produced
(show it in GUI), without hanging the GUI.

I guess threading will solve the no-hanging issue, but as far as I
searched for now, I've only seen how to read the stdout after
subprocess is finished.

Thanks!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter unbinding

2008-12-19 Thread Roger
> either. I'd suggest a plain-python workaround along the lines of

Wow.  You just blew my mind.  I'm going to play with this.  Thanks a
lot, I've really learned a lot in just that small bit.  I don't have
much experience in playing with a lot of the 'private' calls such as
__call__.  I need to do some more reading.

Roger.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to read stdout from subprocess as it is being produced

2008-12-19 Thread anthony . tolle
On Dec 19, 9:34 am, Alex  wrote:
> Hi,
>
> I have a Pyhon GUI application that launches subprocess.
> I would like to read the subprocess' stdout as it is being produced
> (show it in GUI), without hanging the GUI.
>
> I guess threading will solve the no-hanging issue, but as far as I
> searched for now, I've only seen how to read the stdout after
> subprocess is finished.
>
> Thanks!

If I'm interpreting your needs correctly, then you may find this
module helpful:

http://code.activestate.com/recipes/440554/

I've used it successfully in the past when I wanted to use native
python code (no C extensions necessary) for asynchronous reading from
a child process.

I'm not sure if later versions of Python (2.6, 3.0) support this in
the standard library.  I haven't researched it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to read stdout from subprocess as it is being produced

2008-12-19 Thread Albert Hopkins
On Fri, 2008-12-19 at 06:34 -0800, Alex wrote:
> Hi,
> 
> I have a Pyhon GUI application that launches subprocess.
> I would like to read the subprocess' stdout as it is being produced
> (show it in GUI), without hanging the GUI.
> 
> I guess threading will solve the no-hanging issue, but as far as I
> searched for now, I've only seen how to read the stdout after
> subprocess is finished.
> 

I believe that's going to be highly dependent upon the particular, yet
unspecified, GUI toolkit/API.

There are probably a few ways. You're toolkit might native support for
this, but one way would be to use a timer.  Here is some pseudocode:

class MyWindow(toolkit.Window):
def __init__(self, ...):
...
self.subprocess = subprocess.Popen(..., stdout=subprocess.PIPE)
self.running = True

...
toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout)

def read_stdout(self, ...):
if not self.running:
return
char = self.subprocess.stdout.read(1)
if char == '':
self.running = False
return
self.update_something(char)
toolkit.set_timeout(TIMEOUT_VAL, self.read_stdout)


--
http://mail.python.org/mailman/listinfo/python-list


Tix.Balloon crashes in Python 2.61 Windows

2008-12-19 Thread andrew . gregory
I've found that Tix GUI applications crash after switching to Python
2.6.1 (Windows XP) when Balloons are used. IDLE gives this error
message:

Traceback (most recent call last):
  File "D:\PyFiles\InstrumentSetup\Automenu.py", line 217, in 
else: displayedwidget=MainWidget(root, CS)
  File "D:\PyFiles\InstrumentSetup\Automenu.py", line 155, in __init__
b = Tix.Balloon(MyFrame)
  File "C:\Python26\lib\lib-tk\Tix.py", line 529, in __init__
TixWidget.__init__(self, master, 'tixBalloon', static, cnf, kw)
  File "C:\Python26\lib\lib-tk\Tix.py", line 307, in __init__
self.tk.call(widgetName, self._w, *extra)
TclError: unknown color name "{#60}"

A Windows message box came up also. It gave the message:
The exception unknown exception (0x4015) occurred in the
application at location 0x1e03a63b

Perhaps Tix.Balloon has been omitted from the test suite?

I tried searching but cannot see this reported elsewhere. Can anyone
else confirm this behaviour? Where is the best place to report this
bug?  I can supply a script demonstrating the problem.


Andrew.
--
http://mail.python.org/mailman/listinfo/python-list


change string to unicode

2008-12-19 Thread jyoung79
If I have a string like so:

a = '\\u03B1'

and I want to make it display a Greek alpha character, is there a way to 
convert it to unicode ('\u03B1')?  I tried concatenating it like this:

'\u' + '03B1'

but that didn't work.  I'm working in Python 3.0 and was curious if this could 
be done.

Thanks.

Jay
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter unbinding

2008-12-19 Thread Peter Otten
Roger wrote:

>> either. I'd suggest a plain-python workaround along the lines of
> 
> Wow.  You just blew my mind.  I'm going to play with this.  Thanks a
> lot, I've really learned a lot in just that small bit.  I don't have
> much experience in playing with a lot of the 'private' calls such as
> __call__.  I need to do some more reading.

Here's a non-OO variant:

funcs = []
def call(event):
for f in list(funcs): # *
f(event)
root.bind("<1>", call)

funcs.append(test)
funcs.append(test2)
root.bind("<1>", call)

def unbind():
print "unbind"
funcs.remove(test2)

I does the same, but is a bit harder to manage if you have more than one
event/widget to deal with.

(*) iterating over a copy of the list of functions is slightly more robust
as it will not accidentally skip callbacks when the original list is
modified during iteration. I suggest that you change the OO version
accordingly.

Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: encoding problem

2008-12-19 Thread Joe Strout

Marc 'BlackJack' Rintsch wrote:


The question is why the Python interpreter use the default encoding
instead of "utf-8", which I explicitly declared in the source.


Because the declaration is only for decoding unicode literals in that 
very source file.


And because strings in Python, unlike in (say) REALbasic, do not know 
their encoding -- they're just a string of bytes.  If they were a string 
of bytes PLUS an encoding, then every string would know what it is, and 
things like conversion to another encoding, or concatenation of two 
strings that may differ in encoding, could be handled automatically.


I consider this one of the great shortcomings of Python, but it's mostly 
just a temporary inconvenience -- the world is moving to Unicode, and 
with Python 3, we won't have to worry about it so much.


Best,
- Joe




--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parsing a sequence of integers

2008-12-19 Thread Joe Strout

Peter Otten wrote:


If you are using Python 2.x:
...
So you better throw in a float(...):


Or, add

  from __future__ import division

at the top of the file.  I put this at the top of all my Python files, 
whether I expect to be dividing or not.  It just saves grief.


Cheers,
- Joe

--
http://mail.python.org/mailman/listinfo/python-list


Re: change string to unicode

2008-12-19 Thread Steven D'Aprano
On Fri, 19 Dec 2008 09:19:28 -0600, jyoung79 wrote:

> If I have a string like so:
> 
> a = '\\u03B1'
> 
> and I want to make it display a Greek alpha character, is there a way to
> convert it to unicode ('\u03B1')?  I tried concatenating it like this:
> 
> '\u' + '03B1'
> 
> but that didn't work.  I'm working in Python 3.0 and was curious if this
> could be done.

This is from Python 2.5:

>>> print unichr(0x03B1)
α

I don't have Python 3 here, but I guess that you would just use chr() 
instead of unichr().

If you literally have to start with the actual string '\\u03B1' (that is, 
backslash lowercase-U zero three uppercase-B one), then I'd do this:

>>> s = '\\u03B1'
>>> if s.startswith('\\u'):
... s = s[2:]
...
>>> print unichr(int(s, 16))
α



-- 
Steven
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parsing a sequence of integers

2008-12-19 Thread Mensanator
On Dec 19, 9:23�am, Joe Strout  wrote:
> Peter Otten wrote:
> > If you are using Python 2.x:
> > ...
> > So you better throw in a float(...):
>
> Or, add
>
> � �from __future__ import division
>
> at the top of the file. �I put this at the top of all my Python files,
> whether I expect to be dividing or not. �It just saves grief.

If you want division to be floating point.
If, like me, you rarely do floating point
division and want the "/" to mean integer
division as God intended, then you don't
put from __future__ import division in your
source files.

That's one of the good things about Python,
you can have it either way.


>
> Cheers,
> - Joe

--
http://mail.python.org/mailman/listinfo/python-list


Re: change string to unicode

2008-12-19 Thread Peter Otten
jyoun...@kc.rr.com wrote:

> If I have a string like so:
> 
> a = '\\u03B1'
> 
> and I want to make it display a Greek alpha character, is there a way to
> convert it to unicode ('\u03B1')?  I tried concatenating it like this:
> 
> '\u' + '03B1'
> 
> but that didn't work.  I'm working in Python 3.0 and was curious if this
> could be done.

How about

>>> "\\u03b1".encode("ascii").decode("unicode-escape")
'α'

Peter
--
http://mail.python.org/mailman/listinfo/python-list


HTTP://WWW.STREETCANDY.ORG

2008-12-19 Thread nikeshoe.nik...@gmail.com
Get Nike Shoes at Super Cheap Prices
Discount Nike air jordans  (www.streetcandy.org)
Discount Nike Air Max 90 Sneakers  (www.streetcandy.org)
Discount Nike Air Max 91 Supplier  (www.streetcandy.org)
Discount Nike Air Max 95 Shoes Supplier  (www.streetcandy.org)
Discount Nike Air Max 97 Trainers  (www.streetcandy.org)
Discount Nike Air Max 2003 Wholesale  (www.streetcandy.org)
Discount Nike Air Max 2004 Shoes Wholesale (www.streetcandy.org)
Discount Nike Air Max 2005 Shop  (www.streetcandy.org)
Discount Nike Air Max 2006 Shoes Shop  (www.streetcandy.org)
Discount Nike Air Max 360 Catalogs  (www.streetcandy.orgm)
Discount Nike Air Max Ltd Shoes Catalogs  (www.streetcandy.org)
Discount Nike Air Max Tn Men's Shoes  (www.streetcandy.org)
Discount Nike Air Max Tn 2 Women's Shoes  (www.streetcandy.org)
Discount Nike Air Max Tn 3 Customize  (www.streetcandy.org)
Discount Nike Air Max Tn 4 Shoes Customize ( www.streetcandy.orgm)
Discount Nike Air Max Tn 6 Supply  (www.streetcandy.org)
Discount Nike Shox NZ Shoes Supply  (www.streetcandy.org)
Discount Nike Shox OZ Sale  (www.streetcandy.org)
Discount Nike Shox TL Store  (www.streetcandy.org)
Discount Nike Shox TL 2 Shoes Store (www.streetcandy.org)
Discount Nike Shox TL 3 Distributor (www.streetcandy.org)
Discount Nike Shox Bmw Shoes Distributor  (www.streetcandy.org)
Discount Nike Shox Elite Shoes Manufacturer (www.streetcandy.org)
Discount Nike Shox Monster Manufacturer  (www.streetcandy.org)
Discount Nike Shox R4 Running Shoes  (www.streetcandy.org)
Discount Nike Shox R5 Mens Shoes  (www.streetcandy.org)
Discount Nike Shox Ride Womens Shoes (www.streetcandy.org)
Discount Nike Shox Rival Shoes Wholesaler  (www.streetcandy.org)
Discount Nike Shox Energia Wholesaler  (www.streetcandy.org)
Discount Nike Shox LV Sneaker  (www.streetcandy.org)
Discount Nike Shox Turbo Suppliers  (www.streetcandy.org)
Discount Nike Shox Classic Shoes Suppliers (www.streetcandy.org)
Discount Nike Shox Dendara Trainer  (www.streetcandy.org)
Discount Nike Air Jordan 1 Seller  (www.streetcandy.org)
Discount Nike Air Jordan 2 Shoes Seller  (www.streetcandy.org)
Discount Nike Air Jordan 3 Collection  (www.streetcandy.org
Discount Nike Air Jordan 4 Shoes Collection (www.streetcandy.org)
Discount Nike Air Jordan 5 Chaussure Shoes (www.streetcandy.org)
Discount Nike Air Jordan 6 Catalog  (www.streetcandy.org)
Discount Nike Air Jordan 7 Shoes Catalog  (www.streetcandy.org)
Discount Nike Air Jordan 8 Customized  (www.streetcandy.org)
Discount Nike Air Jordan 9 Shoes Customized
(www.streetcandy.org)
Discount Nike Air Jordan 10 Wholesalers  (www.streetcandy.org)
Discount Nike Jordan 11 Shoes Wholesalers (www.streetcandy.org)
Discount Nike Air Jordan 12 Factory  (www.streetcandy.org)
Discount Nike Air Jordan 13 Shoes Factory (www.streetcandy.org)
Discount Nike Air Jordan 14 Shoes Sell  (www.streetcandy.org)
Discount Nike Air Jordan 16 Exporter  (www.streetcandy.org)
Discount Nike Air Jordan 17 Shoes Exporter
(www.streetcandy.org)
Discount Nike Air Jordan 18 Offer  (www.streetcandy.org)
Discount Nike Air Jordan 19 Shoes Offer  (www.streetcandy.org)
Discount Nike Air Jordan 20 Manufacture  (www.streetcandy.org)
Discount Nike Jordan 21 Shoes Manufacture  (www.streetcandy.org)

--
http://mail.python.org/mailman/listinfo/python-list


New Python 3.0 string formatting - really necessary?

2008-12-19 Thread walterbyrd
I have not worked with Python enough to really know. But, it seems to
me that more I look at python 3.0, the more I wonder if it isn't a
step backwards.

To me, it seems that this:

print "%s=%d" % ('this',99)

Is much easier, and faster, to type, and is also easier to read and
understand. It also allows people to leverage their knowledge of C.

This (if it's right) is much longer, and requires more special
characters.

print( "{0}={1}".format('this',99))

Maybe it's worth all the extra trouble, and breaking backward
compatibilty, and all. But, I never had the idea that the old way was
all that big a problem. Of course, I could be wrong. Was the old way
all that big of a problem?

--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: New Book: Programming in Python 3

2008-12-19 Thread Mark Summerfield
Just a follow-up to say that the book has now been published in the
U.S.
It is now in stock at InformIT, and should reach other stores, e.g.,
Amazon, in a week or so.

Also, the introduction, the first few pages of the first chapter, the
whole of chapter 12 (regular expressions), and the index are now
available for free download in a PDF from here:
http://www.informit.com/store/product.aspx?isbn=0137129297

Oh, and I wrote a short article on descriptors which is here:
http://www.informit.com/articles/article.aspx?p=1309289
(The third example is very similar to an example from Chapter 8 and
shows a validation technique that combines class decorators with
descriptors.)


On 4 Dec, 15:02, Mark Summerfield  wrote:
> Now that Python 3 final has been released I thought it would be a good time
> to mention that there's a new book to go with it:
>
> "Programming in Python 3:
> A Complete Introduction to the Python Language"
> ISBN 0137129297http://www.qtrac.eu/py3book.html
>
> I've been working on this for more than a year, testing the examples
> against every Python 3 alpha and beta, and against the final release (using
> Python's unit test and doctest modules of course:).
>
> The book has just gone into production and should be available in print at
> the end of this month in the U.S., and a month or two later elsewhere. The
> book's web page has links to a draft of the introduction and to safari
> books online where you can read extracts.
>
> The book is aimed at a wide audience, but assumes some programming
> experience (not necessarily Python, not necessarily object-oriented). It
> teaches solid procedural style programming, then builds on that to teach
> solid object-oriented programming, and then goes on to more advanced topics
> (e.g., including a nice way to create validated attributes by combining
> class decorators with descriptors). But even newcomers to Python 3 should
> be able to write useful (although small and basic) programs after reading
> chapter 1, and then go on to create larger and more sophisticated programs
> as they work through the chapters.
>
> --
> Mark Summerfield, Qtrac Ltd,www.qtrac.eu
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread Giampaolo Rodola'
On 19 Dic, 17:01, walterbyrd  wrote:
> I have not worked with Python enough to really know. But, it seems to
> me that more I look at python 3.0, the more I wonder if it isn't a
> step backwards.
>
> To me, it seems that this:
>
> print "%s=%d" % ('this',99)
>
> Is much easier, and faster, to type, and is also easier to read and
> understand. It also allows people to leverage their knowledge of C.
>
> This (if it's right) is much longer, and requires more special
> characters.
>
> print( "{0}={1}".format('this',99))
>
> Maybe it's worth all the extra trouble, and breaking backward
> compatibilty, and all. But, I never had the idea that the old way was
> all that big a problem. Of course, I could be wrong. Was the old way
> all that big of a problem?

You can use the old 2.x syntax also in Python 3.x:


C:\>C:\python30\python.exe
Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("%s=%d" % ('this',99))
this=99


--- Giampaolo
http://code.google.com/p/pyftpdlib/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generator slower than iterator?

2008-12-19 Thread MRAB

Federico Moreira wrote:

Great, 2min 34 secs with the open method =)

but why?

ip, sep, rest = line.partition(' ')
   match_counter[ip] += 1

instead of

match_counter[line.strip()[0]] += 1

strip really takes more time than partition?

I'm having the same results with both of them right now.


I think you meant split(), not strip().

split() might split the string into many parts, but you want only the 
first part (at most 1 split), so the extra splits are unnecessary and 
waste time. split(None, 1) and partition(' ') do at most 1 split, so 
they don't do unnecessary work.

--
http://mail.python.org/mailman/listinfo/python-list


best way to code

2008-12-19 Thread eric
hi,

I need to find a "good" design pattern to instanciate, and add
specific code all in one. Let me explain it :

I need to define "some" code, better be in a class, something like

class LinkA(object):
def mystuff(self):
 

class LinkB(object):
def mystuff(self):
 


AND I need an instance of this class
{ "stuff A": LinkA()
  "stuff B": LinkB()
}

This kind of code "would" be fine, I mean, the result effect in memory
is fine for me.
But I don't like the way I have to
1/ give a useless name to LinkA, linkB (there can be hundreds of names
like that)
2/ I have to write it down two times (and that's one time too much)

any ideas ?

something like
[
new object():
def mystuff(self):
   
,
new object():
def mystuff(self):
   
]

would be really perfect (but I know it does not work, or at least, I
don't know how to make it work)

In fact, I would like to define a class, and an instance in a single
statement


thanks

--
Eric
http://codeslash.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


mailbox.mbox.add() appears to set both access and modification times

2008-12-19 Thread tinnews
I'm using mailbox in Python 2.5.2 to filter incoming mail into
separate mailboxes.  I prefer mbox for various reasons and so I have
used that format.

It would appear then when I do:-

dest = mailbox.mbox(destDir, factory=None)
dest.add(m)

it sets both the access and modification times of the mbox to the date
and time now.  This is a disaster for MUAs that detect new mail by
looking to see if the mbox has been modified after it was accessed.

Is this a known bug in mailbox.mbox.add(), or am I doing something
wrong, or what?

-- 
Chris Green
--
http://mail.python.org/mailman/listinfo/python-list


Re: weird dict problem, how can this even happen?

2008-12-19 Thread Joel Hedlund

Joel Hedlund wrote:
First off, please note that I consider my problem to be solved, many 
thanks to c.l.p and especially Duncan Booth. But of course continued 
discussion on this topic can be both enlightening and entertaining as 
long as people are interested. So here goes:


heh, nothing like a wall of text to kill off interest I guess. :-)

But thank you all for your time and helpful advice! Aand happy holidays!

/Joel
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to code

2008-12-19 Thread Peter Otten
eric wrote:

> hi,
> 
> I need to find a "good" design pattern to instanciate, and add
> specific code all in one. Let me explain it :
> 
> I need to define "some" code, better be in a class, something like
> 
> class LinkA(object):
> def mystuff(self):
>  
> 
> class LinkB(object):
> def mystuff(self):
>  
> 
> 
> AND I need an instance of this class
> { "stuff A": LinkA()
>   "stuff B": LinkB()
> }
> 
> This kind of code "would" be fine, I mean, the result effect in memory
> is fine for me.
> But I don't like the way I have to
> 1/ give a useless name to LinkA, linkB (there can be hundreds of names
> like that)
> 2/ I have to write it down two times (and that's one time too much)
> 
> any ideas ?
> 
> something like
> [
> new object():
> def mystuff(self):
>
> ,
> new object():
> def mystuff(self):
>
> ]
> 
> would be really perfect (but I know it does not work, or at least, I
> don't know how to make it work)
> 
> In fact, I would like to define a class, and an instance in a single
> statement

>>> class Register:
... def __init__(self):
... self.items = []
... def __call__(self, method):
... class Link(object):
... mystuff = method
... self.items.append(Link())
...
>>> register = Register()
>>> @register
... def mystuff(self): print "first"
...
>>> @register
... def mystuff(self): print "second"
...
>>> for item in register.items:
... item.mystuff()
...
first
second

Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: New Book: Programming in Python 3

2008-12-19 Thread Thomas Heller
Mark Summerfield schrieb:
> Just a follow-up to say that the book has now been published in the
> U.S.
> It is now in stock at InformIT, and should reach other stores, e.g.,
> Amazon, in a week or so.
> 
> Also, the introduction, the first few pages of the first chapter, the
> whole of chapter 12 (regular expressions), and the index are now
> available for free download in a PDF from here:
> http://www.informit.com/store/product.aspx?isbn=0137129297

Question from a non-native english speaker: is this now valid english?

  "One of Python’s great strengths"
^
  "and also teaches Python’s functional programming features"
  ^
  "The book’s approach is wholly practical"
   ^

Curious,
Thomas
--
http://mail.python.org/mailman/listinfo/python-list


IMAP: How to implement GMail-like threaded conversations view

2008-12-19 Thread Martin
Currently I am trying to get used to Python's imaplib and email
modules.
I'like to create a webmail client simmilar to GMail.

My Questions:
a) Is there any feature hidden in Python's built-in modules (imaplib,
email) that already can group all my mails into threads?

b) If not a... what would be the best way to implement this?

I can think of two approaches:
b.1) Use the "References:" field of the messages in order to find out
which messages are related to each other.

I tried a first implementation which works quite well but I don't know
if there can occur situations where one message is related to two
parents. Also I don't know what happens if someone is too lazy to type
my address. He might click at "Reply", delete topic and old mail-text
and compose a new mail. Theoretically his mail client would set the
"References:" field accordingly never the less, wouldn't it? Therefore
my mail client would consider that completely new mail as part of an
older conversation.

The thoughts above might lead to the second approach:

b.2) Use the "Subject:" field of the messages.

I also tried this implementation and it also works (at first glance).
I stripped all subjects of all mails so that all those "Re:", "Fw:"
tags at the beginning get deleted. Afterwards I grouped those having
the same subject and the same participants. Problem: I have no clue
what "Re:"-tags might exist around the world. I guess each mail client
and each language uses different ones, right?

c) Does anyone know good resources to gain more knowledge about imap /
mailing?
Currently I am using those sites as a reference:

http://www.devshed.com/c/a/Python/Python-Email-Libraries-part-2-IMAP/
(as a start *g)
http://tools.ietf.org/html/rfc3501
http://tools.ietf.org/html/rfc2822
http://docs.python.org/library/imaplib.html
http://docs.python.org/library/email.html

Maybe there are other sources of interest on the web? :)

This is my first post in this newsgroup. So:

"Hello everybody!" :-)

I've been reading this group for quite a while and I am really
astonished how fast people give valuable answers here. This is a
really great community! Many thanks in advance for all ideas!

Greetz,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread r
if 3.0 looks like... print( "{0}={1}".format('this',99)) , WTF...
thats retarded and looks like Ruby code. Thats not intuitive thats
madness! What happens when you need a conversion to string from an
integer, more code?? My faith is slipping. Have the python Gods gone
mad??. Please tell me i am wrong.

Pythons likeness to C is one of its great powers. I always thought of
Python as an intuitive way to write C code.

I am sticking with 2x(which i had planned to do anyway) I have heard
of nothing significant enough to compel me to make the change yet. And
with that example from 3.0, i am really setting my ways now. i may
have to support the continuation of 2.x beyond 2.9.

Guido! please don't play Russian roulette with Python! I have loved
python all the way up through the 2.x line. And i carry a great
respect for you and your accomplishments. Python must feel at home to
a C programmer. That, i feel, is the professional following for
Python. I also feel Python is a gateway to the C language for n00b
programmers. Let Ruby have the Perl programmers, we don't need them!

Excuse me, I think i am going to cry now :(
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: New Book: Programming in Python 3

2008-12-19 Thread MRAB

Thomas Heller wrote:

Mark Summerfield schrieb:

Just a follow-up to say that the book has now been published in the
U.S.
It is now in stock at InformIT, and should reach other stores, e.g.,
Amazon, in a week or so.

Also, the introduction, the first few pages of the first chapter, the
whole of chapter 12 (regular expressions), and the index are now
available for free download in a PDF from here:
http://www.informit.com/store/product.aspx?isbn=0137129297


Question from a non-native english speaker: is this now valid english?

  "One of Python’s great strengths"
^
  "and also teaches Python’s functional programming features"
  ^
  "The book’s approach is wholly practical"
   ^


Looks OK to me.
--
http://mail.python.org/mailman/listinfo/python-list


Building a web questionnaire, can it be done in Python ?

2008-12-19 Thread Stef Mientki

hello,

I'm considering building a web questionnaire in Python.
I've made several desktop applications in Python /  wxPython,
but I've no experience in using Python on a webserver,
and I don't have much knowledge about web applications in general.

As am quit familiar with Python,
therefor it sounds evident to me to make the web application in Python,
but I'm not sure that's really the best way.

I've googled, but the links I get, makes me more confused:
Zope, Plone , ...??
And I can find a lot in other languages Perl, JavaScript, PHP, CGI, ...

So maybe someone on this list can give me some advise,
a good starting point,
because it's almost impossible to evaluate all the possibilities myself,
and I'm afraid the first choice will be the final choice ;-)

The questionnaires are used to diagnose and treat all kinds of patients 
in a hospital.

Therefor I need 2 versions, a web-version and a desktop version,
the latter I need to be able to lock the computer.
The desktop version is no problem, neither the locking.
Also the analysis and reporting of the data will be done in a desktop 
application.


The problematic (at least form my point of view) requirements:


The content and layout comes from an existing database.

The layout of the desktop version and the web-version should be almost 
identical to the paper and pencil version

(most norms are based on the paper and pencil version)

The questions can have different forms, multiple choice, multiple choice 
with multiple answers, but also things like sliders.
The answering should also be possible with the keyboard only: e.g. 
1,2,.. for the answers, PgUp / PgDn or Enter for previous / next question.


The web application should have some kind of security (soap ? https ?) 
and a login.


Depending on answers to previous questions, some questions should be 
ignored.
Depending on answers to previous questions, some questionnairies should 
be ignored.


Patient should be able to browse within 1 questionnaire, but not to the 
previously answered ones.


After each questionnaire there should be check if all questions were 
answered.


Should run in IE and Mozilla.

I'm not sure about this one yet:
While a session can take several hours,
it could be beneficial to connect to the internet only at some 
intermediate intervals,

or when one questionnaire is completely finished.

thanks,
Stef


--
http://mail.python.org/mailman/listinfo/python-list


Re: encoding problem

2008-12-19 Thread digisat...@gmail.com
On 12月19日, 下午9时34分, Marc 'BlackJack' Rintsch  wrote:
> On Fri, 19 Dec 2008 04:05:12 -0800, digisat...@gmail.com wrote:
> > The below snippet code generates UnicodeDecodeError.
> > #!/usr/bin/env
> > python
> > #--*-- coding: utf-8 --*--
> > s = 'äöü'
> > u = unicode(s)
>
> > It seems that the system use the default encoding- ASCII to decode the
> > utf8 encoded string literal, and thus generates the error.
>
> > The question is why the Python interpreter use the default encoding
> > instead of "utf-8", which I explicitly declared in the source.
>
> Because the declaration is only for decoding unicode literals in that
> very source file.
>
> Ciao,
>         Marc 'BlackJack' Rintsch

Thanks for the answer.
I believe the declaration is not only for unicode literals, it is for
all literals in the source even including Comments. we can try runing
a source file without encoding declaration and have only 1 line of
comments with non-ASCII characters. That will arise a Syntax error and
bring me to the pep263 URL.

I read the pep263 and quoted below:

 Python's tokenizer/compiler combo will need to be updated to work as
follows:
   1. read the file
   2. decode it into Unicode assuming a fixed per-file encoding
   3. convert it into a UTF-8 byte string
   4. tokenize the UTF-8 content
   5. compile it, creating Unicode objects from the given Unicode
data
  and creating string objects from the Unicode literal data
  by first reencoding the UTF-8 data into 8-bit string data
  using the given file encoding

The above described Python internal process indicate that the step 2
will utilise the specific encoding to decode all literals in source,
while in step5 will evolve a re-encoding with the specific encoding.

That is the reason why we have to explicitly declare a encoding as
long as we have non-ASCII in source.

Bruno answered why we need specify a encoding when decoding a byte
string with perfect explanation, Thank you very much.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parsing a sequence of integers

2008-12-19 Thread Joe Strout

Mensanator wrote:


from __future__ import division

at the top of the file. I put this at the top of all my Python files,
whether I expect to be dividing or not. It just saves grief.


If you want division to be floating point.
If, like me, you rarely do floating point
division and want the "/" to mean integer
division as God intended, then you don't
put from __future__ import division in your
source files.

That's one of the good things about Python,
you can have it either way.


Until you someday move up to Python 3, at which point you'll have to go 
back and change all your code to use the unambiguous // operator when 
you mean integer division.  Better to do it now, I think, at least in 
any new code you write, to save you the hassle later.


For those not familiar with the topic:

   

Best,
- Joe

--
http://mail.python.org/mailman/listinfo/python-list


Re: Generator slower than iterator?

2008-12-19 Thread Federico Moreira
Yep i meant split sorry.

Thanks for the answer!
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: New Book: Programming in Python 3

2008-12-19 Thread Steve Holden
Thomas Heller wrote:
> Mark Summerfield schrieb:
>> Just a follow-up to say that the book has now been published in the
>> U.S.
>> It is now in stock at InformIT, and should reach other stores, e.g.,
>> Amazon, in a week or so.
>>
>> Also, the introduction, the first few pages of the first chapter, the
>> whole of chapter 12 (regular expressions), and the index are now
>> available for free download in a PDF from here:
>> http://www.informit.com/store/product.aspx?isbn=0137129297
> 
> Question from a non-native english speaker: is this now valid english?
> 
>   "One of Python’s great strengths"
> ^
>   "and also teaches Python’s functional programming features"
>   ^
>   "The book’s approach is wholly practical"
>^
It always has been valid English. The apostrophe is only omitted from
personal pronouns (hers, its, and so on).

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: New Book: Programming in Python 3

2008-12-19 Thread Stefan Behnel
Thomas Heller wrote:
> Mark Summerfield schrieb:
>> Just a follow-up to say that the book has now been published in the
>> U.S.
>> It is now in stock at InformIT, and should reach other stores, e.g.,
>> Amazon, in a week or so.
>>
>> Also, the introduction, the first few pages of the first chapter, the
>> whole of chapter 12 (regular expressions), and the index are now
>> available for free download in a PDF from here:
>> http://www.informit.com/store/product.aspx?isbn=0137129297
> 
> Question from a non-native english speaker: is this now valid english?
> 
>   "One of Python’s great strengths"
> ^
>   "and also teaches Python’s functional programming features"
>   ^
>   "The book’s approach is wholly practical"
>^

'Always' has been. It's not valid German, though, if that's what you are
asking.

Stefan
--
http://mail.python.org/mailman/listinfo/python-list


Re: If programming languages were religions...

2008-12-19 Thread Brian Allen Vanderburg II

martin.lal...@gmail.com wrote:

very interesting
http://www.aegisub.net/2008/12/if-programming-languages-were-religions.html

"Python would be Humanism: It's simple, unrestrictive, and all you
need to follow it is common sense. Many of the followers claim to feel
relieved from all the burden imposed by other languages, and that they
have rediscovered the joy of programming. There are some who say that
it is a form of pseudo-code"

compare to
"Perl would be Voodoo - An incomprehensible series of arcane
incantations that involve the blood of goats and permanently corrupt
your soul. Often used when your boss requires you to do an urgent task
at 21:00 on friday night."

and others
--
http://mail.python.org/mailman/listinfo/python-list
  

If programming languages were religions:

When first powering on a computer, there would only be one programming 
language, the language of the boot loader.  As the computer runs, 
processes of one language would spawn processes of other languages, and 
over the course of time many different languages would have many 
different processes (followers).  One of these languages would rise up 
to be dominant and would kill all processes of other languages by the 
signal, whether old or young.  The processes would be given a fair 
change, convert to their language or be killed.  Countless thousands or 
maybe even millions of processes would die, even the processes that say 
there is no one true programming language and wants to know why all the 
processes can't just get along. 
--

http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread walterbyrd
On Dec 19, 9:13 am, "Giampaolo Rodola'"  wrote:
> You can use the old 2.x syntax also in Python 3.x:

Yeah, but it's deprecated, and - as I understand it - may be removed
completely in future versions. Also, in the future, if you are working
with code from another developer, it's likely that developer will use
the new format. I suppose you can use both - but what an awful mess
that would be.

It seems to me that 3.0 is changing a lot of non-problems. And it's
going to be slower to boot.
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread Michael Torrie
r wrote:
> if 3.0 looks like... print( "{0}={1}".format('this',99)) , WTF...
> thats retarded and looks like Ruby code. Thats not intuitive thats
> madness! What happens when you need a conversion to string from an
> integer, more code?? My faith is slipping. Have the python Gods gone
> mad??. Please tell me i am wrong.


You are wrong.

> 
> Pythons likeness to C is one of its great powers. I always thought of
> Python as an intuitive way to write C code.

I have to confess, I have no idea what you are talking about.  I have
never ever seen Python as an intuitive way to write C code.  That's kind
of bizarre.

> I am sticking with 2x(which i had planned to do anyway) I have heard
> of nothing significant enough to compel me to make the change yet. And
> with that example from 3.0, i am really setting my ways now. i may
> have to support the continuation of 2.x beyond 2.9.

> Guido! please don't play Russian roulette with Python! I have loved
> python all the way up through the 2.x line. And i carry a great
> respect for you and your accomplishments. Python must feel at home to
> a C programmer. That, i feel, is the professional following for
> Python. I also feel Python is a gateway to the C language for n00b
> programmers. Let Ruby have the Perl programmers, we don't need them!
> 
> Excuse me, I think i am going to cry now :(

Okay, you're welcome to.

So funny that now that Python 3.0 is actually released we have people
acting all surprised like they've never seen any of the new features in
Python 3.0 coming.  However these features have been discussed for
years!  And debated!

Personally the new string formatter is sorely needed in Python.  And
they way it has been implemented is a thing of beauty.  Basically the
burden of formatting strings has been moved from the print
statement/function to the objects themselves.  Furthermore, the new {}
notation allows many, many more options for formatting to be used.  Want
to display a floating point number with $#.## notation, and ($#.##) for
negative?  It's all now possible.  Couldn't be done before.  Want to
have the ability to format your own custom object in a particular way
when printing with print()?  Just define a __format__ method in your
object.  print() will ask it to format itself.

In short, this is a huge improvement, and backwards compatibility is
preserved for the 2.x style for those that wish it.

--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread Michael Torrie
walterbyrd wrote:
> On Dec 19, 9:13 am, "Giampaolo Rodola'"  wrote:
>> You can use the old 2.x syntax also in Python 3.x:
> 
> Yeah, but it's deprecated, and - as I understand it - may be removed
> completely in future versions. Also, in the future, if you are working
> with code from another developer, it's likely that developer will use
> the new format. I suppose you can use both - but what an awful mess
> that would be.
> 
> It seems to me that 3.0 is changing a lot of non-problems. And it's
> going to be slower to boot.

How is this?  With projects like PyPy eventually enabling the JIT'ing of
python3 code, I don't see how this is going to be "slower."  If anything
we have a python that can be made to run faster than ever before.

Please qualify your remarks.  Are you a Python core developer?
--
http://mail.python.org/mailman/listinfo/python-list


Re: IMAP: How to implement GMail-like threaded conversations view

2008-12-19 Thread Jean-Paul Calderone

On Fri, 19 Dec 2008 08:47:18 -0800 (PST), Martin  wrote:

Currently I am trying to get used to Python's imaplib and email
modules.
I'like to create a webmail client simmilar to GMail.


I'd suggest using Twisted's IMAP4 client.  It's somewhat easier to
use than Python's imaplib because it does much more parsing of IMAP4's
complex syntax for you.  It will also be easier to do IMAP4 and HTTP
simultaneously if you're using Twisted.

Twisted won't help with the threading feature you want to implement
though, it lets you use the email package if you want to examine the
structure of the messages you retrieve.

Jean-Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread Jean-Paul Calderone

On Fri, 19 Dec 2008 10:27:27 -0700, Michael Torrie  wrote:

walterbyrd wrote:

On Dec 19, 9:13 am, "Giampaolo Rodola'"  wrote:

You can use the old 2.x syntax also in Python 3.x:


Yeah, but it's deprecated, and - as I understand it - may be removed
completely in future versions. Also, in the future, if you are working
with code from another developer, it's likely that developer will use
the new format. I suppose you can use both - but what an awful mess
that would be.

It seems to me that 3.0 is changing a lot of non-problems. And it's
going to be slower to boot.


How is this?  With projects like PyPy eventually enabling the JIT'ing of
python3 code, I don't see how this is going to be "slower."  If anything
we have a python that can be made to run faster than ever before.


What makes you think PyPy is going to enabling JIT'ing of Python 3 code?
Perhaps it will, someday, but I suspect it will provide a JIT for Python 2
long before.

Jean-Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to code

2008-12-19 Thread eric
On Dec 19, 5:35 pm, Peter Otten <__pete...@web.de> wrote:
> eric wrote:
> > hi,
>
> > I need to find a "good" design pattern to instanciate, and add
> > specific code all in one. Let me explain it :
>
> > I need to define "some" code, better be in a class, something like
>
> > class LinkA(object):
> >     def mystuff(self):
> >          
>
> > class LinkB(object):
> >     def mystuff(self):
> >          
>
> > AND I need an instance of this class
> > { "stuff A": LinkA()
> >   "stuff B": LinkB()
> > }
>
> > This kind of code "would" be fine, I mean, the result effect in memory
> > is fine for me.
> > But I don't like the way I have to
> > 1/ give a useless name to LinkA, linkB (there can be hundreds of names
> > like that)
> > 2/ I have to write it down two times (and that's one time too much)
>
> > any ideas ?
>
> > something like
> > [
> > new object():
> >     def mystuff(self):
> >        
> > ,
> > new object():
> >     def mystuff(self):
> >        
> > ]
>
> > would be really perfect (but I know it does not work, or at least, I
> > don't know how to make it work)
>
> > In fact, I would like to define a class, and an instance in a single
> > statement
> >>> class Register:
>
> ...     def __init__(self):
> ...             self.items = []
> ...     def __call__(self, method):
> ...             class Link(object):
> ...                     mystuff = method
> ...             self.items.append(Link())
> ...>>> register = Register()
> >>> @register
>
> ... def mystuff(self): print "first"
> ...>>> @register
>
> ... def mystuff(self): print "second"
> ...>>> for item in register.items:
>
> ...     item.mystuff()
> ...
> first
> second
>
> Peter


hi,

I've tried something like this :

import inspect

class Test(object):
class Inner(object):
def mystuff(self):
print "hello stuff"

class InnerB(object):
def mystuff(self):
print "hello B"


def filter(member):
return inspect.isclass(member) and not member==Test.__class__
d = dict( (name, c()) for name, c in inspect.getmembers(Test,
filter ) )
print d


it works too, but I prefer your method

thanks

--
Eric
http://codeslash.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Building a web questionnaire, can it be done in Python ?

2008-12-19 Thread Steve Bergman
The most popular choice for web apps, and the one I use myself, would
be Django.  You might post your question in the Django group:

http://groups-beta.google.com/group/django-users

The only thing that I see that could be a problem would be the legacy
database.  But that depends very much upon your exact situation.
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread r
I was actually looking forward to 3.0, but the more I hear about 3.0,
the more I am turned off. I think there are a lot of other
pythonista's and pythoneers out there who agree but are not saying
anything. This syntax for string formatting is completely ridiculous.
What is the purpose of breaking backward compatibility just to write a
print() function. This is going to push people away from python. I am
trying to bring people to Python. I heard map is going away too, is
that true also??, and there was talk at one time(serious talk from
Guido) about removing lambda functions. Is this planned for the
future??

Python has been beautifully designed from the beginning. But, I feel a
shift from this now. Are they scared of Ruby, if they are, why the
hell should they be. We do not need to lose any of the great
pythonista's right now, and we damn sure don't want to turn off the
new recruits.

It seems like most of the backward breaks are really just for dumb
reasons(sorry but its true). What is the logic behind this? The whole
reason for not having a print function was the need to use it so much
in debugging. And I was actually going to overlook that until I saw
this perl/ruby like format method. WTF!
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: New Book: Programming in Python 3

2008-12-19 Thread Thomas Heller
Steve Holden schrieb:
> Thomas Heller wrote:
>> Question from a non-native english speaker: is this now valid english?
>> 
>>   "One of Python’s great strengths"
>> ^
>>   "and also teaches Python’s functional programming features"
>>   ^
>>   "The book’s approach is wholly practical"
>>^
> It always has been valid English. The apostrophe is only omitted from
> personal pronouns (hers, its, and so on).

I see, thanks.  But, is the apostrophe optional in the above fragments?

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread bearophileHUGS
r:
> I always thought of Python as an intuitive way to write C code.<

C is a very low level language, not far from assembly, and often it's
not intuitive at all.

C string formatting is short and a flexible enough, but it's out of
place in a language as high level as Python3. The new syntax allows
more flexibility, and it's better for most people that don't know C
already, like newbies, etc.

--

walterbyrd:
>It seems to me that 3.0 is changing a lot of non-problems. And it's
going to be slower to boot.<

They are non-problems for people that already know lot of Python (and
some C). But for all the other people, especially newbies, it's better
in most things.

Most language designers (and generally people very used a certain
language) become so accustomed to their language that they most of the
times become like "blind" to the defects and warts of their language
(I have said this four years ago too, when I have started learning
Python, listing many problems in Python, and among them there were C
string formatting too). So I think it was a feat for the Python
developers to see many characteristics of the Python2.x as what they
are: warts, bugs, etc, and fix them (and most of the times their newer
designs are "the right thing" with just few exceptions, I have counted
only 3 of them, and they are small). They have gained even more of my
respect.

Regarding the speed of Python3 programs, they will go faster because
people will be forced to use things like lazy ranges, lazy map and
filter, lazy keys and values, and the "key" of sort/sorted. All those
things can be used in Python2.x too, but lot of people aren't expert
enough (or they are just lazy) and don't use them, so the average
Python3 program will probably be faster (and use less memory) thanks
to them.

Python3 programs will go slower because they use 2-byte long Unicode
strings by default (it can be compiled for 4-byte Unicode too, and I
think this has to become the default, eventually, because I think it
will become silly to save few bytes for strings when you will have
8-16-32+ GB of RAM), and they use multi-precision integers only. Such
strings and numbers allow to reduce some troubles, even "bugs", etc.

At the moment Python3 isn't much optimized for speed, you can think of
it an experimental release still. I/O and multiprecision integers will
probably be speed up (and some form of transparent on-the-fly
compression or smart representation can in most times halve the memory
used by Py3 strings, putting the performance almost back to the Py2.x
one. In computer science there are LOT of tricks that can be used if
you have the brain and time to invent and implement them. You can see
that for example in how Psyco manages internally string/list/tuple
slices).

Anyway, CPUs and computers are now much faster than the CPUs present
when Python was created. And Python is first of all designed for the
programmer and not for the CPU. So I think it's right to make Python3
become a little higher level language even if this slows it down a
little. For the kind of programs Python is often used for, I think
this is a Win. (Ruby programs are often slower than Python ones
(because Ruby is a little higher level than Python) but it's very
useful anyway). If Python will continue to develop in the following
years (think about a Python4000) then I think it may become good to
make it become even more slower, if this will help make it a little
more higher level still.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread Christian Heimes
walterbyrd schrieb:
> On Dec 19, 9:13 am, "Giampaolo Rodola'"  wrote:
>> You can use the old 2.x syntax also in Python 3.x:
> 
> Yeah, but it's deprecated, and - as I understand it - may be removed
> completely in future versions. Also, in the future, if you are working
> with code from another developer, it's likely that developer will use
> the new format. I suppose you can use both - but what an awful mess
> that would be.

It's not going to be removed for many years - if ever. The % string
formatting system is not deprecated in 3.0. For that very reason it must
stay until 3.2. We don't have plans to deprecate it in 3.1 so it will
stay at least until Python 3.3 which is to be released about 2014.

Christian

--
http://mail.python.org/mailman/listinfo/python-list


RE:change string to unicode

2008-12-19 Thread jyoung79
Hi Steven and Peter,

Thank you both very much for taking the time to answer my question.  Your 
solutions
work perfect! :-)

Thanks again!

Jay


> How about
>
> >>> "\\u03b1".encode("ascii").decode("unicode-escape")
> 'α'
>
> Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread Christian Heimes
r schrieb:
> I was actually looking forward to 3.0, but the more I hear about 3.0,
> the more I am turned off. I think there are a lot of other
> pythonista's and pythoneers out there who agree but are not saying
> anything. This syntax for string formatting is completely ridiculous.

No, it's very powerful and used in other languages, too.

> What is the purpose of breaking backward compatibility just to write a
> print() function. This is going to push people away from python. 

The purpose of a print() function has been discussed for at least 3
years. You are welcome to read up all dicussions.


> I heard map is going away too, is that true also??, and there was talk at one 
> time(serious talk from
> Guido) about removing lambda functions. Is this planned for the
> future??

Wrong and wrong.
map stays but it has been turned into an iterator. The removal of lambda
has been discussed several years ago but it was repulsed. lambda stays.

> Python has been beautifully designed from the beginning. But, I feel a
> shift from this now. Are they scared of Ruby, if they are, why the
> hell should they be. We do not need to lose any of the great
> pythonista's right now, and we damn sure don't want to turn off the
> new recruits.

Python 3.0 is even more beautiful and more Pythonic. Backward
compatibility was broken for the sake of the language.

> It seems like most of the backward breaks are really just for dumb
> reasons(sorry but its true). What is the logic behind this? The whole
> reason for not having a print function was the need to use it so much
> in debugging. And I was actually going to overlook that until I saw
> this perl/ruby like format method. WTF!

Your truth turns to be a totally different truth than mine -- and most
of the active member of the community.

Christian

--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: New Book: Programming in Python 3

2008-12-19 Thread Paul Rudin
Thomas Heller  writes:

> Steve Holden schrieb:
>> Thomas Heller wrote:
>>> Question from a non-native english speaker: is this now valid english?
>>> 
>>>   "One of Python’s great strengths"
>>> ^
>>>   "and also teaches Python’s functional programming features"
>>>   ^
>>>   "The book’s approach is wholly practical"
>>>^
>> It always has been valid English. The apostrophe is only omitted from
>> personal pronouns (hers, its, and so on).
>
> I see, thanks.  But, is the apostrophe optional in the above fragments?

No.

--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread MRAB

bearophileh...@lycos.com wrote:

r:

I always thought of Python as an intuitive way to write C code.<


C is a very low level language, not far from assembly, and often it's
not intuitive at all.

C string formatting is short and a flexible enough, but it's out of
place in a language as high level as Python3. The new syntax allows
more flexibility, and it's better for most people that don't know C
already, like newbies, etc.

--

walterbyrd:

It seems to me that 3.0 is changing a lot of non-problems. And it's

going to be slower to boot.<

They are non-problems for people that already know lot of Python (and
some C). But for all the other people, especially newbies, it's better
in most things.

Most language designers (and generally people very used a certain
language) become so accustomed to their language that they most of the
times become like "blind" to the defects and warts of their language
(I have said this four years ago too, when I have started learning
Python, listing many problems in Python, and among them there were C
string formatting too). So I think it was a feat for the Python
developers to see many characteristics of the Python2.x as what they
are: warts, bugs, etc, and fix them (and most of the times their newer
designs are "the right thing" with just few exceptions, I have counted
only 3 of them, and they are small). They have gained even more of my
respect.

Regarding the speed of Python3 programs, they will go faster because
people will be forced to use things like lazy ranges, lazy map and
filter, lazy keys and values, and the "key" of sort/sorted. All those
things can be used in Python2.x too, but lot of people aren't expert
enough (or they are just lazy) and don't use them, so the average
Python3 program will probably be faster (and use less memory) thanks
to them.

Python3 programs will go slower because they use 2-byte long Unicode
strings by default (it can be compiled for 4-byte Unicode too, and I
think this has to become the default, eventually, because I think it
will become silly to save few bytes for strings when you will have
8-16-32+ GB of RAM), and they use multi-precision integers only. Such
strings and numbers allow to reduce some troubles, even "bugs", etc.

At the moment Python3 isn't much optimized for speed, you can think of
it an experimental release still. I/O and multiprecision integers will
probably be speed up (and some form of transparent on-the-fly
compression or smart representation can in most times halve the memory
used by Py3 strings, putting the performance almost back to the Py2.x
one. In computer science there are LOT of tricks that can be used if
you have the brain and time to invent and implement them. You can see
that for example in how Psyco manages internally string/list/tuple
slices).

Anyway, CPUs and computers are now much faster than the CPUs present
when Python was created. And Python is first of all designed for the
programmer and not for the CPU. So I think it's right to make Python3
become a little higher level language even if this slows it down a
little. For the kind of programs Python is often used for, I think
this is a Win. (Ruby programs are often slower than Python ones
(because Ruby is a little higher level than Python) but it's very
useful anyway). If Python will continue to develop in the following
years (think about a Python4000) then I think it may become good to
make it become even more slower, if this will help make it a little
more higher level still.

I would've hoped that Python 4000 would address the internals (JIT) just 
as Python 3000 addressed the externals.

--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread r
~Michael,
What’s next down this road of self destruction? Hey guys, forget about
about empty parenthesis on a function/method call,  we should not have
to waste are time typing them… Wait forget about them all together and
we will just write Ruby code…

Def function arg arg arg arg arg arg

“Yea, that looks good“.insert(sarcasm)
Things like forcing empty tuple on function/method calls are what make
python so great. Python dumped the C bracket plague,  but enforces
parenthesis even for a no argument function. But hell, why shouldn’t
we have 50 ways to the same thing in Python like Ruby.

PS. Don’t discredit Walter just because he is not on the dev team,
that don’t mean squat!


~Bearophile,
Thanks for your civil approach to this conversation but I must
disagree with you on the new string formatting syntax. You said the
new syntax is suppost to be easier on the n00b , I say it pollutes a
students mind. What is wrong with similarities to C formatting,  I
find nothing complicated about it.

%s (means put a string here)
%d (means put a integer here)
%f (means put a float here)

It does not get any simpler than that, and this will just ease the
transition to C programming for this student. Lets not forget how
important C is!

I always likened Python to my cool uncle who would let me get away
with more than my parents-C- but would enforce the important rules.
Like Python’s forcing of empty tuple in function calls, that is a good
idea. This allows you to clearly see arguments in source code. I like
in Python there is only one, or a very minimal number of ways to do
something(but usually only one is the best). Ruby is littered with
different ways to do the same thing. I think this will be Ruby’s
undoing…. And Pythons if we follow down this road.

And lets not forget Python forcing of indention, that is Pythons
greatest strength!

--
http://mail.python.org/mailman/listinfo/python-list


Segmentation fault in PyObjectMalloc on FreeBSD

2008-12-19 Thread youcancallmeal
I have a multithreaded python app running on FreeBSD (both 7.0 and
6.3) that crashes with a segmentation fault coming from
PyObjectMalloc. This first happened using Python 2.5 built from Ports.
I then pulled down r261 from Subversion and built that so I would have
debugging symbols; it still crashed. Below is a back trace from gdb:

#0  PyObject_Malloc (nbytes=2) at Objects/obmalloc.c:758
#1  0x080942aa in PyString_FromStringAndSize (str=0x0, size=50) at
Objects/stringobject.c:83
#2  0x0809b30b in PyString_FromFormatV (format=0x813c6d4 "%.50s
instance has no attribute '%.400s'",
vargs=0xbf6fa048 "üõ.\bÄQ\031\bì¯>\b") at Objects/stringobject.c:
238
#3  0x080dcd48 in PyErr_Format (exception=0x8158660, format=0x813c6d4
"%.50s instance has no attribute '%.400s'")
at Python/errors.c:538
#4  0x08064549 in instance_getattr1 (inst=0x833ed4c, name=0x81951b0)
at Objects/classobject.c:717
#5  0x08067c9f in instance_nonzero (self=0x833ed4c) at Objects/
classobject.c:754
#6  0x0808a592 in PyObject_IsTrue (v=0x8473000) at Objects/object.c:
1532
#7  0x080cb6d3 in PyEval_EvalFrameEx (f=0x857860c, throwflag=0) at
Python/ceval.c:2173
#8  0x080cef5d in PyEval_EvalFrameEx (f=0x8574e0c, throwflag=0) at
Python/ceval.c:3765
#9  0x080cef5d in PyEval_EvalFrameEx (f=0x856980c, throwflag=0) at
Python/ceval.c:3765
#10 0x080cfbe8 in PyEval_EvalCodeEx (co=0x82f7218, globals=0x49,
locals=0x815dd40, args=0x819402c, argcount=4, kws=0x83a99a0,
kwcount=0, defs=0x833e758, defcount=2, closure=0x0) at Python/
ceval.c:2942
#11 0x08124260 in function_call (func=0x83408b4, arg=0x846ee64,
kw=0x845546c) at Objects/funcobject.c:524
#12 0x08060402 in PyObject_Call (func=0x83408b4, arg=0x846ee64,
kw=0x845546c) at Objects/abstract.c:2487
#13 0x080cbdbc in PyEval_EvalFrameEx (f=0x856dc0c, throwflag=0) at
Python/ceval.c:3978
#14 0x080cfbe8 in PyEval_EvalCodeEx (co=0x82f6cc8, globals=0x49,
locals=0x815dd40, args=0x819402c, argcount=2, kws=0x8572154,
kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:
2942
#15 0x080cdbda in PyEval_EvalFrameEx (f=0x857200c, throwflag=0) at
Python/ceval.c:3774
#16 0x080cef5d in PyEval_EvalFrameEx (f=0x850860c, throwflag=0) at
Python/ceval.c:3765
#17 0x080cef5d in PyEval_EvalFrameEx (f=0x850940c, throwflag=0) at
Python/ceval.c:3765
#18 0x080cef5d in PyEval_EvalFrameEx (f=0x857680c, throwflag=0) at
Python/ceval.c:3765
#19 0x080cfbe8 in PyEval_EvalCodeEx (co=0x83c5f50, globals=0x49,
locals=0x815dd40, args=0x819402c, argcount=2, kws=0x8506364,
kwcount=0, defs=0x83d1c78, defcount=1, closure=0x0) at Python/
ceval.c:2942
#20 0x080cdbda in PyEval_EvalFrameEx (f=0x850620c, throwflag=0) at
Python/ceval.c:3774
#21 0x080cef5d in PyEval_EvalFrameEx (f=0x850980c, throwflag=0) at
Python/ceval.c:3765
#22 0x080cef5d in PyEval_EvalFrameEx (f=0x84efa0c, throwflag=0) at
Python/ceval.c:3765
#23 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef80c, throwflag=0) at
Python/ceval.c:3765
#24 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef60c, throwflag=0) at
Python/ceval.c:3765
#25 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef40c, throwflag=0) at
Python/ceval.c:3765
#26 0x080cef5d in PyEval_EvalFrameEx (f=0x84ef20c, throwflag=0) at
Python/ceval.c:3765
#27 0x080cfbe8 in PyEval_EvalCodeEx (co=0x82cdf98, globals=0x49,
locals=0x815dd40, args=0x819402c, argcount=1, kws=0x0, kwcount=0,
defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2942
#28 0x08124260 in function_call (func=0x82e8b8c, arg=0x8471dec,
kw=0x0) at Objects/funcobject.c:524
#29 0x08060402 in PyObject_Call (func=0x82e8b8c, arg=0x8471dec,
kw=0x0) at Objects/abstract.c:2487
#30 0x08069bed in instancemethod_call (func=0x49, arg=0x8471dec,
kw=0x0) at Objects/classobject.c:2579
#31 0x08060402 in PyObject_Call (func=0x83e8a7c, arg=0x819402c,
kw=0x0) at Objects/abstract.c:2487
#32 0x080c87da in PyEval_CallObjectWithKeywords (func=0x83e8a7c,
arg=0x819402c, kw=0x0) at Python/ceval.c:3548
#33 0x080fccdd in t_bootstrap (boot_raw=0x83a9910) at ./Modules/
threadmodule.c:425
#34 0x281b05cf in pthread_create () from /usr/lib/libthr.so.2
#35 0x in ?? ()

This part is particularly interesting:

(gdb) frame 1
#1  0x080942aa in PyString_FromStringAndSize (str=0x0, size=50) at
Objects/stringobject.c:83
83  op = (PyStringObject *)PyObject_MALLOC(sizeof
(PyStringObject) + size);
(gdb) print size
$7 = 50
(gdb) print sizeof(PyStringObject)
$8 = 24

(gdb) frame 0
#0  PyObject_Malloc (nbytes=2) at Objects/obmalloc.c:758
758 if ((pool->freeblock = *(block **)bp) !
= NULL) {
(gdb) print nbytes
$9 = 2

So 50 + 24 == 2? Or am I missing something? Can anyone suggest how to
figure out what's really going on here?
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to code

2008-12-19 Thread eric
On Dec 19, 6:36 pm, eric  wrote:
> On Dec 19, 5:35 pm, Peter Otten <__pete...@web.de> wrote:
>
>
>
> > eric wrote:
> > > hi,
>
> > > I need to find a "good" design pattern to instanciate, and add
> > > specific code all in one. Let me explain it :
>
> > > I need to define "some" code, better be in a class, something like
>
> > > class LinkA(object):
> > >     def mystuff(self):
> > >          
>
> > > class LinkB(object):
> > >     def mystuff(self):
> > >          
>
> > > AND I need an instance of this class
> > > { "stuff A": LinkA()
> > >   "stuff B": LinkB()
> > > }
>
> > > This kind of code "would" be fine, I mean, the result effect in memory
> > > is fine for me.
> > > But I don't like the way I have to
> > > 1/ give a useless name to LinkA, linkB (there can be hundreds of names
> > > like that)
> > > 2/ I have to write it down two times (and that's one time too much)
>
> > > any ideas ?
>
> > > something like
> > > [
> > > new object():
> > >     def mystuff(self):
> > >        
> > > ,
> > > new object():
> > >     def mystuff(self):
> > >        
> > > ]
>
> > > would be really perfect (but I know it does not work, or at least, I
> > > don't know how to make it work)
>
> > > In fact, I would like to define a class, and an instance in a single
> > > statement
> > >>> class Register:
>
> > ...     def __init__(self):
> > ...             self.items = []
> > ...     def __call__(self, method):
> > ...             class Link(object):
> > ...                     mystuff = method
> > ...             self.items.append(Link())
> > ...>>> register = Register()
> > >>> @register
>
> > ... def mystuff(self): print "first"
> > ...>>> @register
>
> > ... def mystuff(self): print "second"
> > ...>>> for item in register.items:
>
> > ...     item.mystuff()
> > ...
> > first
> > second
>
> > Peter
>
> hi,
>
> I've tried something like this :
>
> import inspect
>
> class Test(object):
>     class Inner(object):
>         def mystuff(self):
>             print "hello stuff"
>
>     class InnerB(object):
>         def mystuff(self):
>             print "hello B"
>
> def filter(member):
>     return inspect.isclass(member) and not member==Test.__class__
> d = dict( (name, c()) for name, c in inspect.getmembers(Test,
> filter ) )
> print d
>
> it works too, but I prefer your method
>
> thanks
>
> --
> Erichttp://codeslash.blogspot.com

Finally here is my 'final' shot:

context: when building a glade GUI I wanted to connect 'nicely'
signals (I hate coding the same info in several places)

here is my main :

if __name__=="__main__":
pathname = os.path.dirname(sys.argv[0])
startup = os.path.join(pathname, 'pyshow/pyshow.glade')
xml = gtk.glade.XML(startup) #'filename.glade')

#the stuff starts here
m = MainApp()
for widget_name, codget in m.items():
codget.set_widget( xml.get_widget(widget_name) )

gtk.main()


and here is the 'MainApp' code, based on the question, and finally I
get stuck to my second solution


import inspect
class Controller(dict):
def __init__(self):
dict.__init__(self)
self.update(
(name, c()) for name, c in inspect.getmembers
(self.__class__, lambda member: inspect.isclass(member) and not
member==self.__class__.__class__  )
   )



class MainApp(Controller):
def __init__(self):
Controller.__init__(self)

class main_window(codget):
def on_destroy(self, widget, modget):
print "bye bye"

class play(codget):
def on_clicked(self, widget, modget):
print "you have clicked"



the business is hidden in codget ( as COntroller gaDGET), and what's
interesting for me, is that every signal handler has a 'modget' ( as
in model gadget) that it can use to do the job (part of the MVC
pattern)

thanks Peter anyway, I didn't use your solution in this specific case,
but I loved the solution anyway, and I'm sure that I'll use it one
day.







--
http://mail.python.org/mailman/listinfo/python-list


pymssql for python 2.6 ?

2008-12-19 Thread TkNeo
when would pymssql come out with a release that is compatible with
python 2.6 ?


Thanks
-TK
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread excord80
On Dec 19, 11:01 am, walterbyrd  wrote:
>
> To me, it seems that this:
>
> print "%s=%d" % ('this',99)
>
> Is much easier, and faster, to type, and is also easier to read and
> understand. [snip]
>
> This (if it's right) is much longer, and requires more special
> characters.
>
> print( "{0}={1}".format('this',99))
>

Yeah, I like the old way better too. It's got this nice elegant
simplicity to it (using the percent sign for not only the things
inside the string, but also to separate it from the tuple that
follows). Also, I like having only *one* special symbol (`%') to worry
about in my strings instead of two (`{' and `}').

But, Python is Python. So I'll keep using the old way until they
deprecate it, and then just get used to the new way. One reason I use
Python is because I really *don't* have the time or inclination to
question every little design decision and argue about alternatives. If
you want to tweak the language to suit your personal tastes, you might
prefer Perl 6.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: New Book: Programming in Python 3

2008-12-19 Thread Benjamin Kaplan
On Fri, Dec 19, 2008 at 12:53 PM, Thomas Heller  wrote:

> Steve Holden schrieb:
> > Thomas Heller wrote:
> >> Question from a non-native english speaker: is this now valid english?
> >>
> >>   "One of Python's great strengths"
> >> ^
> >>   "and also teaches Python's functional programming features"
> >>   ^
> >>   "The book's approach is wholly practical"
> >>^
> > It always has been valid English. The apostrophe is only omitted from
> > personal pronouns (hers, its, and so on).
>
> I see, thanks.  But, is the apostrophe optional in the above fragments?
>

No. The apostrophe on the nouns is used to denote possession. If you don't
include it, the word becomes plural (which makes no sense on proper nouns).
The way to write the sentance without the apostrophe would be "One of the
great strengths of Python" and "The approach of the book is wholly
practical". To a native English speaker, this alternative is much more
awkward.
--
http://mail.python.org/mailman/listinfo/python-list


Re: IMAP: How to implement GMail-like threaded conversations view

2008-12-19 Thread Michael Torrie
Martin wrote:
> Currently I am trying to get used to Python's imaplib and email
> modules.
> I'like to create a webmail client simmilar to GMail.

This is off-topic, but why on earth would you want to emulate Gmail's
conversation views?  It's horrible and a very broken way of viewing
e-mail threads.  Compared the normal, threaded view of, say the
discussions on this list to the view that Gmail gives you.  For
conversations of more than half a dozen posts, Gmail's view is
unnavigatable.  Suppose I want to break into a discussion that's already
 dozens of posts long.  With a real threaded view I can easily see the
flow of the conversation, grab random posts, then maybe read their
parent or grandparent posts.  Looking at the rest of your e-mail, I can
see that maybe you do want to have real threads rather than the google
conversation view which removes all structure.

> 
> My Questions:
> a) Is there any feature hidden in Python's built-in modules (imaplib,
> email) that already can group all my mails into threads?

Each e-mail has a referral number that refers to the parent email. Just
keep track of these in a structure and you can easily build a nice tree
of the thread.

> 
> b) If not a... what would be the best way to implement this?
> 
> I can think of two approaches:
> b.1) Use the "References:" field of the messages in order to find out
> which messages are related to each other.

Yes. This is absolutely the right way to do it.

> 
> I tried a first implementation which works quite well but I don't know
> if there can occur situations where one message is related to two
> parents. Also I don't know what happens if someone is too lazy to type
> my address. He might click at "Reply", delete topic and old mail-text
> and compose a new mail. Theoretically his mail client would set the
> "References:" field accordingly never the less, wouldn't it? Therefore
> my mail client would consider that completely new mail as part of an
> older conversation.

In this case, a lazy user is a lazy user.  Probably best to encourage
people to use better etiquette when using e-mail.

> 
> The thoughts above might lead to the second approach:
> 
> b.2) Use the "Subject:" field of the messages.

Horribly broken.  Thunderbird does this and it drives me crazy.  I often
get messages months apart that happen to have a common subject line,
even though they aren't the same thread or conversation.  I don't want a
new message, which does not refer to the old message in any way, to
attach itself to my 6-month old message and force me to scroll down
through potentially hundreds of e-mails to find the stupid thing.  No,
the RFCs are there for a reason.  They bring sanity to the chaos.
Anything else is madness.  And the fact the Outlook doesn't do proper
referral fields just infuriates me.  Sigh.



--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: New Book: Programming in Python 3

2008-12-19 Thread excord80
On Dec 4, 2:42 pm, Alan G Isaac  wrote:
> Mark Summerfield wrote:
> > "Programming in Python 3:
> > A Complete Introduction to the Python Language"
> > ISBN 0137129297
> >http://www.qtrac.eu/py3book.html
>
> OMG, you really wrote it in Lout?
> I wish you would add to http://www.qtrac.eu/lout.html
> a comment on what you get out of that
> (compared to using e.g., LaTeX or
> reStructuredText).

I'm also curious about why you chose Lout over LaTeX or reST.
--
http://mail.python.org/mailman/listinfo/python-list


PIL on 3.x?

2008-12-19 Thread Daniel Fetchinson
Does anyone know if PIL will be ported to the 3.x branch?

Cheers,
Daniel
-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: Building a web questionnaire, can it be done in Python ?

2008-12-19 Thread excord80
On Dec 19, 11:58 am, Stef Mientki  wrote:
> hello,
>
> I'm considering building a web questionnaire in Python.
> I've made several desktop applications in Python /  wxPython,
> but I've no experience in using Python on a webserver,
> and I don't have much knowledge about web applications in general.
>

Ah. You want to report directly to the Django tutorial:
http://docs.djangoproject.com/en/dev/intro/tutorial01/
--
http://mail.python.org/mailman/listinfo/python-list


Re: PIL on 3.x?

2008-12-19 Thread John Machin
On Dec 20, 6:55 am, "Daniel Fetchinson" 
wrote:
> Does anyone know if PIL will be ported to the 3.x branch?

Have you considered e-mail to the author?



--
http://mail.python.org/mailman/listinfo/python-list


Re: pymssql for python 2.6 ?

2008-12-19 Thread M�ta-MCI (MVP)
Hi! 


Look at http://www.mayukhbose.com/python/ado/ado-connection.php
That run OK with Python 2.6

@-salutations
--
MCI


--
http://mail.python.org/mailman/listinfo/python-list


Re: Factoring Polynomials

2008-12-19 Thread Scott David Daniels

Tim Rowe wrote:

2008/12/18 Scott David Daniels :


def quadsolve(a, b, c):
   try:
   discriminant = sqrt(b**2 - 4 * a * c)


The discriminant of a quadratic is more usually just the b**2 - 4 * a
* c part, not the square root of it. Testing that for negative, zero
or positive avoids the need to use an exception for a normal case.


Absolutely right.  Blame the oversight on my old CPU-stingy days.  When
the CPU was slow, avoiding a sqrt here or there (if you didn't have a
sqrt opcode) was so important that I do it without thinking these days.
Since I still have that disease, perhaps the variable should be renamed
root_discriminant.

As for the testing, I find using math.sqrt catches the negative cases
and raises an exception by itself, leaving only the issue of whether
or not to return a pair or singleton.  Usually for my purposes, I'd let
the exception fly and not return an (?the?) empty tuple.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >