[ANN] XPN 0.4.5 released

2005-03-12 Thread Nemesis
XPN - X Python Newsreader is a multiplatform newsreader with unicode
support. It is written in Python+PyGTK.
It has features like scoring/actions, XFace and Face decoding and random
taglines.

You can find it on:

http://xpn.altervista.org/index-en.html

http://sf.net/projects/xpn

Changes in this release:

* added X-Face support (thanks to Andrew Taylor for helping
  me in the translation of his javascript port of uncompface, and to
  Alien321 for telling me about the Mnheny Thunderbird extension) 
* added Face support (note you can't send Faces, because this is a non
  standard header). 
* added i18n support with gettext. At the moment the supported languages
  are Italian and French (thanks to Guillaume Bedot for the code and for
  the French translation) 
* rewrote NNTP connection handler as an externale module. Now it should
  be more readable and more reliable. 
* some refinements in watch/ignore/mark features 
* fixed some quirk behaviours in the wrapping feature. Now the live
  wrapping should work better. 
* added Subject based threading, it's used when References based
  threading fails 
* now XPN can generate Message-IDs, and you can also use a personal
  [pseudo-]FQDN. 
* added command line options, now you can run xpn with -d option and
  it will store articles and configs files inside a .xpn directory in
  your home-dir. (thanks to Guillaume Bedot for the code) 
* added a simple outbox, you can store your articles in it when you are
  offline and then send them when you estabilish the connection with the
  server. 
* now XPN should autmatically repair its database when it gets
  corrupted. 
* some fixes for Supersede/Cancel features 
* now you can select multiple row in groups list. So for instance you
  can subscribe more than one group with one click, or you can use the
  new download new headers in selected groups. 
* now you can use a different From field when you reply by mail 
* fixed a bug introduced in the previous release that caused a crash
  trying to use a NickName with extended characters in it.
-- 
Jesus loves you. Everyone else thinks you're an ass.
 
 |\ |   |HomePage   : http://nem01.altervista.org
 | \|emesis |XPN (my nr): http://xpn.altervista.org
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


ctypes 0.9.5 released

2005-03-12 Thread Thomas Heller
ctypes 0.9.5 released - Mar 11, 2005


Overview

ctypes is an advanced ffi (Foreign Function Interface) package for
Python 2.3 and higher.

ctypes allows to call functions exposed from dlls/shared libraries
and has extensive facilities to create, access and manipulate
simple and complicated C data types in Python - in other words:
wrap libraries in pure Python.  It is even possible to implement C
callback functions in pure Python.

ctypes runs on Windows, MacOS X, Linux, Solaris, FreeBSD, OpenBSD.
It may also run on other systems, provided that libffi supports
this platform.

For windows, ctypes contains a ctypes.com package which allows to
call and implement custom COM interfaces.

Important

If you download the source distribution, please choose the ZIP
file for Windows, and the .tar.gz file for other machines.
These archive have different contents!

There have been lots of changes - if you are the author or user of
a package that uses ctypes, please test it with this release
and report problems on the ctypes-users mailing list.

Additions

New package ctypes.wrap. This contains decorators usable for
easier creation of wrapper functions.

This package also contains a toolchain for (semi)automatic
creation of wrappers for external libraries - it can parse
C header files and generate ctypes code for the declarations in
them.  It can even handle preprocessor definitions! For details,
see http://starship.python.net/crew/theller/ctypes/codegen.html


Changes in 0.9.5

On systems where sizeof(int) == sizeof(long), c_int/c_long and
c_uint/c_ulong are now aliases.  Similar for c_long/c_longlong and
c_ulong/c_ulonglong.  This prevents unneeded type errors.

If an exception occurs in a callback function, a full traceback is
now printed.  Raising SystemExit in a callback function now
correctly exists Python.

HRESULT is now a proper ctype - no longer a function.  This allows
to use it in the argtypes sequence for function prototypes.

An easier way to define structures and unions that reference
themselves, or have dependencies to other data types.  The
_fields_ attribute can now be set *after* the Structure/Union
class has been created.  This makes the SetPointerType function
obsolete.

The semantics of the _fields_ attribute in sub-subclasses of
Structure and Union has been fixed.  The baseclasses _fields_ list
is extended, not replaced, in subclasses.  Assigning _fields_ when
it is no longer possible raises an error now.

Structures and unions now work as restype and in the argtypes list
for functions.

An important bug has been fixed with pointers.


Detailed changelogs are in CVS:

http://cvs.sourceforge.net/viewcvs.py/ctypes/ctypes/ChangeLog?rev=HEAD


http://cvs.sourceforge.net/viewcvs.py/ctypes/ctypes/win32/com/ChangeLog?rev=HEAD


Download

Downloads are available in the sourceforge files section
http://sourceforge.net/project/showfiles.php?group_id=71702

Separate source distributions are available for windows and non-windows 
systems.
Please use the .zip file for Windows (it contains the ctypes.com framework),
and use the .tar.gz file for non-Windows systems (it contains the
complete cross-platform libffi sources).

Binary windows installers, which contain compiled extension
modules, are also available, be sure to download the correct one
for the Python version you are using.


Homepage

http://starship.python.net/crew/theller/ctypes/

Enjoy,

Thomas

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: csv module and unicode, when or workaround?

2005-03-12 Thread Max M
Chris wrote:
the current csv module cannot handle unicode the docs say, is there any 
workaround or is unicode support planned for the near future? in most 
cases support for characters in iso-8859-1(5) would be ok for my 
purposes but of course full unicode support would be great...
It doesn't support unicode, but you should not have problem 
importing/exporting encoded strings.

I have imported utf-8 encoded string with no trouble. But I might just 
have been lucky that they are inside the latin-1 range?

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Widget geometry ?

2005-03-12 Thread PGMoscatt
Thanks Pierre  all working now.

Pete


Pierre Quentel wrote:

 PGMoscatt a crit :
 Hi All,
 
 I am trying to create a dialog which will have a number of components but
 having trouble with the placement of various widgets.
 
 For example, in my code below you will see I am trying to insert alabel
 but I want the label to be in the top-left of the dialog but it dosen't
 want to go there.
 
 What am I doing wrong ?
 
 Pete
 
 
 
 from Tkinter import *
 
 class show_settings_dialog:
  def __init__(self,parent):
   top = self.top = Toplevel(parent)
   top.title(General Settings...)
   top[height]=300
   top[width]=300
   top.pack_propagate(0)
 
   l1 = Label(top,text=User Name:).grid(row=0, sticky=W)
 
   b = Button(top,text=Ok,command=self.ok)
   b.pack(pady=40)
   
   
   
  def ok(self):
   self.top.destroy()
 
 
 You are mixing pack() and grid() to place widgets in the same container.
 Try doing b.grid(row=0,column=1) instead
 
 Regards
 Pierre

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


Re: csv module and unicode, when or workaround?

2005-03-12 Thread John Machin

Chris wrote:
 hi,
 to convert excel files via csv to xml or whatever I frequently use
the
 csv module which is really nice for quick scripts. problem are of
course
 non ascii characters like german umlauts, EURO currency symbol etc.

The umlauted characters should not be a problem, they're all in the
first 256 characters. What makes you say they are a problem of
course?

 the current csv module cannot handle unicode the docs say, is there
any
 workaround or is unicode support planned for the near future? in most

 cases support for characters in iso-8859-1(5) would be ok for my
 purposes but of course full unicode support would be great...


Here's a perambulation through some of the alternatives:

A. If you save the file from Excel as Unicode text, you can pretty
much DIY:

 buff = file('csvtest.txt', 'rb').read()
 lines = buff.decode('utf16').split(u'\r\n')
 lines
[u'M\xfcller\t\u20ac1234,56', u'M\xf6ller\t\u20ac9876,54',
u'Kawasaki\t\xa53456.78', u'']
 for line in lines:
... print line.split(u'\t')
...
[u'M\xfcller', u'\u20ac1234,56']
[u'M\xf6ller', u'\u20ac9876,54']
[u'Kawasaki', u'\xa53456.78']
[u'']


All you have to do is handle (1) Excel's unnecessary quoting of the
comma in the money amounts [see first two lines above; what it quotes
is probably locale-dependent] (2) double quoting any quotes [no example
given] (3) ignore the empty line introduced by split().

Problem (3) is easy: if not lines[-1:]: del lines[-1:]

Hmmm ... by the time you finish this (and generalise it) you will have
done the Unicode extension to the csv module ...

Alternative B: you can do ODBC access to Excel spreadsheets; hmmm ...
yuk ... no better than CSV i.e. you get the data in your current code
page, not in Unicode:

[('M\xfcller', '\x801234,56'), ('M\xf6ller', '\x809876,54'),
('Kawasaki', '\xa53456.78')]

Alternative C: why not save your file as local-code-page .csv, use the
csv module, and DIY decode:

 rdr = csv.reader(file('csvtest.csv', 'rb'))
 for row in rdr:
...print row
...urow = [x.decode('cp1252') for x in row]
...print urow
...
['Name', 'Amount']
[u'Name', u'Amount']
['M\xfcller', '\x801234,56']
[u'M\xfcller', u'\u20ac1234,56']
['M\xf6ller', '\x809876,54']
[u'M\xf6ller', u'\u20ac9876,54']
['Kawasaki', '\xa53456.78']
[u'Kawasaki', u'\xa53456.78']

Looks good to me, including the euro sign.

HTH,

John

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


Re: csv module and unicode, when or workaround?

2005-03-12 Thread Chris
hi,
thanks for all replies, I try if I can at least get the work done.
I guess my problem mainly was the rather mindflexing (at least for me) 
coding/decoding of strings...

But I guess it would be really helpful to put the UnicodeReader/Writer 
in the docs

thanks a lot
chris
--
http://mail.python.org/mailman/listinfo/python-list


Re: [NGG/98]-Medicationns

2005-03-12 Thread Hinrik Crocker




Hello, Just Visit 
Our Pharrmacy-By-Mail SHOP and save up to 
75%.



  
  
Va

umVi

raCi

isAm

en,
Andman

  
li
ag
al
bi
yother!

P.S. You will be pleasantly surprised with our prrices 
;)

Have a good day!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: a program to delete duplicate files

2005-03-12 Thread Patrick Useldinger
John Machin wrote:
Just look at the efficiency of processing N files of the same size S,
where they differ after d bytes: [If they don't differ, d = S]
PU: O(Nd) reading time, O(Nd) data comparison time [Actually (N-1)d
which is important for small N and large d].
Hashing method: O(NS) reading time, O(NS) hash calc time

Shouldn't you add the additional comparison time that has to be done 
after hash calculation? Hashes do not give 100% guarantee. If there's a 
large number of identical hashes, you'd still need to read all of these 
files to make sure.

Just to explain why I appear to be a lawer: everybody I spoke to about 
this program told me to use hashes, but nobody has been able to explain 
why. I found myself 2 possible reasons:

1) it's easier to program: you don't compare several files in parallel, 
but process one by one. But it's not perfect and you still need to 
compare afterwards. In the worst case, you end up with 3 files with 
identical hashes, of which 2 are identical and 1 is not. In order to 
find this, you'd still have to program the algorithm I use, unless you 
say oh well, there's a problem with the hash, go and look yourself.

2) it's probably useful if you compare files over a network and you want 
to reduce bandwidth. A hash lets you do that at the cost of local CPU 
and disk usage, which may be OK. That was not my case.

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


[Ann] ctypes 0.9.5 released

2005-03-12 Thread Thomas Heller
ctypes 0.9.5 released - Mar 11, 2005


Overview

ctypes is an advanced ffi (Foreign Function Interface) package for
Python 2.3 and higher.

ctypes allows to call functions exposed from dlls/shared libraries
and has extensive facilities to create, access and manipulate
simple and complicated C data types in Python - in other words:
wrap libraries in pure Python.  It is even possible to implement C
callback functions in pure Python.

ctypes runs on Windows, MacOS X, Linux, Solaris, FreeBSD, OpenBSD.
It may also run on other systems, provided that libffi supports
this platform.

For windows, ctypes contains a ctypes.com package which allows to
call and implement custom COM interfaces.

Important

If you download the source distribution, please choose the ZIP
file for Windows, and the .tar.gz file for other machines.
These archive have different contents!

There have been lots of changes - if you are the author or user of
a package that uses ctypes, please test it with this release
and report problems on the ctypes-users mailing list.

Additions

New package ctypes.wrap. This contains decorators usable for
easier creation of wrapper functions.

This package also contains a toolchain for (semi)automatic
creation of wrappers for external libraries - it can parse
C header files and generate ctypes code for the declarations in
them.  It can even handle preprocessor definitions! For details,
see http://starship.python.net/crew/theller/ctypes/codegen.html


Changes in 0.9.5

On systems where sizeof(int) == sizeof(long), c_int/c_long and
c_uint/c_ulong are now aliases.  Similar for c_long/c_longlong and
c_ulong/c_ulonglong.  This prevents unneeded type errors.

If an exception occurs in a callback function, a full traceback is
now printed.  Raising SystemExit in a callback function now
correctly exists Python.

HRESULT is now a proper ctype - no longer a function.  This allows
to use it in the argtypes sequence for function prototypes.

An easier way to define structures and unions that reference
themselves, or have dependencies to other data types.  The
_fields_ attribute can now be set *after* the Structure/Union
class has been created.  This makes the SetPointerType function
obsolete.

The semantics of the _fields_ attribute in sub-subclasses of
Structure and Union has been fixed.  The baseclasses _fields_ list
is extended, not replaced, in subclasses.  Assigning _fields_ when
it is no longer possible raises an error now.

Structures and unions now work as restype and in the argtypes list
for functions.

An important bug has been fixed with pointers.


Detailed changelogs are in CVS:

http://cvs.sourceforge.net/viewcvs.py/ctypes/ctypes/ChangeLog?rev=HEAD


http://cvs.sourceforge.net/viewcvs.py/ctypes/ctypes/win32/com/ChangeLog?rev=HEAD


Download

Downloads are available in the sourceforge files section
http://sourceforge.net/project/showfiles.php?group_id=71702

Separate source distributions are available for windows and non-windows 
systems.
Please use the .zip file for Windows (it contains the ctypes.com framework),
and use the .tar.gz file for non-Windows systems (it contains the
complete cross-platform libffi sources).

Binary windows installers, which contain compiled extension
modules, are also available, be sure to download the correct one
for the Python version you are using.


Homepage

http://starship.python.net/crew/theller/ctypes/

Enjoy,

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


Re: Python 2.4, distutils, and pure python packages

2005-03-12 Thread Martin v. Löwis
Thomas Heller wrote:
It would be for 2.5, anyway, and I have hoped that bdist_wininst would
be replaced by bdist_msi then ;-).  What are your plans for that?
I still hope to write one by for 2.5.
One issue is that you cannot have multiple installations of an MSI
package. So if you want to support different Python installations
on the same machine, you have to clone the MSI file, and change the
product code - or provide multiple MSI files in the first place.
So I guess bdist_wininst would continue to provide a value to
certain users, as you can have as many installations of it as
you want (but then, it doesn't allow to select a target directory,
so you can have only as many installations as you find in the
registry).
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] RELEASED Python 2.4.1, release candidate 1

2005-03-12 Thread Martin v. Löwis
Vincent Wehren wrote:
is there a reason why msiexec iterates through what looks like all (?) 
files and directories in/under the destination directory? There is 
massive file I/O going on there (OK, by now you know I didn't de-install 
2.4 before trying ;-)) which explains the 100% CPU usage and the time it 
takes for the Next button to respond.
I think it is trying to estimate disk usage. To compute the disk usage
correctly, you need to find out
- what files are new files
- what files are going to be deleted
- what files are goging to be replaced
- what files are going to stay
To make this determination, it not only needs to find the names and
sizes of all files, but it also tries to determine a file version.
If a file is to be replaced, you need the disk space of both the
old and the new file temporarily, because you might need to rollback
the installation if the user cancels or some error occurs. For a new
file, you only need to consider the space of the file itself.
Unfortunately, Python files don't have version information at all
in them, but installer doesn't know this - so it looks into every
file.
If you are adventurous, you can try to take the FileCost action
out of the sequence table (use orca.exe from the SDK to do so);
however, I don't think I would like to do that in the official
installer, since people should know in advance if the installation
will exhaust the disk space.
To speed up the installation, it is probably better to uninstall
first, then install the new package, as installer will then
quickly detect that all files are new.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: shuffle the lines of a large file

2005-03-12 Thread paul koelle
Joerg Schuster wrote:
Thanks to all. This thread shows again that Python's best feature is
comp.lang.python.
from comp.lang import python ;)
Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: i18n: looking for expertise

2005-03-12 Thread Martin v. Löwis
klappnase wrote:
enc = locale.nl_langinfo(locale.CODESET).lower()
Notice that this may fail on systems which don't provide the
CODESET information. Recent Linux systems (glibc 6) have it,
and so do recent Solaris systems, but if you happen to use
an HPUX9 or some such, you find that locale.CODESET raises
an AttributeError.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: About Databases...

2005-03-12 Thread EP
[EMAIL PROTECTED] wrote:

 Hello NG,

Hello!

 
I am still quite a newbie with Python (I intensely use wxPython, 
 anyway).
 I would like to know what are, in your opinions, the best/faster 
 databases
 that I could use in Python (and, of course, I should be able to link 
 everything
 with a wxPython GUI)? Specifically, I work on Reservoir Simulation, and
 usually I have to store a discrete/huge amount of data (it depends on 
 the
 oil field). As you may have understood, I know almost NOTHING about 
 databases
 ;-)


... use in Python...

If you have vast amounts of data you will probably benefit by hooking into a 
RDBMS (aka relational database) that is outside Python.  This is easy to do 
in Python if you use a module which already exists for that purpose.

Dedicated RDBMS can perform operations very fast - they are specialized for 
that purpose - however, we can make them run quite slow if we use them poorly, 
especially on large amounts of data.  There is a lot of piece-meal information 
online about how to best use databases (either specific RDBMS or in general) 
but some theorectical background helps as well.  I have Database Design Using 
Entity-Relationship Diagrams on my shelf.  Also, I think Dobbs had one or more 
articles about (mis)using databases recently.

With RDBMS you have another language to learn: SQL.

At the risk of being stoned, let me say that SQL is like talking pidgin, which 
is not to imply you can get away with speaking it imprecisely.

[side note, look up programming language namesake LUA here:  
http://www.extreme-hawaii.com/pidgin/vocab/ to understand why it may not be 
more popular with hackers in Hawaii]

A nominal starting point might be to install MySQL (a relational database which 
is open source free, fast, and very widely used on the Internet) and use the 
MySQLDB in Python to access it.  From there you can decide if you need more or 
less of something.

In my experience MySQL is fast and can handle very large datasets, but there 
seem to be plenty of other good database options.  Oracle seems to be the 
dominant commercial RDBMS, and may be a good choice if you are offered the 
option of using it.  The Oracle universe is very commercial, however - it's big 
business.

There are database approaches you could take directly within Python, including 
storing your data (in binary or text form) as files under your OS.  However 
with that approach you will lose or have to re-create a relational query 
system, and I have reservations that the file access is going to be as 
optimized (speed wise).

BTW, AFAIK, Python or any RDBMS is going to ride on top of your OS, which means 
that if you are trying to do very, very large data transactions at high speeds, 
the OS can be the pacing code.  If you ever find yourself backed up against 
that wall, there are commercial systems (OS) designed to provide greater data 
access speed (that is a simple, data access purposed OS, so that you do not 
need to run on Unix/Linux/__ix or on Windows or on another 
multi-purpose-higher-overhead OS).



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


Re: RELEASED Python 2.4.1, release candidate 1

2005-03-12 Thread Tim N. van der Leeuw
Hi Roger,

Thanks, I understand it now, I didn't yet receive in the mail any
replies to my post on py-dev when I read your post here! That's why it
didn't make any sense to me.

I didn't yet have a chance to try the workaround given in the
bug-report (remove MBCS encoding line). Hope to find time soon.

thanks,

--Tim

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


Re: Safe Local XMLRPC

2005-03-12 Thread Diez B. Roggisch
 I've used the default support available by these classes. Thus it will
 run on a potentially public TCP/IP port. As the application backend
 allows, among other things, saving files to the local filesystem, this
 would be a clear security hole in the wild. Restricting it to
 localhost would be a start, but not sufficient for multi-user systems.

This might not be the answer you want, but I'd personally ditch xmlrpc and
switch to something like pyro or even corba and implement a real
authentication theme. They are easy to use, provide a full OO-style
interface and are even faster than xmlrpc. 

Part of the problems you're facing stem from the stateless nature of xmlrpc
(and soap, for that matter). That allows everybody to access the API
without prior authentication. It requires some effort to implement a
authentication/authorization scheme over xmlrpc. What usually is done in
xmlrpc in similar situations like yours is that there is a 

authenticate(user, password)

function that will return a handle on success that has to be passed to all
subsequent calls to other functions. All this because the handle can't be
associated with each and every xmlrpc request (in soap that can be done,
but its undstandarized.)

With corba/pyro, authenticate would return an object that implicitely has
all the state needed - nameley who created the connection - and then you
don't have to bother about that anymore.

Switching to pyro shouldn't be much more than a few lines of code, more or
less only subclassing your server from Pyro.core.ObjBase instead of
SimpleXMLRPCServer. 

-- 
Regards,

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


Re: Adapting code to multiple platforms

2005-03-12 Thread Patrick Useldinger
Jeffrey Barish wrote:
I have a small program that I would like to run on multiple platforms
(at least linux and windows).  My program calls helper programs that
are different depending on the platform.  I think I figured out a way
to structure my program, but I'm wondering whether my solution is good
Python programming practice.
I use something like this in the setup code:
if os.name == 'posix':
  statfunction = os.lstat
else:
  statfunction = os.stat
and then further in the code:
x = statfunction(filename)
So the idea is to have your own function names and assign the 
os-specific functions one and for all in the beginning. Afterwards, your 
code only uses your own function names and, as long as they behave in 
the same way, there's no more if - else stuff.

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


Re: How to send browser to open a different URL

2005-03-12 Thread Harald Massa
Mike Wimpe [EMAIL PROTECTED] wrote in news:1110628448.532469.117000
@g14g2000cwa.googlegroups.com:

http://groups.google.de/groups?hl=delr=c2coff=1threadm=
2c60a528.0309251324.109d4af5%40posting.google.comrnum=5prev=/groups%3Fq%
3Dhttp%2520redirect%2520header%2520python%26hl%3Dde%26lr%3D%26c2coff%3D1%
26sa%3DN%26tab%3Dwg

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


is there a problem on this simple code

2005-03-12 Thread jrlen balane
basically what the code does is transmit data to a hardware and then
receive data that the hardware will transmit.

import serial
import string
import time
from struct import *


ser = serial.Serial()

ser.baudrate = 9600
ser.port = 0
ser
ser.close()
ser.open()

command = 67
message_no = 1
total_data = 2

item = 12000#to warm-up the hardware
hexed = hex(item)
data_hi, data_lo = divmod(item, 0x100)
checksum = -(data_hi + data_lo + 0x46)  0xff
ser.write(pack('6B', command, message_no, total_data, data_lo,
data_hi, checksum)) #serial transmit protocol
time.sleep(1)

item = 1
no = 0
for item in range(1, 30001, 250):
no = no +1
hexed = hex(item)
data_hi, data_lo = divmod(item, 0x100)
checksum = -(data_hi + data_lo + 0x46)  0xff
ser.write(pack('6B', command, message_no, total_data, data_lo,
data_hi, checksum))
data = ser.read(10)
(command, msg_no, no_databyte, temp1, temp2, pyra1, pyra2,
voltage, current, checksum) = unpack('10B', data)  #serial receive
protocol
print no, command, msg_no, no_databyte, temp1, temp2, pyra1,
pyra2, voltage, current, checksum
time.sleep(1)

ser.close()


===
and here is some result after running the program on Idle Python 2.3
(enthought ed.)

1 70 168 6 0 0 0 0 0 0 12
2 70 2 6 0 0 0 0 0 0 178
3 70 3 6 0 0 0 0 0 0 177
4 70 4 6 0 0 0 0 0 0 176
5 70 5 6 0 0 0 0 0 0 175
6 70 6 6 0 0 0 0 0 0 174
7 70 7 6 0 0 0 0 0 0 173
8 70 8 6 0 0 0 0 0 0 172
9 70 9 6 0 0 0 0 0 0 171
10 70 10 6 0 0 0 0 0 0 170
11 70 11 6 0 0 0 0 0 0 169
12 70 12 6 0 0 0 0 0 0 168
13 70 13 6 0 0 0 0 0 0 167
14 70 14 6 0 0 0 0 0 0 166
15 70 15 6 0 0 0 0 0 0 165

==

the result i am expecting is for the data bytes (bytes 4-9) to change
its value since i am able to control the sensors which the data were
based. i am just asking for your opinion if there is something wrong
with this program, otherwise, it could be a hardware problem.

thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to turn a variable name into a string?

2005-03-12 Thread Scott David Daniels
André Roberge wrote:
[EMAIL PROTECTED] wrote:
I have a number of variables (environmental variables, actually), most
of which will have a value. But some may not have been found by
os.environ.get(), so I set those to None. Now, if any of them are None,
the app cannot proceed, so I want to test for this and warn the user.
I could do something like this (actually, there are more than 3 vars):
a = c:\\programs
b = d:\\data
c = None  (result of an assignment after the os.environ.get() returned
a KeyError).
if (a is None) or (b is None) or (c is None):
#do something here
print 'you are missing some env vars'
But, that seemed clumsy to me, so I wanted to do something more
pythonic, hence my previous post.   So, any suggestions?
How about this:
try:
mumble = os.environ['TMP']
babble = os.environ['Path']
frobotz = os.environ['NotThere']
jangle = int(os.environ['WEIGHT'])
...
except KeyError, e:
print 'Mising env var %r. Fix it and try again' % e.args
raise SystemExit
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


bsddb support for berkeley db 4.3?

2005-03-12 Thread janeaustine50
It doesn't seem like the python 2.4(and the recent 2.4.1) support
berkeley db 4.3. (4.3 fixes some deadlock bugs I occasionally encounter
using 4.2.)

bsddb3(at pybsddb.sf.net) already supports 4.3 since last December(but
doesn't explicitly support win32 -- see the assert statement in
setup.py). I thought the bsddb3 project were merged into the python
project. Hasn't it?

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


Re: pre-PEP: Print Without Intervening Space

2005-03-12 Thread Marcin Ciura
Steve Holden wrote:
You could think about teaching them the linelist.append(fn(x)) way, 
which then gives you the choice of
  .join(linelist) - no gaps
  \n.join(lienlist) - one item per line
   .join(linelist) - spaces between items.
Sure I will. Next week, when we come to list operations.
.join() they already know. I just couldn't use this approach
at the very beginning. Thanks to all who responded.
Regards,
  Marcin
--
http://mail.python.org/mailman/listinfo/python-list


Newbie question Tkinter bitmap

2005-03-12 Thread Wim Goffin



Hi,

I'm trying to get a bitmap onto a button, but I 
can't.Can anyone tell me where to look for a solution?

The call I use is this one:self.b = 
Button(toolbar, text="nieuw", bitmap="@/test.xbm", width=20, 
command=self.print_msg)

The message I get is this:Traceback (most 
recent call last): File "C:\Documents and Settings\Wim\Mijn 
documenten\Python\overhoor.py", line 143, in -toplevel- 
app = App(root) File "C:\Documents and Settings\Wim\Mijn 
documenten\Python\overhoor.py", line 71, in __init__ 
self.b = Button(toolbar, text="nieuw", bitmap="@/test.xbm", width=20, 
command=self.print_msg) File "C:\Python24\lib\lib-tk\Tkinter.py", line 
1939, in __init__ Widget.__init__(self, master, 'button', 
cnf, kw) File "C:\Python24\lib\lib-tk\Tkinter.py", line 1868, in 
__init__ self.tk.call(TclError: error reading bitmap 
file "\test.xbm"

This is hapening on a WindowsXP system.It seems 
as though the file is not found. Because if specify the name of a non-existing 
file, then I get exactly the same error. What could I do to make sure first that 
Puthon does find the file?

Thanks in advance,Wim 
Goffin
-- 
http://mail.python.org/mailman/listinfo/python-list

Python Tkinter Newbie question

2005-03-12 Thread Wim Goffin



Hi,

I'm trying to get a bitmap onto a button, but I 
can't.Can anyone tell me where to look for a solution?

The call I use is this one:self.b = 
Button(toolbar, text="nieuw", bitmap="@/test.xbm", width=20, 
command=self.print_msg)

The message I get is this:Traceback (most 
recent call last): File "C:\Documents and Settings\Wim\Mijn 
documenten\Python\overhoor.py", line 143, in -toplevel- 
app = App(root) File "C:\Documents and Settings\Wim\Mijn 
documenten\Python\overhoor.py", line 71, in __init__ 
self.b = Button(toolbar, text="nieuw", bitmap="@/test.xbm", width=20, 
command=self.print_msg) File "C:\Python24\lib\lib-tk\Tkinter.py", line 
1939, in __init__ Widget.__init__(self, master, 'button', 
cnf, kw) File "C:\Python24\lib\lib-tk\Tkinter.py", line 1868, in 
__init__ self.tk.call(TclError: error reading bitmap 
file "\test.xbm"

This is hapening on a WindowsXP system.It seems 
as though the file is not found. Because if specify the name of a non-existing 
file, then I get exactly the same error. What could I do to make sure first that 
Puthon does find the file?

Thanks in advance,Wim 
Goffin
-- 
http://mail.python.org/mailman/listinfo/python-list

Tkinter Bitmap Newbie question

2005-03-12 Thread Wim Goffin



Hi,

I'm trying to get a bitmap onto a button, but I 
can't.Can anyone tell me where to look for a solution?

The call I use is this one:self.b = 
Button(toolbar, text="nieuw", bitmap="@/test.xbm", width=20, 
command=self.print_msg)

The message I get is this:Traceback (most 
recent call last): File "C:\Documents and Settings\Wim\Mijn 
documenten\Python\overhoor.py", line 143, in -toplevel- 
app = App(root) File "C:\Documents and Settings\Wim\Mijn 
documenten\Python\overhoor.py", line 71, in __init__ 
self.b = Button(toolbar, text="nieuw", bitmap="@/test.xbm", width=20, 
command=self.print_msg) File "C:\Python24\lib\lib-tk\Tkinter.py", line 
1939, in __init__ Widget.__init__(self, master, 'button', 
cnf, kw) File "C:\Python24\lib\lib-tk\Tkinter.py", line 1868, in 
__init__ self.tk.call(TclError: error reading bitmap 
file "\test.xbm"

This is hapening on a WindowsXP system.It seems 
as though the file is not found. Because if specify the name of a non-existing 
file, then I get exactly the same error. What could I do to make sure first that 
Puthon does find the file?

Thanks in advance,Wim 
Goffin
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: About Databases...

2005-03-12 Thread Lee Harr
On 2005-03-11, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Hello NG,

I am still quite a newbie with Python (I intensely use wxPython, anyway).
 I would like to know what are, in your opinions, the best/faster databases
 that I could use in Python (and, of course, I should be able to link 
 everything
 with a wxPython GUI)? Specifically, I work on Reservoir Simulation, and
 usually I have to store a discrete/huge amount of data (it depends on the
 oil field). As you may have understood, I know almost NOTHING about databases
 ;-)
 In general, my data will be numeric (floats, integers). Will a binary storage
 (if it is possible) reduce the size of the DB? And what about speed in 
 storing/retrieving
 data?

 Thank you a lot for every suggestion.

 Andrea.




There is also the PostGIS extension for PostgreSQL
which may be of use in your situation:

http://postgis.refractions.net/



PostGIS adds support for geographic objects to the
PostgreSQL object-relational database. In effect,
PostGIS spatially enables the PostgreSQL server, 
allowing it to be used as a backend spatial database 
for geographic information systems (GIS), much like 
ESRI's SDE or Oracle's Spatial extension.

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


Re: a program to delete duplicate files

2005-03-12 Thread Scott David Daniels
Patrick Useldinger wrote:
Just to explain why I appear to be a lawer: everybody I spoke to about 
this program told me to use hashes, but nobody has been able to explain 
why. I found myself 2 possible reasons:

1) it's easier to program: you don't compare several files in parallel, 
but process one by one. But it's not perfect and you still need to 
compare afterwards. In the worst case, you end up with 3 files with 
identical hashes, of which 2 are identical and 1 is not. In order to 
find this, you'd still have to program the algorithm I use, unless you 
say oh well, there's a problem with the hash, go and look yourself.

2) it's probably useful if you compare files over a network and you want 
to reduce bandwidth. A hash lets you do that at the cost of local CPU 
and disk usage, which may be OK. That was not my case.

3) Probability is on your side.  If two files match in length, but differ
   in contents, a good hash will have probability (1 / max_hash) of
   having a matching hash.  For exactly two files of the same length,
   calculating the hash is clearly a waste.  For even three files of
   the same length, you are most likely to find them distinct in three
   comparisons.  Using hashes, three file reads and three comparisons
   of hash values.  Without hashes, six file reads; you must read both
   files to do a file comparison, so three comparisons is six files.
   Naturally, as it grows beyond three, the deference grows drastically.
-Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Confused with classmethods

2005-03-12 Thread Jong ruuddotdedotjongatconsunet dot
jfj schreef:
Ruud wrote:
So far for *how* it works. As to *why* it works like this, I don't know
for sure. But my guess is that the reasoning was something as follows:
if you define a function (regular or something special like a
classmethod) only for an instance of a class, you obviously don't
want to use it in a class context: it is -by definition- invisible to
the class, or to other instances of the same class.
One possible use case would be to store a callback function.
And in that case you definitely don't want the class magic to happen
when you reference the function.

Yep. Got it. Indeed the reason seems to be a valid optimization:
-in 99% of the cases you request something from an instance it is a 
plain old variable
-in 99% of the cases you request something from a class it's a
function.

So it would be a waste of time to check for the conversion when
something exists in the __dict__ of the instance, indeed.
OTOH, I'm talking about the concept of python and not CPython 
implementation, and that's why I have these questions:)

Thanks,
jfj
I love this type of discussion -- it really forces me to do research
on my assumptions. But in this case I don't believe that this is 
specific to CPython. From the Python Reference Manual, Section 3.2,
The Standard Type Hierarchy, in the part about callable types, 
user-defined methods:

quote
Note that the transformation from function object to (unbound or bound) 
method object happens each time the attribute is retrieved from the 
class or instance. In some cases, a fruitful optimization is to assign 
the attribute to a local variable and call that local variable. Also 
notice that this transformation only happens for user-defined functions; 
other callable objects (and all non-callable objects) are retrieved 
without transformation. It is also important to note that user-defined 
functions which are attributes of a class instance are not converted to 
bound methods; this only happens when the function is an attribute of 
the class.
/quote

So it seems that this mechanism is indeed fully part of the python
concept, not an optimization specific for CPython implementation.
When you define a function as an instance attribute (instead of
a class attribute), then none of the class magic happens.
When you access that attribute, you get the bare function, not a method.

--
'@'.join('.'.join(s) for s in (['ruud','de','jong'],['tiscali','nl']))
--
http://mail.python.org/mailman/listinfo/python-list


Re: psycopg authentication

2005-03-12 Thread Lee Harr
On 2005-03-12, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Hello, I'm new to both PostgreSQL and psycopg and I'm trying to connect
 to my database running on localhost. I have postgres setup to do md5
 authentication and this works when using a db admin tool on my local
 network. For some reason, psycopg fails with IDENT authentication.

 import psycopg
 psycopg.connect(dbname=jlowery user=jlowery host=localhost
 password=XXX)
 Traceback (most recent call last):
   File stdin, line 1, in ?
 psycopg.OperationalError: FATAL 1:  IDENT authentication failed for
 user jlowery

 Is there a way to make this module connect with MD5 auth?



Are you sure you do not have local connections set up
for md5 and host authentications still set to ident?

Did you restart the server after updating pg_hba.conf?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: head for grouped data - looking for best practice

2005-03-12 Thread Peter Otten
Harald Massa wrote:

 def getdoublekey(row):
 return row[0:2]
 
 for key, bereich in groupby(eingabe,getdoublekey):
 print Area:,key
 for data in bereich:
 print --data--, data[2:]
 
 which indeed leeds to the expected result, while looking less hacky ..
 on the other hand side, that getdoublekey ist not very flexible; when
 doing the same with 3 Columns forming the head information, I have to
 define the next function...

Function creation is cheap and easily understood by someone reading your
code -- so you may already have the best solution. If Raymond Hettingers
recent suggestion on python-dev makes it into Python 2.5,
itemgetter()/attrgettter() could grow support for the extraction of
multiple attributes/items.

Anyway, here is a generalized getter factory that tries to handle all the
common cases in an intuitive way. E. g. you can create itemgetters using
the [] notation:

 extract[::3](range(5))
[0, 3]
 extract[3](range(5))
3
 extract[0,3,4](range(5))
(0, 3, 4)
 import os
 extract.path(os)
module 'posixpath' from '/somewhere/posixpath.pyc'

Peter

import itertools
import operator

def tuple_itemgetter(*keys):
Create a function that extracts a tuple of items from an 
   indexable object.

# helper for extract
getters = map(operator.itemgetter, keys)
def get(obj):
return tuple(get(obj) for get in getters)
return get

def tuple_attrgetter(*names):
Create a function that extracts a tuple of attributes from an object.

# helper for extract
getters = map(operator.attrgetter, names)
def get(obj):
return tuple(get(obj) for get in getters)
return get

class extract(object):
Present unified access to the creation of
   attribute and item getters.

def __getitem__(self, index):
if isinstance(index, tuple):
return tuple_itemgetter(*index)
return operator.itemgetter(index)
def __getattribute__(self, name):
return operator.attrgetter(name)
def __call__(self, *names):
return tuple_attrgetter(*names)

extract = extract() # we only ever need one instance

if __name__ == __main__:
# the demo is an anglo-german hotchpotch, really:
eingabe=[
(Stuttgart,70197,Fernsehturm,20),
(Stuttgart,70197,Brotmuseum,123),
(Stuttgart,70197,Porsche,123123),
(Leipzig,01491,Messe,91822),
(Leipzig,01491,Schabidu,9181231),
]
class Site(object):
def __init__(self, stadt, plz, name, nummer):
self.stadt = stadt
self.plz = plz
self.name = name
self.nummer = nummer
def __str__(self):
return Site(stadt=%r, plz=%r, name=%r, nummer=%r) % (
self.stadt, self.plz, self.name, self.nummer)
__repr__ = __str__

def show(iterable, groupkey):
print - * 20
for group, items in itertools.groupby(iterable, groupkey):
print group
for item in items:
print \t, item

show(eingabe, extract[1])
show(eingabe, extract[0, 1, 0:2])
show(eingabe, extract[0:2])
show((Site(*e) for e in eingabe), extract(stadt, plz))
show((Site(*e) for e in eingabe), extract.stadt)

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


Re: Tkinter Bitmap Newbie question

2005-03-12 Thread Diez B. Roggisch
Posting the same question three times is unecessary and is likely to upset
people!

 TclError: error reading bitmap file \test.xbm

This is no valid path name - nor is @/test.xbm, at least to my knowledge.
What happens if you supply the full path like this:

path = C:\\somedir\\test.xbm

-- 
Regards,

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


Re: How to send browser to open a different URL

2005-03-12 Thread Mike Wimpe
although a bit more than I bargained for, this does has some good info,
in case you are way in the future of this post...

love,

mike

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


Re: Licensing Python code under the Python license

2005-03-12 Thread Ville Vainio
 Daniel == Daniel Keep [EMAIL PROTECTED] writes:

Daniel Thanks for the advice.  I'll probably go with either the
Daniel BSD license, or possibly the LGPL.  But I'm leaning
Daniel towards the BSD since it fits on the screen...

Isn't MIT license even shorter and simpler? A while ago some Debian
guys were speculating whether even BSD license is free enough to
include in Debian...

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wishlist item: itertools.flatten

2005-03-12 Thread Ville Vainio
 Michael == Michael Spencer [EMAIL PROTECTED] writes:

Michael Here's a non-recursive implementation. 

Thanks.

Michael There are lots around.  

Yet another fact that suggest the inclusion in stdlib would make sense
;-).

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Tkinter Newbie question

2005-03-12 Thread Harlin Seritt
You have:

=@/test.xbm

take the '/' out or (if it is in a different dir which i think it is),
do

=/@test.xbm

also... make sure your *.xbm is really a bitmap file (that would just
be another thing to check... not to say its not the proper format)...


Regards,

Harlin Seritt

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


Re: Licensing Python code under the Python license

2005-03-12 Thread Harlin Seritt
If this is for making money, make it either a proprietary license or
BSD.

If you're giving it away and expect nothing for it except maybe fame,
do GPL.

:-)

Regards,

Harlin Seritt

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


Re: Licensing Python code under the Python license

2005-03-12 Thread Harlin Seritt
When you ask an opinion, you can expect a long thread list... even if
it's something inane like What kind of license should I use?...
hacker/geeks/freaks/wannabes are only too happy to issue an opinion --
warranted or otherwise...

Regards,

Harlin Seritt

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


Re: Python Tkinter Newbie question

2005-03-12 Thread Harlin Seritt
Try not to triple post if you can help it (I'll assume you accidentally
hit the SENT button three times whistles)

Regards,

Harlin Seritt

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


Re: is there a problem on this simple code

2005-03-12 Thread Harlin Seritt
hah, this code is anything but simple...

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


Re: a program to delete duplicate files

2005-03-12 Thread François Pinard
[Patrick Useldinger]

 Shouldn't you add the additional comparison time that has to be done
 after hash calculation? Hashes do not give 100% guarantee. If there's
 a large number of identical hashes, you'd still need to read all of
 these files to make sure.

Identical hashes for different files?  The probability of this happening
should be extremely small, or else, your hash function is not a good one.

I once was over-cautious about relying on hashes only, without actually
comparing files.  A friend convinced me, doing maths, that with a good
hash function, the probability of a false match was much, much smaller
than the probability of my computer returning the wrong answer, despite
thorough comparisons, due to some electronic glitch or cosmic ray.  So,
my cautious attitude was by far, for all practical means, a waste.

Similar arguments apply, say, for the confidence we may have in
probabilistic algorithms for the determination of number primality.

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


PythonWin

2005-03-12 Thread tkpmep
I have a Python program that collects user input using

msg = Enter the full path and name of the file to be processed: 
answer = raw_input(msg)

If I run it in IDLE, the question is splashed across the execution
window, and if it is long, simply wraps to the next line. Most
importantly, it is intelligible, because I see the entire message. I
enter my answer on the next line, and once again, I can see the entire
path and file name, even if it is longer than long.

However, if I run it in ActivePython's PythonWin, a small message box
pops up, with hardly any space to diplay msg and a smallish space into
which I can type my answer. How can I force PythonWin to get its input
from the execution window or to enlarge its message box sufficiently to
display the entire question?

Thomas Philips

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


Re: a RegEx puzzle (end of thread)

2005-03-12 Thread Charles Hartman
Won't extend this except to say thanks to Michael Spencer for another 
version. If I were doing it only once I'd use that. Since I do it more 
than once I should package it as a function.

Thanks.
Charles Hartman
Professor of English, Poet in Residence
http://cherry.conncoll.edu/cohar
http://villex.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Licensing Python code under the Python license

2005-03-12 Thread Martin v. Löwis
Ville Vainio wrote:
Daniel Thanks for the advice.  I'll probably go with either the
Daniel BSD license, or possibly the LGPL.  But I'm leaning
Daniel towards the BSD since it fits on the screen...
Isn't MIT license even shorter and simpler? A while ago some Debian
guys were speculating whether even BSD license is free enough to
include in Debian...
I encourage anybody to read Larry Rosen's book on this matter,
http://www.phptr.com/bookstore/product.asp?isbn=0131487876rl=1
Larry describes what he likes and dislikes about each of the licenses
from a legal point of view - giving insights you cannot possibly get
without law school.
For example, the BSD license reads
Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions are 
met: [...]

Compare this to the rights that a copyright holder has, e.g. from
http://www.whatiscopyright.org/
exclusive right to reproduce, prepare derivative works, distribute, 
perform and display the work publicly.

Strictly speaking, the BSD license gives non of these rights to the
licensee. The right to redistribute is probably *meant* to include
the right to reproduce - or is it meant to allow distribution only the
very copy that you received yourself (so you have no copy after 
distribution). The right to use is not one that copyright law has
control over, so what does it mean that the license gives you that
right? (*)

What about the right to prepare derivative works? Most likely,
the license is *meant* to give this right also, since you are
permitted to redistribute modifications (but then, perhaps only
modifications of the original author?). And so on.
Larry argues that a license should be legally meaningful, and
legally clear - or else there is little point in formulating
a license in the first place. If the license is formulated
ambiguously, in the case of doubt, courts will have to interpret
them. While courts are capable of producing such an interpretation,
they sometimes do so in a surprising manner (*).
I've been picking on the BSD license because I can remember
the complaints Larry has about its text.
Regards,
Martin
(*) If you are curious: Larry argues that, while the permission to
use is meaningless in copyright law, it is meaningful in patent
law. To use something, you need a license for all patents that
would otherwise prevent you from using it. So the permission to
use *could* be interpreted to be a patent license. However, most
likely, the authors of the license did not intend it to be a
patent license - so what the right to use is remains unclear,
until courts rule on this aspect.
--
http://mail.python.org/mailman/listinfo/python-list


Debugging Python Scripts inside other processes

2005-03-12 Thread A. Klingenstein
I embedded Python in a Windows C++ program. Now I want to debug my 
embedded scripts which of course won't run in any IDE process. 
Commercial IDEs like WingIDE can attach to external processes by 
importing a module in the scripts. Is there a debugger capable of this 
which is Free or Open Source?

What I need are the following things:
- runs in Windows
- single stepping
- variable watches
- breakpoints
Just the typical debugger stuff.
Alex
--
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 309 (Partial Function Application) Idea

2005-03-12 Thread Scott David Daniels
Reinhold Birkenfeld wrote:
Steven Bethard wrote:
Chris Perkins wrote:
Random idea of the day: How about having syntax support for
currying/partial function application, like this:
func(..., a, b)
func(a, ..., b)
func(a, b, ...)
That is:
1) Make an Ellipsis literal legal syntax in an argument list.
2) Have the compiler recognize the Ellipsis literal and transform
  the function call into a curried/parially applied function.
So the compiler would essentially do something like this:
func(a, ...) == curry(func, a)
func(..., a) == rightcurry(func, a)
func(a, ..., b) == rightcurry(curry(func,a), b)
I haven't though this through much, and I'm sure there are issues, but
I do like the way it looks.  The ... really stands out as saying
something is omitted here.
The interaction of this with keyword args and omitted args is
problematic (as is the case for rightcurry, in fact).  I can't
think of a good way to explain what _should_ happen for a
function defined as def function(*args, **kwargs): ... when you:
def fun(bug, frog, verb): ...
f1 = function(1, ..., frog=3)
f2 = f1(..., 4)
f2()
Keywords were why I did no rightcurry definition in the first place;
I couldn't convince myself there was a good, obvious, resolution.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: a program to delete duplicate files

2005-03-12 Thread Patrick Useldinger
François Pinard wrote:
Identical hashes for different files?  The probability of this happening
should be extremely small, or else, your hash function is not a good one.
We're talking about md5, sha1 or similar. They are all known not to be 
100% perfect. I agree it's a rare case, but still, why settle on 
something about right when you can have right?

I once was over-cautious about relying on hashes only, without actually
comparing files.  A friend convinced me, doing maths, that with a good
hash function, the probability of a false match was much, much smaller
than the probability of my computer returning the wrong answer, despite
thorough comparisons, due to some electronic glitch or cosmic ray.  So,
my cautious attitude was by far, for all practical means, a waste.
It was not my only argument for not using hashed. My algorithm also does 
less reads, for example.

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


Re: head for grouped data - looking for best practice

2005-03-12 Thread Steven Bethard
Harald Massa wrote:
def getdoublekey(row):
return row[0:2]
for key, bereich in groupby(eingabe,getdoublekey):
print Area:,key
for data in bereich:
print --data--, data[2:]
Why don't you just pass a slice to itemgetter?
py eingabe=[
... (Stuttgart,70197,Fernsehturm,20),
... (Stuttgart,70197,Brotmuseum,123),
... (Stuttgart,70197,Porsche,123123),
... (Leipzig,01491,Messe,91822),
... (Leipzig,01491,Schabidu,9181231),
... ]
py from itertools import groupby
py from operator import itemgetter
py for key, bereich in groupby(eingabe, itemgetter(slice(0, 2))):
... print Area:, key
... for data in bereich:
... print  --data--, data[2:]
...
Area: ('Stuttgart', '70197')
--data-- ('Fernsehturm', '20')
--data-- ('Brotmuseum', '123')
--data-- ('Porsche', '123123')
Area: ('Leipzig', '01491')
--data-- ('Messe', '91822')
--data-- ('Schabidu', '9181231')
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Safe Local XMLRPC

2005-03-12 Thread Michael Urman
[Sorry, I previously replied to Diez offlist, and probably to a
spam-protected address at that. Here's that reply and my followup
after reading up on pyro
]
On Sat, 12 Mar 2005 11:08:31 -0600, Michael Urman [EMAIL PROTECTED] wrote:
 On Sat, 12 Mar 2005 14:12:21 +0100, Diez B. Roggisch [EMAIL PROTECTED] 
 wrote:
  This might not be the answer you want, but I'd personally ditch xmlrpc and
  switch to something like pyro or even corba and implement a real
  authentication theme.
 
 I don't have a problem with switching interfaces so long as I can keep
 my (admittedly useless) feature of multiple simultaneous connections.
 I am hoping to avoid writing an authentication method, as some slight
 missteps there could lead to real trouble later; this is why I was
 hoping to do unix-domain socket transports which I could just set to
 read-write only by the owner on the filesystem itself.
 
  With corba/pyro, authenticate would return an object that implicitely has
  all the state needed - nameley who created the connection - and then you
  don't have to bother about that anymore.
 
 If I can get the authentication that I'm looking for that cheaply,
 then this does indeed sound like the way for me to go. I'm not worried
 about supporting remote connections, or anything of that nature, so
 local identity is sufficient. I'll look into pyro; conveniently
 there's a debian package for me to try.
 
 Thanks Diez!
 -m
 

Hmm. On inspection, pyro seems to be really heavy, what with its
requirement of a pyro-nameserver, and using TCP as the transport. I
think I'd still prefer convincing a variant of SimpleXMLRPCServer and
xmlrpclib.ServerProxy to use unix domain sockets and using filesystem
security to limit access to the owner.

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


Generating data types automatically

2005-03-12 Thread Torsten Bronger
Hallchen!

I have to generate a lot of data types (for ctypes by the way).  An
example is

ViUInt32  = u_long
ViPUInt32 = POINTER(ViUInt32)
ViAUInt32 = ViPUInt32

Therefore, I defined functions that should make my life easier:

def generate_type_dublett(visa_type, ctypes_type):
visa_type_name = visa_type.__name__
exec visa_type_name + = + ctypes_type.__name__
exec ViP + visa_type_name[2:] + =POINTER( + visa_type_name + )

def generate_type_triplett(visa_type, ctypes_type):
generate_type_dublett(visa_type, ctypes_type)
visa_type_name = visa_type.__name__
exec ViA + visa_type_name[2:] + = + ViP + visa_type_name[2:]

generate_type_triplett(ViUInt32, c_ulong)


However, this doesn't work, probably because the defined type exist
only locally within the function.

What is a better (and working) method for this task?

Thank you!

Tsch,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list


Add Properties to Instances?

2005-03-12 Thread Martin Miller
I'm trying to create some read-only instance specific properties, but
the following attempt didn't work:

 class Foobar(object):
 pass

 foobar = Foobar()
 foobar.x = property(fget=lambda: 42)

 print foobar.x:, foobar.x

Which results in the following ouput instead of '42':
  foobar.x: property object at 0x00AE57B0

I also tried this:
 foobar.__dict__['x'] = property(fget=lambda: 42)
but get the same behavior.

Can anyone tell me what's wrong with this approach (and perhaps the
correct way to do it, if there is one)?

TIA,
Martin

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


Re: Generating data types automatically

2005-03-12 Thread Torsten Bronger
Hallchen!

Torsten Bronger [EMAIL PROTECTED] writes:

 I have to generate a lot of data types (for ctypes by the way).
 An example is

 ViUInt32  = u_long
 ViPUInt32 = POINTER(ViUInt32)
 ViAUInt32 = ViPUInt32

 Therefore, I defined functions that should make my life easier:

 [...]

 However, this doesn't work, probably because the defined type
 exist only locally within the function.

Okay this works:

def generate_type_dublett(visa_type, ctypes_type):
return visa_type + = + ctypes_type + ; + \
ViP + visa_type[2:] + =POINTER( + visa_type + )

def generate_type_triplett(visa_type, ctypes_type):
return generate_type_dublett(visa_type, ctypes_type) + ; + \
ViA + visa_type[2:] + = + ViP + visa_type[2:]

exec generate_type_triplett(ViUInt32,  c_ulong  )
...


Not very beautiful, though.

Tsch,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add Properties to Instances?

2005-03-12 Thread Steven Bethard
Martin Miller wrote:
I'm trying to create some read-only instance specific properties, but
the following attempt didn't work:

class Foobar(object):
   pass
foobar = Foobar()
foobar.x = property(fget=lambda: 42)
print foobar.x:, foobar.x

[snip]
Can anyone tell me what's wrong with this approach (and perhaps the
correct way to do it, if there is one)?
Properties cannot be defined on a per-instance basis.  Properties must 
be defined at the class level.  So you need to do something like:

py class Foobar(object):
... x = property(fget=lambda self: 42)
...
py Foobar().x
42
or
py class Foobar(object):
... pass
...
py Foobar.x = property(fget=lambda self: 42)
py Foobar().x
42
If you want to have different properties on different instances, you'll 
need to make each of the different instances a different subtype of 
Foobar, e.g.:

py class Foobar(object):
... pass
...
py foobar = type('FoobarSub', (Foobar,),
...   dict(x=property(fget=lambda self: 42)))()
py foobar.x
42
py Foobar().x
Traceback (most recent call last):
  File interactive input, line 1, in ?
AttributeError: 'Foobar' object has no attribute 'x'
What's the situation in which you think you want different properties 
for different instances of the same class?

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


Re: Debugging Python Scripts inside other processes

2005-03-12 Thread Robin Becker
A. Klingenstein wrote:
I embedded Python in a Windows C++ program. Now I want to debug my 
embedded scripts which of course won't run in any IDE process. 
Commercial IDEs like WingIDE can attach to external processes by 
importing a module in the scripts. Is there a debugger capable of this 
which is Free or Open Source?

What I need are the following things:
- runs in Windows
- single stepping
- variable watches
- breakpoints
Just the typical debugger stuff.
Alex
I used hapdebugger for such a purpose some time ago, but I believe it 
needs a special startup python.exe.
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Can't seem to insert rows into a MySQL table

2005-03-12 Thread grumfish
I'm trying to add a row to a MySQL table using insert. Here is the code:
connection = MySQLdb.connect(host=localhost, user=root, passwd=pw, 
db=japanese)
cursor = connection.cursor()
cursor.execute(INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s, 
%s), (a, b, c) )
connection.close()

After running, a SELECT * on the table shows no new rows added. Adding 
rows using the MySQL client works fine. With the Python script, nothing. 
There are no exceptions raised or any output at all. The rowcount of the 
cursor is 1 after the execute is 1 and the table's auto_increment value 
is increased for each insert done. Can anybody help? I'm fairly new to 
MySQL so I'm afraid its going to be a stupid oversight on my part. Thank 
you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generating data types automatically

2005-03-12 Thread Michael Hoffman
Torsten Bronger wrote:
def generate_type_dublett(visa_type, ctypes_type):
visa_type_name = visa_type.__name__
exec visa_type_name + = + ctypes_type.__name__
exec ViP + visa_type_name[2:] + =POINTER( + visa_type_name + )
You shouldn't need to use exec for this, and it is best to avoid its use.
If you MUST do things this way, then you can add items to the globals()
dictionary. See the library reference for more details. It's probably
best to avoid globals() as well, although it's not as bad as exec/eval.
Personally, I think it would be better to define your types like this:
ViUInt32, ViPUInt32, ViAUInt32 = generate_type_triplet(u_long)
That way you will easily be able to find the initial definition of
the object by searching and replacing. You'll also have to jump through
fewer weird hoops to get the result you want.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: bsddb support for berkeley db 4.3?

2005-03-12 Thread Martin v. Löwis
[EMAIL PROTECTED] wrote:
It doesn't seem like the python 2.4(and the recent 2.4.1) support
berkeley db 4.3. 
What makes you say that? It builds fine for me.
bsddb3(at pybsddb.sf.net) already supports 4.3 since last December(but
doesn't explicitly support win32 -- see the assert statement in
setup.py). I thought the bsddb3 project were merged into the python
project. Hasn't it?
It certainly has. However, the authors of bsddb3 are free to release
new versions of their software whenever they wish to, independent of
any Python releases. They are encouraged to merge their changes into the
Python CVS, but they are requested to avoid adding new features to
Python 2.4.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generating data types automatically

2005-03-12 Thread Steven Bethard
Torsten Bronger wrote:
Okay this works:
def generate_type_dublett(visa_type, ctypes_type):
return visa_type + = + ctypes_type + ; + \
ViP + visa_type[2:] + =POINTER( + visa_type + )
def generate_type_triplett(visa_type, ctypes_type):
return generate_type_dublett(visa_type, ctypes_type) + ; + \
ViA + visa_type[2:] + = + ViP + visa_type[2:]
exec generate_type_triplett(ViUInt32,  c_ulong  )
...
Exec is nasty.  Can you create a dict and use an update to globals instead?
py def get_types(visa_type_name, ctypes_type):
... pointer = ctypes.POINTER(ctypes_type)
... return {'Vi%s' % visa_type_name:ctypes_type,
... 'ViP%s' % visa_type_name:pointer,
... 'ViA%s' % visa_type_name:pointer}
...
py globals().update(get_types(UInt32, ctypes.c_ulong))
py ViUInt32
class 'ctypes.c_ulong'
py ViPUInt32
class 'ctypes.LP_c_ulong'
py ViAUInt32
class 'ctypes.LP_c_ulong'
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can't seem to insert rows into a MySQL table

2005-03-12 Thread Patrick Useldinger
grumfish wrote:
connection = MySQLdb.connect(host=localhost, user=root, passwd=pw, 
db=japanese)
cursor = connection.cursor()
cursor.execute(INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s, 
%s), (a, b, c) )
connection.close()
Just a guess in the dark (I don't use MySQL): is commit implicit, or 
do you have to add it yourself?

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


Re: Add Properties to Instances?

2005-03-12 Thread Jeremy Bowers
On Sat, 12 Mar 2005 09:48:42 -0800, Martin Miller wrote:

 I'm trying to create some read-only instance specific properties, but the
 following attempt didn't work:

I'm going to echo Steven's comment: What's the situation in which you
think you want different properties for different instances of the same
class?

Another thought would be a custom __setattr__ and a bit of support:

Python 2.3.5 (#1, Mar  3 2005, 17:32:12) 
[GCC 3.4.3  (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2
Type help, copyright, credits or license for more information.
 import sets
 class ReadOnlyAttributes(object):
... def __init__(self):
... self.__dict__['_readOnly'] = sets.Set()
... def addReadOnly(self, key, value):
... setattr(self, key, value)
... self._readOnly.add(key)
... def __setattr__(self, key, value):
... if key in self._readOnly:
... raise AttributeError(can't set attribute)
... self.__dict__[key] = value
... 
 r = ReadOnlyAttributes()
 r.a = 22
 r.a
22
 r.a = 23
 r.a
23
 r.addReadOnly(a, 22)
 r.a
22
 r.a = 23
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 9, in __setattr__
AttributeError: can't set attribute
 r.addReadOnly(a, 23)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 5, in addReadOnly
  File stdin, line 9, in __setattr__
AttributeError: can't set attribute


I don't guarantee this completely fits the bill but I'm sure you can adapt
it from here. 

Also note that, strictly speaking, you can't make a true read-only
attribute, only one that alerts a programmer if they try the simple way.
In a pure-Python object, there is always a way in. This shouldn't worry
you if you're using Python (We're all consenting adults here), but you
should also be aware of that. That said, this is certainly useful in the
real world.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: confusion around CustomException example in 'Python in a Nutshell'

2005-03-12 Thread erick_bodine

Peter Hansen wrote:
 [EMAIL PROTECTED] wrote:
  In Martinelli's Nutshell book in the Exceptions chapter there is an
  example of a custom exception class (pg.112) that I am trying to
  implement without success.  The custom exception class example
pulls
  sys.exc_info() into an attribute and I am assuming that the
attribute
  would then contain the raised exception info in a tuple (admittedly
I
  could be assuming erroneously).
 
  class LinuxDriverError(Exception):
  def __init__(self, *args):
  Exception.__init__(self, *args)
  self.message = args[0]
  self.wrapped_exc = sys.exc_info()
 
  try:
  raise LinuxDriverError, raising Cain!
  except CustomException, error:
  print error.message
  print error.wrapped_exc
 
  # just checking
  print sys.exc_info(): , sys.exc_info()
 
  If I run the above code I get the following output:
 
  Just raising Cain!
  wrapped_exc:  (None, None, None)
  sys.exc_info():  (class __main__.LinuxDriverError at 0xf6f774dc,
  __main__.LinuxDriverError instance at 0xf6f74bec, traceback
object
  at 0xf6f7193c)
 
  I do not understand why the wrapped_exc attribute contains no
objects.

 Because at the time you create the exception there is
 no current exception as seen from the point of view
 of sys.exc_info().

 Given the way this class was written, it is clearly
 intended to be raised from within an except statement
 as a result of another exception having been caught.

 Try this instead:

 try:
  try:
  1/0
  except:
  raise LinuxDriverError, 'raising Cain!'
 except Exception, ex:
  print ex.wrapped_exc

This clears the fog a little.

 By the way, the code you show is probably not what you
 were actually running anyway... you caught a
 CustomException but the LinuxDriverError is not
 a subclass of that class so it wouldn't/shouldn't
 have been caught.

classic keyboard fumbling  What I am trying to do is get information
from a raised custom exception.  I am catching the exception in a
main() function but it was actually raised in a separate module
function.  It would be nice if I could print out where the exception
was raised from (module.function name + line number).

-
def some_module_function():
if something_bad:
raise LinuxDriverError, raising..
---

def main():
try:
mymodule.some_module_function()
except LinuxDriverError, error:
print error.message
print error.from_where



Thanks,

--Erick


 
 -Peter

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


Building Python 2.4 with icc and processor-specific optimizations

2005-03-12 Thread Michael Hoffman
Just out of curiosity, I was wondering if anyone has
compiled Python 2.4 with the Intel C Compiler and its
processor specific optimizations. I can build it fine
with OPT=-O3 or OPT=-xN but when I try to combine
them I get this as soon as ./python is run:

case $MAKEFLAGS in \
*-s*)  CC='icc -pthread' LDSHARED='icc -pthread -shared' OPT='-DNDEBUG -O3 -xN' 
./python -E ./setup.py -q build;; \
*)  CC='icc -pthread' LDSHARED='icc -pthread -shared' OPT='-DNDEBUG -O3 -xN' 
./python -E ./setup.py build;; \
esac
'import site' failed; use -v for traceback
Traceback (most recent call last):
  File ./setup.py, line 6, in ?
import sys, os, getopt, imp, re
  File /usr/local/src/Python-2.4/Lib/os.py, line 130, in ?
raise ImportError, 'no os specific module found'
ImportError: no os specific module found
make: *** [sharedmods] Error 1

Also, if I run ./python, I have this interesting result:

$ ./python
'import site' failed; use -v for traceback
Python 2.4 (#34, Mar 12 2005, 18:46:28)
[GCC Intel(R) C++ gcc 3.0 mode] on linux2
Type help, copyright, credits or license for more information.
 import sys
 sys.builtin_module_names
('__main__', '__builtin__', '__builtin__', '__builtin__', '__builtin__', 
'__builtin__', '__builtin__', '__builtin__', '__builtin__', '__builtin__', 
'__builtin__', '__builtin__', '__builtin__', 'exceptions', 'gc', 'gc')

Whoa--what's going on? Any ideas?
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: Debugging Python Scripts inside other processes

2005-03-12 Thread A. Klingenstein
Robin Becker wrote:
A. Klingenstein wrote:
I embedded Python in a Windows C++ program. Now I want to debug my 
embedded scripts which of course won't run in any IDE process. 
Commercial IDEs like WingIDE can attach to external processes by 
importing a module in the scripts. Is there a debugger capable of this 
which is Free or Open Source?

What I need are the following things:
- runs in Windows
- single stepping
- variable watches
- breakpoints
Just the typical debugger stuff.
Alex
I used hapdebugger for such a purpose some time ago, but I believe it 
needs a special startup python.exe.
I looked at it, but couldn't get it to work. A special python.exe won't 
work for me since I only link against python24.dll, nothing else

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


Re: Wishlist item: itertools.flatten

2005-03-12 Thread gene . tani
window / cons / fencepost / slice functions: +1

(with a flag to say if you want to truncate or pad incomplete tuples at
end of input sequence.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303279
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303060
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347689

Probably more recipes in there, (and not CPAN-ish yet) but multiple
submissions bespeak a certain need, i think.

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


Re: Safe Local XMLRPC

2005-03-12 Thread Michael Urman
Thanks for your time everyone; I got it XMLRPC working over unix
domain stream sockets. In case people are interested, here's the
pieces I put together. I'm sure they throw away a little flexibility,
but they work for my purpose. Any pointers to make the code more
robust, or do less total overriding of should-be-arguments
appreciated.

-m

from SocketServer import UnixStreamServer
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher,
SimpleXMLRPCRequestHandler
from xmlrpclib import ServerProxy, Fault, Transport
from socket import socket, AF_UNIX, SOCK_STREAM

# Server side is pretty easy - almost a direct copy of SimpleXMLRPCServer
SOCKPATH = 'testsock'
class UnixStreamXMLRPCServer(UnixStreamServer, SimpleXMLRCPDispatcher):
def__init__(self, addr=SOCKPATH, requestHandler=SimpleXMLRPCRequestHandler):
self.logRequests = 0 # critical, as logging fails with UnixStreamServer
SimpleXMLRPCDispatcher.__init__(self)
UnixStreamserver.__Init__(self, addr, requestHandler)

# Client is a lot more complicated and feels fragile
from httplib import HTTP, HTTPConnection
class UnixStreamHTTPConnection(HTTPConnection):
def connect(self):
self.sock = socket(AF_UNIX, SOCK_STREAM)
self.sock.connect(SOCKPATH)

class UnixStreamHTTP(HTTP):
_connection_class = UnixStreamHTTPConnection

class UnixStreamTransport(Transport):
def make_connection(self, host):
return UnixStreamHTTP(SOCKPATH) # overridden, but prevents IndexError

proxy = ServerProxy('http://' + SOCKPATH, transport=UnixStreamTransport())
# proxy now works just like any xmlrpclib.ServerProxy
-- 
http://mail.python.org/mailman/listinfo/python-list


SimpleXMLServer meets inetd

2005-03-12 Thread Marek Kubica
Hi!

I was thinking about connecting SimpleXMLRPCServer with inetd.. but I
haven't been able to replace the socket by sys.stdin and sys.stdout. Maybe
socket.fromfd(sys.stdin.fileno()) could help me, but I can't get it to
work, I always get connection refused. Any ideas?

greets,
Marek

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


Re: Can't seem to insert rows into a MySQL table

2005-03-12 Thread Stephen Prinster
grumfish wrote:
 The rowcount of the
cursor is 1 after the execute is 1 and the table's auto_increment value 
is increased for each insert done. 
If the auto_increment is increased, then it seems like the row was 
inserted.  Are you sure the problem is not with your SELECT attempt? 
Just a guess, but it seems like the first time I used MySQLdb, I was 
confused by the need to do a fetchall() (or fetchone() or 
fetchmany()) after executing the SELECT.

Something like this (not tested):
result = cursor.execute(SELECT * FROM edict WHERE kanji = 'a')
print result.fetchall()
HTH,
Steve P.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 309 (Partial Function Application) Idea

2005-03-12 Thread Chris Perkins
Scott David Daniels wrote:
Chris Perkins wrote:
Random idea of the day: How about having syntax support for
currying/partial function application, like this:
func(..., a, b)
func(a, ..., b)
func(a, b, ...)

That is:
1) Make an Ellipsis literal legal syntax in an argument list.
2) Have the compiler recognize the Ellipsis literal and transform
   the function call into a curried/parially applied function.
So the compiler would essentially do something like this:

func(a, ...) == curry(func, a)
func(..., a) == rightcurry(func, a)
func(a, ..., b) == rightcurry(curry(func,a), b)

The interaction of this with keyword args and omitted args is
problematic (as is the case for rightcurry, in fact).  I can't
think of a good way to explain what _should_ happen for a
function defined as def function(*args, **kwargs): ... when you:

 def fun(bug, frog, verb): ...
 f1 = function(1, ..., frog=3)
 f2 = f1(..., 4)
 f2()

Keywords were why I did no rightcurry definition in the first place;
I couldn't convince myself there was a good, obvious, resolution.


I agree that it's not obvious what _should_ happen in complex cases.

I wrote up a psuedo-implementation to play with, just to get a feel
for it.  It works only on @curryable functions, and I use __ in place
of  I think that's about as close as I can get in pure Python.

def curryable(func):
This hurts my brain a little bit, but I _think_ it works.
def proxyfunc(*args, **kwds):
if list(args).count(Ellipsis)  1:
raise TypeError('Your mother was a hampster...')
if Ellipsis in args:
@curryable
def curried(*a, **k): 
kwdict = kwds.copy()
kwdict.update(k)
epos = list(args).index(Ellipsis)
return func(*(args[:epos] + a + args[epos+1:]), **kwdict)
return curried
return func(*args, **kwds)
return proxyfunc

def test():
__ = Ellipsis
@curryable
def fun(bug, frog, verb):
print bug, frog, verb

f1 = fun(1, __, frog=3)
f2 = f1(__, 4)
try:
f2()
except TypeError, e:
print e # multiple values for keyword 'frog'

f1 = fun(1, __, verb=3) 
f2 = f1(__, 4) 
f2()
f2(verb=99)

try:
f1(__, 2, __)
except TypeError, e:
print e

if __name__ == '__main__':
test()


After playing with this a bit, I found the semantics to be reasonably 
obvious once I got used to it; at least in the cases I tried.  I'd be
quite happy to have anything fishy throw an exception.  Cases where 
I would actually use this would be quite simple, I think.

On the other hand, I'm not convinced that this construct would be
especially useful.  I spent some time looking at uses of lambda in the
standard library, hoping to find lots of examples where a (...)
function would be more readable, but I eventually gave up. (Found
dozens of cases where a list-comp or genexp would be better, though).

While I think that func(x, ...) is more readable than partial(func, x),
I'm not sure that I would use either of them often enough to warrant
special syntax. If anyone disagrees, feel free to petition python-dev;
I don't expect to pursue this any further.

Thanks to all for your comments.


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


Re: Can't seem to insert rows into a MySQL table

2005-03-12 Thread deelan
grumfish wrote:
I'm trying to add a row to a MySQL table using insert. Here is the code:
connection = MySQLdb.connect(host=localhost, user=root, passwd=pw, 
db=japanese)
cursor = connection.cursor()
cursor.execute(INSERT INTO edict (kanji, kana, meaning) VALUES (%s, %s, 
%s), (a, b, c) )
connection.close()
which version of MySQLdb are you running? versions
1.1.6 and below gained a connection.autocommit) method set by default
to *false*.
Try this, instead:
connection = MySQLdb.connect(host=localhost, user=root, passwd=pw, 
db=japanese)

connection.autocommit(True)   # --- note this
cursor = connection.cursor()
...other commands...
doing this you tell MySQL to automatically commit changes to db after
every UPDATE or INSERT.  turning autocommit to false is useful when
you wish to do changes in batches and maybe rollback the entire operation
if something went wrong (see commit() and rollback() methods for this).
hope this helps,
deelan.
--
Però è bello sapere che, di questi tempi spietati, almeno
un mistero sopravvive: l'età di Afef Jnifen. -- dagospia.com
--
http://mail.python.org/mailman/listinfo/python-list


Thank you. New question concerning text encoding

2005-03-12 Thread grumfish
Patrick Useldinger wrote:
Just a guess in the dark (I don't use MySQL): is commit implicit, or 
do you have to add it yourself?
Thank you. Inserts work fine now.
Another question. I'm trying to insert Japanese text into the table. I 
created the database using 'CHARACTER SET UTF8'. In Python I do a 
.encode(utf-8) on any strings before inserting them into the database. 
When I try to read them back from the database I don't get the original 
string. I've played with .decode(utf-8) on strings returned from MySQL 
but with no luck. How can I insert Japanese text into a MySQL database 
and the read it out again?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can't seem to insert rows into a MySQL table

2005-03-12 Thread deelan
deelan wrote:
which version of MySQLdb are you running? versions
1.1.6 and below gained a connection.autocommit) method set by default
ehm, 1.1.6 and *above*, of course.  :)
--
Però è bello sapere che, di questi tempi spietati, almeno
un mistero sopravvive: l'età di Afef Jnifen. -- dagospia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Safe Local XMLRPC

2005-03-12 Thread Diez B. Roggisch
 Hmm. On inspection, pyro seems to be really heavy, what with its
 requirement of a pyro-nameserver, and using TCP as the transport. 

The nameserver is purely optional. Regarding the overhead of transport -
well, I didn't check pyro on that, but corba is 10-100 times faster over
the network than soap/xmlrpc. So while the local loopback _might_ be slower
(I'm not even sure about that) than the unix socket, marshalling data as
xml has its own cost overhead.


-- 
Regards,

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


Installation Guide

2005-03-12 Thread Online Support


Hello, 

I'm in critical need to install Python Imaging Library on my linux/cpanel server. I'm not very experienced and I almost always have to use instalation guides. I have downloaded the software, unzipped it, and now I think I just need to install it somehow. Are there files that need to be modified first? I think there is a file called setup.py but I'm not sure how I can run that file. 

I would really appreciate your reply, or if you could point me to an installation giude online for PIL

Best Regards,
- Kevin
		Do you Yahoo!? 
Yahoo! Small Business - Try our new resources site! -- 
http://mail.python.org/mailman/listinfo/python-list

wishlist item: itertools.partition (WAS: Wishlist item: itertools.flatten)

2005-03-12 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
 window / cons / fencepost / slice functions: +1

 (with a flag to say if you want to truncate or pad incomplete tuples
 at end of input sequence.

 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303279
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303060
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347689

 Probably more recipes in there, (and not CPAN-ish yet) but multiple
 submissions bespeak a certain need, i think.
Yes, also worth noting is the thread:
http://mail.python.org/pipermail/python-list/2005-January/263004.html
which concludes with:
from itertools import islice, chain, repeat
def partition(iterable, part_len):
 itr = iter(iterable)
 while 1:
 item = tuple(islice(itr, part_len))
 if len(item)  part_len:
 raise StopIteration
 yield item
def padded_partition(iterable, part_len, pad_val=None):
 padding = repeat(pad_val, part_len-1)
 itr = chain(iter(iterable), padding)
 return partition(itr, part_len)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: pre-PEP: Print Without Intervening Space

2005-03-12 Thread Marcin Ciura
Bengt Richter wrote:
BTW, what makes you think any self-respecting scientist wouldn't be insulted
by the idea of your spoon-feeding them a dumbed-down programming equivalent of
See Spot run?
Am I right thinking that your dream 3 R's curriculum starts with
Stately, plump Buck Mulligan and Plya Enumeration Theorem?
Most of them have no previous programming experience, mind you.
Of course, you may be a suffering victim of circumstances, I don't know.
They're not so bad: I deliver the lectures (1.5 h/week), and there are
also laboratory classes (1.5 h/week). During one semester, most of
Python topics are covered.
Fortunately,
Python is not that hard, and rapidly becomes fun unless the initial experience
is structured against discovering the expressive power that is so enjoyable.
I wholeheartedly agree with you in this point. I'm sure my students
would appreciate being taught Python instead of Pascal if they had
a chance to compare them.
If you want the effect of print x, y, fn(z), etc without spaces, why don't you
just write a function that will let you spell it simply, like
Excellent advice, provided that you already know the concept
of user-defined functions.
IMO teachers should lead their students into contact with reality,
not insulate them from it with delusionary simplifications that
they will have to unlearn in order to progress.
I'm not sure what you mean by delusionary simplifications,
but I hope you meant nothing insulting. They already know how to
use string interpolation, and as soon as they learn how to mutate
the contents of a list, I'll tell them to use looped .append()
followed by .join() instead of looped string concatenation,
and explain why.
Best regards,
  Marcin
--
http://mail.python.org/mailman/listinfo/python-list


blocking a program until a non-Python process terminates

2005-03-12 Thread Earl Eiland
I'm running an .exe in Python, using subProcess.Popen.  The executable
writes data to a file I process later on in the program.  Unfortunately,
my program returns the error no such file  How do I block
execution until the external executable terminates?

Earl

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


Re: Why does this not work?

2005-03-12 Thread Gensek
PingGUI is a program that nobody but me knows anything about. If I
wanted help from people who are experts on it, I'd get nothing at all.

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


Re: Installation Guide

2005-03-12 Thread Skip Montanaro

Kevin I'm in critical need to install Python Imaging Library on my
Kevin linux/cpanel server. I'm not very experienced and I almost always
Kevin have to use instalation guides.

Take a look at the BUILDME and README files in the top-level directory.

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


Re: Add Properties to Instances?

2005-03-12 Thread Martin Miller
So far a couple of people have asked:
 What's the situation in which you think you want different properties
 for different instances of the same class?

Fair enough -- here goes:

Essentially what I'm doing is implementing (yes, yet another ;-)
'enumeration' class using an an approach which involves an instance
factory function which returns a customized version of a predefined
generic '_Enum' class instance.

It does this by first creating an instance of the generic class and
then adds attributes (enumerator ids and corresponding values among
others) to it which are specific to the enumeration being created. This
all works pretty well, but I would like to make the values associated
with the ids immutable -- through normal means, at least.

It's not feature complete, but I would be happy post the current code
if there is interest in more of the details. Meanwhile, I'm going to
study the replies so far and think about the whole issue (and design) a
little more.

Thanks to all who have replied,
Martin

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


Re: PEP 309 (Partial Function Application) Idea

2005-03-12 Thread Steven Bethard
Chris Perkins wrote:
[snip implementation]
While I think that func(x, ...) is more readable than partial(func, x),
I'm not sure that I would use either of them often enough to warrant
special syntax.
Interesting.  Thought it might be worth listing a few of the current 
places people use lambdas (and lambda replacements like 
operator.attrgetter/itemgetter) that this might be useful, and a few of 
the places where it probably wouldn't be.

Places where it might be useful:
getting attributes:
lambda obj: obj.attr
attrgetter('attr')
getattr(__, attr)
getting attributes with defaults[1]:
objs.sort(key=lambda a: getattr(a, 'lineno', 0))
objs.sort(key=getattr(__, 'lineno', 0)
Places where you might be able to use it (with some changes):
using bound methods[1][2]:
map(lambda x: x.strip(), lst)
map(str.strip(), lst) #!! doesn't work for unicode
map(methodcaller('strip'), lst) # proposed by Alex Martelli
__.strip() # note that calling strip on __ would have to
   # return a curryable looking for one arg...
Places where I can't see how to use it:
creating a function out of nothing[2]:
button.setlabel(lambda: 'Click Me!')
button.setlabel('Click Me!'.__str__) # works 'cause str returns self
adding arguments[1]:
lambda x: 
adding method to an instance[1]:
self.plural = lambda n: int(n != 1)
So I guess it's a cool idea, but I don't know if it's really going to 
pacify anyone who is upset about losing lambda...  (Not that I'm 
suggesting that was your intention -- but it's something that's been 
recently on my mind.)

Steve
[1]http://mail.python.org/pipermail/python-list/2004-December/257990.html
[2]http://www.artima.com/forums/flat.jsp?forum=106thread=98196
--
http://mail.python.org/mailman/listinfo/python-list


Re: Safe Local XMLRPC

2005-03-12 Thread Stephen Waterbury
Diez B. Roggisch wrote:
... corba is 10-100 times faster over
the network than soap/xmlrpc. ...
I'm not challenging these statistics (because I don't know),
but I would be interested in the source.  Are you referring
to the results of an actual benchmark, or something more
subjective?
Steve
--
http://mail.python.org/mailman/listinfo/python-list


dinamically altering a function

2005-03-12 Thread vegetax

I i need a decorator that adds a local variable in the function it
decorates, probably related with nested scopes, for example:

def dec(func):
def wrapper(obj = None):
if not obj : obj = Obj()
  bind obj to func
 return func()

return wrapper()

@dec()
def fun(b):
obj.desc = 'marked'
obj.b = b
return obj

so the call to fun : fun(obj = myobj,'b argument')
or fun('b argument')

So the function fun assumes it has an obj instance and other instance
objects computed by the decorator, this decorator will be like a generic
factory for this kind of functions,which depends on the decorator to work.




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


Re: newbie: dictionary - howto get key value

2005-03-12 Thread Bengt Richter
On Thu, 10 Mar 2005 18:56:41 +0100, bruno modulix [EMAIL PROTECTED] wrote:

G. Völkl wrote:
 Hello,
 
 I use a dictionary:
 
 phone = {'mike':10,'sue':8,'john':3}
 
 phone['mike']   -- 10
 
 I want to know who has number 3?
 3 --  'john'

Note that you can have many keys with the same value:
phone = {'mike':10,'sue':8,'john':3, 'jack': 3, 'helen' : 10}


 How to get it in the python way ?

simplest way I could think of in 30':
def key_from_value(aDict, target):
   return [key for key, value in aDict.items() if value==target]

key_from_value(phone, 3)
-- ['john', 'jack']

but this is a linear search, so not very efficient if phone is big.
Then you may want to maintain a reversed index:
(here again, simplest way I could think of)

def rev_index(aDict):
   r = {}
   for key, value in aDict.items():
 if r.has_key(value):
   r[value].append(key)
 else:
   r[value] = [key]
return r
rev_phone = rev_index(phone)
rev_phone
-- {8: ['sue'], 10: ['helen', 'mike'], 3: ['john', 'jack']}

{8: ['sue'], 10: ['helen', 'mike'], 3: ['john', 'jack']}

rev_phone[3]
-- ['john', 'jack']

But now you've got another problem : you need to update the reversed 
index each time you modify the dictionary... Which would lead to writing 
a class extending dict, maintaining a reversed index, and exposing extra 
methods to handle this.

Not very tested:

 twoway.py 
class Twoway(dict):
def __setitem__(self, name, number):
dict.__setitem__(self, name, number)
self.setdefault(number, []).append(name)
def __delitem__(self, name):
num = self[name]
dict.__delitem__(self, name)
self[num].remove(name)
if not self[num]: del self[num]
def __init__(self, src=None):
if src is None: return
dict.__init__(self, src)
for name, num in self.items(): self.setdefault(num, []).append(name)

if __name__ == '__main__':
phone = Twoway({'mike':10,'sue':8,'john':3, 'jack': 3, 'helen' : 10})
print 'jack:', phone['jack']
print 'same phone as jack:', phone[phone['jack']]
print 'deleting jack ...'; del phone['jack']
print 'john:', phone['john']
print phone
-

[13:05] C:\pywk\sovmpy24 twoway.py
jack: 3
same phone as jack: ['john', 'jack']
deleting jack ...
john: 3
{'mike': 10, 3: ['john'], 8: ['sue'], 10: ['mike', 'helen'], 'sue': 8, 'helen': 
10, 'john': 3}

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


error sending path to Win OS

2005-03-12 Thread Earl Eiland
os.path.getsize(Inputdirectory + '\\' + Filename) works, but
os.path.getsize(Inputdirectory + '\\' + Filename.split('.') + '.ext')
Fails reporting no such file or directory
InputDirectory\\Filename.ext.
os.path.getsize(Inputdirectory + r'\' + Filename.split('.') + '.ext')
generates a syntax error.

Earl Eiland

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


Re: a program to delete duplicate files

2005-03-12 Thread John Machin

Patrick Useldinger wrote:
 John Machin wrote:

  Just look at the efficiency of processing N files of the same size
S,
  where they differ after d bytes: [If they don't differ, d = S]
 
  PU: O(Nd) reading time, O(Nd) data comparison time [Actually (N-1)d
  which is important for small N and large d].
 
  Hashing method: O(NS) reading time, O(NS) hash calc time


 Shouldn't you add the additional comparison time that has to be done
 after hash calculation? Hashes do not give 100% guarantee. If there's
a
 large number of identical hashes, you'd still need to read all of
these
 files to make sure.

Maybe I was wrong: lawyers are noted for irritating precision. You
meant to say in your own defence: If there are *any* number (n = 2)
of identical hashes, you'd still need to *RE*-read and *compare* 

1. You are ahead already even before adding any extra time for
comparison on files with equal hashes.

2. As others have explained, with a decent hash function, the
probability of a false positive is vanishingly small. Further, nobody
in their right mind [1] would contemplate automatically deleting n-1
out of a bunch of n reportedly duplicate files without further
investigation. Duplicate files are usually (in the same directory with
different names or in different-but-related directories with the same
names) and/or (have a plausible explanation for how they were
duplicated) -- the one-in-zillion-chance false-positive should stand
out as implausible.

Different subject: maximum number of files that can be open at once. I
raised this issue with you because I had painful memories of having to
work around max=20 years ago on MS-DOS and was aware that this magic
number was copied blindly from early Unix. I did tell you that
empirically I could get 509 successful opens on Win 2000 [add 3 for
stdin/out/err to get a plausible number] -- this seems high enough to
me compared to the likely number of files with the same size -- but you
might like to consider a fall-back detection method instead of just
quitting immediately if you ran out of handles.

You wrote at some stage in this thread that (a) this caused problems on
Windows and (b) you hadn't had any such problems on Linux.

Re (a): what evidence do you have?

Re (b): famous last words! How long would it take you to do a test and
announce the margin of safety that you have?


[1] Yes, I am aware of the subject of this thread.

Regards,

John

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


Re: head for grouped data - looking for best practice

2005-03-12 Thread Harald Massa
Steve,


 Why don't you just pass a slice to itemgetter?
py for key, bereich in groupby(eingabe, itemgetter(slice(0, 2))):


WHOW, that is great! that makes it really simple, just have to structure 
the SQL to make a real cut first, serve first structure.

Thanks to all who helped!

also the function factory function bei Dietz was very helpfull; and 
Peters classes looked really impressive!

Thanks again... now my code will be even clearer.

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


Re: a program to delete duplicate files

2005-03-12 Thread Patrick Useldinger
John Machin wrote:
Maybe I was wrong: lawyers are noted for irritating precision. You
meant to say in your own defence: If there are *any* number (n = 2)
of identical hashes, you'd still need to *RE*-read and *compare* 
Right, that is what I meant.
2. As others have explained, with a decent hash function, the
probability of a false positive is vanishingly small. Further, nobody
in their right mind [1] would contemplate automatically deleting n-1
out of a bunch of n reportedly duplicate files without further
investigation. Duplicate files are usually (in the same directory with
different names or in different-but-related directories with the same
names) and/or (have a plausible explanation for how they were
duplicated) -- the one-in-zillion-chance false-positive should stand
out as implausible.
Still, if you can get it 100% right automatically, why would you bother 
checking manually? Why get back to argments like impossible, 
implausible, can't be if you can have a simple and correct answer - 
yes or no?

Anyway, fdups does not do anything else than report duplicates. 
Deleting, hardlinking or anything else might be an option depending on 
the context in which you use fdups, but then we'd have to discuss the 
context. I never assumed any context, in order to keep it as universal 
as possible.

Different subject: maximum number of files that can be open at once. I
raised this issue with you because I had painful memories of having to
work around max=20 years ago on MS-DOS and was aware that this magic
number was copied blindly from early Unix. I did tell you that
empirically I could get 509 successful opens on Win 2000 [add 3 for
stdin/out/err to get a plausible number] -- this seems high enough to
me compared to the likely number of files with the same size -- but you
might like to consider a fall-back detection method instead of just
quitting immediately if you ran out of handles.
For the time being, the additional files will be ignored, and a warning 
is issued. fdups does not quit, why are you saying this?

A fallback solution would be to open the file before every _block_ read, 
and close it afterwards. In my mind, it would be a command-line option, 
because it's difficult to determine the number of available file handles 
in a multitasking environment.

Not difficult to implement, but I first wanted to refactor the code so 
that it's a proper class that can be used in other Python programs, as 
you also asked. That is what I have sent you tonight. It's not that I 
don't care about the file handle problem, it's just that I do changes by 
(my own) priority.

You wrote at some stage in this thread that (a) this caused problems on
Windows and (b) you hadn't had any such problems on Linux.
Re (a): what evidence do you have?
I've had the case myself on my girlfriend's XP box. It was certainly 
less than 500 files of the same length.

Re (b): famous last words! How long would it take you to do a test and
announce the margin of safety that you have?
Sorry, I do not understand what you mean by this.
-pu
--
http://mail.python.org/mailman/listinfo/python-list


Re: dinamically altering a function

2005-03-12 Thread Steven Bethard
vegetax wrote:
I i need a decorator that adds a local variable in the function it
decorates, probably related with nested scopes, for example:
def dec(func):
def wrapper(obj = None):
if not obj : obj = Obj()
  bind obj to func
 return func()
return wrapper()
@dec()
def fun(b):
obj.desc = 'marked'
obj.b = b
return obj
so the call to fun : fun(obj = myobj,'b argument')
or fun('b argument')
So the function fun assumes it has an obj instance and other instance
objects computed by the decorator, this decorator will be like a generic
factory for this kind of functions,which depends on the decorator to work.
For a byte-code hack that does something similar, see the recent thread:
http://mail.python.org/pipermail/python-list/2005-March/270324.html
It can do something like:
py class Object(object):
... pass
...
py @presets.presets(obj=Object())
... def fun(b):
... obj.desc = marked
... obj.b = b
... return obj
...
py fun(1)
__main__.Object object at 0x01162BD0
py fun(1).b
1
But note that you then only have a single instance for all calls to the 
function:

py fun(1) is fun(2)
True
Have you considered using OO here?  You might find that this is more 
easily written as:

py class Object(object):
... pass
...
py class fun(object):
... def __new__(self, *args):
... if len(args) == 2:
... obj, b = args
... elif len(args) == 1:
... obj, [b] = Object(), args
... else:
... raise TypeError
... obj.desc = marked
... obj.b = b
... return obj
...
py myobj = Object()
py fun(myobj, 2)
__main__.Object object at 0x01162E30
py myobj.b
2
py obj = fun(1)
py obj.b
1
This doesn't use any bytecode hacks, but I'm still not certain it's 
really the way to go.  What is it you're trying to write this way?

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


Re: is there a problem on this simple code

2005-03-12 Thread jrlen balane
@sir harlin
so you are saying that there is nothing wrong in this simple program.


On 12 Mar 2005 07:39:31 -0800, Harlin Seritt [EMAIL PROTECTED] wrote:
 hah, this code is anything but simple...
 
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: blocking a program until a non-Python process terminates

2005-03-12 Thread Michael Hoffman
Earl Eiland wrote:
I'm running an .exe in Python, using subProcess.Popen.  The executable
writes data to a file I process later on in the program.  Unfortunately,
my program returns the error no such file  How do I block
execution until the external executable terminates?
Either:
1)
returncode = subprocess.call(cmdline)
2) or:
pipe = subprocess.Popen(cmdline)
returncode = pipe.wait()
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: dinamically altering a function

2005-03-12 Thread vegetax
Steven Bethard wrote:

 vegetax wrote:
 I i need a decorator that adds a local variable in the function it
 decorates, probably related with nested scopes, for example:
 
 def dec(func):
 def wrapper(obj = None):
 if not obj : obj = Obj()
   bind obj to func
  return func()
 
 return wrapper()
 
 @dec()
 def fun(b):
 obj.desc = 'marked'
 obj.b = b
 return obj
 
 so the call to fun : fun(obj = myobj,'b argument')
 or fun('b argument')
 
 So the function fun assumes it has an obj instance and other instance
 objects computed by the decorator, this decorator will be like a generic
 factory for this kind of functions,which depends on the decorator to
 work.
 
 For a byte-code hack that does something similar, see the recent thread:
 
 http://mail.python.org/pipermail/python-list/2005-March/270324.html
 
 It can do something like:
 
 py class Object(object):
 ... pass
 ...
 py @presets.presets(obj=Object())
 ... def fun(b):
 ... obj.desc = marked
 ... obj.b = b
 ... return obj
 ...
 py fun(1)
 __main__.Object object at 0x01162BD0
 py fun(1).b
 1
 
 But note that you then only have a single instance for all calls to the
 function:
 
 py fun(1) is fun(2)
 True

Interesting hack, but the functions must not share the same object.Maybe i
could make my version of that decorator,i will check it.

 Have you considered using OO here?  You might find that this is more
 easily written as:
 
 py class Object(object):
 ... pass
 ...
 py class fun(object):
 ... def __new__(self, *args):
 ... if len(args) == 2:
 ... obj, b = args
 ... elif len(args) == 1:
 ... obj, [b] = Object(), args
 ... else:
 ... raise TypeError
 ... obj.desc = marked
 ... obj.b = b
 ... return obj
 ...
 py myobj = Object()
 py fun(myobj, 2)
 __main__.Object object at 0x01162E30
 py myobj.b
 2
 py obj = fun(1)
 py obj.b
 1
 
 This doesn't use any bytecode hacks, but I'm still not certain it's
 really the way to go.  What is it you're trying to write this way?

OO doesnt work here,i have factored to classes with inheritance but it looks
clumsy and it is clumsy to use, this things are in nature,functions.

What i want is to declare in the decorator some code that is common to all
these functions, so the functions assume that the decorator will be there
and wont need to duplicate the code provided by it, and the functions are
not known ahead of time, it has to be dynamic.




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


Re: error sending path to Win OS

2005-03-12 Thread Michael Hoffman
Earl Eiland wrote:
os.path.getsize(Inputdirectory + '\\' + Filename) works, but
os.path.getsize(Inputdirectory + '\\' + Filename.split('.') + '.ext')
Fails reporting no such file or directory
InputDirectory\\Filename.ext.
No, that should be a TypeError. This will be easier if you copy and
paste your Python session instead of making stuff up.
os.path.getsize(Inputdirectory + r'\' + Filename.split('.') + '.ext')
generates a syntax error.
'r\ is not a valid string literal (even a raw string cannot end in an
odd number of backslashes). Specifically, a raw string cannot end in a
single backslash (since the backslash would escape the following quote
character). Note also that a single backslash followed by a newline is
interpreted as those two characters as part of the string, not as a
line continuation.'
http://docs.python.org/ref/strings.html
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: error sending path to Win OS

2005-03-12 Thread [EMAIL PROTECTED]
To generate path names take a look at os.path.join(see
http://docs.python.org/lib/module-os.path.html)

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


Re: Why does this not work?

2005-03-12 Thread Michael Hoffman
Gensek wrote:
PingGUI is a program that nobody but me knows anything about. If I
wanted help from people who are experts on it, I'd get nothing at all.
It appears as if that's the situation anyway, at least so far. But you
want wxPython help so you should ask for that instead. Something like
Why doesn't this function re-sort my wxPython grid?
Also, very few people are going to go to the trouble of downloading your
zip. I know I'm not. You need to post the smallest possible snippet of
code that you are having trouble with.
I would respectfully suggest you read this excellent document. The
suggestions will help you get help:
http://www.catb.org/~esr/faqs/smart-questions.html
Then come back and post something with a sensible subject and you will
probably get some more direct help.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: csv module and unicode, when or workaround?

2005-03-12 Thread John Machin

Chris wrote:
 hi,
 thanks for all replies, I try if I can at least get the work done.

 I guess my problem mainly was the rather mindflexing (at least for
me)
 coding/decoding of strings...

 But I guess it would be really helpful to put the
UnicodeReader/Writer
 in the docs

UNFORTUNATELY the solution of saving the Excel .XLS to a .CSV doesn't
work if you have Unicode characters that are not in your Windows
code-page. Nor would it work in a CJK environment if the file was saved
in an MBCS encoding (e.g. Big5). A work-around appears possible, with
some more effort:

I have extended the previous sample XLS; there is now a last line with
IVANOV in Cyrillic letters [pardon my spelling etc etc if necessary].
My code-page is cp1252, which sure don't grok Russki :-)

I've saved it as CSV [no complaint from Excel] and as Unicode text.

 buffc = file('csvtest2.csv', 'rb').read()
 buffc
'Name,Amount\r\nM\xfcller,\x801234,56\r\nM\xf6ller,\x809876,54\r\nKawasaki,\xa53456.78\r\n??,?5678,90\r\n'

Thanks a lot, Bill! That's really clever.

 buffu16 = file('csvtest2.txt', 'rb').read()
 buffu16
'\xff\xfeN\x00a\x00m\x00e\x00\t\x00A\x00m\x00o\x00u\x00n\x00t\x00\r\x00\n\x00
[snip] \x18\x04\x12\x04
\x10\x04\x1d\x04\x1e\x04\x12\x04\t\x00\x00
\x045\x006\x007\x008\x00,\x009\x000\x00\x00\r\x00\n\x00'
 buffu = buffu16.decode('utf16')
 buffu
u'Name\tAmount\r\nM\xfcller\t\u20ac1234,56\r\nM\xf6ller\t\u20ac9876,54\r\nKawasaki\t\xa53456.78\r\n\u0418\u0412\u0410\u041d\u041
e\u0412\t\u04205678,90\r\n'

Aside: this has removed the BOM. I understood (possibly incorrectly)
from a recent thread that Python codecs left the BOM in there, but hey
I'm not complaining :-)

As expected, this looks OK. The extra step required in the work-around
is to convert the utf16 file to utf8 and feed that to the csv reader.
Why utf8? (1) Every Unicode character can be represented, not just ones
in that are in your code-page (2) ASCII characters can't appear as part
of the representation of any other character -- i.e. ones that are
significant to csv (tab, comma, quote, \r, \n) can't cause errors by
showing up as part of another character e.g. CJK characters.

 buffu8 = buffu.encode('utf8')
 buffu8
'Name\tAmount\r\nM\xc3\xbcller\t\xe2\x82\xac1234,56\r\nM\xc3\xb6ller\t\xe2\x82\xac9876,54\r\nKawasaki\t\xc2\xa53456.78\r\n\xd0\x
98\xd0\x92\xd0\x90\xd0\x9d\xd0\x9e\xd0\x92\t\xd0\xa05678,90\r\n'
 x = file('csvtest2.u8', 'wb')
 x.write(buffu8)
 x.close()
 import csv
 rdr = csv.reader(file('csvtest2.u8', 'rb'), delimiter='\t')
 for row in rdr:
... print row
... print [x.decode('utf8') for x in row]
...
['Name', 'Amount']
[u'Name', u'Amount']
['M\xc3\xbcller', '\xe2\x82\xac1234,56']
[u'M\xfcller', u'\u20ac1234,56']
['M\xc3\xb6ller', '\xe2\x82\xac9876,54']
[u'M\xf6ller', u'\u20ac9876,54']
['Kawasaki', '\xc2\xa53456.78']
[u'Kawasaki', u'\xa53456.78']
['\xd0\x98\xd0\x92\xd0\x90\xd0\x9d\xd0\x9e\xd0\x92', '\xd0\xa05678,90']
[u'\u0418\u0412\u0410\u041d\u041e\u0412', u'\u04205678,90']


Howzat?

Cheers,
John

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


Re: dinamically altering a function

2005-03-12 Thread Steven Bethard
vegetax wrote:
Steven Bethard wrote:
Have you considered using OO here?  You might find that this is more
easily written as:
py class Object(object):
... pass
...
py class fun(object):
... def __new__(self, *args):
... if len(args) == 2:
... obj, b = args
... elif len(args) == 1:
... obj, [b] = Object(), args
... else:
... raise TypeError
... obj.desc = marked
... obj.b = b
... return obj
...
py myobj = Object()
py fun(myobj, 2)
__main__.Object object at 0x01162E30
py myobj.b
2
py obj = fun(1)
py obj.b
1
This doesn't use any bytecode hacks, but I'm still not certain it's
really the way to go.  What is it you're trying to write this way?
OO doesnt work here,i have factored to classes with inheritance but it looks
clumsy and it is clumsy to use, this things are in nature,functions.
What i want is to declare in the decorator some code that is common to all
these functions, so the functions assume that the decorator will be there
and wont need to duplicate the code provided by it, and the functions are
not known ahead of time, it has to be dynamic.
If you need to use it as a decorator, you could try something like:
py class Object(object):
... pass
...
py class ObjectSupplier(object):
... def __init__(self, func):
... self.func = func
... def __call__(self, *args):
... if len(args) == 2:
... obj, b = args
... elif len(args) == 1:
... obj, [b] = Object(), args
... else:
... raise TypeError
... return self.func(obj, b)
...
py @ObjectSupplier
... def fun(obj, b):
... obj.desc = marked
... obj.b = b
... return obj
...
py fun(1)
__main__.Object object at 0x01162910
py fun(1).b
1
py myobject = Object()
py fun(myobject, 2)
__main__.Object object at 0x01162770
py myobject.b
2
Basically, ObjectSupplier just guarantees that the function will be 
called with an initialized Object argument if one isn't supplied.  Note 
that your functions must be declared with the initial argument now though.

STeVe
P.S. Making ObjectSupplier general enough to work with any number of 
arguments is left as an exercise to the reader. ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: i18n: looking for expertise

2005-03-12 Thread klappnase
Martin v. Löwis [EMAIL PROTECTED] wrote in message news:[EMAIL 
PROTECTED]...
 klappnase wrote:
  enc = locale.nl_langinfo(locale.CODESET).lower()
 
 Notice that this may fail on systems which don't provide the
 CODESET information. Recent Linux systems (glibc 6) have it,
 and so do recent Solaris systems, but if you happen to use
 an HPUX9 or some such, you find that locale.CODESET raises
 an AttributeError.
 
 Regards,
 Martin

Thanks again,

Things are really tricky and my hair begins to turn gray ;-)
So it seems like I'll have to add another try/except condition (and
now it finally looks pretty much like I had directly copied your code
from IDLE).

Best regards

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


Re: dinamically altering a function

2005-03-12 Thread Jeremy Bowers
 What i want is to declare in the decorator some code that is common to all
 these functions, so the functions assume that the decorator will be there
 and wont need to duplicate the code provided by it, and the functions are
 not known ahead of time, it has to be dynamic.

This sounds like a call for a Pythonic varient on the Template pattern:

class Root(object):
def __init__(self):
self.dataChunk = 22 # or whatever

class Child(Root):
def __call__(self):
print self.dataChunk

 c = Child()
 c()
22


Don't be put off by the OO-ness here, it acts just like a function
thanks to __call__, and behind the scenes you get full OO support for your
functions.

I strongly suspect this is the best solution to your problem, not a
decorator. Note whatever you are doing to create the functions can be done
in other ways, especially note that class statements are executed, not
declarations, for instance:

 import operator
 class Root(object):
... def __init__(self):
... self.op1 = 22   
... self.op2 = 44
... 
 funcs = []
 for op in operator.add, operator.sub, operator.pow:
... def newfunc(self, basefunc = op):
... print basefunc(self.op1, self.op2)
... class New(Root):
... __call__ = newfunc
... funcs.append(New)
... 
 funcs # show the classes
[class '__main__.New', class '__main__.New', class '__main__.New']
 [x() for x in funcs]  # show the new functions
[__main__.New object at 0xb7e78bcc, __main__.New object at 0xb7e78e4c, __ma
in__.New object at 0xb7e78ecc]
 [x()() for x in funcs]  # call each of the functions, note no return
66
-22
116572995441436549620289361494791139391860487905922101805056
[None, None, None]

Upshot is, with a bit of creativity this can do whatever you want, in
conjection with dynamically-created classes, no bytecode hacks, no really
weird decorators, just standard OO and __call__.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PythonWin

2005-03-12 Thread Colin J. Williams
[EMAIL PROTECTED] wrote:
I have a Python program that collects user input using
msg = Enter the full path and name of the file to be processed: 
answer = raw_input(msg)
If I run it in IDLE, the question is splashed across the execution
window, and if it is long, simply wraps to the next line. Most
importantly, it is intelligible, because I see the entire message. I
enter my answer on the next line, and once again, I can see the entire
path and file name, even if it is longer than long.
However, if I run it in ActivePython's PythonWin, a small message box
pops up, with hardly any space to diplay msg and a smallish space into
which I can type my answer. How can I force PythonWin to get its input
from the execution window or to enlarge its message box sufficiently to
display the entire question?
Thomas Philips
You might try out the PythonWin from:
   http://sourceforge.net/project/showfiles.php?group_id=78018
Build 203 is the current version, build 204 is expected.
Colin W.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Confused with classmethods

2005-03-12 Thread Bengt Richter
On Fri, 11 Mar 2005 14:04:26 -0800, jfj [EMAIL PROTECTED] wrote:

Hi.

Suppose this:



def foo (x):
 print x

f = classmethod (foo)

class A: pass

a=A()
a.f = f

a.f()
# TypeError: 'classmethod' object is not callable!

###

I understand that this is a very peculiar use of
classmethods but is this error intentional?
Or did I completely missed the point somewhere?

Yes and yes ;-)

classmethod creates an an object that wraps the function you pass it.
The classmethod object has a __get__ method that gets control instead of the 
__get__
method of a function, when the object is found by way of attribute name
search looking in a new style class or base class. However, you created a 
'classic'
class (A) instance a=A(), and the rules for looking up attributes on
classic class instances are different from the rules for newstyle class 
instances,
(though the difference does not come into play for your particular example ;-)

  def foo(x): print x
 ...
  f = classmethod(foo)
  class A: pass
 ...
  a=A()
  a
 __main__.A instance at 0x02EF142C
  a.f = f
  a.f
 classmethod object at 0x02E81374

getattr(type(a), 'f') is checked first, but nothing is found. In that case,
a.f is simply retrieved with no special effects.

If you want to force the 'special effect' you could do it like:

  a.f.__get__(None, A)
 bound method classobj.foo of class __main__.A at 0x02EE792C

Now the result of that _is_ callable:

  a.f.__get__(None, A)()
 __main__.A

The normal way is to make the method callable accessible as an attribute of the 
class:

  A.f = f
  a.f
 classmethod object at 0x02E81374
The object is still retrieved from the instance (and would be for newstyle 
instance as well,
though you can create a descriptor other than classmethod than can prevent 
this).

  a.f()
 Traceback (most recent call last):
   File stdin, line 1, in ?
 TypeError: 'classmethod' object is not callable

It's not callable, because to become a callable, its __get__ method has to be 
called,
which will return the actual callable -- which will not be the function itself, 
but
a callable that holds a reference to both the function and the thing it's 
bound to
to form a bound method of one kind or another.

If we delete the instance attribute, the search for 'f' will go to the 
instance's class:

  del a.f
  a.f
 bound method classobj.foo of class __main__.A at 0x02EE792C

and the automated magic happens, and what is returned _is_ callable:
  a.f()
 __main__.A

If you want to delve into it, read
http://www.python.org/2.2.2/descrintro.html
and associated info.

If you wanted to make plain foo a bound method of A, you could do it manually:

  foo.__get__(a, A)
 bound method A.foo of __main__.A instance at 0x02EF142C

which you can call, and it will print the first argument (named x instead of 
self in this case):
 foo.__get__(a, A)()
__main__.A instance at 0x02EF142C

If you pass None instead of the instance, you get an unbound method:
 foo.__get__(None, A)
unbound method A.foo

Which you can call with an instance:
  foo.__get__(None, A)(a)
 __main__.A instance at 0x02EF142C
or a different instance
  foo.__get__(None, A)(A())
 __main__.A instance at 0x02EF18CC

If you don't pass the type, some things won't work fully, but the usual will
  foo.__get__(a)
 bound method ?.foo of __main__.A instance at 0x02EF142C

As can be seen, the original function is in there in the bound method:

  foo.__get__(a, A).im_func
 function foo at 0x02EE8B54

And you can call it as such if you like:
  foo.__get__(a, A).im_func('hi, via plain function')
 hi, via plain function

Descriptors are a big deal in the new python. They are at the root
of much of the magic.

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


Re: a program to delete duplicate files

2005-03-12 Thread John Machin

Patrick Useldinger wrote:
 John Machin wrote:

  Maybe I was wrong: lawyers are noted for irritating precision. You
  meant to say in your own defence: If there are *any* number (n =
2)
  of identical hashes, you'd still need to *RE*-read and *compare*


 Right, that is what I meant.

  2. As others have explained, with a decent hash function, the
  probability of a false positive is vanishingly small. Further,
nobody
  in their right mind [1] would contemplate automatically deleting
n-1
  out of a bunch of n reportedly duplicate files without further
  investigation. Duplicate files are usually (in the same directory
with
  different names or in different-but-related directories with the
same
  names) and/or (have a plausible explanation for how they were
  duplicated) -- the one-in-zillion-chance false-positive should
stand
  out as implausible.

 Still, if you can get it 100% right automatically, why would you
bother
 checking manually?

A human in their right mind is required to decide what to do with the
duplicates. The proponents of hashing -- of which I'm not one -- would
point out that any false-positives would be picked up as part of the
human scrutiny.

 Why get back to argments like impossible,
 implausible, can't be if you can have a simple and correct answer
-
 yes or no?

Oh yeah, the computer said so, it must be correct. Even with your
algorithm, I would be investigating cases where files were duplicates
but there was nothing in the names or paths that suggested how that
might have come about.


 Anyway, fdups does not do anything else than report duplicates.
 Deleting, hardlinking or anything else might be an option depending
on
 the context in which you use fdups, but then we'd have to discuss the

 context. I never assumed any context, in order to keep it as
universal
 as possible.

That's very good, but it wasn't under contention.


  Different subject: maximum number of files that can be open at
once. I
  raised this issue with you because I had painful memories of having
to
  work around max=20 years ago on MS-DOS and was aware that this
magic
  number was copied blindly from early Unix. I did tell you that
  empirically I could get 509 successful opens on Win 2000 [add 3 for
  stdin/out/err to get a plausible number] -- this seems high enough
to
  me compared to the likely number of files with the same size -- but
you
  might like to consider a fall-back detection method instead of just
  quitting immediately if you ran out of handles.

 For the time being, the additional files will be ignored, and a
warning
 is issued. fdups does not quit, why are you saying this?

I beg your pardon, I was wrong. Bad memory. It's the case of running
out of the minuscule buffer pool that you allocate by default where it
panics and pulls the sys.exit(1) rip-cord.


 A fallback solution would be to open the file before every _block_
read,
 and close it afterwards.

Ugh. Better use more memory, so less blocks!!

 In my mind, it would be a command-line option,
 because it's difficult to determine the number of available file
handles
 in a multitasking environment.

The pythonic way is to press ahead optimistically and recover if you
get bad news.


 Not difficult to implement, but I first wanted to refactor the code
so
 that it's a proper class that can be used in other Python programs,
as
 you also asked.

I didn't ask; I suggested. I would never suggest a
class-for-classes-sake. You had already a singleton class; why
another. What I did suggest was that you provide a callable interface
that returned clusters of duplicates [so that people could do their own
thing instead of having to parse your file output which contains a
mixture of warning  info messages and data].

 That is what I have sent you tonight. It's not that I
 don't care about the file handle problem, it's just that I do changes
by
 (my own) priority.

  You wrote at some stage in this thread that (a) this caused
problems on
  Windows and (b) you hadn't had any such problems on Linux.
 
  Re (a): what evidence do you have?

 I've had the case myself on my girlfriend's XP box. It was certainly
 less than 500 files of the same length.

Interesting. Less on XP than on 2000? Maybe there's a machine-wide
limit, not a per-process limit, like the old DOS max=20. What else was
running at the time?


  Re (b): famous last words! How long would it take you to do a test
and
  announce the margin of safety that you have?

 Sorry, I do not understand what you mean by this.

Test:
!for k in range(1000):
!open('foo' + str(k), 'w')
Announce:
I can open A files at once on box B running os C. The most files of
the same length that I have seen is D. The ratio A/D is small enough
not to worry.

Cheers,
John

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


  1   2   >