Re: Question - What is a faster alternative to recursion?

2005-03-02 Thread Stephen Thorne
On Wed, 02 Mar 2005 00:58:58 -0600, actuary77
<[EMAIL PROTECTED]> wrote:
> Yes, iteration is 100 times faster than recursion.
> 
> The problem I have is:
> 
> # need to call this function 50 times with seed of 10
> (afunc(afunc(afunc(...   afunc(10))
> 
> required_iterations_ 50
> function:  afunc(x): x**.5 + 1000 * x + 46.
> initial_seed:10
> 
> Result =>  afunc(afunc(afunc(afunc(afunc(afunc ...   (_aseed)
> 
> What is the fastest way to do this without using recursion?
> 
> With recursion:
> 
> 
> def rec(afunc,n,x):
>  y = afunc(x)
>  if n == 0:
>  return y
>  else:
>  return rec(afunc,n-1,y)
> 
> def myfunc(x):
>  return x**.5 + 1000 * x + 46.
> 
> from time import time
> 
> _b=time()
> _y = rec(myfunc,50,10)
> _e=time()
> _t=_e-_b
> print "result: %r time: %f\n" % (_y,_t)
> 
> output:
> result: 1.00493118428005e+154 time: 0.03
> 
> Is there a much faster way?

Sure.

[EMAIL PROTECTED] tmp]$ python timeit.py -s 'from recursive import
calculate' 'calculate(100, 10)'
1000 loops, best of 3: 295 usec per loop
[EMAIL PROTECTED] tmp]$ python timeit.py -s 'from iterative import
calculate' 'calculate(100, 10)'
1 loops, best of 3: 134 usec per loop
[EMAIL PROTECTED] tmp]$ cat iterative.py

def calculate(repeats, value):
for x in range(repeats):
value = value ** .5 + 1000*x + 46
return value

[EMAIL PROTECTED] tmp]$ cat recursive.py
def rec(afunc,n,x):
y = afunc(x)
if n == 0:
return y
else:
return rec(afunc,n-1,y)

def myfunc(x):
return x**.5 + 1000 * x + 46.

def calculate(repeats, value):
rec(myfunc, repeats, value)


As you can see, the iterative solution actually results in less code too ;)

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


why is http://pysqlite.org down ?

2005-03-02 Thread martijn
H!

I'm trying things with databases and Python 2.4 for windows2000.
And now I want to try pysqlite.

but http://pysqlite.org/ is down
and http://pysqlite.sourceforge.net/ redirect to pysqlite.org

does someone know if this is the latest version
http://sourceforge.net/projects/pysqlite/ pysqlite 2.0

thanks

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


Re: Help- Recursion v. Iter Speed comparison

2005-03-02 Thread actuary77
Robert Kern wrote:
actuary77 wrote:
Recurse from  time: 4.305942779541 seconds
Iter from  time: 0.009904632568359 seconds
No comparison, why is recursion so slow?

I usually don't delve too deeply into language design issues, so I hope 
others will correct me if I'm wrong. Recursion is usually slower than 
the equivalent iteration unless if it is specifically optimized by the 
language implementation. Most Schemes, for example, do tail-call 
optimization, and so many uses of recursion run pretty fast. CPython is 
not one of those implementations.

Would using a generator be faster than recursion?

Try it.
I really have complex list comprehension.

Then you shouldn't be using list comprehensions.
I am interating n times.
I have initial function: func(x)
I have initial seed value:  _aseed
iteration   value
  1func(_aseed)
  2func(func(_aseed))
 
  n   func(func(func...(_aseed))
What would be the fastest way to do this?

Non-generator:
def f1(aseed):
values = [func(aseed)]
for i in range(n-1):
values.append(func(values[-1]))
return values
Generator:
def f2(aseed):
value = func(aseed)
for i in range(n):
yield value
value = func(aseed)
Probably not *the* fastest solutions, but I'll wager that the speed 
gains you get from a faster solution will be more than paid for by a 
loss in clarity. 

Do the simplest thing that could possibly work. Don't bother with 
trickier/less Pythonic approaches until they're really called for.

I have a question on the generator solution.  I have reviewed docs and I 
am unable to return a value from the generator.  Below is a little speed 
comparison for a:
  1.  A recursive solution
  2.  A non-generator, list comprehension approach (Thank you)
  3.  The generator.

Do you have any suggestions:
'''  A comparison of Recursion, list comprehension and a generator '''
import sys
from time import time
sys.setrecursionlimit(1)
cnt=1  # number of times to run each test
# The parameters
seed=10
n=100
def myfunc(x):
return x + .5
#
# A Recursive Approach
#
def rec(afunc,x,n):
y = afunc(x)
if n == 0:
return y
else:
return rec(afunc,y,n-1)
_b=time()
for _i in range(0,cnt):
_y = rec(myfunc,seed,n)
_e=time()
_t=_e-_b
print "rec result: %r time: %f\n" % (_y,_t*1.)
#
#  non-generator
#
def f1(afunc,aseed,n):
values = [afunc(aseed)]
for i in range(n-1):
values.append(afunc(values[-1]))
return values[-1]
_b=time()
for _i in range(0,100):
_y = f1(myfunc,seed,n)
_e=time()
_t=_e-_b
print "f1 result: %r time: %f\n" % (_y,_t*1.)
#
#  generator
#
def f2(afunc,aseed,n):
v = myfunc(aseed)
print v
for i in range(n):
yield v
v = afunc(v)
def f2gen(i):
for _i in range(1,n-1):
f2(myfunc,seed,n)
return f2(myfunc,seed,n)
_b=time()
for _i in range(0,cnt):
_y = f2gen(_i)
_e=time()
_t=_e-_b
print "f2gen result: %r time: %f\n" % (_y,_t*1.)
==>
rec result: 10.0050488 time: 47669.999599
f1 result: 10.0049988 time: 399.999619
f2gen result:  time: 30739.998817
I don't know how to get the generator to work correcly, I understand 
that the yield preserves the state of the funcion every time it is 
called. So in order to have myfunc called 50 times, the generator must 
be called 50 times, but it refuses to return a value.  PEP 255 isn't 
helping me.

Any further guidance would be greatly appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expressions: large amount of or's

2005-03-02 Thread André Søreng
Bill Mill wrote:
On Tue, 01 Mar 2005 22:04:15 +0100, André Søreng <[EMAIL PROTECTED]> wrote:
Kent Johnson wrote:
André Søreng wrote:

Hi!
Given a string, I want to find all ocurrences of
certain predefined words in that string. Problem is, the list of
words that should be detected can be in the order of thousands.
With the re module, this can be solved something like this:
import re
r = re.compile("word1|word2|word3|...|wordN")
r.findall(some_string)
Unfortunately, when having more than about 10 000 words in
the regexp, I get a regular expression runtime error when
trying to execute the findall function (compile works fine, but slow).
I don't know if using the re module is the right solution here, any
suggestions on alternative solutions or data structures which could
be used to solve the problem?

If you can split some_string into individual words, you could look them
up in a set of known words:
known_words = set("word1 word2 word3 ... wordN".split())
found_words = [ word for word in some_string.split() if word in
known_words ]
Kent

André
That is not exactly what I want. It should discover if some of
the predefined words appear as substrings, not only as equal
words. For instance, after matching "word2sgjoisejfisaword1yguyg", word2
and word1 should be detected.

Show some initiative, man!

known_words = set(["word1", "word2"])
found_words = [word for word in known_words if word in "word2sgjoisejfisawo
rd1yguyg"]
found_words
['word1', 'word2']
Peace
Bill Mill
bill.mill at gmail.com
Yes, but I was looking for a solution which would scale. Searching 
through the same string 1+++ times does not seem like a suitable 
solution.

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


Re: Help- Recursion v. Iter Speed comparison

2005-03-02 Thread Robert Kern
actuary77 wrote:
#
#  non-generator
#
def f1(afunc,aseed,n):
values = [afunc(aseed)]
for i in range(n-1):
values.append(afunc(values[-1]))
return values[-1]
_b=time()
for _i in range(0,100):
_y = f1(myfunc,seed,n)
Why do you do this? The whole point of this approach was to keep the 
intermediate results instead of recomputing them every time!

And why do you prepend underscores everywhere? It's bad Python style.
_e=time()
_t=_e-_b
print "f1 result: %r time: %f\n" % (_y,_t*1.)
#
#  generator
#
def f2(afunc,aseed,n):
v = myfunc(aseed)
print v
for i in range(n):
yield v
v = afunc(v)
def f2gen(i):
for _i in range(1,n-1):
f2(myfunc,seed,n)
return f2(myfunc,seed,n)
_b=time()
for _i in range(0,cnt):
_y = f2gen(_i)
_e=time()
_t=_e-_b
print "f2gen result: %r time: %f\n" % (_y,_t*1.)
==>
rec result: 10.0050488 time: 47669.999599
f1 result: 10.0049988 time: 399.999619
f2gen result:  time: 30739.998817
I don't know how to get the generator to work correcly, I understand 
that the yield preserves the state of the funcion every time it is 
called. So in order to have myfunc called 50 times, the generator must 
be called 50 times, but it refuses to return a value.  PEP 255 isn't 
helping me.
No, the generator call creates a generator object which you iterate over.
  for value in f2(myfunc, seed, n):
  print value
If you absolutely need a list:
  list(f2(myfunc, seed, n))
--
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: bsddb for k, v in db.items(): do order the numbers ?

2005-03-02 Thread Denis S. Otkidach
On Mon, 28 Feb 2005 11:48:44 -0500
Christopher De Vries <[EMAIL PROTECTED]> wrote:

> If you want your key, value pairs in a certain order you have to sort
> them yourself. Dictionaries and bsddb keys are unsorted.

You are not right, records in BTree (btopen) are certainly sorted.  For
positive integers you can pack keys with struct.pack('>I', value).

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


Running Python Scripts With 'sudo'

2005-03-02 Thread Tim Daneliuk
Given that setuid is a Bad Thing for scripts, what is the general consensus
here on running a Python script via 'sudo' to give it root system access?
Is this reasonably secure, or am I still asking for trouble?
TIA,
--

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter and Text() widget interactivity ?

2005-03-02 Thread Tonino
Many thanks for this - will give it a bash ;)

Tonino

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


creating csv file from

2005-03-02 Thread Sandeep Avinash Gohad

Please Help me

I wish to download the data from any URL (from any website) and
then want to save into ".csv" format.

In the python documentation "12.20 csv -- CSV File Reading and Writing"
import csv
reader = csv.reader(file("some.csv"))
for row in reader:
    print row

How can i use the url as an input so that I can save data from that particular webpage to comma seperated file (csv).

Regards
Sandeep


     





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

Re: Regular Expressions: large amount of or's

2005-03-02 Thread André Søreng
Daniel Yoo wrote:
Kent Johnson <[EMAIL PROTECTED]> wrote:
:> Given a string, I want to find all ocurrences of
:> certain predefined words in that string. Problem is, the list of
:> words that should be detected can be in the order of thousands.
:> 
:> With the re module, this can be solved something like this:
:> 
:> import re
:> 
:> r = re.compile("word1|word2|word3|...|wordN")
:> r.findall(some_string)

The internal data structure that encodes that set of keywords is
probably humongous.  An alternative approach to this problem is to
tokenize your string into words, and then check to see if each word is
in a defined list of "keywords".  This works if your keywords are
single words:
###
keywords = set([word1, word2, ...])
matchingWords = set(re.findall(r'\w+')).intersection(keywords)
###
Would this approach work for you?

Otherwise, you may want to look at a specialized data structure for
doing mutiple keyword matching; I had an older module that wrapped
around a suffix tree:
http://hkn.eecs.berkeley.edu/~dyoo/python/suffix_trees/
It looks like other folks, thankfully, have written other
implementations of suffix trees:
http://cs.haifa.ac.il/~shlomo/suffix_tree/
Another approach is something called the Aho-Corasick algorithm:
http://portal.acm.org/citation.cfm?doid=360825.360855
though I haven't been able to find a nice Python module for this yet.
Best of wishes to you!
Thanks, seems like the Aho-Corasick algorithm is along the lines of
what I was looking for, but have not read the article completely yet.
Also:
http://alexandria.tue.nl/extra1/wskrap/publichtml/200407.pdf
provided several alternative algorithms.
André
--
http://mail.python.org/mailman/listinfo/python-list


Re: function expression with 2 arguments

2005-03-02 Thread Xah Lee
once i have a expresson of a function, how to apply it to arguments?

e.g. if i have
lambda x,y:x+y
i have to applied it to a,b in my code.

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


i18n: looking for expertise

2005-03-02 Thread klappnase
Hello all,

I am trying to internationalize my Tkinter program using gettext and
encountered various problems, so it looks like it's not a trivial
task.
After some "research" I made up a few rules for a concept that I hope
lets me avoid further encoding trouble, but I would feel more
confident if some of the experts here would have a look at the
thoughts I made so far and told me if I'm still going wrong somewhere
(BTW, the program is supposed to run on linux only). So here is what I
have so far:

1. use unicode instead of byte strings wherever possible. This can be
a little tricky, because in some situations I cannot know in advance
if a certain string is unicode or byte string; I wrote a helper module
for this which defines convenience methods for fail-safe
decoding/encoding of strings and a Tkinter.UnicodeVar class which I
use to convert user input to unicode on the fly (see the code below).

2. so I will have to call gettext.install() with unicode=1

3. make sure to NEVER mix unicode and byte strings within one
expression

4. in order to maintain code readability it's better to risk excess
decode/encode cycles than having one too few.

5. file operations seem to be delicate; at least I got an error when I
passed a filename that contains special characters as unicode to
os.access(), so I guess that whenever I do file operations
(os.remove(), shutil.copy() ...) the filename should be encoded back
into system encoding before; The filename manipulations by the os.path
methods seem to be simply string manipulations so encoding the
filenames doesn't seem to be necessary.

6. messages that are printed to stdout should be encoded first, too;
the same with strings I use to call external shell commands.

 file UnicodeHandler.py ##
# -*- coding: iso-8859-1 -*-
import Tkinter
import sys
import locale
import codecs

def _find_codec(encoding):
# return True if the requested codec is available, else return
False
try:
codecs.lookup(encoding)
return 1
except LookupError:
print 'Warning: codec %s not found' % encoding
return 0

def _sysencoding():
# try to guess the system default encoding
try:
enc = locale.getpreferredencoding().lower()
if _find_codec(enc):
print 'Setting locale to %s' % enc
return enc
except AttributeError:
# our python is too old, try something else
pass
enc = locale.getdefaultlocale()[1].lower()
if _find_codec(enc):
print 'Setting locale to %s' % enc
return enc
# the last try
enc = sys.stdin.encoding.lower()
if _find_codec(enc):
print 'Setting locale to %s' % enc
return enc
# aargh, nothing good found, fall back to latin1 and hope for the
best
print 'Warning: cannot find usable locale, using latin-1'
return 'iso-8859-1'

sysencoding = _sysencoding()

def fsdecode(input, errors='strict'):
'''Fail-safe decodes a string into unicode.'''
if not isinstance(input, unicode):
return unicode(input, sysencoding, errors)
return input

def fsencode(input, errors='strict'):
'''Fail-safe encodes a unicode string into system default
encoding.'''
if isinstance(input, unicode):
return input.encode(sysencoding, errors)
return input


class UnicodeVar(Tkinter.StringVar):
def __init__(self, master=None, errors='strict'):
Tkinter.StringVar.__init__(self, master)
self.errors = errors
self.trace('w', self._str2unicode)

def _str2unicode(self, *args):
old = self.get()
if not isinstance(old, unicode):
new = fsdecode(old, self.errors)
self.set(new)
###

So before I start to mess up all of my code, maybe someone can give me
a hint if I still forgot something I should keep in mind or if I am
completely wrong somewhere.

Thanks in advance

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


Re: Need some simple coding help

2005-03-02 Thread mx2k
indeed, we're it is our combat timeline. we enter the initiative and
reaction time, it should find out the lowest then the next, then the
'n'th etc. and shouw it on the screen like
 Next action 'Character Name1' at tick No  'Initiative1
 2nd  action 'Character Name2' at tick No  'Initiative2'
 [...]
 'n'th action 'Character Name n' at tick No  'Initiative n'

  Now you enter a value by which the initiative should be increased,
then adding reaction time to that value and then adding the result to
reaction time. Now soring again by lowest,next,'n'th, etc. and then
again showing the output, asking for another number etc.

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


Re: What's the cost of using hundreds of threads?

2005-03-02 Thread Przemysław Różycki
I'm a bit confused by your math.  Fifty connections should be 102
threads, which is quite reasonable.
My formula applies to one forwarded ('loadbalanced') connection. Every 
such connection creates further n connections (pipes) which share the 
load. Every pipe requires two threads to be spawned. Every 'main 
connection' spawns two other threads - so my formula: 2*pipes+2 gives 
the number of threads spawned per 'main connection'.

Now if connections_count connections are established the thread count 
equals:
conn_count * threads_per_main_connection = conn_count * (2*pipes+2)

For 50 connections and about 10 pipes it will give 1100 threads.
My experience with lots of threads dates back to Python 1.5.2, but I
rarely saw much improvement with more than a hundred threads, even for
heavily I/O-bound applications on a multi-CPU system.  However, if your
focus is algorithmic complexity, you should be able to handle a couple of
thousand threads easily enough.
I don't spawn them because of computional reasons, but due to the fact 
that it makes my code much more simpler. I use built-in tcp features to 
achieve loadbalancing - every flow (directed through pipe) has it's own 
dedicated threads - separate for down- and upload. For every 'main 
connection' these threads share send and receive buffer. If any of pipes 
is congested the corresponding threads block on their send / recv 
functions - without affecting independence of data flows.

Using threads gives me VERY simple code. To achieve this with poll / 
select would be much more difficult. And to guarantee concurrency and 
maximal throughput for all of pipes I would probably have to mirror code 
 from linux TCP stack (I mean window shifting, data acknowlegement, 
retransmission queues). Or perhaps I exaggerate.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need some simple coding help

2005-03-02 Thread mx2k
ah, and sorry for that 'unreadable' code, but that was our first try of
coding ever. we're working through the python documentaion right now -
and - thanks to the post by STeVe we at last now that we have to
construct a class for our purpose.

Thx for any help
mx2k

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


Re: Regular Expressions: large amount of or's

2005-03-02 Thread Ola Natvig
André Søreng wrote:

Yes, but I was looking for a solution which would scale. Searching 
through the same string 1+++ times does not seem like a suitable 
solution.

André
Just for curiosity, what would a regexp do? Perhaps it's a clue in how 
you could do this in the way regexp's are executed.

ola
--
--
 Ola Natvig <[EMAIL PROTECTED]>
 infoSense AS / development
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the cost of using hundreds of threads?

2005-03-02 Thread Przemysław Różycki
Thanks for your comments on winXP threads implementation. You confirmed 
me in conviction that I shouldn't use windows.
Personally I use linux with 2.6.10 kernel, so hopefully I don't have to 
share your grief. ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Non-blocking input on windows, like select in Unix

2005-03-02 Thread fraca7
Jonathan Fine a écrit :
Paul Rubin wrote:

As I recall, some posts to this list say that Windows provides
non-blocking i/o for sockets but not for files.
No, Windows does provide non-blocking I/O for regular files, but it's a 
completely different mechanism than the one used by winsock. You'll have 
to use win32all and enter the Dark Side, that is Windows APIs.

You don't want to do that if you're not already familiar with 
CreateProcess, CreatePipe, overlapped structures, WaitForSingleObject & 
al...
--
http://mail.python.org/mailman/listinfo/python-list


Re: function expression with 2 arguments

2005-03-02 Thread Roel Schroeven
Xah Lee wrote:
> once i have a expresson of a function, how to apply it to arguments?
> 
> e.g. if i have
> lambda x,y:x+y
> i have to applied it to a,b in my code.

OK, I'll bite.

As with any other callable, you can simply call it like this:

a = 4
b = 24
(lambda x, y: x+y)(a, b)

Of course, you could just as well simply write

a+b

instead.

Most often the lambda is not used directly, but passed to a function. A
trivial example:

def f(fn, a, b):
return fn(a, b)

f(lambda x, y: x+y, 3, 42)

-- 
"Codito ergo sum"
Roel Schroeven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expressions: large amount of or's

2005-03-02 Thread André Søreng
Ola Natvig wrote:
André Søreng wrote:

Yes, but I was looking for a solution which would scale. Searching 
through the same string 1+++ times does not seem like a suitable 
solution.

André

Just for curiosity, what would a regexp do? Perhaps it's a clue in how 
you could do this in the way regexp's are executed.

ola
I think this article provides me with what I was looking for:
http://alexandria.tue.nl/extra1/wskrap/publichtml/200407.pdf
Enough info there to keep me going for some while.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the cost of using hundreds of threads?

2005-03-02 Thread Nick Coghlan
Steve Holden wrote:
Apache, for example, can easily spawn more threads under Windows, and 
I've written code that uses 200 threads with excellent performance. 
Things seem to slow down around the 2,000 mark for some reason I'm not 
familiar with.
As far as I know, the default Windows thread stack size is 2 MB. Do the 
math :)
On NT4, beyond a couple of hundred threads a *heck* of a lot of time ends up 
being spent in the kernel doing context switches (and you can kiss even vaguely 
deterministic response times good-bye).

Using a more recent version of Windows improves matters significantly.
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: looking for expertise

2005-03-02 Thread Neil Hodgson
Michael:

> 5. file operations seem to be delicate; at least I got an error when I
> passed a filename that contains special characters as unicode to
> os.access(), so I guess that whenever I do file operations
> (os.remove(), shutil.copy() ...) the filename should be encoded back
> into system encoding before;

   This can lead to failure on Windows when the true Unicode file name can
not be encoded in the current system encoding.

   Neil


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


Re: Faster way to do this...

2005-03-02 Thread Will McGugan
Warren Postma wrote:
Will McGugan wrote:
Isn't that equivalent to simply..
nums= range(100)

I remember the day I first realized that 900 lines of some C++ program I 
was working on could be expressed in three lines of python.  Ahh.
Lately I've found myself commenting C++ code with the equivalent Python 
code. I find it clearer and more terse than simply commenting in English!

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


Online Programming Contest (Python solutions accepted)

2005-03-02 Thread Sridhar
Hi,

We, the students of CEG, Anna University [1] are organizing an online
programming contest as part of aBaCus [2] 2005.  The contest itself
will start on 6th March 2005 at 1:00 pm IST [3] and will end after 5
hours.  You have to solve the problems posted at the start of the
contest.  Teams ranking high will be awarded the prizes.

As a special note, inspite of C,C++ and Java we also allow Python [4]
this time.  So we hope a lot of Pythonistas also could attend the
contest for fun. :-)

For more details about the contest, visit the contest page

 --   http://203.197.138.181/OPC  --

[1] http://en.wikipedia.org/wiki/Anna_University
[2] http://www.annauniv.edu/abacus/
[3] Indian Standard Time (IST) is the time zone for India. It is 5
hours and 30 minutes ahead of GMT/UTC.
[4] http://www.python.org

--
Sridhar Ratna - http://srid.bsdnerds.org

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


Re: reuse validation logic with descriptors

2005-03-02 Thread Nick Coghlan
David S. wrote:
Steve, and others, thanks for the help.  This and Michael Spencer's reply
at http://article.gmane.org/gmane.comp.python.general/390478 have been very
helpful in getting the descriptor definition clear.  For me, it has taken 
reading http://users.rcn.com/python/download/Descriptor.htm about 4 times 
along with your help to get this straight.
If it only takes 2 or 3 re-reads to get descriptors, does that mean Python's 
black magic is really only a kind of off-white colour?

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expressions: large amount of or's

2005-03-02 Thread Gurpreet Sachdeva
Can divide the regex on the bases of alphabets they are starting with
or can iterate on the list.

Regards,
Garry

http://garrythegambler.blogspot.com/


On Wed, 02 Mar 2005 12:50:01 +0100, André Søreng <[EMAIL PROTECTED]> wrote:
> Ola Natvig wrote:
> > André Søreng wrote:
> >
> >>
> >>
> >> Yes, but I was looking for a solution which would scale. Searching
> >> through the same string 1+++ times does not seem like a suitable
> >> solution.
> >>
> >> André
> >
> >
> > Just for curiosity, what would a regexp do? Perhaps it's a clue in how
> > you could do this in the way regexp's are executed.
> >
> > ola
> >
> 
> I think this article provides me with what I was looking for:
> 
> http://alexandria.tue.nl/extra1/wskrap/publichtml/200407.pdf
> 
> Enough info there to keep me going for some while.
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


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


Re: Initializing subclasses of tuple

2005-03-02 Thread Nick Coghlan
[email protected] wrote:
To inherit from an immutable class, like string or tuple, you need to
use the __new__ member, not __init__.  See, e.g.:
http://www.python.org/2.2.3/descrintro.html#__new__
Any volunteers out there willing to put some words about __new__ together for 
the main Python docs, please consider posting them on SF :)

It's currently conspicuous by its absence:
http://www.python.org/dev/doc/devel/ref/customization.html
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: assigning a custom mapping type to __dict__

2005-03-02 Thread Nick Coghlan
Steven Bethard wrote:
The problem with inheriting from dict is that you then need to override 
*all* the methods in the dict object, because they all go straight to 
Python's dict'c C code functions.  So just because you redefine 
__getitem__ doesn't mean you don't still have to redefine __contains__, 
get, update, etc.  UserDict.DictMixin can help with this some, but the 
ideal situation would be to only have to define the methods you actually 
support.  Inheriting from dict likely means you have to redefine a bunch 
of functions to raise Exceptions saying that they're unsupported.
You're just lucky the affected class is already overriding __getattribute__, so 
the __dict__ is generally getting accessed from Python code :)

If it weren't for that, object.c's direct calls to the PyDict_* API would be 
making things even more fun for you than they already are (as Duncan pointed out).

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: assigning a custom mapping type to __dict__

2005-03-02 Thread Nick Coghlan
Steven Bethard wrote:
support.  Inheriting from dict likely means you have to redefine a bunch 
of functions to raise Exceptions saying that they're unsupported.
Hmm. . .
We've got the NotImplemented singleton already to let special methods say "I 
thought I might be able to handle this, but I can't".

Maybe "__op__ = NotImplemented" should clear the associated slot. It would also 
make it easier to inherit from list and handle slices in __getitem__ by writing 
"__getslice__ = NotImplemented" instead of overriding __getslice__ to delegate 
to __getitem__.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decimal, __radd__, and custom numeric types...

2005-03-02 Thread Nick Coghlan
Blake T. Garretson wrote:
Thanks for the suggestions and modified module.  I will probably just
use this "fixed" module to solve my immediate problem.
Expect its performance to be worse than the standard version - it does the right 
thing, but it sure ain't pretty. . .

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


PEP 246 revision

2005-03-02 Thread boisgera


I had a look at the new reference implementation of PEP 246
(Object Adaptation) and I feel uneasy with one specific point
of this new version. I don't fully understand why it checks
if *the type of* the protocol has a method "__adapt__":

...
# (c) then check if protocol.__adapt__ exists & likes obj
adapt = getattr(type(protocol), '__adapt__', None)
...

As a consequence of this change, you can't define a protocol
as a class that implements __adapt__ anymore.

class Protocol(object):
def __adapt__(self, obj):
...

Instead, you may inherit from a class "AdaptingProtocol" ...

class Protocol(AdaptingProtocol):
@classmethod
def adapt(cls, obj):
...

... that uses a specific metaclass

class MetaAdaptingProtocol(type):
def __adapt__(cls, obj):
return cls.adapt(obj)

class AdaptingProtocol:
__metaclass__ = MetaAdaptingProtocol
@classmethod
def adapt(cls, obj):
pass

That seems to be a bit complicated ... A I missing something ?

SB

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


Re: yield_all needed in Python

2005-03-02 Thread Nick Coghlan
Douglas Alan wrote:
Steve Holden <[EMAIL PROTECTED]> writes:

Guido has generally observed a parsimony about the introduction of
features such as the one you suggest into Python, and in particular
he is reluctant to add new keywords - even in cases like decorators
that cried out for a keyword rather than the ugly "@" syntax.

In this case, that is great, since I'd much prefer
   yield *gen1(arg)
If you do write a PEP, try to get genexp syntax supported by the yield 
keyword.
That is, the following currently triggers a syntax error:
  def f():
yield x for x in gen1(arg)
I wouldn't mind seeing it successively yield the values returned by gen1() 
instead. To my mind that better conveys what's going on than putting the yield 
statement inside the for loop (it should also provide the opportunity to 
optimise the next() calls by temporarily swapping the outer generator's frame 
for the inner generator's frame, and swapping them back only when the inner 
generator is exhausted)

That syntax error I mentioned makes it backwards compatible, too (existing code 
must have parentheses around the genexp, which will not by altered if the yield 
keyword gains a native genexp syntax).

If anyone thinks that this would result in a couple of parentheses making too 
much difference, consider this:

Py> [x for x in []]
[]
Py> [(x for x in [])]
[]
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


how to control a USB DISK?

2005-03-02 Thread zyqnews
hello all,
  I now have a simple project. It is to test the change of use disk,
when a new usb disk is plugged into the usb socket, the program will
copy a file to the usb disk, then disabled the usb disk to be pulled
out safely. I intend to make it with python. Does someone here get any
experiences about USB disk programming, and any suggestons ?
Thanks a lot.

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


Re: how to control a USB DISK?

2005-03-02 Thread Ola Natvig
[EMAIL PROTECTED] wrote:
hello all,
  I now have a simple project. It is to test the change of use disk,
when a new usb disk is plugged into the usb socket, the program will
copy a file to the usb disk, then disabled the usb disk to be pulled
out safely. I intend to make it with python. Does someone here get any
experiences about USB disk programming, and any suggestons ?
Thanks a lot.
if you are using windows:
Perhaps you can use COM to detect the evenet of the disk beeing placed 
in it's socket (i don't know if it's possible) and then jost copy the 
file. I gues that the real problem are the detecting of the session 
start and beeing able to disable the disk. I don't know which (if any) 
COM service that can be used.

ola
--
--
 Ola Natvig <[EMAIL PROTECTED]>
 infoSense AS / development
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help- Recursion v. Iter Speed comparison

2005-03-02 Thread Roy Smith
actuary77 <[EMAIL PROTECTED]> wrote:

> Recurse from  time: 4.305942779541 seconds
> 
> Iter from  time: 0.009904632568359 seconds
> 
> No comparison, why is recursion so slow?

I believe Edouard Manet said it best, "Damn your recursion, Henri. 
Iteration, however complex, is always more efficient." (extra points if you 
can identify the source of that quote).  It's not clear what language Manet 
was talking about when he said that, but it's pretty much a universal truth.

There's a fair amount of overhead in a function call.  You've got to push 
the arguments (and whatever state you need to save) onto the stack, and 
when the function returns, all that has to be undone.  Depending on the 
language, this may involve building temporary copies of objects.  If the 
function is small, the call-return overhead may totally swamp the real work 
done.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reuse validation logic with descriptors

2005-03-02 Thread David S.
Steve Holden  holdenweb.com> writes:


> You want assignment to a method-local variable to turn an attribute into 
> a property? That's programming with a magic wand ...
>  
> That will depend on the value returned by property access, surely?
> 
> I suspect you are a little confused about properties and descriptors.
> 
> regards
>   Steve

Quite confused, actually, which was the reason for my original post.  
Thanks again to those who helped me and any other confused folks 
understand this bit of Python that much better.
Peace,
David S.


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


Re: Closing dialog window in Tkinter

2005-03-02 Thread Svennglenn

Harlin Seritt wrote:
> You can add this:
>
> button = Button(top, text="Close Me", command=top.destroy)
> button.pack()
>
> That will kill the Toplevel window.
> 
> Cheers,
> 
> Harlin Seritt

Thank you, it worked great :)

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


Re: how to control a USB DISK?

2005-03-02 Thread Roland Heiber
Hi,
when you're under linux and a 2.6er kernel, take a look at hotplug, you 
can configure it the way that your script gets executed whenever a 
specific device is plugged in/out ...

HtH, Roland
[EMAIL PROTECTED] wrote:
when a new usb disk is plugged into the usb socket, the program will
copy a file to the usb disk, then disabled the usb disk to be pulled
out safely.
--
http://mail.python.org/mailman/listinfo/python-list


Distributing applications

2005-03-02 Thread Phillip Mills
I've learned enough of the Python language to be mildly dangerous and 
have used it in a few personal projects.  All my development of 
commercial (or production) products over the past dozen years have been 
done with C++ or Java.

For a program I'm planning -- to begin during the summer -- having an 
interpreter as part of the application would be very desirable to allow 
sophisticated users to provide their own extensions.  Java would be 
do-able, but

My problems are:
  - I'd like the process of installing the application to be one step; 
no "first download a Python interpreter then a GUI library" kind of 
thing.
  - I also need the core part of the application to be reasonably 
protected.  I'm not looking to defeat hackers, but something equivalent 
to the way Java's class files stored in jars stay where they're supposed 
to be and aren't immediately readable.

I've looked at various web sites for this topic, but most I've found are 
just arguments for using the Python language.  OK, I'll pretend I'm 
convinced...now any comments or references on the mechanics of creating 
a self-contained distribution?

-- 
Phillip Mills
Multi-platform software development
(416) 224-0714

== 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: yield_all needed in Python

2005-03-02 Thread Steven Bethard
Douglas Alan wrote:
Steven Bethard <[EMAIL PROTECTED]> writes:
I'm guessing the * syntax is pretty unlikely to win Guido's
approval. There have been a number of requests[1][2][3] for syntax
like:

x, y, *rest = iterable
Oh, it is so wrong that Guido objects to the above.  Python needs
fully destructuring assignment!
Yeah, there are a lot of folks that like this idea, but most of us are 
willing to conceded that Guido's intuition for these kind of things is 
generally pretty good.  This would be convenient for me occasionally, 
but I certainly wouldn't need it that often...

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


Stuck on Jythonc --all w/ ZipException PyMethod

2005-03-02 Thread Mitch Amiano
I'm getting started working with Jython (hope this is an ok group for 
the question), and ran into a stumbling block using the jythonc tool.

It is a fairly simple Jython script which uses the Apache Batik SVG 
library, imports the SVG Canvas, and puts up a simple Swing interface to 
let the user load and display an SVG file. (I translated the script from 
a Batik Java example.) The script runs fine under jython, but so far 
I've been unable to get a working jar file using jythonc.

After various problems involving CLASSPATH and the registry (protected 
members not showing up), it is persistently giving a ZipException: 
Duplicate entry error on the PyMethod class. Altering the CLASSPATH 
seems to have no effect on the problem.

Is this a problem between jythonc and newer jvms? I've also tried with 
j2sdk 1.4.2_05, with the same results.

I've exhausted other means, and at my wits end.
Thanks in advance for any pointers.

My command line is:
C:\jython-2.1\jythonc.bat --compiler C:\jdk1.5.0_01\bin\javac.exe --all 
-j usebatik.jar usebatik.py

The output is:
processing usebatik
Required packages:
  javax.swing
  org.w3c.dom
  java.awt.event
  java.lang
  java.io
  org.apache
Creating adapters:
  java.awt.event.ActionListener used in usebatik
Creating .java files:
  usebatik module
Compiling .java to .class...
Compiling with args: ['C:\\jdk1.5.0_01\\bin\\javac.exe', '-classpath', 
'C:\\jython-2.1\\jython.jar;;.\\jpywork;;C:\\jython-2.1\\Tools\\jythonc;C:\\Documents 
and Settings\\Valued 
Customer\\Desktop\\Grazer\\usebatik\\.;C:\\jython-2.1\\Lib;C:\\jython-2.1', 
'.\\jpywork\\usebatik.java']
0  Note: * uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Building archive: usebatik.jar
Tracking java dependencies:
Traceback (innermost last):
  File "C:\jython-2.1\Tools\jythonc\jythonc.py", line 5, in ?
  File "C:\jython-2.1\Tools\jythonc\main.py", line 301, in main
  File "C:\jython-2.1\Tools\jythonc\main.py", line 294, in writeResults
  File "C:\jython-2.1\Tools\jythonc\jar.py", line 98, in dump
  File "C:\jython-2.1\Tools\jythonc\jar.py", line 92, in dumpFiles
  File "C:\jython-2.1\Tools\jythonc\jar.py", line 111, in addPackage
java.util.zip.ZipException: duplicate entry: org/python/core/PyMethod.class
	at java.util.zip.ZipOutputStream.putNextEntry(Unknown Source)
	at sun.reflect.GeneratedMethodAccessor30.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.python.core.PyReflectedFunction.__call__(PyReflectedFunction.java)
	at org.python.core.PyMethod.__call__(PyMethod.java)
	at org.python.core.PyObject.__call__(PyObject.java)
	at org.python.core.PyInstance.invoke(PyInstance.java)
	at jar$py.addPackage$11(C:\jython-2.1\Tools\jythonc\jar.py:111)
	at jar$py.call_function(C:\jython-2.1\Tools\jythonc\jar.py)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyFunction.__call__(PyFunction.java)
	at org.python.core.PyInstance.invoke(PyInstance.java)
	at jar$py.dumpFiles$9(C:\jython-2.1\Tools\jythonc\jar.py:92)
	at jar$py.call_function(C:\jython-2.1\Tools\jythonc\jar.py)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyFunction.__call__(PyFunction.java)
	at org.python.core.PyInstance.invoke(PyInstance.java)
	at jar$py.dump$10(C:\jython-2.1\Tools\jythonc\jar.py:98)
	at jar$py.call_function(C:\jython-2.1\Tools\jythonc\jar.py)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyFunction.__call__(PyFunction.java)
	at org.python.core.PyInstance.invoke(PyInstance.java)
	at main$py.writeResults$8(C:\jython-2.1\Tools\jythonc\main.py:294)
	at main$py.call_function(C:\jython-2.1\Tools\jythonc\main.py)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyFunction.__call__(PyFunction.java)
	at main$py.main$9(C:\jython-2.1\Tools\jythonc\main.py:301)
	at main$py.call_function(C:\jython-2.1\Tools\jythonc\main.py)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyFunction.__call__(PyFunction.java)
	at org.python.core.PyObject.invoke(PyObject.java)
	at org.python.pycode._pyx0.f$0(C:\jython-2.1\Tools\jythonc\jythonc.py:5)
	at 
org.python.pycode._pyx0.call_function(C:\jython-2.1\Tools\jythonc\jythonc.py)
	at org.python.core.PyTableCode.call(PyTableCode.java)
	at org.python.core.PyCode.call(PyCode.java)
	at org.python.core.Py.runCode(Py.java)
	at org.python.core.__builtin__.execfile_flags(__builtin__.java)
	at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java)
	at org.python.util.jyth

Re: assigning a custom mapping type to __dict__

2005-03-02 Thread Steven Bethard
Nick Coghlan wrote:
Steven Bethard wrote:
The problem with inheriting from dict is that you then need to 
override *all* the methods in the dict object, because they all go 
straight to Python's dict'c C code functions.  So just because you 
redefine __getitem__ doesn't mean you don't still have to redefine 
__contains__, get, update, etc.  UserDict.DictMixin can help with this 
some, but the ideal situation would be to only have to define the 
methods you actually support.  Inheriting from dict likely means you 
have to redefine a bunch of functions to raise Exceptions saying that 
they're unsupported.

You're just lucky the affected class is already overriding 
__getattribute__, so the __dict__ is generally getting accessed from 
Python code :)

If it weren't for that, object.c's direct calls to the PyDict_* API 
would be making things even more fun for you than they already are (as 
Duncan pointed out).
Yup, I noticed that.  Lucky us. =)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Distributing applications

2005-03-02 Thread Toby Dickenson
On Wednesday 02 March 2005 14:12, Phillip Mills wrote:
> now any comments or references on the mechanics of creating 
> a self-contained distribution?

Run to http://starship.python.net/crew/theller/py2exe/


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


Re: creating csv file from

2005-03-02 Thread Skip Montanaro
> "Sandeep" == Sandeep Avinash Gohad <[EMAIL PROTECTED]> writes:

Sandeep> How can i use the url as an input so that I can save data from
Sandeep> that particular webpage to comma seperated file (csv).

This worked for me:

import urllib, csv
reader = csv.reader(urllib.urlopen("http://.../some.csv";))
for row in reader:
print row

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


Re: Distributing applications

2005-03-02 Thread Jaime Wyant
I wanted a nice tightly-wrapped distribution of my own and really
didn't want to go the py2exe route.  I may have used a sledgehammer to
kill a fly, but here is what I did...

1) Downloaded python source (2.3.4)
2) Modified source, so that sys.path would pull from a registry key
setup by my installer.
2) Compiled python
3) Compiled wxPython 2.5.3.1
4) Bundled my app along with the custom python installation using NSIS.

My `setup.exe' file was 6654281 bytes -- not bad.  Considering its the
entire python distribution (I may have missed a couple of modules --
but i don't think so) and wxPython.

I chose not to use py2exe because it made updating my app a bit
messier.  For instance, suppose I don't use the smtplib module in
version 1 of my software.  Py2exe realizes that and doesn't 'package'
smtplib with my executable.  Now, if I release version 1.1 which does
use smtplib, then I'd have to figure out how to get the updates out
without having the user redownload the entire application.  Granted, I
didn't put much thought into an update mechanism, but it seemed to be
messy at the time.

If I have my own distribution, I can simply give the users an "update"
program that will query  my webserver which will download the latest
version for them automagically.  Because my distribution has all of
the modules already available, I don't have to worry about sending
them any missing modules.  Simply download the latest version of my
app and it works with my custom rolled distribution.

But, this only works for Windows...

jw

On Wed, 02 Mar 2005 09:12:26 -0500, Phillip Mills
<[EMAIL PROTECTED]> wrote:
> I've learned enough of the Python language to be mildly dangerous and
> have used it in a few personal projects.  All my development of
> commercial (or production) products over the past dozen years have been
> done with C++ or Java.
> 
> For a program I'm planning -- to begin during the summer -- having an
> interpreter as part of the application would be very desirable to allow
> sophisticated users to provide their own extensions.  Java would be
> do-able, but
> 
> My problems are:
>   - I'd like the process of installing the application to be one step;
> no "first download a Python interpreter then a GUI library" kind of
> thing.
>   - I also need the core part of the application to be reasonably
> protected.  I'm not looking to defeat hackers, but something equivalent
> to the way Java's class files stored in jars stay where they're supposed
> to be and aren't immediately readable.
> 
> I've looked at various web sites for this topic, but most I've found are
> just arguments for using the Python language.  OK, I'll pretend I'm
> convinced...now any comments or references on the mechanics of creating
> a self-contained distribution?
> 
> --
> Phillip Mills
> Multi-platform software development
> (416) 224-0714
> 
> == 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
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some simple coding help

2005-03-02 Thread Steven Bethard
mx2k wrote:
indeed, we're it is our combat timeline. we enter the initiative and
reaction time, it should find out the lowest then the next, then the
'n'th etc. and shouw it on the screen like
 Next action 'Character Name1' at tick No  'Initiative1
 2nd  action 'Character Name2' at tick No  'Initiative2'
 [...]
 'n'th action 'Character Name n' at tick No  'Initiative n'
  Now you enter a value by which the initiative should be increased,
then adding reaction time to that value and then adding the result to
reaction time. Now soring again by lowest,next,'n'th, etc. and then
again showing the output, asking for another number etc.
Not sure if I got your calculation right, but something like this should 
work:

py> characters
[Character('Steve', 3, 2), Character('mx2k', 5, 1)]
py> def get_init(character):
... return (character.initiative + character.reaction_time +
... int(raw_input('%s initiative: ' % character.name)))
...
py> def print_initiatives(characters, rounds):
... for _ in range(rounds):
... inits = dict([(character, get_init(character))
...   for character in characters])
... for character in sorted(inits, key=inits.__getitem__):
... print character, inits[character]
...
py> print_initiatives(characters, 3)
[... I type '5', '6' ...]
Character('Steve', 3, 2) 10
Character('mx2k', 5, 1) 12
[... I type '9', '1' ...]
Character('mx2k', 5, 1) 7
Character('Steve', 3, 2) 14
[... I type '1', '2' ...]
Character('Steve', 3, 2) 6
Character('mx2k', 5, 1) 8
If you want the characters in the opposite order, simply use
sorted(inits, key=inits.__getitem__, reverse=True)
instead of
sorted(inits, key=inits.__getitem__)
HTH,
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: any Python equivalent of Math::Polynomial::Solve?

2005-03-02 Thread Cousin Stanley
| In case you are still interested pygsl wraps the GSL solver.
| 
| from pygsl import poly
|
| pc = poly.poly_complex( 3 )
|
| tmp, rs = pc.solve( ( 2 , 3 , 1 ) )
|
| print rs
| 
|
| You get pygsl at http://sourceforge.net/projects/pygsl/
Pierre 
  I am still interested and have downloaded the PyGSL source
  from SourceForge and will attempt to build under Debian Linux 
  Thanks for the information 
--
Stanley C. Kitching
Human Being
Phoenix, Arizona
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need some simple coding help

2005-03-02 Thread Steven Bethard
mx2k wrote:
ah, and sorry for that 'unreadable' code, but that was our first try of
coding ever. we're working through the python documentaion right now -
and - thanks to the post by STeVe we at last now that we have to
construct a class for our purpose.
Well, you don't *have* to -- it could be done all with lists as you had. 
 But I think you'll find that it lends itself to a much cleaner 
solution.  Also, if you ever find yourself writing a list of 5 or more 
if statements, you're probably not going at the problem from the easiest 
angle.  Ask around, tell people what you're trying to do, and what you 
think your if statements are doing now, and they can probably point you 
to the easier way.

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


Re: [Python-Dev] Re: python-dev Summary for 2005-01-16 through 2005-01-31

2005-03-02 Thread Max M
Martin v. Löwis wrote:
Steve Holden wrote:
The more I participate, the more I can relate to Eric Raymond's notion
of a "gift society". Volunteers give their contributions to the
community just because they want to, and they may get recognition in
return. But because these are gifts, you can just stop giving them away
at any time, and nobody should feel bad about doing so. The community
only is only entitled to the contributor saying so - finding somebody
else to step in is indeed optional.
I write a few open source projects myself, and I get virtually no 
feedback or patches on anything. Only complaints if there are bugs :-)

But on the other hand I use a lot of other peoples code without commenting.
I guess that is the way it must work. You take leadership in a small 
area, and you keep it as long as you care to.

So while it might not feel as a "brotherhood of shared effort" in the 
single sub-project, it might very well be on a higher level.

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


Re: creating csv file from

2005-03-02 Thread Premshree Pillai
On Wed, 2 Mar 2005 08:27:35 -0600, Skip Montanaro <[EMAIL PROTECTED]> wrote:
> > "Sandeep" == Sandeep Avinash Gohad <[EMAIL PROTECTED]> writes:
> 
> Sandeep> How can i use the url as an input so that I can save data from
> Sandeep> that particular webpage to comma seperated file (csv).
> 
> This worked for me:
> 
> import urllib, csv
> reader = csv.reader(urllib.urlopen("http://.../some.csv";))
> for row in reader:
> print row

He's not opening a CSV file... he wants to open a 'regular' web-page,
and then "convert it to CSV".

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


-- 
Premshree Pillai
http://www.livejournal.com/users/premshree/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running Python Scripts With 'sudo'

2005-03-02 Thread Steve Holden
Tim Daneliuk wrote:
Given that setuid is a Bad Thing for scripts, what is the general consensus
here on running a Python script via 'sudo' to give it root system access?
Is this reasonably secure, or am I still asking for trouble?
TIA,
The value of "sudo" is that everyone must authenticate as themselves, 
and sudo logs all activity. Therefore the system administrators can 
partition responsibility and know from the logs exactly who did what.

The risks involved with setuid scripts involve the exploitation of race 
conditions within the kernel, IIRC, and since the root permissions are 
established by sudo for the invoking process, I believe sudo would 
eliminate the risks involved (because the setuid bit would no longer be 
used on the script).

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.pycon.org/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Stuck on Jythonc --all w/ ZipException PyMethod

2005-03-02 Thread Simon Brunning
On Wed, 02 Mar 2005 14:13:48 GMT, Mitch Amiano <[EMAIL PROTECTED]> wrote:
> I'm getting started working with Jython (hope this is an ok group for
> the question), and ran into a stumbling block using the jythonc tool.

Well, I'm sure that no one is going to object to Jython questions
here, but you might get more response on the Jython users list:

http://lists.sourceforge.net/lists/listinfo/jython-users

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Zope - Restrict Acquisition Question

2005-03-02 Thread Jack
I have the following requirement for Zope:
I need to use Zope as a web cloning tool.

The directory structure is as follows:
->>Core Folder
->>Client 1
->>Client 2
...
->>Client n

1] Client 1 and Client 2 need to acquire from the Core Folder.
2] Client 2 must not acquire from Client 1.
3] Client 1 must not acquire from Client 2.

Note: I know that creating a Zope object named Client 2 and putting it
into Client 1's folder will work but there will be about 50+ clients.
So that would require 50+ objects in each client folder.

There's got to be a better way ... Any Ideas?

Thanks!

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


What e-mail list provides the best support for Twisted?

2005-03-02 Thread Andy Leszczynski
Thx, A.
--
http://mail.python.org/mailman/listinfo/python-list


rearrange text

2005-03-02 Thread Daniel Skinner
If I have the following text

var = '1,2,3,4'

and I want to use the comma as a field delimeter and rearrange the
fields to read

'1,3,2,4'

How would I accomplish this in python?

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


Dr. Dobb's Python-URL! - weekly Python news and links (Mar 1)

2005-03-02 Thread Cameron Laird
Editor's note:  "Python-URL!" is minimal.  It doesn't support advertisements,
we never allow the subscribers' addresses to be used for other purposes, we
don't claim infallibility, and we even take a couple weeks off some years.
Occasionally, though--not as often as the US enters a shooting war, say,
but more frequently than IBM hires a new CEO--we pause for a sufficiently
important correction or announcement.  This year, we apologize for
inexplicably changing Oliver Schoenborn's name a couple of weeks ago to
"Philip".  Also, has anyone indexed Python bloggers (that is, webloggers
of things Pythonic)?


QOTW:  "... more like generator included." -- Efrat Regev, on the proper
characterization of our language of choice

VOTW:  Steves break ground on VOTWs.  Notice the surrounding serious
discussions on what exactly makes for an improvement in the language.
http://groups-beta.google.com/group/comp.lang.python/msg/1c39adfc9408e225
http://groups-beta.google.com/group/comp.lang.python/msg/1fb3718aee61e4a7


Andrew Kuchling's explanation of PyZeroconf is exemplary:
http://www.amk.ca/python/zeroconf

All those calendrical/temporal things you need that the standard
datetime module doesn't supply?  Gustavo Niemeyer supplies (most
of) them:
https://moin.conectiva.com.br/DateUtil

Laugh?  Cry?  Appeal to the UN?  Not only can Python define "(almost)
arbitrary infix operators", but you can parametrize their production,
with "probably the best Python hack *ever*":
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122

Python 3000 might be real, and relatively free of trauma:
http://mail.python.org/pipermail/python-dev/2005-January/051363.html

Graybeard Steve Holden rambles through the sort of speech that
commentators usually take as a sign of breakdown.  In this
case, though, the delivery has the virtues of:  accuracy; and
relevance:

http://groups-beta.google.com/group/comp.lang.python/msg/9eb125ba50863d57

The state of the art of use of decorations continues to advance:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/133cf2869cc6907d/

Pythoneers, too, can solve polynomials (although probably not without
obscure astronomical, linguistic, artistic, ... references):

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/4a4db288862f890f/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Brett Cannon continues the marvelous tradition established by 
Andrew Kuchling and Michael Hudson of intelligently summarizing
action on the python-dev mailing list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

The Python Business Forum "further[s] the interests of companies
that base their business on ... Python."
http://www.python-in-business.org

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cet

Re: rearrange text

2005-03-02 Thread Roel Schroeven
Daniel Skinner wrote:
> If I have the following text
> 
> var = '1,2,3,4'
> 
> and I want to use the comma as a field delimeter and rearrange the
> fields to read
> 
> '1,3,2,4'
> 
> How would I accomplish this in python?

I take it you want to swap the second and the third element? That can be
accomplished by splitting into a list of fields, swap the second and
third element, join the fields back to a string:

 >>> var  = '1,2,3,4'
 >>> fields = var.split(',')
 >>> fields
 ['1', '2', '3', '4']
 >>> fields[1], fields[2] = fields[2], fields[1]
 >>> fields
 ['1', '3', '2', '4']
 >>> newvar = ','.join(fields)
 >>> newvar
 '1,3,2,4'


-- 
"Codito ergo sum"
Roel Schroeven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: rearrange text

2005-03-02 Thread Simon Brunning
On 2 Mar 2005 07:36:48 -0800, Daniel Skinner <[EMAIL PROTECTED]> wrote:
> If I have the following text
> 
> var = '1,2,3,4'
> 
> and I want to use the comma as a field delimeter 

That bit's easy:

C:\WINNT\system32>python
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> var = '1,2,3,4'
>>> split_var = var.split(',')
>>> split_var
['1', '2', '3', '4']

> and rearrange the
> fields to read
> 
> '1,3,2,4'

I don't really understand this rearrangement, but I'll do it the dumb way:

>>> rearranged_var = split_var[0], split_var[2], split_var[1], split_var[3]
>>> rearranged_var
('1', '3', '2', '4')

Then you can join it all up again like so:

>>> ','.join(rearranged_var)
'1,3,2,4'

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: rearrange text

2005-03-02 Thread Daniel Skinner
ah thanks I couldn't figure out how to join it up very appropriately,
had this loop ... yeeeaah .. :)

Thanks for both comments

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


Re: HELP: Python equivalent of UNIX command "touch"

2005-03-02 Thread pekka niiranen
Roy Smith wrote:
pekka niiranen  <[EMAIL PROTECTED]> wrote:
Does anybody know Python recipe for changing the date
of the directory or files in W2K to current date and time?
In UNIX shell command "touch" does it.

You want os.utime()
Nope, it does not work for directories in Windows
--
http://mail.python.org/mailman/listinfo/python-list


Re: HELP: Python equivalent of UNIX command "touch"

2005-03-02 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
pekka niiranen  <[EMAIL PROTECTED]> wrote:
>Roy Smith wrote:
>> pekka niiranen  <[EMAIL PROTECTED]> wrote:
>> 
>>>Does anybody know Python recipe for changing the date
>>>of the directory or files in W2K to current date and time?
>>>In UNIX shell command "touch" does it.
>> 
>> 
>> You want os.utime()
>
>Nope, it does not work for directories in Windows

Well, there's always the old fashioned way (which early versions of
touch used).  Read the first byte of the file, rewind, write the byte
back out, seek to the end (to preserve the file length), and close the
file.  I'm not sure what to do for directories (I guess you could
create and delete a temp file).

Of course, if you told me that doesn't work on Windows either, I
wouldn't be too surprised. :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] IPython 0.6.12 is out.

2005-03-02 Thread Fernando Perez
Hi all,

I'm glad to announce the release of IPython 0.6.12.  This is mainly a bugfix
release.

IPython's homepage is at:

http://ipython.scipy.org

and downloads are at:

http://ipython.scipy.org/dist

I've provided RPMs (for Python 2.3 and 2.4, built under Fedora Core 3), plus
source downloads (.tar.gz).  We now also have a native win32 installer which
should work correctly for both Python 2.3 and 2.4.

Debian, Fink and BSD packages for this version should be coming soon, as the
respective maintainers (many thanks to Jack Moffit, Andrea Riciputi and Dryice
Liu) have the time to follow their packaging procedures.

Many thanks to Enthought for their continued hosting support for IPython, and
to all the users who contributed ideas, fixes and reports.


WHAT is IPython?


1. An interactive shell superior to Python's default. IPython has many
features for object introspection, system shell access, and its own special
command system for adding functionality when working interactively.

2. An embeddable, ready to use interpreter for your own programs. IPython can
be started with a single call from inside another program, providing access to
the current namespace.

3. A flexible framework which can be used as the base environment for other
systems with Python as the underlying language.


Release notes
-

As always, the NEWS file can be found at http://ipython.scipy.org/NEWS, and
the full ChangeLog at http://ipython.scipy.org/ChangeLog.

* New hooks system.  This can be considered the first step in cleaning up
ipython to expose its internals in a more rational manner.  IPython/hooks.py
contains the hooks which are meant to be easily overridden by users for
customizations.  Currently only the editor hook (called by %edit) exists, but
a framework is in place.

* Fix a subtle bug with corrupted init files under win32, thanks to Ville
Vainio for trackign this.

* Fix for Debian, which recently removed the profiler module from the default
python distribution and moved it to non-free.

* Allow empty and left-aligned output prompts, if users so want them.

* New %time magic to time statements and expressions.  It reports CPU and wall
clock time.

* Other small fixes and cleanups.


Enjoy, and as usual please report any problems.

Regards,

Fernando.

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


ANNOUNCE: Kamaelia 0.1.1 Released

2005-03-02 Thread Michael Sparks
Kamaelia 0.1.1 has been released!

This is the initial release version of Kamaelia.

What is it?
===
Kamaelia is a collection of Axon components designed for network
protocol experimentation in a single threaded, select based
environment. Axon components are python generators are augmented by
inbox and outbox queues (lists) for communication in a communicating
sequential processes (CSP) like fashion.

The architecture is specifically designed to try and simplify the
process of designing and experimenting with new network protocols in
real environments.

This release contains components allowing the creation of TCP based
clients and servers, and includes a few (very) simple protocol handlers
to show usage.

Other components include vorbis decode and playback, asynchronous file
reading, and equivalents of "tee" and "strings". (Writing systems is
much like building unix pipelines, hence the need for similar tools)

Examples

Sample echo server: (default generator callback style)

from Kamaelia.SimpleServerComponent import SimpleServer
from Axon.Component import component, scheduler

class EchoProtocolCB(component):
def mainBody(self):
  if self.dataReady("inbox"):
 data = self.recv("inbox")
 self.send(data,"outbox")
  if self.dataReady("control"):
 data = self.recv("control")
 return 0
  return 1

SimpleServer(protocol=EchoProtocolCB).activate()
scheduler.run.runThreads(slowmo=0)

Sample echo server: (Normal generator style)

from Kamaelia.SimpleServerComponent import SimpleServer
from Axon.Component import component, scheduler

class EchoProtocol(component):
   def main(self):
  while 1:
 if self.dataReady("inbox"):
data = self.recv("inbox")
self.send(data,"outbox")
 if self.dataReady("control"):
data = self.recv("control")
return
 yield 1

SimpleServer(protocol=EchoProtocol).activate()
scheduler.run.runThreads(slowmo=0)

The two styles are provided for those comfortable with generators and
those who aren't. The plain generator form can be particularly useful
in simplifying error handling (see Kamaelia.Internet.TCPClient for an
example). The callback form is useful for implementing components in
other languages - eg pyrex.

Requirements

   * Python 2.3 or higher recommended, though please report any bugs
 with 2.2.
   * Axon (Any released version, 1.0.3 recommended, 1.0.4 when released)
   * vorbissimple (if you want to use the vorbis decode component)

(Both Axon and vorbissimple are separate parts of the Kamaelia project,
and available at the same download location - see below)

Platforms
=
Kamaelia has been used successfully under both Linux and Windows (2000
and ME).

(This has not yet been tested with Axon running on series 60 mobiles
since to the select module hasn't been released for Series 60 mobiles
yet)

Where can I get it?
===
Web pages are here:
   http://kamaelia.sourceforge.net/Docs/
   http://kamaelia.sourceforge.net/ (includes info on mailing lists)

ViewCVS access is available here:
   http://cvs.sourceforge.net/viewcvs.py/kamaelia/

Licensing
=
Kamaelia is released under the Mozilla tri-license scheme (MPL/ GPL/
LGPL). Specifically you may choose to accept either the Mozilla Public
License 1.1, the GNU General Public License 2.0 or the Lesser General
Public License 2.1. Proprietary terms and conditions available upon
request.

Best Regards,


Michael.
-- 
Michael Sparks, Senior R&D Engineer, Digital Media Group
[EMAIL PROTECTED]
British Broadcasting Corporation, Research and Development
Kingswood Warren, Surrey KT20 6NP

This message (and any attachments) may contain personal views
which are not the views of the BBC unless specifically stated.


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


Re: Distributing applications

2005-03-02 Thread André Søreng
Phillip Mills wrote:
I've learned enough of the Python language to be mildly dangerous and 
have used it in a few personal projects.  All my development of 
commercial (or production) products over the past dozen years have been 
done with C++ or Java.

For a program I'm planning -- to begin during the summer -- having an 
interpreter as part of the application would be very desirable to allow 
sophisticated users to provide their own extensions.  Java would be 
do-able, but

My problems are:
  - I'd like the process of installing the application to be one step; 
no "first download a Python interpreter then a GUI library" kind of 
thing.
For creating a self-contained installation/distribution under Windows,
use py2exe:
http://starship.python.net/crew/theller/py2exe/
If you want to create a nice Windows installer for your module(s):
http://www.python.org/doc/current/dist/postinstallation-script.html

  - I also need the core part of the application to be reasonably 
protected.  I'm not looking to defeat hackers, but something equivalent 
to the way Java's class files stored in jars stay where they're supposed 
to be and aren't immediately readable.

Hmm, not sure about that one. You mean that those users who write 
extensions should not be able to modify the core code you wrote? Are you
talking about a restricted execution environment for untrusted code?
I'd rather make it so to only accept code which is signed by a trusted 
party or something like that.

I've looked at various web sites for this topic, but most I've found are 
just arguments for using the Python language.  OK, I'll pretend I'm 
convinced...now any comments or references on the mechanics of creating 
a self-contained distribution?

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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-03-02 Thread konrad . hinsen
Carl Banks wrote:

> If you don't have a great need for speed, you can accomplish this
> easily with the linear algebra module of Numeric/numarray.   Suppose
> your quintic polynomial's in the form
>
>a + b*x + c*x**2 + d*x**3 + e*x**4 + x**5
>
> The roots of it are equal to the eigenvalues of the companion matrix:
>
>   0   1   0   0   0
>   0   0   1   0   0
>   0   0   0   1   0
>   0   0   0   0   1
>  -a  -b  -c  -d  -e

The method "zeros()" in Scientific.Functions.Polynomial uses exactly
that trick for finding the zeros of a general polynomial. If you need
to do more with polynomials than just finding the zeros, the Polynomial
class is probably better than an on-the-spot solution.

Root finding through eigenvalues is not the fastest method, but it's
simple and stable, and not terribly bad either.

Sorry for not making that comment earlier, I don't have the time to
follow this list at the moment (to my great regret), but I was made
aware of this thread through PythonURL.

Konrad.

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


Re: Problem in Dictionaries

2005-03-02 Thread Terry Reedy

"Glauco Silva" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I would like to know if the dictionary can sort with a function that i 
>give to then!

No.  You have to either make a list of key,value items and sort that, 
possibly with a cmp or key parameter

items = d.items()
items.sort(()

or write or find a sorted_dict class (Google may help).  In most 
applications, people find that they only need a sorted listing of a dict 
occasionally, so they just use the fast builtin dict and the fast builtin 
list sort when needed.

Terry J. Reedy



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


Re: What's the cost of using hundreds of threads?

2005-03-02 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Przemys³aw Ró¿ycki  <[EMAIL PROTECTED]> wrote:
>Thanks for your comments on winXP threads implementation. You confirmed 
>me in conviction that I shouldn't use windows.
>Personally I use linux with 2.6.10 kernel, so hopefully I don't have to 
>share your grief. ;)

?  !?  I'm confused, and apparently I'm confusing others.
The one message I posted in this thread--largely reinforced
by others--emphasizes only that WinXP is far *better* than
earlier Win* flavors in its thread management.  While I not
only agree that Windows has disadvantages, but have stopped
buying it for our company, my reasons have absolutely nothing
to do with the details of implementation of WinXP.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the cost of using hundreds of threads?

2005-03-02 Thread Przemysław Różycki
> In article <[EMAIL PROTECTED]>,
> Przemysław Różycki  <[EMAIL PROTECTED]> wrote:
>
>> Thanks for your comments on winXP threads implementation. You 
confirmed me in conviction that I shouldn't use windows.
>> Personally I use linux with 2.6.10 kernel, so hopefully I don't have 
to share your grief. ;)
>
>
>
> ?  !?  I'm confused, and apparently I'm confusing others.
> The one message I posted in this thread--largely reinforced
> by others--emphasizes only that WinXP is far *better* than
> earlier Win* flavors in its thread management.  While I not
> only agree that Windows has disadvantages, but have stopped
> buying it for our company, my reasons have absolutely nothing
> to do with the details of implementation of WinXP.
>
:) . Ok, perhaps my answer wasn't that precise. I wrote my post only to 
say that your discussion on windows' threading performace doesn't 
concern me - because my program is written for linux environment. And 
yes, I agree that my comment could sound a bit enigmatic.
--
http://mail.python.org/mailman/listinfo/python-list


Re: yield_all needed in Python

2005-03-02 Thread Terry Reedy

"Steven Bethard" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Douglas Alan wrote:
>> In this case, that is great, since I'd much prefer
>>
>>yield *gen1(arg)
>>
>> than
>>
>>yield_all gen1(arg)
>
> I'm guessing the * syntax is pretty unlikely to win Guido's approval. 
> There have been a number of requests[1][2][3] for syntax like:
>
> x, y, *rest = iterable
>
> for unpacking a variable sized list (where *rest would work in an 
> analogous way to what it does in the args of a def.)  Guido has 
> consistently rejected these proposals, e.g.:
>
> "I think it's not worth adding now, and if you don't hear from me again 
> on this topic it's because I haven't changed my mind..."
>
> My suspicion is that if he doesn't like the * syntax when there's a close 
> parallel to the argument parsing usage, he's not likely to like it when 
> there isn't one.

Hmm.  My impression is that Guido did not like x,*y=iterable because he 
does *not* see it as a 'close parallel' but as a strained analogy.  To me, 
yield *iterable is closer to the use in function calling.  It would mean 
'unpack in time' rather than 'unpack in space' but that is natural (to me, 
anyway) since that is what generators are about.

In any case, I also like this better than yield_all and would estimate that 
it a higher chance of accceptance, even if still under 50%.  Part of the 
justification could be that the abbreviated form is much easier to speed up 
than the expanded form.  If the ref count of the iterator is just 1, then 
it might be reasonable to assume that iterator.next will not be called from 
anywhere else.  (IE, I can't think of an exception, but know that there 
might be one somehow.)

Terry J. Reedy


Terry J. Reedy



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


Re: possible python/linux/gnome issue!!

2005-03-02 Thread JanC
bruce schreef:

> i'm running rh8.0 with gnome.. i'm not sure of the version (it's
> whatever rh shipped).
> 
> i've recently updated (or tried to update) python to the latest
> version. when i try to run the 'Server Settings/Services' Icon within
> gnome, nothing happens...
> 
> i tried to run the 'start services' command from a command line, and
> got the following...
> 
> it appears to be a conflict somewhere...

Red Hat uses Python for their configuration tools.  It seems like those 
are not compatible with the newer python version you installed.

You should keep the older Python version installed & make sure the Red Hat 
tools use that instead of (I think) the newer version.

-- 
JanC

"Be strict when sending and tolerant when receiving."
RFC 1958 - Architectural Principles of the Internet - section 3.9
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looking for expertise

2005-03-02 Thread klappnase
"Neil Hodgson" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> Michael:
> 
> > 5. file operations seem to be delicate; at least I got an error when I
> > passed a filename that contains special characters as unicode to
> > os.access(), so I guess that whenever I do file operations
> > (os.remove(), shutil.copy() ...) the filename should be encoded back
> > into system encoding before;
> 
>This can lead to failure on Windows when the true Unicode file name can
> not be encoded in the current system encoding.
> 
>Neil

Like I said, it's only supposed to run on linux; anyway, is it likely
that problems will arise when filenames I have to handle have
basically three sources:

1. already existing files

2. automatically generated filenames, which result from adding an
ascii-only suffix to an existing filename (like xy --> xy_bak2)

3. filenames created by user input

?
If yes, how to avoid these?

Any hints are appreciated

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


Re: Need some simple coding help

2005-03-02 Thread Terry Reedy

"mx2k" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>  Now you enter a value by which the initiative should be increased,
> then adding reaction time to that value and then adding the result to
> reaction time. Now soring again by lowest,next,'n'th, etc. and then
> again showing the output, asking for another number etc.

If I correct understand your goal, you might use a priority queue (heap) 
(there is one in the standard library).  You insert all chars with the 
initial response time as the 'key'.  You remove the one who is going to 
respond first and perform his actions.  If he is to get another turn, add 
his next reaction time to the current value and insert him back into the 
queue.  The next character to act will then be at the front of the queue. 
Repeat.

Terry J. Reedy



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


Re: Identify and perform actions to data within stated limits

2005-03-02 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I found the len(*) obscurely mentioned on someones webpage.

*All* the built functions are prominently listed and described in Library 
Reference 2.1Built-in Functions.  I urge you and any beginner to at least 
read the whole of chapter 2.

Terry J. Reedy





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


Re: Python Online Programming Contest

2005-03-02 Thread Varun
Hi,
The results of OPC (online programming contest) is out. The statistics
of python usage is available at
http://www.samhita.info/opc/status.php.
Regards,
-OPC Team

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


How would you program this?

2005-03-02 Thread engsol
There is a number puzzle which appears in the daily paper.
Because I'm between Python projects, I thought it might be
fun to write a program to solve it20 minute job, max.

On closer inspection, it became apparent that it's not a
simple thing to program. How would you approach it?

The puzzle: a 4 x 4 grid. The rows are summed (and given), the
cols are summed (and given), and the two diagonals are summed,
and given. In addition, 4 clues are given, but none of the 4 are in
the same row or col.

Example from today's paper:...solution time is 8 minutes, 1 second,
so they say.

The set of allowable numbers  is 1 thru 9

Rows:
3 + B + C + D = 22
E + F + 8 + H = 26
I + J + K + 8 = 31
M + 7 + O + P = 25

Col sums:
24, 18, 31, 31

Diag sums:
3 + F + K + P = 24
M + J + 8 + D = 24



The first impulse is to just brute force it with nested for loops,
but the calculator shows the possible combinations are 
9^12 = 5,159,780,352, which would take much too long.

Another approach would be to inspect each square and determine
what the range of reasonable numbers would be. For example,

if A + 9 + C + D = 14, then A, C, D can only have a value of 1 or 2 or 3,
which would greatly reduce the for loop range of A, C and D. 
While useful, it's still a manual task.

I can't help but think there's a better way. If you have a real Python
project, this isn't worth your time, but if a student, it might be a good
exercise to think how you'd do it.
Norm B
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help- Recursion v. Iter Speed comparison

2005-03-02 Thread Kent Johnson
Roy Smith wrote:
I believe Edouard Manet said it best, "Damn your recursion, Henri. 
Iteration, however complex, is always more efficient." (extra points if you 
can identify the source of that quote).  It's not clear what language Manet 
was talking about when he said that, but it's pretty much a universal truth.
GIYF
http://www.sprex.com/else/sidman/boite.html
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Distributing applications

2005-03-02 Thread Serge Orlov
Jaime Wyant wrote:
> I chose not to use py2exe because it made updating my app a bit
> messier.  For instance, suppose I don't use the smtplib module in
> version 1 of my software.  Py2exe realizes that and doesn't 'package'
> smtplib with my executable.  Now, if I release version 1.1 which does
> use smtplib, then I'd have to figure out how to get the updates out
> without having the user redownload the entire application.  Granted,
> I didn't put much thought into an update mechanism, but it seemed to
> be messy at the time.

I don't follow you. How is that different compared to adding a module
to your application? Let's say version 1.1 of your software has
module1.py updated, module2.py added and it needs smtplib. You just
bundle three compiled files and unpack them let's say to
\program files\my software\module1.pyc
\program files\my software\module2.pyc
\program files\my software\python\smtplib.pyc

I don't see any mess.

>
>If I have my own distribution, I can simply give the users an "update"
> program that will query  my webserver which will download the latest
> version for them automagically.  Because my distribution has all of
> the modules already available, I don't have to worry about sending
> them any missing modules.  Simply download the latest version of my
> app and it works with my custom rolled distribution.
>
> But, this only works for Windows...

Why? As I understand "update" program was written by you, so what
prevents it from working on other platforms besides testing?

  Serge.

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


Re: How would you program this?

2005-03-02 Thread Russell Blau
"engsol" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> There is a number puzzle which appears in the daily paper.
> Because I'm between Python projects, I thought it might be
> fun to write a program to solve it20 minute job, max.
>
> On closer inspection, it became apparent that it's not a
> simple thing to program. How would you approach it?
>
> The puzzle: a 4 x 4 grid. The rows are summed (and given), the
> cols are summed (and given), and the two diagonals are summed,
> and given. In addition, 4 clues are given, but none of the 4 are in
> the same row or col.
>
> Example from today's paper:...solution time is 8 minutes, 1 second,
> so they say.
>
> The set of allowable numbers  is 1 thru 9
>
> Rows:
> 3 + B + C + D = 22
> E + F + 8 + H = 26
> I + J + K + 8 = 31
> M + 7 + O + P = 25
>
> Col sums:
> 24, 18, 31, 31
>
> Diag sums:
> 3 + F + K + P = 24
> M + J + 8 + D = 24
>
>
>
> The first impulse is to just brute force it with nested for loops,
> but the calculator shows the possible combinations are
> 9^12 = 5,159,780,352, which would take much too long.
>

What you have is a set of 10 linear equations in 11 variables.  Normally
that isn't
enough to generate a unique solution, but the additional constraint that all
variables must have values in the range 1..9 probably will get you to a
unique solution.  I suggest you Google for techniques for solving
"simultaneous linear equations".


-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.



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


Re: How would you program this?

2005-03-02 Thread James Stroud

>
> Rows:
> 3 + B + C + D = 22
> E + F + 8 + H = 26
> I + J + K + 8 = 31
> M + 7 + O + P = 25
>
> Col sums:
> 24, 18, 31, 31
>
> Diag sums:
> 3 + F + K + P = 24
> M + J + 8 + D = 24
>
>
>

This is a system of 12 variables and 10 equations. Looks like there will be 
more than one solution (if I remember my 8th grade algebra--its beginning to 
get very foggy). Given a proper set of linear equations, I think numarray and 
scientific python have very convenient tools for this. An introductory linear 
algebra book can provide everything you need to know about this topic.

-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Non-blocking input on windows, like select in Unix

2005-03-02 Thread Jonathan Fine
fraca7 wrote:
Jonathan Fine a écrit :
Paul Rubin wrote:

As I recall, some posts to this list say that Windows provides
non-blocking i/o for sockets but not for files.

No, Windows does provide non-blocking I/O for regular files, but it's a 
completely different mechanism than the one used by winsock. You'll have 
to use win32all and enter the Dark Side, that is Windows APIs.

You don't want to do that if you're not already familiar with 
CreateProcess, CreatePipe, overlapped structures, WaitForSingleObject & 
al...

Thank you for this.
My application will, I think, become much more complicated if I cannot
use non-blocking input.  (As already explained, it is not a problem
that can be solved by threads.  Basically, I _need_  either to read
all available data, _or_ to read very carefully a byte at a time.)
Knowing that non-blocking input can be done under Windows, I would
like to use it.  In the longer run, that will be easier than
rewriting my application.  Or so it seems to me.
I did a google search, on the web, for
  CreateProcess, CreatePipe, overlapped structures, WaitForSingleObject
This is the first page is produced
  http://www.codeproject.com/threads/anonpipe1.asp
Seems to be the right sort of thing.  But I don't have time to read it
now.
I'm not really a Windows programmer.  Don't know the system calls.
But I do want my application to run on Windows.
I'll get back to this in a couple of weeks.  (Busy right now.)
--
Jonathan
--
http://mail.python.org/mailman/listinfo/python-list


Re: ZoDB's capabilities

2005-03-02 Thread Dieter Maurer
Larry Bates <[EMAIL PROTECTED]> writes on Mon, 28 Feb 2005 18:48:39 -0600:
> There is a VERY large website that uses Zope/ZODB that takes up to
> 9000 hits per second when it gets busy.  ZODB is very fast and
> holds up well under load.

But, you will not get 9000 hits per second from the ZODB (unless
both your disk and your processor are unexpectedly fast).

To get 9000 hits per second, you need extensive caching.


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


Re: java crashes in python thread

2005-03-02 Thread Dieter Maurer
Easeway wrote:
> I use os.system invoking java VM, when running in python thread, the
> java application crashes.

Andreas Jung has reported similar behaviour.

He suggested that Java 1.4 and the threads of Linux 2.6
do not work reliably together.
He tried Java 1.5 and this combination crashes only occationally.
But this, it is not yet reliable...

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


Re: What's the cost of using hundreds of threads?

2005-03-02 Thread Aahz
In article <[EMAIL PROTECTED]>,
=?ISO-8859-2?Q?Przemys=B3aw_R=F3=BFycki?=
  <[EMAIL PROTECTED]> wrote:
>
>I don't spawn them because of computional reasons, but due to the fact
>that it makes my code much more simpler. I use built-in tcp features
>to achieve loadbalancing - every flow (directed through pipe) has it's
>own dedicated threads - separate for down- and upload. For every 'main
>connection' these threads share send and receive buffer. If any of
>pipes is congested the corresponding threads block on their send / recv
>functions - without affecting independence of data flows.
>
>Using threads gives me VERY simple code. To achieve this with poll /
>select would be much more difficult. And to guarantee concurrency and
>maximal throughput for all of pipes I would probably have to mirror
>code from linux TCP stack (I mean window shifting, data acknowlegement,
>retransmission queues). Or perhaps I exaggerate.

Maybe it would help if you explained what these "pipes" do.  Based on
what you've said so far, what I'd do in your situation is create one
thread per pipe and one thread per connection, then use Queue to move
data between threads.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code -- 
not in reams of trivial code that bores the reader to death."  --GvR
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distributing applications

2005-03-02 Thread Phillip Mills
First, thanks to all the people who have answered so far for the 
suggestions.

In article <[EMAIL PROTECTED]>,
 André Søreng <[EMAIL PROTECTED]> wrote:

> Phillip Mills wrote:

> > My problems are:

[...]

> http://starship.python.net/crew/theller/py2exe/

Apparently I had more problems than I mentioned.  :-)  One of them being 
that a Windows-only solution is only a partial solution.

> >   - I also need the core part of the application to be reasonably 
> > protected.  I'm not looking to defeat hackers, but something equivalent 
> > to the way Java's class files stored in jars stay where they're supposed 
> > to be and aren't immediately readable.
> > 
> Hmm, not sure about that one. You mean that those users who write 
> extensions should not be able to modify the core code you wrote?

Partly that and partly a file management thing.  For most end users a 
.jar is one thing to deal with; it's the most recent one or it's not; 
it's present in the right location or it's not

-- 
Phillip Mills
Multi-platform software development
(416) 224-0714

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


Mail System Error - Returned Mail

2005-03-02 Thread imre . adam
The original message was received at Wed, 2 Mar 2005 20:06:59 +0100
from 87.26.243.56

- The following addresses had permanent fatal errors -


- Transcript of session follows -
... while talking to python.org.:
554 Service unavailable; [188.60.170.174] blocked using relays.osirusoft.com
Session aborted, reason: lost connection

  Virus Warning Message 
The virus (W32/[EMAIL PROTECTED]) was detected in the attachment 
attachment.zip. The
attached File attachment.zip has been removed.

Nachfolgender Virus (W32/[EMAIL PROTECTED]) wurde im Attachment attachment.zip 
gefunden,
deshalb wurde das Attachment attachment.zip gelöscht.
Für Fragen dazu steht Ihnen der chello Helpdesk sehr gerne zur Verfügung.
Weitere Informationen zum Virenschutz: http://portal.chello.at/av-info.html

Le serveur de mail chello a détecté le virus W32/[EMAIL PROTECTED] dans le 
fichier
attachment.zip inclus dans ce mail. Ce fichier attachment.zip a donc été 
supprimée
pour en éviter la diffusion. Pour plus d'information, merci de cliquer sur
le lien suivant  http://www.chello.fr

Az Önnek kézbesített levél mellékletében a vírusszűrő rendszer a(z)
W32/[EMAIL PROTECTED] nevű vírust találta, ezért a(z) attachment.zip nevű 
mellékletet biztonsági okokból eltávolította.
További információért, kérjük kattintson az alábbi hivatkozásra:
http://home.hun.chello.hu/upcmnfc/start/tamogatas/virusszures/

V příloze attachment.zip byl detekován virus W32/[EMAIL PROTECTED] Příloha 
attachment.zip byla proto odstraněna.
Pro dotazy kontaktujte prosím technickou podporu.

W załączniku attachment.zip wykryto wirus W32/[EMAIL PROTECTED] Plik 
attachment.zip został
usunięty. Więcej informacji znajdziesz na stronie internetowej:
http://home.pol.chello.pl/upcmnfc/start/pomoc/wirusy/

V priloženom súbore attachment.zip bol zistený vírus (W32/[EMAIL PROTECTED]).
Súbor attachment.zip bol odstránený. V prípade otázok prosím kontaktujte linku 
technickej podpory.
http://www.chello.sk

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

Re: Distributing applications

2005-03-02 Thread Jaime Wyant
On 2 Mar 2005 10:43:38 -0800, Serge Orlov <[EMAIL PROTECTED]> wrote:
> Jaime Wyant wrote:
> > I chose not to use py2exe because it made updating my app a bit
> > messier.  For instance, suppose I don't use the smtplib module in
> > version 1 of my software.  Py2exe realizes that and doesn't 'package'
> > smtplib with my executable.  Now, if I release version 1.1 which does
> > use smtplib, then I'd have to figure out how to get the updates out
> > without having the user redownload the entire application.  Granted,
> > I didn't put much thought into an update mechanism, but it seemed to
> > be messy at the time.
> 
> I don't follow you. How is that different compared to adding a module
> to your application? Let's say version 1.1 of your software has
> module1.py updated, module2.py added and it needs smtplib. You just
> bundle three compiled files and unpack them let's say to
> \program files\my software\module1.pyc
> \program files\my software\module2.pyc
> \program files\my software\python\smtplib.pyc
> 
> I don't see any mess.
> 

The way I *think* about it is this -->  To update my app, I only have
to download a new version of it... Being written in python, the app
itself is pretty small

Suppose the following are true:
1) when the user installs my custom built python distribution they
also get version 1.0 of the app.
2) Suppose it is installed in c:\myapp (for simplicity).
3) I've just released version 1.1

Because *all* of the modules are in my custom built distribution, I
don't have to actively scan for new modules between releases.  So
I can write a simple "updater" script that will:
1) download a new myapp.zip
2) remove the c:\myapp directory and its subdirs
3) unzip it to c:\myapp, overwriting what is there

After those three steps are complete, then my app is updated.  Super
simple.  All I have to do is "zip" up my application and post it to a
website somewhere...

IIRC, py2exe bundles things up in a .zip file.  So in order to update
a py2exe app i'd have to ->
1) check for new module dependencies
2) get the newly imported modules AND my newly updated modules back to
the client
3) update the zip file with the new modules.

This becomes especially hairy when someone is updating from 1.0 to say
1.5.  Then I have to keep track of all the deltas between 1.0/1.5.  My
way is much simpler because I don't have to keep up with *anything*. 
As long as I test my code against my custom built distribution, it
ought to JUST WORK.

I don't trust myself to keep up with anything ;).

However, if you have an idea on updating py2exe bundled apps, I'm all ears...

> >
> >If I have my own distribution, I can simply give the users an "update"
> > program that will query  my webserver which will download the latest
> > version for them automagically.  Because my distribution has all of
> > the modules already available, I don't have to worry about sending
> > them any missing modules.  Simply download the latest version of my
> > app and it works with my custom rolled distribution.
> >
> > But, this only works for Windows...
> 
> Why? As I understand "update" program was written by you, so what
> prevents it from working on other platforms besides testing?

Yes, but the *update* program runs in the context of my distribution
which is strictly bundled for windows.  Now, someone *could* build a
distributable version for Linux somehow (I guess) and then the update
techniques I mentioned would probably work there.

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


Re: How would you program this?

2005-03-02 Thread Carl Banks

engsol wrote:
> There is a number puzzle which appears in the daily paper.
> Because I'm between Python projects, I thought it might be
> fun to write a program to solve it20 minute job, max.
>
> On closer inspection, it became apparent that it's not a
> simple thing to program.

No kidding--it's a constrained integer programming problem.  Those can
be pretty nasty.  This one is pretty simple, being linear with only 12
unknowns.  However, they get very difficult very fast.  There are whole
optimization textbooks written on this kind of problem.


> How would you approach it?
>
> The puzzle: a 4 x 4 grid. The rows are summed (and given), the
> cols are summed (and given), and the two diagonals are summed,
> and given. In addition, 4 clues are given, but none of the 4 are in
> the same row or col.
>
> Example from today's paper:...solution time is 8 minutes, 1 second,
> so they say.
>
> The set of allowable numbers  is 1 thru 9
>
> Rows:
> 3 + B + C + D = 22
> E + F + 8 + H = 26
> I + J + K + 8 = 31
> M + 7 + O + P = 25
>
> Col sums:
> 24, 18, 31, 31
>
> Diag sums:
> 3 + F + K + P = 24
> M + J + 8 + D = 24
>
> The first impulse is to just brute force it with nested for loops,
> but the calculator shows the possible combinations are
> 9^12 = 5,159,780,352, which would take much too long.

Not necessary.

It looks like there are 12 unknowns and 10 equations, and all equations
are linear.  Any two variables completely determine the values of all
the others: we just need to solve the linear equations to get them.
Once you've found all the others, check to see if they all satisfy the
constaint (i.e., they're all integers from 1 to 9).

In Python, this is easy with Numeric/numarray; pure Python I wouldn't
want to try (that's what Numeric is for), but it's possible.

So we've reduced the problem to brute forcing 2 variables, which is
only 81 combinations; definitely doable.


-- 
CARL BANKS

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


ANN: PyDev 0.9.1 released

2005-03-02 Thread Fabio Zadrozny
Hi All,
PyDev - Python IDE (Python development enviroment for Eclipse) version 
0.9.1 has just been released.

You can check the homepage (http://pydev.sourceforge.net/) or my blog 
(http://pydev.blogspot.com/) for more details.

--
COMMENTS ON RELEASE:
Content assistant improvements:
- assign content assistant when assigned to variable strips the "get";
- move imports content assistant should be improved to move import 
closer to existant import and
not to top of file;
- Icons added to them;

Others:
- Ctrl+Shift+O: if no selection: Organizes all global imports from the 
file (sorts alphabetically);
- Ctrl+Shift+O: if some line selection: sorts alphabetically the lines 
selected;
- Ctrl+Shift+F: if no selection: Formats all code;
- Ctrl+Shift+F: if some line selection: Formats selected code;
- PyLint only blocks interface on "update results";
- the namespace in debug mode is not polluted anymore (Scott Schleiser 
provided the patch);
- The PYTHONPATH used for debug now should be the same used in run.
- Editor preferences

Code Completion:
- get parameters in code completion;
- builtins like ' ', {}, [] should bring correct suggestions;
- relative imports;
- other bug-fixes;
--
Regards,
Fabio Zadrozny
--
Software Developer
ESSS - Engineering Simulation and Scientific Software
www.esss.com.br
--
http://mail.python.org/mailman/listinfo/python-list


Re: yield_all needed in Python

2005-03-02 Thread Steven Bethard
Terry Reedy wrote:
"Steven Bethard" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
My suspicion is that if he doesn't like the * syntax when there's a close 
parallel to the argument parsing usage, he's not likely to like it when 
there isn't one.
Hmm.  My impression is that Guido did not like x,*y=iterable because he 
does *not* see it as a 'close parallel' but as a strained analogy.  To me, 
yield *iterable is closer to the use in function calling.  It would mean 
'unpack in time' rather than 'unpack in space' but that is natural (to me, 
anyway) since that is what generators are about.
I don't see the * in
yield *iterable
being much closer to the use in argument unpacking.  Note what happens 
to iterables after *:

py> def gen():
... yield 1
... yield 2
... print "complete!"
...
py> def f(*args):
... print args
...
py> f(*gen())
complete!
(1, 2)
The entire iterable is immediately exhausted.  So if
yield *iterable
is supposed to parallel argument unpacking, I would expect that it would 
also immediately exhaust the iterable, e.g. it would be equivalent to:
for item in tuple(iterable):
yield item
which I don't think is what the OP wants.

I'm certain I could get used to the syntax.  I'm only suggesting that I 
don't find it very intuitive.  (And I *have* thought a lot about 
argument unpacking -- see my older threads about *args being an iterable 
instead of a tuple.)

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


Re: ANN: xsdbXML python release with C#/.NET port

2005-03-02 Thread aaronwmail-usenet
Yikes...  A couple people pointed out that the upload had no
csharp code.  That was because sourceforge was uploading the
wrong file (but reporting the right filesize).  I think it's fixed now
(uploaded from paris and minnesota).  Sorry!!!
--- Aaron Watters

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


Re: yield_all needed in Python

2005-03-02 Thread Douglas Alan
Nick Coghlan <[EMAIL PROTECTED]> writes:

> If you do write a PEP, try to get genexp syntax supported by the
> yield keyword.

> That is, the following currently triggers a syntax error:
>def f():
>  yield x for x in gen1(arg)

Wouldn't

   yield *(x for x in gen1(arg))

be sufficient, and would already be supported by the proposal at
hand?

Also, with the syntax you suggest, it's not automatically clear
whether you want to yield the generator created by the generator
expression or the values yielded by the expression.  The "*" makes
this much more explicit, if you ask me, without hindering readability.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How would you program this?

2005-03-02 Thread Paul Rubin
"Carl Banks" <[EMAIL PROTECTED]> writes:
> No kidding--it's a constrained integer programming problem.  Those can
> be pretty nasty.  This one is pretty simple, being linear with only 12
> unknowns.  However, they get very difficult very fast.  There are whole
> optimization textbooks written on this kind of problem.

Why is it an integer programming problem rather than just a set of
simultaneous equations?  It looks offhand like 12 equations in 12
unknowns that can be solved with linear algebra, but I haven't tried
solving it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How would you program this?

2005-03-02 Thread Bill Mill
On Wed, 02 Mar 2005 10:23:33 -0800, engsol <[EMAIL PROTECTED]> wrote:
> There is a number puzzle which appears in the daily paper.
> Because I'm between Python projects, I thought it might be
> fun to write a program to solve it20 minute job, max.
> 
> On closer inspection, it became apparent that it's not a
> simple thing to program. How would you approach it?
> 
> The puzzle: a 4 x 4 grid. The rows are summed (and given), the
> cols are summed (and given), and the two diagonals are summed,
> and given. In addition, 4 clues are given, but none of the 4 are in
> the same row or col.
> 
> Example from today's paper:...solution time is 8 minutes, 1 second,
> so they say.
> 
> The set of allowable numbers  is 1 thru 9
> 
> Rows:
> 3 + B + C + D = 22
> E + F + 8 + H = 26
> I + J + K + 8 = 31
> M + 7 + O + P = 25
> 
> Col sums:
> 24, 18, 31, 31
> 
> Diag sums:
> 3 + F + K + P = 24
> M + J + 8 + D = 24
> 
> The first impulse is to just brute force it with nested for loops,
> but the calculator shows the possible combinations are
> 9^12 = 5,159,780,352, which would take much too long.
> 

Are you sure about that? You can eliminate a whole lot of options just
based on the row (or column, if you're so inclined) totals. Here's
what I came up with in 10 minutes:

#linalg_brute.py--
ns = range(1,10)
def mkrow(limit):
return [(a,b,c) for a in ns for b in ns for c in ns if a + b + c == limit]
row1 = mkrow(19)
row2 = mkrow(18)
row3 = mkrow(23)
row4 = mkrow(18)
for b,c,d in row1:
for e,f,h in row2:
for i,j,k in row3:
for m,o,p in row4:
if 3 + e + i + m == 24 and 7 + b + f + j == 18 \
and 8 + c + k + o == 31 and 8 + d + h + p == 31 \
and 3 + f + k + p == 24 and m + j + 8 + d == 24:
print 3,b,c,d
print e,f,8,h
print i,j,k,8
print m,7,o,p
print '-'
#--end linalg_brute.py-

Of course, it could use a whole bunch of generalization, but that
wasn't the point. It runs quite nicely:

02:42 PM /d/code/Python$ time python linalg.py
3 3 8 8
9 3 8 6
9 5 9 8
3 7 6 9
-
3 3 9 7
8 3 8 7
9 5 9 8
4 7 5 9
-

real0m1.255s
user0m1.221s
sys 0m0.030s

Both solutions look correct to me; how about you? With clever enough
heuristics, problems that you can expect people to solve will almost
always fall to brute force algorithms, I feel.

Peace
Bill Mill
bill.mill at gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distributing applications

2005-03-02 Thread Mitch Amiano
I'm fairly new to python myself (with about 16 years of various 
languages); I found py2exe fairly straightforward to use.
The instructions are ok, but if you care to see it I took some notes and 
threw them into an article on my company site.


Regards
- Mitch
Phillip Mills wrote:
I've learned enough of the Python language to be mildly dangerous and 
have used it in a few personal projects.  All my development of 
commercial (or production) products over the past dozen years have been 
done with C++ or Java.

For a program I'm planning -- to begin during the summer -- having an 
interpreter as part of the application would be very desirable to allow 
sophisticated users to provide their own extensions.  Java would be 
do-able, but

My problems are:
  - I'd like the process of installing the application to be one step; 
no "first download a Python interpreter then a GUI library" kind of 
thing.
  - I also need the core part of the application to be reasonably 
protected.  I'm not looking to defeat hackers, but something equivalent 
to the way Java's class files stored in jars stay where they're supposed 
to be and aren't immediately readable.

I've looked at various web sites for this topic, but most I've found are 
just arguments for using the Python language.  OK, I'll pretend I'm 
convinced...now any comments or references on the mechanics of creating 
a self-contained distribution?

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


Re: How would you program this?

2005-03-02 Thread Roel Schroeven
Paul Rubin wrote:
> "Carl Banks" <[EMAIL PROTECTED]> writes:
> 
>>No kidding--it's a constrained integer programming problem.  Those can
>>be pretty nasty.  This one is pretty simple, being linear with only 12
>>unknowns.  However, they get very difficult very fast.  There are whole
>>optimization textbooks written on this kind of problem.
> 
> 
> Why is it an integer programming problem rather than just a set of
> simultaneous equations?  It looks offhand like 12 equations in 12
> unknowns that can be solved with linear algebra, but I haven't tried
> solving it.

It's because solutions involving non-integer numbers are invalid in this
context. And there are 12 unknowns but only 10 equations.

-- 
"Codito ergo sum"
Roel Schroeven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How would you program this?

2005-03-02 Thread Bill Mill


This should have said "time python linalg_brute.py" . I changed the
name, but didn't rerun the test. linalg.py is the same as
linalg_brute.py.

> 
> 02:42 PM /d/code/Python$ time python linalg.py
> 3 3 8 8
> 9 3 8 6
> 9 5 9 8
> 3 7 6 9
> -
> 3 3 9 7
> 8 3 8 7
> 9 5 9 8
> 4 7 5 9
> -
> 
> real0m1.255s
> user0m1.221s
> sys 0m0.030s
> 

Peace
Bill Mill
bill.mill at gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: yield_all needed in Python

2005-03-02 Thread Jeremy Bowers
On Wed, 02 Mar 2005 22:54:14 +1000, Nick Coghlan wrote:

> Douglas Alan wrote:
>> Steve Holden <[EMAIL PROTECTED]> writes:
>>>Guido has generally observed a parsimony about the introduction of
>>>features such as the one you suggest into Python, and in particular
>>>he is reluctant to add new keywords - even in cases like decorators
>>>that cried out for a keyword rather than the ugly "@" syntax.
>> 
>> In this case, that is great, since I'd much prefer
>> 
>>yield *gen1(arg)
> 
> If you do write a PEP, try to get genexp syntax supported by the yield 
> keyword.
> 
> That is, the following currently triggers a syntax error:
>def f():
>  yield x for x in gen1(arg)

H.

At first I liked this, but the reason that is a syntax error is that it is
"supposed" to be

def f():
yield (x for x in gen1(arg))

which today on 2.4 returns a generator instance which will in turn
yield one generator instance from the genexp, and I am quite uncomfortable
with the difference between the proposed behaviors with and without the
parens.

Which sucks, because at first I really liked it :-)

We still would need some syntax to say "yield this 'in place' rather than
as an object".

Moreover, since "yield" is supposed to be analogous to "return", what does

return x for x in gen1(arg)

do? Both "it returns a list" and "it returns a generator" have some
arguments in their favor.

And I just now note that any * syntax, indeed, any syntax at all will
break this.

You know, given the marginal gains this gives anyway, maybe it's best off
to just observe that in the event that this is really important, it's
possible to hand-code the short-circuiting without too much work, and let
people write a recipe or something.

def genwrap(*generators):
while generators:
try:
returnedValue = generators[-1].next()
if hasattr(returnedValue, 'next'):
generators.append(returnedValue)
continue
yield returnedValue
except StopIteration:
generators.pop()

Not tested at all because the wife is calling and I gotta go :-)

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


Re: Distributing applications

2005-03-02 Thread Serge Orlov
Phillip Mills wrote:
> First, thanks to all the people who have answered so far for the
> suggestions.
>
> In article <[EMAIL PROTECTED]>,
>  André Søreng <[EMAIL PROTECTED]> wrote:
>
> > Phillip Mills wrote:
>
> > > My problems are:
>
> [...]
>
> > http://starship.python.net/crew/theller/py2exe/
>
> Apparently I had more problems than I mentioned.  :-)  One of them
> being that a Windows-only solution is only a partial solution.

There is also py2app for Mac. Still partial? :) Then follow Jaime's
way: build and bundle python with your application.

>
> > >   - I also need the core part of the application to be reasonably

> > > protected.  I'm not looking to defeat hackers, but something
> > > equivalent to the way Java's class files stored in jars stay
> > > where they're supposed to be and aren't immediately readable.
> > >
> > Hmm, not sure about that one. You mean that those users who write
> > extensions should not be able to modify the core code you wrote?
>
> Partly that and partly a file management thing.  For most end users a

> .jar is one thing to deal with; it's the most recent one or it's not;

> it's present in the right location or it's not

Python byte code is like java byte code and python supports importing
from zip files like java. Since python comes with a liberal license
you can change the importing code to decrypt your modules with a
"secret" key. That will be much safer than java. Of course that won't
stop real hackers.

  Serge.

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


COM programming with Excel

2005-03-02 Thread Bruce Jewell








I have been accessing Excel data with win32com.  It
seems to work well until I get to cells that are formatted for Currency or
Accounting.  With these, I get a text string that looks like “(0,
2500)” where the 2500 is actually $25.00, but it cannot be parsed or separated. 
Can anyone help me get the $25.00 that I seek.

 

Thanks,

Excel Abuser






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

Re: Faster way to do this...

2005-03-02 Thread Robert Kern
Will McGugan wrote:
Warren Postma wrote:
Will McGugan wrote:
Isn't that equivalent to simply..
nums= range(100)

I remember the day I first realized that 900 lines of some C++ program 
I was working on could be expressed in three lines of python.  Ahh.

Lately I've found myself commenting C++ code with the equivalent Python 
code. I find it clearer and more terse than simply commenting in English!
If you used literate programming tools, you might be able to get a 
Python version and a C++ version of your code in one go!

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


  1   2   >