Re: newbie: working iwth list of tuples

2006-01-29 Thread Raymond Hettinger
[Raymond Hettinger]
> Parameterized filter, extract, and reduce functions can be handled in a
> like manner.

Just for grins, here is a more worked-out example:

def pfunc(inputfields, operation):
"Parameterized computation of a new field"
# For example, append a field that is the sum of fields 1 and 3:
#z = pfunc((1, 3), operator.add)
#print map(z, database)
def z(record):
newfield = operation(*[record[f] for f in inputfields])
return record + (newfield,)
return z

def rfunc(inputfield, operation):
"Parameterized reduce operation"
#
# For example, find the maximum value of field 2:
#r = rfunc(2, max)
#print reduce(r, database)
def z(cumval, record):
x = record[inputfield]
return operation(cumval, x)
return z

def filt_func(inputfields, operation):
"Parameterized filter operation"
#
# For example, get records where field1 < field2:
#f = filt_func((1, 3), operator.lt)
#print filter(f, database)
def z(record):
i, j = inputfields
return operation(i, j)
return z

def xfunc(fields):
"Parameterized extract operation"
#
# For example, extract fields 1, 3, and 4
# x = xfunc((1,3,4))
# print map(x, database)
def z(record):
return tuple([record[f] for f in fields])
return z


#  The examples can be run on the following sample database: 

database = [
(10, 25, 30, 40, 50, 60),
(100, 250, 300, 400, 500, 600),
(1, 2.5, 3, 4, 5, 6),
]

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


Re: newbie: working iwth list of tuples

2006-01-29 Thread John Bauman

"Paul Rubin"  wrote in message 
news:[EMAIL PROTECTED]
> "falcon" <[EMAIL PROTECTED]> writes:
>> I forgot to add that I passing a tuple of functions to the reduce
>> function but apparently that is not allowed.  My guess was that a tuple
>> made up of individual (simple) functions might be easier to manipulate
>> programatically than a function which has to know the structure of a
>> list.
>
> Python really doesn't support this style all that well.  Try Haskell.
> See also the SICP book, which uses Scheme.
>
>> (My test code)
>> x=[('a',1),('a',1),('a',3),('b',1),('b',2),('c',2),('c',3),('c',4)]
>> reduce((lambda x,y: x+y,lambda x,y: x+y),x)
>
> I can't even tell what you're trying to do there.
I think that this is what he wants.
def zipfunc(fun):
def runfun(*args):
return tuple(x(*y) for x,y in zip(fun,zip(*args)))
return runfun

Use this as:
x=[('a',1),('a',1),('a',3),('b',1),('b',2),('c',2),('c',3),('c',4)]
reduce(zipfunc((lambda x,y: x+y,lambda x,y: x+y)),x)
I think he wants the apply the first function in the tuple to the first 
element in every tuple, and likewise the second, third, etc. 


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


Re: Decoupling the version of the file from the name of the module.

2006-01-29 Thread Raymond Hettinger
[EMAIL PROTECTED]
> I'm a newbie experimenting with Python. I want to incrementally develop
> a module called 'circle'.
 . . .
> Basically I want to decouple the version of my file from the name of
> the module.
>
> Is there a *simple* way out of this dilemma.

In the client code, use an import/as statement and update that single
line as needed:

import circle_b as circle

If you don't want to edit the client code every time, the import can be
automated to smartly find the most recently updated version.  Build a
list of filenames using your naming convention.  Sort them by
modification date.  Then, import the most recent one as circle:

   names = glob.glob('circle_*.py')
   names.sort(key=lambda f: os.stat(f).st_mtime)
   newest_name = names[-1]
   newest_module, ext = os.path.splitext(newest_name)
   circle = __import__(newest_module)

Of course, the right answer is to do what everyone else does.  Use a
version control system instead of multiple files.


Raymond

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


Re: Data Crunching and Charting....

2006-01-29 Thread Mr BigSmoke
Great!! I kept looking enthought site everyday for 2/3 months about one
year ago... but it always had old chaco versions, no news... Then i
posted questions about it here at comp.lang.python and some people said
the project had been abbandoned... Great to know that it's not true!!
TNX VERY MUCH!!

Fabio Pliger

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


Re: Python loading library containing embedded python...

2006-01-29 Thread Martin v. Löwis
Brennus wrote:
> I have a dll/so which embeds python. I can verify it works by
> compiling it as an executable and adding an appropriate main.

Please explain in more detail how you did the embedding. Did you
statically link the Python interpreter into your dll/so, or did
you use a shared one?

> How can I make my dll/so with embedded python support use via ctypes?

Whether you can do this at all depends on the fine details of
embedding: e.g. what operating system, how precisely did you do
the embedding, and so on.

For example, on many Unix systems, you might end up with two definitions
of all the Python symbols, at which point it depends on the precise
linker command line options to determine what precisely happens
(e.g. which of the definition of the symbol is used in what place).

> The dll/so must support use in processes which might contain other
> instances of Python. I can not change that requirement. Running via
> ctypes is an easy test of this capability (or much of it I suspect).

Then your best bet is to *really* embed Python. I.e. link all symbols
statically, preferably renaming them (if possible), and make sure that
the resulting dll does neither reference nor expose any Python symbols.
Given the different linkers on different systems, this is very tricky
to implement.

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


Re: newbie: working iwth list of tuples

2006-01-29 Thread Raymond Hettinger
[Raymond Hettinger]
> > Parameterized filter, extract, and reduce functions can be handled in a
> > like manner.
>
> Just for grins, here is a more worked-out example:

See the ASPN Cookbook recipe for a version with doctests and a couple
bug-fixes:

   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473803

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


Re: Using bytecode, not code objects

2006-01-29 Thread Fredrik Lundh
Fabiano Sidler wrote:

> I'm looking for a way to compile python source to bytecode instead of
> code-objects. Is there a possibility to do that? The reason is: I want
> to store pure bytecode with no additional data.

use marshal.

> The second question is, therefore: How can I get the correct values
> for a given bytecode, such as the stacksize and flags attributes of
> the correspondent code object?
>
> No, I don't want to extract all of these things out of a code object.

you don't have to.  marshal can convert a code object to a single byte
string, which contains everything you need.  see the second example on
this page for sample code:

http://www.effbot.org/librarybook/marshal.htm





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


Re: writing large files quickly

2006-01-29 Thread Fredrik Lundh
Bengt Richter wrote:

> >> How the heck does that make a 400 MB file that fast? It literally takes
> >> a second or two while every other solution takes at least 2 - 5 minutes.
> >> Awesome... thanks for the tip!!!
> >
> >Because it isn't really writing the zeros.   You can make these
> >files all day long and not run out of disk space, because this
> >kind of file doesn't take very many blocks.   The blocks that
> >were never written are virtual blocks, inasmuch as read() at
> >that location will cause the filesystem to return a block of NULs.
> >
> I wonder if it will also "write" virtual blocks when it gets real
> zero blocks to write from a user, or even with file system copy utils?

I've seen this behaviour on "big iron" Unix systems, in a benchmark that
repeatedly copied data from a memory mapped section to an output file.

but for the general case, I doubt that adding "is this block all zeros" or
"does this block match something we recently wrote to disk" checks will
speed things up, on average...





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


adding current date to a file name in a python script

2006-01-29 Thread markryde
Hello,

I am trying to add the current date to a file name in python script
like thus:

import os
import sys
import rpm
import time
import datetime

today = datetime.date.today()
print "The date is", today
myFile = '/work/output1'
myFile = myFile.join(today)
myFile = myFile.join(".txt")

print "myFile is",myFile


running the scripts indeed prints the correct date ,
but afterwards there is the following error:


The date is 2006-01-29
Traceback (most recent call last):
  File "addDate.py", line 13, in ?
myFile = myFile.join(today)
TypeError: sequence expected, datetime.date found

How should I do this ? 

Regards,
MR

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


Re: Decoupling the version of the file from the name of the module.

2006-01-29 Thread Steven D'Aprano
On Sun, 29 Jan 2006 00:07:29 -0800, Raymond Hettinger wrote:

> [EMAIL PROTECTED]
>> I'm a newbie experimenting with Python. I want to incrementally develop
>> a module called 'circle'.
>  . . .
>> Basically I want to decouple the version of my file from the name of
>> the module.
>>
>> Is there a *simple* way out of this dilemma.

[snip]

> Of course, the right answer is to do what everyone else does.  Use a
> version control system instead of multiple files.

Which is the right answer to a question, but I'm not convinced it is the
right answer to the implied question.

For serious development, version control systems are the way to go. No
arguments from me, we agree.

But CVS or similar doesn't help you when you are *distributing* your
modules to others. I fear I'm belabouring the obvious, but in case it
isn't obvious what I mean, here is a made-up example:

I distribute two apps, Parrot and Shrubbery. Both rely on a common module,
Spam. Parrot uses version 1 of Spam and Shrubbery uses version 2. For the
sake of the argument, Spam is completely backwards compatible, so I
have no problems with somebody installing Parrot plus Spam version 1, then
installing Shrubbery, where Spam version 2 overwrites the older Spam
module. But if Spam version 1 overwrites version 2, then Shrubbery stops
working.

The easy answer is to say, "Then don't do that", but that's a terribly
impractical answer. Blaming the user is no real solution either. In
old-time Windows land, installation programs would blindly nuke newer DLLs
with older DLLs all the time. Under Linux, one convention is for shared
libraries to include the version number in the file name, so that newer
libraries weren't blown away by older ones.

What is the Python solution? Enquiring minds want to know.



-- 
Steven.

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


Re: adding current date to a file name in a python script

2006-01-29 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
> myFile = '/work/output1'
> myFile = myFile.join(today)
> myFile = myFile.join(".txt")

join does something completely different. You want:

myFile = '/work/output1/%s.txt' % today

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs C for a mail server

2006-01-29 Thread Sybren Stuvel
Dan Lowe enlightened us with:
> I'm on my second major mail system deployment built around Exim, and
> would recommend it to anybody needing a robust, flexible mail
> server.

Same here. I used Sendmail, QMail, Exim 3 and Exim 4, and out of
those, Exim 4 came out winner.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: adding current date to a file name in a python script

2006-01-29 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I am trying to add the current date to a file name in python script
> like thus:
>
> import os
> import sys
> import rpm
> import time
> import datetime
>
> today = datetime.date.today()
> print "The date is", today
> myFile = '/work/output1'
> myFile = myFile.join(today)
> myFile = myFile.join(".txt")
>
> print "myFile is",myFile
>
>
> running the scripts indeed prints the correct date ,
> but afterwards there is the following error:
>
> The date is 2006-01-29
> Traceback (most recent call last):
>   File "addDate.py", line 13, in ?
> myFile = myFile.join(today)
> TypeError: sequence expected, datetime.date found
>
> How should I do this ?

datetime.date.today() returns a date object, not a string.

if the default string conversion is what you want, use str(today) to
convert to a string.

also note that "join" doesn't do what you think it does; "x.join(y)"
joins all members of the sequence y (which must all be strings) using
x as the separator.  this gives you a filename like

'.2/work/output10/work/output10/work/output16/work/output1-/work/output10/work/o
utput11/work/output1-/work/output12/work/output19t2/work/output10/work/output10/
work/output16/work/output1-/work/output10/work/output11/work/output1-/work/outpu
t12/work/output19x2/work/output10/work/output10/work/output16/work/output1-/work
/output10/work/output11/work/output1-/work/output12/work/output19t'

which is probably not what you want.

to fix this, you can use +=

myFile = '/work/output1'
myFile += str(today)
myFile += ".txt"

or % formatting:

myFile = '/work/output1%s.txt' % today

(here, "%s" does the str() call for you).





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


Re: generating method names 'dynamically'

2006-01-29 Thread Max
Magnus Lycka wrote:
> Daniel Nogradi wrote:
> 
>> Well, I would normally do what you suggest, using parameters, but in
>> the example at hand I have to have the method names as variables and
>> the reason is that the whole thing will be run by apache using
>> mod_python and the publisher handler. There a URL
>> http://something.com/program2/Bob is mapped to the 'Bob' method of the
>> file program2.py and I want to be able to have URL's with different
>> names. I know I can solve this problem with parameters and functions
>> and using the GET http method, but I would like to have pretty URL's
>> without & and ? signs. I didn't want to ask this on the mod_python
>> list because after all it's a pure python question.
> 
> 
> Ouch! This certainly seems like a possible security hole!
> 
I wouldn't think so, as long as Klass doesn't have /other/ methods - as 
long as it only has methods that are meant to be viewed externally. 
Which would probably not be the way one would ordinarily write the 
class, but if one knew one had to, one should be fine.

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


Re: generating method names 'dynamically'

2006-01-29 Thread Fredrik Lundh
"Unknown" wrote:

> >> Well, I would normally do what you suggest, using parameters, but in
> >> the example at hand I have to have the method names as variables and
> >> the reason is that the whole thing will be run by apache using
> >> mod_python and the publisher handler. There a URL
> >> http://something.com/program2/Bob is mapped to the 'Bob' method of the
> >> file program2.py and I want to be able to have URL's with different
> >> names. I know I can solve this problem with parameters and functions
> >> and using the GET http method, but I would like to have pretty URL's
> >> without & and ? signs. I didn't want to ask this on the mod_python
> >> list because after all it's a pure python question.
> >
> > Ouch! This certainly seems like a possible security hole!
>
> I wouldn't think so, as long as Klass doesn't have /other/ methods - as
> long as it only has methods that are meant to be viewed externally.
> Which would probably not be the way one would ordinarily write the
> class, but if one knew one had to, one should be fine.

the security issue isn't "making arbitrary methods available from an
instance", the security issue is "using getattr to map URL fragments
to attribute accesses or method calls".

anyone doing this should study this security advisory (and the module
it talks about) carefully:

http://www.python.org/security/PSF-2005-001/





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


Re: Builder Pattern

2006-01-29 Thread Paddy
> What the following discussion says is that the C++ -> Python
> transliteration is totally trivial and obvious and berates the original
> requestor for making me waste 10 minutes to provide it.

Thanks for the giggle :-)

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


Re: SLUT distibution mangled?

2006-01-29 Thread Ido Yehieli
ok, Thanks Paul!

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


Re: SLUT distibution mangled?

2006-01-29 Thread Rob Wolfe
Actually when you remember the ancient history of Windows and MS/DOS
you will see why. That filename, and a lot of others (as noted by
Fredrik) are legacies of that time. They were special filenames (think
"/dev/null") that related to specific devices.

Gives us a good example of one of the little "gotchas" involved in
cross platform development.

Rob

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


Re: writing large files quickly

2006-01-29 Thread Thomas Bellman
Grant Edwards <[EMAIL PROTECTED]> writes:

> $ dd if=/dev/zero of=zeros bs=64k count=1024
> 1024+0 records in
> 1024+0 records out
> $ ls -l zeros
> -rw-r--r--  1 grante users 67108864 Jan 28 14:49 zeros
> $ du -h zeros
> 65M zeros

> In my book that's 64MB not 65MB, but that's an argument for
> another day.

You should be aware that the size that 'du' and 'ls -s' reports,
include any indirect blocks needed to keep track of the data
blocks of the file.  Thus, you get the amount of space that the
file actually uses in the file system, and would become free if
you removed it.  That's why it is larger than 64 Mbyte.  And 'du'
(at least GNU du) rounds upwards when you use -h.

Try for instance:

$ dd if=/dev/zero of=zeros bs=4k count=16367
16367+0 records in
16367+0 records out
$ ls -ls zeros
65536 -rw-rw-r--  1 bellman bellman 67039232 Jan 29 13:57 zeros
$ du -h zeros
64M zeros

$ dd if=/dev/zero of=zeros bs=4k count=16368
16368+0 records in
16368+0 records out
$ ls -ls zeros
65540 -rw-rw-r--  1 bellman bellman 67043328 Jan 29 13:58 zeros
$ du -h zeros
65M zeros

(You can infer from the above that my file system has a block
size of 4 Kbyte.)


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"There are many causes worth dying for, but  !  bellman @ lysator.liu.se
 none worth killing for." -- Gandhi  !  Make Love -- Nicht Wahr!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: newbie: working iwth list of tuples

2006-01-29 Thread Kent Johnson
falcon wrote:
> Hi All,
> I am fairly new to Python (less than a week).  My goal is to write a
> small prototype of a database.  Rather than build it using the typical
> method where one provides selection, projection, aggregation, union,
> intersection, etc. functions, I would like to do it in a more
> 'functional' style (executing a database query by using map, reduce,
> filter, etc.  

You might be interested in a similar attempt:
http://www.jtauber.com/relational_python

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


Re: "Dynamic" website content

2006-01-29 Thread sophie_newbie
To be honest that doesn't seem to work. Also it seems that only Mozilla
based browsers support server push.

Maybe it is something to do with how Apache is configured?

Or is Python buffering the output? Is there a line of code to make
python unbeffered?

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


Re: "Dynamic" website content

2006-01-29 Thread sophie_newbie
I am running apache on windows by the way. I think there may be issues
with unbuffered output on windows...

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


Tk.quit() now working!

2006-01-29 Thread al pacino
i have a weired problem with button widget in Tkinter
the callback function(Tk.quit()) for button widget is not working! when
i 'press' the button
the GUI hangs.
 code for displaying a 'button objec':
###
import Tkinter
top=Tkinter.Tk()
button=Tkinter.Button(top,text='press me',command=top.quit)#callback to
end the appllication
button.pack()
Tkinter.mainloop()
###
any comments?

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


Re: Python vs C for a mail server

2006-01-29 Thread Jens Theisen
Nicolas wrote:

> http://nicolas.lehuen.com/

> My two latest problems with coding in C++ are due to the environments :
> libraries using different string types and the whole problem with the
> building system. I love the language, but I get a much better leverage
> through Python and Java due to the quality and ease of use of their
> built-in and third party libraries. I use C++ only for my core data
> structure (namely a tuned version of a ternary search tree which I use
> to build full text indices).

Those points are all valid. I'm using Python for that reason. And there is  
another point that there are good Python bindings for the the more  
important C libraries, but usually no decent C++ wrapper for it.

Jens

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


Re: Python vs C for a mail server

2006-01-29 Thread Jens Theisen
Alex wrote:

> 
> 

> Since Robert Martin and Bruce Eckel (the authors of the two documents
> linked above) are both acknowledged gurus of statically typechecked
> languages such as C++, the convergence of their thinking and experience
> indicated by those documents is interesting.

Indeed, especially Eckels article shed some light about testing as an  
alternative to static typing. I still can't quite understand why you can't  
do both. Clearly unit tests should be part of any software, not only  
Python software.

Test failures, however, don't tell you anything about the current usage of  
your program - just about the inteded usage at the point where the test  
was writte. Clearly you can't test _anything_? And clearly you can never  
be sure that all you collegues did so as well? This not only about type  
safety, but simply name safety.

What do you do when you want to no if a certain method or function is  
actually used from somewhere, say "foobar", it a language which allows  
(and even encourages) that it could be called by:

getattr(obj, "foo" + "bar")()

?

There is no systematic way to find this call.

In C++, just commend out the definition and the compiler will tell you.

I'm pretty sure I red a PEP about static type safety in Python at some  
point. It was even thinking about generics I think.

> The "but without declaration it can't be self-documenting" issue is a
> red herring.  Reading, e.g.:

> int zappolop(int frep) { ...

> gives me no _useful_ "self-documenting" information

That's true. If the programmer wants to obfuscate his intention, I'm sure  
neither Python nor C++ can stop him. The question is how much more work is  
to write comprehensible code in one language or the other. I'm a bit  
afraid about Python on that matter.

Python provides ways to easy literal documentation. But I'd really like to  
have a way of indicating what I'm talking about in a way that's ensured to  
be in-sync with the code. Tests are not where the code is. I have  
difficulties remembering the type of a lot of symbols, and looking at  
testing code to fresh up usage is more difficult that just jumping to the  
definition (which the development envirnment is likely to be able to).

> [smart pointers and GC]

As you say, smart pointers are not full-blown garbage collection, which is  
usually what you want, isn't it? I my (admittedly short) life as a  
professional developer I have not yet come accross a situation where  
reference counting was not sufficient to model the memory management.

As for the locking: Apart from locking your whatever you need to lock in  
your user code, I don't think any special locking is necessary for the  
memory management. Smart pointer can increment and decrement their ref  
counts atomically as far as I know.

We use boost::shared_ptr in multi-threaded code just out of the box. We  
also use a reference counted string implementation in multi threaded code.

> At Google, we collectively have rather a lot of experience in these
> issues, since we use three general-purpose languages: Python, Java, C++.

I have no doubt that goolge know what they're doing, and if you're working  
there then you're likely to know what you're talking about.

I found it especially astonishing what you had to say against the use of  
smart pointers.

Jens

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


Re: Fast generation of permutations

2006-01-29 Thread Anton Vredegoor
Paul Rubin wrote:

> Cool, I'd still like to know why (13**5)-13 = C(52,5) other than
> by just doing the arithmetic and comparing the results.  Maybe your
> tkinter script can show that.

That seems to be very hard :-) Unless I'm missing something.

Anton

def noverk(n,k):
return reduce(lambda a,b: a*(n-b)/(b+1),range(k),1)

print noverk(52,5)
print 13**5-13

#prints:

2598960
371280

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


Re: Tk.quit() now working!

2006-01-29 Thread Fredrik Lundh
"al pacino" wrote:

> i have a weired problem with button widget in Tkinter
> the callback function(Tk.quit()) for button widget is not working! when
> i 'press' the button
> the GUI hangs.
>  code for displaying a 'button objec':
> ###
> import Tkinter
> top=Tkinter.Tk()
> button=Tkinter.Button(top,text='press me',command=top.quit)#callback to
> end the appllication
> button.pack()
> Tkinter.mainloop()
> ###
> any comments?

how do you run your Tkinter program ?





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


Re: Fast generation of permutations

2006-01-29 Thread Anton Vredegoor
Anton Vredegoor wrote:

> Paul Rubin wrote:
>
> > Cool, I'd still like to know why (13**5)-13 = C(52,5) other than
> > by just doing the arithmetic and comparing the results.  Maybe your
> > tkinter script can show that.
>
> That seems to be very hard :-) Unless I'm missing something.

Like a factor seven, you mentioned that a few posts back. Sorry about
that.

Anton

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


Re: Printing HTML

2006-01-29 Thread Steve Holden
Unknown wrote:
> Rene Pijlman wrote:
> 
>>Max <[EMAIL PROTECTED]>:
>>
>>
>>>How can I print (as in laser printer, not the python print statement) 
>>>HTML from Python 
>>
>>
>>Is the printer attached to your server, or are you printing over the
>>internet?
>>
> 
> 
> I'm not sure if the printer is attached to the workstation (probably) or 
> over the network, but it'll definitely be installed as one of the 
> windows printers. (I guess I should have mentioned the fact that I'm 
> working for windows - but I did say I was using MS Access and pywin32).
> 
wxPython has a printing framework that works more than adequately under 
Windows. If you have the wxPython demos installed (nowadays they are a 
separate download) look under "Miscellaneous/PrintFramework" to find 
working code.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: "Intro to Pyparsing" Article at ONLamp

2006-01-29 Thread Anton Vredegoor
Paul McGuire wrote:

> There are two types of parsers: design-driven and data-driven.  With
> design-driven parsing, you start with a BNF that defines your language or
> data format, and then construct the corresponding grammar parser.  As the
> design evolves and expands (new features, keywords, additional options), the
> parser has to be adjusted to keep up.
>
> With data-driven parsing, you are starting with data to be parsed, and you
> have to discern the patterns that structure this data.  Data-driven parsing
> usually shows this exact phenomenon that you describe, that new structures
> that were not seen or recognized before arrive in new data files, and the
> parser breaks.  There are a number of steps you can take to make your parser
> less fragile in the face of uncertain data inputs:
> - using results names to access parsed tokens, instead of relying on simple
> position within an array of tokens
> - anticipating features that are not shown in the input data, but that are
> known to be supported (for example, the grammar expressions returned by
> pyparsing's makeHTMLTags method support arbitrary HTML attributes - this
> creates a more robust parser than simply coding a parser or regexp to match
> "' > For example, I had this
> > experience when parsing chess games from videotext pages I grab from my
> > videotext enabled TV capture card. Maybe once or twice in a year
> > there's a chess page with games on videotext, but videotext chess
> > display format always changes slightly in the meantime so I have to
> > adapt my script. For such things I've switched back to 'hand' coding
> > because it seems to be more flexible.
> >
>
> Do these chess games display in PGN format (for instance, "15. Bg5 Rf8 16.
> a3 Bd5 17. Re1+ Nde5")? The examples directory that comes with pyparsing
> includes a PGN parser (submitted by Alberto Santini).

Ah, now I remember, I think this was what got me started on pyparsing
some time ago. The dutch videotext pages are online too (and there's a
game today):

http://teletekst.nos.nl/tekst/683-01.html

But as I said there can be transmission errors and human errors. And
the dutch notation is used, for example a L is a B, a P is a K, D is Q,
T is R. I'd be interested in a parser that could make inferences about
chess games and use it to correct these pages!

> > What I would like to see, in order to improve on this situation is a
> > graphical (tkinter) editor-highlighter in which it would be possible to
> > select blocks of text from an (example) page and 'name' this block of
> > text and select a grammar which it complies with, in order to assign a
> > role to it later. That would be the perfect companion to pyparsing.
> >
> > At the moment I don't even know if such a thing would be feasible...
>
> There are some commercial parser generator products that work exactly this
> way, so I'm sure it's feasible.  Yes, this would be a huge enabler for
> creating grammars.

And pave the way for a natural language parser. Maybe there's even some
(sketchy) path now to link computer languages and natural languages. In
my mind Python has always been closer to human languages than other
programming languages. From what I learned about it, language
recognition is the easy part, language production is what is hard. But
even the easy part has a long way to go, and since we're also using a
*visual* interface for something that in the end originates from sound
sequences (even what I type here is essentially a representation of a
verbal report) we have ultimately a difficult switch back to auditory
parsing ahead of us.

But in the meantime the tools produced (even if only for text parsing)
are already useful and entertaining. Keep up the good work.

Anton.

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


Re: equivalent to c++ "reference" or "pointers"

2006-01-29 Thread Steve Holden
Collin Jones wrote:
> Hello,
> 
> Is there a Python equivalent to creating "reference" or "pointer"-type 
> variables as in C++??  I'm trying to create a couple classes that have 
> something like a container-and-iterator relationship; one class acts as 
> a data resource (container-like) and can be queried by multiple control 
> classes if needed (iterator-like).
> 
> If it's of any use, one class will contain all the frames of an 
> animation and its attributes, and the other will query the former for 
> image data and those attributes but control the actual animation process 
> on its own.
> 
> Here is a simple (albeit crappily written) example, in C++, of what I'm 
> trying to achieve.  Perhaps in Python I should be using a different 
> paradigm than this... that would be fine, as long as I can figure out 
> something that will serve my purpose.
> 
> #include 
> using namespace std;
> 
> class CrazyRes {
> private:
> char *astring, *bstring;
> public:
> void setAString(char *s);
> void setBString(char *s);
> char *getAString() { return astring; }
> char *getBString() { return bstring; }
> };
> void CrazyRes::setAString(char *s)
> {
> astring = new char[255];
> strcpy(astring, s);
> }
> void CrazyRes::setBString(char *s)
> {
> bstring = new char[255];
> strcpy(bstring, s);
> }
> 
> class CrazyCtrl {
> private:
> CrazyRes *res;
> public:
> void attach(CrazyRes *r) { res = r; }
> void printAString() { cout << res->getAString(); }
> void printBString() { cout << res->getBString(); }
> };
> 
> int main()
> {
> CrazyRes res;
> CrazyCtrl ctrl;
> 
> res.setAString("Hey! A-String!\n");
> res.setBString("Whoa! B-String!\n");
> 
> ctrl.attach(&res);
> ctrl.printAString();
> ctrl.printBString();
> 
> return 0;
> }
> 
> I tried to keep this to the point... thanks in advance for any suggestions.
> 
Basically names are bound to values by reference in Python - a name, or 
an item in a "container" such as a list or a dictionary, is simply a 
reference to a value. Assignment binds a new item or name to an existing 
value.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Python vs C for a mail server

2006-01-29 Thread Jay Parlar
> Indeed, especially Eckels article shed some light about testing as an
> alternative to static typing. I still can't quite understand why you 
> can't
> do both. Clearly unit tests should be part of any software, not only
> Python software.
>
You can do both, but why? *Especially* in a language like C++, where 
thanks to pointers and casting, there really isn't any type safety 
anyway. How much time in your C/C++ code is spent casting and trying to 
trick the compiler into doing something that it thinks you shouldn't be 
doing?

> Test failures, however, don't tell you anything about the current 
> usage of
> your program - just about the inteded usage at the point where the test
> was writte. Clearly you can't test _anything_? And clearly you can 
> never
> be sure that all you collegues did so as well? This not only about type
> safety, but simply name safety.
>
How does type safety tell you anything about the current usage of your 
program? All static types can tell you is what the input/output types 
should be, and in no way show any semantic relationship between actual 
output and the input. Tests can do that.

And unit tests *might* not tell about the current usage, but 
integration tests certainly do.

> What do you do when you want to no if a certain method or function is
> actually used from somewhere, say "foobar", it a language which allows
> (and even encourages) that it could be called by:
>
> getattr(obj, "foo" + "bar")()
>
> ?
>
> There is no systematic way to find this call.
>
> In C++, just commend out the definition and the compiler will tell you.
>

I don't think I've ever seen anyone advocating calling a function like 
getattr(obj "foo" + "bar")(). You can do some very powerful things with 
getattr, thanks to Python's dynamic nature, but I don't think anyone is 
recommending calling a function like that.


> That's true. If the programmer wants to obfuscate his intention, I'm 
> sure
> neither Python nor C++ can stop him. The question is how much more 
> work is
> to write comprehensible code in one language or the other. I'm a bit
> afraid about Python on that matter.
>
And is that fear based simply on "feeling", or on actual experience. 
Because in all of my own industry experience, it's been MUCH easier to 
jump into someone else's Python code than someone else's C++ code (and 
at my last job, I had to do a lot of both). I find Python to be much 
more self-documenting, because there's not so much scaffolding all over 
the place obfuscating the true intention of the code.


> Python provides ways to easy literal documentation. But I'd really 
> like to
> have a way of indicating what I'm talking about in a way that's 
> ensured to
> be in-sync with the code. Tests are not where the code is. I have
> difficulties remembering the type of a lot of symbols, and looking at
> testing code to fresh up usage is more difficult that just jumping to 
> the
> definition (which the development envirnment is likely to be able to).
>

You need to look at doctest: 
http://docs.python.org/lib/module-doctest.html
With doctest, tests are EXACTLY where the code is. I've used doctest 
with incredibly successful results, in industry.



>> [smart pointers and GC]
>
> As you say, smart pointers are not full-blown garbage collection, 
> which is
> usually what you want, isn't it? I my (admittedly short) life as a
> professional developer I have not yet come accross a situation where
> reference counting was not sufficient to model the memory management.
>
Reference counting by itself is not necessarily sufficient (because of 
circular references). That's why even Python, with its reference 
counting based system, has additional capabilities for finding circular 
references.

>> At Google, we collectively have rather a lot of experience in these
>> issues, since we use three general-purpose languages: Python, Java, 
>> C++.
>
> I have no doubt that goolge know what they're doing, and if you're 
> working
> there then you're likely to know what you're talking about.
>

I believe that Alex's official job title at Google is "Uber Technical 
Lead". I'm sure I'll quickly be corrected if that's wrong, but trust me 
(and everyone else who's spent significant time reading c.l.p.) that 
Alex Martelli knows what he's talking about.

A lot of your arguments are the very typical arguments that people levy 
against Python, when they're first around it. And that's fine, most 
people go through that. They are taught programming in C++ or Java, and 
that that *that* is the way you're supposed to program. Then they see 
that Python does things in different ways, and automatically assume 
that Python is doing it wrong.

All I can say is that if you spend time with Python (and more 
importantly, read quality, well-established Python code that's already 
out there), you'll see and understand the Python way of doing things.


Jay P.

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


Re: Python vs C for a mail server

2006-01-29 Thread Peter Hansen
Jens Theisen wrote:
> Test failures, however, don't tell you anything about the current usage of  
> your program - just about the inteded usage at the point where the test  
> was writte. Clearly you can't test _anything_? And clearly you can never  
> be sure that all you collegues did so as well? This not only about type  
> safety, but simply name safety.
> 
> What do you do when you want to no if a certain method or function is  
> actually used from somewhere, say "foobar", it a language which allows  
> (and even encourages) that it could be called by:
> 
> getattr(obj, "foo" + "bar")()
> ?
> 
> There is no systematic way to find this call.

While this isn't really a "test", as you are really asking about 
something to do with managing your code base, it is quite possible to 
write a test which *does* check whether foobar() is called, and even to 
pinpoint all places from which it is called, if that's really what you 
want to do.  Believing you can't do that suggests you have no real 
experience with writing tests for code, so it might be best not to argue 
so strenuously against them.

-Peter

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


Tkinter PhotoImage won't show ;-(

2006-01-29 Thread vm
please help!

I can't find anything wrong (except the result ofc ;-)

This:



picfile = 'logo.gif'

pic = tk.PhotoImage(file=picfile, master=root)

canpic = cv.create_image(320, 240, image=pic) #cv is is a Tkinter 
Canvas ofc



...works just fine, but when I put it in the event binding function, it 
doesn't work,

it doesn't report any errors too, I'm sure the function went all the way 
through

because I print the test-text at the end of the function... But it doesn't 
show picture!



here's the entire program I wrote to test this out:

===

import Tkinter as tk, os



root = tk.Tk()

root.title = 'Picviewer'



###setting Listbox, Canvas

lb = tk.Listbox(root,width =20, height=22)

lb.grid(column=0, row=0, columnspan = 2)



cv = tk.Canvas(root, width=640, height=480, bg='white')

cv.grid(column=2,row=0, rowspan=2)



###listing all .gifs in current working directory into the Listbox lb

cwd = os.getcwd()

filelista = os.listdir(cwd)

filelista.sort()

for element in filelista:

  if os.path.isfile(element) and '.gif' in element.lower(): lb.insert( 
lb.size() ,element)



###Load-button bind function (showing picture) - the problem seems to be in 
here somewhere I think

def putpic(event):

  picfile = lb.selection_get()

  pic = tk.PhotoImage(file=picfile, master=root)

  canpic = cv.create_image(320, 240, image=pic)

  ###just to see what's going on

  print str(picfile), "\n", str(pic), '\n', str(canpic)



###setting Load-button

load = tk.Button(root, text='Load', width=16)

load.bind('', putpic)

load.grid(column=0, row=2, columnspan=2)



###Putting the logo image at start (more like test image at start - and it 
works)

pic = tk.PhotoImage(file='logo.gif', master=root)

canpic = cv.create_image(320, 240, image=pic)



root.mainloop()



Maybe I just need a fresh pair of eyes, SOMEONE!




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


Re: Python vs C for a mail server

2006-01-29 Thread Alex Martelli
Jens Theisen <[EMAIL PROTECTED]> wrote:
   ...
> Indeed, especially Eckels article shed some light about testing as an
> alternative to static typing. I still can't quite understand why you can't
> do both. Clearly unit tests should be part of any software, not only
> Python software.

Clearly.  Given this, adding static typing as well still has all the
costs in terms of productivity, but much diminished benefits.  So it's
not a question of "can't", but of "not worth the cost".

> Test failures, however, don't tell you anything about the current usage of
> your program - just about the inteded usage at the point where the test
> was writte. Clearly you can't test _anything_? And clearly you can never
> be sure that all you collegues did so as well? This not only about type
> safety, but simply name safety.

So you are now arguing against any kind of introspection abilities?  Do
dlopen and dlsym sap the power you attribute to C++, then?

> What do you do when you want to no if a certain method or function is
> actually used from somewhere, say "foobar", it a language which allows
> (and even encourages) that it could be called by:
> 
> getattr(obj, "foo" + "bar")()
> 
> ?

"Encourages"?  What a silly assertion.  Python makes introspection
easier than Java's Reflection, C#'s similar capabilities, and C/C++'s
primitive dlopen/dlsym, but the existence of similar dynamic name
resolution abilities in each of these languages reflects similar
underlying real needs.  The functionality is there for those cases in
which it's needed, but it's silly to use it when not needed.


> There is no systematic way to find this call.
> 
> In C++, just commend out the definition and the compiler will tell you.

You're too optimistic re C++: given its complex rules, the compiler
might well find a different 'foobar' once you comment out that one.

But more: if that function is called via dlopen and dlsym, or similar
functionalities on Windows etc, what can the compiler tell you?  It will
tell you nothing, and if you take that as meaning the function is not
called, you're in for a surprise.

So, in C++ like in any of the other languages offering handier
introspection facilities, Python included, you need integration tests
(harder than unit tests) or heuristics based on source analysis (which
won't catch the cases in which the namestrings are constructed
dynamically).

If you're arguing against introspection and dynamic libraries, then
you're not arguing against Python per se, but rather against the whole
grain of modern component-oriented development; since C++, as much as
Java, Python and C#, is most often used for such kind of development,
you should take the debate to a more general forum.


> I'm pretty sure I red a PEP about static type safety in Python at some
> point. It was even thinking about generics I think.

You're probably thinking of Guido's musings in his blog, never actually
formalized to the point of being a PEP.  Of course, he soon realized
that there was nothing "static" about the typechecking functionality he
was (and is) thinking of introducing in Python 3000 -- it's entirely
dynamic, just like a Java cast or a C++ dynamic_cast.  Just like
decorators are just syntax sugar over existing higher-order-function
possibilities, so the typing checks will be syntax sugar over either
existing or propoposed (my PEP246) dynamic adaptation ones.

E.g., you may (in a few years when Python3000 comes) write:

def f(x: Foo): ...

just like you may write (in fewer years if and when PEP246 is accepted):

def f(x):
   x = adapt(x, Foo)
   ...

or perhaps (if PEP246 is rejected) the semantics will be

def f(x):
   assert isinstance(x, Foo)
   ...

Syntax sugar matters: people will be vastly more likely to use
adaptation or typechecking if a nice syntax is provided, just like they
now use HOFs more freely thanks to decorator syntax.  But it does not in
any way change the abilities of the language, there's nothing static
about it, and it doesn't really address any of the criticisms such as
yours -- although it may reduce the volume of complaints if it takes
good understanding of the language to realize the functionality is
indeed dynamic, but that's just like saying that Java's goofy:

  zap = (Zapper) gup;

is better than C++'s more explicit:

  zap = dynamic_cast(gup);

because the latter immediately ADMITS it's dynamic, while the former
LOOKS (confusingly;-) more static (even though its semantics isn't).

I prefer truth in advertising: call dynamic what's dynamic, let the
critics criticize (just like they criticize dynamic_cast), and ignore
them (except when you're looking for excuses not to work, just like I'm
doing now since I should be slaving over the 2nd edition of my Nutshell
book;-).


> > The "but without declaration it can't be self-documenting" issue is a
> > red herring.  Reading, e.g.:
> 
> > int zappolop(int frep) { ...
> 
> > gives me no _useful_ "self-documenting" information
> 
> That's true. If the programmer wan

Re: Tkinter PhotoImage won't show ;-(

2006-01-29 Thread Fredrik Lundh
"vm" wrote:

> I can't find anything wrong (except the result ofc ;-)
>
> This:
>
> picfile = 'logo.gif'
>
> pic = tk.PhotoImage(file=picfile, master=root)
>
> canpic = cv.create_image(320, 240, image=pic) #cv is is a Tkinter
> Canvas ofc
>
> ...works just fine, but when I put it in the event binding function, it
> doesn't work,

this is explained in the python faq, and towards the end of this
page:

http://effbot.org/tkinterbook/photoimage.htm





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


Server side newbie

2006-01-29 Thread swisscheese
I have a simple python desktop app with several edit controls and a
couple of buttons. It just does some math. What's the simplest way to
make it a server-side app so visitors to my site can run the app via
their browser?

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


stumped by tricky logic

2006-01-29 Thread Dave
So I'm trying to write a CSS preprocessor.

I want to add the ability to append a selector onto other selectors.
So, given the following code:
=
#selector {

  { property: value; property: value; }
.other_selector   { property: value; property: value; }

#selector_2 {

 .more_selector { property: value; }

}

}
=

I want to return the following:
=
#selector { property: value; property: value; }
#selector .other_selector { property: value; property: value; }
#selector #selector_2 .more_selector { property: value; }
=

What I think I need to do is match the "{" character with its "}" pair,
then see if there's another "{" before a matching "}" - but that's
about as far as my brain will go. The actually code to make this
actually happen is not coming out when I type.

Any suggestions would be very appreciated. And handsomely rewarded (by
karma, not me).

- Dave

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


Re: Server side newbie

2006-01-29 Thread Dave
Check out mod_python for Apache. Basically, you would write your python
app as a server-side script and the end user would interact with your
code via a webpage. It's likely that you won't need any GUI code you
wrote, as HTML form elements will be your choices in the browser.

Check out PSP: it enables you to mix Python code with an otherwise
ordinary HTML page.

Mod_Python:
http://www.modpython.org/

PSP article:
http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html

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


Re: Server side newbie

2006-01-29 Thread Peter Hansen
swisscheese wrote:
> I have a simple python desktop app with several edit controls and a
> couple of buttons. It just does some math. What's the simplest way to
> make it a server-side app so visitors to my site can run the app via
> their browser?

There will probably be a dozen answers, any of which might meet whatever 
subjective way you have of judging "simplicity", but here's one:

1. strip the GUI code off
2. wrap the remaining core with a simple CGI interface
2. make a web form in HTML that calls it

-Peter

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


OT: Re: Using non-ascii symbols

2006-01-29 Thread Magnus Lycka
Runsun Pan wrote:
> The simplified chinese exists due to the call for modernization of
> language decades ago. That involved the 'upside-down' of almost
> entire culture 
This is in some ways quite the opposite compared to Nynorsk
in Norway, which was an attempt to revive the old and pure
Norwegian, after being dominated (in politics as well as in
grammar) by Denmark from 1387-1814. (I guess it was a
complicating factor that the end of the union with Denmark
led to a union with Sweden. The Norwegians probably had some
difficulties deciding what neighbour they disliked most. When
they broke out of the union with Sweden in 1905, they actually
elected a Danish prince to be their king.) Anyway, only a
fraction of the Norwegians use Nynorsk today, and the majority
still speak the Danish-based bokmål. On the other hand, the
spelling of bokmål has also been modernized a lot, with a
series of spelling reforms of both languages.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decoupling the version of the file from the name of the module.

2006-01-29 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> Now suppose I have make a new version with __version__ = 1.1. What
> shall I call this file and (I don't want to overwrite the old file if I
> need to go back to it) how do I import it from the shell. Your advice
> sounds nice, but I would appreciate if you could give me (or point me
> to) a simple example.
> 
> Thanks
> 

As Kirk, Roy and Peter suggested (nay, commanded), use a versioning 
system, either CVS or Subversion for example (both are quite simple, 
Subversion has a 1 click installer for Windows boxes, and there is a 
small book/user manual with it so that you're not lost), they'll do what 
you need (keep the old versions around "just in case") and much more to 
boot. Spending a day or two learning about how the versioning system 
you'll have chosen work is an investment that you'll get back tenfold in 
no time, so don't get intimidated or scared.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs C for a mail server

2006-01-29 Thread Alex Martelli
Jay Parlar <[EMAIL PROTECTED]> wrote:
   ...
> Because in all of my own industry experience, it's been MUCH easier to
> jump into someone else's Python code than someone else's C++ code (and
> at my last job, I had to do a lot of both). I find Python to be much 
> more self-documenting, because there's not so much scaffolding all over
> the place obfuscating the true intention of the code.

In the average, you're right.  However, if you can rely on ALL the code
in question being brilliantly well designed, written by programmers of
unbelievably high quality, in full and strict adherence to rigorous
coding-style guides (which absolutely forbid the use of LARGE slices of
each language) and a reasonably thorough process (mandatory code reviews
before anything is committed, mandatory testing, the works), the issue
is substantially ameliorated.  It does remain true that the amount of
Python code needed to implement any given functionality X is smaller
than the amount of C++ code needed for the same purpose, of course; the
amount of effort to understand a codebase of uniformly high quality
being roughly proportional to the size of that codebase, Python will
still be advantageous.  But by, oh, some small factor (maybe a factor of
2? surely not as high as 5), NOT orders of magnitude.

If the design, the programmers, the coding-style, and-or the process are
of lesser quality, then you're in trouble either way, and I will concede
that the situation degrades faster for C++ -- not only does it offer
people more ways to get themselves into trouble, but unless you can
count on uniformly high quality the effort is not just linearly
proportional to the size of the codebase, it grows much faster than
that, so the "lack of scaffolding" and other factors making Python more
expressive do matter more.

Still, if I was back to working as a freelance consultant and got hired
to fix a problem situation, I wouldn't _start_ by recommending a switch
from Java or C++ to Python as the highest-urgency issue: I would first
focus on people (both as individual and teams), process, design, and
tack language (including style) and other technological issues
(including choice of tools, frameworks, libraries, etc) as being, while
undoubtedly important, of slightly lesser urgency.  Don't get me wrong:
using the most appropriate technologies does make a big difference; but
it's too easy a temptation to focus on technological "silver bullets"
and assume they can "just fix things" if ``softer'' but at least as
crucial problems are left to keep festering in the background.


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


Re: Strange behavior of int()

2006-01-29 Thread Rob E
> Why is int(r/k), where r = 0.5 and k = 0.5 = 0?  Shouldn't it be 1?
> And why is the last one = 4 and not 5?

I dont' know why the differences in your exact case.  However, please
realise that Regardless of the programming language good programming 
practice is to never rely on the int of a floating point division 
-- or even the int of a floating point constant to be exactly 
the integer value you expect it to be.  This is because both 
constant representations and math operations have rounding 
error.  Instead do less precise conversions by rounding.  For 
example:

a=b/c
if (a >= 0.0):
   d = int(a+0.5)
else:
   d = int(a-0.5)

If you don't do this sort of thing your programs generally 
are  senstivie to the details of foating point rounding -- 
which is generally dependent on processor, compilier and
in pythons case probably the runtime system.

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


Re: Tkinter PhotoImage won't show ***SOLVED***

2006-01-29 Thread vm
I was missing "global pic" line at the begining of
putpic function. doh!


"vm" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> please help!
>
> I can't find anything wrong (except the result ofc ;-)
>
> This:
>
>
>
> picfile = 'logo.gif'
>
> pic = tk.PhotoImage(file=picfile, master=root)
>
> canpic = cv.create_image(320, 240, image=pic) #cv is is a Tkinter 
> Canvas ofc
>
>
>
> ...works just fine, but when I put it in the event binding function, it 
> doesn't work,
>
> it doesn't report any errors too, I'm sure the function went all the way 
> through
>
> because I print the test-text at the end of the function... But it doesn't 
> show picture!
>
>
>
> here's the entire program I wrote to test this out:
>
> ===
>
> import Tkinter as tk, os
>
>
>
> root = tk.Tk()
>
> root.title = 'Picviewer'
>
>
>
> ###setting Listbox, Canvas
>
> lb = tk.Listbox(root,width =20, height=22)
>
> lb.grid(column=0, row=0, columnspan = 2)
>
>
>
> cv = tk.Canvas(root, width=640, height=480, bg='white')
>
> cv.grid(column=2,row=0, rowspan=2)
>
>
>
> ###listing all .gifs in current working directory into the Listbox lb
>
> cwd = os.getcwd()
>
> filelista = os.listdir(cwd)
>
> filelista.sort()
>
> for element in filelista:
>
>  if os.path.isfile(element) and '.gif' in element.lower(): 
> lb.insert( lb.size() ,element)
>
>
>
> ###Load-button bind function (showing picture) - the problem seems to be 
> in here somewhere I think
>
> def putpic(event):
>
>  picfile = lb.selection_get()
>
>  pic = tk.PhotoImage(file=picfile, master=root)
>
>  canpic = cv.create_image(320, 240, image=pic)
>
>  ###just to see what's going on
>
>  print str(picfile), "\n", str(pic), '\n', str(canpic)
>
>
>
> ###setting Load-button
>
> load = tk.Button(root, text='Load', width=16)
>
> load.bind('', putpic)
>
> load.grid(column=0, row=2, columnspan=2)
>
>
>
> ###Putting the logo image at start (more like test image at start - and it 
> works)
>
> pic = tk.PhotoImage(file='logo.gif', master=root)
>
> canpic = cv.create_image(320, 240, image=pic)
>
>
>
> root.mainloop()
>
> 
>
> Maybe I just need a fresh pair of eyes, SOMEONE!
>
>
>
> 


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


Re: Decoupling the version of the file from the name of the module.

2006-01-29 Thread Robert Kern
Steven D'Aprano wrote:

> I distribute two apps, Parrot and Shrubbery. Both rely on a common module,
> Spam. Parrot uses version 1 of Spam and Shrubbery uses version 2. For the
> sake of the argument, Spam is completely backwards compatible, so I
> have no problems with somebody installing Parrot plus Spam version 1, then
> installing Shrubbery, where Spam version 2 overwrites the older Spam
> module. But if Spam version 1 overwrites version 2, then Shrubbery stops
> working.
> 
> The easy answer is to say, "Then don't do that", but that's a terribly
> impractical answer. Blaming the user is no real solution either. In
> old-time Windows land, installation programs would blindly nuke newer DLLs
> with older DLLs all the time. Under Linux, one convention is for shared
> libraries to include the version number in the file name, so that newer
> libraries weren't blown away by older ones.
> 
> What is the Python solution? Enquiring minds want to know.

http://peak.telecommunity.com/DevCenter/PythonEggs
http://peak.telecommunity.com/DevCenter/PkgResources

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: stumped by tricky logic

2006-01-29 Thread Max
Dave wrote:
> So I'm trying to write a CSS preprocessor.
> 
> I want to add the ability to append a selector onto other selectors.
> So, given the following code:
> =
> #selector {
> 
>   { property: value; property: value; }
> .other_selector   { property: value; property: value; }
> 
> #selector_2 {
> 
>  .more_selector { property: value; }
> 
> }
> 
> }

> =
> 
> I want to return the following:
> =
> #selector { property: value; property: value; }
> #selector .other_selector { property: value; property: value; }
> #selector #selector_2 .more_selector { property: value; }
> =
> 

Should the properties of #selector be "inherited" by .other_selector? 
That's what I'd think the most logical approach, but by your example it 
seems not.

> What I think I need to do is match the "{" character with its "}" pair,
> then see if there's another "{" before a matching "}" - but that's
> about as far as my brain will go. The actually code to make this
> actually happen is not coming out when I type.
> 
> Any suggestions would be very appreciated. And handsomely rewarded (by
> karma, not me).
> 

I'd use a class called Style or somesuch with three attributes:
-Selector (containing "#selector" for example)
-Props (containing the property: value pairs, either as-is or in a 
dictionary)
-Parent (containing a reference to the style that contains this one, or 
None)

Use a recursive function to read the file, and pass the containing Style 
object to it. It reads the props into the class, and recurses on any 
"sub-styles".

After this, you'll have constructed a tree (keep a reference to root). 
Now you can use an extension of a standard pre-order traversal to output it.

> - Dave
> 

Hope this helps.


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


Re: stumped by tricky logic

2006-01-29 Thread Roy Smith
"Dave" <[EMAIL PROTECTED]> wrote:
> So I'm trying to write a CSS preprocessor.

What you're trying to do is write a parser.  I don't know CSS, so I can't 
comment on the details, but basically, you're trying to parse a non-trivial 
language.  It is usually hopeless to try and write a parser using just 
pattern-matching.  You really need to read up on grammars and parsers to do 
this right.  Consider, for example, something like

#selector { /* } */ foo; }

getting that right is pretty tricky, and this is far from the most complex 
example possible.

I think you might want to start at 
http://python.miscellaneousmirror.org/topics/parsing.html, and do a bunch 
of reading about parsing theory, before you sit down to start writing code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Find directory name of file?

2006-01-29 Thread veracon
I'm pretty new at Python, so I have no idea how to do this: How do I
find the name of the directory that contains the application currently
being executed (e.g. if the file is /home/user/file.py, I want to get
the /home/user part)?

Thanks!

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


Re: Find directory name of file?

2006-01-29 Thread jmdeschamps

veracon wrote:
> I'm pretty new at Python, so I have no idea how to do this: How do I
> find the name of the directory that contains the application currently
> being executed (e.g. if the file is /home/user/file.py, I want to get
> the /home/user part)?
> 
> Thanks!

look into os.path module for help

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


Re: VB to Python migration

2006-01-29 Thread Magnus Lycka
Josh wrote:
> We currently use a MS Access back end and need to migrate to a proper 
> SQL server. We need to leave options open for SQL Server (for customers 
> who want to use existing infrastructure) and something like MySQL or 
> PostgreSQL. But in the mean time, we need to be able to access an 
> MSAccess (Jet) database from Python.

mxODBC is probably the best way to talk to Jet in a way (DB API)
that makes it reasonably easy to port the data to another RDBMS.
Writing multi RDBMS applications is a whole chapter in itself,
if not a subject for a whole book.

Whether to use an ORM such as SQLObject on top of that is another
issue...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: VB to Python migration

2006-01-29 Thread Magnus Lycka
Ravi Teja wrote:
> 230 UI screens is a lot. An app of that nature is not something people
> commonly do in Python (although I would be happy to see people show me
> wrong).

Maybe not, but I don't doubt that it's reasonable to replace a
VB app with 230 UI screens with Python code.

A code of that size is something that's grown over time, and if
it's rewritten, it seems likely that it will end up with fewer
screens without fewer features.

Besides, while VB makes it very easy to duplicate a lot of code,
and end up in a situation where you have to manually change things
230 times through the GUI if something changes in all screens, it's
very convenient to use inheritence for GUI development with e.g.
wxPython. I supect the screens have a lot in common, and that it
would be fairly clear how to build a class hierachy of that, and
avoid code duplication. The end result will be a more homogenous
application and a lower maintenance cost.

The really silly thing to do is to apply VB idioms on Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Hostname

2006-01-29 Thread [EMAIL PROTECTED]
Hi
Iam new in Python.
I want to know for my first Project in Python how i can get the
Hostname from a URL?
Thanks for Help

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


Re: Find directory name of file?

2006-01-29 Thread jmdeschamps
also the function os.cwd() 
;-)

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


Re: newbie: working iwth list of tuples

2006-01-29 Thread falcon
Wow, great answers here.  Thank you all for the links and examples, I'm
going through them all now.

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


Re: Hostname

2006-01-29 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Hi
> Iam new in Python.
> I want to know for my first Project in Python how i can get the
> Hostname from a URL?

>>> import urlparse
>>> urlparse.urlsplit('http://foo.bar.com/zapzap')
('http', 'foo.bar.com', '/zapzap', '', '')
>>> 

As you may notice, the hostname is the second item of the tuple result.

> Thanks for Help

You're welcome.


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


Re: Hostname

2006-01-29 Thread [EMAIL PROTECTED]
Wow! This was a fast answer and it works.

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


Re: Returning a value from code string

2006-01-29 Thread Fried Egg
>From above:

I hope the contents of the database are trusted, because if the code is
coming from an untrusted source, well, U R pwn3d.

Seems like you are jumping through a lot of hoops for very little
benefit.
What am I missing?



Why does anyone care about "why" people do things when they ask a
specific technical question on a newsgroup?  Maybe op is risking his
server (who cares) or maybe he is just trying to explore an idea
(again, who cares).  It almost seems like bad etiquette, really.  It
also seems somehow different than asking questions that elicit
technical context.

Sorry to rant about etiquette.  I just have a problem similar to the
original poster's, and it pissed me off when I wrote to the newsgroup
asking "how do I do x,y,z?" and somebody writes back saying "you really
shouldn't want to do x,y,z..." when they really haven't a clue.  This
exchange has been a lot better than that, probably because of my poor
explanation in my question.

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


ANN: (slightly) extended Python debugger 0.11

2006-01-29 Thread R. Bernstein
The second public release of the extended Python debugger is now
available from sourceforge:

http://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827

For this release documentation has been added. That is also available
online at: http://bashdb.sourceforge.net/pydb/pydb/lib/index.html

A lot of important changes were made and changes that will facilitate
growth.

The ability to do non-interactive POSIX-shell line tracing was added,
and debugger output can be redirected. This should help out in
situations such as CGI's where there is no terminal or interactivity
is not possible.

Regression tests were added to ensure quality, and lo' bugs
were found. Debugger command options were added.

More information can be found in the NEWS file that comes with the
distribution.

Given the feedback on the pdb.py debuggers (i.e. it's just not used
all that often), compatibility with that has been deprecated where it
conflicts with other debuggers.

I've only tested this on GNU/Linux, OSX Solaris and cygwin using
Python versions 2.3.5 and 2.4.2.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs C for a mail server

2006-01-29 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
abhinav <[EMAIL PROTECTED]> wrote:
>ya its supposed to be some stupid 6 month project which my friend has
>to do.I am just helping him out.he may not be implementing a full
>fledged rfc compliance mail server but may support some of the major
>functionalities.so basically its an extra ordinary need.I just wanted
>to know which language would be better for implementation and has
>faster development cycle.I have heard a lot about python and its ease
>of use.My point is it should be worth a 6 month project and speedy
>development since he is already proficient in C/C++ socket programming
>and taking the pain of learning python should be worth the effort.
>

In that case, you'll come closer to having a working mail server in
Python. I just hope that it's understood you won't have a mail server
which is ready to be used on the Internet for any but very limited
applications.


-- 
Jim Segrave   ([EMAIL PROTECTED])

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


Print dict in sorted order

2006-01-29 Thread Kamilche
I have a code snippet here that prints a dict in an arbitrary order.
(Certain keys first, with rest appearing in sorted order). I didn't
want to subclass dict, that's error-prone, and overkill for my needs. I
just need something that returns a value like dict.__str__, with a key
ordering I specify.

If you have any opinions on how it could be made better, I'm all ears!



def DictToString(d, preferred_order = ['gid', 'type',
   'parent', 'name']):
' Return a string containing the sorted dict'
keys = d.keys()
keys.sort()
sortmax = len(preferred_order)
for i in range(sortmax-1, -1, -1):
sortkey = preferred_order[i]
try:
index = keys.index(sortkey)
except ValueError:
continue
temp = keys[index]
del keys[index]
keys.insert(0, temp)
s = []
s.append('{')
max = len(keys)
for i in range(max):
key = keys[i]
val = d[key]
s.append(repr(key))
s.append(': ')
s.append(repr(val))
if i < max-1:
s.append(', ')
s.append('}')
return ''.join(s)


def main():
d = {'whatever': 145,
 'gid': 12345678901234567890,
 'name': 'Name',
 'type': 'an egg',
 32: 'Thirty-two (32)'}

# Convert dicts to strings
s1 = str(d)
s2 = DictToString(d)
print "Python str:", s1
print "Custom str:", s2

# Verify the strings are different
assert(s1 != s2)

# Convert the strings back to dicts
d1 = eval(s1)
d2 = eval(s2)

# Verify the dicts are equivalent
assert(d1 == d2)

print "\nSuccess!\n"



main()

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


Re: Python vs C for a mail server

2006-01-29 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
Dan Lowe  <[EMAIL PROTECTED]> wrote:
>
>On Jan 28, 2006, at 8:39 PM, Dennis Lee Bieber wrote:
>
>> On Sat, 28 Jan 2006 18:03:56 +1100, Steven D'Aprano said:
>>>
>>> Google is your friend. The first four mail servers listed are, in  
>>> order:
>>>
>>> sendmail
>>> postfix
>>> Microsoft Exchange
>>> qmail
>>>
>>  Dig a bit deeper, and exim might be a candidate for the list. I'm
>> pretty sure O'Reilly has books for sendmail, postfix, and exim; don't
>> know about qmail.
>
>O'Reilly does have an Exim book, but it is out of date. It covers the  
>3.x family, while 4.x has been out for quite a while now. The 4.x  
>family is very different from 3.x, so the book isn't worth a whole  
>lot these days.
>
>I'm on my second major mail system deployment built around Exim, and  
>would recommend it to anybody needing a robust, flexible mail server.

There is an exim 4 book out, but not via O'Reilly - I gather sales
were insufficient to persuade O'Reilly to do an update. As we use Exim
heavily, we have both the 3 and 4 books in our NOC, as well as sending
almost all new staff to Phil Hazel's excellent courses in Cambridge.




-- 
Jim Segrave   ([EMAIL PROTECTED])

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


Authenticating to Kerberos

2006-01-29 Thread David
Hi,

I've had a quick look but cannot find a module that will let me authenticate
against Kerberos.  There appears to be a krb5 module that hasn't been
updated for a long time and I can't find much on it except the pages at
starship.python.net.

I don't need to do anything except authenticate and gain the correct
credentials.

Are there any modules that I could use to authenticate against Kerberos
(perhaps there is another module will do just the auth, e.g. for LDAP?).

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


Re: Print dict in sorted order

2006-01-29 Thread Paul Rubin
"Kamilche" <[EMAIL PROTECTED]> writes:

> I have a code snippet here that prints a dict in an arbitrary order.
> (Certain keys first, with rest appearing in sorted order). I didn't
> want to subclass dict, that's error-prone, and overkill for my needs. I
> just need something that returns a value like dict.__str__, with a key
> ordering I specify.
> 
> If you have any opinions on how it could be made better, I'm all ears!

Here's my version.  Obviously you could save a line or two here and
there, depending on your stylistic preference.



from sets import Set
from cStringIO import StringIO

def DictToString(d, preferred_order = ['gid', 'type',
   'parent', 'name']):
r = StringIO()
def out(k, v):
r.write('%s:%s,'% (repr(k), repr(v)))
r.write('{')
for k in preferred_order:
if k in d:
out(k, d[k])
for k in sorted([k1 for k1 in d.keys() if k1 not in Set(preferred_order)]):
out(k, d[k])
r.write('}')
return r.getvalue()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: VB to Python migration

2006-01-29 Thread Ravi Teja
Magnus Lycka wrote:
> Ravi Teja wrote:
> > 230 UI screens is a lot. An app of that nature is not something people
> > commonly do in Python (although I would be happy to see people show me
> > wrong).
>
> Maybe not, but I don't doubt that it's reasonable to replace a
> VB app with 230 UI screens with Python code.
>
> A code of that size is something that's grown over time, and if
> it's rewritten, it seems likely that it will end up with fewer
> screens without fewer features.

Rewrites are always good and result in smaller code base if features
are not added. However, I doubt that will make the screens fewer. Lines
of code? Certainly.

> Besides, while VB makes it very easy to duplicate a lot of code,
> and end up in a situation where you have to manually change things
> 230 times through the GUI if something changes in all screens, it's
> very convenient to use inheritence for GUI development with e.g.
> wxPython. I supect the screens have a lot in common, and that it
> would be fairly clear how to build a class hierachy of that, and
> avoid code duplication. The end result will be a more homogenous
> application and a lower maintenance cost.

You are comparing Python with VB 6. That's not what the OP is moving to
as an alternative. It's .NET. VB 6 has been out of development since 8
years? Its not something to be compared to anymore. .NET on the other
hand has all the advantages of Python accessible toolkits for this task
and then some. For example, it's not just inheritance but visual
inheritance. It's not just a GUI but GUI with data bindings, with
sophisticated caching, paging etc. GUI Builders are far more
sophisticated and integrated than, say wxGlade.

I am not saying Python is unfit for 230 screens. Just that I have not
seen anyone build such a thing and better write about it. People on the
other hand have build web sites with such volume. Result? We have a ton
of web application frameworks to address such needs. We would have the
same for Data GUIs if that was the case. We have people drooling over
TurboGears, not Dabo (apologies Dabo team).

> The really silly thing to do is to apply VB idioms on Python.

It is. But that's what people do on their first few projects and it's
perfectly natural. Didn't you :-) ?

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


RE: OpenGL

2006-01-29 Thread Delaney, Timothy (Tim)
Mike C. Fletcher wrote:

> ctypes re-re-implementation of the same Python API to OpenGL.  My
> intention is that the ctypes implementation will become the 3.0.0
> release when it is finished and optimised.

You should be aware then that it's likely that ctypes will be included
in Python 2.5.

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


Re: Hostname

2006-01-29 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Wow! This was a fast answer and it works.

That's why we used to joke about Guido's time machine: somebody would
express a need (sometimes phrased as a suggestion for an enhancement),
and Guido would zip back in time and implement the needed functionality
_before_ the request...;-)


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


Re: Server side newbie

2006-01-29 Thread Pierre Quentel
swisscheese a écrit :
> I have a simple python desktop app with several edit controls and a
> couple of buttons. It just does some math. What's the simplest way to
> make it a server-side app so visitors to my site can run the app via
> their browser?
> 
Among the many web frameworks for Python, Karrigell is probably the 
easiest to get started with

You can check out a recent review on devshed :
http://www.devshed.com/c/a/Python/Karrigell-for-Python/

It says : "Python novices won't find any obstacles when working with 
Karrigell, and Python experts won't feel too limited"

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


StringIO proposal: add __iadd__

2006-01-29 Thread Paul Rubin
I've always found the string-building idiom

  temp_list = []
  for x in various_pieces_of_output(): 
 v = go_figure_out_some_string()
 temp_list.append(v)
  final_string = ''.join(temp_list)

completely repulsive.   As an alternative I suggest

   temp_buf = StringIO()
   for x in various_pieces_of_output(): 
  v = go_figure_out_some_string()
  temp_buf += v
   final_string = temp_buf.getvalue()

here, "temp_buf += v" is supposed to be the same as "temp_buf.write(v)".
So the suggestion is to add a __iadd__ method to StringIO and cStringIO.

Any thoughts?

Also, I wonder if it's now ok to eliminate the existing StringIO
module (make it an alias for cStringIO) now that new-style classes
permit extending cStringIO.StringIO.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: StringIO proposal: add __iadd__

2006-01-29 Thread Alex Martelli
Paul Rubin  wrote:
   ...
>temp_buf = StringIO()
>for x in various_pieces_of_output(): 
>   v = go_figure_out_some_string()
>   temp_buf += v
>final_string = temp_buf.getvalue()
> 
> here, "temp_buf += v" is supposed to be the same as "temp_buf.write(v)".
> So the suggestion is to add a __iadd__ method to StringIO and cStringIO.

What's the added value of spelling x.write(v) as x += v?  Is it worth
the utter strangeness of having a class which allows += and not + (the
only one in the std library, I think it would be)...?

> Any thoughts?

I think that the piece of code you like and I just quoted is just fine,
simply by changing the += to a write.

> Also, I wonder if it's now ok to eliminate the existing StringIO
> module (make it an alias for cStringIO) now that new-style classes
> permit extending cStringIO.StringIO.

I love having a pure-Python version of any C-coded standard library
module (indeed, I wish I had more!-) for all sorts of reasons, including
easing the burden of porting Python to weird platforms.  In StringIO's
case, it's nice to be able to use the above idiom to concatenate Unicode
strings just as easily as plain ones, for example -- cStringIO (like
file objects) wants plain bytestrings.

It would be nice (in Py3k, when backwards compatibility can be broken)
to make the plain-named, "default" modules those coded in C, since
they're used more often, and find another convention to indicate pure
Python equivalents -- e.g., pickle/pypickle and StringIO/pyStringIO
rather than the current cPickle/pickle and cStringIO/StringIO.  But I
hope the pure-python "reference" modules stay around (and, indeed, I'd
love for them to _proliferate_, maybe by adopting some of the work of
the pypy guys at some point;).


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


Re: StringIO proposal: add __iadd__

2006-01-29 Thread Paul Rubin
[EMAIL PROTECTED] (Alex Martelli) writes:
> What's the added value of spelling x.write(v) as x += v?  Is it worth
> the utter strangeness of having a class which allows += and not + (the
> only one in the std library, I think it would be)...?

Sure, + can also be supported.  Adding two StringIO's, or a StringIO to a
string, results in a StringIO with the obvious contents.

> In StringIO's case, it's nice to be able to use the above idiom to
> concatenate Unicode strings just as easily as plain ones, for
> example -- cStringIO (like file objects) wants plain bytestrings.

I wasn't aware of that limitation--maybe cStringIO could be extended
to take Unicode.  You'd use an encode or decode method to get a
bytestring out.  Or there could be a mutable-string class separate
from cStringIO, to be used for this purpose (of getting rid of the
list.append kludge).

> But I hope the pure-python "reference" modules stay around (and,
> indeed, I'd love for them to _proliferate_, maybe by adopting some
> of the work of the pypy guys at some point;).

Maybe the standard versions of some of these things can be written in
RPython under PyPy, so they'll compile to fast machine code, and then
the C versions won't be needed.  But with CPython I think we need the
C versions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange behavior of int()

2006-01-29 Thread Dan Bishop
Brian wrote:
> Hello,
>
> Can someone tell me what I am doing wrong in this code.
>
> If I create a file change.py with the following contents:
>
> def intTest(M, c):
> r = M
> for k in c:
> print 'int(r/k) = ', int(r/k), 'r =', r, 'k =', k, 'r/k
> =', r/k
> r = r - (k*int(r/k))
>
> intTest(2.30, [0.25, 0.10, 0.05, 0.01])
>
> and execute it, I get the output:
>
> int(r/k) =  9 r = 2.3 k = 0.25 r/k = 9.2
> int(r/k) =  0 r = 0.05 k = 0.1 r/k = 0.5
> int(r/k) =  0 r = 0.05 k = 0.05 r/k = 1.0
> int(r/k) =  4 r = 0.05 k = 0.01 r/k = 5.0

The important thing to remember is that, as far as your computer is
concerned, there are no such numbers as 2.30, 0.10, 0.05, or 0.01.
What's actually stored is the closest binary equivalents.  So your
intTest call is equivalent to

intTest(5179139571476070*2**(-51), [0.25, 7205759403792794*2**(-56),
7205759403792794*2**(-57), 5764607523034235*2**(-59)])

The first time through the loop, r = 5179139571476070*2**(-51) and k =
0.25, so r/k = 5179139571476070*2**(-49), which equals
9.199289457264239899814128875732421875.  This is as close
to the desired 9.2 as you can get.  So far, so good.

Now, it happens that the value k*int(r/k) = 2.25 is computed exactly.
Subtracting this from r gives

r = 5179139571476070*2**(-51) - 2.25
  = 5179139571476070*2**(-51) - 5066549580791808*2**(-51)
  = (5179139571476070 - 5066549580791808) * 2**(-51)
  = 112589990684262*2**(-51)
  = 7205759403792768*2**(-57)

My last computation here is to normalize the result to 53 significant
bits.  But note that the last 6 of those are zero, because the result
was shifted by 6 places.

0011001100110011001100110011001100110011001100110 * 2**(-51)
 /  /
/  /
   /  /
  /  /
 /  /
/  /
1100110011001100110011001100110011001100110011000 * 2**(-57)
   ^^
   padding

The loss of 6 significant bits means that this approximation of 0.05 is
slightly different from the direct approximation of 0.05.  The worst
part is, it's slightly *less*

7205759403792768*2**(-57) # result of the computation
7205759403792794*2**(-57) # 0.05 as stored in the computer

This causes r/k to be slightly *less* than one, which makes int(r/k)
zero and f's up the rest of your computations.

The way to fix this is to use numbers that can be stored exactly in
binary.  The simplest way is to represent monetary amounts as integer
numbers of cents

>>> intTest(230, [25, 10, 5, 1])
int(r/k) =  9 r = 230 k = 25 r/k = 9.2
int(r/k) =  0 r = 5 k = 10 r/k = 0.5
int(r/k) =  1 r = 5 k = 5 r/k = 1.0
int(r/k) =  0 r = 0 k = 1 r/k = 0.0

You might also consider using the decimal.Decimal class.  (Of course,
you'll still have roundoff problems if working with nondecimal amounts
like 1/3 or 1/7.  In that case, use a Rational class.)

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


Re: Returning a value from code string

2006-01-29 Thread Alex Martelli
Fried Egg <[EMAIL PROTECTED]> wrote:
   ...
> Why does anyone care about "why" people do things when they ask a
> specific technical question on a newsgroup?  Maybe op is risking his

Because experienced techies have learned that people (including other
techies) often ask the wrong "specific technical question", having
previously made some badly-founded assumptions and premature preliminary
design decisions; by taking a step back, and getting the "why", it's
therefore quite often possible to help the querant come up with a much
better overall solution.

The classic example is right at the start of Bentley's classic "Writing
Efficient Programs" (or maybe "Programming Pearls" -- been a while since
I read either!-), where another programmer asks him how to invoke the
system sort from within a program, and Bentley at first wastes a lot of
time and energy answering the exact question that was asked -- but
finally steps back, DOES ask the crucial question, "why do you want to
know?", and helps the querant find a solution which runs rings around
anything the querant might have come up with by shelling out to a system
sort.  Many experienced techies are familiar with Bentley's
masterpieces, and the lesson appears to have sunk in -- or it may well
have been rediscovered independently many, many times, of course.

It's unfortunate that you appear not to understand or accept this, but I
hope nobody will change their helpful behavor and motivation as a
consequence of your complaint.  It's only by relentlessly asking "why",
that very experienced developers can *most* help others.


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


Re: Returning a value from code string

2006-01-29 Thread Peter Hansen
Fried Egg wrote:
>>From above:
> Seems like you are jumping through a lot of hoops for very little
> benefit.
> What am I missing?
> 
> 
> Why does anyone care about "why" people do things when they ask a
> specific technical question on a newsgroup?  Maybe op is risking his
> server (who cares) or maybe he is just trying to explore an idea
> (again, who cares).  It almost seems like bad etiquette, really.  It
> also seems somehow different than asking questions that elicit
> technical context.

To be blunt, you're wrong.  Though some of us have trouble posting 
"why?" responses that never sound rude, it is not only a good idea to 
understand why, it's *necessary*.  In fact, only by understanding why 
can one really understand the "technical context".  This is a basic 
tenet of good requirements engineering.

Among other good reasons to ask why, there are the following:

1. Experience in this newsgroup shows that a large percentage of people 
asking questions have a poor understanding of their own requirements, or 
are making the mistake of defining their problem in terms of a desired 
solution rather than merely specifying requirements and allowing the 
experts to choose the most appropriate solution.  An example of this is 
the frequent "How can I use package X to do such-and-such?" where the 
ultimate best answer turns out to be "don't use package X, you don't 
need it for what it turns out you're trying to do".  Yes, sometimes the 
OP specifically wanted to use X to solve the problem, to learn more 
about X, but then that's just when asking "why?" is most critical.  They 
usually don't tell us when that's the case, so we have to ask to be sure.

2. Because of different linguistic and cultural backgrounds in this 
international newsgroup, or the inherent ambiguities in human language, 
a poster sometimes misuses a word or phrase, or entirely misunderstands 
something he's read, and if we don't dig down to the "why?" we risk 
providing an answer which answers the letter of his question but 
entirely misses the spirit, and ultimately is a disservice.

3. People posting here have a wide range of experience, whether with 
Python, with programming, or with computers in general.  Sometimes it's 
not at all clear how experienced a poster is, and if a given answer 
doesn't take into account the possibility that the poster is such a 
rookie that he might be completely off the mark about how to do 
something, or even whether it's a good idea to do something, then that 
answer might be more harmful than helpful.

In the specific case in question, Kirk's first post gave little or no 
hint about how much he knew about security issues and, by asking "why?", 
with a single word Steven hoped to learn enough to say things like "oh, 
there's a package designed to do that which you can just plug in" or 
"oh, it's clear you are totally new to issues of network security and 
are about to put your foot right in it, so here's some background to 
save you from yourself", or whatever...

> Sorry to rant about etiquette.  I just have a problem similar to the
> original poster's, and it pissed me off when I wrote to the newsgroup
> asking "how do I do x,y,z?" and somebody writes back saying "you really
> shouldn't want to do x,y,z..." when they really haven't a clue.  This
> exchange has been a lot better than that, probably because of my poor
> explanation in my question.

Being pissed off when someone trying to help you responds in a manner 
you consider to be overstepping some unspoken bounds is really your 
problem, not that of the respondent, and you ought to learn to deal with 
it given, the anarchy that is Usenet.  While it's arguable whether 
bluntly asking "why?" violates some kind of "etiquette", it most 
definitely does *not* violate "netiquette", and actually follows it very 
closely.  IMHO.

YMMV, but ultimately it's your problem if you don't think people should 
ask why.  If it really concerns you, prepend your posts with "I believe 
I have good reasons for doing the things I'm doing here and kindly ask 
that potential respondents limit their responses to directly addressing 
the technical issues I raised and not asking "why?" I'm doing this. 
Thank you in advance."

If you were to do that, it would largely (but not entirely) eliminate 
that kind of reply, and would save some of us the trouble of reading the 
rest of your post.

-Peter

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


Re: StringIO proposal: add __iadd__

2006-01-29 Thread Alex Martelli
Paul Rubin  wrote:
   ...
> > In StringIO's case, it's nice to be able to use the above idiom to
> > concatenate Unicode strings just as easily as plain ones, for
> > example -- cStringIO (like file objects) wants plain bytestrings.
> 
> I wasn't aware of that limitation--maybe cStringIO could be extended
> to take Unicode.  You'd use an encode or decode method to get a
> bytestring out.  

But why can't I have perfectly polymorphic "append a bunch of strings
together", just like I can now (with ''.join of a list of strings, or
StringIO), without caring whether the strings are Unicode or
bytestrings?

> Or there could be a mutable-string class separate
> from cStringIO, to be used for this purpose (of getting rid of the
> list.append kludge).

StringIO works just fine.  Developing (and having to document, learn,
teach, ...) a separate interface just in order to remove StringIO does
not seem worth it.  As for extending cStringIO.write I guess that's
possible, but not without breaking compatibility (code that now uses
that write with unicode strings assuming that they'll get encoded into
bytestrings by the default encoding, and similarly assumes that getvalue
always returns a bytestring, when called on a cStringIO instance); you'd
need instead to add another couple of methods, or wait for Py3k.


> > But I hope the pure-python "reference" modules stay around (and,
> > indeed, I'd love for them to _proliferate_, maybe by adopting some
> > of the work of the pypy guys at some point;).
> 
> Maybe the standard versions of some of these things can be written in
> RPython under PyPy, so they'll compile to fast machine code, and then
> the C versions won't be needed.  But with CPython I think we need the
> C versions.

By all means, the C versions are welcome, I just don't want to lose the
Python versions either (and making them less readable by recoding them
in RPython would interfere with didactical use).


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


Re: obtain client ip address from SimpleXMLRPCServer ?

2006-01-29 Thread stuff
Thanks again Peter.  I found 2 potential solutions for obtaining the ip
address of the incoming
connection.  The first was to subclass SimpleXMLRPCRequestHandler class
and pass it
to the SimpleXMLRPCServer constructor.  In doing so, I could directly
access the client_address via self.client_address.  This worked just
fine but was a bit overkill.

The other solution I noticed was that SimpleXMLRPCServer's (which
ultimately subclasses BaseServer) handle_request method invokes
get_request (which merely calls self.socket.accept() -- which returns a
tuple including the ip address).  By re-implementing get_request() as
such:

def get_request(self):
req = self.socket.accept()
ip_address = req[1][0]
return req

I can grab the ip address for internal use and have the get_request
method return the expected data for use by hande_request().

Now I just need to find a thread-safe way of passing this data back to
the XMLRPC server's registered_instance.

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


Re: Python vs C for a mail server

2006-01-29 Thread Paul Boddie
Jay Parlar wrote:
> I don't think I've ever seen anyone advocating calling a function like
> getattr(obj "foo" + "bar")().

>From Lib/compiler/visitor.py:

meth = getattr(self.visitor, 'visit' + className, 0)

Later on:

meth(node, *args)

Of course, you can drop the "visit" prefix and make the mechanism more
predictable, but a search on the standard library for getattr produces
a lot of evidence against your assertion.

Paul

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


Re: StringIO proposal: add __iadd__

2006-01-29 Thread Paul Rubin
[EMAIL PROTECTED] (Alex Martelli) writes:
> But why can't I have perfectly polymorphic "append a bunch of strings
> together", just like I can now (with ''.join of a list of strings, or
> StringIO), without caring whether the strings are Unicode or
> bytestrings?

I see that 'a' + u'b' = u'ab', which makes sense.  I don't use Unicode
much so haven't paid much attention to such things.  Is there some
sound reason cStringIO acts differently from StringIO?  I'd expect
them to both do the same thing.

> As for extending cStringIO.write I guess that's
> possible, but not without breaking compatibility ... you'd
> need instead to add another couple of methods, or wait for Py3k.

We're already discussing adding another method, namely __iadd__.
Maybe that's the place to put it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Find directory name of file?

2006-01-29 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
> also the function os.cwd() 
> ;-)

I'm not sure how os.cwd() helps, but generally the solution to this 
starts with pointing out that sys.argv[0] usually contains the path to 
the main script, which is often the answer needed.

Recipes have been posted in the past which cover a wider range of 
situations, including when running as a "py2exe'd" program (i.e. 
"frozen"), as the simple solution doesn't cover all cases.

Checking the archives would probably help.

-Peter

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


Re: StringIO proposal: add __iadd__

2006-01-29 Thread Erik Max Francis
Paul Rubin wrote:

> I've always found the string-building idiom
> 
>   temp_list = []
>   for x in various_pieces_of_output(): 
>  v = go_figure_out_some_string()
>  temp_list.append(v)
>   final_string = ''.join(temp_list)
> 
> completely repulsive.   As an alternative I suggest
> 
>temp_buf = StringIO()
>for x in various_pieces_of_output(): 
>   v = go_figure_out_some_string()
>   temp_buf += v
>final_string = temp_buf.getvalue()
> 
> here, "temp_buf += v" is supposed to be the same as "temp_buf.write(v)".
> So the suggestion is to add a __iadd__ method to StringIO and cStringIO.
> 
> Any thoughts?

Why?  StringIO/cStringIO have file-like interfaces, not sequences.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   The opinion of the strongest is always the best.
   -- Jean de la Fontaine
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs C for a mail server

2006-01-29 Thread Fredrik Lundh
Paul Boddie wrote:

> > I don't think I've ever seen anyone advocating calling a function like
> > getattr(obj "foo" + "bar")().
>
> >From Lib/compiler/visitor.py:
>
> meth = getattr(self.visitor, 'visit' + className, 0)
>
> Later on:
>
> meth(node, *args)
>
> Of course, you can drop the "visit" prefix and make the mechanism more
> predictable, but a search on the standard library for getattr produces
> a lot of evidence against your assertion.

if you read Jay's assertion in context, your "refutation" strikes me as
somewhat silly.





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


Re: Find directory name of file?

2006-01-29 Thread Grant Edwards
On 2006-01-29, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> also the function os.cwd() 

Neither os.path nor os.cwd are going to tell you the location
of the python program being executed.

Looking at the value of sys.argv[0] is probably the best bet.
If it's a relative path, then you can use os.path to convert it
to an absolute path if you like:

Try something like this at the beginning of your program and
see if it does what you want:

  print os.path.abspath(sys.argv[0])

-- 
Grant Edwards   grante Yow!  It's the land of
  at   DONNY AND MARIE as promised
   visi.comin TV GUIDE!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print dict in sorted order

2006-01-29 Thread Fuzzyman
You can always use OrderedDict :

htttp://www.voidspace.org.uk/python/odict.html

from odict import OrderedDict
my_dict = OrderedDict(some_dict.keys())
keys = my_dict.keys()
keys.sort()
my_dict.setkeys(keys)
print my_dict

Of course if your ordering requirement was *that* trivial, you could do
:

from odict import OrderedDict
my_dict = OrderedDict(some_dict.keys())
my_dict.sort()

*Or* you can do :

from odict import SequenceOrderedDict
my_dict = SequenceOrderedDict(some_dict.keys())
keys = my_dict.keys()
keys.sort()
my_dict.keys = keys
print my_dict

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

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


Re: StringIO proposal: add __iadd__

2006-01-29 Thread Scott David Daniels
Alex Martelli wrote:
> It would be nice (in Py3k, when backwards compatibility can be broken)
> to make the plain-named, "default" modules those coded in C, since
> they're used more often, and find another convention to indicate pure
> Python equivalents -- e.g., pickle/pypickle and StringIO/pyStringIO
How about something like a package py for all such python-coded modules
so you use py.StringIO (which I hope gets renamed to stringio in the
Py3K shift).

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


Re: Python vs C for a mail server

2006-01-29 Thread Volker Grabsch
Jens Theisen wrote:
> What do you do when you want to no if a certain method or function is  
> actually used from somewhere, say "foobar", it a language which allows  
> (and even encourages) that it could be called by:
>
> getattr(obj, "foo" + "bar")()

No. The recommended way to do it is:

obj.foobar()

> There is no systematic way to find this call.
>
> In C++, just commend out the definition and the compiler will tell you.

In such a case I normally just grep for "foobar". I did so (and I'll do so)
in C/C++, Python, and any other language.


Any programming language allows you to do strange/stupid stuff. But none
of them encourages it. So I can't see your point in any way.



Greets,

Volker

-- 
Volker Grabsch
---<<(())>>---
\frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt
[G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using bytecode, not code objects

2006-01-29 Thread Michael Spencer
Fredrik Lundh wrote:
> Fabiano Sidler wrote:
> 
>> I'm looking for a way to compile python source to bytecode instead of
>> code-objects. Is there a possibility to do that? The reason is: I want
>> to store pure bytecode with no additional data.
> 
> use marshal.
> 
>> The second question is, therefore: How can I get the correct values
>> for a given bytecode, such as the stacksize and flags attributes of
>> the correspondent code object?
>>
>> No, I don't want to extract all of these things out of a code object.
> 
> you don't have to.  marshal can convert a code object to a single byte
> string, which contains everything you need.  see the second example on
> this page for sample code:
> 
> http://www.effbot.org/librarybook/marshal.htm
> 
> 
> 
> 
> 
There's a typo in the text accompanying that example: img.get_magic() should be 
imp.get_magic().

Michael




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


Re: StringIO proposal: add __iadd__

2006-01-29 Thread Alex Martelli
Paul Rubin  wrote:

> [EMAIL PROTECTED] (Alex Martelli) writes:
> > But why can't I have perfectly polymorphic "append a bunch of strings
> > together", just like I can now (with ''.join of a list of strings, or
> > StringIO), without caring whether the strings are Unicode or
> > bytestrings?
> 
> I see that 'a' + u'b' = u'ab', which makes sense.  I don't use Unicode
> much so haven't paid much attention to such things.  Is there some
> sound reason cStringIO acts differently from StringIO?  I'd expect
> them to both do the same thing.

I believe that cStringIO tries to optimize, while StringIO doesn't and
is thereby more general.


> > As for extending cStringIO.write I guess that's
> > possible, but not without breaking compatibility ... you'd
> > need instead to add another couple of methods, or wait for Py3k.
> 
> We're already discussing adding another method, namely __iadd__.
> Maybe that's the place to put it.

Still need another method to 'getvalue' which can return a Unicode
string (currently, cStringIO.getvalue returns plain strings only, and it
might break something if that guarantee was removed).

That being said, if the only way to use a StringIO was to call += or
__iadd__ on it, I would switch my recommendation away from it and
towards "just join the sequence of strings".  Taking your example:

   temp_buf = StringIO()
   for x in various_pieces_of_output(): 
  v = go_figure_out_some_string()
  temp_buf += v
   final_string = temp_buf.getvalue()

it's just more readable to me to express it

   final_string = ''.join(go_figure_out_some_string()
  for x in various_pieces_of_output())

Being able to use temp_buf.write(v) [like today, but with StringIO, not
cStringIO] would still have me recommending it to newbies, but having to
explain that extra += just tips the didactical balance.  It's already
hard enough to jump ahead to a standard library module in the middle of
an explanation of strings, just to explain how to concatenate a bunch...

Yes, I do understand your performance issues:

Nimue:~/pynut alex$ python2.4 -mtimeit -s'from StringIO import StringIO'
's=StringIO(); s.writelines(str(i) for i in range(33)); x=s.getvalue()'
1000 loops, best of 3: 337 usec per loop

Nimue:~/pynut alex$ python2.4 -mtimeit -s'from cStringIO import
StringIO' 's=StringIO(); s.writelines(str(i) for i in range(33));
x=s.getvalue()'
1 loops, best of 3: 98.1 usec per loop

Nimue:~/pynut alex$ python2.4 -mtimeit 's=list(); s.extend(str(i) for i
in range(33)); x="".join(s)'
1 loops, best of 3: 99 usec per loop

but using += instead of writelines [[actually, how WOULD you express the
writelines equivalent???]] or abrogating plain-Python StringIO would not
speed up the cStringIO use (which is already just as fast as the ''.join
use).


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


Storing lines from a text file

2006-01-29 Thread bradfordh
Hello everyone.

I am not sure how hard of a question is, but I do know that I need some
help if you can give it. What I want to do is read the lines in a text
file and store each line into a variable. I believe that I can use
readlines() to read the individual lines, but how would I store each
line into a variable for further analysis? Thanks for any and all
suggestions.


-Tempo-

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


Storing lines from a text file

2006-01-29 Thread bradfordh
Hello everyone.

I am not sure how hard of a question is, but I do know that I need some
help if you can give it. What I want to do is read the lines in a text
file and store each line into a variable. I believe that I can use
readlines() to read the individual lines, but how would I store each
line into a variable for further analysis? Thanks for any and all
suggestions.


-Tempo-

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


Re: StringIO proposal: add __iadd__

2006-01-29 Thread Alex Martelli
Scott David Daniels <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> > It would be nice (in Py3k, when backwards compatibility can be broken)
> > to make the plain-named, "default" modules those coded in C, since
> > they're used more often, and find another convention to indicate pure
> > Python equivalents -- e.g., pickle/pypickle and StringIO/pyStringIO
> How about something like a package py for all such python-coded modules
> so you use py.StringIO (which I hope gets renamed to stringio in the
> Py3K shift).

Sounds good to me, indeed better than 'name mangling'!-)


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


Re: Storing lines from a text file

2006-01-29 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I am not sure how hard of a question is, but I do know that I need some
> help if you can give it. What I want to do is read the lines in a text
> file and store each line into a variable. I believe that I can use
> readlines() to read the individual lines, but how would I store each
> line into a variable for further analysis? Thanks for any and all
> suggestions.

any reason you cannot do the analysis on the list you get from readlines ?

if you insist on having the lines in individual variables, you can use straight-
forward sequence unpacking:

a, b, c, d, e = f.readlines()





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


Re: Returning a value from code string

2006-01-29 Thread Kirk McDonald
Peter Hansen wrote:
> In the specific case in question, Kirk's first post gave little or no 
> hint about how much he knew about security issues and, by asking "why?", 
> with a single word Steven hoped to learn enough to say things like "oh, 
> there's a package designed to do that which you can just plug in" or 
> "oh, it's clear you are totally new to issues of network security and 
> are about to put your foot right in it, so here's some background to 
> save you from yourself", or whatever...

Heh heh. For what it's worth, I did have a perfectly good reason for 
trying to do what might otherwise be a suicidally insane idea. On the 
other hand, I've been re-evaluating my needs, and I'll probably be 
hardcoding the more important bits of code that I was going to store in 
the database (in that pulling these things from the database whenever I 
need to use them is remarkably slow compared to letting mod_python cache 
them, and these particular functions are unlikely to ever change). If I 
do need a way to have dynamic code in the database, I've added a thing 
that just reflects POST data back to the database-stored PSP document in 
which the form was found (if the form wants it to), letting the PSP 
document deal with it. That should be adequate.

In short, I learned something about exec and namespaces that I'm not 
actually going to use. Hooray!

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


Re: Storing lines from a text file

2006-01-29 Thread bradfordh
so this:
a, b, c, d, e =f.readlines()

..this will put the first line in a, second in b, etc? How do I
accomplish this when I'm not sure how many lines there are going to be
every time? Thanks.

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


Re: Python vs C for a mail server

2006-01-29 Thread Jay Parlar
> Paul Boddie wrote:
>
>> I don't think I've ever seen anyone advocating calling a function like
>> getattr(obj "foo" + "bar")().
>
>> From Lib/compiler/visitor.py:
>
> meth = getattr(self.visitor, 'visit' + className, 0)
>
> Later on:
>
> meth(node, *args)
>
> Of course, you can drop the "visit" prefix and make the mechanism more
> predictable, but a search on the standard library for getattr produces
> a lot of evidence against your assertion.
>
I don't think you understood my assertion, then. The example that the 
original poster gave was using getattr() with a simple string ("foo" + 
"bar") for the 'name' argument, and without a default return value (as 
opposed to throwing a variable in there, or a string plus a variable 
like you did, or a default retval).

I even said you can do some "very powerful things" with getattr, by 
which I meant something exactly like you did. What did you think I 
meant by that?



Jay P.


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


Re: Storing lines from a text file

2006-01-29 Thread Kirk McDonald
[EMAIL PROTECTED] wrote:
> so this:
> a, b, c, d, e =f.readlines()
> 
> ..this will put the first line in a, second in b, etc? How do I
> accomplish this when I'm not sure how many lines there are going to be
> every time? Thanks.
> 

With a list:
http://python.org/doc/2.4.2/tut/node5.html#SECTION00514

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


instance references?

2006-01-29 Thread bytecolor
I'm working on a simple graphics package. I've got a function show()
that the user needs to call at the end of the script to actually
display the points, lines and circles that have been defined in the
script.

p1 = point(0, 0)
l1 = line(1, 3, -4, 5)
c1 = circle(-2, 3, 1)
show()

In each __init__() method of the point, line, and circle objects I add
self to a list in a separate module, then show() uses this list to
actually draw the objects. This works except:

l1 = line(point(1, 3), point(-4, 5))
c1 = circle(point(-2, 3), 1)

adds the references to the points used to define the objects to the
render list. I only want objects that have been assigned to a variable
to be rendered. (Try to ignore the function overloading.)

So how can I tell if an instance of point, line or circle has actually
been assigned to a variable?

-- 
bytecolor

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


Language Semantics: @ symbol??

2006-01-29 Thread Enigma Curry
Sorry, for the noob question, but I haven't been able to find
documentation on this matter.

I've been looking for documentation that describes what the @function()
syntax is all about.

I've seen this on a few pages, for instance:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871

and also in TurboGears:

http://www.turbogears.com/docs/wiki20/page5.html

The general format appears to be:

@somefunction()
def a_newfunction():


What does it mean and what does it do?

Thanks!

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


Re: Python loading library containing embedded python...

2006-01-29 Thread Brennus
Martin v. Löwis wrote:

>Brennus wrote:
>> I have a dll/so which embeds python. I can verify it works by
>> compiling it as an executable and adding an appropriate main.
>
>Please explain in more detail how you did the embedding. Did you
>statically link the Python interpreter into your dll/so, or did
>you use a shared one?

I compiled pythoncore.lib. I statically link this to my dll
and define Py_BUILD_CORE before including Python.h.

The only difference I can see with doing this vs linking the
python dll dynamically is that Py_IsInitialized returns true
when using the dll. This makes sense, but little else does.

>> How can I make my dll/so with embedded python support use via ctypes?
>
>Whether you can do this at all depends on the fine details of
>embedding: e.g. what operating system, how precisely did you do
>the embedding, and so on.
>
>For example, on many Unix systems, you might end up with two definitions
>of all the Python symbols, at which point it depends on the precise
>linker command line options to determine what precisely happens
>(e.g. which of the definition of the symbol is used in what place).
>
>> The dll/so must support use in processes which might contain other
>> instances of Python. I can not change that requirement. Running via
>> ctypes is an easy test of this capability (or much of it I suspect).
>
>Then your best bet is to *really* embed Python. I.e. link all symbols
>statically, preferably renaming them (if possible), and make sure that
>the resulting dll does neither reference nor expose any Python symbols.
>Given the different linkers on different systems, this is very tricky
>to implement.

For now, I am testing this in Windows with Visual Studio.

I will look into renaming the symbols, but I am not sure
I understand why this is necessary. Surely two unrelated
DLLs can exist in a process with the same function names?
If not, I am surprised this problem hasn't been seen or
even exploited by plugin competitors more often.

Most of the time Py_Initialize and Py_IsInitialized works.
High level tests with PyRun_SimpleString("") crash in any
DLL I use from ctypes, while working fine as an executable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing lines from a text file

2006-01-29 Thread bradfordh
With what kind of list? I don't see how I can do it with a list unless
I create one indefinate list and use the objects in the indefinate list
for the names of  the lists to hold the lines of text. Is that how you
are suggesting that I do it?

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


Re: Language Semantics: @ symbol??

2006-01-29 Thread Jay Parlar

Enigma Curry wrote:
>
>
> Sorry, for the noob question, but I haven't been able to find
> documentation on this matter.
>
> I've been looking for documentation that describes what the @function()
> syntax is all about.
>
> I've seen this on a few pages, for instance:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871
>
> and also in TurboGears:
>
> http://www.turbogears.com/docs/wiki20/page5.html
>
> The general format appears to be:
>
> @somefunction()
> def a_newfunction():
> 
>
> What does it mean and what does it do?
>
> Thanks!

It's called a decorator, new in Python 2.4:

http://python.org/doc/2.4.2/whatsnew/node6.html

Not sure where it lives in the official documentation right now 
though... Maybe someone else can provide that.

Jay P.

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


  1   2   >