Re: MD5 module Pythonicity

2005-10-14 Thread Fredrik Lundh
Fredrik Lundh wrote:

> Forcing every digest module to add code to cater for just one of many
> use cases is most likely a waste of time.

here's the hash API specification, btw:

http://www.python.org/peps/pep-0247.html






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


Re: MD5 module Pythonicity

2005-10-14 Thread Fredrik Lundh
Leandro Lameiro wrote:

> What's wrong in having a function like the one I said, that would
> split files for you, feed md5.update and, when it is over, return the
> digest?

Calculating the digest sum for a file on disk, without doing anything else
with that file, is a very small subset of everything you may want to use
digests for.  Forcing every digest module to add code to cater for just
one of many use cases is most likely a waste of time.

> "Although practicality beats purity."
> "Readability counts."
> "Beautiful is better than ugly."
>
> Have I got the wrong "Pythonic" definition?

You're confusing the kitchensink approach with the modular approach.
Bloated API:s are not practical, readable, nor beautiful.  Small flexible
components that can be easily combined are.





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


Re: MD5 module Pythonicity

2005-10-14 Thread Mike Meyer
Leandro Lameiro <[EMAIL PROTECTED]> writes:
> What's wrong in having a function like the one I said, that would
> split files for you, feed md5.update and, when it is over, return the
> digest?

Nothing in particular; it's just a trivial thing to write. If you add
every usefull utility function to the standard library, you wind up
with a multi-thousand page library documentation. The line has to be
drawn somewhere.

> It is easier, doesn't require MD5 objects creation, works well on
> small and big files, makes the code more readable and simple. Also,
> calculating MD5 of files seems to be a common enough task to be put in
> the library (well, at least on GNU/Linux we have one command just for
> this - md5sum)

Wanting to sum a file at the command line isn't that uncommon, so a
utility makes some sense. But how often does a program need the md5
sum of a file?  Especially compared to how often it wants to take the
md5 sum of some string that isn't in a file?

It might be worth adding. Except that md5 isn't really trusted
anymore; you really want to be using sha1 (and you presumably have an
sha1sum utility. FreeBSD has md5 and sha1 commands). But the sha
module doesn't have a file handler either.

You might try posting a patch to sourceforge, and see if it gets
accepted.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-14 Thread Peter T. Breuer
In comp.os.linux.misc Jeroen Wenting  
wrote:
> Without Microsoft 90% of us would never have seen a computer more powerful 
> than a ZX-81 and 90% of the rest of us would never have used only dumb 
> mainframe terminals.

Uh - when microsoft produced dos 1.0, or whatever it was, I was sitting
at my Sun 360 workstation (with 4M of RAM, later upgraded to 8M),
running SunOS 3.8 or thereabouts.

And a mean game of tetris it played too. Chess wasn't worth the
humiliation at level 5.

I believe every researcher in britain got one as a matter of course, but
they only replaced the perq machines that everyone had had to put up
with before then.  The vaxen running hpux or so were plentiful too, and
had fine monitors, tending more to the PC shape.  We'd made our own word
processor machines and spreadsheet automatons before that.  It didn't
take that many components, just a good engineer and a room full of
lackeys with soddering irons.  The BBC were selling kits too (what were
they?  Ataris?), not that I ever fell for that.

Maybe five years earlier I'd designed and built my own computer from
scratch using the MC 6802 chip as processor.  Somebody really should
have told me about assembler - I wrote in machine code, flashing the
code into prom with a 100ms pulse from a 16V battery.  Goodness knows
how much memory I had ...  maybe a few KB.

I think the Suns were abut $3 each when they first appeared, but
prices dropped rapidly so that  after maybe three years the standard
price was about $8000. PCs had appeared and came in at about $4000, if I
recall right, so there was a price differential but it wasn't huge,
especially when a Sun could support a whole research team via vt100
lines, and a PC was a one-person job, thanks to the o/s.


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


Re: Microsoft Hatred FAQ

2005-10-14 Thread Jim Moe
Xah Lee wrote:
> 
> Question: U.S. Judges are not morons, and quite a few others are
> not morons. They find MS guilty, so it must be true.
> 
> Answer: so did the German population thought Jews are morons by
> heritage, to the point that Jews should be exterminated from earth.
> Apparently, the entire German population cannot be morons, they must be
> right.
> 
   Extremely lame.

-- 
jmm (hyphen) list (at) sohnen-moe (dot) com
(Remove .AXSPAMGN for email)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem splitting a string

2005-10-14 Thread Mike Meyer
Robert Kern <[EMAIL PROTECTED]> writes:
> Anthony Liu wrote:
>> I have this simple string:
>> 
>> mystr = 'this_NP is_VL funny_JJ'
>> 
>> I want to split it and give me a list as
>> 
>> ['this', 'NP', 'is', 'VL', 'funny', 'JJ']
> You could use regular expressions as Jason Stitt mentions, or you could
> replace '_' with ' ' and then split.
>
> In [2]: mystr = 'this_NP is_VL funny_JJ'
>
> In [3]: mystr.replace('_', ' ').split()
> Out[3]: ['this', 'NP', 'is', 'VL', 'funny', 'JJ']

A third alternative is to split once, then split the substrings a
second time and stitch the results back together:

>>> sum([x.split('_') for x in mystr.split()], [])
['this', 'NP', 'is', 'VL', 'funny', 'JJ']

Which is probably slow. To bad extend doesn't take multiple arguments.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can module access global from __main__?

2005-10-14 Thread Tony Nelson
In article <[EMAIL PROTECTED]>,
 "Neal  Norwitz" <[EMAIL PROTECTED]> wrote:

> Steve Holden wrote:
> > Neal Becker wrote:
> > >
> > > Still curious about the answer.  If I know that I am imported from 
> > > __main__,
> > > then I can do access X as sys.modules[__main__].X.  In general, I don't
> > > know how to determine who is importing me.
> > >
> > I don't think you can without huge amounts of introspection - it's even
> > worse than the "what's the name of this object" question that seems to
> > come up regularly.
> 
> import sys
> 
> frame = sys._getframe()
> caller = frame.f_back
> print 'Called from', caller.f_code.co_filename, caller.f_lineno
> # for more info, look into the traceback module
> 
> > A module can be imported from multiple modules, and
> > you only get to execute code on the first import.
> > Even then (on the first import) I am not sure how you could introspect
> > to find the answer you want.
> 
> You can install your own __import__() hook to catch all imports.
> 
> Just because you can do something, it doesn't follow that you should do
> it, especially in this case.  Unless you really, really need these
> tricks, they shouldn't be used.

Neal, I have a similar question (in that maybe I shouldn't do 
something), and you seem to know your way around modules, so I'll just 
butt in.  If this isn't OK I'll post as a new thread.

I have written a python module that uses some C functions.  I wrote the 
module in two parts, one python, one pyrex (C).  They need to share some 
globals.  (I use pyrex to handle ref counting.  I think I'm glad I did.)

At first they just sort of mutually imported each other, and it worked 
until I put tests in the python one and set it up to run them when it 
was __main__.  This reminded me that there are also other ways modules 
can be imported under different names, so I tried a different approach.

Now I'm just shoving references to the python module's globals into the 
pyrex module (first defining them in the pyrex module).  The pyrex 
module doesn't import the python module anymore.  This also works, even 
when the python module has a different name ("__main__").  I just feel 
dirty about it.

How does one normally make a module that uses some functions in C?  Will 
that approach work with pyrex?  With globals?

TonyN.:'[EMAIL PROTECTED]
  '  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-14 Thread Jeroen Wenting

>>
>>Q: Microsoft's Operating System is used over 90% of PCs. If that's
>>not monopoly, i don't know what is.
>
> They got where they are  by CHEATING.  That is why they are evil, not
> because they have a large market share.

no, they got their by clever marketing and generally having a product that 
was easier to use for the average user than anything the competition made 
and a lot more powerful than other products created for their main target 
market.

Microsoft isn't evil, they're not a monopoly either.
If they were a monopoly they'd have 100% of the market and there'd be no 
other software manufacturers at all.
Prices would be far far higher than they are today, like they were back in 
the days before Microsoft started competing with the likes of Ashton Tate 
and WordPerfect corporation by offering similar products at 20% the price 
(which is the real reason they got to be top dog, they delivered a working 
product for a fraction of the price their competition did, and the 
competition couldn't drop their prices that much and remain profitable).

Without Microsoft 90% of us would never have seen a computer more powerful 
than a ZX-81 and 90% of the rest of us would never have used only dumb 
mainframe terminals.
IBM's prediction that there would be 5 computers (not counting game 
computers like the Comodores and Spectrums) by 2000 would likely have come 
true. 


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


Re: Straight line detection

2005-10-14 Thread Nigel Rowe
Tim Roberts wrote:

> "PyPK" <[EMAIL PROTECTED]> wrote:
>>
>>Does anyone know of a simple implementation of a straight line
>>detection algorithm something like hough or anything simpler.So
>>something like if we have a 2D arary of pixel elements representing a
>>particular Image. How can we identify lines in this Image.
>>for example:
>>
>>ary =
>>[[1,1,1,1,1],
>> [1,1,0,0,0],
>> [1,0,1,0,0],
>> [1,0,0,1,0],
>> [1,0,0,0,1]]
>>So if 'ary' represents pxl of an image which has a horizontal line(row
>>0),a vertical line(col 0) and a diagonal line(diagonal of ary). then
>>basically I want identify any horizontal or vertical or diagonal line
>>anywhere in the pxl array.
> 
> If all you want is horizontal, vertical, or 45 degree diagonal, it's
> pretty easy to do that just be checking all of the possibilities.
> 
> But what if your array is:
> 
>  [[1,1,1,1,1],
>   [1,1,1,1,1],
>   [1,1,1,1,1],
>   [1,1,1,1,1],
>   [1,1,1,1,1]]
> 
> Would you say there were 12 lines there?

Actually I'd say 24.

5 vertical, 
5 horizontal, 
7 diagonal downward to the right (lengths 2,3,4,5,4,3,2)
7 diagonal downward to the left (lengths 2,3,4,5,4,3,2)

-- 
Nigel Rowe
A pox upon the spammers that make me write my address like..
rho (snail) swiftdsl (stop) com (stop) au
-- 
http://mail.python.org/mailman/listinfo/python-list


MD5 module Pythonicity

2005-10-14 Thread Leandro Lameiro
Hi folks

Recently I have been discussing with a friend about python ease of
use, and it is really good at this. This friend needed to calculate
the MD5 hash of some files and was telling me about the MD5 module.
The way he told me and how it is described in the Python Docs, the
method to calculate hashes did not seemed very pythonic to me, but it
was certainly very simple and easy:

The method is (taken from python official documentation):

>>> import md5
>>> m = md5.new()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'

The idea to use this for files is: open file, take little chunks of
the file, call update for each one, and when you are done reading the
file, call digest. Well, OK, it is very simples and easy.
But wouldn't it be more pythonic if it did exist some kind of
md5.calculate_from_file("file") ?!
This way, you wouldn't have to split the file by yourself (this
function proposed would do this for you etc) and would make code a lot
more readable:

>>> import md5
>>> md5.calculate_from_file("/home/foo/bar.bz2")

or something like this. (Maybe passing to the md5 calculate_from_file
the open file object, instead of the string)

One alternative also shown in the documentation is to do everything at once:

>>> import md5
>>> md5.new("Nobody inspects the spammish repetition").digest()

Well, OK, this one is a bit more readable (it is not as good as I
think it could be), but has the disadvantage of having to load the
WHOLE file to memory.

What's wrong in having a function like the one I said, that would
split files for you, feed md5.update and, when it is over, return the
digest?
It is easier, doesn't require MD5 objects creation, works well on
small and big files, makes the code more readable and simple. Also,
calculating MD5 of files seems to be a common enough task to be put in
the library (well, at least on GNU/Linux we have one command just for
this - md5sum)

"Although practicality beats purity."
"Readability counts."
"Beautiful is better than ugly."

Have I got the wrong "Pythonic" definition?

--
Thanks in advance
Regards
Leandro Lameiro
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to make this code faster

2005-10-14 Thread Tony Nelson
In article <[EMAIL PROTECTED]>,
 "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

> def f(x,y):
> return math.sin(x*y) + 8 * x
> I have code like this:
> 
> def main():
> n = 2000
> a = zeros((n,n), Float)
> xcoor = arange(0,1,1/float(n))
> ycoor = arange(0,1,1/float(n))
> 
> 
> for i in range(n):
> for j in range(n):
> a[i,j] = f(xcoor[i], ycoor[j])  # f(x,y) = sin(x*y) + 8*x
> 
> print a[1000,1000]
> pass
> 
> if __name__ == '__main__':
> main()

I would guess that you are spending most of your time calculating 
sin(x*y).  To find out, just replace f(x,y) with 1, which will produce 
wrong results really fast, and see what that does to your execution time.

TonyN.:'[EMAIL PROTECTED]
  '  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyGame & Web hosts

2005-10-14 Thread Terry Hancock
On Friday 14 October 2005 11:04 pm, boyanpn wrote:
> I wonder if my web host suports python (with pygame), if I download
> game from www.pygame.org and upload it to my site, could users access
> to it with browser and play game ?

In the main, no.

PyGame is a multimedia library, using SDL to access the graphics capabilities
on a machine. It is fundamentally, a client (or standalone) application, and
does not (AFAIK) have anything to do with web services.

In order to be able to play a game "on your site" "using a browser" would
require either:

1) A very simple game that can use an HTML interface and software on your
server meant to deal with that.

2) Games that are actually implemented as Java or Javascript or some other
"applet" technology that is downloaded into their browser.  "Some other"
pretty much only applies if your users are using a plugin or have a very
nonstandard browser.  However, DO be aware that there is a version of Python
called Jython (http://www.jython.org) which would allow you to package a
Python program for use as an applet (running on Java).  The bad news is,
it won't be anything like the PyGame environment (you'd be using Java libraries,
like Swing, etc).

Or, probably more useful to you, you could just provide games that people
can download. This is what actually happens with an applet, of course, so
there's no actual saving of bandwidth by "running it on your server". What
is saved is the hassle of installing the software once it's downloaded.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Problem splitting a string

2005-10-14 Thread Robert Kern
Anthony Liu wrote:
> I have this simple string:
> 
> mystr = 'this_NP is_VL funny_JJ'
> 
> I want to split it and give me a list as
> 
> ['this', 'NP', 'is', 'VL', 'funny', 'JJ']

> I think the documentation does say that the
> separator/delimiter can be a string representing all
> delimiters we want to use.

No, it doesn't.

In [1]: str.split?
Type:   method_descriptor
Base Class: 
String Form:
Namespace:  Python builtin
Docstring:
S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the
delimiter string.  If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator.

> I do I split the string by using both ' ' and '_' as
> the delimiters at once?

You could use regular expressions as Jason Stitt mentions, or you could
replace '_' with ' ' and then split.

In [2]: mystr = 'this_NP is_VL funny_JJ'

In [3]: mystr.replace('_', ' ').split()
Out[3]: ['this', 'NP', 'is', 'VL', 'funny', 'JJ']

-- 
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: Problem splitting a string

2005-10-14 Thread Erik Max Francis
Anthony Liu wrote:

> I have this simple string:
> 
> mystr = 'this_NP is_VL funny_JJ'
> 
> I want to split it and give me a list as
> 
> ['this', 'NP', 'is', 'VL', 'funny', 'JJ']
> 
> 1. I tried mystr.split('_| '), but this gave me:
> 
> ['this_NP is_VL funny_JJ']
> 
> It is not splitted at all.

Use re.split:

 >>> re.split('_| ', s)
['this', 'NP', 'is', 'VL', 'funny', 'JJ']

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   To love without criticism is to be betrayed.
   -- Djuna Barnes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C Wrapper Function, crashing Python?

2005-10-14 Thread Tony Nelson
In article <[EMAIL PROTECTED]>,
 "Java and Swing" <[EMAIL PROTECTED]> wrote:

> one more update...
> 
> if I remove PyMem_Free and free(...) ...so no memory clean up...I can
> still only call doStuff 4 times, the 5th attemp crashes Python.
> 
> Java and Swing wrote:
> > update:
> > if I use C's free(result), free(a) free(b) instead of PyMem_Free...I
> > only get one successfuly use/call of doStuff.
> >
> > i.e.
> > // this works
> > doStuff(...)
> >
> > // python crashes here
> > doStuff(...)
> >
> > Java and Swing wrote:
> > > static PyObject *wrap_doStuff(PyObject *self, PyObject *args) {
> > >   // this will store the result in a Python object
> > >   PyObject *finalResult;
> > >
> > >   // get arguments from Python
> > >   char *result = 0;
> > >   char *in= 0;
> > >   char *aString = 0;
> > >   char *bString = 0;
> > >   MY_NUM *a;
> > >   MY_NUM *b;
> > >   int ok = PyArg_ParseTuple(args, "sss", &in, &aString, &bString);
> > >   if (!ok) return 0;
> > >
> > >   // do work to get a and b
> > >   // count - returns an int;  GetVal - returns a char *
> > >   a = GetVal(aString, count(aString, ","));
> > >   b = GetVal(bString, count(bString, ","));
> > >
> > >   // make function call, which returns a char *
> > >   result = doStuff(in, a, b);
> > >
> > >   // save result in Python string
> > >   finalResult = PyString_FromString(result);
> > >
> > >   // free memory
> > >   PyMem_Free(result);
> > >   PyMem_Free(a);
> > >   PyMem_Free(b);
> > >
> > >   // return the result as a Python string
> > >   return finalResult;
> > > }
> > >
> > > ...from python I can call this function 4 times...works fine.  WHen I
> > > call it for the fifth time python.exe crashes.  im thinking some memory
> > > problem in the wrapper function perhaps...but I am not sure.  The
> > > actually C function, doStuff can be called 5, 6,7...N times without a
> > > problem
> > > so i know its gotta be my wrapper.
> > > 
> > > Any ideas?  Thanks!
> 

I think your wrapper should look something like:

static PyObject *wrap_doStuff(PyObject *self, PyObject *args)
{
// this will store the result in a Python object
PyObject *finalResult;

// get arguments from Python
char *result = 0;
char *in= 0;
char *aString = 0;
char *bString = 0;
MY_NUM *a;
MY_NUM *b;

int ok = PyArg_ParseTuple(args, "sss", &in, &aString, &bString);
if (!ok) return 0;

// do work to get a and b
// count - returns an int;  GetVal - returns a char *
a = GetVal(aString, count(aString, ","));
b = GetVal(bString, count(bString, ","));

// make function call, which returns a char *
result = doStuff(in, a, b);

// save result in Python string
finalResult = PyString_FromString(result);

// free memory
free(result);
free(a);
free(b);

// return the result as a Python string
return finalResult;
}

You must match malloc() with free(), and PyMem_Malloc() with 
PyMem_Free().  Malloc() and free() usually crash /after/ the call that 
did the damage.  You may wish to avail yourself of your platform's 
malloc debugging facilities.

Note that I don't do this stuff in C, I do it in pyrex, and I'm new to 
it anyway, so there may still be something wrong.  Unless you are 
determined to learn how to do this in C, I think you should switch to 
pyrex.

TonyN.:'[EMAIL PROTECTED]
  '  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem splitting a string

2005-10-14 Thread Jason Stitt
On Oct 14, 2005, at 11:52 PM, Anthony Liu wrote:I have this simple string:mystr = 'this_NP is_VL funny_JJ'I want to split it and give me a list as['this', 'NP', 'is', 'VL', 'funny', 'JJ']1. I tried mystr.split('_| '), but this gave me:['this_NP is_VL funny_JJ']Try re.split, as in:import rere.split('_| ', mystr)-Jason-- 
http://mail.python.org/mailman/listinfo/python-list

Problem splitting a string

2005-10-14 Thread Anthony Liu
I have this simple string:

mystr = 'this_NP is_VL funny_JJ'

I want to split it and give me a list as

['this', 'NP', 'is', 'VL', 'funny', 'JJ']

1. I tried mystr.split('_| '), but this gave me:

['this_NP is_VL funny_JJ']

It is not splitted at all.

2. I tried mystr.split('_'), and this gave me:

['this', 'NP is', 'VL funny', 'JJ']

in which, space is not used as a delimiter.

3.  I tried mystr.split(' '), and this gave me:

['this_NP', 'is_VL', 'funny_JJ']

in which, '_' is not used as delimiter.

I think the documentation does say that the
separator/delimiter can be a string representing all
delimiters we want to use.

I do I split the string by using both ' ' and '_' as
the delimiters at once?

Thanks.






__ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing lists

2005-10-14 Thread Christian Stapfer
"jon" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> To take the heat out of the discussion:
>
> sets are blazingly fast.

I'd prefer a (however) rough characterization
of computational complexity in terms of Big-Oh
(or Big-whatever) *anytime* to marketing-type
characterizations like this one...

Regards,
Christian


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


PyGame & Web hosts

2005-10-14 Thread boyanpn
I a newbie in python so excuse me if my question sounds stupid or
something :(

I wonder if my web host suports python (with pygame), if I download
game from www.pygame.org and upload it to my site, could users access
to it with browser and play game ?

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


Re: Microsoft Hatred FAQ

2005-10-14 Thread Tim Hammerquist
["Followup-To:" header set to comp.lang.perl.misc.]

Roedy Green <[EMAIL PROTECTED]> wrote:
> "Xah Lee" <[EMAIL PROTECTED]> wrote or quoted :
> > Q: Microsoft's Operating System is used over 90% of PCs.
> > If that's not monopoly, i don't know what is.
> 
> They got where they are  by CHEATING.  That is why they are
> evil, not because they have a large market share.

Mr. Lee is a troll.  And an increasingly obscene one.

I think his mother didn't pay him enough attention.
Perhaps she locked him in the basement... and he never left?

IAC, I've had enough.  I don't killfile many people...  but Mr.
Lee seems to have gone above and beyond.  His arguments are
nothing but incendiary, and he doesn't even know Perl well
enough to bash it as he does.

*plonk*

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


Re: Reading IEEE 754 format strings directly into a floating point array

2005-10-14 Thread Ben Caradoc-Davies
Madhusudan Singh wrote:
> The values are returned as IEEE format binary floating point numbers. There
> are 4 bytes per point. Multiple points are not separated by any delimiter.
> Is it possible to read these directly into a floating point array of the
> size of the string ?

Consider using the struct module from the standard library, with format 
"f". It also allows you to specify endianness in a platform-independent 
manner, and for mixed formats, supports standard and native alignment.

http://docs.python.org/lib/module-struct.html

You have a string of length 4*n, so make a format with (for example) 
">"+"f"*n, and struct.unpack will return a tuple of length n.

For large volumes of data, the array module may be more useful (as 
someone else has already noted).

-- 
Ben Caradoc-Davies <[EMAIL PROTECTED]>
http://wintersun.org/
"Those who deny freedom to others deserve it not for themselves."
- Abraham Lincoln
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-14 Thread Keith Thompson
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> Hm... What does this have to do with Perl?
>
> Why did you post this in comp.lang.perl.misc?

He posted this in comp.lang.python, comp.lang.perl.misc,
comp.unix.programmer, comp.lang.java.programmer, *and*
comp.os.linux.misc because he's a troll.

I wish I could say that he'll go away if we ignore him.  I can say,
however, that ignoring him will minimize his impact.  In the past, his
rants have led to long rambling arguments across multiple newsgroups,
none of them relevant to any point that might be made -- which is
probably exactly what he wants.

-- 
Keith Thompson (The_Other_Keith) [EMAIL PROTECTED]  
San Diego Supercomputer Center <*>  
We must do something.  This is something.  Therefore, we must do this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: output

2005-10-14 Thread Steven D'Aprano
On Fri, 14 Oct 2005 17:48:59 -0700, Shi Mu wrote:

> After I run the following python code, I expect to have the printing such as:
> The year is 2005
> 
> However, I got something like:
> The year is 2005
> Fri Oct 14 17:43:31 2005
> Fri Oct 14 17:43:31 2005
> The year is 2005
> 
> What is the reason?
> 
> The code follows:
> 
> import time
> import now


>>> import now
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named now

Looks like your bug is in your module "now". Would you like to tell us
what is in it, or should we try to guess?

Looking at the rest of your code:


> class today(now.now):

You have a class called "now" in the module "now", and are sub-classing it
into a class called "today". I think this is bad design.

Firstly, it is recommended practice to name classes with an initial
capital letter. So you would use now.Now as the class.

Secondly, I don't feel that today is something which should be a class.
After all, there is only one thing "today". I feel that today should be a
function that returns the date of today, or maybe an instance of a date
class. Then you could have instances "yesterday", "tomorrow",
"one_week_from_last_wednesday" and so forth.

But let's continue:


> def __init__(self, y = 1970):

You are initialising an instance of "today" with a default year of 1970?
Do you have a time machine?

This suggests to me that you are actually trying to create a general date
class. Am I close?

>   now.now.__init__(self)

Remember, now is a module, now.now is a class from that module. So you
are calling the __init__ method of the now.now class with self as a
parameter. This is very confusing code. Who knows what this is doing --
not us, because you haven't shown us the code.

What are you trying to accomplish here? It almost looks like you are
trying to use the Borg design pattern, by making every instance of today
store it's data inside the superclass. Is this deliberate?


> def update(self,tt):
>   if len(tt) < 9 :
>   raise TypeError
>   if tt[0] < 1970 or tt[0] > 2038:
>   raise OverflowError
>   self.t = time.mktime(tt)
>   self(self.t)

Why are you calling self as if it were a function? Does now.now have a
__call__ method? 

> if __name__ == "__main__":
> n = today()
> print "The year is", n.year

I would guess that when you create an instance of class today, somewhere
in that mess of calling the superclass, you have a print statement that
prints the current time and date. That piece of code is being called twice.

-- 
Steven.

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


Re: deleting a parameter's name as it is passed to a function

2005-10-14 Thread Paul Rubin
"Amir  Michail" <[EMAIL PROTECTED]> writes:
> But dosomestuff can get rid of its reference before it returns (perhaps
> it has a lot more to do before it returns and so you would want to
> garbage collect the parameter object as soon as possible).

That would be so rare and weird that your best bet is to just pass a
boxed object in the odd circumstances where it will make any
difference.  Instead of dosomestuff(x), say dosomestuff([x]).  Then
dosomestuff can mutate the list:

   def dosomestuff(xl):
   x = xl.pop()
   ... do stuff with x ...
   x = None# free the reference
   ... more stuff...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading IEEE 754 format strings directly into a floating point array

2005-10-14 Thread Robert Kern
Madhusudan Singh wrote:
> I am querying an instrument in a measurement application.
> 
> The values are returned as IEEE format binary floating point numbers. There
> are 4 bytes per point. Multiple points are not separated by any delimiter.
> 
> Is it possible to read these directly into a floating point array of the
> size of the string ?
> 
> Alternatively, I could write a routine to do it, but wanted to find out if
> there was a simpler solution.

http://docs.python.org/lib/module-array.html
http://numeric.scipy.org

-- 
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: [Info] PEP 308 accepted - new conditional expressions

2005-10-14 Thread Bengt Richter
On Wed, 12 Oct 2005 02:15:40 -0400, Chris Smith <[EMAIL PROTECTED]> wrote:

>> "Sebastian" == Sebastian Bassi <[EMAIL PROTECTED]> writes:
>
>Sebastian> On 9/30/05, Reinhold Birkenfeld <[EMAIL PROTECTED]> wrote:
>>> after Guido's pronouncement yesterday, in one of the next
>>> versions of Python there will be a conditional expression with
>>> the following syntax: X if C else Y
>
>Sebastian> I don't understand why there is a new expression, if
>Sebastian> this could be accomplished with:
>
>Sebastian> if C: X else: Y
>
>Sebastian> What is the advantage with the new expression?
>
>One very frequent use case is building a string.
But what you show doesn't require choice of which to _evaluate_,
since you are merely choosing between immutable constants, and there is
no side effect or computation overhead to avoid by not evaluating
the unselected expression. So

"the answer is " + ('no', 'yes')[X==0]

would do as well.

>Instead of:
>
>if X==0:
>   filler="yes"
>else:
>   filler="no"
>return "the answer is %s" % filler
>
>
>What I really want to do is take four lines of conditional, and put
>them into one, as well as blow off dealing with a 'filler' variable:
>
>return "the answer is " + "yes" if X==0 else "no"
As has been pointed out, though legal there is some doubt as to whether
you meant what you wrote ;-)
>
>
>Or whatever the final release syntax is.
>Conditional expressions are a nice way to shim something in place, on
>an acute basis.  Chronic use of them could lead to a full-on plate of
>spaghetti, where you really wanted code.
>They can be impenitrable.  Whenever I'm dealing with them in C/C++, I
>always line the ?, the :, and the ; characters vertically, which may
>seem a bit excessive in terms of whitespace, but provides a nice
>hieroglyph over on the right side of the screen, to make things
>obvious.
>Best,
>Chris

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


SAFE CYBER SEX LESSONS

2005-10-14 Thread Sk8xHAnDiCApx69
hi there imhappily married and me and my wife are looking to cyber
-- 
http://mail.python.org/mailman/listinfo/python-list

Reading IEEE 754 format strings directly into a floating point array

2005-10-14 Thread Madhusudan Singh
I am querying an instrument in a measurement application.

The values are returned as IEEE format binary floating point numbers. There
are 4 bytes per point. Multiple points are not separated by any delimiter.

Is it possible to read these directly into a floating point array of the
size of the string ?

Alternatively, I could write a routine to do it, but wanted to find out if
there was a simpler solution.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deleting a parameter's name as it is passed to a function

2005-10-14 Thread Steven D'Aprano
On Fri, 14 Oct 2005 17:40:48 -0700, Amir  Michail wrote:

> Hi,
> 
> I think it would be useful to delete a name of a parameter object as
> the object is passed to a function:
> 
> dosomestuff(del a)

That's a horrible syntax. It would require Python to be completely
re-designed to allow statements where expressions are allowed, and it
isn't even clear what your syntax means. It looks like it means "delete
object a, and then call dosomestuff on the result returned by del".


> instead of
> 
> dosomestuff(a)
> del a

That is lovely and clear.

> The idea is to garbage collect the object as soon as possible, and this
> may be sooner than when dosomestuff returns.

What difference does that make? Why do you care when object a is garbage
collected?


-- 
Steven.

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


Re: Help with creating a dict from list and range

2005-10-14 Thread George Sakkis
"James Stroud" <[EMAIL PROTECTED]> wrote:

> Could be even simpler since enumerate creates tuples anyway:
>
> dct = dict(x for x in enumerate(description))
>
> James
>
> On Friday 14 October 2005 08:37, Steve Holden wrote:
> >  >>> dct = dict((x[1], x[0]) for x in enumerate(description))
> >  >>> dct
> >
> > {'second': 1, 'third': 2, 'first': 0}


"James Stroud" wrote

> Could be even simpler since enumerate creates tuples anyway:
>
> dct = dict(x for x in enumerate(description))
>
> James
>
> On Friday 14 October 2005 08:37, Steve Holden wrote:
> >  >>> dct = dict((x[1], x[0]) for x in enumerate(description))
> >  >>> dct
> >
> > {'second': 1, 'third': 2, 'first': 0}

Or even simplest :-)

dct = dict(enumerate(description))

George


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


Accessing Parallel Port in Python Error : Priviledged Instruction

2005-10-14 Thread [EMAIL PROTECTED]
Hello

When I use Pyparallel to access the parallel port in WinXP with Python
I get an error saying that this is a priviledged instruction

Any clue ?

Mike

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


Re: wierd threading behavior

2005-10-14 Thread Neil Hodgson
Qun Cao:

> import thread
> def main():
> thread.start_new(test.())
> 
> def test():
> print 'hello'
> 
> main()
> "
> this program doesn't print out 'hello' as it is supposed to do.
> while if I change main()

The program has exited before the thread has managed to run. It is 
undefined behaviour whether secondary threads survive main thread 
termination but it looks like they don't on your system.

Use the threading module and call join to wait for all threads to 
complete before exiting the program.

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


Re: XML dom question

2005-10-14 Thread George Sakkis
"George" <[EMAIL PROTECTED]> wrote:

> How can I do the following in python:
>
> [snipped]

In exactly the same way you could do it if you actually read the replies to the 
thread with the same
topic you posted yesterday. Duh!

George


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


Re: Microsoft Hatred FAQ

2005-10-14 Thread [EMAIL PROTECTED]
Hm... What does this have to do with Perl?

Why did you post this in comp.lang.perl.misc?

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


Re: Microsoft Hatred FAQ

2005-10-14 Thread Roedy Green
On 14 Oct 2005 19:01:42 -0700, "Xah Lee" <[EMAIL PROTECTED]> wrote or
quoted :

>
>Q: Microsoft's Operating System is used over 90% of PCs. If that's
>not monopoly, i don't know what is.

They got where they are  by CHEATING.  That is why they are evil, not
because they have a large market share.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class property

2005-10-14 Thread Bengt Richter
On Thu, 06 Oct 2005 16:09:22 +0200, Laszlo Zsolt Nagy <[EMAIL PROTECTED]> wrote:

>Peter Otten wrote:
>
>>Laszlo Zsolt Nagy wrote:
>>
>>  
>>
>>>I was trying for a while, but I could not implement a 'classproperty'
>>>function. Is it possible at all?
>>>
>>>
>>
>>You could define a "normal" property in the metaclass:
>>  
>>
>The only way I could do this is:
>
>class MyXMetaClass(type):
>_x = 0
>def get_x(cls):
>print "Getting x"
>return cls._x
>def set_x(cls,value):
>cls._x = value
>print "Set %s.x to %s" % (cls.__name__,value)
>x = property(get_x,set_x)
>
>class A(object):
>__metaclass__ = MyXMetaClass
>   
>print A.x
>A.x = 8
>
>
>Results in:
>
>Getting x
>0
>Set A.x to 8
>
>But of course this is bad because the class attribute is not stored in 
>the class. I feel it should be.
>Suppose we want to create a class property, and a class attribute; and 
>we would like the property get/set methods to use the values of the 
>class attributes.
>A real example would be a class that keeps track of its direct and 
>subclassed instances:
>
>class A(object):
>cnt = 0
>a_cnt = 0
>def __init__(self):
>A.cnt += 1
>if self.__class__ is A:
>A.a_cnt += 1
>   
>class B(A):
>pass
>   
>print A.cnt,A.a_cnt # 0,0
>b = B()
>print A.cnt,A.a_cnt # 1,0
>a = A()
>print A.cnt,A.a_cnt # 2,1
>
>But then, I may want to create read-only class property that returns the 
>cnt/a_cnt ratio.
>This now cannot be implemented with a metaclass, because the metaclass 
>cannot operate on the class attributes:
But it can install a property that can.
>
>class A(object):
>cnt = 0
>a_cnt = 0
>ratio = a_class_property_that_returns_the_cnt_per_a_cnt_ratio() # 
>def __init__(self):
>A.cnt += 1
>if self.__class__ is A:
>A.a_cnt += 1
>
>Any ideas?
>

 >>> class A(object):
 ... cnt = 0
 ... a_cnt = 0
 ... def __init__(self):
 ... A.cnt += 1
 ... if self.__class__ is A:
 ... A.a_cnt += 1
 ... class __metaclass__(type):
 ... def ratio(cls):
 ... print "Getting ratio..."
 ... return float(cls.a_cnt)/cls.cnt #
 ... ratio = property(ratio)
 ...
I inverted your ratio to lessen the probability if zero division...

 >>> class B(A): pass
 ...
 >>> A.ratio
 Getting ratio...
 Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 11, in ratio
 ZeroDivisionError: float division

Oops ;-)

 >>> A.cnt, A.a_cnt
 (0, 0)
 >>> b=B()
 >>> A.cnt, A.a_cnt
 (1, 0)
 >>> A.ratio
 Getting ratio...
 0.0
 >>> a=A()
 >>> A.ratio
 Getting ratio...
 0.5

 >>> a=A()
 >>> A.ratio
 Getting ratio...
 0.3

The old instance is no longer bound, so should it still be counted as it is?
You might want to check how to use weak references if not...

 >>> b2=B()
 >>> B.ratio
 Getting ratio...
 0.5
 >>> b3=B()
 >>> B.ratio
 Getting ratio...
 0.40002

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


Re: win32api.FindFiles Win2003, problem with Short Name

2005-10-14 Thread Neil Hodgson
Frank Borell:
> On all three types of PC/Servers they are set to 0.
> 
> For now I'll have to process this script on non 2003 servers?!?

What do you get if you call win32api.GetShortPathName on the long name?

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


Re: Class property (was: Class methods)

2005-10-14 Thread Bengt Richter
On Thu, 06 Oct 2005 11:05:10 +0200, Laszlo Zsolt Nagy <[EMAIL PROTECTED]> wrote:

>Hughes, Chad O wrote:
>
>> Is there any way to create a class method?  I can create a class 
>> variable like this:
>>
>Hmm, seeing this post, I have decided to implement a 'classproperty' 
>descriptor.
>But I could not. This is what I imagined:
>
>class A(object):
>_x = 0
>@classmethod
>def get_x(cls):
>print "Getting x..."
>return cls._x
>@classmethod
>def set_x(cls,value):
>print "Setting x..."
>cls._x = value
>x = classproperty(get_x,set_x)
>
>Usage example:
>
> >>>print A.x
>Getting x
>0
> >>>A.x = 8
>Setting x
> >>>print A.x
>Getting x
>8
>
>I was trying for a while, but I could not implement a 'classproperty' 
>function. Is it possible at all?
>Thanks,
>
>   Les
>
Using Peter's advice (not tested beyond what you see):

 >>> class A(object):
 ... _x = 0
 ... class __metaclass__(type):
 ... def get_x(cls):
 ... print "Getting x..."
 ... return cls._x
 ... def set_x(cls,value):
 ... print "Setting x..."
 ... cls._x = value
 ... x = property(get_x, set_x)
 ...
 >>> A.x
 Getting x...
 0
 >>> A.x = 8
 Setting x...
 >>> A.x
 Getting x...
 8
 >>> vars(A).items()
 [('__module__', '__main__'), ('__metaclass__', ), ('_x', 8), ('_
 _dict__', ), ('__weakref__', ), ('__doc__', None)]
 >>> A._x
 8
 >>> vars(A).keys()
 ['__module__', '__metaclass__', '_x', '__dict__', '__weakref__', '__doc__']

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


Re: Help with creating a dict from list and range

2005-10-14 Thread James Stroud
Could be even simpler since enumerate creates tuples anyway:

dct = dict(x for x in enumerate(description))

James

On Friday 14 October 2005 08:37, Steve Holden wrote:
>  >>> dct = dict((x[1], x[0]) for x in enumerate(description))
>  >>> dct
>
> {'second': 1, 'third': 2, 'first': 0}
>
> 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/

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Microsoft Hatred FAQ

2005-10-14 Thread Xah Lee
Microsoft Hatred, FAQ

Xah Lee, 20020518

Question: U.S. Judges are not morons, and quite a few others are
not morons. They find MS guilty, so it must be true.

Answer: so did the German population thought Jews are morons by
heritage, to the point that Jews should be exterminated from earth.
Apparently, the entire German population cannot be morons, they must be
right.

Judge for yourself, is a principle i abide by. And when you judge, it
is better to put some effort into it.

How much you invest in this endearvor depends on how important the
issue is to you. If you are like most people, for which the issue of
Microsoft have remote effect on your personal well-being, then you can
go out and buy a case of beer on one hand and pizza on the other, and
rap with your online confabulation buddies about how evil is MS. If you
are an author writing a book on this, then obviously its different
because your reputation and ultimately daily bread depend on what you
put down. If you are a MS competitor such as Apple or Sun, then
obviously you will see to it with as much money as you can cough out
that MS is guilty by all measures and gets put out of business. If you
are a government employee such as a judge, of course it is your
interest to please your boss, with your best accessment of the air.

When i judge things, i like to imagine things being serious, as if my
wife is a wager, my daughter is at stake, that any small factual error
or mis-judgement or misleading perspective will cause unimaginable
things to happen. Then, my opinions becomes better ones.

Q: Microsoft's Operating System is used over 90% of PCs. If that's
not monopoly, i don't know what is.

A: Now suppose there is a very ethical company E, whose products have
the best performance/price ratio, and making all the competitors
looking so majorly stupid and ultimately won over 90% of the market as
decided by consumers. Is E now a monopoly? Apparently, beer drinkers
and pizza eaters needs to study a bit on the word monopoly, from the
perspectives of language to history to law. If they have some extra
time, they can sharpen views from philosophy & logic contexts as well.

Q: What about all the people in the corporate environments who are
forced to use MS products and aren't allowed the option/choice to use
Mac/Linux/UNIX?

A: Kick your boss's ass, or, choose to work for a company who have
decisions that you liked.

Q: What about MS buying out all competitors?

A: Microsoft offered me $1 grand for saying good things about them.
They didn't put a gunpoint on my head. I CHOOSE to take the bribe.
Likewise, sold companies can and have decided what's best for them.
It's nothing like under gunpoint.

Q: Microsoft forced computer makers to not install competitor's
applications or OSes.

A: It is free country. Don't like MS this or that? Fuck MS and talk to
the Solaris or BeOS or AIX or HP-UX or Apple or OS/2 or Amiga or NeXT
or the Linuxes with their free yet fantastically easy-to-use and
network-spamming X-Windows. Bad business prospects? Then grab the
opportunity and become an entrepreneur and market your own beats-all
OS. Too difficult? Let's sue Microsoft!

Q: Microsoft distributed their Internet Explorer web browser free,
using their “monopoly” power to put Netscape out of business.

A: entirely inane coding monkeys listen: It takes huge investment to
give away a quality software free. Netscape can give away Operating
Systems free to put MS out of business too. Nobody is stopping Sun
Microsystem from giving Java free, or BeOS a browser free, or Apple to
bundle QuickTime deeply with their OS free.

Not to mention that Netscape is worse than IE in just about every
version till they become the OpenSource mozilla shit and eventually
bought out by AOL and still shit.

• Netscape struggles, announced open browser source code in 1998-01,
industry shock
http://wp.netscape.com/newsref/pr/newsrelease558.html

• Netscape browser code released in 1998-03. Mozilla FAQ.
http://mozilla.org/docs/mozilla-faq.html

• AOL buys Netscape in 1998-11 for 4.2 billion.
http://news.com.com/2100-1023-218360.html?legacy=cnet

• Jamie Zawinski, resignation and postmortem, 1999-04
http://www.jwz.org/gruntle/nomo.html

• suck.com, Greg Knauss & Terry Colon, 2000-04, Netscape 6 mockery
http://www.suck.com/daily/2000/04/10/
http://xahlee.org/UnixResource_dir/_/24,greg_knauss_netscape.zip

• Xah Lee, Netscape Crap
http://xahlee.org/Writ_dir/macos-talk/58.txt

Q: Microsoft implemented extra things to standard protocols in
their OS so that other OS makers cannot be compatible with their OS
while their OS can be compatible with all. They used this Embrace &
Extend to lock out competitors.

A: My perspective is this: suppose you are now a company who's OS sits
over 90% of computers (regardless how this come to be for the moment).
Now, lots of “standard” protocols in the industry is a result of
popularity (RFC = Really Fucking Common), and popularity resulted from
be

Re: Numeric array equivalent of index ?

2005-10-14 Thread Robert Kern
Nicolas Pernetty wrote:
> Hello,
> 
> I'm trying to find a clear and fast equivalent to the index method of
> plain python list :
> 
>>>a = [5,1,4,3,4]
>>>a.index(4)
> 
> 2
> 
> I have to use it on a Numeric array, so the best I've come up with is
> (rather ugly I think) :
> 
>>>from Numeric import array, equal, nonzero
>>>a = array([5,1,4,3,4])
>>>nonzero(equal(a,4))[0]
> 
> 2
> 
> Does someone know of a more Pythonic way ?

There's a list for Numeric. You'll get better answers there.

  http://numeric.scipy.org/

And no, no one has bothered adding a .index() equivalent for general,
unsorted arrays.

-- 
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


XML dom question

2005-10-14 Thread George
How can I do the following in python:

compare the text in the element tags  with the elements
tags in filling and if they match replace the text within the elements
tags  with the text in the matching element tag of fillin.
For example Since the text Monday in form matches the Element tag
 in fillin put maandag in the element tag  of Monday.


Kind of a Pseudo Code

 Fo information:
 get element tags for li
 get text for li


 Fi information:
 get childtags for dutchdays


 if(text for li=child tags for dutchdays):
   replace child tags for dutchdays text with text for li

Some pieces of code that I tried out but cannot put together to get the
results.

import xml.dom.minidom
from xml.dom.minidom import parseString
import xml.xpath

form="""

  My Sample Web Page  


What are the weekdays?

Monday
Tuesday
Wednesday
Thursday
Friday




"""
fillin="""

maandag
dinsdag
woensdag
donderdag
vrijdag
zaterdag
zondag

"""


fo=xml.dom.minidom.parseString(form)
fi=xml.dom.minidom.parseString(fillin)

mon=fi.getElementsByTagName('Monday')
monlist=mon[0]
m=monlist.childNodes[0]
mo=m.data
fri=fi.getElementsByTagName('Friday')
frilist=fri[0]
f=frilist.childNodes[0]
fr=f.data

for li in xml.xpath.Evaluate("//li", form_doc):
 li.normalize()
 day_text = li.childNodes[0]
 day_str = day_text.nodeValue


Thanks for the help!!

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


Capturing audio from a microphone on Mac OS X

2005-10-14 Thread Michael
Hi,


This might seem a dumb question, but every search I've done so far has come
up blank - with the possible exception of Schtoom. I've seen Schtoom that
does manage to capture audio under Mac OS X, but it's unclear whether the
audio tools it uses can be used independently of Schtoom.

So my question this: does anyone know of a library or simple approach
to capturing audio (any quality :) from a microphone on Mac OS X ?
Specifically something that works with Mac OS X 10.3, with python 2.3 .

Ideally, something like the approach that pyalsaaudio [*] takes would be
great, but at this stage I suspect that the number of available examples
out there is small, so I'm more than happy to take something and adapt it.
   [*] http://sourceforge.net/projects/pyalsaaudio/

I haven't searched for something similar under windows yet, I'm hoping
that's less problematic (famous last works).

Thanks in advance to anyone who replies,


Michael.

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


Re: deleting a parameter's name as it is passed to a function

2005-10-14 Thread Amir Michail
Paul Rubin wrote:
> "Amir  Michail" <[EMAIL PROTECTED]> writes:
> > The idea is to garbage collect the object as soon as possible, and this
> > may be sooner than when dosomestuff returns.
>
> If it's a parameter to dosomestuff, then there's still a reference
> until dosomestuff returns.  Simply getting rid of the name only frees
> a dictionary entry.

But dosomestuff can get rid of its reference before it returns (perhaps
it has a lot more to do before it returns and so you would want to
garbage collect the parameter object as soon as possible).

Amir

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


Re: deleting a parameter's name as it is passed to a function

2005-10-14 Thread Paul Rubin
"Amir  Michail" <[EMAIL PROTECTED]> writes:
> The idea is to garbage collect the object as soon as possible, and this
> may be sooner than when dosomestuff returns.

If it's a parameter to dosomestuff, then there's still a reference
until dosomestuff returns.  Simply getting rid of the name only frees
a dictionary entry.
-- 
http://mail.python.org/mailman/listinfo/python-list


output

2005-10-14 Thread Shi Mu
After I run the following python code, I expect to have the printing such as:
The year is 2005

However, I got something like:
The year is 2005
Fri Oct 14 17:43:31 2005
Fri Oct 14 17:43:31 2005
The year is 2005

What is the reason?

The code follows:

import time
import now

class today(now.now):
def __init__(self, y = 1970):
now.now.__init__(self)
def update(self,tt):
if len(tt) < 9 :
raise TypeError
if tt[0] < 1970 or tt[0] > 2038:
raise OverflowError
self.t = time.mktime(tt)
self(self.t)

if __name__ == "__main__":
n = today()
print "The year is", n.year
-- 
http://mail.python.org/mailman/listinfo/python-list


Numeric array equivalent of index ?

2005-10-14 Thread Nicolas Pernetty
Hello,

I'm trying to find a clear and fast equivalent to the index method of
plain python list :
>> a = [5,1,4,3,4]
>> a.index(4)
2

I have to use it on a Numeric array, so the best I've come up with is
(rather ugly I think) :
>> from Numeric import array, equal, nonzero
>> a = array([5,1,4,3,4])
>> nonzero(equal(a,4))[0]
2


Does someone know of a more Pythonic way ?

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


deleting a parameter's name as it is passed to a function

2005-10-14 Thread Amir Michail
Hi,

I think it would be useful to delete a name of a parameter object as
the object is passed to a function:

dosomestuff(del a)

instead of

dosomestuff(a)
del a

The idea is to garbage collect the object as soon as possible, and this
may be sooner than when dosomestuff returns.

Amir

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


Re: wierd threading behavior

2005-10-14 Thread Shitiz Bansal
seems that in the thread module, the stdout stream is captured by a single thread. Qun Cao <[EMAIL PROTECTED]> wrote:
Thanks Sam,That was a stupid typo ( yeah, I actually typed it in :), it should be(test,()).I am using python 2.4.1 in ubuntu. I do aware that threading.Thread isprefered,but I did not realize thread is deprecated. It is still a mysteriousbehavior anyhow. :)-- http://mail.python.org/mailman/listinfo/python-list
		 Yahoo! Music Unlimited - Access over 1 million songs. Try it free.-- 
http://mail.python.org/mailman/listinfo/python-list

machine-independant bench

2005-10-14 Thread Tarek Ziadé
Hi list,

I am trying to code some utilities to bench code performances, 
machine-independant,
to be able to measure the absolute cost of a piece of code.

So i came up with the pystone idea (i've been told too in fact ;)).

so I just run pystones on the test machines and use it as a ratio over
 code performance measurement. This is pretty good, but the major caveat 
is that if the CPU is busy
, it can be slower than expected.

So i've introduced a tolerance flag, (another approach than the three 
times run like hotshot does).

Any comment ?

Any alternatives to pystone in mind ?

Tarek

-- 
Tarek Ziadé | Nuxeo R&D (Paris, France)
CPS Plateform : http://www.cps-project.org
mail: tziade at nuxeo.com | tel: +33 (0) 6 30 37 02 63
You need Zope 3 - http://www.z3lab.org/

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


Re: How to get a raised exception from other thread

2005-10-14 Thread Shitiz Bansal


Threads can share the same memory space.
Hence a very neat way to achieve the objective.
 
> For example:> > ---> programA.py> ---> > import programB
Exception=0;
> thread = programB.MakeThread()> thread.start()
if (Exception):
  raise SomeException()
> ---> programB.py> ---> import threading, time> > class SomeException(Exception):> pass> > class MakeThread(threading.Thread):> def __init__(self):> threading.Thread.__init__(self)> > def run(self):> i = 0> while 1:> print i> i += 1> time.sleep(1) #wait a second to continue> if i>10: omit this ->raise SomeException()
instead:
 
if i>10:
Exception=1 or whatever> 
Sounds cool?
 
shitizJeremy Moles <[EMAIL PROTECTED]> wrote:
On non-Windows system there are a ton of ways to do it--this is almost awhole field unto itself. :) (D-BUS, fifos, sockets, shmfs, etc.) InWindows, I wouldn't have a clue. I guess this is a hard question to answer without a bit moreinformation. :)On Fri, 2005-10-14 at 14:45 -0700, dcrespo wrote:> Hi all,> > How can I get a raised exception from other thread that is in an> imported module?> > For example:> > ---> programA.py> ---> > import programB> > thread = programB.MakeThread()> thread.start()> > ---> programB.py> ---> import threading, time> > class SomeException(Exception):> pass> > class MakeThread(threading.Thread):>!
 ; def
 __init__(self):> threading.Thread.__init__(self)> > def run(self):> i = 0> while 1:> print i> i += 1> time.sleep(1) #wait a second to continue> if i>10:> raise SomeException()> > > Thanks> > Daniel> -- http://mail.python.org/mailman/listinfo/python-list
		 Yahoo! Music Unlimited - Access over 1 million songs. Try it free.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: updating local()

2005-10-14 Thread Bengt Richter
On Thu, 06 Oct 2005 07:15:12 -0700, Robert Kern <[EMAIL PROTECTED]> wrote:

>Flavio wrote:
>> Ok, its not thousands, but more like dozens of variables...
>> I am reading a large form from the web which returns a lot of values.
>> (I am Using cherrypy)
>> 
>> I know I could pass these variables around as:
>> 
>> def some_function(**variables):
>> ...
>> 
>> some_function(**variables)
>> 
>> but its a pain in the neck to have to refer to them as
>> variables['whatever']...
>> 
>> dont you think? 
>
>Use a Bunch.
>
>class Bunch(dict):
>def __init__(self, *args, **kwds):
>dict.__init__(self, *args, **kwds)
>self.__dict__ = self
>
>--
Or use a version-sensitive byte-code hack to set some preset locals before 
executing,
either with one-time presets via normal decorator, e.g.,

 >>> from ut.presets import presets
 >>> @presets(x=111, y=222, z='zee')
 ... def foo():
 ... return locals()
 ...
 >>> foo()
 {'y': 222, 'x': 111, 'z': 'zee'}

Or the same, just using a predefined dict instead of the keyword format:

 >>> e = {'a':0, 'b':1}
 >>> @presets(**e)
 ... def foo():
 ... return locals()
 ...
 >>> foo()
 {'a': 0, 'b': 1}

What happened to foo viat the decoration:
 >>> import dis
 >>> dis.dis(foo)
   1   0 LOAD_CONST   1 ((0, 1))
   3 UNPACK_SEQUENCE  2
   6 STORE_FAST   0 (a)
   9 STORE_FAST   1 (b)

   3  12 LOAD_GLOBAL  0 (locals)
  15 CALL_FUNCTION0
  18 RETURN_VALUE

To mess with the same base function with different presets more dynamically,
use the explicit way of calling the decorator:

The base function:

 >>> def bar(x, y=123):
 ...return locals()
 ...

decorate and invoke on the fly with particular presets:

 >>> presets(**e)(bar)('exx')
 {'a': 0, 'y': 123, 'b': 1, 'x': 'exx'}

The keyword way:
 >>> presets(hey='there')(bar)('exx')
 {'y': 123, 'x': 'exx', 'hey': 'there'}

BTW, @presets does not change the signature of the function whose selected 
locals
are being preset from the decoration-time-generated constant, e.g.,

 >>> presets(hey='there')(bar)()
 Traceback (most recent call last):
   File "", line 1, in ?
 TypeError: bar() takes at least 1 argument (0 given)
 >>> presets(hey='there')(bar)('exx', 'wye')
 {'y': 'wye', 'x': 'exx', 'hey': 'there'}
 >>> presets(hey='there')(bar)('exx', 'wye', 'zee')
 Traceback (most recent call last):
   File "", line 1, in ?
 TypeError: bar() takes at most 2 arguments (3 given)

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


Re: wierd threading behavior

2005-10-14 Thread Qun Cao
Thanks Sam,
That was a stupid typo ( yeah, I actually typed it in :), it should be
(test,()).
I am using python 2.4.1 in ubuntu.  I do aware that threading.Thread is
prefered,
but I did not realize thread is deprecated.  It is still a mysterious
behavior anyhow. :)

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


Re: wierd threading behavior

2005-10-14 Thread Sam Pointon
thread is a low-level threading module, and start_new is deprecated.
Aside from that, thread.start_new(test.()) is syntaxically wrong (a
pair of brackets can't follow a dot). However, your example does work
for me once I fix the syntax, and it prints hello but then hangs. I
can't explain the other results, though - possibly undefined behaviour
or more likely me not having much experience with the low-level thread
interface.

Use threading instead, like so:

import threading

def test():
print 'Test successful!'

def main():
thread = threading.Thread(target = test)
thread.start()

main()

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


Re: UI toolkits for Python

2005-10-14 Thread Claudio Grondi

"Kenneth McDonald" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]
> Thanks for reminding me of Gtk. OK, add that to the list.
>
> The Web Browser interface is good for simple things, and will get better
> with CSS2's adoption, but they still don't have a good way for important
> things like interactive styled text, key bindings, etc. Good for
> simple things
> (for which I use them), not for more complex stuff.

I don't fully understand your attitude here. The Web Browser interface has
all I can imagine is required for a GUI, so what is missing when you
consider, that you can generate custom images on the fly on the server and
let the user shape the page without requesting CPU power from the server
using JavaScript.
I don't even name here the not really beeing itegral part of Internet
Browsers JavaApplets and any other kind of plugin stuff.
The only issue I can see with this approach is the speed of responding to
user interactions, but for really optimize this one needs a compiled
language anyway.
What is that complex, that it can't be solved using an Internet Browser as a
GUI?
Do I miss here something?

Claudio



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


Re: threading/forking and IPC

2005-10-14 Thread Qun Cao
Thanks David, 
This seems like the exact thing I am looking for!

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


wierd threading behavior

2005-10-14 Thread Qun Cao
Hello,

I am just starting to play threading in python, here is a really
interesting problem I am very curious about:
"
import thread
def main():
thread.start_new(test.())

def test():
print 'hello'

main()
"
this program doesn't print out 'hello' as it is supposed to do.
while if I change main() into :
"
def main():
while 1:
thread.start_new(test.())
"
It goes on to print 'hello' forever.

while if I use:
"
def main():
for i in range(5):
print i
thread.start_new(test.())
"
It prints out 1,2,3,4,5 in main(), but still doesn't print out anything
from test()!

This is really wierd behavior for me, I am sure it's just something
simple&stupid, please enlighten me! 

Thanks, 
qun

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


Re: Best way to handle cgi sessions

2005-10-14 Thread Christoph Haas
On Friday 14 October 2005 21:22, Derek Perriero wrote:
> What would be the best way to create a cgi session that contains the
> basic elements of a cookie and can also hold secure data, such as a
> username/password. [...]

Said. Done. I just tidied up a module we will be using for a web site
here. It uses the promised session-cookie handling (with a lot of security
checks) and a MySQL database backend. I tried to document as well as 
possible
so I hope it will even help you if you use it or not. To try it out just
grab the two files from http://workaround.org/pysessions/ and copy them 
into a
cgi-bin/ directory. Create a database and the two tables following the
scheme described on top of the MySessions.py module. Then access the
/cgi-bin/mypage CGI. Hope to have helped.

Everyone:
This is my first "bigger" Python script. I would really like to hear 
comments
on it. If it's deemed to be decent I could use some help making it a 
package
that can be used by others as well. There is probably a bit of perlishness
that I'd like to get rid of to make it look more snake-like.

Regards
 Christoph
-- 
~
~
".signature" [Modified] 1 line --100%--1,48 All

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


Re: object inheritance and default values

2005-10-14 Thread Ron Adam
George Sakkis wrote:
> "Ron Adam" <[EMAIL PROTECTED]> wrote:
> 
> 
>>I'm trying to implement simple svg style colored complex objects in
>>tkinter and want to be able to inherit default values from other
>>previously defined objects.
>>
>>I want to something roughly similar to ...
>>
>>class shape(object):
>> def __init__(self, **kwds):
>>  # set a bunch of general defaults here.
>>  self.__dict__.update(kwds)
>>def draw(self, x=0, y=0, scale=1.0):
>>  # draw the object
>>
>>hello = shape(text='hello')
>>redhello = hello(color='red')
>>largeredhello = redhello(size=100)
>>largeredhiya = largeredhello(text='Hiya!')
>>largeredhiya.draw(c, 20, 50)
>>
>>
>>I think this will need to require __new__ or some other way to do it.
>>But I'm not use how to get this kind of behavior.  Maybe the simplest
>>way is to call a method.
>>
>>redhello = hello.makenew( color='red' )
> 
> 
> Just name it '__call__' instead of makenew and you have the syntax sugar you 
> want:
> 
> def __call__(self, **kwds):
> new = self.__class__(**self.__dict__)
> new.__dict__.update(kwds)
> return new
> 
> Personally I would prefer an explicit method name, e.g. 'copy'; hiding the 
> fact that 'shape' is a
> class while the rest are instances is likely to cause more trouble than it's 
> worth.
> 
> George

Just got it to work with __call__ as a matter of fact.  ;-)

 def __call__(self,**kwds):
 for key in self.__dict__:
 if key not in kwds:
 kwds[key] = self.__dict__[key]
 return shape(**kwds)

The purpose having the objects not call the methods explicityly in this 
case is to simplify the data structure in a way that it doesn't care. 
The point is to create as much consistancy in the data structure as 
possible without having to special case some objects as base objects, 
and some as instances.

 # Triangle
 triangle = shape( obj='regpolygon',
   points=getrpoly(3),
   fill='grey',
   size=75
   )

 # Text
 text = shape( obj='text', fill='black', size=10 )

 # CAUTION ICON
 caution = group( triangle(x=6, y=5),
  triangle(fill='yellow'),
  text( text='!',
x=39, y=32, size=35,
font='times', style='bold' )
  )

I can use a shape() in the group exactly like triangle(), or text(). 
They are all the same thing to group. It's just a matter of what the 
defaults are.  This keeps things very simple.  ;-)

Then when it needs to be drawn...

 caution.draw(canvas, x, y, scale)

I still need to work on reusing and nesting groups and having them set 
default values. Maybe I need to make group a sub shape which contains a 
list of shapes, etc...

This is another work it out as I go project. ;-)

Cheers,
Ron























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


Re: How to get a raised exception from other thread

2005-10-14 Thread Jeremy Moles
On non-Windows system there are a ton of ways to do it--this is almost a
whole field unto itself. :) (D-BUS, fifos, sockets, shmfs, etc.) In
Windows, I wouldn't have a clue. 

I guess this is a hard question to answer without a bit more
information. :)

On Fri, 2005-10-14 at 14:45 -0700, dcrespo wrote:
> Hi all,
> 
> How can I get a raised exception from other thread that is in an
> imported module?
> 
> For example:
> 
> ---
> programA.py
> ---
> 
> import programB
> 
> thread = programB.MakeThread()
> thread.start()
> 
> ---
> programB.py
> ---
> import threading, time
> 
> class SomeException(Exception):
> pass
> 
> class MakeThread(threading.Thread):
> def __init__(self):
> threading.Thread.__init__(self)
> 
> def run(self):
> i = 0
> while 1:
> print i
> i += 1
> time.sleep(1) #wait a second to continue
> if i>10:
> raise SomeException()
> 
> 
> Thanks
> 
> Daniel
> 

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


Re: Function to execute only once

2005-10-14 Thread George Sakkis
"snoe" <[EMAIL PROTECTED]> wrote:

> I've been seeing alot about decorators and closures lately and my
> initial thought was that this would be a good place to use them instead
> of wrapping it around a class. That was my initial thought :) What I
> came up with was this:

Apparently you're not the first to think of it:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425445.

George


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


Re: Yes, this is a python question, and a serious one at that (moving to Win XP)

2005-10-14 Thread Fernando Perez
> Kenneth McDonald a écrit :
>> For unfortunate reasons, I'm considering switching back to Win XP  (from
>> OS X) as my "main" system. Windows has so many annoyances that  I can
>> only compare it to driving in the Bay Area at rush hour (OS X  is like
>> driving in Portland at rush hour--not as bad, but getting  there), but
>> there are really only a couple of things that are really,  absolutely
>> preventing me from making the switch. Number one is the  lack of a
>> decent command line and command-line environment, and I'm  wondering
>> (hoping) if perhaps someone has written a "Python shell"-- something
>> that will look like a regular shell, let users type in  commands, maybe
>> have some of the nice features of bash etc. like tab  completion, etc,
>> and will then execute an underlying python script  when the command is
>> entered. I'm not thinking of IDLE, but something  that is really aimed
>> more at being a system terminal, not a Python- specific terminal.
>> 
>> Yes, I know that Cygwin is out there, but last I looked, they still
>> went through the Win command-line window, which imposes a lot of
>> restrictions.

You can look at ipython: http://ipython.scipy.org.  Its 'pysh' profile does
much of what you describe, and has a dedicated following of win32 users
precisely for your usage case.  It gets installed to your start menu under
win32 as a separate entry from the 'raw' ipython.

Stop by the users list if you have further questions.

Cheers,

f

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

Re: confusion between global names and instantiated object variable names

2005-10-14 Thread Alex Martelli
wanwan <[EMAIL PROTECTED]> wrote:
   ...
> when I run my example, an error shows:
> "NameError: global name'menubar' is not defined"
> 
> I wonder why it doesn't work.  Isn't that the way to define an object
> variable?  

The code you posted should not trigger this error.  Most likely problem:
you have typed a comma where you meant to type a dot, for example
instead of self.menubar you wrote self,menubar somewhere -- it's a hard
error to spot with certain fonts.


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


How to get a raised exception from other thread

2005-10-14 Thread dcrespo
Hi all,

How can I get a raised exception from other thread that is in an
imported module?

For example:

---
programA.py
---

import programB

thread = programB.MakeThread()
thread.start()

---
programB.py
---
import threading, time

class SomeException(Exception):
pass

class MakeThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)

def run(self):
i = 0
while 1:
print i
i += 1
time.sleep(1) #wait a second to continue
if i>10:
raise SomeException()


Thanks

Daniel

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


Re: array subset could be improved? -repost ;)

2005-10-14 Thread Fernando Perez
Jim O'D wrote:

> Hi all
> 
> I have an array a=array([2,3,-1]).
> 
> I want to extract an array with all the elements of a that are less than 0.

Numeric is currently changing into the new scipy core.  If you are willing to
play with beta code, get it here:

http://numeric.scipy.org

if not, wait a little for an official release.

With the new numeric, you'll be able to do:

negatives = a[a<0]

Cheers,

f

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


Re: confusion between global names and instantiated object variable names

2005-10-14 Thread wanwan
oops, of course.

Very careless mistake.

thx

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


Re: Python's Performance

2005-10-14 Thread Kenneth McDonald
Um, sorry, but this isn't correct.Although there might be a slight bit of gray area, the simple difference between compiled and interpreted languages is that compiled languages produce a binary consisting of bytes that mean something specific to the CPU of the computer the program is running on. The program is executed pretty much by just sending those bytes to the CPU.In an interpreted language, the "binary" (whether it be a straight text file or a bytecode file that has been produced from a text file) is, at runtime, processed by another program which _does_ consist of the bytes the CPU understands directly. Interpreted languages put an extra layer of software between the executable and the program.In practical terms, there are three differences:1) Interpreted language programs are typically much easier to transfer between machines (not necessarily between operating systems).2) Compiled languages typically have the potential (depending how much work goes into the compiler, amongst other things) to be _far_ faster than interpreted languages.3) Compiled languages require an often very painful, ugly compilation step to produce a binary. In interpreted languages (that produce bytecode), this phase is usually quite a bit easier, if not invisible.Yes, a language can have both an interpreter and a compiler, but almost always one of those plays a trivial role in the use of the language, because it is usually very difficult to get the semantics of the two to match and at the same time produce enough of a benefit to make the effort worthwhile. KenOn 14-Oct-05, at 9:29 AM, Alex Stapleton wrote:You can see that the entire, interpreted vs compiled debate is   utterly meaningless and that only implementation specific details   actually matter. e.g. Java is native if you compile it with GCJ. x86   is interpreted if you run it under a VM like VirtualPC. -- 
http://mail.python.org/mailman/listinfo/python-list

A way to set levels of access to users

2005-10-14 Thread dcrespo
Hi all,

I have this table on a database:

Table: user

coduser | username | password | securitylevel
   1| fcumana  || 0123456789qwe

where "securitylevel" is a string where the presence of each character
is a permited key for running certain functions.

For example:

functions.py
-
securitylevel=6
def function1():
print "This is the function 'function1'"

...and/or other functions
-

Because securitylevel=6 exists in securitylevel in the database, the
user running it is allowed to access.

The lack here is that if there's a lot of functions and users, and I
want to enable certain users to access certain functions, then, it will
get confusing for maintain it.

Any help?

Daniel

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


Re: threading/forking and IPC

2005-10-14 Thread David Wahler

Sophia Cao wrote:
> Hello,
>
> I am seeking a python solution for my project.  I am trying to
> implement an architecture where there is a server who receives incoming
> messages from several clients, then those messages need to be written
> to a MySQL database.  To avoid too many connections to the database, I
> plan to save the incoming messages into a queue, while use a seperate
> process/thread to constantly monitoring the queue and storing the
> messages to the database.  I am not sure wheather I should use
> threading or forking and how to implement the sharing of this message
> queue.
>
> Thanks a lot for any advice.

If you want to have a shared queue, it's much easier and simpler to use
threading, as it allows you to share data structures between threads.
Python already has a multithreaded queue class -- see
http://docs.python.org/lib/module-Queue.html. Just create a global
Queue object or pass each thread a reference to it, and they can all
share it.

-- David

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


Re: confusion between global names and instantiated object variable names

2005-10-14 Thread Piet van Oostrum
> "wanwan" <[EMAIL PROTECTED]> (w) wrote:

>w> I'm trying to make a GUI, but for some of the instantiated object
>w> variable names, the interpreter is looking at them as global names.
>w> Here is an example of what I did:


>w> class mygui:


>w> def __init__(self, root):

>w> self.menubar = Menu(root)

>w> # Game Menu
>w> self.menu1 = Menu(self.menubar, tearoff=0)
>w> self.menu1.add_command(label="Open File", command=donothing)
>w> self.menu1.add_separator()
>w> self.menu1.add_command(label="Exit", command=root.quit)
>w> self.menubar.add_cascade(label="File", menu=self.menu1)

>w> # ignoring the rest of the program  ...


>w> when I run my example, an error shows:
>w> "NameError: global name'menubar' is not defined"

If it talks about global name, it can't be self.menubar or
anything.menubar. So there must be a soloist menubar reference somewhere.
Doesn't it tell you the line number?
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function to execute only once

2005-10-14 Thread Paul Rubin
"snoe" <[EMAIL PROTECTED]> writes:
> Also why is it if I set tmp as a global and don't pass it as a
> paremeter to the various functions as per the OP that I get an
> "UnboundLocalError: local variable 'tmp' referenced before assignment"?

If you don't declare it as a global, and if you try to assign a value
to it, then Python thinks it's a local.  If you only refer to it and
never assign it, Python decides it's global.  Python is weird that
way.  One consequence is that if it's local to some outer scope, then
it's neither global nor local to your function, so there's no way to
assign to it.

I think Pythonic style is to not do complex things with closures,
but to use class instances instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: KeyboardInterrupt being lost?

2005-10-14 Thread David Wahler
Operation Latte Thunder wrote:
> I have a simple test proggie that isn't behaving like I expect ( found
> below ).  The script will infinitely run ( as expected ), but seems to
> completely ignore control-C's.  Shouldn't the interpreter pass along
> KeyboardInterrupts and break out of the while loop, or am I missing
> something?
>
> Using python 2.4.2 on linux ( if it matters )
>
> -- Script Below --
>
> import threading, traceback, time
>
> class TestThread ( threading.Thread ):
> def __init__ ( self ):
> threading.Thread.__init__ ( self )
> def run ( self ):
> print "Starting..."
> while True:
> time.sleep ( 1 )
> return
>
> if __name__ == '__main__':
> test = TestThread ( )
> test.start()
> print "Started..."
> test.join()
>
>
> --
> chris

Chris,

Thread.join() is implemented using a lock, and the acquisition of a
lock is uninterruptible. (See
http://docs.python.org/lib/module-thread.html) Therefore, your main
thread will block until the other thread terminates or the process is
forcibly killed. Even if it could be interrupted, I don't think there's
any way to raise that exception in the other thread. (Python's
threading support leaves something to be desired when compared to, say,
Java.)

-- David

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


threading/forking and IPC

2005-10-14 Thread Sophia Cao
Hello,

I am seeking a python solution for my project.  I am trying to
implement an architecture where there is a server who receives incoming
messages from several clients, then those messages need to be written
to a MySQL database.  To avoid too many connections to the database, I
plan to save the incoming messages into a queue, while use a seperate
process/thread to constantly monitoring the queue and storing the
messages to the database.  I am not sure wheather I should use
threading or forking and how to implement the sharing of this message
queue. 

Thanks a lot for any advice.

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


Re: Function to execute only once

2005-10-14 Thread snoe
The problem seemed to be because I was rebinding result inside
executor. Can someone explain why it works below but not in the first
one?

Also why is it if I set tmp as a global and don't pass it as a
paremeter to the various functions as per the OP that I get an
"UnboundLocalError: local variable 'tmp' referenced before assignment"?

def execute_once(fn):
print "in execute_once"
result = {}
def executor(*args, **kwargs):
if fn not in result:
result[fn] = fn(*args, **kwargs)
return result[fn]
return executor

@execute_once
def execute(tmp):
print "in execute"
tmp = tmp+1
return tmp

def func1(tmp):
return execute(tmp)

def func2(tmp):
return execute(tmp)

tmp = 0
print 'init tmp:', tmp
tmp = func1(tmp)
print 'ran func1 tmp:', tmp
tmp = func2(tmp)
print 'ran func2 tmp:', tmp
tmp = func1(tmp)
print 'ran func1 tmp:', tmp

OUTPUT:
in execute_once
init tmp: 0
in execute
ran func1 tmp: 1
ran func2 tmp: 1
ran func1 tmp: 1

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


Re: MS Word Outline -> reStructuredText script?

2005-10-14 Thread Jim
I'll look into that.  I also found that Open Office can read the .doc
file and then saveAs a DocBook xml file.  I think DocUtils can parse
and write both DocBook and reStructured text, but It'll take me some
time to experiment with it.

David Mertz has an article that shows reSt -> DocBook, I just need to
do the opposite.

http://www-128.ibm.com/developerworks/library/x-matters24/?ca=dnt-45

-Jim

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


confusion between global names and instantiated object variable names

2005-10-14 Thread wanwan
I'm trying to make a GUI, but for some of the instantiated object
variable names, the interpreter is looking at them as global names.
Here is an example of what I did:


class mygui:


def __init__(self, root):

self.menubar = Menu(root)

# Game Menu
self.menu1 = Menu(self.menubar, tearoff=0)
self.menu1.add_command(label="Open File", command=donothing)
self.menu1.add_separator()
self.menu1.add_command(label="Exit", command=root.quit)
self.menubar.add_cascade(label="File", menu=self.menu1)

# ignoring the rest of the program  ...


when I run my example, an error shows:
"NameError: global name'menubar' is not defined"

I wonder why it doesn't work.  Isn't that the way to define an object
variable?  

Any response would be appreciated.

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


Re: [PIL]: Question On Changing Colour

2005-10-14 Thread Scott David Daniels

Try this:
 >>> import colorsys as cs
 >>> grey = (.7, .7, .7)
 >>> blue = (0., 0., 1.)
 >>> hsv_grey = cs.rgb_to_hsv(*grey)
 >>> hsv_blue = cs.rgb_to_hsv(*blue)
 >>> hsv_grey
(0.0, 0.0, 0.69996)
 >>> hsv_blue
(0.3, 1.0, 1.0)

The problem is that the saturation of the grey is 0.  There
is no Hue to anything between black and white.  Maybe you want
something like:

def apply_hue(color, rgb):
 hue, _saturation, _value = cs.rgb_to_hsv(*color)
 _hue, saturation, value = cs.rgb_to_hsv(*rgb)
 return cs.hsv_to_rgb(hue, max(.1, saturation), value)

Or:

def apply_hs(color, rgb):
 hue, saturation, value = cs.rgb_to_hsv(*color)
 _hue, _saturation, value = cs.rgb_to_hsv(*rgb)
 return cs.hsv_to_rgb(hue, saturation, value)


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


Re: Best way to handle cgi sessions

2005-10-14 Thread Christoph Haas
On Friday 14 October 2005 21:22, Derek Perriero wrote:
> What would be the best way to create a cgi session that contains the
> basic elements of a cookie and can also hold secure data, such as a
> username/password. I've explored the possibilities of using SmartCookie,
> but that doesn't encrypt my parameters.

Encrypting the parameters is probably not the best way. Usually you store
the information you need in your own database and just pass the client
(web browser/user) a handle (session ID). That way you temporarily identify
the user through the session ID but can store data in your database that 
the
user cannot even see.

There are a few things you need to take care of like:
- only pass a new session cookie if necessary
  (otherwise the user may be prompted to accept the same cookie time and
  again)
- expire the session if the user hasn't been using it
- check if the session ID fits the IP address you recorded
- create unique session IDs

A link from my list of bookmarks about session handling:
http://starship.python.net/~davem/cgifaq/faqw.cgi?req=show&file=faq02.011.htp

We have recently developed such a session handler for a Debian-related web
site which uses a MySQL table to store session information. If there is
interest I'll tidy it up a bit and make it publicly available.

Cheers
 Christoph
-- 
~
~
".signature" [Modified] 1 line --100%--1,48 All

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


Re: Function to execute only once

2005-10-14 Thread snoe
I've been seeing alot about decorators and closures lately and my
initial thought was that this would be a good place to use them instead
of wrapping it around a class. That was my initial thought :) What I
came up with was this:
def execute_once(fn):
 result = None
 def executor(*args, **kwargs):
 if not result:
result = fn(*args, **kwargs)
 return result
 return executor

@execute_once
def execute(tmp):
tmp = tmp+1
return tmp

def func1(tmp):
execute(tmp)

def func2(tmp):
execute(tmp)

tmp=0
print 'init tmp:', tmp
func1(tmp)
print 'ran func1 tmp:', tmp
func2(tmp)
print 'ran func2 tmp:', tmp

It gives the following error:
init tmp: 0
Traceback (most recent call last):
  File "C:\Download\test.py", line 26, in ?
func1(tmp)
  File "C:\Download\test.py", line 19, in func1
execute(tmp)
  File "C:\Download\test.py", line 5, in executor
if not result:
UnboundLocalError: local variable 'result' referenced before assignment

Makes sense to me, except I expected some closure 'magic'. I thought
that when I wrapped executor() inside execute_once() the name result
would be available to executor(). What am I missing here (I expect the
answer to be 'alot') but is this type of solution valid for this
problem?

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


Re: MS Word Outline -> reStructuredText script?

2005-10-14 Thread Graham Fawcett
Jim wrote:
> Hi,
>
> I'm using reStructuredText as a format for some group documentation,
> and often my co-workers take notes during meetings in Word's outline
> mode.  Does anyone already have a python script that will convert from
> Word (or the Open Office file format version of a word document) to
> reStructured Text?

I don't have a script; but if you have to roll your own, you might
consider having your colleagues save their Word documents in XML
format. Office 2003, and perhaps slightly earlier versions, do this.
Then you can "simply" parse the XML and transform it into anything you
like, including a reST document.

If you cannot convince them, then you could also have your script
automate Word, via win32com.client.Dispatch('Word.Application'), and do
the save-as-XML yourself before parsing the generated XML. At the end
of the day, I think this would be easier than, e.g., trying to use
win32com to traverse the document's object model.

Graham

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


Re: object inheritance and default values

2005-10-14 Thread Kay Schluehr

George Sakkis wrote:
> "Ron Adam" <[EMAIL PROTECTED]> wrote:
>
> > I'm trying to implement simple svg style colored complex objects in
> > tkinter and want to be able to inherit default values from other
> > previously defined objects.
> >
> > I want to something roughly similar to ...
> >
> > class shape(object):
> >  def __init__(self, **kwds):
> >   # set a bunch of general defaults here.
> >   self.__dict__.update(kwds)
> > def draw(self, x=0, y=0, scale=1.0):
> >   # draw the object
> >
> > hello = shape(text='hello')
> > redhello = hello(color='red')
> > largeredhello = redhello(size=100)
> > largeredhiya = largeredhello(text='Hiya!')
> > largeredhiya.draw(c, 20, 50)
> >
> >
> > I think this will need to require __new__ or some other way to do it.
> > But I'm not use how to get this kind of behavior.  Maybe the simplest
> > way is to call a method.
> >
> > redhello = hello.makenew( color='red' )
>
> Just name it '__call__' instead of makenew and you have the syntax sugar you 
> want:
>
> def __call__(self, **kwds):
> new = self.__class__(**self.__dict__)
> new.__dict__.update(kwds)
> return new
>
> Personally I would prefer an explicit method name, e.g. 'copy'; hiding the 
> fact that 'shape' is a
> class while the rest are instances is likely to cause more trouble than it's 
> worth.
>
> George

Symmetry can be achieved by making shape a factory function of Shape
objects while those Shape objects are factory functions of other Shape
objects by means of __call__:

def shape(**kwds):
class Shape(object):
  def __init__(self,**kwds):
  self.__dict__.update(kwds)

  def __call__(self, **kwds):
  new = self.__class__(**self.__dict__)
  new.__dict__.update(kwds)
  return new

return Shape(**kwds)

Kay

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


KeyboardInterrupt being lost?

2005-10-14 Thread Operation Latte Thunder
I have a simple test proggie that isn't behaving like I expect ( found
below ).  The script will infinitely run ( as expected ), but seems to
completely ignore control-C's.  Shouldn't the interpreter pass along
KeyboardInterrupts and break out of the while loop, or am I missing
something?

Using python 2.4.2 on linux ( if it matters )

-- Script Below --

import threading, traceback, time

class TestThread ( threading.Thread ):
def __init__ ( self ):
threading.Thread.__init__ ( self )
def run ( self ):
print "Starting..."
while True:
time.sleep ( 1 )
return

if __name__ == '__main__':
test = TestThread ( )
test.start()
print "Started..."
test.join()


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


Re: Inheritance...

2005-10-14 Thread Duncan Booth
KraftDiner wrote:

> I have a base class
> 
> class geometry(object):
>def __init__(self):
>   self.blue = 1
>   self.red = 2
>def render(self):
>   pass
> 
> class square(geometry):
> def __init__(self):
>  super(square, self).__init__()
>def render(self)
>   print 'square'
> 
> class circle(geometry):
> def __init__(self):
>  super(square, self).__init__()
>def render(self)
>   print 'square'
> 
> objLst = []
> objLst.append(square())
> objLst.append(circle())
> 
> for obj in objLst:
>obj.render()
> print obj.blue
> 
> What is wrong with this... I will not print blue... (1)
> 
> 
a) No need to post your question twice.

b) When posting your code, you should post the actual code you have a 
problem with. The code you posted here contains syntax errors, so I presume 
you miscopied, or paraphrased it.

So, first fix your syntax errors.
Then correct the occurrences of the word 'square' in the class 'circle'.
Then your code will print 1.

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


Re: Looking for a Python mentor

2005-10-14 Thread Christoph Haas
On Friday 14 October 2005 21:35, billie wrote:
> "Nir Aides"  wrote
>
> > Hello Len,
> >
> > You should try the #python IRC room.
> > It is always very active and helpful.
> >
> > Nir
>
> Do you mean efnet #Python chan?
> It's not too much active...

I believe he meant irc.freenode.net :)

 Christoph
-- 
~
~
".signature" [Modified] 1 line --100%--1,48 All
-- 
http://mail.python.org/mailman/listinfo/python-list


Inheritance...

2005-10-14 Thread KraftDiner
I have a base class

class geometry(object):
   def __init__(self):
  self.blue = 1
  self.red = 2
   def render(self):
  pass

class square(geometry):
def __init__(self):
 super(square, self).__init__()
   def render(self)
  print 'square'

class circle(geometry):
def __init__(self):
 super(square, self).__init__()
   def render(self)
  print 'square'

objLst = []
objLst.append(square())
objLst.append(circle())

for obj in objLst:
   obj.render()
print obj.blue

What is wrong with this... I will not print blue... (1)

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


Inheritance...

2005-10-14 Thread KraftDiner
I have a base class

class geometry(object):
   def __init__(self):
  self.blue = 1
  self.red = 2
   def render(self):
  pass

class square(geometry):
def __init__(self):
 super(square, self).__init__()
   def render(self)
  print 'square'

class circle(geometry):
def __init__(self):
 super(square, self).__init__()
   def render(self)
  print 'square'

objLst = []
objLst.append(square())
objLst.append(circle())

for obj in objLst:
   obj.render()
print obj.blue

What is wrong with this... I will not print blue... (1)

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


Re: object inheritance and default values

2005-10-14 Thread George Sakkis
"Ron Adam" <[EMAIL PROTECTED]> wrote:

> I'm trying to implement simple svg style colored complex objects in
> tkinter and want to be able to inherit default values from other
> previously defined objects.
>
> I want to something roughly similar to ...
>
> class shape(object):
>  def __init__(self, **kwds):
>   # set a bunch of general defaults here.
>   self.__dict__.update(kwds)
> def draw(self, x=0, y=0, scale=1.0):
>   # draw the object
>
> hello = shape(text='hello')
> redhello = hello(color='red')
> largeredhello = redhello(size=100)
> largeredhiya = largeredhello(text='Hiya!')
> largeredhiya.draw(c, 20, 50)
>
>
> I think this will need to require __new__ or some other way to do it.
> But I'm not use how to get this kind of behavior.  Maybe the simplest
> way is to call a method.
>
> redhello = hello.makenew( color='red' )

Just name it '__call__' instead of makenew and you have the syntax sugar you 
want:

def __call__(self, **kwds):
new = self.__class__(**self.__dict__)
new.__dict__.update(kwds)
return new

Personally I would prefer an explicit method name, e.g. 'copy'; hiding the fact 
that 'shape' is a
class while the rest are instances is likely to cause more trouble than it's 
worth.

George


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


Re: Function to execute only once

2005-10-14 Thread Benji York
PyPK wrote:
> now I want execute() function to get executed only once. That is the
> first time it is accessed.

How about just calculating the value at import time?
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing lists

2005-10-14 Thread Scott David Daniels
Let me begin by apologizing to Christian as I was too snippy in
my reply, and sounded even snippier than I meant to.

Christian Stapfer wrote:
> "Scott David Daniels" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>>a "better" set implementation will win if
>>it can show better performance without
>>related down-sides.
> 
> Is there ever such a thing? I always
> thought that, most of the time, there
> is no such thing as a free lunch in
If you look at the history of Python's sort, it has steadily gotten
better.  The list implementations has been tweaked to produce better
performance appending and popping.  There are a number of such cases.
In fact, as Python rolls along, code keeps getting improved.  Usually
the requirement is that the change not degrade current benchmarks and
provide a substantial improvement in at least some practical cases.

>>As to the "either now, or eventually;"  if you _must_ have performance
>>now, not in some abstract future, then it behooves you to _test_,
>>_test_, _test_!
> 
> Well, I might want to test: but *first* I want
> to design, preferably in "armchair style" ... [using] 
 > rough complexity measures to 

>If the documentation stated the order-of-magnitude
>behavior of those basic operations up front, then
>I (and *anyone* else who ever wanted to use those
>operations on large lists / large sets) could do
>a quick order-of-magnitude estimation of how
>a certain program design will behave, performance
>wise.

I think this is where I started over-reacting.  There are
a number of requests here over time by people who state
that things would be so much better for every one if only
someone (never themselves) did some more work that they
might not otherwise want to do.  The people who implement
the code often do so on their own time.  I find the Python
docs surprisingly good for even commercial documentation.
For work that is done gratis, it is phenomenal.  I hesitate
to ask any more of it (although I have pointed out bugs in
docs as I've found them).

>>And, if the proper documentation is in place, and it
>>says "dictionary lookup is O(N)" (and you avoid using
>>it for exactly that reason), how surprised will you be
>>to discover that the O(N) is only reached if the hash
>>values of the keys are all equal?
> 
> It's not that difficult to distinguish
> *average* case and *worst* case scenarios.
> It might even be a good idea to state,
> if that can easily be done, what the
> *best* case happens do be...
> 
>>Oh, maybe you expect "O(N)" to really mean "\Theta(N)".
>>Then, if you are a dweeb like me, you will respond that
>>"This is not possible, a dictionary of size N must take at
>>least 'O(lg N)' to read the key, never mind processing it."
>>But, it turns out, that given a bound on the size of a
>>process, processing an address is "O(1)", not "O(lg N)".
>>Is that too practical for you, or not enough?
> 
> I do not expect a developer to expend *inordinate*
> amounts of work to figure out the computational
> complexity of what he has implemented. But, as I
> wrote, he *must* have thought about the matter, and
> is thus, by definition, in a rather good position
> to provide what he can frequently simply pull from
> memory when it comes to documenting the interface
> of his module.

I talked about Big-O (worst case) or Big-Theta (average case)
just to point out that no simple characterization like "O(N)"
tells enough of the story to be practically useful.  Once you
decide that isn't good enough, the burden on creating the
documentation is getting substantial, especially given that
you've already spent the effort to write the code and tests
for it.  In fact I'd hesitate to raise the documentation bar
any higher -- I'd hate to think someone thought, "Oh, forget
it, I'll just use this code myself."

> *Experimenting* is not necessarily as easy to
>do as you seem to believe.
No, "experimenting" is not always easy (though often it is
easy enough).  However, "experimenting" puts the cost on the
person who derives the benefit, and is thus likely to not be
done in a slipshod way.

> I am not at all a lawyer type, as you seem to
> imagine. I just want to suggest that some
> (to the implementer - but not the average user)
> *easily* available information about computational
> complexity (especially for the most basic data types)
> would be a good thing to have. Nothing more.
My point is that simple performance characterization is not
good enough to be useful, and fully accurate characterization
is an onerous documentation burden.  Something in between
will be fraught with complaints about "surprising" worst
cases.  Whether you would approach middle-ground documentation
with the spirit of "this is enough to go on" or not, rest
assured that a number of people will complain in a "language-
lawyer-like" way about any perceived imperfections.

>>Would you mind if the quality is proportional to
>>the price you paid?
Here I was too snippy.  S

Re: Moving to Win XP as a Python developer

2005-10-14 Thread Thomas Heller
Trent Mick <[EMAIL PROTECTED]> writes:

> [Thomas Heller wrote]
>> I have an elisp function bound to a key in XEmacs that starts cmd in the
>> directory where the current buffer is.  IMO this is very convenient.  To
>> access explorer from that command prompt (in the rare cases that I need
>> it) I use 'start .'.
>
> I kind of have the same thing with Dave's Quick Search Deskbar
> (http://www.dqsd.net/) and my little "go" script
> (http://trentm.com/projects/go/). The keystrokes to open a cmd.exe shell
> in my "src" folder is down to:
>
> # to focus in the Quick Search Deskbar textbox
> go src
>
> or to open Explorer in that dir:
>
> go -o src 
>
> or in another "tagged" dir:
>
> go ~   # open in my home dir
>
> DQSD is a fantastic tool for speeding up launching other things, too:
> mainly Google searches.

Since we are speaking of tricks here:

I have other keys defined in XEmacs for context-sensitive help on the
word under the cursor in Python's htmlhelp file (F2), and the MSDN
library (F6).  Kind of a hack which needs a small compiled C program,
though, since I did not know how to call the needed apis with elisp.

But, what I'm still missing is a function that finds and opens a Python
module.

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


MS Word Outline -> reStructuredText script?

2005-10-14 Thread Jim
Hi,

I'm using reStructuredText as a format for some group documentation,
and often my co-workers take notes during meetings in Word's outline
mode.  Does anyone already have a python script that will convert from
Word (or the Open Office file format version of a word document) to
reStructured Text?

If not I've got a fun project ahead of me.

Thanks,
-Jim

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


Re: Looking for a Python mentor

2005-10-14 Thread billie

"Nir Aides"  wrote
> Hello Len,
>
> You should try the #python IRC room.
> It is always very active and helpful.
>
> Nir

Do you mean efnet #Python chan?
It's not too much active... 


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


Re: Function to execute only once

2005-10-14 Thread Paul Rubin
"PyPK" <[EMAIL PROTECTED]> writes:
> now I want execute() function to get executed only once. That is the
> first time it is accessed.
> so taht when funcc2 access the execute fn it should have same values as
> when it is called from func1.

There's nothing built into Python for that.  You have to program the
function to remember whether it's already been called.  It sounds like
you're trying to avoid performing some side effect more than once.

Anyway, there's multiple ways you can do it.  The conceptually
simplest is probably just use an attribute on the function:

   tmp = 0   # you want to modify this as a side effect
   def execute():
 global tmp
 if not execute.already_called:
tmp += 1
execute.already_called = True
 return tmp
   execute.already_called = False

Other ways include using a class instance, using an iterator, etc.

Generally too, you might find it cleaner to avoid having side effects
like that.  Instead, put tmp itself inside a class instance:

class Memo:
  def __init__(self):
self.value = 0# any side effects operate on this
self.already_called = False

  def __call__(self):
if not self.already_called:
   self.already_called = True
   self.value += 1
return self.value

execute = Memo()

Now you don't have global state cluttering things up, you can make
multiple instances easily, etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to Win XP as a Python developer

2005-10-14 Thread Trent Mick
[Thomas Heller wrote]
> I have an elisp function bound to a key in XEmacs that starts cmd in the
> directory where the current buffer is.  IMO this is very convenient.  To
> access explorer from that command prompt (in the rare cases that I need
> it) I use 'start .'.

I kind of have the same thing with Dave's Quick Search Deskbar
(http://www.dqsd.net/) and my little "go" script
(http://trentm.com/projects/go/). The keystrokes to open a cmd.exe shell
in my "src" folder is down to:

# to focus in the Quick Search Deskbar textbox
go src

or to open Explorer in that dir:

go -o src 

or in another "tagged" dir:

go ~   # open in my home dir

DQSD is a fantastic tool for speeding up launching other things, too:
mainly Google searches.

Cheers,
Trent

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function to execute only once

2005-10-14 Thread Jaime Wyant
If I understand you correctly, you want `tmp' to be global...

If so, declare it as so in execute ->

def execute():
global tmp
tmp = tmp+1
return tmp

Otherwise, what happens is that you declare a variable local to
execute, that is named tmp.  When the assignment occurs it uses the
global value of `tmp', which is 0, and adds it to the *local* tmp.

I hope that is not too confusing.

jw

On 14 Oct 2005 12:11:58 -0700, PyPK <[EMAIL PROTECTED]> wrote:
> Hi if I have a function called
> tmp=0
> def execute():
> tmp = tmp+1
> return tmp
>
> also I have
> def func1():
> execute()
> 
> and
> def func2():
> execute()
> 
>
> now I want execute() function to get executed only once. That is the
> first time it is accessed.
> so taht when funcc2 access the execute fn it should have same values as
> when it is called from func1.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Best way to handle cgi sessions

2005-10-14 Thread Derek Perriero
What would be the best way to create a cgi session that contains the
basic elements of a cookie and can also hold secure data, such as a
username/password.  I've explored the possibilities of using
SmartCookie, but that doesn't encrypt my parameters.Here's some background info on what I'm trying to do:form = cgi.FieldStorage()
try: username = form["username"].value
 password  = form["password"].value
except KeyError: print "Please Enter Username/Password"
## authenticate against LDAP serverif not authen.ldap(username,password):

cookie =
0  
#Cookie dies and page goes back to re-login display = functions.display_html_admin("main_temp.html")
 functions.print_html_header(cookie) print display
 exitelse:
 cookie = authen.genCookie(username) display = functions.display_html_admin("main_temp.html")
 functions.print_html_header(cookie) print display
 exit

...
## From authen.py

def genCookie(username):
    cookie = SmartCookie()

    cookie["CGISESSID"] = generate_hash()
    cookie["CGISESSID"]["path"] = "/tmp"
    cookie["logintype"] = "admin"
    cookie["username"]  = username
    cookie["loggedin"]  = "verified"
   
    return(cookie)

#end:
 -- Perriero, Derek[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Function to execute only once

2005-10-14 Thread PyPK
Hi if I have a function called
tmp=0
def execute():
tmp = tmp+1
return tmp

also I have
def func1():
execute()

and
def func2():
execute()


now I want execute() function to get executed only once. That is the
first time it is accessed.
so taht when funcc2 access the execute fn it should have same values as
when it is called from func1.

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


Re: [ANN] XPN 0.5.5 released

2005-10-14 Thread Cousin Stanley

>> Can I install the newer xpn version
>> and move the older data files into it
>> without reconfiguring & reloading data files ? 
  
Cousin Nemesis  

  This worked OK with no problems
  and I'm posting this reply via xpn-0.5.5  

  I copied the following from the older xpn-0.5.0 version
  to the newer xpn-0.5.5 version 

dirs  

  o dats
  o groups_info
  o outbox

files  

  o custom_headers.txt
  o groups_list
  o server_logs.dat

  No initial configuration, downloading newsrc file,
  or re-subscribing to newsgroups was required 
  and all of my previously kept & watched messages
  seem to be in place  

  Thanks for the update 


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona


== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to Win XP as a Python developer

2005-10-14 Thread Thomas Heller
Scott David Daniels <[EMAIL PROTECTED]> writes:

> Christian Stapfer wrote:
>> "John J. Lee" <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>>
>>>cmd.exe can be made bearable
>>>
>>>0. Make a shortcut to cmd.exe, stick it somewhere get-at-able,
>>>  eg. quick launch toolbar

> I put it on my desktop.  Once having made it, fiddle with
> "Start in" to be your favorite python code directory (that is
> why I usually have several), and append a space and /D /X /F:ON
> to the "Target" line.

I have an elisp function bound to a key in XEmacs that starts cmd in the
directory where the current buffer is.  IMO this is very convenient.  To
access explorer from that command prompt (in the rare cases that I need
it) I use 'start .'.

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


object inheritance and default values

2005-10-14 Thread Ron Adam

I'm trying to implement simple svg style colored complex objects in 
tkinter and want to be able to inherit default values from other 
previously defined objects.

I want to something roughly similar to ...

class shape(object):
 def __init__(self, **kwds):
  # set a bunch of general defaults here.
  self.__dict__.update(kwds)
def draw(self, x=0, y=0, scale=1.0):
  # draw the object

hello = shape(text='hello')
redhello = hello(color='red')
largeredhello = redhello(size=100)
largeredhiya = largeredhello(text='Hiya!')
largeredhiya.draw(c, 20, 50)


I think this will need to require __new__ or some other way to do it. 
But I'm not use how to get this kind of behavior.  Maybe the simplest 
way is to call a method.

redhello = hello.makenew( color='red' )

But I want to be able to have all the objects access alike?

Hmmm..  I think maybe if if don't ever access shape (or Shape) directly 
in my data structure, then __new__ would work?  So my first default 
object should be an instance of shape with a __new__ method to create 
more?  Ok, off to try it.  But any comments will be welcome.

Cheers,
Ron


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


  1   2   >