Re: ActiveState Code: the new Python Cookbook site

2008-07-11 Thread Thin Myrna
Trent Mick wrote:

> Stef Mientki wrote:
>> one small remark,
>> If I want to browse 200 recipes, at 10 per page  
>> ... please make something like 100 available per page,
>> are internet is fast enough nowadays.
> 
> Touche. Done:
> 
>http://code.activestate.com/recipes/?paginate_by=100
> 

The old cookbook offered choices by category. Did you drop that feature?

> Cheers,
> Trent
> 

Thin


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


Re: error with configure (svn 64857)

2008-07-11 Thread Martin v. Löwis
> Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ?

I'm not so sure that there is anything wrong in configure. configure
doesn't pass -lgcc_s to icc; instead, icc is making this up on its
own. So I would guess you need to get libgcc_s onto you system in a
way that the linker finds it. Else you need to read the icc
documentation (but I'm fairly sure that icc is *required* to link
with libgcc_s, for interoperability with gcc-compiled binaries).

I'm somewhat puzzled that the wchar_t test is the one where it
crashes; this test comes fairly late, and configure has run multiple
compiler invocations before that.

Can you build any binaries at all with your icc installation?

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


Re: Python 3.0 and removal of the 'string' module

2008-07-11 Thread Martin v. Löwis
> This is rather disappointing. Is that entire page suspect? 

All documentation about Python 3 is suspect until Python 3 gets
actually released (nobody can say for sure how the release will
look like in all details).

Wiki pages, traditionally, are always suspect for incorrect
or outdated information, IMO. It's in the nature of Wikis.

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


Re: Bypassing WebFilter security

2008-07-11 Thread pranav
On Jul 11, 11:42 am, "Daniel Fetchinson" <[EMAIL PROTECTED]>
wrote:
> >> I am working in an organization, which is using a very strict
> >> webcontent filter management suite. Due to this i am unable to
> >> download any exe file, or surf web (even the necessary downloads from
> >> sourceforgenet are blocked). I was wondering, if python could be of
> >> any help. Say i have a python script, and i pass the URL of
> >> downloadable file, and it just downloads the file for me.
>
> > Nice try. Can I talk to your employer for a minute? :)
>
> > Honestly, the language doesn't make any difference here, and there isn't
> > much
> > you can do unless you control both sides, i.e. the server and the client.
> > But
> > I would suggest you actually talk to your employer yourself to see if
> > there's
> > an official way to get what you want.
>
> Yes, the language itself doesn't matter as long as you go through the
> web. But if I were you I would use an ssh client to ssh to a remote
> machine on which I have an account, download the file there to that
> machine and scp it to the local machine. Assuming of course port 21 is
> not blocked.
>
> In fact, this is something I do regularly for similar reasons :)
>
> Good luck,
> Daniel
> --
> Psss, psss, put it down! -http://www.cafepress.com/putitdown

Daniel, cool even i thought of the same thing, but you see, the
assumption has no use in my case! It is also blocked, Anyways, i will
talk to the system admins here. Thanks all
--
http://mail.python.org/mailman/listinfo/python-list


Re: socket-module: different behaviour on windows / unix when a timeout is set

2008-07-11 Thread Gabriel Genellina

En Wed, 09 Jul 2008 15:02:56 -0300, Mirko Vogt <[EMAIL PROTECTED]> escribi�:

it seems that the socket-module behaves differently on unix / windows  
when a timeout is set.

[...]
Now I will change the code slightly - to be precise I set a timeout on  
the socket:



# test.py

import socket
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.settimeout(3.0) #  <-
print 'trying to connect...'
sock.connect(('127.0.0.1',))
print 'connected!'


# executed on linux

$ python test.py
trying to connect...
Traceback (most recent call last):
  File "test.py", line 5, in 
sock.connect(('127.0.0.1',))
  File "", line 1, in connect
socket.error: (111, 'Connection refused')
$


# executed on windows


C:\Python25\python.exe test.py

trying to connect...
connected!


Which Python version? Which Windows version? I've tried 2.3.4, 2.4.4,  
2.5.1 and 3.0a4, all on WinXP SP2, and in all cases I got an exception  
(details differ between versions). In no case I could make the connection  
succeed when nobody was listening at port , as expected.


--
Gabriel Genellina

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

numeric emulation and the rich comparison operators

2008-07-11 Thread Ethan Furman

Greetings, List!

Still working on my Measure class, and my next question is... (drum roll 
please ;)


What are the advantages of using __[eq|ne|lt|gt|le|ge]__ vs __cmp__?

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


Re: Python 3.0 and removal of the 'string' module

2008-07-11 Thread Ben Finney
"Martin v. Löwis" <[EMAIL PROTECTED]> writes:

> > This is rather disappointing. Is that entire page suspect? 
> 
> All documentation about Python 3 is suspect until Python 3 gets
> actually released (nobody can say for sure how the release will
> look like in all details).

Is there a better information source, then, for the current state of
what's expected in Python 3.0?

-- 
 \“Somebody told me how frightening it was how much topsoil we |
  `\   are losing each year, but I told that story around the campfire |
_o__) and nobody got scared.” —Jack Handey |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: problem with exec and locals()

2008-07-11 Thread Peter Otten
Uwe Schmitt wrote:

>> Apparently, exec in locals() knows nothing about slots (because locals()
>> is the only dictionary in the universe where slots would be involved ? --
>> perhaps not, but close).
>>
>> Mel.
> 
> Thanks for your answer. I wonder if this is a bug, or did I miss
> something in the docs ???
 
Hm, the documentation has an explicit warning:

http://docs.python.org/lib/built-in-funcs.html#l2h-47

"""
locals(  )
 Update and return a dictionary representing the current local symbol table.
Warning: The contents of this dictionary should not be modified; changes
may not affect the values of local variables used by the interpreter.
"""

By the way, the local namespace is affected if you don't provide it
explicitly:

>>> def f():
... exec "a=42"
... print a
... a = "whatever"
...
>>> f()
42

Peter

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


Re: installing any python module

2008-07-11 Thread Gabriel Genellina
En Thu, 10 Jul 2008 14:02:29 -0300, Bhagwat Kolde <[EMAIL PROTECTED]>  
escribi�:



What is the correct process of installing any external python module?
Once we downloaded any python module,

Q1) Where this module should be placed in python installation file
structure?


If it is a single Python module, you can put it anywhere in the Python  
path. A good place may be the site-packages subdirectory. Execute this  
line to see the list of directories that are currently searched for  
modules:


python -c "import sys; print '\n'.join(sys.path)"

More complex packages (containing many modules and its own internal  
hierarchy) usually provide a setup.py script



Q2) How to execute setup.py file?


Like any other script. For many Python packages, you only have to execute  
this:


cd path/to/the/downloaded/and/uncompressed/package
python setup.py install

Please read the package documentation for any specific instructions. There  
is a generic guide aimed at site administrators: "Installing Python  
Modules" 


--
Gabriel Genellina

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

Re: ActiveState Code: the new Python Cookbook site

2008-07-11 Thread Peter Otten
Thin Myrna wrote:

> The old cookbook offered choices by category. Did you drop that feature?

Looks like categories have become tags:

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

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


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-11 Thread Bill Davy
"Tim Golden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Bill Davy wrote:
>> I'm not sure OL2003 can read news.  I think perhaps some later OL can 
>> (added tot he View menu, perhaps?).  So I use OL Express to read news. 
>> The OL with which I wish to communicate is:
>>
>> Application name Outlook
>> Version 11.0
>> Build 8217
>> Product ID 70141-700-0350904-56905
>> Language English (United States)
>> Application Path C:\Program Files\Microsoft Office\OFFICE11\
>> System Language English (United Kingdom)
>> Mail Support Not Available
>> Current folder Inbox
>> Current item Not Available
>
> Where did you get to with this, Bill? I wasn't sure if no news
> was good news or whether you'd gone a different way, or
> were still trying things...
>
> TJG


Hi Tim,
Well, at 5pm last Friday I posted:
"

I kept looking and thought I was saved when I found Receipe 10.16 in the
Python Cookbook but 

I changed the following:

self.oOutlookApp = Dispatch("Outlook.Application")
#self.oOutlookApp =
gencache.EnsureDispatch("Outlook.Application")

Because gencache failed and I hade run makepy last week (I only get one day
a week to look at this).

Then the following failed because (as I found) olFolderContacts is not in
any of constants' dictionaries.

ofContacts = onMAPI.GetDefaultFolder(constants.olFolderContacts)

So, sadly, I shall have to put this aside for another week and get on with
some work.  Any thoughts would be gratefully accepted.

TIA,
   Bill
"

and since then have been busy with work, and my other job, and the garden. 
Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E etc 
etc but that's another story).  So any help today will be much appreciated.
Rgds,
   Bill 


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


importing .dll in a python file

2008-07-11 Thread moijes12
Hi

I need to use a .dll from a python script.I have installed pywin.But
in the program ,which is like:

import dllName

I get :

Import Error : DLL not found

Please suggest a solution!
--
http://mail.python.org/mailman/listinfo/python-list


Trying to learn

2008-07-11 Thread luster123
Hey,
Can someone please teach me the basics of Python and Pygame?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems Returning an HTTP 200 Ok Message

2008-07-11 Thread Gabriel Genellina
En Thu, 10 Jul 2008 18:10:46 -0300, Guy Davidson <[EMAIL PROTECTED]>  
escribi�:



On Jul 10, 12:38 pm, samwyse <[EMAIL PROTECTED]> wrote:

On Jul 10, 1:50 pm, Guy Davidson <[EMAIL PROTECTED]> wrote:

> My code (attached below) us supposed to read an HTTP Post message
> coming from a power meter, parse it, and return a proper HTTP 200 Ok
> message. The problem is that the socket fails to send the entire
> message as one message, creating a fragmented message which the power
> meter then fails to read and accept.

From your description, I get the feeling that your power meter has a
broken network stack, and you're trying to program around it.  You
need to repair the meter.


The meter sends HTTP Post messages, and expects, as a reply, an HTTP
200/Ok message.

I try to send the following message, using the socket.send() command:

'HTTP/1.1 200 OK\r\nDate: Thu, 10 July 2008 14:07:50 GMT\r\nServer:
Apache/2.2.8 (Fedora)\r\nX-Powered-By: PHP/5.2.4\r\nContent-Length: 4\r
\nConnection: close\r\nContent-Type: text/html; charset=UTF-8\r\n\r
\n[0]\n'

However, when I snoop on the packets in wireshark, here's what I see:

HTTP/1.1 200 Ok:

HTTP/1.1 200 OK
Date: Wed, 09 July 2008 14:55:50 GMT
Server: Apache/2.2.8 (Fedora)
X-Powered-By:

Continuation or non-HTTP traffic:

PHP/5.2.4
Content-Length: 4
Connection: close
Content-Type: text/html; charset=UTF-8

[0]

It splits into two packages, which the meter can't read, and the
communication breaks down there.

Any ideas?


As Guy Davidson has already pointed out, this is a problem in the meter  
TCP implementation, and you should ask the vendor to fix it. (Anyway,  
looks like "somewhere" there is a buffer size of 100 bytes or so, very  
small).


As a workaround, try to shorten your HTTP response; I guess the Server and  
X-Powered-By headers are not required; the Date probably isn't either; and  
if all your responses are like "[0]" a simple "Content-Type: text/plain"  
may suffice (the meter might just ignore it, anyway).


--
Gabriel Genellina

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

Re: Trying to learn

2008-07-11 Thread Ben Finney
luster123 <[EMAIL PROTECTED]> writes:

> Can someone please teach me the basics of Python and Pygame?

Yes, you can do it.

http://docs.python.org/tut/tut.html>
http://www.python.org/doc/>
http://clusty.com/search?query=pygame+tutorial>

-- 
 \ “Too many pieces of music finish too long after the end.” —Igor |
  `\   Stravinskey |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

ANN: P4D 1.1

2008-07-11 Thread Kay Schluehr
P4D = E4X style embedded DSL for Python but without E and X.

For more information see:

http://pypi.python.org/pypi/P4D/1.1-py2.5
--
http://mail.python.org/mailman/listinfo/python-list


Re: importing .dll in a python file

2008-07-11 Thread Tim Golden

moijes12 wrote:

I need to use a .dll from a python script.I have installed pywin.But
in the program ,which is like:

import dllName

I get :

Import Error : DLL not found

Please suggest a solution!



Well, the short answer is: use the ctypes module.

The longer answer is: read around the subject a
bit before you expect Python to import an arbitrary
DLL and then give up when it doesn't :)

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


Re: numeric emulation and the rich comparison operators

2008-07-11 Thread Gabriel Genellina
En Thu, 10 Jul 2008 17:37:42 -0300, Ethan Furman <[EMAIL PROTECTED]>  
escribi�:



Greetings, List!

Still working on my Measure class, and my next question is... (drum roll  
please ;)


What are the advantages of using __[eq|ne|lt|gt|le|ge]__ vs __cmp__?


If your objects obey the trichotomy law (an object MUST BE less than,  
greater than, or equal to another one, and there is no other possibility)  
then __cmp__ is enough, and easier to define than all the rich comparison  
operations.
In other cases, __cmp__ is not suitable: by example, complex numbers can't  
define "greater than" [in a way that preserves the meaning for real  
numbers]; you can only use "equal" or "not equal". You can't use __cmp__  
for this, because it *has* to return either >0 or <0 (implying "greater  
than" or "less than"). In this case it's best to use the rich comparison  
operators: define __eq__ and __ne__ and make all other comparisons between  
complex numbers raise an exception.


--
Gabriel Genellina

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

Re: Basic Question about Python WebServer File handling

2008-07-11 Thread Gabriel Genellina
En Thu, 10 Jul 2008 22:20:21 -0300, Alok Kumar <[EMAIL PROTECTED]>  
escribi�:



I need to have a python webserver which can handle Get request from the
clients and upload the *files* from 4 different directories.

Can someone please point me what to exactly look for.


Look at SimpleHTTPServer.py in the standard library - either use it as it  
is or subclass SimpleHTTPRequestHandler to suit your needs.


--
Gabriel Genellina

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

Django admin multi layour

2008-07-11 Thread Christian Kortenhorst (Forum)
Hey All

Just been messing around with django and found that can not seam to get
admin to work how, it does not support multilayer input I want it I know
there is some way of writing your own "view", but wondering would it be
possible to write a multilayer setup or what is the wok around or what
should i be looking for?

my setup is


class Faculty(models.Model):
class Admin: pass
name = models.CharField(maxlength=200)
director = models.CharField(maxlength=200)
web_url = models.CharField(maxlength=200)

def __str__(self):
return self.name

class School(models.Model):
class Admin: pass

faculty = models.ForeignKey(Faculty)
name = models.CharField(maxlength=200)

def __str__(self):
return self.name

class Programme(models.Model):
class Admin: pass

duration_choices = (
('Years', 'years'),
('Days', 'days')
)

school = models.ForeignKey(School)
name = models.CharField(maxlength=200)
description = models.CharField(maxlength=1000)

def __str__(self):
return self.name

class Stream(models.Model):
class Admin: pass
programme_code = models.ForeignKey(Programme,
edit_inline=models.TABULAR, num_in_admin=3)
stream_number = models.IntegerField(core=True)

.



Want to be able to click in and keep adding programs to a school and when i
do that a new box is created and a steam is created.

e.g.

add a Faculty
-> input for school is shown
-> add a school
-> -> input for Programme is shown
-> -> add a programme
-> -> -> etc..

also the option to add new school and program so can have a one to many
relationship.

Thanks
Christian K

-- 
Christian Kortenhorst
mod: +353-(0)87-6183349
home: +353-(0)1-4966287
--
http://mail.python.org/mailman/listinfo/python-list

Re: problem with exec and locals()

2008-07-11 Thread Gabriel Genellina
En Fri, 11 Jul 2008 03:51:39 -0300, Uwe Schmitt  
<[EMAIL PROTECTED]> escribi�:



On 1 Jul., 15:15, Mel <[EMAIL PROTECTED]> wrote:

rocksportrockerwrote:

> the following code does not work until I ommit the "a=0" statement.

>    def test():
>        exec "a=3" in locals()
>        print a
>        a=0

>     test()

> print raises:
>      UnboundLocalError: local variable 'a' referenced before
> assignment

> Can anybody explain what is going wrong here ?

AFAIK, local variables are implemented rather like __slots__ in  
new-style
classes.  This is a very valuable efficiency measure, but it can cause  
this
kind of trouble.  Without `a=0`, the bytecode compiler makes no slot  
for a,


Thanks for your answer. I wonder if this is a bug, or did I miss
something
in the docs ???


Read the warnings in the docs for the locals() builtin function:
http://docs.python.org/lib/built-in-funcs.html#l2h-47
and the execfile function:
http://docs.python.org/lib/built-in-funcs.html#l2h-26

--
Gabriel Genellina

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

Re: Trying to learn

2008-07-11 Thread Gabriel Genellina
En Fri, 11 Jul 2008 05:49:23 -0300, Ben Finney  
<[EMAIL PROTECTED]> escribi�:



luster123 <[EMAIL PROTECTED]> writes:


Can someone please teach me the basics of Python and Pygame?


Yes, you can do it.

http://docs.python.org/tut/tut.html>
http://www.python.org/doc/>
http://clusty.com/search?query=pygame+tutorial>


Also you can find other resources in the Python wiki:  



--
Gabriel Genellina

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

Question about: GUI Builder for Tkinter and call to C/C++ code

2008-07-11 Thread pauladospublicidad

First I'll introduce myself. I normally programm in C/C++ and Java.
Sometimes I have to mix them (normally using C/C++ in java, because in
java is easier to make portable graphic user interfaces). However to
use C/C++ code in java is really complex and difficult.

Not too much time ago, I discover python. I had think to use it for
developing portable graphic user intefaces, that will call my C/C++
code / libraries / programs.

I had thought to use tkinter for making the GUIs, for portability and
for not installing anything more than python. It's to say, for not
adding more packages because I'm new in python and I don't now too
much about install new packages.

I have seen that for wxpython there is gui builders (such as boa) but
for tkinter I have not found anyon. I would like to know if anyone
knows a GUI Builder for tkinter in order to develop my GUI's
graphically and in a easier way.

Apart from this, I would like to call my C/C++ code / modulles /
applications from python. I have read that python is implemented
normally in C, so is easy to add new modules from C. I would like to
find any tutorial / manual / link for dummies in order to make this
(call my C code from python).

Another solution could be to call the GUI made in python from C/C++
code, but I'm sure this would be more complex.

To sum up, if anyone knows something about this subjects, about what I
would like to do, I'll appreciate any answer :D


Byee!

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


Re: recommended gcc versions for python2.5 compilation on Solaris sparc/x86, AIX, Linux

2008-07-11 Thread Jeroen Ruigrok van der Werven
-On [20080711 06:18], YIN Ming ([EMAIL PROTECTED]) wrote:
>2.  use new version of gcc (rather than odd version)

See
http://www.in-nomine.org/2008/04/11/python-26a2-execution-times-with-various-compilers/
 that I wrote a while ago.

Basically for Python GCC 3.4.6 outperformed the newer GCCs. So do not
automatically assume that newer is better.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
The weak can never forgive. Forgiveness is the attribute of the strong...
--
http://mail.python.org/mailman/listinfo/python-list

Re: Question about: GUI Builder for Tkinter and call to C/C++ code

2008-07-11 Thread Diez B. Roggisch

pauladospublicidad schrieb:

First I'll introduce myself. I normally programm in C/C++ and Java.
Sometimes I have to mix them (normally using C/C++ in java, because in
java is easier to make portable graphic user interfaces). However to
use C/C++ code in java is really complex and difficult.

Not too much time ago, I discover python. I had think to use it for
developing portable graphic user intefaces, that will call my C/C++
code / libraries / programs.

I had thought to use tkinter for making the GUIs, for portability and
for not installing anything more than python. It's to say, for not
adding more packages because I'm new in python and I don't now too
much about install new packages.

I have seen that for wxpython there is gui builders (such as boa) but
for tkinter I have not found anyon. I would like to know if anyone
knows a GUI Builder for tkinter in order to develop my GUI's
graphically and in a easier way.


AFAIK there is none, at least not usable with python. However, back when 
I did tk, I found it easy and clear enough (especially with the powerful 
layout managemnt) to hand-craft the GUI.



Apart from this, I would like to call my C/C++ code / modulles /
applications from python. I have read that python is implemented
normally in C, so is easy to add new modules from C. I would like to
find any tutorial / manual / link for dummies in order to make this
(call my C code from python).


There are various options, depending on if you are real about using C, 
or if you are more into C++.


If you *can*, you should IMHO rely on a C-API (potentially layering a 
C++-lib). Then you can use the since python2.5 build-in ctypes-module to 
 access any DLL/shared library you like.


For extending and embedding, see the official docs:

http://docs.python.org/ext/ext.html

For C++ wrappers, there are several available:

 - SWIG
 - Boost::Python
 - SIP (used to wrap the great Qt gui toolkit)

I can personally recommend the latter, others MMV.


Another solution could be to call the GUI made in python from C/C++
code, but I'm sure this would be more complex.


You don't want this, no. It's possible, but needlessly complex.

HTH,

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


Moving to functional programming

2008-07-11 Thread James Fassett
Hi all,

Had a simple problem that turned into an interesting solution and I
thought I would share it here.

I had a list of tuples that I needed to get the first value from and
generate a list.

tuple_list = (
('John', 'Doe'),
('Mark', 'Mason'),
('Jeff', 'Stevens'),
('Bat', 'Man')
  )

# what I'd do in C or other procedural languages
result_list = []
for item in tuple_list:
result_list.append(item[0])

# the first Pythonic attempt using comprehensions
result_list = [x[0] for x in tuple_list]

# the final functional way
[result_list, _] = zip(*tuple_list)

I really like how Python allows me to do what I feel is the most
natural solution (for a seasoned procedural programmer) while allowing
a satisfying path towards a more functional approach.

Cheers,
James
--
http://mail.python.org/mailman/listinfo/python-list


RE: recommended gcc versions for python2.5 compilation on Solarissparc/x86, AIX, Linux

2008-07-11 Thread YIN Ming
Dear Jeroen,

Thanks so much for your help. :)

Best regards,
Yin Ming

-Original Message-
From: Jeroen Ruigrok van der Werven [mailto:[EMAIL PROTECTED] 
Sent: Friday, July 11, 2008 5:55 PM
To: YIN Ming
Cc: [email protected]; LEGRAND Mathieu
Subject: Re: recommended gcc versions for python2.5 compilation on 
Solarissparc/x86, AIX, Linux

-On [20080711 06:18], YIN Ming ([EMAIL PROTECTED]) wrote:
>2.  use new version of gcc (rather than odd version)

See
http://www.in-nomine.org/2008/04/11/python-26a2-execution-times-with-various-compilers/
 that I wrote a while ago.

Basically for Python GCC 3.4.6 outperformed the newer GCCs. So do not
automatically assume that newer is better.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
The weak can never forgive. Forgiveness is the attribute of the strong... 
 
 


 This e-mail contains information for the intended recipient only.  It may 
contain proprietary material or confidential information.  If you are not the 
intended recipient you are not authorised to distribute, copy or use this 
e-mail or any attachment to it.  Murex cannot guarantee that it is virus free 
and accepts no responsibility for any loss or damage arising from its use.  If 
you have received this e-mail in error please notify immediately the sender and 
delete the original email received, any attachments and all copies from your 
system.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to functional programming

2008-07-11 Thread bearophileHUGS
James Fassett:
> # the first Pythonic attempt using comprehensions
> result_list = [x[0] for x in tuple_list]
>
> # the final functional way
> [result_list, _] = zip(*tuple_list)
>
> I really like how Python allows me to do what I feel is the most
> natural solution (for a seasoned procedural programmer) while allowing
> a satisfying path towards a more functional approach.

The list comprehension is quite more readable to me, so I suggest you
to use it. It's probably the default way to do it in Python.

If you want functional code this is another way (I have not tested the
relative performance but it may be quick):

>>> tuple_list = (
... ('John', 'Doe'),
... ('Mark', 'Mason'),
... ('Jeff', 'Stevens'),
... ('Bat', 'Man')
...   )
>>> from operator import itemgetter
>>> map(itemgetter(0), tuple_list)
['John', 'Mark', 'Jeff', 'Bat']

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


Re: error with configure (svn 64857)

2008-07-11 Thread Mathieu Prevot
2008/7/11 "Martin v. Löwis" <[EMAIL PROTECTED]>:
>> Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ?
>
> I'm not so sure that there is anything wrong in configure. configure
> doesn't pass -lgcc_s to icc; instead, icc is making this up on its
> own. So I would guess you need to get libgcc_s onto you system in a
> way that the linker finds it. Else you need to read the icc
> documentation (but I'm fairly sure that icc is *required* to link
> with libgcc_s, for interoperability with gcc-compiled binaries).
>
> I'm somewhat puzzled that the wchar_t test is the one where it
> crashes; this test comes fairly late, and configure has run multiple
> compiler invocations before that.
>
> Can you build any binaries at all with your icc installation?

Yes of course, I successfuly built and installed nmap, wget, so I
thought there was something in the python configure process.

If didn't investigate everything but I solved the problem by adding
the "-static-libgcc" option:

CFLAGS="-w -static-intel -static-libgcc"

I think one should commit changes so configure can manage this. I can
I want to help for further diagnosis or improvement. Also it seems
-Wall will be deprecated, and usually we use -w:

   -w  Control diagnostics, where  is one of the following:

 0 -- Display errors (same as -w)

 1 -- Display warnings and errors (default)

 2 -- Display remarks, warnings, and errors


Cheers,
Mathieu
--
http://mail.python.org/mailman/listinfo/python-list


Re: error with configure (svn 64857)

2008-07-11 Thread Mathieu Prevot
2008/7/11 WDC <[EMAIL PROTECTED]>:
> On Jul 10, 6:57 pm, "Mathieu Prevot" <[EMAIL PROTECTED]> wrote:
>> 2008/7/10 "Martin v. Löwis" <[EMAIL PROTECTED]>:
>>
>> >> I have the following error when I run configure:
>>
>> >> checking size of wchar_t... configure: error: cannot compute sizeof 
>> >> (wchar_t)
>>
>> >> what can I do ?
>>
>> > Study config.log for the source of the problem.
>>
>> Thank you Martin. How can I remove -lgcc_s and use the Intel equivalent ?
>>
>> configure:21939: checking for wchar_t
>> configure:21970: icc -c -g -O2  conftest.c >&5
>> conftest.c(123): warning #279: controlling expression is constant
>>   if ((ac__type_new_ *) 0)
>>   ^
>>
>> configure:21976: $? = 0
>> configure:21991: result: yes
>> configure:21998: checking size of wchar_t
>> configure:22306: icc -o conftest -g -O2   conftest.c  >&5
>> ld: library not found for -lgcc_s
>> configure:22309: $? = 1
>> configure: program exited with status 1
>>
>> Mathieu
>
> I think he wanted YOU to find the problem. The best way to learn is to
> figure it out yourself! Good luck.

Yes WDC I know, but for some problems 1) we can gain much efficiency
with getting help from guys that are familiar with the environment and
 2) we also allow the committers to know a problem and improve the
sources. That's the way an open source group works IMHO :)

Now that the problem is solved for me, it is for all MacOSX+Intel icc guys.

Cheers,
Mathieu
--
http://mail.python.org/mailman/listinfo/python-list


Re: importing .dll in a python file

2008-07-11 Thread moijes12
On Jul 11, 2:09 pm, Tim Golden <[EMAIL PROTECTED]> wrote:
> moijes12 wrote:
> > I need to use a .dll from a python script.I have installed pywin.But
> > in the program ,which is like:
>
> > import dllName
>
> > I get :
>
> > Import Error : DLL not found
>
> > Please suggest a solution!
>
> Well, the short answer is: use the ctypes module.
>
> The longer answer is: read around the subject a
> bit before you expect Python to import an arbitrary
> DLL and then give up when it doesn't :)
>
> TJG

Thanks a lot Tim.

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



How to serialize and deserialize the objects into memory?

2008-07-11 Thread hardemr
Hello Everyone,

I want to serialize and deserialize the objects into Memory not into
file. How can i do that?

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


Re: How to serialize and deserialize the objects into memory?

2008-07-11 Thread Diez B. Roggisch

hardemr schrieb:

Hello Everyone,

I want to serialize and deserialize the objects into Memory not into
file. How can i do that?



Use pickle & module StringIO/cStringIO as file-to-memory-object.

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


MySQLdb will only import for root

2008-07-11 Thread martinnorth

Hi,

I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I 
try to import MySQLdb I get the following error:


ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08)
[GCC 3.3.1 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named MySQLdb

But if I lrun python as the root user it imports fine. Can anyone 
suggest what might be wrong with the installation? Or is there nothing 
wrong? I haven't seen any examples that mentioned being root to import a 
module.


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


Re: MySQLdb will only import for root

2008-07-11 Thread Diez B. Roggisch

martinnorth schrieb:

Hi,

I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I 
try to import MySQLdb I get the following error:


ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08)
[GCC 3.3.1 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import MySQLdb
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named MySQLdb

But if I lrun python as the root user it imports fine. Can anyone 
suggest what might be wrong with the installation? Or is there nothing 
wrong? I haven't seen any examples that mentioned being root to import a 
module.


Try importing sys and printing out sys.path both with a "normal" account 
and the root-account, to see if there are any differences. And of course 
make sure both actually use the same interpreter.


Beyond that, you are right: there is no root-only-importing.

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


Re: MySQLdb will only import for root

2008-07-11 Thread Jeff
Is it possible the module was installed with priviledges set too
strict?  Perhaps the interpreter cannot see the module when it is run
from a normal user account.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PIL: Transparent PNGs and im.paste: ValueError: bad transparency mask

2008-07-11 Thread Ken Starks

Durand wrote:

I posted this too soon. Converting the images to png with image magick's 
convert did the trick...However, I'm still not sure why I need to convert the 
images in the first place. Are there different types of PNGs?

http://en.wikipedia.org/wiki/Portable_Network_Graphics#Transparency_of_image
--
http://mail.python.org/mailman/listinfo/python-list


Re: socket-module: different behaviour on windows / unix when a timeout is set

2008-07-11 Thread Mirko Vogt
Gabriel Genellina wrote:
> En Wed, 09 Jul 2008 15:02:56 -0300, Mirko Vogt <[EMAIL PROTECTED]> escribi�:
> 
>> it seems that the socket-module behaves differently on unix / windows
>> when a timeout is set.
> [...]
>> Now I will change the code slightly - to be precise I set a timeout on
>> the socket:
>>
>>
>> # test.py
>>
>> import socket
>> sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>> sock.settimeout(3.0) #  <-
>> print 'trying to connect...'
>> sock.connect(('127.0.0.1',))
>> print 'connected!'
>>
>>
>> # executed on linux
>>
>> $ python test.py
>> trying to connect...
>> Traceback (most recent call last):
>>   File "test.py", line 5, in 
>> sock.connect(('127.0.0.1',))
>>   File "", line 1, in connect
>> socket.error: (111, 'Connection refused')
>> $
>>
>>
>> # executed on windows
>>
>>> C:\Python25\python.exe test.py
>> trying to connect...
>> connected!
> 
> Which Python version? Which Windows version? I've tried 2.3.4, 2.4.4,
> 2.5.1 and 3.0a4, all on WinXP SP2, and in all cases I got an exception
> (details differ between versions). In no case I could make the
> connection succeed when nobody was listening at port , as expected.
> 

Hey, this is strange.

Linux:
$ python --version
Python 2.5.2
$

Windows:
C:\Python25>python.exe --version
Python 2.5.2
C:\Python25>

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

strip() using strings instead of chars

2008-07-11 Thread Christoph Zwerschke

In Python programs, you will quite frequently find code like the
following for removing a certain prefix from a string:

if url.startswith('http://'):
url = url[7:]

Similarly for stripping suffixes:

if filename.endswith('.html'):
filename = filename[:-5]

My problem with this is that it's cumbersome and error prone to count
the number of chars of the prefix or suffix. If you want to change it
from 'http://' to 'https://', you must not forget to change the 7 to 8.
If you write len('http://')  instead of the 7, you see this is actually
a DRY problem.

Things get even worse if you have several prefixes to consider:

if url.startswith('http://'):
url = url[7:]
elif url.startswith('https://'):
url = url[8:]

You can't take use of url.startswith(('http://', 'https://')) here.

Here is another concrete example taken from the standard lib:

if chars.startswith(BOM_UTF8):
chars = chars[3:].decode("utf-8")

This avoids hardcoding the BOM_UTF8, but its length is still hardcoded,
and the programmer had to know it or look it up when writing this line.

So my suggestion is to add another string method, say "stripstr" that
behaves like "strip", but instead of stripping *characters* strips
*strings* (similarly for lstrip and rstrip). Then in the case above,
you could simply write url = url.lstripstr('http://') or
url = url.lstripstr(('http://', 'https://')).

The new function would actually comprise the old strip function, you
would have strip('aeiou') == stripstr(set('aeio')).

Instead of a new function, we could also add another parameter to strip
(lstrip, rstrip) for passing strings or changing the behavior, or we
could create functions with the signature of startswith and endswith
which instead of only checking whether the string starts or ends with
the substring, remove the substring (startswith and endswith have
additional "start" and "end" index parameters that may be useful).

Or did I overlook anything and there is already a good idiom for this?

Btw, in most other languages, "strip" is called "trim" and behaves
like Python's strip, i.e. considers the parameter as a set of chars.
There is one notable exception: In MySQL, trim behaves like stripstr
proposed above (differently to SQLite, PostgreSQL and Oracle).

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


Re: MySQLdb will only import for root

2008-07-11 Thread Peter Otten
martinnorth wrote:

> Hi,
> 
> I am running Python and MySQL on Ubuntu and have installed MySQLdb. If I
> try to import MySQLdb I get the following error:
> 
> ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
> Python 2.5.2 (r252:60911, Mar 27 2008, 16:42:08)
> [GCC 3.3.1 (SuSE Linux)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import MySQLdb
> Traceback (most recent call last):
>File "", line 1, in 
> ImportError: No module named MySQLdb
> 
> But if I lrun python as the root user it imports fine. Can anyone
> suggest what might be wrong with the installation? Or is there nothing
> wrong? I haven't seen any examples that mentioned being root to import a
> module.

You have probably installed two versions of Python. You can verify that by
typing

$ which python

and

$ sudo which python

I suspect that root sees the python that comes with Ubuntu and that has
MySQLdb installed while the normal user sees ActiveState's Python. 

Peter

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


Re: MySQLdb will only import for root

2008-07-11 Thread Diez B. Roggisch

Jeff schrieb:

Is it possible the module was installed with priviledges set too
strict?  Perhaps the interpreter cannot see the module when it is run
from a normal user account.


Possible - certainly. Yet unrealistic, because usually root access is 
*required* to system-wide install a package - thus the normal install 
processes ensure proper rights.


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


Perfect hashing for Py

2008-07-11 Thread bearophileHUGS
Following links from this thread:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/179e1a45485ab36a#

I have found this perfect hash (minimal too) implementation:
http://burtleburtle.net/bob/hash/perfect.html

I have already translated part of it to D, and it seems to work well
enough. As discussed in the PyConDue, I think this may be used in
frozenset (and frozendict) to build a (minimal too?) perfect hash on
the fly, to allow (hopefully) faster retrieval of items that don't
change.
That code is C and I think it's public domain, so if experiments show
it gives enough speed up, it may be added to CPython 2.6/3.

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


Re: Python 3.0 and removal of the 'string' module

2008-07-11 Thread Benjamin
On Jul 11, 3:06 am, Ben Finney <[EMAIL PROTECTED]>
wrote:
> "Martin v. Löwis" <[EMAIL PROTECTED]> writes:
>
> > > This is rather disappointing. Is that entire page suspect?
>
> > All documentation about Python 3 is suspect until Python 3 gets
> > actually released (nobody can say for sure how the release will
> > look like in all details).
>
> Is there a better information source, then, for the current state of
> what's expected in Python 3.0?

Look at the development docs. We try to keep them up to date:
http://doc.python.org/dev/3.0
>
> --
>  \“Somebody told me how frightening it was how much topsoil we |
>   `\   are losing each year, but I told that story around the campfire |
> _o__) and nobody got scared.” —Jack Handey |
> Ben Finney

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


Re: strip() using strings instead of chars

2008-07-11 Thread Bruno Desthuilliers

Christoph Zwerschke a écrit :

In Python programs, you will quite frequently find code like the
following for removing a certain prefix from a string:

if url.startswith('http://'):
url = url[7:]


DRY/SPOT violation. Should be written as :

 prefix = 'http://'
 if url.startswith(prefix):
 url = url[len(prefix):]

(snip)


My problem with this is that it's cumbersome and error prone to count
the number of chars of the prefix or suffix.


cf above


If you want to change it
from 'http://' to 'https://', you must not forget to change the 7 to 8.
If you write len('http://')  instead of the 7, you see this is actually
a DRY problem.


cf above


Things get even worse if you have several prefixes to consider:

if url.startswith('http://'):
url = url[7:]
elif url.startswith('https://'):
url = url[8:]

You can't take use of url.startswith(('http://', 'https://')) here.


for prefix in ('http://', 'https://'):
if url.startswith(prefix):
url = url[len(prefix):]
break

For most complex use case, you may want to consider regexps, 
specifically re.sub:


>>> import re
>>> pat = re.compile(r"(^https?://|\.txt$)")
>>> urls = ['http://toto.com', 'https://titi.com', 'tutu.com', 
'file://tata.txt']

>>> [pat.sub('', u) for u in urls]
['toto.com', 'titi.com', 'tutu.com', 'file://tata']


Not to dismiss your suggestion, but I thought you might like to know how 
to solve your problem with what's currently available !-)


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


Re: using Python's AST generator for other languages

2008-07-11 Thread Benjamin
On Jul 11, 12:27 am, eliben <[EMAIL PROTECTED]> wrote:
> > > 2) What is the meaning of the comment in astgen.py ? Are the Python
> > > maintainers unhappy with the design of the AST ?3
>
> > Node, I think, is talking about a node in the parse tree. (AST is
> > generated from another parse tree.) See PEP 339 for details.
>
> 
>
> Thanks, PEP 339 clarified a lot to me. I wonder, though, at the need
> for two Python compilation frameworks in the same code base. While
> CPython uses the flow described in PEP 339 (parsing to an AST
> generated from ASDL), the compiler module of the standard library
> takes a different approach, with a custom AST description syntax in
> ast.txt
> Why aren't the two methods unified. I.e. can't the compiler.ast module
> be also generated from ASDL, and provide a more unified interface to
> the real thing ?

You are correct on all points and this is one of the main reasons that
the compiler package is going away in 3.0.
>
> Eli

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


Re: How to serialize and deserialize the objects into memory?

2008-07-11 Thread Gerhard Häring

hardemr wrote:

Hello Everyone,

I want to serialize and deserialize the objects into Memory not into
file. How can i do that?


You want to serialize the objects, but only keep them in memory? That 
hardly makes any sense. Serialization is need if you want to store your 
objects in a file or if you want to communicate (via network) with other 
processes.


-- Gerhard

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


Re: python scalability

2008-07-11 Thread Gerhard Häring

Tim Mitchell wrote:

Thanks for all the replies - they have all been helpful.

On reflection I think our problems are probably design and people related.


I strongly agree. "Scalability" is becoming a buzzword lately, which is 
meaningless unless qualified what exactly is meant.


It's overused wrt technologies, programming languages, tools, etc.

But in other interesting areas people think much less about "scalability".

Will the current software development process work with a team of 5, 10, 
20, 50 team members? Does it "scale" here?


Will the software development process still work with an increased 
turnover rate? Does it "scale"?


Will the way of doing things still work with an increasingly aging codebase?

-- Gerhard

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


Re: How to serialize and deserialize the objects into memory?

2008-07-11 Thread Inyeol . Lee
On Jul 11, 12:58 pm, hardemr <[EMAIL PROTECTED]> wrote:
> Hello Everyone,
>
> I want to serialize and deserialize the objects into Memory not into
> file. How can i do that?

pickle.dumps and pickle.loads.

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


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-11 Thread Tim Golden

Bill Davy wrote:
and since then have been busy with work, and my other job, and the garden. 


Aha! So you're English, are you? Looks like you're in the West Country.
Weather map suggests you're not short of rain over there :)

Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E etc 
etc but that's another story).  So any help today will be much appreciated.

Rgds,


Can't remember what the particular obstacles were you
were facing, but this runs OK on my setup -
Python 2.5.2 / pywin32 211 / Outlook 2003:


import os, sys
import win32com.client
constants = win32com.client.constants

def items (contacts):
 items = contacts.Items
 item = items.GetFirst ()
 while item:
   yield item
   item = items.GetNext ()

#
# Add whatever fields you like from:
# http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx
#
FIELDS = ['FullName', 'CompanyName', 'Email1Address']

outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
ns = outlook.GetNamespace ("MAPI")
for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)):
 if contact.Class == constants.olContact:
   print contact
   for field in FIELDS:
 print "  ", field, "=>", getattr (contact, field, "")



Hope that helps.
TJG
--
http://mail.python.org/mailman/listinfo/python-list


read file into list of lists

2008-07-11 Thread antar2
Hello,

I can not find out how to read a file into a list of lists. I know how
to split a text into a list

sentences = line.split(\n)

following text for example should be considered as a list of lists (3
columns and 3 rows), so that when I make the print statement list[0]
[0], that the word pear appears


pear noun singular
books nouns plural
table noun singular

Can someone help me?

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


Re: ANN: P4D 1.1

2008-07-11 Thread Fuzzyman
On Jul 11, 10:09 am, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> P4D = E4X style embedded DSL for Python but without E and X.
>
> For more information see:
>
> http://pypi.python.org/pypi/P4D/1.1-py2.5

That looks a lot like YAML. Any reason to use it over YAML?

Michael Foord
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: read file into list of lists

2008-07-11 Thread Laurent Rahuel
Hello,

A way to do it

===
from __future__ import with_statement

res = []
with open("sentences.txt","r") as f:
  sentences = [elem for elem in f.read().split('\n') if elem]
  for sentence in sentences:
res.append(sentence.split())

print res
===

antar2 wrote:

> Hello,
> 
> I can not find out how to read a file into a list of lists. I know how
> to split a text into a list
> 
> sentences = line.split(\n)
> 
> following text for example should be considered as a list of lists (3
> columns and 3 rows), so that when I make the print statement list[0]
> [0], that the word pear appears
> 
> 
> pear noun singular
> books nouns plural
> table noun singular
> 
> Can someone help me?
> 
> Thanks
pear noun singular
books nouns plural
table noun singular--
http://mail.python.org/mailman/listinfo/python-list

Re: read file into list of lists

2008-07-11 Thread bockman
On 11 Lug, 15:15, antar2 <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I can not find out how to read a file into a list of lists. I know how
> to split a text into a list
>
> sentences = line.split(\n)
>
> following text for example should be considered as a list of lists (3
> columns and 3 rows), so that when I make the print statement list[0]
> [0], that the word pear appears
>
> pear noun singular
> books nouns plural
> table noun singular
>
> Can someone help me?
>
> Thanks


You can use split again, using ' ' or nothing(defaults to whitespace
characters) as separator,
like this:

>>> text = """pear noun singular
books nouns plural
table noun singular"""

>>> words = [ x.split() for x in text.split('\n') ]
>>> print words
[['pear', 'noun', 'singular', ''], ['books', 'nouns', 'plural', ''],
['table', 'noun', 'singular']]


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


Re: MySQLdb will only import for root

2008-07-11 Thread Jeffrey Froman
Diez B. Roggisch wrote:

>> Is it possible the module was installed with priviledges set too
>> strict?  Perhaps the interpreter cannot see the module when it is run
>> from a normal user account.
> 
> Possible - certainly. Yet unrealistic, because usually root access is
> required to system-wide install a package - thus the normal install
> processes ensure proper rights.

According to the OP, it is root that *does* have access to MySQLdb and a
normal user that does not. It is a very realistic possibility to install
something as root to which normal users do not have access. Installation
scripts that assume a particular umask during install, for example, are
especial culprits.

I have noticed this problem myself with python modules that include compiled
C extensions, as MySQLdb does. However, in the case where the extension
module itself has incorrect permissions, the error would point to a missing
_mysql, rather than a missing MySQLdb.


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

Pickle and wx.TextCtrl

2008-07-11 Thread DWebre


Trying to read a pickled filed and list contents.

The attached program works using pprint, but I want to write to my frame.
WriteText only produces half of the records.

What is happening?


(See attached file: ReadDB_b.py)


D. J. Webre, Jr. PE & PLS
Director of  Engineering & Technical Support
LA DOTD, Office of Public Works, Hurricane Flood Protection & Intermodal
Transportation
8900 Jimmy Wedell Dr.  Rm 215
Baton Rouge, LA  70807

http://www.dotd.louisiana.gov/sitemap.asp?ID=8
(225) 274-4339  e-mail: [EMAIL PROTECTED]
(225) 274-4322 Fac

ReadDB_b.py
Description: Binary data
--
http://mail.python.org/mailman/listinfo/python-list

Re: read file into list of lists

2008-07-11 Thread Paddy
On Jul 11, 2:15 pm, antar2 <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I can not find out how to read a file into a list of lists. I know how
> to split a text into a list
>
> sentences = line.split(\n)
>
> following text for example should be considered as a list of lists (3
> columns and 3 rows), so that when I make the print statement list[0]
> [0], that the word pear appears
>
> pear noun singular
> books nouns plural
> table noun singular
>
> Can someone help me?
>
> Thanks

lofl = [line.strip().split() for line in the_opened_file]

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


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-11 Thread Bill Davy
"Tim Golden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Bill Davy wrote:
>> and since then have been busy with work, and my other job, and the 
>> garden.
>
> Aha! So you're English, are you? Looks like you're in the West Country.
> Weather map suggests you're not short of rain over there :)
>
>> Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E 
>> etc etc but that's another story).  So any help today will be much 
>> appreciated.
>> Rgds,
>
> Can't remember what the particular obstacles were you
> were facing, but this runs OK on my setup -
> Python 2.5.2 / pywin32 211 / Outlook 2003:
>
> 
> import os, sys
> import win32com.client
> constants = win32com.client.constants
>
> def items (contacts):
>  items = contacts.Items
>  item = items.GetFirst ()
>  while item:
>yield item
>item = items.GetNext ()
>
> #
> # Add whatever fields you like from:
> # http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx
> #
> FIELDS = ['FullName', 'CompanyName', 'Email1Address']
>
> outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
> ns = outlook.GetNamespace ("MAPI")
> for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)):
>  if contact.Class == constants.olContact:
>print contact
>for field in FIELDS:
>  print "  ", field, "=>", getattr (contact, field, "")
>
> 
>
> Hope that helps.
> TJG


jUST IN CASE,. i CUT'NPASTED THE PROGRAM:

import os, sys
import win32com.client
constants = win32com.client.constants

def items (contacts):
  items = contacts.Items
  item = items.GetFirst ()
  while item:
yield item
item = items.GetNext ()

#
# Add whatever fields you like from:
# http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx
#
FIELDS = ['FullName', 'CompanyName', 'Email1Address']

outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
ns = outlook.GetNamespace ("MAPI")
for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)):
  if contact.Class == constants.olContact:
print contact
for field in FIELDS:
  print "  ", field, "=>", getattr (contact, field, "")

---
And then I ran it:

Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] 
on win32
Type "copyright", "credits" or "license()" for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 1.2.2
>>>  RESTART 
>>> 
>>>

Traceback (most recent call last):
  File "H:/Personal/OutlookIF1/t2.py", line 18, in 
outlook = win32com.client.gencache.EnsureDispatch 
("Outlook.Application")
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
536, in EnsureDispatch
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], 
bForDemand=bForDemand)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
393, in EnsureModule
module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
262, in GetModuleForTypelib
AddModuleToCache(typelibCLSID, lcid, major, minor)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
554, in AddModuleToCache
dict = mod.CLSIDToClassMap
AttributeError: 'module' object has no attribute 'CLSIDToClassMap'
>>>

-

Outlook is running fine.

This is how the fucntion where the failure occurs begins:

def AddModuleToCache(typelibclsid, lcid, major, minor, verbose = 1, 
bFlushNow = not is_readonly):
 """Add a newly generated file to the cache dictionary.
 """
 fname = GetGeneratedFileName(typelibclsid, lcid, major, minor)
 mod = _GetModule(fname)
 # if mod._in_gencache_ is already true, then we are reloading this
 # module - this doesn't mean anything special though!
 mod._in_gencache_ = 1
 dict = mod.CLSIDToClassMap
 info = str(typelibclsid), lcid, major, minor
 for clsid, cls in dict.items():
  clsidToTypelib[clsid] = info

---

Yes, we have suffiicient rain but the gaden needed it.  I am about to become 
the proud tenant of half an allotment.  Still, this time last year we had 
floods.

TIA,
   Bill 


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


Re: read file into list of lists

2008-07-11 Thread Gerard flanagan

antar2 wrote:

Hello,

I can not find out how to read a file into a list of lists. I know how
to split a text into a list

sentences = line.split(\n)

following text for example should be considered as a list of lists (3
columns and 3 rows), so that when I make the print statement list[0]
[0], that the word pear appears


pear noun singular
books nouns plural
table noun singular

Can someone help me?




class Table(object):

def __init__(self, text=None):
self.rows = []
if text:
self.write(text)

def write(self, text):
self.rows.extend(line.split() for line in text.splitlines())

def read(self):
return '\n'.join(' '.join(row) for row in self.rows)

def __getitem__(self, i):
return self.rows[i]

def __iter__(self):
return iter(self.rows)

table = Table()

table.write('apple orange coconut')

print table[0][1]

print table.read()

table.write('clematis rose lily')

print table[1][2]

print table.read()


for row in table:
print row



(If you have quoted items, it is more difficult)

G.

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


Re: Python 3.0 and removal of the 'string' module

2008-07-11 Thread John Roth
On Jul 11, 6:26 am, Benjamin <[EMAIL PROTECTED]> wrote:
> On Jul 11, 3:06 am, Ben Finney <[EMAIL PROTECTED]>
> wrote:
>
> > "Martin v. Löwis" <[EMAIL PROTECTED]> writes:
>
> > > > This is rather disappointing. Is that entire page suspect?
>
> > > All documentation about Python 3 is suspect until Python 3 gets
> > > actually released (nobody can say for sure how the release will
> > > look like in all details).
>
> > Is there a better information source, then, for the current state of
> > what's expected in Python 3.0?
>
> Look at the development docs. We try to keep them up to 
> date:http://doc.python.org/dev/3.0
>
>
>
> > --
> >  \        “Somebody told me how frightening it was how much topsoil we |
> >   `\   are losing each year, but I told that story around the campfire |
> > _o__)                             and nobody got scared.” —Jack Handey |
> > Ben Finney
>
>

The PEPs are also a good source; library changes are all listed in PEP
3008. PEP 361 not only gives the schedule but it also gives a lot of
detail on 3.0 features backported to 2.6 and incompatible features
that raise warnings in 3.0

PEP 3000, PEP 3100 and PEP 3099 are also well worth reviewing.

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


Re: Unit Testing Techniques

2008-07-11 Thread Matthew Fitzgibbons

I'm by no means a testing expert, but I'll take a crack at it.

Casey McGinty wrote:
I'm familiar with the unittest module in Python, however I'm hoping 
someone can point me to some examples of more advanced usages of the 
framework. For example:


1. Using the framework to test a package with nested sub-packages and 
modules without having to hard code the location/name of each test module.

I've never run into this.

2. Testing class/methods that depend on file system directory 
structures, file data, or values read from system hardware.
Rule of thumb: always separate software from hardware. Write mock 
classes or functions that do your hardware/file access that always 
return known data (but remember to test for alpha and beta errors--make 
sure both valid and invalid data are handled correctly). That way you 
can test the client code that is accessing the hardware.


Testing the actual hardware/file access code can get more interesting. 
If you're just reading files, your test suite should write the test 
files in setUp, try to read them in the test* methods, then clean up in 
tearDown. Again, remember to test both good and bad files.


In my shop, we do both hardware and software, and testing the comms 
between them can be a real pain. We've done lots of interesting things 
like wiring faults into the hardware with switches to connect and 
disconnect them, recording command sequences, etc., but I expect this is 
beyond the scope of what you're interested in. Just keep in mind that 
testing a chunk of code requires at least as much creativity as writing 
the code in the first place.


3. Testing class/methods that require simulating functionality from 
imported modules.

You can do neat things like this:

import unittest
import mymodule

def my_mock_function():
"""Returns known values."""


class MyTest(unittest.TestCase):
def setUp(self):
self._orig_function = mymodule.function
mymodule.function = my_mock_function

def tearDown(self):
# remember to restore the original function
# unittest doesn't re-import modules
mymodule.function = self._orig_function

def test1(self):
"""Test some code that uses mymodule."""

# etc...

The dynamic nature of Python makes this sort of thing much easier than 
other languages.



4. Testing graphical interfaces and associated signal callback functions.
Again, there are lots of strategies you can use; the specifics depend on 
you design and the toolkit.


1) You can mock the backend: make sure the right functions get called in 
response the user actions.

2) Simulate user actions by manually posting events, calling functions, etc.
3) Mock the gui: make sure the backend is calling all the right GUI 
functions.


Try to keep your backend and gui as independent as possible, it will 
make testing much easier.




Thank you.




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


I typically make a bunch of different suites that can be run 
individually, in various combinations, or all together. Testing I/O 
tends to be very slow, so it's nice to be able to turn of these tests 
when you're working on other parts of the system.


There are many other testing tools besides unittest. The one I use the 
most is coverage.py, to determine if my test suites are hitting all my 
code. But you can check out pymock, doctest, nose, etc. too. You may 
have to use a combination of tools to meet your needs.


There is also the Testing in Python mailing list 
(http://lists.idyll.org/listinfo/testing-in-python). You can probably 
get some advice there as well. The more specifics you can give, the better.


As you solve your testing problems, please take the time to post your 
solutions (if you can) so we can all learn from your experiences.


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


Re: strip() using strings instead of chars

2008-07-11 Thread Christoph Zwerschke

Bruno Desthuilliers schrieb:

DRY/SPOT violation. Should be written as :

 prefix = 'http://'
 if url.startswith(prefix):
 url = url[len(prefix):]


That was exactly my point. This formulation is a bit better, but it 
still violates DRY, because you need to type "prefix" two times. It is 
exactly this idiom that I see so often and that I wanted to simplify. 
Your suggestions work, but I somehow feel such a simple task should have 
a simpler formulation in Python, i.e. something like


url = url.lstripstr(('http://', 'https://'))

instead of

for prefix in ('http://', 'https://'):
if url.startswith(prefix):
url = url[len(prefix):]
break

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


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-11 Thread Tim Golden

Bill Davy wrote:

Traceback (most recent call last):
  File "H:/Personal/OutlookIF1/t2.py", line 18, in 
outlook = win32com.client.gencache.EnsureDispatch 
("Outlook.Application")
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
536, in EnsureDispatch
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], 
bForDemand=bForDemand)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
393, in EnsureModule

module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
262, in GetModuleForTypelib

AddModuleToCache(typelibCLSID, lcid, major, minor)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
554, in AddModuleToCache

dict = mod.CLSIDToClassMap
AttributeError: 'module' object has no attribute 'CLSIDToClassMap'



Just in case, could you delete the contents of your gen_py
directory (probably in %TEMP%\gen_py)

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


Re: strip() using strings instead of chars

2008-07-11 Thread Marc 'BlackJack' Rintsch
On Fri, 11 Jul 2008 16:45:20 +0200, Christoph Zwerschke wrote:

> Bruno Desthuilliers schrieb:
>> DRY/SPOT violation. Should be written as :
>> 
>>  prefix = 'http://'
>>  if url.startswith(prefix):
>>  url = url[len(prefix):]
> 
> That was exactly my point. This formulation is a bit better, but it 
> still violates DRY, because you need to type "prefix" two times. It is 
> exactly this idiom that I see so often and that I wanted to simplify. 
> Your suggestions work, but I somehow feel such a simple task should have 
> a simpler formulation in Python, i.e. something like
> 
> url = url.lstripstr(('http://', 'https://'))

I would prefer a name like `remove_prefix()` instead of a variant with
`strip` and abbreviations in it.

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


Re: read file into list of lists

2008-07-11 Thread Jeffrey Froman
Laurent Rahuel wrote that antar2 wrote:

>> following text for example should be considered as a list of lists (3
>> columns and 3 rows), so that when I make the print statement list[0]
>> [0], that the word pear appears
>> 
>> 
>> pear noun singular
>> books nouns plural
>> table noun singular

File objects are themselves iterable, returning one line per iteration. So a
simple approach is:

>>> table = [line.split() for line in open('sentences.txt')]
>>> table[0][0]
'pear'


Jeffrey

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


decorator to prevent adding attributes to class?

2008-07-11 Thread Neal Becker
After spending the morning debugging where I had misspelled the name of an
attribute (thus adding a new attr instead of updating an existing one), I
would like a way to decorate a class so that attributes cannot be (easily)
added.

I guess class decorators are not available yet (pep 3129), but probably
inheritance can be used.

Can anyone suggest an implementation?

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


Editra

2008-07-11 Thread Henry Read
Editra is a multi-platform text editor with an implementation that focuses
on creating an easy to use interface and features that aid in code
development. Currently it supports syntax highlighting and variety of other
useful features for over 60 programming languages.

Editra is freely available under the terms of the wxWindows
Licence.


Currently the project is in the alpha development phase but test builds of
"stable" points are available for download and trial as Windows and Mac
OSX(Universal) binaries, currently other Unix and Linux based systems will
have to install from source using the included setup script. Please feel
free give it a try and to report bugs and request features.

*Editra*.org | News 
It is a good editor for Python, also it is small.It can also support auto
completion with Python modules.
It is suitable for Python beginners.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Editra

2008-07-11 Thread Henry Read
It has been already in wxpython-doc-demos package.

On Fri, Jul 11, 2008 at 11:38 PM, Henry Read <[EMAIL PROTECTED]> wrote:

> Editra is a multi-platform text editor with an implementation that focuses
> on creating an easy to use interface and features that aid in code
> development. Currently it supports syntax highlighting and variety of other
> useful features for over 60 programming languages.
>
> Editra is freely available under the terms of the wxWindows 
> Licence.
>
>
> Currently the project is in the alpha development phase but test builds of
> "stable" points are available for download and trial as Windows and Mac
> OSX(Universal) binaries, currently other Unix and Linux based systems will
> have to install from source using the included setup script. Please feel
> free give it a try and to report bugs and request features.
>
> *Editra*.org | News 
> It is a good editor for Python, also it is small.It can also support auto
> completion with Python modules.
> It is suitable for Python beginners.
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: decorator to prevent adding attributes to class?

2008-07-11 Thread Michele Simionato
On Jul 11, 5:29 pm, Neal Becker <[EMAIL PROTECTED]> wrote:
> After spending the morning debugging where I had misspelled the name of an
> attribute (thus adding a new attr instead of updating an existing one), I
> would like a way to decorate a class so that attributes cannot be (easily)
> added.
>
> I guess class decorators are not available yet (pep 3129), but probably
> inheritance can be used.
>
> Can anyone suggest an implementation?

This article could give you same idea (it is doing the opposite,
warning you
if an attribute is overridden):
http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1/

There is also a recipe that does exactly what you want by means of a
metaclass:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158
It is so short I can write it down here:
# requires Python 2.2+

def frozen(set):
"Raise an error when trying to set an undeclared name."
def set_attr(self,name,value):
if hasattr(self,name):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" %
self)
return set_attr

class Frozen(object):
"""Subclasses of Frozen are frozen, i.e. it is impossibile to add
 new attributes to them and their instances."""
__setattr__=frozen(object.__setattr__)
class __metaclass__(type):
__setattr__=frozen(type.__setattr__)

Of course using frozen classes is not Pythonic at all, and I wrote the
recipe as
a proof of concept, not to use it.

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


Re: Weird lambda rebinding/reassignment without me doing it

2008-07-11 Thread David C. Ullrich
In article <[EMAIL PROTECTED]>,
 Terry Reedy <[EMAIL PROTECTED]> wrote:

> David C. Ullrich wrote:
> > In article 
> > <[EMAIL PROTECTED]>,
> >  ssecorp <[EMAIL PROTECTED]> wrote:
> > 
> >> I am never redefining the or reassigning the list when using validate
> >> but since it spits the modified list back out that somehow means that
> >> the modified list is part of the environment and not the old one.
> >> i thought what happend inside a function stays inside a function
> >> meaning what comes out is independent of what comes in.
> >> Meaning if I want the list I send as a parameter to the function I
> >> have to do x = func(x) and not just func(x) and x is magically what
> >> comes out of func().
> > 
> > A function cannot modify the value of a global variable
> 
> Yes it can.
>  >>> a=[]
>  >>> def f():
>   a.append('yes I can')
> 
>  >>> f()
>  >>> a
> ['yes I can']
> 
> > (unless it specifies "global"). It doesn't reassign anything.
> 
> The statement 'global a' would allow f to *rebind* the global *name* 
> 'a'. 

Aargh. That's exactly what I meant, sorry. 

> The word 'variable' should almost not be used in discussing Python 
> since it is often unclear whether it refers to a name (or collection 
> slot) or an object bound thereto.

Indeed. Which is exactly why I included those snippets of
code that you snipped, one of which does exactly what your
snippet above does... you're probably right, "variable" is
a bad idea, and "modify the value of a variable" is a very
bad idea.

The code doesn't "modify the value of the variable" in the
sense that the value of the variable is a certain object,
and after the function call the value is the same object.
It does "modify the value of the variable" in the sense
that the object which is the value of the variable has been
modified.

There's a problem here. Please note that this is not a criticism,
and I don't really know what anyone could do about the problem.
The problem is that if the reader is not accustomed to thinking
explicitly about what's going on under the hood when code is
executed he's going to have a hard time understanding the
difference between "assigning a value to a variable" and
"binding a name to an object". Once I realized that dicts
rule everything this became clear to me, but for some time
the discussions I saw on all this made no sense to me.

Which is why I think it's a good idea to include examples
illustrating what can and cannot be done, which is why I
did that. I tend to suspect that the OP is at least as 
confused on the subtlties as I was back then (evidence below).

> > But in the functions below you're not reassigning a variable,
> > you're _modifiying_ an object. A function _can_ modify an
> > object you pass to it:
> 
> It can modify any mutable object it can access.
> 
> >> Doesnt Python have closure or that isnt what this is about?
> 
> Python does have closures.  This is not about that.

This is why I suspect what I say I suspect. He's thought
that the word "closure" meant something like "local scope"...

> >> def validate(placed):
> >> student = round(random.random()*401)
> >> if student in placed:
> >> return validate(placed)
> >> else:
> >> placed.append(student)
> >> return student, placed
> 
> Delete this. It is redundant with the below.
> 
> >> def val(placed):
> >> student = round(random.random()*401)
> >> if student in placed:
> >> return validate(placed)
> >> else:
> >> placed.append(student)
> >> return student
> 
> I believe this is equivalent to
> 
> def addval(placed):
>while True:
>  student = round(random.random()*401)
>  if student not in placed:
>break
>placed.append(student)
>return student
> 
> While this avoids the indefinite recursion depth problem, it does not 
> avoid the indefinite time problem.  Use random.shuffle, or write your 
> own version if doing this for practice.  Also consider removing the 
> return statement unless you actually directly use the added value.  It 
> is easier to remember that addval mutates 'placed' without the return.
> 
> > g = lambda x:validate(x)
> 
> This is doubly diseased.
> 
> First, never write a 'name = lambda...' statement since it is equivalent 
> to a def statement except that the resulting function object lacks a 
> proper .funcname attribute.  The above only trivially abbreviates
>def g(x): return validate(x)
> by 3 characters.  Another reason is that the lambda form somehow more 
> often tricks people into the next mistake .
> 
> Second, never write a function (with either def or lambda) that simply 
> returns a function of the argument(s).  The wrapping does nothing!  This 
> is a waste of time and space for both you and the interpreter.  The 
> above is functionally equivalent to
>g = validate
> and if you want that, you could name the function 'g' when you define it.
> 
> > l=[]
> In some fonts, 'l' and '1' are nearly identical; please use s

Re: Weird lambda rebinding/reassignment without me doing it

2008-07-11 Thread David C. Ullrich
In article 
<[EMAIL PROTECTED]>,
 ssecorp <[EMAIL PROTECTED]> wrote:

> >>> def mod(x,y):
>   return x.append(y)
> 
> >>> mod([1,2],3)
> >>> k=[1,2,3]
> >>> k
> [1, 2, 3]
> >>> l = mod(k,4)
> >>> l
> >>> k
> [1, 2, 3, 4]
> >>> l
> >>> k==l
> False
> >>> mod(k,5)
> >>> k
> [1, 2, 3, 4, 5]
> >>> mod(l,4)
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> mod(l,4)
>   File "", line 2, in mod
> return x.append(y)
> AttributeError: 'NoneType' object has no attribute 'append'
> >>> l
> >>> l=k
> >>> l
> [1, 2, 3, 4, 5]
> >>> i=mod(k,1)
> >>> i
> >>>
> 
> same stuff but i dont find this intuitive.

You need to read the docs. AList.append(x) does _not_
return AList with x appended. In fact it returns None,
because it wants to be a "procedure" that doesn't return
anything at all, but there is no such thing in Python;
functions and methods that do not explicitly contain
a "return" statement return None.

So when you say "return x.append(a)" you're saying
"return None", which explains the rest of it. You
noticed that the second line of

> >>> l = mod(k,4)
> >>> l

didn't print anything? That's because the first line
set l to None. If you'd typed "print l" instead of just "l"
you would have seen

>>> l = mod(k,4)
>>> l
>>> None

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


Re: decorator to prevent adding attributes to class?

2008-07-11 Thread Robert Bossy

Michele Simionato wrote:

This article could give you same idea (it is doing the opposite,
warning you
if an attribute is overridden):
http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1/

There is also a recipe that does exactly what you want by means of a
metaclass:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158
It is so short I can write it down here:
# requires Python 2.2+

def frozen(set):
"Raise an error when trying to set an undeclared name."
def set_attr(self,name,value):
if hasattr(self,name):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" %
self)
return set_attr

class Frozen(object):
"""Subclasses of Frozen are frozen, i.e. it is impossibile to add
 new attributes to them and their instances."""
__setattr__=frozen(object.__setattr__)
class __metaclass__(type):
__setattr__=frozen(type.__setattr__)
  
I don't get it. Why use a metaclass? Wouldn't the following be the same, 
but easier to grasp:


class Frozen(object):
   def __setattr__(self, name, value):
  if not hasattr(self, name):
 raise AttributeError, "cannot add attributes to %s" % self
  object.__setattr__(self, name, value)

Btw, the main drawback with Frozen is that it will not allow to set any 
new attributes even inside __init__.



Some people would advise to use __slots__:
   http://docs.python.org/ref/slots.html#l2h-222
Some other people would advise NOT to use __slots__:
   http://groups.google.com/group/comp.lang.python/msg/0f2e859b9c002b28



Personally, if I must absolutely, I'd go for explicitely freeze the 
object at the end of __init__:


class Freezeable(object):
   def freeze(self):
  self._frozen = None

   def __setattr__(self, name, value):
  if hasattr(self, '_frozen') and not hasattr(self, name):
 raise AttributeError
  object.__setattr__(self, name, value)


class Foo(Freezeable):
   def __init__(self):
  self.bar = 42
  self.freeze() # ok, we set all variables, no more from here


x = Foo()
print x.bar
x.bar = -42
print x.bar
x.baz = "OMG! A typo!"


Cheers,
RB
--
http://mail.python.org/mailman/listinfo/python-list


Using the Random Module.

2008-07-11 Thread WDC
I am currently learning, and loving, Python and have a question about
random().

Right now, what I have to do to get a whole number and not a decimal
using random.random() is this:

>>>random.random()
0.84765728501856734
>>>_ * 10**17
84765728501856734.0

Is there a better way to do that besides doing this:

>>>random.randint(0, 9)
09657398671238769

Thanks for your time.

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


Using SWIG to build C++ extension

2008-07-11 Thread mk

Hello,

I'm having terrible problems building C++ extension to Python 2.4 using 
SWIG. I'd appreciate if somebody knowledgeable at the subject took a 
look at it. swig-1.3.29, g++ (GCC) 4.1.1 20070105 (Red Hat 4.1.1-52).


I used following commands to build C++ extension:

# swig -c++ -python edit_distance.i
# c++ -c edit_distance.c edit_distance_wrap.cxx edit_distance.cpp -I. 
-I/usr/include/python2.4



Linux RH (9.156.44.105) root ~/tmp # c++ -c edit_distance.c 
edit_distance_wrap.cxx edit_distance.cpp -I. -I/usr/include/python2.4

c++: edit_distance.cpp: No such file or directory
edit_distance_wrap.cxx: In function ‘PyObject* 
_wrap_edit_distance(PyObject*, PyObject*)’:

edit_distance_wrap.cxx:2579: error: ‘string’ was not declared in this scope
edit_distance_wrap.cxx:2579: error: ‘arg1’ was not declared in this scope
edit_distance_wrap.cxx:2580: error: ‘arg2’ was not declared in this scope
edit_distance_wrap.cxx:2597: error: expected type-specifier before ‘string’
edit_distance_wrap.cxx:2597: error: expected `>' before ‘string’
edit_distance_wrap.cxx:2597: error: expected `(' before ‘string’
edit_distance_wrap.cxx:2597: error: expected primary-expression before 
‘>’ token

edit_distance_wrap.cxx:2597: error: expected `)' before ‘;’ token
edit_distance_wrap.cxx:2605: error: expected type-specifier before ‘string’
edit_distance_wrap.cxx:2605: error: expected `>' before ‘string’
edit_distance_wrap.cxx:2605: error: expected `(' before ‘string’
edit_distance_wrap.cxx:2605: error: expected primary-expression before 
‘>’ token

edit_distance_wrap.cxx:2605: error: expected `)' before ‘;’ token

What's weird is that I _did_ use std:: namespace prefix carefully in the 
code:


#include 
#include 
#include 

 const unsigned int cost_del = 1;
 const unsigned int cost_ins = 1;
 const unsigned int cost_sub = 1;


 unsigned int edit_distance( std::string& s1, std::string& s2 )
 {
const size_t len1 = s1.length(), len2 = s2.length();
std::vector > d(len1 + 1, 
std::vector(len2 + 1));


for(int i = 1; i <= len1; ++i)
for(int j = 1; j <= len2; ++j)
d[i][j] = std::min(d[i - 1][j] + 1, 
std::min(d[i][j - 1] + 1, d[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 
: 1)));


return d[len1][len2];
}

Ok, anyway I fixed it in the generated code (edit_distance_wrap.cxx). It 
compiled to .o file fine then. It linked to _edit_distance.so as well:


# c++ -shared edit_distance_wrap.o -o _edit_distance.so

But now I get import error in Python!

Linux RH root ~/tmp # python
Python 2.4.3 (#1, Dec 11 2006, 11:38:52)
[GCC 4.1.1 20061130 (Red Hat 4.1.1-43)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import edit_distance
Traceback (most recent call last):
  File "", line 1, in ?
  File "edit_distance.py", line 5, in ?
import _edit_distance
ImportError: ./_edit_distance.so: undefined symbol: _Z13edit_distanceRSsS_



What did I do to deserve this? :-)


edit_distance.i file just in case:

%module edit_distance
%{
#include "edit_distance.h"
%}

extern unsigned int edit_distance(string& s1, string& s2);





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


Re: decorator to prevent adding attributes to class?

2008-07-11 Thread Michele Simionato
On Jul 11, 6:38 pm, Robert Bossy
> I don't get it. Why use a metaclass? Wouldn't the following be the same,
> but easier to grasp:
>
> class Frozen(object):
>     def __setattr__(self, name, value):
>        if not hasattr(self, name):
>           raise AttributeError, "cannot add attributes to %s" % self
>        object.__setattr__(self, name, value)

This is easier, but it does not stop the user from
adding class level attributes: this is the job
of the metaclass. If you don't care about
class level attributes (including methods,
properties, etc) and you are content with restricting
only the instance attributes your recipe is fine, yes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to functional programming

2008-07-11 Thread craig75
On Jul 11, 3:36 am, [EMAIL PROTECTED] wrote:
> James Fassett:
>
> > # the first Pythonic attempt using comprehensions
> > result_list = [x[0] for x in tuple_list]
>
> > # the final functional way
> > [result_list, _] = zip(*tuple_list)
>
> > I really like how Python allows me to do what I feel is the most
> > natural solution (for a seasoned procedural programmer) while allowing
> > a satisfying path towards a more functional approach.
>
> The list comprehension is quite more readable to me, so I suggest you
> to use it. It's probably the default way to do it in Python.
>
> If you want functional code this is another way (I have not tested the
> relative performance but it may be quick):
>
> >>> tuple_list = (
>
> ...     ('John', 'Doe'),
> ...     ('Mark', 'Mason'),
> ...     ('Jeff', 'Stevens'),
> ...     ('Bat', 'Man')
> ...   )>>> from operator import itemgetter
> >>> map(itemgetter(0), tuple_list)
>
> ['John', 'Mark', 'Jeff', 'Bat']
>
> Bye,
> bearophile


Functional programmers love pattern matching (which I think makes the
code much easier to understand):

[x for (x,y) in tuple_list]

or

map(lambda (x,y):x, tuple_list)

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


Re: Using SWIG to build C++ extension

2008-07-11 Thread mk


And what's infuriating is that the .o files do contain the necessary symbol:

# grep _Z13edit_distanceRSsS_ *
Binary file edit_distance.o matches
Binary file _edit_distance.so matches
Binary file edit_distance_wrap.o matches

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


spam

2008-07-11 Thread rickman
spam
--
http://mail.python.org/mailman/listinfo/python-list


Re: strip() using strings instead of chars

2008-07-11 Thread Duncan Booth
Christoph Zwerschke <[EMAIL PROTECTED]> wrote:

> In Python programs, you will quite frequently find code like the
> following for removing a certain prefix from a string:
> 
> if url.startswith('http://'):
>  url = url[7:]

If I came across this code I'd want to know why they weren't using 
urlparse.urlsplit()...

> 
> Similarly for stripping suffixes:
> 
> if filename.endswith('.html'):
>  filename = filename[:-5]

... and I'd want to know why os.path.splitext() wasn't appropriate here.

> 
> My problem with this is that it's cumbersome and error prone to count
> the number of chars of the prefix or suffix. If you want to change it
> from 'http://' to 'https://', you must not forget to change the 7 to 8.
> If you write len('http://')  instead of the 7, you see this is actually
> a DRY problem.
> 
> Things get even worse if you have several prefixes to consider:
> 
> if url.startswith('http://'):
>  url = url[7:]
> elif url.startswith('https://'):
>  url = url[8:]
> 
> You can't take use of url.startswith(('http://', 'https://')) here.
> 
No you can't, so you definitely want to be parsing the URL properly. I 
can't actually think of a use for stripping off the scheme without either 
saving it somewhere or doing further parsing of the url.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python with Ecmascript

2008-07-11 Thread Alan Isaac

NJSModule?
http://en.wikipedia.org/wiki/NJS



Daniel Fetchinson wrote: 

This seems to be very good indeed. Just downloaded njs but the only
njsmodule version I could find was for python 2.1. Does anyone have a
recent copy?


1. You might ask here:
http://lists.njs-javascript.org/cgi-bin/mailman/listinfo/users

2. Did you try to compile it?
Is there anything obviously 2.5 incompatible?

Cheers,
Alan Isaac
--
http://mail.python.org/mailman/listinfo/python-list


Re: ActiveState Code: the new Python Cookbook site

2008-07-11 Thread Trent Mick

Peter Otten wrote:

Thin Myrna wrote:


The old cookbook offered choices by category. Did you drop that feature?


Looks like categories have become tags:

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


Yes, that is correct. I should document the tag names to category 
mapping that I've used (mostly a straightforward "remove spaces and 
capitalization" thing).


My hope is that allowing free form tagging and (importantly) multiple 
tags will allow for more interesting and useful grouping.


However, there is value in there being good suggestions of common tags 
when adding tags. I need to add that to the recipe add form:


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


Trent

--
Trent Mick
trentm at activestate.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using the Random Module.

2008-07-11 Thread Michiel Overtoom
You wrote...

>Is there a better way to do that besides doing this:
>
random.randint(0, 9)
>09657398671238769

Maybe this?

random.randint(0, 9e16)


-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

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


Re: Moving to functional programming

2008-07-11 Thread sturlamolden
On Jul 11, 12:00 pm, James Fassett <[EMAIL PROTECTED]> wrote:

> tuple_list = (
>     ('John', 'Doe'),
>     ('Mark', 'Mason'),
>     ('Jeff', 'Stevens'),
>     ('Bat', 'Man')
>   )
>
> # what I'd do in C or other procedural languages
> result_list = []
> for item in tuple_list:
>     result_list.append(item[0])

Here are some various 'functional' solutions. Pick the one that fits
your problem best:

result_list = [fn for fn,ln in tuple_list]

result_generator = (fn for fn,ln in tuple_list)

result_list = map(lambda (fn,ln): fn, result_list)

result_generator = itertools.imap(lambda (fn,ln): fn, result_list)


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


Re: Using the Random Module.

2008-07-11 Thread WDC
On Jul 11, 2:15 pm, Michiel Overtoom <[EMAIL PROTECTED]> wrote:
> You wrote...
> >Is there a better way to do that besides doing this:
>
> random.randint(0, 9)
> >09657398671238769
>
> Maybe this?
>
>         random.randint(0, 9e16)
>
> --
> "The ability of the OSS process to collect and harness
> the collective IQ of thousands of individuals across
> the Internet is simply amazing." - Vinod 
> Vallopillilhttp://www.catb.org/~esr/halloween/halloween4.html

That would work yes, but is there a random() function that would do
that without the attributes? Not trying to be lazy, I just want to
know if there is a built in way.

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


Re: Python with Ecmascript

2008-07-11 Thread Daniel Fetchinson
>>>NJSModule?
>>>http://en.wikipedia.org/wiki/NJS
>
>> This seems to be very good indeed. Just downloaded njs but the only
>> njsmodule version I could find was for python 2.1. Does anyone have a
>> recent copy?
>
> 1. You might ask here:
> http://lists.njs-javascript.org/cgi-bin/mailman/listinfo/users
>
> 2. Did you try to compile it?
> Is there anything obviously 2.5 incompatible?

Well, so far I couldn't even compile njs (./configure complains about
HOST setting or some such) so haven't looked at njsmodule yet.

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


Converting from local -> UTC

2008-07-11 Thread Keith Hughitt
Hi,

I am having a little trouble figuring out how to convert a python
datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would
like to create a UTC date so that when I send it to MySQL (which
treats all dates at local dates by default), it will already have
incorporated the proper UTC offset. I've tried looking through the
docs http://python.active-venture.com/lib/datetime-datetime.html), but
have not had any luck.

Does anyone have any suggestions? Any help would be greatly
appreciated.

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


imaplib -- can't read body

2008-07-11 Thread Sells, Fred
I'm trying to read mail using the imaplib module.  I can get the subject and 
date, but not the body, have not found any example on how to do that and I 
don't know much about imap.  Here's what I have, working as noted...

If anyone can show me what I'm missing in order to get the body of a mail 
message, that would be greatly appreciated,

Fred
--- code starts below---

import imaplib, sys, os, re, rfc822

OK = "OK"

FETCHTHIS = '(BODY[HEADER.FIELDS (SUBJECT FROM)])'

### got inemsg from the web, works up to the last line; msg.fp has no read and 
readline returns empty string.
class inemsg:
def __init__(self,msg):
(self.msgfromname, self.msgfrom) = msg.getaddr('from')
self.msgto = msg.getaddr('to')
self.msgsubject = msg.getheader('subject')
self.msgdate = msg.getheader('date')
self.msgtext = msg.fp.read()


class msg: # a file-like object for passing a string to rfc822.Message
def __init__(self, text):
self.lines = text.split('\015\012')
self.lines.reverse()
def readline(self):
try: return self.lines.pop() + '\n'
except: return ''


class MailReader:
def __init__(self, mailserver, user, password):
self.M = imaplib.IMAP4(mailserver)
self.M.login(user, password)
result, message = self.M.select(readonly=1)
print ( 'constructor', result, message)
if result != OK: raise Exception, message

def getMessages(self, *mailboxes):
if mailboxes:
filter = '(%s)' % ' '.join(list(mailboxes))
else:
filter = '(UNSEEN UNDELETED)'
mtype, data = self.M.search(None, filter )
print ('getMessages', mtype, data)
for num in data[0].split():
f = self.M.fetch(num, FETCHTHIS)
print ('fetch', f)
m = rfc822.Message(msg(f[1][0][1]), 0)
subject = m['subject']
fromaddr = m.getaddr('from')
if fromaddr[0]=='': n = fromaddr[1]
else: n=fromaddr[0]
print (subject, fromaddr) 
return None   #no reason to return until I can get the message 
content/body.   


if __name__=='__main__':
x = MailReader("myserver", "myuser", "mypassword")
messages = x.getMessages()
print messages

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 and removal of the 'string' module

2008-07-11 Thread Terry Reedy



Ben Finney wrote:

"Martin v. Löwis" <[EMAIL PROTECTED]> writes:

This is rather disappointing. Is that entire page suspect? 

All documentation about Python 3 is suspect until Python 3 gets
actually released (nobody can say for sure how the release will
look like in all details).


Is there a better information source, then, for the current state of
what's expected in Python 3.0?


Start with the actual beta release.  That is what is there.  There are a 
few tweaks that might happen, and a few modules that might be added, and 
some bugs that should be fixed.  The issue tracker has information on 
the day-to-day state of most of these.


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

Re: Simple question, how do you tell how many items in a list?

2008-07-11 Thread Terry Reedy



Alex Bryan wrote:
I am just wondering how you get an integer value for how many items 
there are in a list, preferably w/o a for loop.


Read the library reference sections on built-in functions and classes.

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


Re: Moving to functional programming

2008-07-11 Thread Terry Reedy



[EMAIL PROTECTED] wrote:

James Fassett:

# the first Pythonic attempt using comprehensions
result_list = [x[0] for x in tuple_list]


This has the virtue of working for tuples of any length and doing the 
minimal work required.



# the final functional way
[result_list, _] = zip(*tuple_list)


This requires the tuples in tuple_list to be of length 2.  It also 
produces a second list that is then tossed away.



The list comprehension is quite more readable to me, so I suggest you
to use it. It's probably the default way to do it in Python.


It also has two virtues that the non-equivalent alternative lacks.


If you want functional code this is another way (I have not tested the
relative performance but it may be quick):


tuple_list = (

... ('John', 'Doe'),
... ('Mark', 'Mason'),
... ('Jeff', 'Stevens'),
... ('Bat', 'Man')
...   )

from operator import itemgetter
map(itemgetter(0), tuple_list)

['John', 'Mark', 'Jeff', 'Bat']


This again makes just one list from tuples of any length.

Some of the other alternatives in another post do minimal work but only 
work with pairs.


tjr

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


Filechooser issues

2008-07-11 Thread Mr SZ
Hi,
I am using a gtk.filechooser dialog to open and save files.How do I add a 
filter so that only images are filtered ?I did something like this:

    def get_save_filename(self):
    
    filename = None
    chooser = gtk.FileChooserDialog("Save File...", self.window,
    gtk.FILE_CHOOSER_ACTION_SAVE,
    (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, 
 gtk.STOCK_SAVE, gtk.RESPONSE_OK))
    ff = gtk.FileFilter.add_pixbuf_formats()
    chooser.add_filter(ff)
    response = chooser.run()
    if response == gtk.RESPONSE_OK: filename = chooser.get_filename()
    chooser.destroy()
    
    return filename

Now I get an error when I add ff or a filefilter .The error is :

Traceback (most recent call last):
  File "tutorial.py", line 91, in on_save_as_menu_item_activate
    filename = self.get_save_filename()
  File "tutorial.py", line 231, in get_save_filename
    ff = gtk.FileFilter.add_pixbuf_formats()
TypeError: descriptor 'add_pixbuf_formats' of 'gtk.FileFilter' object needs an 
argument

The documentation doesn't say anything about an argument to be passed:
http://www.pygtk.org/docs/pygtk/class-gtkfilefilter.html#method-gtkfilefilter--add-pixbuf-formats

Regards,
SZ

" life isn't heavy enough,it flies away and floats far above action"


  Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au--
http://mail.python.org/mailman/listinfo/python-list

Re: Filechooser issues

2008-07-11 Thread Jerry Hill
On Fri, Jul 11, 2008 at 3:09 PM, Mr SZ <[EMAIL PROTECTED]> wrote:
> ff = gtk.FileFilter.add_pixbuf_formats()

> The documentation doesn't say anything about an argument to be passed:
> http://www.pygtk.org/docs/pygtk/class-gtkfilefilter.html#method-gtkfilefilter--add-pixbuf-formats

I don't know anything about gtk or its python bindings.  That being
said, the reference page seems to say you need to do this:

ff = gtk.FileFilter()#Create a file filter object
ff.add_pixbuf_formats()#Tell the object what to filter for

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


Re: decorator to prevent adding attributes to class?

2008-07-11 Thread Neal Becker
Robert Bossy wrote:

> class Foo(Freezeable):
> def __init__(self):
> self.bar = 42
> self.freeze() # ok, we set all variables, no more from here
> 
> 
> x = Foo()
> print x.bar
> x.bar = -42
> print x.bar
> x.baz = "OMG! A typo!"
> 

Pretty nice, but unfortunately the subclass has to remember to call freeze
in it's init.  Too bad that can't be automated.


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


Re: Simple question, how do you tell how many items in a list?

2008-07-11 Thread WDC
On Jul 11, 2:53 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Alex Bryan wrote:
> > I am just wondering how you get an integer value for how many items
> > there are in a list, preferably w/o a for loop.
>
> Read the library reference sections on built-in functions and classes.

Quite simple.

If I understand you correctly, you have a list like this:

>>> list = ['a', 'b', 'c', 'd']

As you can see, the list has 4 entries.

The len() function also says that we have 4 entries.

>>> len(list)
4

Now, if we wanted a particular entry, we would do this:

>>> list[0]
'a'

(Remember, when calling something in a list we count zero.)

>>> list[3]
'd'

Hope this helped.

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


Re: Using the Random Module.

2008-07-11 Thread castironpi
On Jul 11, 1:29 pm, WDC <[EMAIL PROTECTED]> wrote:
> On Jul 11, 2:15 pm, Michiel Overtoom <[EMAIL PROTECTED]> wrote:
>
> > You wrote...
> > >Is there a better way to do that besides doing this:
>
> > random.randint(0, 9)
> > >09657398671238769
>
> > Maybe this?
>
> >         random.randint(0, 9e16)
>
> > --
> > "The ability of the OSS process to collect and harness
> > the collective IQ of thousands of individuals across
> > the Internet is simply amazing." - Vinod 
> > Vallopillilhttp://www.catb.org/~esr/halloween/halloween4.html
>
> That would work yes, but is there a random() function that would do
> that without the attributes? Not trying to be lazy, I just want to
> know if there is a built in way.
>
> Thanks Michiel.

You want a random integer.  Is there a range you want it in?

Past a certain point, you'll exceed the granularity of the random
number generator, and some values in the range will never be generated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: read file into list of lists

2008-07-11 Thread John Machin
On Jul 11, 11:35 pm, Paddy <[EMAIL PROTECTED]> wrote:
> On Jul 11, 2:15 pm, antar2 <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello,
>
> > I can not find out how to read a file into a list of lists. I know how
> > to split a text into a list
>
> > sentences = line.split(\n)
>
> > following text for example should be considered as a list of lists (3
> > columns and 3 rows), so that when I make the print statement list[0]
> > [0], that the word pear appears
>
> > pear noun singular
> > books nouns plural
> > table noun singular
>
> > Can someone help me?
>
> > Thanks
>
> lofl = [line.strip().split() for line in the_opened_file]
>

>>> line = '   foo   bar   '
>>> line.strip().split()
['foo', 'bar']
>>> line.split()
['foo', 'bar']

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


Re: Determining when a file has finished copying

2008-07-11 Thread Sean DiZazzo
On Jul 9, 5:34 pm, keith <[EMAIL PROTECTED]> wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
>
>
> Ethan Furman wrote:
> > writeson wrote:
> >> Guys,
>
> >> Thanks for your replies, they are helpful. I should have included in
> >> my initial question that I don't have as much control over the program
> >> that writes (pgm-W) as I'd like. Otherwise, the write to a different
> >> filename and then rename solution would work great. There's no way to
> >> tell from the os.stat() methods to tell when the file is finished
> >> being copied? I ran some test programs, one of which continously
> >> copies big files from one directory to another, and another that
> >> continously does a glob.glob("*.pdf") on those files and looks at the
> >> st_atime and st_mtime parts of the return value of os.stat(filename).
> >>> From that experiment it looks like st_atime and st_mtime equal each
> >> other until the file has finished being copied. Nothing in the
> >> documentation about st_atime or st_mtime leads me to think this is
> >> true, it's just my observations about the two test programs I've
> >> described.
>
> >> Any thoughts? Thanks!
> >> Doug
>
> > The solution my team has used is to monitor the file size.  If the file
> > has stopped growing for x amount of time (we use 45 seconds) the file is
> > done copying.  Not elegant, but it works.
> > --
> > Ethan
>
> Also I think that matching the md5sums may work.  Just set up so that it
> checks the copy's md5sum every couple of seconds (or whatever time
> interval you want) and matches against the original's.  When they match
> copying's done. I haven't actually tried this but think it may work.
> Any more experienced programmers out there let me know if this is
> unworkable please.
> K
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.6 (GNU/Linux)
> Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org
>
> iD8DBQFIdVkX8vmNfzrLpqoRAsJ2AKCp8wMz93Vz8y9K+MDSP33kH/WHngCgl/wM
> qTFBfyIEGhu/dNSQzeRrwYQ=
> =Xvjq
> -END PGP SIGNATURE-

I use a combination of both the os.stat() on filesize, and md5.
Checking md5s works, but it can take a long time on big files.  To fix
that, I wrote a simple  sparse md5 sum generator.  It takes a small
number bytes from various areas of the file, and creates an md5 by
combining all the sections. This is, in fact, the only solution I have
come up with for watching a folder for windows copys.

The filesize solution doesn't work when a user copies into the watch
folder using drag and drop on Windows because it allocates all the
attributes of the file before any data is written.  The filesize will
always show the full size of the file.

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


Adding a Cairo object into a vbox using pygtk

2008-07-11 Thread Mr SZ
Hi ,

I am trying to attach a cairo object into a vbox.I can pack a textbox with the 
following code:

    entry = gtk.Entry()
    entry.set_max_length(50)
    entry.connect("activate", self.enter_callback, entry)
    entry.set_text("hello")
    entry.insert_text(" world", len(entry.get_text()))
    entry.select_region(0, len(entry.get_text()))
    self.vbox.pack_start(entry, True, True, 0)
    entry.show()

but when I do the same for a cairo object I had created from the pycairo 
examples ,it wont.

    self.window = builder.get_object("mainwindow")
    self.vbox = builder.get_object("winvbox")
    # connect signals
    builder.connect_signals(self)
    
   
    self.cairorun(cairoshape)
    
    def cairorun(self,Widget):
   
    widget = Widget()
    self.vbox.pack_start(widget, True, True, 0)
    widget.show()

class cairoshape(framework.Screen):
    def draw(self, cr, width, height):
    image = cairo.ImageSurface.create_from_png ("image.png")
    cr.set_source_surface (image, 0, 0)
    cr.paint ()

and the framework.py from the examples:


#! /usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk, gobject, cairo

# Create a GTK+ widget on which we will draw using Cairo
class Screen(gtk.DrawingArea):

    # Draw in response to an expose-event
    __gsignals__ = { "expose-event": "override" }

    # Handle the expose-event by drawing
    def do_expose_event(self, event):

    # Create the cairo context
    cr = self.window.cairo_create()

    # Restrict Cairo to the exposed area; avoid extra work
    cr.rectangle(event.area.x, event.area.y,
    event.area.width, event.area.height)
    cr.clip()

    self.draw(cr, *self.window.get_size())

    def draw(self, cr, width, height):
    # Fill the background with gray
    cr.set_source_rgb(0.5, 0.5, 0.5)
    cr.rectangle(0, 0, width, height)
    cr.fill()

# GTK mumbo-jumbo to show the widget in a window and quit when it's closed
def run(Widget):
    window = gtk.Window()
    window.connect("delete-event", gtk.main_quit)
    widget = Widget()
    widget.show()
    window.add(widget)
    window.present()
    gtk.main()

if __name__ == "__main__":
    run(Screen)

In short,I can attach the cairo widget to a main window but I'm unable to pack 
it into a vbox.


Regards,
SZ

" life isn't heavy enough,it flies away and floats far above action"


  Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au--
http://mail.python.org/mailman/listinfo/python-list

Re: error with configure (svn 64857)

2008-07-11 Thread Martin v. Löwis
> If didn't investigate everything but I solved the problem by adding
> the "-static-libgcc" option:
> 
> CFLAGS="-w -static-intel -static-libgcc"
> 
> I think one should commit changes so configure can manage this.

I don't think that change should be made. I'm almost certain that it is
correct. Many people build Python with icc, and never reported any such
problem. So there must something be wrong with your icc installation.

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


Re: ANN: P4D 1.1

2008-07-11 Thread Kay Schluehr
On 11 Jul., 15:25, Fuzzyman <[EMAIL PROTECTED]> wrote:
> On Jul 11, 10:09 am, Kay Schluehr <[EMAIL PROTECTED]> wrote:
>
> > P4D = E4X style embedded DSL for Python but without E and X.
>
> > For more information see:
>
> >http://pypi.python.org/pypi/P4D/1.1-py2.5
>
> That looks a lot like YAML. Any reason to use it over YAML?
>
> Michael Foordhttp://www.ironpythoninaction.com/

I considered an embedded YAML DSL for Python a long time ago but YAML
and Python are not orthogonal. For instance YAML specifies syntax for
lists and dictionaries and also data sections which can be expressed
easily as triple quoted strings in Python. Embedding YAML is a bit
excessive.

Syntactically P4D is inspired by SLiP

http://slip.sourceforge.net/

and I'd say it is mostly Python extened by SLiP + extra syntax for
element filters and attribute access which was kept from E4X.

Why an embedded DSL and not an external one? I don't want to argue
about this but just say that you need to feel the difference. Check
out the package and start editing P4D elements on the console prompt.
It's just like a Python feature...

Notice that there was a showstopper in the initial release I
announced. It has been corrected here:

http://pypi.python.org/pypi/P4D/1.1.1-py2.5
--
http://mail.python.org/mailman/listinfo/python-list


Re: Graphics

2008-07-11 Thread Glenn Hutchings
vanam <[EMAIL PROTECTED]> writes:

> hi all
> i am new to python programming a beginner. I Came to know from the
> groups that "How to think like a computer scientist" is preferable for
> begineers. i just looking through that i came to one section where a
> sample program for generation of graphics is present.i tried to copy
> the same script to the interpreter and it is showing an error i want
> to know whether is there anything that has to be installed in addition
> to python 2.5
> below is the program
> from gasp import *
> begin_graphics()
> Circle((200, 200), 60)
> Line((100, 400), (580, 200))
> Box((400, 350), 120, 100)
> end_graphics()

You're probably getting an ImportError from the 'from gasp...' line.  You
need to grab and install the GASP package from https://launchpad.net/gasp.

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


  1   2   >