Re: Help with generators outside of loops.

2004-12-08 Thread Andrea Griffini
David Eppstein wrote:
In article <[EMAIL PROTECTED]>,
 "Robert Brewer" <[EMAIL PROTECTED]> wrote:

But I'm guessing that you can't index into a generator as if 
it is a list.
row = obj.ExecSQLQuery(sql, args).next()

I've made it a policy in my own code to always surround explicit calls 
to next() with try ... except StopIteration ... guards.

Otherwise if you don't guard the call and you get an unexpected 
exception from the next(), within a call chain that includes a for-loop 
over another generator, then that other for-loop will terminate without 
any error messages and the cause of its termination can be very 
difficult to track down.
Isn't the handling of StopIteration confined in the very moment of
calling .next() ? This was what I expected... and from a simple test
looks also what is happening...
>>> for x in xrange(10):
if x == 8:
raise StopIteration()
print x

0
1
2
3
4
5
6
7
Traceback (most recent call last):
  File "", line 3, in -toplevel-
raise StopIteration()
StopIteration
i.e. the loop didn't stop silently
Andrea
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple GUI question

2004-12-08 Thread Brian van den Broek
Roose said unto the world upon 2004-12-08 02:23:
You want somthing like:
root = Tkinter.Tk()
root.withdraw()
msg = tkMessageBox.showwarning("Ooops", "Some warning")

Awesome thanks!  Any chance you know about the font thing : )
Nah I'll stop being lazy and hack it... but for some reason Tkinter doesn't
jive with the way I think at all.  It seems very different from the rest of
Python, which makes sense obviously since it was around before Python...
Hi,
I don't know Tkinter past a hour of playing, so I cannot show you how. I 
can, however, show you a good place to start looking:


Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple GUI question

2004-12-08 Thread Brian van den Broek
Brian van den Broek said unto the world upon 2004-12-08 03:16:

Hi,
I don't know Tkinter past a hour of playing, so I cannot show you how. I 
can, however, show you a good place to start looking:
 

Best,
Brian vdB
Hi,
I didn't mean that in a grouchy way. I just took a quick look at some of
the links and
 looked
promising.
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


guarding for StopIteration (WAS: Help with generators outside of loops.)

2004-12-08 Thread Steven Bethard
David Eppstein wrote:
I've made it a policy in my own code to always surround explicit calls 
to next() with try ... except StopIteration ... guards.

Otherwise if you don't guard the call and you get an unexpected 
exception from the next(), within a call chain that includes a for-loop 
over another generator, then that other for-loop will terminate without 
any error messages and the cause of its termination can be very 
difficult to track down.
Just to clarify here, the only time code raising a StopIteration will 
cause a for-loop to exit silently is if the StopIteration is raised in 
an __iter__ method, e.g.:

>>> def g():
... raise StopIteration
...
>>> class C(object):
... def __iter__(self):
... for i in range(3):
... yield i
... g()
...
>>> for i in C():
... print i
...
0
>>>
A StopIteration raised within the body of a for-loop will not cause it 
to terminate silently; the StopIteration exception will be propagated 
upward:

>>> def g():
... raise StopIteration
...
>>> def f(n):
... for i in range(n):
... print i
... g()
...
>>> f(3)
0
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 4, in f
  File "", line 2, in g
StopIteration
>>>
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: guarding for StopIteration (WAS: Help with generators outside of loops.)

2004-12-08 Thread Steven Bethard
Steven Bethard wrote:
Just to clarify here, the only time code raising a StopIteration will 
cause a for-loop to exit silently is if the StopIteration is raised in 
an __iter__ method, e.g.:
That was a little imprecise.  What I should have said is "the only time 
code raising a StopIteration will cause a for-loop to exit silently is 
if the StopIteration is raised in the code that is executed under the 
iteration protocol."

So, using the legacy iterator protocol:
>>> class C:
... def __getitem__(self, index):
... if index > 3:
... raise IndexError
... if index == 1:
... raise StopIteration
... return index
...
>>> for i in C():
... print i
...
0
Or using a separate iterator object:
>>> class C(object):
... def __iter__(self):
... return I()
...
>>> class I(object):
... def __init__(self):
... self.count = -1
... def next(self):
... self.count += 1
... if self.count == 1:
... raise StopIteration
... return self.count
...
>>> for i in C():
... print i
...
0
Or using a generator to create the iterator object:
>>> class C(object):
... def __iter__(self):
... for i in range(3):
... if i == 1:
... raise StopIteration
... yield i
...
>>> for i in C():
... print i
...
0
Basically, each of these raises a StopIteration in the equivalent of the 
.next method.  If a function that raises a StopIteration is put into any 
of the places where my code says 'raise StopIteration', then that 
StopIteration will silently terminate the loop.

I don't believe there should be any other places where raising a 
StopIteration would silently terminate a loop.

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


Re: why python is slower than java?

2004-12-08 Thread Andrew Dalke
JanC: 
> That person might be a student in some third-world country...

Then think of the extra incentive to provide useful answers.

Also, Eric had pointed out that payment included "money,
sex, chocolate" and other non-monetary possibilities.

Personally I think it'll be hard to put a monetary micropayment
into place because at that level those other factors have at
least a comparable impact.

Andrew
[EMAIL PROTECTED]


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


creating generators from function

2004-12-08 Thread Simon Wittber
I use a coroutine/generator framework for simulating concurrent processes.

To do this, I write all my functions using the general form:

while True:
do stuff
yield None

To make these generator functions compatible with a standard thread
interface, I attempted to write a decorator which converts a standard
function into a generator function (code attached below).
Unfortunately, I received an exception, before I could test if my idea
would work:

TypeError: cannot create 'generator' instances

I guess I can go the other way, and convert a generator into a
function, but that just doesn't seem right.

Is there anyway solve the problem described?

Sw.


from opcode import opmap
import types
globals().update(opmap)

def generatorize(f):
co = f.func_code
nc = [ord(x) for x in co.co_code]
for op,i in enumerate(nc):
if op == RETURN_VALUE:
nc[i] = YIELD_VALUE
newcode = ''.join([chr(x) for x in nc])
codeobj = type(co)(co.co_argcount, co.co_nlocals, co.co_stacksize,
co.co_flags, newcode, co.co_consts, co.co_names,
co.co_varnames, co.co_filename, co.co_name,
co.co_firstlineno, co.co_lnotab, co.co_freevars,
co.co_cellvars)

print types.GeneratorType(f)(codeobj, f.func_globals, f.func_name,
f.func_defaults, f.func_closure)
return f

@generatorize
def f():
while True:
return 1

def g():
while True:
yield 1

print g()
print f()
-- 
http://mail.python.org/mailman/listinfo/python-list


os.path.islink()

2004-12-08 Thread Egor Bolonev
hi all
i want my program to ignore ntfs links, but os.path.islink() isnt work as  
i expect

print os.path.islink('''C:\Documents and Settings\Егор\My  
Documents\Scripts\Antiloop\)
outputs
False

far file manager said 'C:\Documents and Settings\Егор\My  
Documents\Scripts\Antiloop\' is link

how to detect ntfs links?
=program==
import os, os.path
def get_all_files(path):
if len(path) > 0:
if path[-1] == ':':
path=path+'\\'
try:
for i in os.listdir(path):
j = os.path.join(path, i)
if os.path.isdir(j) and not os.path.islink(j):
for ii in get_all_files(j):
yield ii
else:
yield j
except:pass
for i in get_all_files('c:'):
print i
==
--
http://mail.python.org/mailman/listinfo/python-list


Re: How is Python designed?

2004-12-08 Thread Limin Fu
Of course for such simple expression, that function
will not run recursively, but for more complex
expressions, it will, as a example:
 a + b * ( c + ( d - e ) / f )...


--- LutherRevisited <[EMAIL PROTECTED]> wrote:

> Kinda off subject, just thought I'd add that 0! = 1
> for that recursion example,
> since that wasn't considered.  Nice post though.
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 




__ 
Do you Yahoo!? 
The all-new My Yahoo! - What will yours do?
http://my.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.islink()

2004-12-08 Thread Peter Maas
Egor Bolonev schrieb:
far file manager said 'C:\Documents and Settings\ÐÐÐÑ\My  
Documents\Scripts\Antiloop\' is link

how to detect ntfs links?
There are no ntfs links. What appears as a link on GUI level is
nothing but a plain file with special content, so that
os.path.islink() tells the truth. Windows "links" are a special
Windows feature (shortcuts) and must be detected via Win32 api
calls or by searching for content characteristics of shortcuts.
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: creating generators from function

2004-12-08 Thread Steven Bethard
Simon Wittber wrote:
I use a coroutine/generator framework for simulating concurrent processes.
To do this, I write all my functions using the general form:
while True:
do stuff
yield None
To make these generator functions compatible with a standard thread
interface, I attempted to write a decorator which converts a standard
function into a generator function (code attached below).
[snip]
@generatorize
def f():
while True:
return 1

def g():
while True:
yield 1

print g()
print f()
I'm a little confused as to what you're trying to do here.  The f() 
function, in particular, doesn't make much sense -- the 'while True' 
doesn't do anything since the 'return 1' is executed on the first time 
through the loop.  If you really do want to turn your functions into 
generators of the form:

while True:
do stuff
yield None
why can't you just do:
>>> def generatorize(f):
... def new_f(*args, **kwds):
... while True:
... f(*args, **kwds)
... yield None
... return new_f
...
>>> @generatorize
... def f():
... return 1
...
>>> i = f()
>>> print i.next()
None
>>> print i.next()
None
Basically, I've assumed that 'do stuff' is the function that's being 
wrapped.

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


Re: cookie lib policy how-tp?

2004-12-08 Thread Riko Wichmann
Tried that already. At least, I hope I guessed at least one of the 
possible identifiers correct: MSIE6.0, MSIE 6.0, MSIE/6.0

When my opera is set to identify as MSIE, it sends
 "Mozilla/4.0 (compatible; MSIE 6.0; X11; Linux i686) Opera 7.54  [en]".
Hi Marc,
thanks for the hint! that brought me a big step forward!
Cheers,
Riko
--
http://mail.python.org/mailman/listinfo/python-list


spawn or fork

2004-12-08 Thread C Gillespie
Dear All,

I have a function
def printHello():
fp = open('file','w')
fp.write('hello')
fp.close()

I would like to call that function using spawn or fork. My questions are:

1. Which should I use
2. How do I call that function if it is defined in the same file.

Many thanks

Colin


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


Connecting to numarray. Problem with the setup program

2004-12-08 Thread Jean Moser
I tried many times to connect to numarray without success.
I choosed the release: numarray-1.1.1.win32py2.2.exe then I went to
the setup program made by Greenfield and I tried to follow the
commands.The mentioned Python directory is C:\PROGRA~2 which is not
covenient. I tried to change it but without success. From now on I
could not go further. What shall I do ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.islink()

2004-12-08 Thread Egor Bolonev
On Wed, 08 Dec 2004 10:23:13 +0100, Peter Maas <[EMAIL PROTECTED]> wrote:
Egor Bolonev schrieb:
far file manager said 'C:\Documents and Settings\Егор\My   
Documents\Scripts\Antiloop\' is link
 how to detect ntfs links?
There are no ntfs links. What appears as a link on GUI level is
nothing but a plain file with special content, so that
os.path.islink() tells the truth. Windows "links" are a special
Windows feature (shortcuts) and must be detected via Win32 api
calls or by searching for content characteristics of shortcuts.
gui folder link is a .lnk file
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.islink()

2004-12-08 Thread Egor Bolonev
On Wed, 08 Dec 2004 20:29:27 +1000, Egor Bolonev <[EMAIL PROTECTED]> wrote:
gui folder link is a .lnk file
i want to detect "'s"

C:\Documents and Settings\Егор\My Documents>dir
 Том в устройстве C не имеет метки.
 Серийный номер тома: 386D-F630
 Содержимое папки C:\Documents and Settings\Егор\My Documents
08.12.2004  20:39  .
08.12.2004  20:39  ..
08.12.2004  20:39 Antiloop
06.12.2004  20:47  My eBooks
02.12.2004  22:50  My Music
06.12.2004  23:34  My Pictures
06.12.2004  23:56  My Videos
08.12.2004  20:23  Scripts
04.12.2004  16:23  upload
16.11.2004  21:14  Virtual CD v6
16.11.2004  21:15  Virtual CDs
08.12.2004  20:36  [temp]
04.12.2004  20:11  Личное
06.12.2004  22:51  Новая папка
   0 файлов  0 байт
  14 папок   8 970 833 920 байт свободно

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


Re: os.path.islink()

2004-12-08 Thread Erik Max Francis
Egor Bolonev wrote:
gui folder link is a .lnk file
What he's telling you is that Windows doesn't implement symbolic links. 
 os.path.islink does not detect what you think it does.

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  I am an island / A little freak of melancholy
  -- Lamya
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple GUI question

2004-12-08 Thread Eric Brunel
Roose wrote:
[snip]
Another thing I would *like* but is not strictly necessary would be to
change the font size and color of the text within the box.  Is there a good
way of doing that?  I have googled around but can't find any decent example
code for some reason.
Short answer: you can't. The tkMessageBox functions use "native" dialogs, which 
cannot be configured.

The long answer depends on which platform you're on. If you are on Windows..., 
see short answer ;-) : the dialogs used are actually the native ones, and apart 
from abandonning the tkMessageBox module and designing your own dialogs, there 
is no way to alter their appearence (not that I know of).

If you're on Unix, it's a bit better but not much: since there's no such thing 
as "native" dialogs, the dialogs are actually tcl code that is in the tcl/tk 
distro, that you can hack anyway you want. This is however not recommended (not 
by me, anyway...), because it has many drawbacks (modify the tcl code will 
modify *all* your dialogs and you won't be able to simply distribute your script 
with the appearence changes: you'll have to distribute the new tcl code for the 
dialogs too...)

So if you really want to do that, the simplest way is definetely to avoid using 
the tkMessageBox module and to design your own dialogs.

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: spawn or fork

2004-12-08 Thread Miki Tebeka
Hello Colin,

> I have a function
> def printHello():
> fp = open('file','w')
> fp.write('hello')
> fp.close()
> 
> I would like to call that function using spawn or fork. My questions are:
> 
> 1. Which should I use
spawn and fork are very different functions. Read the documentation on
each.
Note the "fork" is available only in Unix like systems.

> 2. How do I call that function if it is defined in the same file.
Just call it.

def foo():
print 1

foo()

Bye.
--

Miki Tebeka <[EMAIL PROTECTED]>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating generators from function

2004-12-08 Thread Peter Otten
Simon Wittber wrote:

> I use a coroutine/generator framework for simulating concurrent processes.
> 
> To do this, I write all my functions using the general form:
> 
> while True:
> do stuff
> yield None
> 
> To make these generator functions compatible with a standard thread
> interface, I attempted to write a decorator which converts a standard
> function into a generator function (code attached below).
> Unfortunately, I received an exception, before I could test if my idea
> would work:
> 
> TypeError: cannot create 'generator' instances
> 
> I guess I can go the other way, and convert a generator into a
> function, but that just doesn't seem right.
> 
> Is there anyway solve the problem described?
 
Generators are just functions with an extra flag set. I tried the following
modification of your code:


from opcode import opmap
globals().update(opmap)

def _f(): pass
function = type(_f)
del _f

def generatorize(f):
co = f.func_code
nc = [ord(x) for x in co.co_code]
for i, op in enumerate(nc[:-1]):
if op == RETURN_VALUE:
nc[i] = YIELD_VALUE
newcode = ''.join([chr(x) for x in nc])

codeobj = type(co)(co.co_argcount, co.co_nlocals, co.co_stacksize,
co.co_flags + 32, newcode, co.co_consts,
co.co_names,
co.co_varnames, co.co_filename, co.co_name,
co.co_firstlineno, co.co_lnotab, co.co_freevars,
co.co_cellvars)

return function(codeobj, f.func_globals, f.func_name,
f.func_defaults, f.func_closure)

@generatorize
def f():
while True:
return 1

def g():
while True:
yield 1

print g()
print f()

import itertools
print list(itertools.islice(f(), 5))


The hardest part was to find the enumerate() bug. I agree with Steven that
converting between functions and generators by replacing return with yield
and vice versa is hardly ever useful, though.

Peter












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


Re: Python for Palm OS?

2004-12-08 Thread 'Dang' Daniel Griffith
On Wed, 08 Dec 2004 04:48:42 GMT, Maurice LING <[EMAIL PROTECTED]>
wrote:

>As mentioned, since Pippy is pretty old or rather based on rather old 
>code base, can it be assumed that not much is happening at this front?
>
>This might be dumb to ask then, does anyone know if Pippy had been used 
>in any noticeable form for Palm development anywhere? Or it's more of an 
>proof of concept kind of thing? Or has anyone envisioned anything?
>
>Cheers
>Maurice
I think their web site (at one time, at least) explicitly said they
had stopped development of Pippy.  I use it on rare occasions when I
need a programmable calculator.  But since it only supports 32-bit
integer math, i.e., not float or long, that's a pretty limited
occasion.  It appears to have access to Palm "form" capabilities, but
I was never able to figure out how they work.  The docs are a little
light.  Still, I'm impressed that they got it there in the first
place.  I also saw the Lua port, but have not installed it, yet.  I
was too busy with Carmen Electra.  Or, at least, envisioning Carmen
Electra.  ;-)
--dang
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deferred decorator

2004-12-08 Thread Nick Coghlan
Bryan wrote:
i'm also curious if it's possible to write this recipe using the new 
class style for the Deffered class.it appears you can nolonger 
delegate all attributes including special methods to the contained 
object by using the __getattr__ or the new __getattribute__ methods.  
does anyone know how to port this recipe to the new class style?
Override __getattribute__. I don't know why you think it doesn't let you 
override all attribute accesses, as that's exactly what it is for.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: spawn or fork

2004-12-08 Thread C Gillespie

"Miki Tebeka" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hello Colin,
>
> > I have a function
> > def printHello():
> > fp = open('file','w')
> > fp.write('hello')
> > fp.close()
> >
> > I would like to call that function using spawn or fork. My questions
are:
> >
> > 1. Which should I use
> spawn and fork are very different functions. Read the documentation on
> each.
> Note the "fork" is available only in Unix like systems.
>
> > 2. How do I call that function if it is defined in the same file.
> Just call it.
>
> def foo():
> print 1
>
Thanks, but can I call it using spawn?



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


Re: Sorting in huge files

2004-12-08 Thread Jeremy Sanders
On Tue, 07 Dec 2004 12:27:33 -0800, Paul wrote:

> I have a large database of 15GB, consisting of 10^8 entries of
> approximately 100 bytes each. I devised a relatively simple key map on
> my database, and I would like to order the database with respect to the
> key.

You won't be able to load this into memory on a 32-bit machine, even with
loads of swap. Maybe you could do this on x86-64 with lots of swap (or
loadsa memory), or other 64-bit hardware. It will be _really_ slow,
however.

Otherwise you could do an on-disk sort (not too hard with fixed-length
records), but this will require some coding. You'll probably need to do
some reading to work out which sorting algorithm accesses the data less
randomly. I think the key phrase is an "external sort" rather than an
"interal sort".

It's probably easiest to load it into the thing into a database (like
PostgreSQL), to do the work for you.

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


Re: How do I do this? (eval() on the left hand side)

2004-12-08 Thread Nick Coghlan
It's me wrote:
Yes, Russell, what you suggested works.
I have to chew more on the syntax to see how this is working.
because in the book that I have, it says:
exec code [ in globaldict [, localdict] ]
The [] indicate the last two parts are optional. If you don't supply them, exec 
just uses the current namespace.

However, as others have said, you are much better off using a separate 
dictionary for such values, rather than stuffing them into the local variables:

  user_vars = {}
  y = "a"
  user_vars[y] = 4
It keeps a clean separation between your variables and the user's variables, 
easily avoiding namespace conflicts.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: writing to mailboxes

2004-12-08 Thread Thomas Guettler
Am Tue, 07 Dec 2004 15:30:13 -0500 schrieb Eric S. Johansson:

> I've been searching around for the equivalent to the mailbox module 
> except with the capability of writing messages as well as reading.  If 
> it makes it easier, I only need to write to maildir mailboxes.

Hi,

there is a script called "getmail". It is a fetchmail
replacement written in python. It can write to maildir mailboxes.

HTH,
 Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Google's MapReduce

2004-12-08 Thread bearophileHUGS
(This Google article suggestion comes from the CleverCS site):

http://labs.google.com/papers/mapreduce-osdi04.pdf

"MapReduce is a programming model and an associated implementation for
processing and generating large data sets. Users specify a map function
that processes a key/value pair to generate a set of intermediate
key/value pairs, and a reduce function that merges all intermediate
values associated with the same intermediate key."

This looks like something that can be (nicely) done with Python too.
Bye,
Bearophile

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


Re: How do I do this? (eval() on the left hand side)

2004-12-08 Thread Nick Coghlan
Caleb Hattingh wrote:
'>>> a  # The value of a is changed.
8
'>>>
The value of a is changed. . . *maybe*.
The Python language definition states explicitly that updates to the dictionary 
returned by locals() may not actually alter the local variables.

Generally, altering the contents of the dicts returned by locals() and globals() 
is unreliable at best.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: [BUG] IMO, but no opinions? Uncle Tim? was: int(float(sys.maxint)) buglet ?

2004-12-08 Thread Nick Coghlan
In the absence of identifying an actual problem this would solve, I
would oppose adding *gratuitous* complication.  Abusing your sense of
aesthetics isn't "an actual problem" in this sense to me, although it
may be to you.  Of course you're welcome to make any code changes you
like in your own copy of Python .
.>>> _int = int
.>>> def int(*args): return _int(_int(*args))

.>>> from sys import maxint
.>>> int(maxint)
.2147483647
.>>> int(-maxint-1)
.-2147483648
Pretty! };>
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Quixote+Nevow+LivePage

2004-12-08 Thread mirnazim

[EMAIL PROTECTED] wrote:
> I am really sorry if i sounded a bit bad, i did not mean that.
> what i meant was that , i got my answer to Q2 that livepage is for
> twisted only. but Q1 and Q2 still stand.
>
> I m sorry again.

comp.lang.python is a wonderful community.
Most tolerant community.
Most humble community.
Most helpfull communit.

.

.
I m out of words.

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


Re: cookie lib policy how-tp?

2004-12-08 Thread Marc Christiansen
Riko Wichmann <[EMAIL PROTECTED]> wrote:
>>>Tried that already. At least, I hope I guessed at least one of the 
>>>possible identifiers correct: MSIE6.0, MSIE 6.0, MSIE/6.0
>> 
>> 
>> When my opera is set to identify as MSIE, it sends
>>  "Mozilla/4.0 (compatible; MSIE 6.0; X11; Linux i686) Opera 7.54  [en]".
> 
> Hi Marc,
> 
> thanks for the hint! that brought me a big step forward!

You're welcome :)
  Marc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unknown locale nb_NO ?

2004-12-08 Thread StasZ
On Wed, 08 Dec 2004 10:31:31 +0300, Denis S. Otkidach wrote:

> On Tue, 07 Dec 2004 17:06:12 +0100
> Stas Z <[EMAIL PROTECTED]> wrote:
> 
>> When I 'googled' for it, I saw that no_NO has become nn_NO/nb_NO.
>> However it strikes me as odd, that Python2.3.4 raises an exception when
>> querying for a valid locale. I tend to call it a bug :-(
> 
> Is it valid?  Have you tried "locale -a | grep nb_NO"?
It's valid, but I filed it as a bug and it started a small discussion here:
https://sourceforge.net/tracker/index.php?func=detail&aid=1080864&group_id=5470&atid=105470

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


new comp.lang.python mirror at lampfroums.org--any Linux, Apache, MYSQL, Python Apps?

2004-12-08 Thread astro

Hello all,
We have set up new linux, apache, mysql, python, perl, and php forums
at http://lampforums.org .

comp.lang.python is at: http://lampforums.org/forumdisplay.php?f=18

The interface allows your posts to appear immediately on the forums,
and also to private message other users.

Your posts will appear on the usenet too.

We've also started a number of forums devoted to popular LAMP
applications such as oscommerce, cafelog, postnuke, phpnuke, gallery,
coppermine, and more, for which there aren't any specific usenet
groups.

I've used a few python applications, but what are the most popular LAMP
(Python) CMS's?

Please let us know if you'd like to see any more forums.

The LAMP forums include:

alt.apache.configuration
comp.lang.perl.misc
comp.lang.php
comp.lang.python
comp.os.linux.hardware
comp.os.linux.misc
comp.os.linux.networking
comp.os.linux.setup
mailing.database.mysql

The LAMP application forums include:

LAMP Open Source Portals
Drupal Geeklog Mambo Open Source PHP-Nuke phpWCMS phpWebS

Open Source LAMP Content Management Systems
CMS, Postnuke, PHPnuke, Drupal, Mambo

Open Source LAMP Ecommerce
Oscommerce, Zen Cart, CubeCart

Open Source LAMP Wiki
phpwiki, tikiwiki.org

LAMP Open Source Photo Management
Gallery, Coppermine

Open Source LAMP Mailing Lists
phplist

Open Source LAMP Blogs
b2evolution Nucleus pMachine Free WordPres

Open Source LAMP Forums / Bulletin Boards: phpBB2, SMF, phorum
phpBB2 SMF phorum

LAMP Open Source CMS Polls: Advanced Poll , phpESP, PHPSurveyor
Advanced Poll phpESP PHPSurveyor

Please let us know what other forums/features you would like to see at
http://lampforums.org .

[EMAIL PROTECTED]


-- 
astro

astro's Profile: http://lampforums.org/member.php?userid=1
View this thread: http://lampforums.org/showthread.php?t=92951

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


Re: spawn or fork

2004-12-08 Thread Eric Brunel
C Gillespie wrote:
Dear All,
I have a function
def printHello():
fp = open('file','w')
fp.write('hello')
fp.close()
I would like to call that function using spawn or fork. My questions are:
1. Which should I use
2. How do I call that function if it is defined in the same file.
spawn execute an external executable program *outside* your current script, 
*not* a Python function. So say you want to run wordpad.exe from your Python 
script, you could do:

os.spawn(os.P_NOWAIT, "C:\\Program files\\Accesories\\wordpad.exe, [...])
So you *need* an external executable to be passed to spawn.
fork works another way: it duplicates the context of your process in another one 
and continues both processes in parallel. So basically, it doesn't *execute* 
anything, but just creates a process. You may then call your function is the new 
process (a.k.a the "child" process):

def printHello():
  ...
if os.fork() == 0:
  ## fork returns 0 in the process copy => this is where we call our function
  printHello()
else:
  ## If fork doesn't return 0, we're in the original => other code
  ...
However, fork is only available on Unices.
What are you trying to do exactly? If you provide more explanations, we may 
provide a better help than the simplistic one above.

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: PIL for Windows for Python 2.4

2004-12-08 Thread Scott F
Peter Hansen <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Actually, you're just seeing the repr() of the filename.
> You really are missing that file in the place where it's
> looking.  
> 
> -Peter
> 


Give the man a beer!  Thanks.  I had   ImConfig.h.win   so I changed 
setup.py to that and off we go.

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


problem with win32file.RemoveDirectory

2004-12-08 Thread me
Hello python world.
Since yesterday I'm using Python 2.4/PythonWin (build 203) on my Win98 
system.
My problem - that did not occured in the previous version Python 
2.3.4/PythonWin (build 163) - is the following:

The command i. e. 'win32file.RemoveDirectory("C:\\Python 2.4\\folder")' 
causes the error message:

Traceback (most recent call last):
  File "C:\Python24\remove.py", line 2, in ?
win32file.RemoveDirectory('C:\\Python24\\folder')
error: (120, 'RemoveDirectoryW', 'This function is only valid in Win32 
mode.')

The new documentation tells me that RemoveDirectory "is implemented 
using RemoveDirectoryW."
Does that mean a "NT/2000 Unicode specific version" and the 
impossibility using this function on Win98?

Thanks for your help,
Johannes
--
http://mail.python.org/mailman/listinfo/python-list


Re: How is Python designed?

2004-12-08 Thread Diez B. Roggisch
> Of course for such simple expression, that function
> will not run recursively, but for more complex
> expressions, it will, as a example:
>  a + b * ( c + ( d - e ) / f )...

No, it won't. You seem to not properly understand what recursion is, and
confuse it with overloaded methods. The compute-method of an expression ast
node is called once for every node - to yield its value. Not more - not
less. The fact for 

a * b

the compute methods of objects representing the variables a and b is called
inside a binary operator object neither makes it recursive nor costs more
time.

So there are three compute calls - first on the *-Operator object, then on a
and b.

Using depth-first-search, there are three calls of compute - first on a, b,
then on *.

So three compute calls in both cases. As I said before: No reason not to do
depth-first, if it suits your needs. But it won't buy you anything.

-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spawn or fork

2004-12-08 Thread Diez B. Roggisch
> Thanks, but can I call it using spawn?

No, but you can spawn a python interpreter that calls it. Like this:

spawnv(P_, sys.executable, ['-c', 'import myfile; foo()'])

But I suggest you use fork - then you can call it in the interpreter itself.
-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spawn or fork

2004-12-08 Thread C Gillespie

> What are you trying to do exactly? If you provide more explanations, we
may
> provide a better help than the simplistic one above.
Dear All,

Thanks for the suggestions.

Basically, I have the situation where a user (via the web) requests data
from a database that has to be written to file. However, this takes a couple
of minutes. So the way I thought of doing this is:
1. create an empty file.
2a. tell the user where to look for the file.
2b. spawn a process to insert data into the file.

This way the user can see the data as its being written.

Thanks

Colin


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


Re: creating generators from function

2004-12-08 Thread Simon Wittber
> I'm a little confused as to what you're trying to do here.  The f()
> function, in particular, doesn't make much sense

I see I am misunderstood. The example was contrived, and it seems, incorrect.

I simulate threads, using generator functions and a scheduler.

My implementation lives here: http://metaplay.com.au/svn/LGT/LGT/nanothreads.py

If the same functions were to run inside a normal thread, they would
need to loop forever, rather than yield None on each iteration. I see
now that replacing return with yield won't work, a yield instruction
needs to be inserted somewhere.

I guess this changes my question to: Can I convert a function
containing an infinite loop, into a generator which will yield on each
iteration?

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


Re: creating generators from function

2004-12-08 Thread Timo Virkkala
Simon Wittber wrote:
I guess this changes my question to: Can I convert a function
containing an infinite loop, into a generator which will yield on each
iteration?
Why don't you just use threads? It would probably be easier in the long 
run...
--
Timo Virkkala
--
http://mail.python.org/mailman/listinfo/python-list


Re: deferred decorator

2004-12-08 Thread Bryan
Nick Coghlan wrote:
Bryan wrote:
i'm also curious if it's possible to write this recipe using the new 
class style for the Deffered class.it appears you can nolonger 
delegate all attributes including special methods to the contained 
object by using the __getattr__ or the new __getattribute__ methods.  
does anyone know how to port this recipe to the new class style?

Override __getattribute__. I don't know why you think it doesn't let you 
override all attribute accesses, as that's exactly what it is for.

Cheers,
Nick.
here's an example. __getattribute__ gets called for x but not for the special 
method __add__.  and the __str__ method was found in the base class object which 
printed the memory location, but didn't call __getattribute__.  so 
__getattribute__ cannot be used to capture special methods and delegate them to 
an encapsulated object.   this is why i'm asking what the technique using new 
classes would be for this recipe.

>>> class Foo(object):
... def __getattribute__(self, name):
... raise AttributeError('__getattribute__ is called')
...
>>> f = Foo()
>>> f.x()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in __getattribute__
AttributeError: __getattribute__ is called
>>> f + f
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'Foo' and 'Foo'
>>> str(f)
'<__main__.Foo object at 0x0118AD10>'
--
http://mail.python.org/mailman/listinfo/python-list


Re: How is Python designed?

2004-12-08 Thread Limin Fu
It seems that we focused on different things. I was
talking about the example I have given for arithmetic
evaluation. And you focused the AST-based evaluation,
which, I belive, is different from my example. I also
agree that they called the functions for the same
number of times, the difference is how they are
called.

Resursive function is a function called itself. Am I
wrong? 

I'm sure the code in my example is recursive. As I
have said, you may show those codes I gave as example
to somebody know C++ well to check if it is recursive.

Best regards,

Limin



__ 
Do you Yahoo!? 
Read only the mail you want - Yahoo! Mail SpamGuard. 
http://promotions.yahoo.com/new_mail 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.islink()

2004-12-08 Thread Tim G
You may well be able to do it with the win32file module
functions: GetFileAttributesEx or GetFileInformationByHandle
It's not my area of expertise, but usually a bit of poking around
in msdn.microsoft.com yields some results, as does Googling
around for other people (often VB or Delphi-based) who have
done the same thing.

TJG

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


Re: How do I do this? (eval() on the left hand side)

2004-12-08 Thread Peter Hansen
Nick Coghlan wrote:
Generally, altering the contents of the dicts returned by locals() and 
globals() is unreliable at best.
Nick, could you please comment on why you say this about globals()?
I've never heard of any possibility of "unreliability" in updating
globals() and, as far as I know, a large body of code exists which
does in fact rely on this -- much of mine included. ;-)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: spawn or fork

2004-12-08 Thread Eric Brunel
C Gillespie wrote:
What are you trying to do exactly? If you provide more explanations, we
may
provide a better help than the simplistic one above.
Dear All,
Thanks for the suggestions.
Basically, I have the situation where a user (via the web) requests data
from a database that has to be written to file. However, this takes a couple
of minutes. So the way I thought of doing this is:
1. create an empty file.
2a. tell the user where to look for the file.
2b. spawn a process to insert data into the file.
This way the user can see the data as its being written.
You may want to use threads for this instead of processes. See 
http://docs.python.org/lib/module-threading.html

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help with generators outside of loops.

2004-12-08 Thread Christopher J. Bottaro
Steven Bethard wrote:
> I don't do much with SQL/databases stuff, but if you really know the
> result will be a single row, you can take advantage of tuple unpacking
> and do something like:
> 
> row, = obj.ExecSQLQuery(sql, args)
> 
> or
> 
> [row] = obj.ExecSQLQuery(sql, args)
> 
> This has the advantage that you'll get a ValueError if you happen to be
> wrong (and there are more or fewer values in the generator).
> 
>  >>> def g(n):
> ... for i in range(n):
> ... yield i
> ...
>  >>> x, = g(1)
>  >>> x
> 0
>  >>> x, = g(2)
> Traceback (most recent call last):
>File "", line 1, in ?
> ValueError: too many values to unpack
>  >>> x, = g(0)
> Traceback (most recent call last):
>File "", line 1, in ?
> ValueError: need more than 0 values to unpack
> 
> Steve

Wow, good advice.  One question, how is the generator class implemented so
that if assigned to a tuple/list, it knows what to do?  Is it possible to
overload the assignment operator kinda like in C++?

Thank you all who replied to the original post, it was very helpful.

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


Re: Python 2.3.5 ?

2004-12-08 Thread Stefan Behnel
Stefan
mails!
the way you read
it doesn't reflect
why top-posting is bad:
It's me wrote:
Not to mention that there are packages out there that doesn't work (yet)
with 2.4.  Pynum is one such package.
--
It's me
"Larry Bates" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
Just because 2.4 arrives doesn't mean that ALL work is stopped
on 2.3.  It is quite common to have releases overlap.  The very
newest release is put out (2.4) , but bugs are still being fixed
in older (2.3).
Larry Bates

Luis M. Gonzalez wrote:
I'm confussed...
Python 2.4 (final) hs been released a few days ago, but now I see that
Python 2.3.5 is being worked on.
Why? What does it mean?

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


Re: How is Python designed?

2004-12-08 Thread Diez B. Roggisch
> I'm sure the code in my example is recursive. As I
> have said, you may show those codes I gave as example
> to somebody know C++ well to check if it is recursive.

I just had second thoughts about tree-traversal beeing recursive - and I
have to admit that I'm not entirely sure if I can hold up the statement
that it's not recursive. It might be counted as that, as the strategy of
traversing a tree certainly is of a recursive nature, as its styled
somewhat like this:

def treewalk(node):
for child in node.childs:
treewalk(child)
node.do_something()

So maybe you're right in claiming it beeing recursive. But then,
depth-traversal is recursive, too.

Now apart from that, I still fail to see where your method of evaluation has
any speed gains. 

-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How is Python designed?

2004-12-08 Thread Diez B. Roggisch
> agree that they called the functions for the same
> number of times, the difference is how they are
> called.

What do you mean by difference in calling - a call is a call, no?
-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating generators from function

2004-12-08 Thread Terry Reedy

"Simon Wittber" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I guess this changes my question to: Can I convert a function
> containing an infinite loop, into a generator which will yield on each
> iteration?

A function containing an infinite loop will never return, so it is bugged 
and useless unless it does has an external effect with something like 
'print xxx' within the loop.  Even then, it depends on 'while True:' 
actually meaning 'while '.  The obvious change for a buggy function is to insert a 
yield statement.  For the implicit conditional with print, change 'print' 
to 'yield'.

Note 1. Many algorithm books, especially when using pseudocode, use 'print 
sequence_item' to avoid language specific details of list construction. 
One of the beauties of Python2.2+ is that one can replace simply 'print' 
with 'yield' and have a working algorithm.

Note 2. Delving deep into CPython internals, as you are, is CPython hacking 
rather than Python programming per se. Fun, maybe, but I wonder if this is 
really to best way to do what you want to do.

Terry J. Reedy



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


updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))

2004-12-08 Thread Steven Bethard
Peter Hansen wrote:
Nick Coghlan wrote:
Generally, altering the contents of the dicts returned by locals() and 
globals() is unreliable at best.

Nick, could you please comment on why you say this about globals()?
I've never heard of any possibility of "unreliability" in updating
globals() and, as far as I know, a large body of code exists which
does in fact rely on this -- much of mine included. ;-)
Updating locals() is unreliable.  Updating globals() is fine, AFAIK.
http://docs.python.org/lib/built-in-funcs.html
I believe that the only time that locals() is updatable is when locals() 
is globals():

>>> locals() is globals()
True
>>> x
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'x' is not defined
>>> locals()['x'] = 3
>>> x
3
>>> def f():
... print locals() is globals()
... locals()['x'] = 3
... print x
...
>>> f()
False
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 4, in f
NameError: global name 'x' is not defined
Steve
--
http://mail.python.org/mailman/listinfo/python-list


I need to create the table and I want to edit its content from www level.

2004-12-08 Thread Rootshell
Hello.

I have one more problem with 'tabla.py' file: 
Can't do the compilation 'cause something wrong is happening with module 
'posix'.

The message is as follows: "no module name posix".
I guess that it is necessary to import it.
Unfortunately 'posix' seems to be the unix module and my platform is WinXP.
I'll appreciate any help.

Thank you.

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


Re: Problem while trying to extract a directory from a zipfile.

2004-12-08 Thread vincent wehren
ralobao wrote:
I have this code:
try:
file = zipfile.ZipFile(nome_arquivo)
Gauge.start() #inicia o Gauge
for element in file.namelist():
try:
newFile = open(diretorio + element,"wb")
except:
newFile = open(diretorio + element + '/',"w")
# Gauge
percent = percent + 10
Gauge.update(percent)
Gauge.set_text("Extraindo" + element)
# Extrai
newFile.write(file.read(element))
newFile.close()
But when i try to extract an zipfile with a directory in it the code
returns me an IOErro exception: "It is a directory"
Please how can i solve it ?
You need to create any directories yourself. Maybe
the recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252508
gives you some ideas on how.
HTH
--
Vincent Wehren


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


Re: Help with generators outside of loops.

2004-12-08 Thread Steven Bethard
Christopher J. Bottaro wrote:
Wow, good advice.  One question, how is the generator class implemented so
that if assigned to a tuple/list, it knows what to do?  Is it possible to
overload the assignment operator kinda like in C++?
Tuple unpacking works with generators because generators implement the 
iterator protocol.  Any object that implements the iterator protocol can 
be used in tuple unpacking:

>>> class I(object):
... def __init__(self, n):
... self.n = n
... self.i = -1
... def next(self):
... self.i += 1
... if self.i == self.n:
... raise StopIteration
... return self.i
... def __iter__(self):
... return self
...
>>> x, y, z = I(3)
>>> x, y, z
(0, 1, 2)
So you're not really overloading the assignment operator; you're taking 
advantage of something the assignment operator already does.

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


Re: How is Python designed?

2004-12-08 Thread Limin Fu

> So maybe you're right in claiming it beeing
> recursive. But then,
> depth-traversal is recursive, too.

No, in the depth-traversal implementation, a function
can avoid calling itself (at least in my
implementation it's like this). 

Because you can write seperate functions: a function
for depth-traversal (say trav()) and another function
for evaluation (say eval()). trav() may call eval().
And eval() NEVER call other functions. For one
arithmetic tree, trav() is called once, and eval() is
called by trav() at each node. So it is not recursive.


> Now apart from that, I still fail to see where your
> method of evaluation has
> any speed gains. 

And if you inplement eval() as an "inline" function,
there will be no cost for function calls for eval().
In this way it can gain some speeds.

Best regards,

Limin




__ 
Do you Yahoo!? 
Yahoo! Mail - Easier than ever with enhanced search. Learn more.
http://info.mail.yahoo.com/mail_250
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spawn or fork

2004-12-08 Thread sjdevnull
Eric Brunel wrote:
> > Basically, I have the situation where a user (via the web) requests
data
> > from a database that has to be written to file. However, this takes
a couple
> > of minutes. So the way I thought of doing this is:
> > 1. create an empty file.
> > 2a. tell the user where to look for the file.
> > 2b. spawn a process to insert data into the file.
> >
> > This way the user can see the data as its being written.
>
> You may want to use threads for this instead of processes. See
> http://docs.python.org/lib/module-threading.html

I haven't seen any reason he wants to give up protected memory, so the
only reason to use threads is if the platform doesn't support fork (or
has a broken/nonperformant implementation thereof).

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


Re: I need to create the table and I want to edit its content from www level.

2004-12-08 Thread Gerhard Haering
On Wed, Dec 08, 2004 at 09:03:54AM -0800, Rootshell wrote:
> Hello.
> 
> I have one more problem with 'tabla.py' file: 

We don't know about the files on your harddisk ;-)

> Can't do the compilation 'cause something wrong is happening with
> module 'posix'.

Whoever wrote tabla.py probably didn't read the documentation for the
posix module, which says:

*Do not import this module directly*. Instead, import the module
os, which provides a portable version of this interface.

> The message is as follows: "no module name posix".
> I guess that it is necessary to import it.
> Unfortunately 'posix' seems to be the unix module and my platform is WinXP.
> I'll appreciate any help.

Try replacing posix with os in the source code.

-- Gerhard


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Bug 834351 - Mouse wheel crashes program

2004-12-08 Thread Gary Richardson
Has this bug been fixed in 2.3.5 or 2.4? Does it exist in XP systems?

#-
from Tkinter import *
def _onMouseWheel(event):
print event
root = Tk()
root.bind('',_onMouseWheel)
root.mainloop()



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


Re: 2D array

2004-12-08 Thread Adam DePrince
On Tue, 2004-12-07 at 23:02, Steven Bethard wrote:
> LutherRevisited wrote:
> > I'm wanting to do something with a list that is basically a 2 dimensional
> > array.  I'm not so good with lists so can someone give me an example of how 
> > I
> > might implement this in Python?  thanks.
> 
> If you're planning to do anything serious with a 2D array, you should 
> probably look at numarray:
>  http://www.stsci.edu/resources/software_hardware/numarray
> 
>  >>> import numarray as na
>  >>> arr = na.array(range(10), shape=(5, 2))
>  >>> arr
> array([[0, 1],
> [2, 3],
> [4, 5],
> [6, 7],
> [8, 9]])
>  >>> arr[0,1]
> 1
>  >>> arr[4,0]
> 8
> 
> If you're not doing any heavy computation, you can probably do this with 
> nested lists:
> 
>  >>> arr = [[0, 1],
> ...[2, 3],
> ...[4, 5],
> ...[6, 7],
> ...[8, 9]]
>  >>> arr[0][1]
> 1
>  >>> arr[4][0]
> 8
> 
> Steve

If your data is sparse you might want to consider using a dictionary
where the key is a tuple representing the coordinates.

a = {}
a[(0,0)] = 0
a[(0,1)] = 1
a[(1,0)] = 2
a[(1,1)] = 3
a[(2,0)] = 4
a[(2,1)] = 5
a[(3,0)] = 6
a[(3,1)] = 7
a[(4,0)] = 8
a[(4,1)] = 9

>>> a.get( (3,0), None )
6
>>> print a.get( (5,0), None )
None




Adam DePrince 


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


Re: How is Python designed?

2004-12-08 Thread Diez B. Roggisch
> No, in the depth-traversal implementation, a function
> can avoid calling itself (at least in my
> implementation it's like this).

How so? It has to keep state of which nodes to visit - so instead of calling
trav, you call functions to store and fetch nodes in a container like a
stl-list. That's the same cost, function-call is function call.

There is no difference - you simply decoupled the tree traversal from the
evaluation - but combined, its the same effort. It's like in my second
example with bytecodes - the traversal is done beforehand (and only once),
and then the eval is only done on the nodes in a row.

> Because you can write seperate functions: a function
> for depth-traversal (say trav()) and another function
> for evaluation (say eval()). trav() may call eval().
> And eval() NEVER call other functions. For one
> arithmetic tree, trav() is called once, and eval() is
> called by trav() at each node. So it is not recursive.
>> Now apart from that, I still fail to see where your
>> method of evaluation has
>> any speed gains.
> 
> And if you inplement eval() as an "inline" function,
> there will be no cost for function calls for eval().
> In this way it can gain some speeds.

No. Inlining works only when the actual type of your node is known, e.g.
like this (Constant and Variable are both of type :

{
Constant left;
Variable right;

left.eval();
right.eval();
}

Here the compiler can take advantage from the fact that it knows at
compiletime which eval to inline

But if you have 

{
list nodes;
for(nodes::iterator it = nodes.begin(); it != nodes.end(); it++) {
(*exp).eval();
   }
}

the compiler can't possibly know which node is in exp- so it has to resort
to a vtable-lookup and a method call on the result.

-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Docs. Hardcopy 2.4 Library Reference, interested?

2004-12-08 Thread Brad Clements
Is anyone interested in purchasing a hardcopy version of the Python 2.4
Library reference?

That is, assuming it was NOT  a direct print of current html/pdf versions.

So, nicely formatted for a printed book (spiral bound probably), with
several indexes as appropriate, or perhaps a permutted index.

I'm thinking about doing this through lulu.com or cafepress, but it's going
to take a lot of work to make a really nice printed version of the library
reference from the LaTex source files (even via sgmlconv). Also wondering if
I can get bleeds from either of these sites.

So, before I waste my time. Is anyone interested in such a beast? And if so,
how much would you be willing to spend?

On demand printing still looks expensive to me. :-(

-- 
Novell DeveloperNet Sysop #5

(oh gee, but no NLMs anymore )

_



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


Re: Google's MapReduce

2004-12-08 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> (This Google article suggestion comes from the CleverCS site):
>
> http://labs.google.com/papers/mapreduce-osdi04.pdf
>
> "MapReduce is a programming model and an associated implementation for
> processing and generating large data sets. Users specify a map function
> that processes a key/value pair to generate a set of intermediate
> key/value pairs, and a reduce function that merges all intermediate
> values associated with the same intermediate key."

Summarizing groups (and sometimes simultaneously by subgroups) has been a 
standard operation for decades in both statistics packages and database 
report generators.  Python has various versions of the map and reduce 
operations that they use.  Its dicts can easily be used to group items with 
the same key.  What is somewhat specific to Google is the need to generate 
*multiple* key-value pairs from each input document.  What MapReduce does 
that is somewhat innovative is automatically parallelize the computation to 
run fault-tolerantly on a cluster of up to 1000s of machines with machine 
slowdowns and failures 'common'.  And indeed, that is the reason to use the 
system with trivial map or reduce functions, as they sometimes do.

What this does show is that Google could be regarded as a cluster 
supercomputing company, with Web search as the visible development 
application.

Terry J. Reedy



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


Re: new comp.lang.python mirror at lampfroums.org--any Linux, Apache, MYSQL, Python Apps?

2004-12-08 Thread Terry Reedy

"astro" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> Hello all,
> We have set up new linux, apache, mysql, python, perl, and php forums
> at http://lampforums.org .

Perhaps you could say at the top of that page what LAMP means.
My guess: Linux-Apache-Mysql-Planguage -- but why that particular 
selection?  Just to have a cute acronym?  Why not other open souce 
programs/languages?  If you are successful, you will get visitors who are 
even more puzzled than me.

Terry J. Reedy




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


Re: Recursive list comprehension

2004-12-08 Thread Adam DePrince
On Mon, 2004-12-06 at 10:01, Timothy Babytch wrote:
> Serhiy Storchaka wrote:
> 
>  >>>sum([['N', 'F'], ['E'], ['D']], [])
> ['N', 'F', 'E', 'D']
> 
> THE BEST!
> 
> -- 
> Timothy Babytch, PHP-dev Teamleader

Sum certainly takes the cake for hackish elegance, and would be my
choice if I was absolutely certain that my data structure was exactly a 
list of lists.   A more general solution with applicability to arbitrary
levels of nesting is below.

a = [['N','F'],['E'],['D']]
b = [[['A','B',['C','D']],'N','F'],'E', ['F'] ]
c = iter([[iter(['A','B',('C','D')]),'N','F'],'E', iter(['F']) ])

def flatten( i ):
try:
i = i.__iter__()
while 1:
j = flatten( i.next() )
try:
while 1:
yield j.next()
except StopIteration:
pass
except AttributeError:
yield i

if __name__ == "__main__":
print list( flatten( a ) )
print list( flatten( b ) )
print list( flatten( c ) )

Which when run gives you ... 

['N', 'F', 'E', 'D']
['A', 'B', 'C', 'D', 'N', 'F', 'E', 'F']
['A', 'B', 'C', 'D', 'N', 'F', 'E', 'F']


Adam DePrince

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


Re: after embedding and extending python (using swig) problem importing (non-core) modules

2004-12-08 Thread stefan
thanks a lot for the quick answer.

I had to provide the debug-versions, since I was in debug mode, like
you already expected! thanks a lot again!

-stefan

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


Re: HTML Structure Extraction

2004-12-08 Thread Fredrik Lundh
<[EMAIL PROTECTED]> wrote:

> I'm going to write a program that extracts the structure of HTML
> documents. The structure would be in the form of a tree, separating the
> tags and grouping the start and end tags. I think I will use
> htmllib.HTMLParser, is it appropriate for my application? If so, I
> believe I will need to keep track of the depth reached.

you mean like:

http://www.crummy.com/software/BeautifulSoup/
http://effbot.org/zone/element-tidylib.htm
http://utidylib.berlios.de/
http://www.xmlsoft.org/
http://effbot.org/zone/pythondoc-elementtree-HTMLTreeBuilder.htm

and a few dozen others?

 



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


Re: How is Python designed?

2004-12-08 Thread Limin Fu
I think code says thing clearer, here I pasted
a simplified version of my implementation with
depth-tranverse. Note: this simplified version cannot
handle unary computation. To read the real version,
please read one source file of Yuan at:
http://cvs.sourceforge.net/viewcvs.py/yuan-language/yuan_devel/source/yn_expression.cpp?view=markup

I just mention a few points in the following codes:
1. evaluation is done during traverse.
2. no need to store "node"s or temporary variables in
a list/queue/stack.
3. when eval() is called, it knows the exact type of
the object.

class node{
  // booleans to tell the type of node:
  bool isVariable,isSomethingElse; 

  char oper; // operator
  double  value; // temporary value
  something *tempVarForSomething;

  node *left,*right; // pointers to its sons
  node *parent;  // pointer to its parent
 
  void eval();
  void trav();
};

void node::eval()
{
   if(oper=='+')
 value=left->value+right->value;
   else if 
}
void node::trav()
{
   node *p=this;
   while(1){
  // go along "right" to reach a leaf:
  while(p->right) p=p->right;

  if(p->isVariable){
 // get the value:
 p->value=...;
  }else if(p->isSomethingElse){
 // do something else
  }

  if(!p->parent) break;

  // if "p" is a "left" son:
  if(p==p->parent->left){
 // go back to "parent"
 p=p->parent;

 // evaluation:
 p->eval();

 if(p==this) break;
  }
  if(p==this) break;
  // Now "p" must be a "right" son,
  // jump to the "left"
  p=p->parent->left;
   }
}

--- "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

> > No, in the depth-traversal implementation, a
> function
> > can avoid calling itself (at least in my
> > implementation it's like this).
> 
> How so? It has to keep state of which nodes to visit
> - so instead of calling
> trav, you call functions to store and fetch nodes in
> a container like a
> stl-list. That's the same cost, function-call is
> function call.
> 
> There is no difference - you simply decoupled the
> tree traversal from the
> evaluation - but combined, its the same effort. It's
> like in my second
> example with bytecodes - the traversal is done
> beforehand (and only once),
> and then the eval is only done on the nodes in a
> row.
> 
> > Because you can write seperate functions: a
> function
> > for depth-traversal (say trav()) and another
> function
> > for evaluation (say eval()). trav() may call
> eval().
> > And eval() NEVER call other functions. For one
> > arithmetic tree, trav() is called once, and eval()
> is
> > called by trav() at each node. So it is not
> recursive.
> >> Now apart from that, I still fail to see where
> your
> >> method of evaluation has
> >> any speed gains.
> > 
> > And if you inplement eval() as an "inline"
> function,
> > there will be no cost for function calls for
> eval().
> > In this way it can gain some speeds.
> 
> No. Inlining works only when the actual type of your
> node is known, e.g.
> like this (Constant and Variable are both of type :
> 
> {
> Constant left;
> Variable right;
> 
> left.eval();
> right.eval();
> }
> 
> Here the compiler can take advantage from the fact
> that it knows at
> compiletime which eval to inline
> 
> But if you have 
> 
> {
> list nodes;
> for(nodes::iterator it = nodes.begin(); it !=
> nodes.end(); it++) {
> (*exp).eval();
>}
> }
> 
> the compiler can't possibly know which node is in
> exp- so it has to resort
> to a vtable-lookup and a method call on the result.
> 
> -- 
> Regards,
> 
> Diez B. Roggisch
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 




__ 
Do you Yahoo!? 
Yahoo! Mail - Easier than ever with enhanced search. Learn more.
http://info.mail.yahoo.com/mail_250
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with generators outside of loops.

2004-12-08 Thread David Eppstein
In article <[EMAIL PROTECTED]>,
 Andrea Griffini <[EMAIL PROTECTED]> wrote:

> Isn't the handling of StopIteration confined in the very moment of
> calling .next() ? This was what I expected... and from a simple test
> looks also what is happening...

Not if someone farther back in the call chain is looking for 
StopIteration.  Which could be the case if the call chain includes a 
for-loop that is calling the next() method of another generator.

-- 
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: guarding for StopIteration (WAS: Help with generators outside of loops.)

2004-12-08 Thread David Eppstein
In article <[EMAIL PROTECTED]>,
 Steven Bethard <[EMAIL PROTECTED]> wrote:

> David Eppstein wrote:
> > I've made it a policy in my own code to always surround explicit calls 
> > to next() with try ... except StopIteration ... guards.
> > 
> > Otherwise if you don't guard the call and you get an unexpected 
> > exception from the next(), within a call chain that includes a for-loop 
> > over another generator, then that other for-loop will terminate without 
> > any error messages and the cause of its termination can be very 
> > difficult to track down.
> 
> Just to clarify here, the only time code raising a StopIteration will 
> cause a for-loop to exit silently is if the StopIteration is raised in 
> an __iter__ method, e.g.:

Sure.  But in the situation I was attempting to describe, the __iter__ 
method calls the code of the outer generator, which (perhaps nested 
several levels deep) may call an inner generator.  In this case, the 
inner generator's StopIteration can terminate the outer loop.

-- 
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ming for python

2004-12-08 Thread Jack Diederich
On Tue, Dec 07, 2004 at 07:55:09PM +0100, titouille wrote:
> Hello everybody !!
> 
> anyone has try to build ming0.3beta1 for python 2.3.3 under windows ??
> 
> Since three days, I try to build it with mingw32, and finally, I am 
> stopped with C declarations error in src/actioncompiler/swf4compiler.y
> 

I haven't tried under windows, but here is how I got it to compile
under linux.  Below is my setup.py

-Jack

"""
This is the setup.py for ming-0.3beta1
Do the normal ming compile and then remove all the .o files
copy this file to py_ext/
and run as a normal python instal, eg 'python setup.py install'
Keep copying header files into this directory until it doesn't complain
Done!
"""

files = []
dirs = ['../src/', '../src/blocks/', '../src/actioncompiler']
ignore = ['read.c', 'main.c']
for (dir) in dirs:
  for (file) in os.listdir(dir):
if (file.endswith('.c') and file not in ignore):
  files.append('%s/%s' % (dir, file))

files.append('ming_wrap.c')
setup(name="ming",
  py_modules=["ming", 'mingc'],
  ext_modules=[Extension(name="_mingc",
 sources=files,
 libraries=['gif', 'png', 'z'],
 include_dirs=dirs,
)]
 )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sys.stdin.read question

2004-12-08 Thread Caleb Hattingh
I don't have much experience with popen3.  I do know that IDLE  
(interactive interpreter) does something to sys.stdin, and that is  
probably the problem you are seeing.  Try your commands through the python  
interactive interpreter started from a shell (DOS or Bash), see if it  
still happens.

thx
Caleb
On Tue, 7 Dec 2004 23:16:50 +0100, Lars Tengnagel <[EMAIL PROTECTED]> wrote:
Hej Caleb and others
I've been strugling with the same problem where i try to use popen3 to  
run a
program. If I use a piped commandline
the program can read the file without problems but in the IDLE and with
popen it comes with an error.
I haven't been able to read the stdin either so the problem so far is
unsolved for my point.
But the newline command would explain my problems with the program.
Can it be a problem under windows since I'm using XP and the winpython

Hopefully Lars
"Caleb Hattingh" <[EMAIL PROTECTED]> skrev i en meddelelse
news:[EMAIL PROTECTED]
It runs properly in a shell (bash), but on another matter:
'>>> r=sys.stdin.read(1)
g
'>>> r
'g'
'>>> r=sys.stdin.read(5)
1234567890
'>>> r
'\n1234'
'>>>
What exactly happened to my 1234567890?  I understand that I am only
taking 5 characters, but where does the newline (\n) come from?  Is  
that a
remnant from when I terminated the previous 'g' input?

Thanks
Caleb
On Tue, 07 Dec 2004 23:36:56 -0500, Caleb Hattingh <[EMAIL PROTECTED]>
wrote:
Hi
You are probably typing this within IDLE.  Try it after starting python
in a shell like DOS or Bash.  Should work then (works for me, and I  
also
get the AttributeError in IDLE.

Thanks
Caleb
On Tue, 07 Dec 2004 21:15:51 GMT, It's me <[EMAIL PROTECTED]> wrote:
Why do I get an "AttributeError: read" message when I do:
import sys
r=sys.stdin.read()
??
I've tried:
r=sys.stdin.read(80)
r=sys.stdin.read(1)
same error message.
I couldn't find any reference to this function in my Python book (they
have
the stdout but not in).
Some sample code I saw uses this function in the same manner I am and
so I
am assuming this is the correct syntax?
Or is this a bug in Python 2.4?
--
It's me




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


Re: How do I do this? (eval() on the left hand side)

2004-12-08 Thread Caleb Hattingh
Peter, I second that.
Nick
In what way is it unreliable?  I can't seem to create a situation where  
the update through globals and locals doesn't work.   Are you referring  
perhaps to the possibility of variables being garbage collected and then  
not being around later when one tries to access them through a string  
name?  I don't know very much about the garbage collector, so I can't say  
for sure.

thx
Caleb
On Wed, 08 Dec 2004 10:38:30 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote:
Nick Coghlan wrote:
Generally, altering the contents of the dicts returned by locals() and  
globals() is unreliable at best.
Nick, could you please comment on why you say this about globals()?
I've never heard of any possibility of "unreliability" in updating
globals() and, as far as I know, a large body of code exists which
does in fact rely on this -- much of mine included. ;-)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting in huge files

2004-12-08 Thread Adam DePrince
On Tue, 2004-12-07 at 16:47, Paul wrote:
> I really do need to sort. It is complicated and I haven't said why, but
> it will help in finding similar keys later on. Sorry I can't be more
> precise, this has to do with my research.

Precision is precisely what we require to give you an answer more
meaningful than "write a script to load it into your favorite database
and type 'select * from table order by column;' "  

Now unless you have an NDA with an employer or are working on something
classified, (in which case you have already given us too much
information and should start looking for another job and lawyer) I would
venture a guess that you have more to gain than lose from giving us more
information.  Decisions are hard sometimes ... is the help worth the
risk that somebody in this forum will look at your question, say "hey
that is a neat idea," duplicate all of your research and publish before
you shaming you to a life of asking "do you want fries with that" and
pumping gas.  

> 
> Your two other suggestions with itertools and operator are more useful,
> but I was mostly wondering about performance issue.

What performance issue?  Nowadays any decent laptop should be able to
handle this dataset (from disk) without too much trouble. 

c = make_a_cursor_for_my_favoriate_database()
f = open( "mydata" )
for line in f.xreadlines():
c.execute( "insert into table( fields) values (%s,%s ... )",
line.split() )
c.commit()
print "I'm done loading, feel free to hit control+C if you get tired"
c.execute( "select * from table order by field" )
while 1:
print c.fetchone()

Then, from your shell:

myloadscript.py | gzip -9 > results.txt 

Start it up Friday night and take the weekend off.  Just make sure you
plug your laptop into the wall before you go home.

> 
> Is this reasonnable to do on 10^8 elements with repeats in the keys? I
> guess I should just try and see for myself.

Repeats in the keys don't matter.  


Adam DePrince 


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


Re: How do I do this? (eval() on the left hand side)

2004-12-08 Thread Peter Otten
Caleb Hattingh wrote:

> In what way is it unreliable?  I can't seem to create a situation where
> the update through globals and locals doesn't work.   Are you referring

Updates to a locals() dictionary may not be reflected by the variables in
the local scope, e. g.:

>>> def f():
... locals()["a"] = 1
... print a
...
>>> f()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in f
NameError: global name 'a' is not defined
>>> def f():
... a = 42
... locals()["a"] = 1
... print a
...
>>> f()
42

Updating globals() should be safe.
 
Peter

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


Re: updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))

2004-12-08 Thread Caleb Hattingh
Steve,
I don't think I understand.  Here is what I just tried:
'>>> def f():
x = 3
d = locals()
print x
print d['x']
d['x'] = 5
print x

'>>> f()
3
3
3
'>>>
In your example, x had not yet been initialised, maybe.  What I am seeing  
is that "x" does not seem to update when being assigned to - I guess this  
is what you are referring to by being unreliable.

But "unreliable" sounds kinda vague and intermittent, and I assume that is  
not the case here - What is the Rule(tm)?

Thanks
Caleb

On Wed, 08 Dec 2004 16:59:23 GMT, Steven Bethard  
<[EMAIL PROTECTED]> wrote:

Peter Hansen wrote:
Nick Coghlan wrote:
Generally, altering the contents of the dicts returned by locals() and  
globals() is unreliable at best.
  Nick, could you please comment on why you say this about globals()?
I've never heard of any possibility of "unreliability" in updating
globals() and, as far as I know, a large body of code exists which
does in fact rely on this -- much of mine included. ;-)
Updating locals() is unreliable.  Updating globals() is fine, AFAIK.
http://docs.python.org/lib/built-in-funcs.html
I believe that the only time that locals() is updatable is when locals()  
is globals():

 >>> locals() is globals()
True
 >>> x
Traceback (most recent call last):
   File "", line 1, in ?
NameError: name 'x' is not defined
 >>> locals()['x'] = 3
 >>> x
3
 >>> def f():
... print locals() is globals()
... locals()['x'] = 3
... print x
...
 >>> f()
False
Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 4, in f
NameError: global name 'x' is not defined
Steve
--
http://mail.python.org/mailman/listinfo/python-list


MP3 - VBR - Frame length in time

2004-12-08 Thread Ivo Woltring
Dear Pythoneers,

I have this problem with the time calculations of an VBR (variable bit rate)
encoded MP3.
I want to make a daisy writer for blind people. To do this I have to know
exactly what the length in time of an mp3 is. With CBR encoded files I have
no real problems (at least with version 1 and 2), but with VBR encoded I get
into trouble.
I noticed that players like WinAMP and Windows Media player have this
problem too.
I don't mind to have to read the whole mp3 to calculate, because performance
is not a real issue with my app.

Can anyone help me? I am really interested in technical information on VBR
and MP3.
Can anybody tell me the length in time of the different bitrates in all the
versions of mp3 and all the layers.

Tooling or links also really welcome. My own googling has helped me some but
on the subject of VBR I get stuck.

Thanks a lot,
Ivo.


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


Re: new comp.lang.python mirror at lampfroums.org--any Linux, Apache, MYSQL, Python Apps?

2004-12-08 Thread astro

The top of the page at http://lampforums.org has a few places where LAMP
is spelled out as Linux, Apache, MYSQL, and PHP/Perl/Python.

I could make it more clear, I suppose--any suggestions as to how to
word it would be great!

The LAMP acronym has been around for awhile--I think there are even a
few books with LAMP in the title.

I think that most people on here knows what it stands for, but I could
be wrong.

Thanks for the feedback!

And any feedback on specific the re-wording of the page would be
great.

Also, what are everyone's favorite python applications for content
management/blogging/etc?

Best,

Elliot


-- 
astro

astro's Profile: http://lampforums.org/member.php?userid=1
View this thread: http://lampforums.org/showthread.php?t=92951

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


Re: Recursive list comprehension

2004-12-08 Thread Steven Bethard
Adam DePrince wrote:
def flatten( i ):
try:
i = i.__iter__()
while 1:
j = flatten( i.next() )
try:
while 1:
yield j.next()
except StopIteration:
pass
except AttributeError:
yield i

Probably you want to catch a TypeError instead of an AttributeError; 
objects may support the iterator protocol without defining an __iter__ 
method:

>>> class C:
... def __getitem__(self, index):
... if index > 3:
... raise IndexError(index)
... return index
...
>>> list(iter(C()))
[0, 1, 2, 3]
I would write your code as something like:
>>> def flatten(i):
... try:
... if isinstance(i, basestring):
... raise TypeError('strings are atomic')
... iterable = iter(i)
... except TypeError:
... yield i
... else:
... for item in iterable:
... for sub_item in flatten(item):
... yield sub_item
...
>>> list(flatten([['N','F'],['E'],['D']]))
['N', 'F', 'E', 'D']
>>> list(flatten([C(), 'A', 'B', ['C', C()]]))
[0, 1, 2, 3, 'A', 'B', 'C', 0, 1, 2, 3]
Note that I special-case strings because, while strings support the 
iterator protocol, in this case we want to consider them 'atomic'.  By 
catching the TypeError instead of an AttributeError, I can support 
old-style iterators as well.

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


Re: 2D array

2004-12-08 Thread Steven Bethard
Adam DePrince wrote:
If your data is sparse you might want to consider using a dictionary
where the key is a tuple representing the coordinates.
a = {}
a[(0,0)] = 0
a[(0,1)] = 1
[snip]
print a.get( (5,0), None )
Good point.  Note that you don't need the parentheses in the assignments 
or item accesses:

>>> a = {}
>>> a[0,0] = 10
>>> a[0,0]
10
Also note that you don't need to specify None as the default value when 
you call dict.get -- None is assumed if no default value is supplied:

>>> print a.get((5, 2))
None
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))

2004-12-08 Thread Steven Bethard
Caleb Hattingh wrote:
Steve,
I don't think I understand.  Here is what I just tried:
'>>> def f():
x = 3
d = locals()
print x
print d['x']
d['x'] = 5
print x

'>>> f()
3
3
3
'>>>

In your example, x had not yet been initialised, maybe.  What I am 
seeing  is that "x" does not seem to update when being assigned to - I 
guess this  is what you are referring to by being unreliable.
Yes, that was my intent.  In the same way that my "x" was not 
initialized, your "x" is not updated.  locals() is readable but not 
writable in any case where locals() is not globals(), I believe.

But "unreliable" sounds kinda vague and intermittent, and I assume that 
is  not the case here - What is the Rule(tm)?
Unfortunately, I don't think there is a Rule(tm) because the behavior of 
locals() (and globals()?) are implementation details.  I remember 
hearing an explanation of why locals() is not writable that had to do 
with something about efficiency and the call stack (or something like 
that)...

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


Re: Recursive list comprehension

2004-12-08 Thread Peter Otten
Adam DePrince wrote:

> def flatten( i ):
> try:
> i = i.__iter__()
> while 1:
> j = flatten( i.next() )
> try:
> while 1:
> yield j.next()
> except StopIteration:
> pass
> except AttributeError:
> yield i

While trying to break your code with a len() > 1 string I noted that strings
don't feature an __iter__ attribute. Therefore obj.__iter__() is not
equivalent to iter(obj) for strings. Do you (plural) know whether this is a
CPython implementation accident or can be relied upon?

Peter

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


jython and swing

2004-12-08 Thread Nandan
hello, can I ask a jython question here?

when I use the jython interpreter I have no problem with the statement:

from java import lang
from javax import swing

but when I put this in a script, I get a package not found error.
what am I doing wrong?

the script header is #!/bin/env jython
 
--
Nandan Bagchee
Ohio State University
[EMAIL PROTECTED]

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


Re: How do I do this? (eval() on the left hand side)

2004-12-08 Thread Caleb Hattingh
Thx Peter
I verified this situation myself with a post from Steven Bethard earlier  
(trying to use "locals" within a function definition).

I am convinced now that locals() doesn't work as (I) expected.  Steven  
says there was some or other reason why locals() as used in this context  
is not writable - Do you know why this is?  I really do not like  
guidelines like "may not work", "is unreliable" and so on.  Perhaps this  
is a character flaw, but I really do like to know what works, when it  
works, and when it doesn't work.

In this scenario, we can see it doesn't work.  To my eyes, it doesn't work  
*in the way I expect* (which is highly subjective, no argument there).   
Would this be a situation where it would be nice to have an exception  
thrown if locals() is assigned to in a scope where it is not writable?

It would also be nice if globals and locals behaved the same, differing  
only in scope (which is what I expected originally anyway).  But we can't  
have everything, I guess :)

Caleb
On Wed, 08 Dec 2004 20:49:53 +0100, Peter Otten <[EMAIL PROTECTED]> wrote:
Caleb Hattingh wrote:
In what way is it  
unreliable?ÃÂÃÂIÃÂcan'tÃÂseemÃÂtoÃÂcreateÃÂaÃÂsituationÃÂwhere
the update through globals and locals doesn't  
work.ÃÂÃÂÃÂAreÃÂyouÃÂreferring
Updates to a locals() dictionary may not be reflected by the variables in
the local scope, e. g.:
def f():
... locals()["a"] = 1
... print a
...
f()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in f
NameError: global name 'a' is not defined
def f():
... a = 42
... locals()["a"] = 1
... print a
...
f()
42
Updating globals() should be safe.
Peter
--
http://mail.python.org/mailman/listinfo/python-list


Multiple concurrent telnet sessions

2004-12-08 Thread Tony Pryor
Hello,

Anyone know if running two client telnet sessions at the same time
should be an inherent problem? They don't seem to want to share a port
or are they trying to use the same console for interaction with the
connected servers?

-Tony

Hello from parent loop 1   ipaddress1 
Hello from parent loop 2   ipaddress2 
Hello from thread 1
Hello from thread 2
Unhandled exception in thread started by >
Unhandled exception in thread started by >
Traceback (most recent call last):
  File "telmt.py", line 34, in ?
time.sleep(60)


import thread, sys, time, telnetlib

def child(tid,ip):
print 'Hello from thread', tid
tn = telnetlib.Telnet()
tn.mt_interact()
tn.open(ip, 10001)
def clear(tn):
tn.write("AT")
tn.expect("OK")
tn.write("ATMC")
tn.expect("OK")
tn.expect("ATUCL")
tn.expect("OK")
clear(tn)
time.sleep(1)
tn.write("ATDI,15,")
(unparsed, ack) = expect("DONE")
print unparsed
time.sleep(1)
clear(tn)

def parent(iplist):
i = 0
for ip in iplist:
i = i+1
tuple = (i, ip,)
thread.start_new_thread(child, tuple)
print 'Hello from parent loop', i, ' ', ip
   
iplist = ["ip.ad.dr.1", "ip.ad.dr.2"]
parent(iplist)
time.sleep(60)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive list comprehension

2004-12-08 Thread Nick Craig-Wood
Adam DePrince <[EMAIL PROTECTED]> wrote:
>  def flatten( i ):
>  try:
>  i = i.__iter__()
>  while 1:
>  j = flatten( i.next() )
>  try:
>  while 1:
>  yield j.next()
>  except StopIteration:
>  pass
>  except AttributeError:
>  yield i

Hmm, there is more to that than meets the eye!  I was expecting

  print list(flatten("hello"))

to print

  ['h', 'e', 'l', 'l', 'o']

But it didn't, it printed

  ['hello']

With a little more investigation I see that str has no __iter__
method.  However you can call iter() on a str

>>> for c in iter("hello"): print c
... 
h
e
l
l
o

Or even

>>> for c in "hello": print c
... 
h
e
l
l
o

...and this works because str supports __getitem__ according to the
docs.

So there is some magic going on here!  Is str defined to never have an
__iter__ method?  I see no reason why that it couldn't one day have an
__iter__ method though.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: mkplaylist.py 0.3

2004-12-08 Thread Marc 'BlackJack' Rintsch
Hi,

Hereby I'm announcing the first version of my playlist generating
Python script that not only replaces the functionality of the simple
Bash script I used to create playlists beforem but also reads meta data
(tags, comments) from MP3 and Ogg Vorbis files and writes extended M3U
playlists.

The script scans given directories for media files with known file
name extensions and writes the file names into a playlist file in M3U or
extended M3U format. Those very simple formats are used or at least
understood by the vast majority of media players on different
platforms.

For reading meta data some third party software is needed.  Namely the
mad mp3 decoder and the Python bindings for it

  http://www.underbit.com/products/mad/
  http://spacepants.org/src/pymad/

the ID3 tag reader from

  http://id3-py.sourceforge.net/

and the Ogg Vorbis Python bindings by Andrew Chatham

  http://www.andrewchatham.com/pyogg

It's "beta quality" software and only tested on Linux, so I'm
interested in positive/negative feedback and bug reports.

You can find the script here:

  http://www.marc.rintsch.de/software.html#mkplaylist


Ciao,
Marc 'BlackJack' Rintsch

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


Re: Recursive list comprehension

2004-12-08 Thread Steven Bethard
Peter Otten wrote:
I noted that strings
don't feature an __iter__ attribute. Therefore obj.__iter__() is not
equivalent to iter(obj) for strings. Do you (plural) know whether this is a
CPython implementation accident or can be relied upon?
Nick Craig-Wood wrote:
> With a little more investigation I see that str has no __iter__
> method.  However you can call iter() on a str
[snip]
> ...and this works because str supports __getitem__ according to the
> docs.
>
> So there is some magic going on here!  Is str defined to never have an
> __iter__ method?  I see no reason why that it couldn't one day have an
> __iter__ method though.
The magic is the old-style iteration protocol (also called the 'sequence 
protocol') which calls __getitem__ starting at 0 until an IndexError is 
raised.  From the docs:

http://www.python.org/doc/lib/built-in-funcs.html
iter(  	o[, sentinel])
Return an iterator object. The first argument is interpreted very 
differently depending on the presence of the second argument. Without a 
second argument, o must be a collection object which supports the 
iteration protocol (the __iter__() method), or it must support the 
sequence protocol (the __getitem__() method with integer arguments 
starting at 0). If it does not support either of those protocols, 
TypeError is raised...

I looked around to see if there was any talk specifically of str and 
__iter__/__getitem__ and couldn't find any.  (Though I wouldn't claim 
that this means it's not out there.) ;)  My guess is that there isn't 
any guarantee that str objects might not one day grow an __iter__ 
method, so I wouldn't rely on it.

See my other post that uses iter() and TypeError instead of .__iter__() 
and AttributeError -- it's relatively simple to avoid relying on 
.__iter__, and doing so also allows you to support other objects that 
support the sequence protocol but have no __iter__ method.

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


Re: Python Docs. Hardcopy 2.4 Library Reference, interested?

2004-12-08 Thread Paul Rubin
"Brad Clements" <[EMAIL PROTECTED]> writes:
> Is anyone interested in purchasing a hardcopy version of the Python 2.4
> Library reference?
> 
> That is, assuming it was NOT  a direct print of current html/pdf versions.
> 
> So, nicely formatted for a printed book (spiral bound probably), with
> several indexes as appropriate, or perhaps a permutted index.
> 
> I'm thinking about doing this through lulu.com or cafepress, but it's going
> to take a lot of work to make a really nice printed version of the library
> reference from the LaTex source files (even via sgmlconv). Also wondering if
> I can get bleeds from either of these sites.

I don't see any point to doing that work.  The pdfs look good enough.
I have my own laser printer so I don't think I'd buy a printed copy of
the pdf's, but someone without a printer might find it worthwhile, and
I might buy it if I only had my old inkjet printer.  I wouldn't pay
extra for nicer formatting though.

I haven't felt so far like I needed hardcopy (except for some Tkinter
I downloaded, where a printed copy was very helpful).  What I really
want is better documentation, not nicer printing of the existing docs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import a module without executing it?

2004-12-08 Thread Kent Johnson
Andy, this is a nice example. It prompted me to look at the docs for compiler.visitor. The docs are, 
um, pretty bad. I'm going to attempt to clean them up a little. Would you mind if I include this 
example?

Thanks,
Kent
Andy Gross wrote:
Here's a quick example that will pull out all functions defined in the 
top-level of a module:

---
#/usr/bin/env python
from compiler import parse, walk
from compiler.visitor import ASTVisitor
testdata = r'''
def aFunction(anArg):
return anArg + 1
'''
class SimpleVisitor(ASTVisitor):
def visitFunction(self, parsedFunc):
print "Function %(name)s at %(lineno)s takes %(argnames)s " \
  " with code %(code)s" % parsedFunc.__dict__
if __name__ == "__main__":
ast = parse(testdata)
walk(ast, SimpleVisitor(), verbose=True)
---
[EMAIL PROTECTED]:~$ ./test.py
Function aFunction at 2 takes ['anArg']  with code 
Stmt([Return(Add((Name('anArg'), Const(1])

HTH,
/arg
On Dec 7, 2004, at 11:14 PM, Caleb Hattingh wrote:
Andy
thx for that.  I had a file called 'tktest.py' lying around, and I did:
'>>> a = compiler.parseFile('tktest.py')
And "a" looks something like this:
***
Stmt([Import([('Tkinter', None)]), Function(None, 'add_rows', ['w', 
'titles', 'rows'], [], 0, None, 
Stmt([Discard(CallFunc(Getattr(Name('w'), 'configure'), 
[Keyword('state', Const('normal'))], None, None)), For(AssName('r', 
'OP_ASSIGN'), Name('rows'), Stmt([For(AssTuple([AssName('t', 
'OP_ASSIGN'), AssName('v', 'OP_ASSIGN')]), CallFunc(Name('zip'), 
[Name('titles'), Name('r')], None, None), 
Stmt([Discard(CallFunc(Getattr(Name('w'), 'insert'), [Const('end'), 
Mod((Const('%s:\t%s\n'), Tuple([Name('t'), Name('v')])))], None, 
None))]), None), Discard(CallFunc(Getattr(Name('w'), 'insert'), 
[Const('end'), Const('\n')], None, None))]), None), 
Discard(CallFunc(Getattr(Name('w'), 'configure'), [Keyword('state', 
Const('disabled'))], None, None))])), Assign([AssName('app', 
'OP_ASSIGN')], CallFunc(Getattr(Name('Tkinter'), 'Tk'), [], None, 
None)), Assign([AssName('t', 'OP_ASSIGN')], 
CallFunc(Getattr(Name('Tkinter'), 'Text'), [Name('app'), 
Keyword('state', Const('disabled'))], None, None)), 
Discard(CallFunc(Getattr(Name('t'), 'pack'), [], None, None)), 
Assign([AssName('info', 'OP_ASSIGN')], List([List([Const('Ali'), 
Const(18)]), List([Const('Zainab'), Const(16)]), 
List([Const('Khalid'), Const(18)])])), 
Discard(CallFunc(Name('add_rows'), [Name('t'), List([Const('Name'), 
Const('Age')]), Name('info')], None, None)), 
Discard(CallFunc(Getattr(Name('app'), 'mainloop'), [], None, None))])
***

Pretty impressive :)
Do you know of more batteries that can process this stuff further, for 
interest sake (and maybe the OP)?

thx again
Caleb
On Tue, 7 Dec 2004 15:57:16 -0500, Andy Gross <[EMAIL PROTECTED]> wrote:
You'll want to use the "compiler" package.  compiler.parseFile will 
return an AST that you can inspect (which is not really 'reflection', 
btw).

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

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


Re: Recursive list comprehension

2004-12-08 Thread Adam DePrince
On Wed, 2004-12-08 at 15:02, Steven Bethard wrote:
> Adam DePrince wrote:
> > def flatten( i ):
> > try:
> > i = i.__iter__()
> > while 1:
> > j = flatten( i.next() )
> > try:
> > while 1:
> > yield j.next()
> > except StopIteration:
> > pass
> > except AttributeError:
> > yield i
> 
> 
> Probably you want to catch a TypeError instead of an AttributeError; 
> objects may support the iterator protocol without defining an __iter__ 
> method:
> 
>  >>> class C:
> ... def __getitem__(self, index):
> ... if index > 3:
> ... raise IndexError(index)
> ... return index
> ...
>  >>> list(iter(C()))
> [0, 1, 2, 3]
> 
> I would write your code as something like:
> 
>  >>> def flatten(i):
> ... try:
> ... if isinstance(i, basestring):
> ... raise TypeError('strings are atomic')
> ... iterable = iter(i)
> ... except TypeError:
> ... yield i
> ... else:
> ... for item in iterable:
> ... for sub_item in flatten(item):
> ... yield sub_item
> ...
>  >>> list(flatten([['N','F'],['E'],['D']]))
> ['N', 'F', 'E', 'D']
>  >>> list(flatten([C(), 'A', 'B', ['C', C()]]))
> [0, 1, 2, 3, 'A', 'B', 'C', 0, 1, 2, 3]
> 
> Note that I special-case strings because, while strings support the 
> iterator protocol, in this case we want to consider them 'atomic'.  By 
> catching the TypeError instead of an AttributeError, I can support 
> old-style iterators as well.

Of course, iter( "a" ).next() is "a" -- if you don't look for the
special case of a string you will spin until you blow your stack.   The
problem with a special case is it misses objects that have string like
behavior but are not members of basestring.  This change deals with that
case, albeit at the expense of some performance (it adds a small
O(depth) factor)).  

def flatten(i, history=[]):
try:
if reduce( lambda x,y:x or y, map( lambda x:i is x, history ),\
False ):
raise TypeError('Dej' )
iterable = iter(i)
except TypeError:
yiel>>> list(flatten([C(), 'A', 'B', ['C', C()]]))
> [0, 1, 2, 3, 'A', 'B', 'C', 0, 1, 2, 3]
> 
> Note that I special-case strings because, while strings support the 
> iterator protocol, in this case we want to consider them 'atomic'.  By 
> catching the TypeError instead of an AttributeError, I can support 
> old-style iterators as well.

Of course, iter( "a" ).next() is "a" -- if you don't look for the
special case of a string you will spin until you blow your stack.   The
problem with a special case is it misses objects that have string like
behavior but are not members of basestring.  This change deals with that
case, albeit at the expense of some performance (it adds a small
O(depth) factor)).  

def flatten(i, history=[]):
try:
if isinstance( i,basestring) or reduce( lambda x,y:x or y, map(
lambda x:i is x, history ),\ False ):
raise TypeError('strings are atomic' )
iterable = iter(i)
except TypeError:
yield i
else:
history = history + [i] 
for item in iterable:
for sub_item in flatten(item, history ):
yield sub_item

if __name__ == "__main__":
print list( flatten( a ) )
print list( flatten( b ) )
print list( flatten( c ) )


> 
> Steve
Adam DePrince 


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


Help beautify ugly heuristic code

2004-12-08 Thread Stuart D. Gathman
I have a function that recognizes PTR records for dynamic IPs.  There is
no hard and fast rule for this - every ISP does it differently, and may
change their policy at any time, and use different conventions in
different places.  Nevertheless, it is useful to apply stricter
authentication standards to incoming email when the PTR for the IP
indicates a dynamic IP (namely, the PTR record is ignored since it doesn't
mean anything except to the ISP).  This is because Windoze Zombies are the
favorite platform of spammers.

Here is the very ugly code so far.  It offends me to look at it, but
haven't had any better ideas.  I have lots of test data from mail logs.

# examples we don't yet recognize:
#
# 1Cust65.tnt4.atl4.da.uu.net at ('67.192.40.65', 4588)
# 1Cust200.tnt8.bne1.da.uu.net at ('203.61.67.200', 4144)
# 1Cust141.tnt30.rtm1.nld.da.uu.net at ('213.116.154.141', 2036)
# user64.net2045.mo.sprint-hsd.net at ('67.77.185.64', 3901)
# wiley-268-8196.roadrunner.nf.net at ('205.251.174.46', 4810)
# 221.fib163.satnet.net at ('200.69.163.221', 3301)
# cpc2-ches1-4-0-cust8.lutn.cable.ntl.com at ('80.4.105.8', 61099)
# user239.res.openband.net at ('65.246.82.239', 1392)
# xdsl-2449.zgora.dialog.net.pl at ('81.168.237.145', 1238)
# spr1-runc1-4-0-cust25.bagu.broadband.ntl.com at ('80.5.10.25', 1684)
# user-0c6s7hv.cable.mindspring.com at ('24.110.30.63', 3720)
# user-0c8hvet.cable.mindspring.com at ('24.136.253.221', 4529)
# user-0cdf5j8.cable.mindspring.com at ('24.215.150.104', 3783)
# mmds-dhcp-11-143.plateautel.net at ('63.99.131.143', 4858)
# ca-santaanahub-cuda3-c6b-134.anhmca.adelphia.net at ('68.67.152.134', 62047)
# cbl-sd-02-79.aster.com.do at ('200.88.62.79', 4153)
# h105n6c2o912.bredband.skanova.com at ('213.67.33.105', 3259)

import re

ip3 = re.compile('([0-9]{1,3})[.x-]([0-9]{1,3})[.x-]([0-9]{1,3})')
rehmac = re.compile(
 'h[0-9a-f]{12}[.]|pcp[0-9]{6,10}pcs[.]|no-reverse|S[0-9a-f]{16}[.][a-z]{2}[.]'
)

def is_dynip(host,addr):
  """Return True if hostname is for a dynamic ip.
  Examples:

  >>> is_dynip('post3.fabulousdealz.com','69.60.99.112')
  False
  >>> is_dynip('adsl-69-208-201-177.dsl.emhril.ameritech.net','69.208.201.177')
  True
  >>> is_dynip('[1.2.3.4]','1.2.3.4')
  True
  """
  if host.startswith('[') and host.endswith(']'):
return True
  if addr:
if host.find(addr) >= 0: return True
a = addr.split('.')
ia = map(int,a)
m = ip3.search(host)
if m:
  g = map(int,m.groups())
  if g == ia[1:] or g == ia[:3]: return True
  if g[0] == ia[3] and g[1:] == ia[:2]: return True
  g.reverse()
  if g == ia[1:] or g == ia[:3]: return True
if rehmac.search(host): return True
if host.find("%s." % '-'.join(a[2:])) >= 0: return True
if host.find("w%s." % '-'.join(a[:2])) >= 0: return True
if host.find("dsl%s-" % '-'.join(a[:2])) >= 0: return True
if host.find(''.join(a[:3])) >= 0: return True
if host.find(''.join(a[1:])) >= 0: return True
x = "%02x%02x%02x%02x" % tuple(ia)
if host.lower().find(x) >= 0: return True
z = [n.zfill(3) for n in a]
if host.find('-'.join(z)) >= 0: return True
if host.find("-%s." % '-'.join(z[2:])) >= 0: return True
if host.find("%s." % ''.join(z[2:])) >= 0: return True
if host.find(''.join(z)) >= 0: return True
a.reverse()
if host.find("%s." % '-'.join(a[:2])) >= 0: return True
if host.find("%s." % '.'.join(a[:2])) >= 0: return True
if host.find("%s." % a[0]) >= 0 and \
  host.find('.adsl.') > 0 or host.find('.dial-up.') > 0: return True
  return False

if __name__ == '__main__':
  import fileinput
  for ln in fileinput.input():
a = ln.split()
if len(a) == 2:
  ip,host = a
  if host.startswith('[') and host.endswith(']'):
continue# no PTR
  if is_dynip(host,ip):
print ip,host
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [SPAM] Re: Import a module without executing it?

2004-12-08 Thread Andy Gross
On Dec 8, 2004, at 5:44 AM, Kent Johnson wrote:
Andy, this is a nice example. It prompted me to look at the docs for 
compiler.visitor. The docs are, um, pretty bad. I'm going to attempt 
to clean them up a little. Would you mind if I include this example?
Be my guest!
/arg
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2D array

2004-12-08 Thread Adam DePrince
On Wed, 2004-12-08 at 15:06, Steven Bethard wrote:
> Adam DePrince wrote:
> > If your data is sparse you might want to consider using a dictionary
> > where the key is a tuple representing the coordinates.
> > 
> > a = {}
> > a[(0,0)] = 0
> > a[(0,1)] = 1
> [snip]
> print a.get( (5,0), None )
> 
> Good point.  Note that you don't need the parentheses in the assignments 
> or item accesses:
> 
>  >>> a = {}
>  >>> a[0,0] = 10
>  >>> a[0,0]
> 10
> 
> Also note that you don't need to specify None as the default value when 
> you call dict.get -- None is assumed if no default value is supplied:

The use of  None as the default parameter was on purpose; the lack of
"magic" in python is often cited in religious wars between python and
perl aficionados.  Use of get(something, None) was on purpose, the level
of familiarity with the language implied by the original question
suggested that the notion of optional parameters, and specifically those
of get, may not have been immediately obvious.

As for a[0,0] instead of a[(0,0)] ... the former just *looks* so
aesthetically wrong to me that I've never used it, and had forgotten
that it was even possible.   

> 
>  >>> print a.get((5, 2))
> None
> 
> Steve
Adam DePrince 


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


Re: opinions comments needed for improving a simple template engine.

2004-12-08 Thread fuzzylollipop
the ONLY way to tell what is slow is to actually profile each of the
operations, that said, start with examining object creation / memory
allocation. string concationation usually does both . . .

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


Re: Recursive list comprehension

2004-12-08 Thread Steven Bethard
Adam DePrince wrote:
On Wed, 2004-12-08 at 15:02, Steven Bethard wrote:
Note that I special-case strings because, while strings support the 
iterator protocol, in this case we want to consider them 'atomic'.  By 
catching the TypeError instead of an AttributeError, I can support 
old-style iterators as well.
Of course, iter( "a" ).next() is "a" -- if you don't look for the
special case of a string you will spin until you blow your stack.   The
problem with a special case is it misses objects that have string like
behavior but are not members of basestring.
Yup.  Unfortunately, there's no "string protocol" like there's an 
"iterator protocol" or we could check this kind of thing easier.  Seems 
like your history check might be the best option if you need to support 
this kind of thing.

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


Re: 2D array

2004-12-08 Thread Steven Bethard
Adam DePrince wrote:
The use of  None as the default parameter was on purpose; the lack of
"magic" in python is often cited in religious wars between python and
perl aficionados.  Use of get(something, None) was on purpose, the level
of familiarity with the language implied by the original question
suggested that the notion of optional parameters, and specifically those
of get, may not have been immediately obvious.
As for a[0,0] instead of a[(0,0)] ... the former just *looks* so
aesthetically wrong to me that I've never used it, and had forgotten
that it was even possible.   
Sorry, I hadn't meant any of my comments as criticisms -- just wanted to 
make sure the OP knew about all the options open to them.  I'm used to 
a[0,0] because I've used numarray a bit, but to each his own, of course. =)

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


Re: Multiple concurrent telnet sessions

2004-12-08 Thread Lee Harr
On 2004-12-08, Tony Pryor <[EMAIL PROTECTED]> wrote:
> Hello,
>
> Anyone know if running two client telnet sessions at the same time
> should be an inherent problem? They don't seem to want to share a port
> or are they trying to use the same console for interaction with the
> connected servers?
>

I don't know if it will work, but have you looked at using
twisted for networking?  If nothing else, someone on the
twisted mailing list may be able to point you in the right
direction...

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


Re: Bug 834351 - Mouse wheel crashes program

2004-12-08 Thread "Martin v. Löwis"
Gary Richardson wrote:
Has this bug been fixed in 2.3.5 or 2.4? Does it exist in XP systems?
To my knowledge, it has not been fixed. I have not even tried to
reproduce it, yet. Contributions are welcome.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: MP3 - VBR - Frame length in time

2004-12-08 Thread Lonnie Princehouse
It might be much easier to use an external program to figure out the
length.
Here's an example that uses sox to convert just about any audio file
into a raw format, and then determines duration by dividing length of
the raw output by number of bytes per frame.

I don't know if they make sox for Windows, but there must be something
analogous.
This takes a few seconds to run on a P4/2.8, depending of course on the
input mp3.

---
import os

# return length of audio file, in seconds
def audio_file_duration(filename):
if not os.path.exists(filename):
raise Exception("file not found")
# convert into 8000Hz mono 8-bit
output_stream = os.popen('sox %s -t raw -r 8000 -U -b -c 1 -p -' %
filename)
bytes_read = 0
block_size = 2048
while True:
chunk = output_stream.read(block_size)
if not chunk:
break
bytes_read += len(chunk)
return float(bytes_read) / 8000

---
I apologize for the hosed indentation.  Google Groups is mangling my
posts.

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


  1   2   >