Re: Conversion of perl based regex to python method

2006-05-24 Thread Peter Otten
Andrew Robert wrote:

Wanted:

> perl -ple 's/([^\w\s])/sprintf("%%%2X", ord $1)/ge'  somefile.txt

Got:

> # Evaluate captured character as hex
> def ret_hex(ch):
> return chr((ord(ch) + 1) % )

Make it compile at least before posting :-)
 
> # Evaluate the value of whatever was matched
> def eval_match(match):
> return ret_hex(match.group(0))
> 
> # open file
> file = open(r'm:\mq\mq\scripts\testme.txt','r')
> 
> # Read each line, pass any matches on line to function
> for line in file.readlines():
> re.sub('[^\w\s]',eval_match, line)

for line in file:
...

without readlines() is better because it doesn't read the whole file into
memory first. If you want to read data from files passed as commandline
args or from stdin you can use fileinput.input():

import re
import sys
import fileinput

def replace(match):
return "%%%2X" % ord(match.group(0))

for line in fileinput.input():
sys.stdout.write(re.sub("[^\w\s]", replace, line))

Peter

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


Re: John Bokma harassment

2006-05-24 Thread James
> We seem to have strayed a long way from Voltaire's
> "I do not agree with what you say, but I will defend to the death your
> right to say it."

Not at all. My problem with Xah Lee is that he is abusing the Usenet as
a personal BLOG. He has a web site to post these articles and he can
certainly put up a discussion board there if he wants a vigorous
discussion of his ideas. It's worse. He does not even respond to
questions directly posed to him in the thread of his "articles". Just
imagine if every blogger on the Internet started using Usenet instead
and cross-posting at that.

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


Re: deploying big python applications

2006-05-24 Thread Serge Orlov
AndyL wrote:
> Hi,
>
> let me describe how I do that today. There is standard python taken from
>   python.org installed in a c:\python23 with at least dozen different
> additional python packages (e.g. SOAPpy, Twisted, wx, many smaller ones
> etc) included. Also python23.dll moved from c:\windows to c:\python23.
> This is zipped and available as over 100MB file to anyone to manually
> unzip on his/her PC. This is a one time step.
>
> On top of that there is 30K lines of code with over 100 .py files
> application laid out within a directory tree. Very specific for the
> domain, typical application. This again is zipped and available to
> anyone as much smaller file to unzip and use. This step is per software
> releases.
>
> There is one obvious drawback - I can not separate python from standard
> libraries easily.

True, python releases on windows are forward incompatible with C
extensions, so don't even think about that. I'm not even talking about
big pure python packages that could probably break because of small
subtle changes in python API between releases.

> So when upgrade to 2.4 comes, I need to reinstall all
> the packages.

Yes, but how much time it will *actually* take? I bet it's 1 hour.
Seriously, why don't you *time* it with a stopwatch? And then compare
that time to the time needed to debug the new release.

> In order to address that as well as the Linux port I
> project following structure:
>   -default python.org installation or one time step on Windows
>   -set of platform dependent libraries in directory A
>   -set of platform independent libraries in directory B
>   -application in directory C

I would suggest the same structure I described for deploying over LAN:
http://groups.google.com/group/comp.lang.python/msg/2482a93eb7115cb6?hl=en&;

The only problem is that exemaker cannot find python relative to
itself, you will have to mash exemaker, python and application launcher
in one directory. So the layout is like this:

app/
engine/  -- directory with your actual application
app.exe  -- renamed exemaker.exe
app.py  -- dispatching module, see below
python.exe
python24.dll
lib -- python stdlib, etc

=== app.py ===
from engine import real_application


This way file engine/real_application.py is platform independant.

On Linux/Unix shell script is an equivalent of exemaker. Or C program
like exemaker, but you will have to compile it for all platforms.

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


Re: IronPython 1.0 Beta 7 Released

2006-05-24 Thread Ravi Teja
Also, IronPython cannot access CPython libraries. So it cannot be used
as a drop-in replacement for CPython in most non-trivial apps. Python
for .NET however allows you to both use both CPython and .NET
libraries.

> Ironpython is not a first class .NET language.
> That means that although you can write programs that run on .NET and
> you have access to all its libraries, you can't write libraries that
> could be consumed by other languages.

I was hoping that it would eventually, like Jython by method signatures
in docstrings. But if it does not, I wonder what significant benefit
does it provide at all compared to Python for .NET (once the .NET 2.0
version is out, atleast).

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


Re: Modify one character in a string

2006-05-24 Thread Paul Rubin
"mp" <[EMAIL PROTECTED]> writes:
> How do I go about modifying one character in a string elegantly?
> In other words, I want a function that will change '' to 'aaza',
> given the index 2 of the character in the string.

Ehh, there are various ways, all ugly.
   x = ''
   y = x[:2] + 'z' + x[3:]
is the most direct.

> Also, how do I do this when dealing with a file ; which file mode
> should I use and what function should I use to modify a single
> character once in that file mode?

You mean you want to change a character in a file?

   f = open(file, 'r+')   # open for reading and writing
   f.seek(2)  # position at character index 2
   f.write('z')   # put a 'z' there
   f.seek(0)  # rewind
   print f.read() # get entire contents and see the change

You could also look at the mmap module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to change sys.path?

2006-05-24 Thread [EMAIL PROTECTED]
sys.path.append("")

eg. sys.path.append("/home/webdoc")

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


Re: how to change sys.path?

2006-05-24 Thread [EMAIL PROTECTED]
sys.append()

Bye.

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


Modify one character in a string

2006-05-24 Thread mp
X-No-Archive
How do I go about modifying one character in a string elegantly?
In other words, I want a function that will change '' to 'aaza',
given the index 2 of the character in the string.

Also, how do I do this when dealing with a file ; which file mode
should I use and what function should I use to modify a single
character once in that file mode?

Thanks
MP

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


Re: python __import__ question

2006-05-24 Thread Ben Finney
Evgeniy Zamriy <[EMAIL PROTECTED]> writes:

> I have this code:
>   try:
>   empty_mod = __import__(some_empty_module)
>   except ImportError:
>   print "test"
>   raise
> 
> But python doesn't work with this except:
> ImportError: No module named 

Your example is incomplete.

>>> try:
... empty_mod = __import__(some_empty_module)
... except ImportError:
... print "test"
... raise
...
Traceback (most recent call last):
  File "", line 2, in ?
NameError: name 'some_empty_module' is not defined

Can you post a minimal, complete example that shows the behaviour?

-- 
 \ "As we enjoy great advantages from the inventions of others, we |
  `\ should be glad to serve others by any invention of ours."  -- |
_o__)Benjamin Franklin |
Ben Finney

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


Re: IronPython 1.0 Beta 7 Released

2006-05-24 Thread Luis M. González
Well, basically, ironpython is to .NET what jython is to JAVA.
It is a faithful implementation of the python language, written in c#,
created to run on and take full advantage of the .NET framework.

That means that you have access to all the available libraries of the
.NET framework and you can use your favorite language. It is 100%
compliant with cpython.

If you want to take advantage of ironpython, all you have to do is
learn more about the .NET framework and its libraries. You don't need
to learn anything new regarding language features. It's just plain and
regular python.

You have to bear in mind something very important though:
Ironpython is not a first class .NET language.
That means that although you can write programs that run on .NET and
you have access to all its libraries, you can't write libraries that
could be consumed by other languages.
This is because ironpython is still a dynamic language, while all the
other .NET  languages are static. So it cannot be compiled like c# or
VB, for example.
It is not a problem if all you want is to create end user programs, but
if you want to write reusable libraries, you're better off using any
other statically typed language.
In this case, a good alternative is Boo, which is very similar to
python (syntax wise), but statically typed.

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


RE: determining available space for Float32, for instance

2006-05-24 Thread David Socha
Robert Kern wrote: 
> David Socha wrote:
> > I am looking for a way to determine the maxium array size I can 
> > allocate for arrays of Float32 values (or Int32, or Int8, 
> ...) at an 
> > arbitrary point in the program's execution.  This is needed because 
> > Python cannot allocate enough memory for all of the data we need to 
> > process, so we need to "chunk" the processing, as described below.
> > 
> > Python's memory management process makes this more 
> complicated, since 
> > once memory is allocated for Float32, it cannot be used for 
> any other 
> > data type, such as Int32.
> 
> Just for clarification, you're talking about Numeric arrays 
> here (judging from the names, you still haven't upgraded to 
> numpy), not general Python. Python itself has no notion of 
> Float32 or Int32 or allocating chunks of memory for those two 
> datatypes.

Yes, I am talking about numarray arrays, not general Python.
 
> > I'd like a solution that includes either memory that is not yet 
> > allocated, or memory that used to be allocated for that 
> type, but is 
> > no longer used.
> > 
> > We do not want a solution that requires recompiling Python, 
> since we 
> > cannot expect our end users to do that.
> 
> OTOH, *you* could recompile Python and distribute your Python 
> with your application. We do that at Enthought although for 
> different reasons. However, I don't think it will come to that.

We could, but that seems like it simply creates a secondar problems,
since then the user would have to choose between installing our version
of Python or Enthought's version, for instance. 

> > Does anyone know how to do this?
> 
> With numpy, it's easy enough to change the datatype of an 
> array on-the-fly as long as the sizes match up.
> 
> In [8]: from numpy import *
> 
> In [9]: a = ones(10, dtype=float32)
> 
> In [10]: a
> Out[10]: array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  
> 1.], dtype=float32)
> 
> In [11]: a.dtype = int32
> 
> In [12]: a
> Out[12]:
> array([1065353216, 1065353216, 1065353216, 1065353216, 1065353216,
>1065353216, 1065353216, 1065353216, 1065353216, 
> 1065353216], dtype=int32)
> 
> However, keeping track of the sizes of your arrays and the 
> size of your datatypes may be a bit much to ask.

Exactly.  Building a duplicate mechanism for tracking this informaiton
would be a sad solution.  Surely Python has access to the amount of
memory being used by the different data types.  How can I get to that
information?
 
> [snip]
> numpy (definitely not Numeric) does have a feature called 
> record arrays which will allow you to deal with your agents 
> much more conveniently:
> 
>   http://www.scipy.org/RecordArrays
> 
> Also, you will certainly want to look at using PyTables to 
> store and access your data. With PyTables you can leave all 
> of your data on disk and access arbitrary parts of it in a 
> relatively clean fashion without doing the fiddly work of 
> swapping chunks of memory from disk and back again:
> 
>   http://www.pytables.org/moin

Do RecordArrays and PyTables work well together?  

Thanks for the info.  The PyTables looks quite promising for our
application (I had been looking for an HDF5 interface, but couldn't
recall the 'HDF5' name).

David Socha
Center for Urban Simulation and Policy Analysis
University of Washington
206 616-4495


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


Re: John Bokma harassment

2006-05-24 Thread David Steuber
I'm loath to crosspost this but I don't know which (if any) news group
Xah actually reads.  I also don't want to make just a private response
to Xah's email to a public post.  Anyway, the TOS of dreamhost.com is
here:

  http://www.dreamhost.com/tos.html

Two important sections I'll quote:



INTERNET ETIQUETTE

Electronic forums such as mail distribution lists and Usenet news
groups all have expectations regarding subject area and appropriate
etiquette for posting. Users of these forums should be considerate of
the expectations and sensitivities of others on the network when
posting material for electronic distribution. The network resources of
DreamHost Webhosting may not be used to impersonate another person or
misrepresent authorization to act on behalf of others or DreamHost
Webhosting. All messages transmitted via DreamHost Webhosting should
correctly identify the sender; users may not alter the attribution of
origin in electronic mail messages or posting.
Users must not attempt to undermine the security or integrity of
computing systems or networks and must not attempt to gain
unauthorized access. This includes (but is not limited to) such things
as port scanning of either DreamHost or external computers and Denial
Of Service attacks of any kind.

TERMINATION

This contract may be terminated by either party, without cause, by
giving the other party 30 days written notice. DreamHost Webhosting
will accept termination by electronic mail. Notwithstanding the above,
DreamHost Webhosting may terminate service under this contract at any
time, without penalty, if the Customer fails to comply with the terms
of this contract, including non-payment. DreamHost Webhosting reserves
the right to charge a reinstatement fee.



IANAL, but it looks like you can have your account canceled, Xah.
Although to tell the truth, even though I find your crossposting
excessive and your rants uninteresting I don't think it is frequent
enough to bitch about.  I do hope that no refund policy doesn't apply
when they terminate your account.

You would probably stand a good chance of keeping your account if you
stop crossposting so much.  Dreamhosting has defined internet
etiquette for you.  Stick within those bounds and you can defend
yourself against people who complain.

Good luck

-- 
http://www.david-steuber.com/
1998 Subaru Impreza Outback Sport
2006 Honda 599 Hornet (CB600F) x 2 Crash & Slider
The lithobraker.  Zero distance stops at any speed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: John Bokma harassment

2006-05-24 Thread marc spitzer
On 2006-05-25, John Bokma <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] (Bob Felts) wrote:
>
>> Count me among the clueless, then.  I just wrote to DreamHost and asked
>> that they reverse their decision to terminate his account.
>
> I am sure that DreamHost has quite a nice /dev/null for clueless idiots 
> like you and your sock puppets :-D.
>

point of order, rudness is always off topic.  Since you want to have 
such high standards for others you might want to start applying them
to your self as well.

marc

-- 
[EMAIL PROTECTED]
SDF Public Access UNIX System - http://sdf.lonestar.org
-- 
http://mail.python.org/mailman/listinfo/python-list


os listdir access denied when run as a service

2006-05-24 Thread Thomas Thomas
Hi All,

I am trying to access a mapped network drive folder. everything works fine
normally. But when i run the application as service I am getting the error

Traceback (most recent call last):
  File "docBoxApp.py", line 129, in ?
  File "core\PollFiles.pyc", line 332, in doPoll
  File "core\PollFiles.pyc", line 47, in createFileList
  File "core\PollFiles.pyc", line 25, in addFolderFiles
WindowsError: [Errno 5] Access is denied: 'G:\\DT Hot Folder test/*.*'


below is my code


def addFolderFiles(folder,filelist=[]):
logger=ServerInterface.getErrorLogger()
folder = folder.encode('ascii') #convert path to ascii for  File Method
for filename in os.listdir(folder):#line 25
file=os.path.join(folder,filename)
logger.error("loop file :"+file);
if os.path.isfile(file):
logger.error("is file :"+file);
if ((not (file.find(".tmp")>=0)) and (not
(file.find("~")>=0))):
filelist.append(file)
elif os.path.isdir(file):
logger.error("file is a directory :"+file);
addFolderFiles(file,filelist)

def createFileList(files,folders,filelist=[]):
logger=ServerInterface.getErrorLogger()
for file in files:
file = file.encode('ascii') #convert path to ascii for  File Method
if os.path.isfile(file):
   if ((not (file.find(".tmp")>=0)) and (not (file.find("~")>=0))):
filelist.append(file)

for folder in  folders:
logger.error("got a folder :"+folder);
logger.error("it was in the list :"+folders.__str__());
addFolderFiles(folder,filelist)
return (1,filelist)

anything I can do about this..


-
Thomas Thomas

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


Re: Unexpected extension module behaviour

2006-05-24 Thread rimmer
Thanks for the help John.

Indeed, changing <= to < has it licked.

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


Re: how to "normalize" indentation sources

2006-05-24 Thread AndyL
John Machin wrote:
> On 25/05/2006 12:00 PM, AndyL wrote:
> 
>> Hi,
>>
>> I have a lot of sources with mixed indentation typically 2 or 4 or 8 
>> spaces. Is there any way to automatically convert them in let's say 4 
>> spaces?
>>
> 
> Yup. Right under your nose:
> 
> C:\junk>\python24\tools\scripts\reindent.py --help
> reindent [-d][-r][-v] [ path ... ]
> 
> -d (--dryrun)  Dry run.  Analyze, but don't make any changes to, files.
> -r (--recurse) Recurse.  Search for all .py files in subdirectories too.
> -v (--verbose) Verbose.  Print informative msgs; else no output.
> -h (--help)Help. Print this usage information and exit.
> 
> Change Python (.py) files to use 4-space indents and no hard tab 
> characters.
> Also trim excess spaces and tabs from ends of lines, and remove empty lines
> at the end of files.  Also ensure the last line ends with a newline.
> [snip]
> 
> 
thx a lot, A.
-- 
http://mail.python.org/mailman/listinfo/python-list


python __import__ question

2006-05-24 Thread Evgeniy Zamriy

Hello, All:

I have this code:
  try:
  empty_mod = __import__(some_empty_module)
  except ImportError:
  print "test"
  raise

But python doesn't work with this except:
ImportError: No module named 

My python version is 2.4.2 (Linux)

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


Re: John Bokma harassment

2006-05-24 Thread Ben Bullock
"Ken Tilton" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
>
> Ben Bullock wrote:
>> "Xah Lee" <[EMAIL PROTECTED]> wrote in message 
>> news:[EMAIL PROTECTED]
>>
>>> If you believe this lobbying to my webhosting provider is unjust,
>>> please write to my web hosting provider [EMAIL PROTECTED]
>>
>>
>> Why don't you just change your provider? It would take less time than 
>> this.
>
> Are you joking. "Just change your provider?" Do you have a little button 
> on your computer that says "Change provider"? Cool! :)

No, but if you go any look at the website of Xah Lee, he seems to have spent 
enough time and energy complaining that it would be overwhelmingly greater 
than the time it would take him to apply for a new provider.

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


Re: how to "normalize" indentation sources

2006-05-24 Thread John Machin
On 25/05/2006 12:00 PM, AndyL wrote:
> Hi,
> 
> I have a lot of sources with mixed indentation typically 2 or 4 or 8 
> spaces. Is there any way to automatically convert them in let's say 4 
> spaces?
> 

Yup. Right under your nose:

C:\junk>\python24\tools\scripts\reindent.py --help
reindent [-d][-r][-v] [ path ... ]

-d (--dryrun)  Dry run.  Analyze, but don't make any changes to, files.
-r (--recurse) Recurse.  Search for all .py files in subdirectories too.
-v (--verbose) Verbose.  Print informative msgs; else no output.
-h (--help)Help. Print this usage information and exit.

Change Python (.py) files to use 4-space indents and no hard tab characters.
Also trim excess spaces and tabs from ends of lines, and remove empty lines
at the end of files.  Also ensure the last line ends with a newline.
[snip]


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


Re: Unexpected extension module behaviour

2006-05-24 Thread John Machin
On 25/05/2006 12:09 PM, rimmer wrote:
> I'm writing an extension module in C in which I'm passing an array of
> floats from C to python.  The code below illustrates a simple C
> function designed to output an array of floats.
> 
[snip]
Couldn't restrain myself from reading further :-)

> 
> Then I write a wrapper function to pass the data back and forth between
> C and Python.
> 
> 
> extTestWrapper.c
> 
> 
> #include "/usr/include/python2.4/Python.h"
> #include 
> 
> // external declarations
> extern float *testArray(int);

Um, shouldn't that be "double", not "float"?

> 
> // Python wrapper for the testArray function
> PyObject *extTest_testArray(PyObject *self, PyObject *args) {
> 
>   double *nums;
>   int nsamp;
>   int i;
>   PyObject *pynums;
> 
>   if (!PyArg_ParseTuple(args, "i", &nsamp)) {
> return NULL;
>   }
> 
>   // call the C function
>   nums = testArray(nsamp);
> 
>   // build a Python list object containing the array values
>   pynums = PyList_New(nsamp);

Test for errors!

>   for (i=0; i<=nsamp; i++){

Um, shouldn't that be "<", not "<="???
Note, you have the same problem in the C function.
"nsamp" is presumed in the absence of any docs to mean "number of 
samples". A caller passing in 5 expects to get 5 values, NOT 6.
But you are calling PyList_New with 5.

> PyList_SetItem(pynums, i, PyFloat_FromDouble(nums[i]));

Given you are trying to stuff one extra item into the list, you should 
definitely test for errors here!!!

I suggest that you change this incrementally. First, just change the 
above line to test for errors. Then run it again so you can see what 
happens. Second, fix the other problems.

>   }
>   return Py_BuildValue("O", pynums);

Rather unnecessary; you can just return pynums.

[read before snipping :-)]


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


deploying big python applications

2006-05-24 Thread AndyL
Hi,

let me describe how I do that today. There is standard python taken from 
  python.org installed in a c:\python23 with at least dozen different 
additional python packages (e.g. SOAPpy, Twisted, wx, many smaller ones 
etc) included. Also python23.dll moved from c:\windows to c:\python23. 
This is zipped and available as over 100MB file to anyone to manually 
unzip on his/her PC. This is a one time step.

On top of that there is 30K lines of code with over 100 .py files 
application laid out within a directory tree. Very specific for the 
domain, typical application. This again is zipped and available to 
anyone as much smaller file to unzip and use. This step is per software 
releases.

There is one obvious drawback - I can not separate python from standard 
libraries easily. So when upgrade to 2.4 comes, I need to reinstall all 
the packages. In order to address that as well as the Linux port I 
project following structure:
-default python.org installation or one time step on Windows
-set of platform dependent libraries in directory A
-set of platform independent libraries in directory B
-application in directory C

This way I can easily port (or just use) entire software under 
Linux/Unix yet do not have to worry about collecting all the packages 
evry time I change the platform or the version of Python.

I hope I described it well enough. How to achieve it, is there any 
better solution, or ready one. Please advice.

Thx in advance, A.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: John Bokma harassment

2006-05-24 Thread John Bokma
[EMAIL PROTECTED] (Bob Felts) wrote:

> Count me among the clueless, then.  I just wrote to DreamHost and asked
> that they reverse their decision to terminate his account.

I am sure that DreamHost has quite a nice /dev/null for clueless idiots 
like you and your sock puppets :-D.

-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


how to "normalize" indentation sources

2006-05-24 Thread AndyL
Hi,

I have a lot of sources with mixed indentation typically 2 or 4 or 8 
spaces. Is there any way to automatically convert them in let's say 4 
spaces?


Thx, A.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected extension module behaviour

2006-05-24 Thread John Machin
On 25/05/2006 12:09 PM, rimmer wrote:
> I'm writing an extension module in C in which I'm passing an array of
> floats from C to python.  The code below illustrates a simple C
> function designed to output an array of floats.
> 
> -
> extTest.c
> -
> #include 
> 
> double *testArray(int nsamp) {
> 
>   double nums[1];
>   int i;
>   double cumdata = 0.0;
> 
>   printf("%d\n", nsamp);
>   for (i=0; i<=nsamp; i++) {
> printf("%d\n", i);
> nums[i] = cumdata;
> cumdata += 0.5;
> printf("%f\n", nums[i]);
>   }
>   return nums;

Your problem is right here. The array nums is local to the function.
You are returning a pointer to memory whose contents are utterly useless 
once you return from the function. Depending on the architecture and the 
compiler, the pointer may point outside the stack, maybe causing the 
hardware to take exception when the pointer is dereferenced, or it may 
be inside the stack, in which case the next few function calls are 
liable to trash the contents.

> }
> 
> Then I write a wrapper function to pass the data back and forth between
> C and Python.

Before you do that, test it with a simple C main()!!!

[snip]

> Here is where I'm stumped.  I must be doing something wrong during the
> PyList_SetItem or the Py_BuildValue.

Yes, you may have problems there too, but I didn't bother reading that 
far :-)

> 
> Any ideas on fixing this problem ?
> 
> Regards,
> 
> Rimmer
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


wxPython: changing entries of a HtmlListBox

2006-05-24 Thread KvS
Hi all,

a question wrt renewing the entries in a wx.HtmlListBox, I don't
understand how to do it.

I have some global variable containing a list:

gl_NAWList=["Bet","Dik"]

then I create a subclass of wx.HtmlListBox as described in the wxPython
demo:

class MyHtmlListBox(wx.HtmlListBox):
def OnGetItem(self, n):
return gl_NAWList[n]

and this works well after putting an instance called "hlb" of it in a
frame etc. Now I want to change the entries in hlb and I thought I
should simply be able to call the following function (bound to a button
click, "self" refers to the frame on which both teh button and hlb are
placed):

def klik(self, event):
gl_NAWList=["Boy","Boy"]
#print "gl_NAWList = ",gl_NAWList
self.hlb.SetItemCount(len(gl_NAWList))
self.Refresh()

but that doesn't seem to be working in the sense that the entries are
still "Bet" and "Dik". Also if I change this code to completely destroy
teh existing hlb and create a new instance it's not working. As will
probably be painfully clear ;) I just started playing a bit around with
wxPython. Any hints would be very much appreciated!

Thanks, Kees

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


Re: How does a generator object refer to itself?

2006-05-24 Thread Michael
Russell wrote:
> The issue is how to write a generator that refers to its own generator
> object. 
> 
> def me():
> ..
> nextVal = yield you(me.send)# This is wrong!

>>> def self_decorate(func):
...class context:
...def __init__(self):
...self.me = None
...def start(self):
...self.me = func(self)
...return self.me
...return context().start
...
>>> @self_decorate
... def me(self):
... print "ME!",self.me
... yield 1
...
>>> me
>
>>> x=me()
>>> x

>>> x.next()
ME! 
1

You don't need python 2.5 at all to do this. You do need to have a token
mutable first argument though, as you can see. For more examples of how to
add context to generators in the interests of doing fun and interesting
things loosely coupled, please look at our MiniAxon tutorial here:
   http://kamaelia.sf.net/MiniAxon/

(We don't tend to use decorators though because we'd like our code to run on
Nokia phones as well which use a variant of python 2.2)

For examples of fun things you can do:
   http://kamaelia.sf.net/KamaeliaMacro.html
   http://kamaelia.sf.net/Cookbook.html

Basic approach we're taking is a riff on the idea of Unix Philosophy:
   Write components that do one thing and do it well.
   Write components to work together.
   Write components to handle object streams, because that is a universal
   interface.

... with apologies to Doug McIlroy.

:-)


Michael.

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


Unexpected extension module behaviour

2006-05-24 Thread rimmer
I'm writing an extension module in C in which I'm passing an array of
floats from C to python.  The code below illustrates a simple C
function designed to output an array of floats.

-
extTest.c
-
#include 

double *testArray(int nsamp) {

  double nums[1];
  int i;
  double cumdata = 0.0;

  printf("%d\n", nsamp);
  for (i=0; i<=nsamp; i++) {
printf("%d\n", i);
nums[i] = cumdata;
cumdata += 0.5;
printf("%f\n", nums[i]);
  }
  return nums;
}

Then I write a wrapper function to pass the data back and forth between
C and Python.


extTestWrapper.c


#include "/usr/include/python2.4/Python.h"
#include 

// external declarations
extern float *testArray(int);

// Python wrapper for the testArray function
PyObject *extTest_testArray(PyObject *self, PyObject *args) {

  double *nums;
  int nsamp;
  int i;
  PyObject *pynums;

  if (!PyArg_ParseTuple(args, "i", &nsamp)) {
return NULL;
  }

  // call the C function
  nums = testArray(nsamp);

  // build a Python list object containing the array values
  pynums = PyList_New(nsamp);
  for (i=0; i<=nsamp; i++){
PyList_SetItem(pynums, i, PyFloat_FromDouble(nums[i]));
  }
  return Py_BuildValue("O", pynums);
}

// method table mapping names to wrappers
static PyMethodDef extTestMethods [] = {
  {"testArray", extTest_testArray, METH_VARARGS},
  {NULL, NULL}
};

//module init function
void initextTest() {
  Py_InitModule("extTest", extTestMethods);
}

I then run the following setup.py script using python setup.py install
--install-lib=.


# setup.py for extTest

from distutils.core import setup, Extension

setup(name="extTest", version="0.0.1",
ext_modules=[Extension("extTest", ["extTest.c", "extTestWrapper.c"])])


The library builds and installs ok.  When I invoke the testArray
function, it appears to work correctly (the output is as expected).

For example,

import extTest
a = extTest.testArray(5)

yields the following output:

5
0
0.00
1
0.50
2
1.00
3
1.50
4
2.00
5
2.50
Exception exceptions.IndexError: 'list assignment index out of range'
in 'garbage collection' ignored
Fatal Python error: unexpected exception during garbage collection
Aborted

Here is where I'm stumped.  I must be doing something wrong during the
PyList_SetItem or the Py_BuildValue.

Any ideas on fixing this problem ?

Regards,

Rimmer

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


Re: Compiling Python from Sources

2006-05-24 Thread rwr
Thank YOU ever s much as it worked my friend!!!

Thank you.

Sincerely,
rwr

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


Re: IronPython 1.0 Beta 7 Released

2006-05-24 Thread sam
vbgunz:
When you download IronPython,the tutorial directory has some examples
of interfacing With the .NET environment i.e.:
1: IronPython -> C#
2: C# -> IronPython
3: IronPython -> VB
4: VB -> IronPython
Sam Schulenburg

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


Re: Compiling Python from Sources

2006-05-24 Thread [EMAIL PROTECTED]

rwr wrote:
> Due to my ignorance exactly what do you mean by "In my case, I had to
> run configure over and over againeach time going through the log
> finding a new missing file, re-install,
> and repeat until the errors stopped." My

In my case, my error log said it couldn't find the file "make".
So I re-installed Cygwin and chose the custom rather than default
install. I had to go through dozens of install options before finding
the make file (it isn't with the compilers).

The configure then got a little further and stopped, complaining that
it couldn't find "m4". So I had to re-install Cygwin again, this time
looking for make and m4.

This process was repeated until the configure ran to completion.

>
> Why I ask is that I utilized "apt-get install gcc" to install  gcc. Are
> there additional options that are found by appending "--help"?

I don't know, I don't actually use linux. It may be that what you
installed was a default set of options. If so, I have no clue how you
get it to do what you want, I'm suggesting that as a possible place
to look.

>
> Curiously,
> rwr
> 
> Ps. Thank you for your help and for your time.   :)))

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


Re: Bind an instance of a base to a subclass - can this be done?

2006-05-24 Thread Diez B. Roggisch
Maric Michaud schrieb:
> Le Mercredi 24 Mai 2006 22:04, Diez B. Roggisch a écrit :
>> Nope, not in that way. But you might consider writing a proxy/wrapper
>> for an object. That looks like this (rouch sketch from head):
>>
>> class FileWrapper(object):
>> def __init__(self, f):
>>self._f = f
>>
>> def __getattr__(self, name):
>>return getattr(self._f, name)
>>
>> def myreadline(self):
>>
> Why use a proxy when you can just inherit from the builtin file object ?

To be honest - in my perception file is a function. Which it isn't, but 
I see it that way :)

You are of course right, and have the better solution (unless the OP is 
not in control of file creation).

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


GMPY: divm() still broken (was: module conflict? gmpy and operator)

2006-05-24 Thread [EMAIL PROTECTED]
Drat, gmpy is still broken.

Prior to ver 1.01, divm(4,8,20) would produce a
'not invertible' error even though this is a valid
linear congruence (because gcd(8,20)=4 divides 4).
The issue was that the modular inverse function invert()
requires that 8 & 20 be co-prime (have gcd=1). Linear
congruence doesn't require that, only that the gcd
divides 4. But if the gcd divides 4, then all three
parameters are divisible by 4, so we can convert the
non-invertible (4,8,20) into the invertible (1,2,5).

That feature was added to the 1.01 version of divm()
in addition to fixing the memory leak.

And although it works, it has an "interesting" side
effect: completely corrupting the gmpy module.


IDLE 1.1a3
>>> from gmpy import *
>>> x = mpz('8')
>>> y = mpz('20')
>>> z = mpz('4')
>>> x,y,z
(mpz(8), mpz(20), mpz(4))
>>> divm(z,x,y)
mpz(3)

Correct answer...

>>> x,y,z
(mpz(2), mpz(5), mpz(1))

...but variables have changed (that's not supposed to
happen). 2,5,1 results from dividing x,y,z by gcd(8,20)
in order to obtain a valid modular inverse.

Invoking divm(z,x,y) again still produces the correct
answer.

>>> divm(z,x,y)
mpz(3)

But if x,y,z are actually 2,5,1, this should fail with
a 'not invertible' error. So even though it is being
called with x,y,z, the original values are still being
used somehow.

Calling divm() with literals...

>>> divm(4,8,20)
mpz(3)

...also produces the correct answer, but the literals
had to be coerced to mpzs.

Earlier, we saw that x,y,z somehow have two different
values simultaneously. With the literals coerced to mpzs,
we have corrupted gmpy so that it cannot do any further
coercion on 8:

>>> mpz(8)
mpz(2)

8 is now stuck with value 2 when coerced to mpz.

So even though divm(4,8,20) should work, it can't any
more since failure to coerce 4 & 8 means divm() is
actually trying to evaluate (1,2,20).

>>> divm(4,8,20)

Traceback (most recent call last):
  File "", line 1, in -toplevel-
divm(4,8,20)
ZeroDivisionError: not invertible


My speculation is that the three mpz_divexact functions
shown below must be doing some kind of bizarre pointer
magic that permits x,y,z to have two different values
simultaneously while also corrupting the coercion of
literals. It's legal in the gmp program to have a result
overwrite an operand, but my guess is that shouldn't
be done.

static char doc_divm[]="\
divm(a,b,m): returns x such that b*x==a modulo m, or else raises\n\
a ZeroDivisionError exception if no such value x exists\n\
(a, b and m must be mpz objects, or else get coerced to mpz)\n\
";
static PyObject *
Pygmpy_divm(PyObject *self, PyObject *args)
{
PympzObject *num, *den, *mod, *res;
int ok;

if(!PyArg_ParseTuple(args, "O&O&O&",
Pympz_convert_arg, &num,
Pympz_convert_arg, &den,
Pympz_convert_arg, &mod))
{
return last_try("divm", 3, 3, args);
}
if(!(res = Pympz_new()))
return NULL;
if(mpz_invert(res->z, den->z, mod->z)) { /* inverse exists */
  ok = 1;
} else {
  /* last-ditch attempt: do num, den AND mod have a gcd>1 ? */
  PympzObject *gcd;
  if(!(gcd = Pympz_new()))
  return NULL;
  mpz_gcd(gcd->z, num->z, den->z);
  mpz_gcd(gcd->z, gcd->z, mod->z);
  mpz_divexact(num->z, num->z, gcd->z);
  mpz_divexact(den->z, den->z, gcd->z);
  mpz_divexact(mod->z, mod->z, gcd->z);
  Py_DECREF((PyObject*)gcd);
  ok = mpz_invert(res->z, den->z, mod->z);
}

if (ok) {
mpz_mul(res->z, res->z, num->z);
mpz_mod(res->z, res->z, mod->z);
if(options.ZM_cb && mpz_sgn(res->z)==0) {
PyObject* result;
if(options.debug)
fprintf(stderr, "calling %p from %s for %p %p %p %p\n",
options.ZM_cb, "divm", res, num, den, mod);
result = PyObject_CallFunction(options.ZM_cb, "s",
"divm",
   res, num, den, mod);
if(result != Py_None) {
Py_DECREF((PyObject*)res);
return result;
}
}
Py_DECREF((PyObject*)num);
Py_DECREF((PyObject*)den);
Py_DECREF((PyObject*)mod);
return (PyObject*)res;
} else {
PyObject* result = 0;
if(options.ZD_cb) {
result = PyObject_CallFunction(options.ZD_cb,
"sOOO", "divm", num, den, mod);
} else {
PyErr_SetString(PyExc_ZeroDivisionError, "not invertible");
}
Py_DECREF((PyObject*)num);
Py_DECREF((PyObject*)den);
Py_DECREF((PyObject*)mod);
Py_DECREF((PyObject*)res);
return result;
}
}


And despite using gmpy 1.01 for six months, I've never
encountered this problem before because in the algorithm
where I use it, my operands are guaranteed to be invertible
by construction, so I have never provoked the corrupting
influence of divm().

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


Re: John Bokma harassment

2006-05-24 Thread Bob Felts
John Bokma <[EMAIL PROTECTED]> wrote:

> "Ant" <[EMAIL PROTECTED]> wrote:
> 
> > I have no particular affinity for Xah's views, but what does get up my
> > nose is usenet Nazism.
> 
> That's because you're clueless.

Count me among the clueless, then.  I just wrote to DreamHost and asked
that they reverse their decision to terminate his account.

Xah may be annoying; but he's harmless.  Certain self-elected net
nannies, however, are not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python mentioned in context of $100 laptop...

2006-05-24 Thread skip

>From Google alerts:

MIT's US$100 laptop prototype completed
Ars Technica - Boston,MA,USA
... and interactivity. Called Sugar, the OLPC interface is built with
Python, GTK, and Mozilla's Gecko HTML rendering engine. Tom Hoffman ...
<http://arstechnica.com/news.ars/post/20060524-6903.html>

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


Re: Web frameworks and credit cards

2006-05-24 Thread Victor Ng
Ed,
Its very simple to add credit card processing to your app. I have
personally used moneris , worldpay and debitech with no issues.
Sometimes you need to do a little ctypes or pyrex but overall - its
easy.

On 5/24/06, Ed Leafe <[EMAIL PROTECTED]> wrote:
>   I may have an opportunity to develop an online ordering system for a
> client, and will have the ability to develop using any tool I choose.
> Given the fact that there are more web frameworks in Python than
> keywords ;-) , what I need to know is any experience anyone out there
> has had integrating credit card processing with the various Python
> web frameworks. Until now, my only practical experience is with Zope
> 2.x, but I'm open to any and all alternatives, so long as it's Python!
>
> -- Ed Leafe
> -- http://leafe.com
> -- http://dabodev.com
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
"Never attribute to malice that which can be adequately explained by
stupidity."  - Hanlon's Razor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web frameworks and credit cards

2006-05-24 Thread Victor Ng
Ed,


On 5/24/06, Ed Leafe <[EMAIL PROTECTED]> wrote:
>   I may have an opportunity to develop an online ordering system for a
> client, and will have the ability to develop using any tool I choose.
> Given the fact that there are more web frameworks in Python than
> keywords ;-) , what I need to know is any experience anyone out there
> has had integrating credit card processing with the various Python
> web frameworks. Until now, my only practical experience is with Zope
> 2.x, but I'm open to any and all alternatives, so long as it's Python!
>
> -- Ed Leafe
> -- http://leafe.com
> -- http://dabodev.com
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
"Never attribute to malice that which can be adequately explained by
stupidity."  - Hanlon's Razor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to change sys.path?

2006-05-24 Thread Ju Hui
yes, we can add path to PYTHONPATH,but how to remove some items?
my sys.path:
>>> import sys
>>> for x in sys.path:
... print x
...

D:\usr\local\lib\site-packages\setuptools-0.6a11-py2.4.egg
D:\usr\local\lib\site-packages\clientcookie-1.3.0-py2.4.egg
c:\temp
C:\WINDOWS\system32\python24.zip
C:\Documents and Settings\phpbird
D:\usr\local\DLLs
D:\usr\local\lib
D:\usr\local\lib\plat-win
D:\usr\local\lib\lib-tk
D:\usr\local
D:\usr\local\lib\site-packages
>>>

the value of
HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.4\PythonPath
D:\usr\local\Lib;D:\usr\local\DLLs;D:\usr\local\Lib\lib-tk;

the content are difference, how to remove
C:\WINDOWS\system32\python24.zip
or
D:\usr\local\lib\site-packages\clientcookie-1.3.0-py2.4.egg
?

thanks.

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


Re: IronPython 1.0 Beta 7 Released

2006-05-24 Thread vbgunz
maybe I am a bit ignorant and love living in the bliss of it and maybe
I am a bit tired on the subject but may I ask you a question? if i
decided to use IronPython for strict cPython work, is this possible?
probably dumb when I can use cPython but is it still possible in case
maybe sometime down the road I wanted to use the .NET libaries?

In other words, IronPython is Python but with the extra capability of
working in .NET correct? Do you have some introductory information on
it? I am very interested on some news that explains what IronPython is.
What would you recommend I check out for a great intro on IronPython?

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


Re: Compiling Python from Sources

2006-05-24 Thread rwr
Due to my ignorance exactly what do you mean by "In my case, I had to
run configure over and over againeach time going through the log
finding a new missing file, re-install,
and repeat until the errors stopped." My

Why I ask is that I utilized "apt-get install gcc" to install  gcc. Are
there additional options that are found by appending "--help"?

Curiously,
rwr

Ps. Thank you for your help and for your time.   :)))

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


Re: John Bokma harassment

2006-05-24 Thread Peter Decker
On 24 May 2006 15:54:56 GMT, John Bokma <[EMAIL PROTECTED]> wrote:

> And ain't it cool that reporting Xah's abuse might stop both?

C'mon - admit it! you hafta be a Republican with a hardon for Bush! 

-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: John Bokma harassment

2006-05-24 Thread usenet
Xah Lee wrote:
> I do not like to post off-topic messages

Oh REALLY?  That's strange, because I don't recall ever seeing an
on-topic message (a Perl message in a Perl newsgroup) from Xah.  Every
one of the many Xah post I've ever seen (including the "Philosopher"
message that this thread morphed into) was off-topic for a Perl
programming newsgroup.

-- 
http://DavidFilmer.com

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


Re: John Bokma harassment

2006-05-24 Thread Peter Decker
On 24 May 2006 15:26:12 GMT, John Bokma <[EMAIL PROTECTED]> wrote:
> "Ant" <[EMAIL PROTECTED]> wrote:
>
> > I have no particular affinity for Xah's views, but what does get up my
> > nose is usenet Nazism.
>
> That's because you're clueless.

Sounds like your one of those Bush ass-lickers who think that being
different is a crime.

Intelligent people can handle weirdos. It's only uptight jerks who
want everyone to fall into line with state/corporate policy. Sunshine
is the best disinfectant.
-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why can't timedeltas be divided?

2006-05-24 Thread Robert Kern
Maric Michaud wrote:
> Le Jeudi 25 Mai 2006 00:07, Dan Bishop a écrit :
> 
>>If I try to write something like:
>>
>>num_weeks = time_diff / datetime.timedelta(days=7)
> 
> because it has no meaning,

Yes, it does.

> what you want is :
> 
> num_weeks = time_diff.days / 7
> or
> num_weeks = (time_diff / 7).days

Uh, no. Besides the integer division problem in your first line, keep in mind
that the .days attribute does not give you the time interval measured in days.
It gives you the number of *whole* days in the interval. The first method will
be incorrect if time_diff is not an even multiple of 1 day. The latter will be
incorrect if time_diff is not an even multiple of 7 days.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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

Re: Compiling Python from Sources

2006-05-24 Thread rwr
Thank you ever so much mensanator!!!

Very much appreciated!
rwr

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


Re: Python keywords vs. English grammar

2006-05-24 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Boris Borcic <[EMAIL PROTECTED]> wrote:

> Roy Smith wrote:

> > and all three keywords are verbs, so when you describe the code, you can 
> > use the same English words as in the program source, "You try to execute 
> > some code, but it throws a foo, which is caught by the handler".
> 
> Not convincing at all

I wasn't trying to convince anybody of anything.  Just making an 
observation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Web frameworks and credit cards

2006-05-24 Thread Ed Leafe
I may have an opportunity to develop an online ordering system for a  
client, and will have the ability to develop using any tool I choose.  
Given the fact that there are more web frameworks in Python than  
keywords ;-) , what I need to know is any experience anyone out there  
has had integrating credit card processing with the various Python  
web frameworks. Until now, my only practical experience is with Zope  
2.x, but I'm open to any and all alternatives, so long as it's Python!

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com



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


Re: NEWB: how to convert a string to dict (dictionary)

2006-05-24 Thread manstey
Thanks.  I didn't know eval could do that. But why do many posts say
they want a solution that doesn't use eval?

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


Re: Large Dictionaries

2006-05-24 Thread Klaas
Chris:
> class StorageBerkeleyDB(StorageTest):
>def runtest(self, number_hash):
>db = bsddb.hashopen(None, flag='c', cachesize=8192)
>for (num, wildcard_digits) in number_hash.keys():
>key = '%d:%d' % (num, wildcard_digits)
>db[key] = None
>db.close()

BDBs can accomplish what you're looking to do, but they need to be
tuned carefully.  I won't get into too many details here, but you have
a few fatal flaws in that code.

1. 8Kb of cache is _pathetic_.  Give it a few hundred megs.  This is by
far your nbiggest problem.
2. Use BTREE unless you have a good reason to use DBHASH
3. Use proper bdb env creation instead of the hash_open apis.
4. Insert your keys in sorted order.

-Mike

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


Re: pickling multiple dictionaries

2006-05-24 Thread manstey
Thanks very much. How large is *really* large for making pytables
worthwhile. Our python script generates an xml file of about 450Mb. Is
pytables worth using then?

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


Re: Large Dictionaries

2006-05-24 Thread Klaas
Chris:
> Berkeley DB is great for accessing data by key for things already
> stored on disk (i.e. read access), but write performance for each
> key-value pair is slow due to it being careful about flushing
> writes to disk by default. 

This is absolutely false.

-Mike

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


Re: John Bokma harassment

2006-05-24 Thread Larry Elmore
Bill Atkins wrote:
> John Bokma <[EMAIL PROTECTED]> writes:
> 
> 
>>Ken Tilton <[EMAIL PROTECTED]> wrote:
>>
>>
>>>Ben Bullock wrote:
>>>
"Xah Lee" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]


>If you believe this lobbying to my webhosting provider is unjust,
>please write to my web hosting provider [EMAIL PROTECTED]


Why don't you just change your provider? It would take less time than
this. 
>>>
>>>Are you joking. "Just change your provider?" Do you have a little
>>>button on your computer that says "Change provider"? Cool! :)
>>
>>No, it will cost Xah money. In the end he will be with a bullet proof 
>>hoster, like other kooks on Usenet, or get the message.
>>
>>
>>>C'mon, John Bokma (and everyone else dumb enough to crosspost their 
>>>shushing to every group on the crosspost list -- why do they do that?
>>
>>So other people can read that reporting Xah *does* have an effect. A lot 
>>of people think that a kill file is the only solution.
> 
> 
> You win my unofficial contest for "Usenet Tool of the Year."  It is
> not difficult to skip to the next file or to add a sender to a
> killfile.  It is certainly less of a hassle than all this complaining
> you do.

No shit.  Lately it seems that for every "spam" post of Xah's, there's
at three or more by John *to all the same newsgroups* bitching about
Xah's use of bandwidth.  Pot, meet kettle.  I'm killfiling Xah for being
a useless twit and killfiling John for being a prick about it.

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


Re: Best way to handle exceptions with try/finally

2006-05-24 Thread Enigma Curry
We used to have a try..except..finally syntax in Python. It was taken
out a while ago for reasons unknown to me. The good news is that it is
back in Python 2.5.

I haven't tested it, but Guido said so himself:
http://video.google.com/videoplay?docid=60331183357868340

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


Re: Compiling Python from Sources

2006-05-24 Thread [EMAIL PROTECTED]

rwr wrote:


> configure:1687: checking for gcc
> configure:1703: found /usr/bin/gcc
> configure:1713: result: gcc

At this point, configure thinks you have the gcc compiler installed.

> configure:1753: checking for C++ compiler default output file name
> configure:1756: gccconftest.cc  >&5

Now it's going to invoke the compiler to see what kind of output it
creates.

> gcc: installation problem, cannot exec 'cc1plus': No such file or
> directory

The gcc compiler is complaining that it cannot find the file cc1plus.
The problem appears to be with the installation of gcc. If gcc was
included in your default os setup, you may need to re-install it as
the default setup may not include all the options (such as installing
the c compiler but not the c++ compiler).

I ran into a similar problem with Cygwin. In the setup program you
have to specifically tell it which compilers to install. Which it does.
But it doesn't include the tools needed by similar configuration
programs such as make and m4. Those are in a different section
of the setup program and you need to know which ones to install.
There's no option for "install everything I need to compile c/c++
programs". In my case, I had to run configure over and over again
each time going through the log finding a new missing file, re-install,
and repeat until the errors stopped.

> configure:1759: $? = 1
> configure: failed program was:
> | /* confdefs.h.  */
> |
> | #define _GNU_SOURCE 1
> | #define _NETBSD_SOURCE 1
> | #define __BSD_VISIBLE 1
> | #define _BSD_TYPES 1
> | #define _XOPEN_SOURCE 600
> | #define _XOPEN_SOURCE_EXTENDED 1
> | #define _POSIX_C_SOURCE 200112L
> | /* end confdefs.h.  */
> |
> | int
> | main ()
> | {
> |
> |   ;
> |   return 0;
> | }
> configure:1798: error: C++ compiler cannot create executables
> See `config.log' for more details.



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


RE: PEP-xxx: Unification of for statement and list-comp syntax

2006-05-24 Thread Delaney, Timothy (Tim)
Heiko Wundram wrote:

> Am Mittwoch 24 Mai 2006 06:12 schrieb Tim Roberts:
>> At one time, it was said that the "%" operator was the fastest way to
>> concatenate strings, because it was implemented in C, whereas the +
>> operator was interpreted.  However, as I recall, the difference was
>> hardly measurable, and may not even exist any longer.
> 
> The difference doesn't exist anymore for CPython (if you join a lot of
> strings)

Actually, the string concatenation optimisations only work in certain
specific cases (although they are the most common cases).

It is still definitely advised to append to a list, then join the list.

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


Re: Why can't timedeltas be divided?

2006-05-24 Thread John Machin
On 25/05/2006 8:25 AM, Maric Michaud wrote:
> Le Jeudi 25 Mai 2006 00:07, Dan Bishop a écrit :
>> If I try to write something like:
>>
>> num_weeks = time_diff / datetime.timedelta(days=7)
> 
> because it has no meaning, what you want is :
> 
> num_weeks = time_diff.days / 7
> or
> num_weeks = (time_diff / 7).days
> 
> 

The ratio of two durations has no meaning???
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bind an instance of a base to a subclass - can this be done?

2006-05-24 Thread Ben Cartwright
Lou Pecora wrote:
> I want to subclass a base class that is returned from a Standard Library
> function (particularly, subclass file which is returned from open).  I
> would add some extra functionality and keep the base functions, too.
> But I am stuck.
>
> E.g.
>
> class myfile(file):
>def myreadline():
>   #code here to return something read from file
>
> Then do something like (I know this isn't right, I'm just trying to
> convey the idea of what I would like)
>
> mf=myfile()
>
> mf=open("Afile","r")
>
> s=mf.myreadline() # Use my added function
>
> mf.close()# Use the original file function
>
>
> Possible in some way?  Thanks in advance for any clues.

This:

  >>> mf=myfile()
  >>> mf=open("Afile","r")

Is actually creating an instance of myfile, then throwing it away,
replacing it with an instance of file.  There are no variable type
declarations in Python.

To accomplish what you want, simply instantiate the subclass:

  >>> mf=myfile("Afile","r")

You don't need to do anything tricky, like binding the instance of the
base class to a subclass.  Python does actually support that, e.g.:

  >>> class Base(object):
  def f(self):
  return 'base'
  >>> class Subclass(Base):
  def f(self):
  return 'subclass'
  >>> b = Base()
  >>> b.__class__
  
  >>> b.f()
  'base'
  >>> b.__class__ = Subclass
  >>> b.__class__
  
  >>> b.f()
  'subclass'

But the above won't work for the built-in file type:

  >>> f = file('foo')
  >>> f.__class__
  
  >>> f.__class__ = Subclass
  TypeError: __class__ assignment: only for heap types

Again though, just instantiate the subclass.  Much cleaner.

Or if that's not an option due to the way your module will be used,
just define your custom file methods as global functions that take a
file instance as a parameter.  Python doesn't force you to use OOP for
everything.

--Ben

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


Re: Best way to handle exceptions with try/finally

2006-05-24 Thread Zameer
> I tend to put "return"
> statements at the end of functions to make an attempt at being clean.  I
> realize that a lot of the time functions will just return but I was
> hoping by explicitly stating my function returns that another person
> reading my code would more easily see any exit points in my code.  Turns
> out that it came to bite me later.

You can put the return statement at the end.

try:
stuff()
finally:
cleanup()
return

The return statement is not necessary in this case, but it's not in the
finally part either. If you like it, keep it. Just don't make it part
of finally if you want exceptions to propagate.

I can see where you are going by making the return statement part of
finally, and I actually expected it to work the same as if it was not
part of finally. Turns out it doesn't. Can somebody please comment on
how this works in other languages? I know that finally is not a part of
standard C++ but Borland and Microsoft compilers allow use of the
keyword __finally. Delphi also has finally and I seem to recall that
returning from the finally part does not prevent the exception from
propagating, but memory may not serve me right.

Thank you for "raising" this quite interesting question.

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


Re: Finding Upper-case characters in regexps, unicode friendly.

2006-05-24 Thread John Machin
On 25/05/2006 5:43 AM, [EMAIL PROTECTED] wrote:
> I'm trying to make a unicode friendly regexp to grab sentences
> reasonably reliably for as many unicode languages as possible, focusing
> on european languages first, hence it'd be useful to be able to refer
> to any uppercase unicode character instead of just the typical [A-Z],
> which doesn't include, for example É.   Is there a way to do this, or
> do I have to stick with using the isupper method of the string class?
> 

You have set yourself a rather daunting task.

:-)
je suis ici a vous dire grandpere que maintenant nous ecrivons sans 
accents sans majuscules sans ponctuation sans tout vive le sms vive la 
revolution les professeurs a la lanterne ah m pas des lanternes
(-:

I would have thought that a full-on NLP parser might be required, even 
for more-or-less-conventionally-expressed utterances. How will you 
handle "It's not elementary, Dr. Watson."?

However if you persist: there appears to be no way of specifying "an 
uppercase character" in Python's re module. You are stuck with isupper().

Light entertainment for the speed-freaks:
 >>> ucucase = set(unichr(i) for i in range(65536) if unichr(i).isupper())
 >>> len(ucucase)
704

Is foo in ucucase faster than foo.isupper()?

Cheers,
John



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


Re: COM Server crashing when returning large arrays

2006-05-24 Thread Alastair Alexander
Bingo! Downloaded release 208 and the problem is solved!


"Stefan Schukat" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Hello Alistair,

which version of pythoncom you are using? In the newer versions there is
an support
for a "native" safearray (the data type Excel is providing). In older
versions the complete
array was converted to a tuple which is very time and memory consuming.
during this
conversion you could run out of memory since you have the Python objects
and the
COM data in your process. I think in 207 the patch was included.

Stefan

> -Original Message-
> From: [EMAIL PROTECTED]
> [mailto:[EMAIL PROTECTED] On
> Behalf Of Alastair Alexander
> Sent: Monday, May 22, 2006 6:27 PM
> To: python-list@python.org
> Subject: COM Server crashing when returning large arrays
>
> Hi ... I'm using pythoncom to create a python COM server
> application that needs to be able to return large arrays to
> COM client apps. For example, I need to be able to return an
> array to Excel that is 500 by 10, with each element of the
> array holding a 32 byte string.
>
> If I run the code for smaller arrays, say 10 by 10, it works
> fine. If I allow the server to try to return the entire 500
> by 10 array, pythonw.exe causes a memory access violation and
> dies and I get an "automation exception" error message in the
> client app.
>
> I assume I'm violating some upper limit for data transfer
> from pythoncom into COM. Anyone know if such limitations
> exist? Is there a way around them?
> Can anyone point me in the right direction?
>
> Thanks
>
> Alastair
>
>
> p.s. 1st message on comp.lang.python, indeed 1st message on
> any news group
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


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


Re: Why can't timedeltas be divided?

2006-05-24 Thread Maric Michaud
Le Jeudi 25 Mai 2006 00:07, Dan Bishop a écrit :
> If I try to write something like:
>
>     num_weeks = time_diff / datetime.timedelta(days=7)

because it has no meaning, what you want is :

num_weeks = time_diff.days / 7
or
num_weeks = (time_diff / 7).days


-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compiling Python from Sources

2006-05-24 Thread rwr
This file contains any messages produced by compilers while
running configure, to aid debugging if configure makes a mistake.

It was created by python configure 2.3, which was
generated by GNU Autoconf 2.59.  Invocation command line was

  $ ./configure

## - ##
## Platform. ##
## - ##

hostname = blackbeauty
uname -m = i686
uname -r = 2.6.12-10-386
uname -s = Linux
uname -v = #1 Fri Apr 28 13:13:44 UTC 2006

/usr/bin/uname -p = unknown
/bin/uname -X = unknown

/bin/arch  = i686
/usr/bin/arch -k   = unknown
/usr/convex/getsysinfo = unknown
hostinfo   = unknown
/bin/machine   = unknown
/usr/bin/oslevel   = unknown
/bin/universe  = unknown

PATH: /usr/local/sbin
PATH: /usr/local/bin
PATH: /usr/sbin
PATH: /usr/bin
PATH: /sbin
PATH: /bin
PATH: /usr/bin/X11


## --- ##
## Core tests. ##
## --- ##

configure:1443: checking MACHDEP
configure:1552: result: linux2
configure:1558: checking EXTRAPLATDIR
configure:1573: result:
configure:1592: checking for --without-gcc
configure:1641: result: no
configure:1647: checking for --with-cxx=
configure:1668: result: no
configure:1687: checking for c++
configure:1716: result: no
configure:1687: checking for g++
configure:1716: result: no
configure:1687: checking for gcc
configure:1703: found /usr/bin/gcc
configure:1713: result: gcc
configure:1753: checking for C++ compiler default output file name
configure:1756: gccconftest.cc  >&5
gcc: installation problem, cannot exec 'cc1plus': No such file or
directory
configure:1759: $? = 1
configure: failed program was:
| /* confdefs.h.  */
|
| #define _GNU_SOURCE 1
| #define _NETBSD_SOURCE 1
| #define __BSD_VISIBLE 1
| #define _BSD_TYPES 1
| #define _XOPEN_SOURCE 600
| #define _XOPEN_SOURCE_EXTENDED 1
| #define _POSIX_C_SOURCE 200112L
| /* end confdefs.h.  */
|
| int
| main ()
| {
|
|   ;
|   return 0;
| }
configure:1798: error: C++ compiler cannot create executables
See `config.log' for more details.

##  ##
## Cache variables. ##
##  ##

ac_cv_env_CC_set=
ac_cv_env_CC_value=
ac_cv_env_CFLAGS_set=
ac_cv_env_CFLAGS_value=
ac_cv_env_CPPFLAGS_set=
ac_cv_env_CPPFLAGS_value=
ac_cv_env_CPP_set=
ac_cv_env_CPP_value=
ac_cv_env_LDFLAGS_set=
ac_cv_env_LDFLAGS_value=
ac_cv_env_build_alias_set=
ac_cv_env_build_alias_value=
ac_cv_env_host_alias_set=
ac_cv_env_host_alias_value=
ac_cv_env_target_alias_set=
ac_cv_env_target_alias_value=
ac_cv_prog_CXX=gcc

## - ##
## Output variables. ##
## - ##

AR=''
BASECFLAGS=''
BLDLIBRARY=''
BLDSHARED=''
BUILDEXEEXT=''
CC=''
CCSHARED=''
CFLAGS=''
CFLAGSFORSHARED=''
CONFIGURE_MACOSX_DEPLOYMENT_TARGET=''
CONFIG_ARGS=''
CPP=''
CPPFLAGS=''
CXX='gcc'
DEFS=''
DLINCLDIR=''
DLLLIBRARY=''
DYNLOADFILE=''
ECHO_C=''
ECHO_N='-n'
ECHO_T=''
EGREP=''
EXEEXT=''
EXTRAMACHDEPPATH=''
EXTRAPLATDIR=''
HAVE_GETHOSTBYNAME=''
HAVE_GETHOSTBYNAME_R=''
HAVE_GETHOSTBYNAME_R_3_ARG=''
HAVE_GETHOSTBYNAME_R_5_ARG=''
HAVE_GETHOSTBYNAME_R_6_ARG=''
INSTALL_DATA=''
INSTALL_PROGRAM=''
INSTALL_SCRIPT=''
INSTSONAME=''
LDFLAGS=''
LDLAST=''
LDLIBRARY=''
LDLIBRARYDIR=''
LDSHARED=''
LIBC=''
LIBM=''
LIBOBJS=''
LIBRARY=''
LIBS=''
LIBTOOL_CRUFT=''
LINKCC=''
LINKFORSHARED=''
LN=''
LTLIBOBJS=''
MACHDEP='linux2'
MACHDEP_OBJS=''
MAINOBJ='python.o'
OBJEXT=''
OPT=''
PACKAGE_BUGREPORT=''
PACKAGE_NAME='python'
PACKAGE_STRING='python 2.3'
PACKAGE_TARNAME='python'
PACKAGE_VERSION='2.3'
PATH_SEPARATOR=':'
PYTHONFRAMEWORK=''
PYTHONFRAMEWORKDIR='no-framework'
PYTHONFRAMEWORKINSTALLDIR=''
PYTHONFRAMEWORKPREFIX=''
RANLIB=''
RUNSHARED=''
SGI_ABI=''
SHELL='/bin/sh'
SHLIBS=''
SIGNAL_OBJS=''
SO=''
SOVERSION='1.0'
SRCDIRS=''
THREADHEADERS=''
THREADOBJ=''
TRUE=''
UNICODE_OBJS=''
USE_SIGNAL_MODULE=''
USE_THREAD_MODULE=''
VERSION='2.3'
ac_ct_CC=''
ac_ct_RANLIB=''
bindir='${exec_prefix}/bin'
build_alias=''
datadir='${prefix}/share'
exec_prefix='NONE'
host_alias=''
includedir='${prefix}/include'
infodir='${prefix}/info'
libdir='${exec_prefix}/lib'
libexecdir='${exec_prefix}/libexec'
localstatedir='${prefix}/var'
mandir='${prefix}/man'
oldincludedir='/usr/include'
prefix='NONE'
program_transform_name='s,x,x,'
sbindir='${exec_prefix}/sbin'
sharedstatedir='${prefix}/com'
sysconfdir='${prefix}/etc'
target_alias=''

## --- ##
## confdefs.h. ##
## --- ##

#define _BSD_TYPES 1
#define _GNU_SOURCE 1
#define _NETBSD_SOURCE 1
#define _POSIX_C_SOURCE 200112L
#define _XOPEN_SOURCE 600
#define _XOPEN_SOURCE_EXTENDED 1
#define __BSD_VISIBLE 1

configure: exit 77

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


Re: Compiling Python from Sources

2006-05-24 Thread [EMAIL PROTECTED]

rwr wrote:
> As a newbie I am having problems/errors configuring Python after
> unpacking the Python archive:
>
> # ./configure
> checking MACHDEP... linux2
> checking EXTRAPLATDIR...
> checking for --without-gcc... no
> checking for --with-cxx=... no
> checking for c++... no
> checking for g++... no
> checking for gcc... gcc
> checking for C++ compiler default output file name... configure: error:
> C++ compiler cannot create executables
> See `config.log' for more details.
>
> Any help on my current dilemma???

Did you look in config.log for more details?
Would you like to share them?

> TIA,
> rwr

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


Why can't timedeltas be divided?

2006-05-24 Thread Dan Bishop
If I try to write something like:

num_weeks = time_diff / datetime.timedelta(days=7)

I get:

TypeError: unsupported operand type(s) for /: 'datetime.timedelta'
and 'datetime.timedelta'

Of course, one could extend the timedelta class to implement division,

def _microseconds(self):
return (self.days * 86400 + self.seconds) * 100 +
self.microseconds
def __truediv__(self, other):
if isinstance(other, datetime.timedelta):
return self._microseconds() / other._microseconds()
else:
return datetime.timedelta(0, 0, self._microseconds() /
other)
def __floordiv__(self, other):
   if isinstance(other, datetime.timedelta):
  return self._microseconds() // other._microseconds()
   return NotImplemented

but why is a basic arithmetic operation missing from the standard
datetime module?

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


Re: Bind an instance of a base to a subclass - can this be done?

2006-05-24 Thread Maric Michaud
Le Mercredi 24 Mai 2006 22:04, Diez B. Roggisch a écrit :
> Nope, not in that way. But you might consider writing a proxy/wrapper
> for an object. That looks like this (rouch sketch from head):
>
> class FileWrapper(object):
>     def __init__(self, f):
>        self._f = f
>
>     def __getattr__(self, name):
>        return getattr(self._f, name)
>
>     def myreadline(self):
>        
Why use a proxy when you can just inherit from the builtin file object ?

class myFile(file) :
def myreadline(self) : print 'yo'


In [20]: myFile('frwiki-20060511-abstract.xml')
Out[20]: 

In [21]: myFile('frwiki-20060511-abstract.xml').myreadline()
yo

In [22]: 



-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Compiling Python from Sources

2006-05-24 Thread rwr
As a newbie I am having problems/errors configuring Python after
unpacking the Python archive:

# ./configure
checking MACHDEP... linux2
checking EXTRAPLATDIR...
checking for --without-gcc... no
checking for --with-cxx=... no
checking for c++... no
checking for g++... no
checking for gcc... gcc
checking for C++ compiler default output file name... configure: error:
C++ compiler cannot create executables
See `config.log' for more details.

Any help on my current dilemma???
TIA,
rwr

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


Request for comment: programmer starting page (micro knowledge base)

2006-05-24 Thread Paolo Pantaleo
I am writting down a pege with useful links for a Python programmer.
That is reference, tutorials and anything that can be useful. I use it
regulary when programming in Python and I can't do without it.

I would be happy if you go and see that page, and tell me what you
think about and suggest links to be added.

The page is : http://ppp3.co.nr

Thnx
Paolo Pantaleo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python keywords vs. English grammar

2006-05-24 Thread Boris Borcic
Roy Smith wrote:
> I noticed something interesting today.  In C++, you write:
> 
> try {
>throw foo;
> } catch {
> }
> 
> and all three keywords are verbs, so when you describe the code, you can 
> use the same English words as in the program source, "You try to execute 
> some code, but it throws a foo, which is caught by the handler".

Not convincing at all, since the *explicit* throw/raise lexically inside a try 
block with a catch/except clause that's *predetermined* to catch it... is the 
exception rather than the rule. Normally you'd use another form of block exit. 
Or is the case different in C++  by any chance ?

> 
> In Python, you write:

usually, you don't write something similar to that, and neither in C++ I guess.
> 
> try:
>raise foo
> except:
> 
> and now you've got a mix of verbs and (I think), a preposition.  You can't 
> say, "You try to execute some code, but it raises a foo, which is excepted 
> by the handler".  It just doesn't work grammatically.
> 
> Sigh.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to use matplotlib contour()?

2006-05-24 Thread Robert Kern
Grant Edwards wrote:
> I downloaded examples/contour_demo.py, and it doesn't run.
> 
> I've searched both the user guide and the Wiki for "contour"
> and got zero hits.
> 
> http://matplotlib.sourceforge.net/matplotlib.pylab.html#-contour
> appears to be a good reference if you already know how to use
> contour(), but I could glean zero clues from it on how to
> actually use contour().  For example, it doesn't explain what
> the actual formats/types of the parameters.  It explains what
> the parameters do, but not what they _are_

Yes, unfortunately, much of the documentation was written by people who were
very familiar with the Matlab interfaces that these functions are emulating.

> For example one parameter is specied as "an array".  No clue as
> to how many dimensions or what the axis are.
> 
> In another place it says "the X,Y parameters specify the (x,y)
> coordinates of a surface".  _How_ do they specify the surface?
> Are they just equal length lists of x and y coordinates that
> specify len(X) points.  Or do they specify a len(X) x len(Y)
> grid of points?

> Why would my Z values be a 2D array?

contour() only does contouring on gridded data. If you want to handle scattered
datapoints, you will have to do some interpolation.

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

So X, Y, and Z are all 2-D arrays laid out corresponding to the grid that you
have sampled. I thought the contour_demo.py example was reasonably clear on
this, but if you didn't get it to run, then I can see why you wouldn't have 
read it.

Talking about this on matplotlib-users will probably get these problems fixed
faster:

  https://lists.sourceforge.net/lists/listinfo/matplotlib-users

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


how to use matplotlib contour()?

2006-05-24 Thread Grant Edwards
I downloaded examples/contour_demo.py, and it doesn't run.

I've searched both the user guide and the Wiki for "contour"
and got zero hits.

http://matplotlib.sourceforge.net/matplotlib.pylab.html#-contour
appears to be a good reference if you already know how to use
contour(), but I could glean zero clues from it on how to
actually use contour().  For example, it doesn't explain what
the actual formats/types of the parameters.  It explains what
the parameters do, but not what they _are_

For example one parameter is specied as "an array".  No clue as
to how many dimensions or what the axis are.

In another place it says "the X,Y parameters specify the (x,y)
coordinates of a surface".  _How_ do they specify the surface?
Are they just equal length lists of x and y coordinates that
specify len(X) points.  Or do they specify a len(X) x len(Y)
grid of points?

Since I can't find any documentation, I thought I'd just try a
few things.

I've got X,Y,Z values in an Nx3 array named "data" that looks
like this:

X  Y   Z


[[  4.94958000e+01   3.65706000e+00   1.8460e-01]
 [  4.94958000e+01   3.66447000e+00   1.82142000e-01]
 [  4.94958000e+01   5.04936000e+00   1.90937000e-01]
 ..., 
 [  2.19844000e+03   9.7421e+00   8.29735000e-01]
 [  2.19844000e+03   9.93863000e+00   9.82307000e-01]
 [  2.19844000e+03   1.03143000e+01   8.28844000e-01]]
 
If I just pass the array to contour() by doing
"pylab.contour(data)" I get this error:

   Traceback (most recent call last):
 File "./surfplot.py", line 11, in ?
   pylab.contour(data)
 File "/usr/lib/python2.4/site-packages/matplotlib/pylab.py", line 1659, in 
contour
   ret =  gca().contour(*args, **kwargs)
 File "/usr/lib/python2.4/site-packages/matplotlib/axes.py", line 1244, in 
contour
   return self._contourHelper.contour(*args, **kwargs)
 File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 727, 
in contour
   x, y, z, lev = self._contour_args(False, badmask, origin, extent, *args)
 File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 544, 
in _contour_args
   lev = self._autolev(z, 7, filled, badmask)
 File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 471, 
in _autolev
   lev = linspace(zmin, zmax, N+2)[1:-1]
 File "/usr/lib/python2.4/site-packages/matplotlib/mlab.py", line 87, in 
linspace
   dx = (xmax-xmin)/(N-1)
   TypeError: unsupported operand type(s) for -: 'str' and 'str'

I've no clue what that means.  Well, I know what the TypeError
means _literally_, but I've no idea how I'm supposed to
interpret that particular error in regards to what I passed to
contour().

Attempting to use one of the other forms found on the above web
page I pass X,Y,Z vectors to contour() by doing
"pylab.contour(data[:,0],data[:,1],data[:,2])":

   Traceback (most recent call last):
 File "./surfplot.py", line 13, in ?
   pylab.contour(data[:,0],data[:,1],data[:,2])
 File "/usr/lib/python2.4/site-packages/matplotlib/pylab.py", line 1659, in 
contour
   ret =  gca().contour(*args, **kwargs)
 File "/usr/lib/python2.4/site-packages/matplotlib/axes.py", line 1244, in 
contour
   return self._contourHelper.contour(*args, **kwargs)
 File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 727, 
in contour
   x, y, z, lev = self._contour_args(False, badmask, origin, extent, *args)
 File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 539, 
in _contour_args
   x,y,z = self._check_xyz(args[:3])
 File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 515, 
in _check_xyz
   raise TypeError("Input z must be a 2D array.")
   TypeError: Input z must be a 2D array.
   
Which is almost as cryptic a result as my first attempt.

Why would my Z values be a 2D array?

-- 
Grant Edwards   grante Yow!  My NOSE is NUMB!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using python for a CAD program

2006-05-24 Thread Paddy
I guess the 'advanced O/R mapping tools' make it easier to map the data
to an RDBMS, but their is still the performance issue. Since this has
degenerated into a an issue of performance then I suggest the original
poster create a clear interface between his data and its persistance
method. This should make it easier to attach another, if his first
choice is not up to it.

- Cheers, Pad.

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


Re: Python Version Testing Tool?

2006-05-24 Thread Serge Orlov
Michael Yanowitz wrote:
> Hello:
>
>Is there a version testing tool available for Python
> such that I can check to see if my code will still run in
> versions 2.2, 2.3, 2.4.3, and 1.1 (for example) (or whatever)
> without having to install all these different versions on my
> computer?

Such tool will never be reliable, unless it duplicates all the work
that went into all python versions.

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


Re: Finding Upper-case characters in regexps, unicode friendly. (oh, bugger)

2006-05-24 Thread Tim Chase
Sorry...I somehow missed the key *uppercase* bit of that, and 
somehow got it in my head that you just wanted unicode letters, 
not numbers.  Please pardon the brain-blink.  I can't find 
anything in Python's regexp docs that do what you want.  Vim's 
regexp engine has a "uppercase characters" and "lowercase 
characters" atoms, but it seems there's no counterpart to them in 
Python.  Thus, you may have to take a combined attack of 
regexps+isupper().

Using isupper() has some peculiar side-effects in that it only 
checks uppercase-able characters, so

 >>> "1A".isupper()
True

which may or may not be what you wanted.  The previously 
shot-from-the-hip regexp stuff will help you filter out any 
non-alphabetic unicode characters, which can then be passed in 
turn to isupper()

-tkc




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


Re: Use of lambda functions in OOP, any alternative?

2006-05-24 Thread Scott David Daniels
Pablo wrote:

> Second solution: This is what i want, but...
> 
> class Base(object):
> def __init__(self, attr):
> self._attr = attr
> def getattr(self):
> return self._attr
> attr = property(fget=lambda self: self.getattr())
> 
> class Derived(Base):
> def getattr(self):
> return 2*self._attr
> 
> Question: Isn't there an *alternative* way to do it without the lambda
> function?
> 
> Thanks in advance!

Simplest:

 class Base(object):
 def __init__(self, attr):
 self._attr = attr
 def getattr(self):
 return self._attr
 @property  # single-arg property is a read-only thing.
 def attr(self):
 return self.getattr()

### Little longer; maybe more explicit (tastes vary):

 class Base(object):
 def __init__(self, attr):
 self._attr = attr
 def getattr(self):
 return self._attr
 def attr(self):
 return self.getattr()
 attr = property(fget=attr)


--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding Upper-case characters in regexps, unicode friendly.

2006-05-24 Thread Tim Chase
> I'm trying to make a unicode friendly regexp to grab sentences
> reasonably reliably for as many unicode languages as
> possible, focusing on european languages first, hence it'd be
> useful to be able to refer to any uppercase unicode character
> instead of just the typical [A-Z], which doesn't include, for
> example É.   Is there a way to do this, or do I have to stick
> with using the isupper method of the string class?

Well, assuming you pass in the UNICODE or LOCALE specifier, the 
following portion of a regexp *should* find what you're describing:


###
import re
tests = [("1", False),
("a", True),
("Hello", True),
("2bad", False),
("bad1", False),
("a c", False)
]
r = re.compile(r'^(?:(?=\w)[^\d_])*$')
for test, expected_result in tests:
 if r.match(test):
 passed = expected_result
 else:
 passed = not expected_result
 print "[%s] expected [%s] passed [%s]" % (
 test, expected_result, passed)
###

That looks for a "word" character ("\w") but doesn't swallow it 
("(?=...)"), and then asserts that the character is not ("^") a 
digit ("\d") or an underscore.  It looks for any number of "these 
things" ("(?:...)*"), which you can tweak to your own taste.

For Unicode-ification, just pass the re.UNICODE parameter to 
compile().

Hope this makes sense and helps,

-tkc




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


Python Version Testing Tool?

2006-05-24 Thread Michael Yanowitz
Hello:

   Is there a version testing tool available for Python
such that I can check to see if my code will still run in
versions 2.2, 2.3, 2.4.3, and 1.1 (for example) (or whatever)
without having to install all these different versions on my
computer?

Thanks in advance:
Michael Yanowitz

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


Re: PEP 3102 for review and comment

2006-05-24 Thread Kay Schluehr

molasses wrote:
> I don't mind the naked star and will be happy if thats what we end up with.
>
> Though how about using *None?
> I think that makes the intention of the function clearer.
>
> eg.
> def compare(a, b, *None, key=None):
>
> Which to me reads as "no further positional arguments".
>
> Or alternatively:
> def compare(a, b, *0, key=None):
>
> -- Mark

Argh!

Sorry, but this syntax seems to me a perlish hackaround. Although the
star is clearly beautifull and vry pythonic ;)

>From the PEP:
One can easily envision a function
which takes a variable number of arguments, but also takes one
or more 'options' in the form of keyword arguments.  Currently,
the only way to do this is to define both a varargs argument,
and a 'keywords' argument (**kwargs), and then manually extract
the desired keywords from the dictionary.

The current solution is fine and not very troublesome. But if you want
to drop a named dict just replace it by an unnamed one ( unless you
think this will seduce people to use devilish, horrible lambda ... ).

Suggestions:

def compare(a, b, *args, **kwd):# the classics

def compare(a, b, *args, {"key":None}):  # pass keywords in unnamed
dict

def compare(a, b, *args, {key=None}):   # alternative syntax

def compare(a, b, *args, **kwd={...,"key":None}):   # having the
cake and eating it

Regards,
Kay

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


Re: Looking for help with Regular Expression

2006-05-24 Thread Roger Miller
Seem to be a lot of regular expression questions lately. There is a
neat little RE demonstrator buried down in
Python24/Tools/Scripts/redemo.py, which makes it easy to experiment
with regular expressions and immediately see the effect of changes. It
would be helpful if it were mentioned in the RE documentation, although
I can understand why one might not want a language reference to deal
with informally-supported tools.

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


Re: Bind an instance of a base to a subclass - can this be done?

2006-05-24 Thread Diez B. Roggisch
Lou Pecora schrieb:
> I've been scanning Python in a Nutshell, but this seems to be either 
> undoable or so subtle that I don't know how to do it.
> 
> I want to subclass a base class that is returned from a Standard Library 
> function (particularly, subclass file which is returned from open).  I 
> would add some extra functionality and keep the base functions, too.  
> But I am stuck.
> 
> E.g. 
> 
> class myfile(file):
>def myreadline():
>   #code here to return something read from file
> 
> Then do something like (I know this isn't right, I'm just trying to 
> convey the idea of what I would like)
> 
> mf=myfile()
> 
> mf=open("Afile","r")  
> 
> s=mf.myreadline() # Use my added function
> 
> mf.close()# Use the original file function
> 
> 
> Possible in some way?  Thanks in advance for any clues.

Nope, not in that way. But you might consider writing a proxy/wrapper 
for an object. That looks like this (rouch sketch from head):

class FileWrapper(object):
def __init__(self, f):
   self._f = f

def __getattr__(self, name):
   return getattr(self._f, name)

def myreadline(self):
   


Then you do

f = FileWrapper(open(name, mode))


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


Pydev 1.0.8 released

2006-05-24 Thread Fabio Zadrozny
Hi All,



Pydev and Pydev Extensions 1.0.8 have been released



Check http://www.fabioz.com/pydev for details on Pydev Extensions



and http://pydev.sf.net for details on Pydev


This is a 'single-bugfix' release because of a major bug that could
cause Pydev to hang when making a new line under certain condations.

What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python and
Jython development -- making Eclipse a first class Python IDE -- It
comes with many goodies such as code completion, syntax highlighting,
syntax analysis, refactor, debug and many others.


Cheers,

-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
http://www.esss.com.br

Pydev Extensions
http://www.fabioz.com/pydev

Pydev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com

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

Finding Upper-case characters in regexps, unicode friendly.

2006-05-24 Thread possibilitybox
I'm trying to make a unicode friendly regexp to grab sentences
reasonably reliably for as many unicode languages as possible, focusing
on european languages first, hence it'd be useful to be able to refer
to any uppercase unicode character instead of just the typical [A-Z],
which doesn't include, for example É.   Is there a way to do this, or
do I have to stick with using the isupper method of the string class?

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


Re: simple print is not working..

2006-05-24 Thread Paul Osman
On 24-May-06, at 3:41 PM, [EMAIL PROTECTED] wrote:

> What is wrong with this script?
>
> #!/usr/bin/python
> fsfile = open('/tmp/fs_info.al', 'r')
> for line in fsfiles.readlines():
> print line
> fsfile.close()
>
>
> #./get_fs_info.py
>   File "./get_fs_info.py", line 4
> print line
> ^
> SyntaxError: invalid syntax
>
>
> Any ideas?
>
> Thanks
> AL

Well first, you have to indent properly :) Assuming you did that and  
the copy & paste just removed it, you're also creating a variable  
called fsfile, then trying to call the readlines() method on an  
object called fsfiles... that'll cause a problem.

Cheers,

--
Paul Osman
http://www.eval.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Programming Books?

2006-05-24 Thread vbgunz
> Thanks vbgunz that was the reply I was looking for!
> Do you think it is wise to hold back for a 3rd edition?

No, 2nd edition is literally perfect. The reason why is because almost
nothing significant enough has changed since it's publication. In other
words, you will not learn any outdated material. everything you learn
in Learning Python is still applicable in the latest version of Python
(2.4.3, 2.5).

I will not be surprised in the least if typos are the only items
corrected in the 3rd edition, perhaps along with a little bit of some
new material. The fundamentals, the basics, the only real knowledge
necessary to start getting busy in Python is found in the book. Good
luck, I hope you enjoy it!

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


Re: simple print is not working..

2006-05-24 Thread Carl J. Van Arsdall
[EMAIL PROTECTED] wrote:
> What is wrong with this script?
>
> #!/usr/bin/python
> fsfile = open('/tmp/fs_info.al', 'r')
> for line in fsfiles.readlines():
> print line
> fsfile.close()
>
>
>   
Did you cut and paste that code?  I see a couple typos

First, on the line

for line in fsfiles.readlines():

There's an extra s in fsfile

Secondly, the line:

print line

should have an indentation to denote that its the block of code that the 
for loop will execute on.

.c



-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: simple print is not working..

2006-05-24 Thread lahirister

[EMAIL PROTECTED] wrote:

Sorry typo: Script is like this:

#!/usr/bin/python
fsfile = open('/tmp/fs_info.al', 'r')
for line in fsfile.readlines():
print line
fsfile.close()

*not* fsfiles as I typed in original post.

> What is wrong with this script?
>
> #!/usr/bin/python
> fsfile = open('/tmp/fs_info.al', 'r')
> for line in fsfiles.readlines():
> print line
> fsfile.close()
>
>
> #./get_fs_info.py
>   File "./get_fs_info.py", line 4
> print line
> ^
> SyntaxError: invalid syntax
> 
> 
> Any ideas?
> 
> Thanks
> AL

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


Finding Upper-case characters in regexps, unicode friendly.

2006-05-24 Thread possibilitybox
I'm trying to make a unicode friendly regexp to grab sentences
reasonably reliably for as many unicode languages as possible, focusing
on european languages first, hence it'd be useful to be able to refer
to any uppercase unicode character instead of just the typical [A-Z],
which doesn't include, for example É.   Is there a way to do this, or
do I have to stick with using the isupper method of the string class?

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


simple print is not working..

2006-05-24 Thread lahirister
What is wrong with this script?

#!/usr/bin/python
fsfile = open('/tmp/fs_info.al', 'r')
for line in fsfiles.readlines():
print line
fsfile.close()


#./get_fs_info.py
  File "./get_fs_info.py", line 4
print line
^
SyntaxError: invalid syntax


Any ideas?

Thanks
AL

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


Bind an instance of a base to a subclass - can this be done?

2006-05-24 Thread Lou Pecora
I've been scanning Python in a Nutshell, but this seems to be either 
undoable or so subtle that I don't know how to do it.

I want to subclass a base class that is returned from a Standard Library 
function (particularly, subclass file which is returned from open).  I 
would add some extra functionality and keep the base functions, too.  
But I am stuck.

E.g. 

class myfile(file):
   def myreadline():
  #code here to return something read from file

Then do something like (I know this isn't right, I'm just trying to 
convey the idea of what I would like)

mf=myfile()

mf=open("Afile","r")  

s=mf.myreadline() # Use my added function

mf.close()# Use the original file function


Possible in some way?  Thanks in advance for any clues.

-- Lou Pecora  (my views are my own) REMOVE THIS to email me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3102 for review and comment

2006-05-24 Thread gangesmaster
None is not currently a keyword

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


Re: John Bokma harassment

2006-05-24 Thread George Sakkis
Geoffrey Summerhayes wrote:

> "Bill Atkins" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > John Bokma <[EMAIL PROTECTED]> writes:
> >
> > [snip]
> >
> >> --
> >> John   MexIT: http://johnbokma.com/mexit/
> >>personal page:   http://johnbokma.com/
> >> Experienced programmer available: http://castleamber.com/
> >> Happy Customers: http://castleamber.com/testimonials.html
> >
> > Interesting.  Doesn't your signature contain advertisements for your
> > website?  Aren't you posting to five different groups?
>
> Shh! Pointing out ironic hypocrisy never works.

You can say that again: http://tinyurl.com/hvvqd 

George

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


Xah Lee network abuse

2006-05-24 Thread PofN
Xah Lee wrote:
> I'm sorry to trouble everyone.

Liar. You were never sorry when you troubled us with your posting
excrements in the past, you are not sorry now.

>  But as you might know, due to my
> controversial writings and style,

Liar. You are a net abuser, a kook and a troll. It has nothing to do
with your writings and style. It has everything to do with your
vialoation of netiquette, with you x-posting of off-topic messages,
with your trolling and kookery.

> recently John Bokma lobbied people to
> complaint to my web hosting provider.

Liear. John asked people do do their duty as net citizens and to report
a serial net abuser.

> After exchanging a few emails, my
> web hosting provider sent me a 30-day account cancellation notice last
> Friday.

Shit. So they gave you 30 more days to abuse the net. Shit, shit, shit.
They should have pulled the plug immediately.

> I'm not sure I will be able to keep using their service, but I do hope
> so.

Lets hope not.

> I do not like to post off-topic messages,

Liar. Your whole usenet "career" is build around the posting of
off-topic messages.

> but this is newsgroup
> incidence is getting out of hand,

Liar. You were getting out of hand for some time now.

> and I wish people to know about it.

People know very well about you, Xah Lee, the serial newsgroup abuser,
troll, liar, and kook.

> I wrote some full detail here:
> http://xahlee.org/Periodic_dosage_dir/t2/harassment.html

More lies.

> If you believe this lobbying to my webhosting provider is unjust,
> please write to my web hosting provider [EMAIL PROTECTED]

I believe it is justified, and I wrote dreamhost to thank them. You now
reap what you saw. You refused to play nice with us in the past, now
don't be surprised that people don't come to your aid.

> Your help is appreciated. Thank you.

I appreciate the courage of John and friends to stand up against
someone who is out of control. You are not even affraid off accusing
John of a crime (harrasment) and starting a smear campaing on your web
site. You have sunken so low that you are fast approaching the earth's
metal core.

*Thanks John for making usenet a better place!*

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


Re: A critic of Guido's blog on Python's lambda

2006-05-24 Thread Kay Schluehr
Michele Simionato wrote:
> Kay Schluehr wrote:
> > http://www.fiber-space.de/EasyExtend/doc/EE.html
>
> Well, I have not read that page yet, but the name "fiber space" reminds
> me of old
> memories, when I was doing less prosaic things than now. Old times ..
> ;)
>
>  Michele Simionato

But I guess that time this stuff was taught to you as "fiber bundles",
right? Oh, yes. Old times ;)

Well, besides the cute rhyme on "cyberspace" I had this analogy in mind
and that's why I called the extension languages "fibers". The
association is "fibers over a base space" or a base language as in this
case. The terms are not used strictly of course. I could not even say
what triviality could be in this context. But I still seek for an
acceptable glue mechanism which is beyond the scope of the current
first release :)

Kay

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


Re: Web framework comparison video

2006-05-24 Thread Adam Jones
Just as a note, TurboGears has added a lot that would change the
scoring on this. The project has been moving pretty quickly towards 1.0
lately, and I would advise anyone interested in a comparison to check
out the recent changes before making a final decision. The same will
probably hold true for many of the projects mentioned though.

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


Re: John Bokma harassment

2006-05-24 Thread Geoffrey Summerhayes

"Bill Atkins" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> John Bokma <[EMAIL PROTECTED]> writes:
>
> [snip]
>
>> -- 
>> John   MexIT: http://johnbokma.com/mexit/
>>personal page:   http://johnbokma.com/
>> Experienced programmer available: http://castleamber.com/
>> Happy Customers: http://castleamber.com/testimonials.html
>
> Interesting.  Doesn't your signature contain advertisements for your
> website?  Aren't you posting to five different groups?

Shh! Pointing out ironic hypocrisy never works.

--
Geoff

P.S. You forgot that it's also off-topic for all groups.
P.P.S. Mea culpa


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


Re: Conversion of perl based regex to python method

2006-05-24 Thread Andrew Robert
Andrew Robert wrote:
> I have two Perl expressions
> 
> 
> If windows:
> 
> perl -ple "s/([^\w\s])/sprintf(q#%%%2X#, ord $1)/ge"  somefile.txt
> 
> If posix
> 
> perl -ple 's/([^\w\s])/sprintf("%%%2X", ord $1)/ge'  somefile.txt
> 
> 
> 
> The [^\w\s]  is a negated expression stating that any character
> a-zA-Z0-9_, space or tab is ignored.
> 
> The () captures whatever matches and throws it into the $1 for
> processing by the sprintf
> 
> In this case, %%%2X which is a three character hex value.
> 
> How would you convert this to a python equivalent using the re or
> similar module?
> 
> I've begun reading about using re expressions at
> http://www.amk.ca/python/howto/regex/ but I am still hazy on implementation.
> 
> Any help you can provide would be greatly appreciated.
> 
> Thanks,
> Andy
Okay.. I got part of it..

The code/results below seem to do the first part of the expression.

I believe the next part is iterating across each of the characters,
evaluate the results and replace with hex as needed.


# Import the module
import re

# Open test file
file=open(r'm:\mq\mq\scripts\testme.txt','r')

# Read in a sample line
line=file.readline()

# Compile expression to exclude all characters plus space/tab
pattern=re.compile('[^\w\s]')

# Look to see if I can find a non-standard character
# from test line  #! C:\Python24\Python

var=pattern.match('!')

# gotcha!
print var
<_sre.SRE_Match object at 0x009DA8E0

# I got
print var.group()

!

# See if pattern will come back with something it shouldn't
var =pattern.match('C')
print var

#I got
None



Instead of being so linear, I was thinking that this might be closer.
Got to figure out the hex line but then we are golden


# Evaluate captured character as hex
def ret_hex(ch):
return chr((ord(ch) + 1) % )

# Evaluate the value of whatever was matched
def eval_match(match):
return ret_hex(match.group(0))

# open file
file = open(r'm:\mq\mq\scripts\testme.txt','r')

# Read each line, pass any matches on line to function
for line in file.readlines():
 re.sub('[^\w\s]',eval_match, line)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scipy: vectorized function does not take scalars as arguments

2006-05-24 Thread Travis E. Oliphant
ago wrote:
> Once I vectorize a function it does not acccept scalars anymore. Es
> 
> def f(x): return x*2
> vf = vectorize(f)
> print vf(2)
> 
> AttributeError: 'int' object has no attribute 'astype'
> 
> Is this the intended behaviour?
> 

Vectorize handles scalars in recent versions of NumPy.  Which version do 
you have?

-Travis


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


Re: Python Programming Books?

2006-05-24 Thread gregarican
I third this opinion. This book gave me a lot of insight and helped me
get comfortable using Python. I also recall looking at a document Guido
published on how to get started with Python as well as reading the
reference docs that come bundled with the language install. Of course I
came from a background of already using Ruby so the departure wasn't
altogether difficult. The languages are different but to me they seem
like cousins :-)

Typically when I try to teach myself a new language, such as Python,
Ruby, Smalltalk, Scheme, Haskell, etc. I check out my online catalog
through my local library system. Usually I can find a couple of books
to peruse. If I don't like them I can just drop them back off. Then I
check out eBay for used books. This route was especially helpful for
teaching myself Smalltalk, since a lot of the books were 10-20 years
old so I picked them up for anywhere between $1.00 to $5.00.

I digress. "Learning Python" by Mark Lutz is a thorough and complete
introduction to what you need to know to get started. Even if you are
coming into Python with no prior programming language exposure.

John Salerno wrote:
> vbgunz wrote:
> > Learning Python by Mark Lutz will be the most perfect book to get you
> > started! Perhaps there are others aimed at the non-programmer but after
> > getting through that book (2 times) I finally left it with wings... It
> > is a great book for the n00b in my humble opinion. After that, you'll
> > pretty much start flying higher on your own as long as you always keep
> > the python docs handy along with the addresses to comp.lang.python and
> > it's IRC channel #python on irc.freenode.net...
> >
> > Good luck, welcome to Python!
> >
>
> I second this opinion completely. Use this book to start with! It is a
> wonderful intro to the language and will give you a solid foundation.
>
> As for waiting for a 3rd edition, don't do it! If you're like me, you'll
> want the latest there is, so I was tempted to start with something newer
> too (since this book covers up to 2.2), but honestly it covers
> everything you need to know. There are maybe two or three new additions
> that you can read about elsewhere, but Learning Python is THE book to
> start with, IMO.
> 
> Get it now! :)

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


perl to python

2006-05-24 Thread Depcnb1



This is Jeff Hutchinson
-- 
http://mail.python.org/mailman/listinfo/python-list

perl to python

2006-05-24 Thread Depcnb1



I'm looking for Steve Rumbalski    

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

Re: Python Programming Books?

2006-05-24 Thread Jerry
I think that Beginning Python: From Novice to Professional is a great
book for beginners.  It's probably a bit too simplistic for someone who
already understands the language or who has a decent background in
development.  I just borrowed it from my brother and while I consider
myself a pretty good developer (I know PHP, Perl, Shell Scripting,
VBScript, Visual Basic, and some C), I found that some of the things
that other books presented where more advanced and that they left me
missing some of the more basic concepts in Python (i.e. list
comprehension made simple).  After Beginning Python, a good book to go
to would be Dive Into Python which you can get free at
http://www.diveintopython.org.  The book covers much of the same
material that Beginning Python does, but has many more full fleged
examples to help solidify what you are doing.  I've also heard really
good things about Learning Python, but these other two books seem to
cover all of the same material.

After these, I plan on reading Game Programming with Python and the
Python Cookbook to round out my library.
I'll have to check out Python Essential Reference and I'll probably get
Mastering Regular Expressions (which I think is a must have for any
language even though it focuses on Perl).

--
Jerry

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


Re: Python keywords vs. English grammar

2006-05-24 Thread bruno at modulix
defcon8 wrote:
> 1. Does it matter?
> 2. Is it affecting your productivity.
> 3. Are you not trying to programme?
> 4. It is open source, change it and stop whining.
> 

What about trying emacs +x doctor  ?

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >