Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread Dotan Cohen
On 13/02/2008, Erik Max Francis <[EMAIL PROTECTED]> wrote:
>  And the rest of us just use SI.  (And if you bring up the
>  _kilogram-force_, I'll just cry.)

Don't cry, I just want to say that I've hated the kilogram-force
almost as much as I've hated the electron-volt. Who is the lazy who
comes up with these things?

Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread cokofreedom
> And the rest of us just use SI.  (And if you bring up the
> _kilogram-force_, I'll just cry.)

SI = Super Incredible?

Awesome name for Force/Mass / NewItemOfClothing2050!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ways to declare empty set variable

2008-02-13 Thread cokofreedom
The irony that, x = (,) produces an error.

Personally I would of thought it would be a better example of an empty
tuple than anything else, but it still isn't that readable.

The use of dict/list/tuple/set seems to stand out a lot better, makes
it readable! Else in a few years you'll have §x§ = !^!()

Or maybe I am going crazy...
-- 
http://mail.python.org/mailman/listinfo/python-list


Big time WTF with generators - bug?

2008-02-13 Thread James Stroud
Hello,

I'm boggled.

I have this function which takes a keyer that keys a table (iterable). I 
filter based on these keys, then groupby based on the filtered keys and 
a keyfunc. Then, to make the resulting generator behave a little nicer 
(no requirement for user to unpack the keys), I strip the keys in a 
generator expression that unpacks them and generates the k,g pairs I 
want ("regrouped"). I then append the growing list of series generator 
into the "serieses" list ("serieses" is plural for series if your 
vocablulary isn't that big).

Here's the function:

def serialize(table, keyer=_keyer,
  selector=_selector,
  keyfunc=_keyfunc,
  series_keyfunc=_series_keyfunc):
   keyed = izip(imap(keyer, table), table)
   filtered = ifilter(selector, keyed)
   serialized = groupby(filtered, series_keyfunc)
   serieses = []
   for s_name, series in serialized:
 grouped = groupby(series, keyfunc)
 regrouped = ((k, (v[1] for v in g)) for (k,g) in grouped)
 serieses.append((s_name, regrouped))
   for s in serieses:
 yield s


I defined a little debugging function called iterprint:

def iterprint(thing):
   if isinstance(thing, str):
 print thing
   elif hasattr(thing, 'items'):
 print thing.items()
   else:
 try:
   for x in thing:
 iterprint(x)
 except TypeError:
   print thing

The gist is that iterprint will print any generator down to its 
non-iterable components--it works fine for my purpose here, but I 
included the code for the curious.

When I apply iterprint in the following manner (only change is the 
iterprint line) everything looks fine and my "regrouped" generators in 
"serieses" generate what they are supposed to when iterprinting. The 
iterprint at this point shows that everything is working just the way I 
want (I can see the last item in "serieses" iterprints just fine).

def serialize(table, keyer=_keyer,
  selector=_selector,
  keyfunc=_keyfunc,
  series_keyfunc=_series_keyfunc):
   keyed = izip(imap(keyer, table), table)
   filtered = ifilter(selector, keyed)
   serialized = groupby(filtered, series_keyfunc)
   serieses = []
   for s_name, series in serialized:
 grouped = groupby(series, keyfunc)
 regrouped = ((k, (v[1] for v in g)) for (k,g) in grouped)
 serieses.append((s_name, regrouped))
 iterprint(serieses)
   for s in serieses:
 yield s

Now, here's the rub. When I apply iterprint in the following manner, it 
looks like my generator ("regrouped") gets consumed (note the only 
change is a two space de-dent of the iterprint call--the printing is 
outside the loop):

def serialize(table, keyer=_keyer,
  selector=_selector,
  keyfunc=_keyfunc,
  series_keyfunc=_series_keyfunc):
   keyed = izip(imap(keyer, table), table)
   filtered = ifilter(selector, keyed)
   serialized = groupby(filtered, series_keyfunc)
   serieses = []
   for s_name, series in serialized:
 grouped = groupby(series, keyfunc)
 regrouped = ((k, (v[1] for v in g)) for (k,g) in grouped)
 serieses.append((s_name, regrouped))
   iterprint(serieses)
   for s in serieses:
 yield s

Now, what is consuming my "regrouped" generator when going from inside 
the loop to outside?

Thanks in advance for any clue.

py> print version
2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)]

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

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


Re: Big time WTF with generators - bug?

2008-02-13 Thread James Stroud
Paul Rubin wrote:
> James Stroud <[EMAIL PROTECTED]> writes:
>> I defined a little debugging function called iterprint:
>>
>> def iterprint(thing): ...
>>for x in thing:
>>  iterprint(x)
> 
> of course this mutates the thing that is being printed.  Try using
> itertools.tee to fork a copy of the iterator and print from that.
> I didn't look at the rest of your code enough to spot any errors
> but take note of the warnings in the groupby documentation about
> pitfalls with using the results some number of times other than
> exactly once.

Thank you for your answer, but I am aware of this caveat. Something is 
consuming my generator *before* I iterprint it. Please give it another 
look if you would be so kind.

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

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


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread Erik Max Francis
Dotan Cohen wrote:

> On 13/02/2008, Erik Max Francis <[EMAIL PROTECTED]> wrote:
>>  And the rest of us just use SI.  (And if you bring up the
>>  _kilogram-force_, I'll just cry.)
> 
> Don't cry, I just want to say that I've hated the kilogram-force
> almost as much as I've hated the electron-volt. Who is the lazy who
> comes up with these things?

The electron-volt is a weird little miscreant that ended up becoming 
popular.  The kilogram-force is a unit that could only demonstrate that 
its inventors completely missed the freakin' point.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
   Sit loosely in the saddle of life.
-- Robert Louis Stevenson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Speed of light

2008-02-13 Thread Bjoern Schliessmann
Dotan Cohen wrote:

> Don't cry, I just want to say that I've hated the kilogram-force
> almost as much as I've hated the electron-volt. Who is the lazy
> who comes up with these things?

eV has a advantages some "kilogram force" hasn't: It's on completely
different order of magnitude. People aren't happy writing 81.8 aJ
(Attojoule = 1e-15 Joule), instead they prefer 
511 keV. And the "e" in eV even allows you to leave out the
elementary charge in your calculations most of the time (because
it's already in the unit).

Regards,


Björn

-- 
BOFH excuse #292:

We ran out of dial tone and we're and waiting for the phone company
to deliver another bottle.

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


Re: Big time WTF with generators - bug?

2008-02-13 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> I defined a little debugging function called iterprint:
> 
> def iterprint(thing): ...
>for x in thing:
>  iterprint(x)

of course this mutates the thing that is being printed.  Try using
itertools.tee to fork a copy of the iterator and print from that.
I didn't look at the rest of your code enough to spot any errors
but take note of the warnings in the groupby documentation about
pitfalls with using the results some number of times other than
exactly once.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Big time WTF with generators - bug?

2008-02-13 Thread James Stroud
Paul Rubin wrote:
> James Stroud <[EMAIL PROTECTED]> writes:
>> I defined a little debugging function called iterprint:
>>
>> def iterprint(thing): ...
>>for x in thing:
>>  iterprint(x)
> 
> of course this mutates the thing that is being printed.  Try using
> itertools.tee to fork a copy of the iterator and print from that.
> I didn't look at the rest of your code enough to spot any errors
> but take note of the warnings in the groupby documentation about
> pitfalls with using the results some number of times other than
> exactly once.

I can see I didn't explain so well. This one must be a bug if my code 
looks good to you. Here is a summary:

- If I iterprint inside the loop, iterprint looks correct.
- If I iterprint outside the loop, my generator gets consumed and I am 
only left with the last item, so my iterprint prints only one item 
outside the loop.

Conclusion: something consumes my generator going from inside the loop 
to outside.

Please note that I am not talking about the yielded values, or the 
for-loop that creates them. I left them there to show my intent with the 
function. The iterprint function is there to show that the generator 
gets consumed just moving from inside the loop to outside.

I know this one is easy to dismiss to my consuming the generator with 
the iterprint, as this would be a common mistake.

James


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

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


Re: Big time WTF with generators - bug?

2008-02-13 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> Thank you for your answer, but I am aware of this caveat. Something is
> consuming my generator *before* I iterprint it. Please give it another
> look if you would be so kind.

I'll see if I can look at it some more later, I'm in the middle of
something else right now.  All I can say at the moment is that I've
encountered problems like this in my own code many times, and it's
always been a matter of having to carefully keep track of how the
nested iterators coming out of groupby are being consumed.  I doubt
there is a library bug.  Using groupby for things like this is
powerful, but unfortunately bug-prone because of how these mutable
iterators work.  I suggest making some sample sequences and stepping
through with a debugger seeing just how the iterators advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Big time WTF with generators - bug?

2008-02-13 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> I can see I didn't explain so well. This one must be a bug if my code
> looks good to you.

I didn't spot any obvious errors, but I didn't look closely enough
to say that the code looked good or bad.

> Conclusion: something consumes my generator going from inside the loop
> to outside.

I'm not so sure of this, the thing is you're building these internal
grouper objects that don't expect to be consumed in the wrong order, etc.

Really, I'd try making a test iterator that prints something every
time you advance it, then step through your function with a debugger.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Big time WTF with generators - bug?

2008-02-13 Thread James Stroud
Paul Rubin wrote:
> James Stroud <[EMAIL PROTECTED]> writes:
>> I can see I didn't explain so well. This one must be a bug if my code
>> looks good to you.
> 
> I didn't spot any obvious errors, but I didn't look closely enough
> to say that the code looked good or bad.
> 
>> Conclusion: something consumes my generator going from inside the loop
>> to outside.
> 
> I'm not so sure of this, the thing is you're building these internal
> grouper objects that don't expect to be consumed in the wrong order, etc.
> 
> Really, I'd try making a test iterator that prints something every
> time you advance it, then step through your function with a debugger.

Thank you for your suggestion. I replied twice to your first post before 
you made your suggestion to step through with a debugger, so it looks 
like I ignored it.

Thanks again.

James

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

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


No Module Named pstats

2008-02-13 Thread Juha S.
Hi,

I'm trying to use the Python profilers to test my code, but I get the 
following output for cProfile.run() at the interpreter:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/cProfile.py", line 36, in run
result = prof.print_stats(sort)
  File "/usr/lib/python2.5/cProfile.py", line 80, in print_stats
import pstats
ImportError: No module named pstats


I also tried to use the profile module but I get:

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


I'm on Ubuntu 7.10 with Python 2.5, and I can't seem to figure out 
what's missing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No Module Named pstats

2008-02-13 Thread I. Soumpasis
2008/2/13, Juha S. <[EMAIL PROTECTED]>:
>
> Hi,
>
> I'm trying to use the Python profilers to test my code, but I get the
> following output for cProfile.run() at the interpreter:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.5/cProfile.py", line 36, in run
> result = prof.print_stats(sort)
>   File "/usr/lib/python2.5/cProfile.py", line 80, in print_stats
> import pstats
> ImportError: No module named pstats
>
>
> I also tried to use the profile module but I get:
>
> >>> import profile
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named profile
>
>
> I'm on Ubuntu 7.10 with Python 2.5, and I can't seem to figure out
> what's missing.


I think you have to install python-profiler.

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

Re: Big time WTF with generators - bug?

2008-02-13 Thread Peter Otten
James Stroud wrote:

groupby() is "all you can eat", but "no doggy bag".

> def serialize(table, keyer=_keyer,
>                       selector=_selector,
>                       keyfunc=_keyfunc,
>                       series_keyfunc=_series_keyfunc):
>    keyed = izip(imap(keyer, table), table)
>    filtered = ifilter(selector, keyed)
>    serialized = groupby(filtered, series_keyfunc)
>    serieses = []
>    for s_name, series in serialized:
>      grouped = groupby(series, keyfunc)
>      regrouped = ((k, (v[1] for v in g)) for (k,g) in grouped)
>      serieses.append((s_name, regrouped))

You are trying to store a group for later consumption here. 

>    for s in serieses:
>      yield s

That doesn't work:

>>> groups = [g for k, g in groupby(range(10), lambda x: x//3)]
>>> for g in groups:
... print list(g)
...
[]
[]
[]
[9]

You cannot work around that because what invalidates a group is the call of
groups.next():

>>> groups = groupby(range(10), lambda x: x//3)
>>> g = groups.next()[1]
>>> g.next()
0
>>> groups.next()
(1, )
>>> g.next()
Traceback (most recent call last):
  File "", line 1, in 
StopIteration

Perhaps Python should throw an out-of-band exception for an invalid group
instead of yielding bogus data.

Peter

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

Re: Python not finding modules

2008-02-13 Thread Guilherme Polo
2008/2/13, Mani Chandra <[EMAIL PROTECTED]>:
> Hey!
> I installed a few python modules through the freebsd ports, but when I 
> try to import them in the interpreter it says "module xxx not found". This 
> seems to happen for some modules and not for the others. ex:- I installed 
> psyco and parallel python which seem to be found but then scipy, PIL aren't 
> being imported. Below is my $PYTHONPATH
>
>  ['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c7-py2.5.egg', 
> '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', 
> '/usr/local/lib/python2.5/plat-freebsd6', '/usr/local/lib/python2.5/lib-tk', 
> '/usr/local/lib/python2.5/lib-dynload', 
> '/usr/local/lib/python2.5/site-packages', 
> '/usr/local/lib/python2.5/site-packages/gtk-2.0', 
> '/usr/local/lib/vtk/python', '/usr/local/lib/python2.5/site-packages']
>
>  The scipy libs are located at "/usr/local/lib/python2.4/site-packages/scipy" 
>  so I manually added this path to the PYTHONPATH but it still doesn't seem to 
> find it.
>

You need to install python modules for python2.5, you clearly installed for 2.4.

>  Can someone please help me out here?:)
>
>  ps Also does including a directory in PYTHONPATH include all of it's 
> sub-directories too?
>
>
>
>   Download prohibited? No problem. CHAT from any browser, without 
> download. Go to http://in.messenger.yahoo.com/webmessengerpromo.php/
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Python not finding modules

2008-02-13 Thread Mani Chandra
Hey!
I installed a few python modules through the freebsd ports, but when I try 
to import them in the interpreter it says "module xxx not found". This seems to 
happen for some modules and not for the others. ex:- I installed psyco and 
parallel python which seem to be found but then scipy, PIL aren't being 
imported. Below is my $PYTHONPATH

['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c7-py2.5.egg', 
'/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', 
'/usr/local/lib/python2.5/plat-freebsd6', '/usr/local/lib/python2.5/lib-tk', 
'/usr/local/lib/python2.5/lib-dynload', 
'/usr/local/lib/python2.5/site-packages', 
'/usr/local/lib/python2.5/site-packages/gtk-2.0', '/usr/local/lib/vtk/python', 
'/usr/local/lib/python2.5/site-packages']

The scipy libs are located at "/usr/local/lib/python2.4/site-packages/scipy"  
so I manually added this path to the PYTHONPATH but it still doesn't seem to 
find it.

Can someone please help me out here?:)

ps Also does including a directory in PYTHONPATH include all of it's 
sub-directories too?



  Download prohibited? No problem. CHAT from any browser, without download. 
Go to http://in.messenger.yahoo.com/webmessengerpromo.php/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Big time WTF with generators - bug?

2008-02-13 Thread James Stroud
Peter Otten wrote:
> groupby() is "all you can eat", but "no doggy bag".

Thank you for your clear explanation--a satisfying conclusion to nine 
hours of head scratching.

James

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

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


Re: Big time WTF with generators - bug?

2008-02-13 Thread Paul Rubin
Peter Otten <[EMAIL PROTECTED]> writes:
> >    for s_name, series in serialized:
> >      grouped = groupby(series, keyfunc)
> >      regrouped = ((k, (v[1] for v in g)) for (k,g) in grouped)
> >      serieses.append((s_name, regrouped))
> 
> You are trying to store a group for later consumption here. 

Good catch, the solution is to turn that loop into a generator,
but then it has to be consumed very carefully.  This stuff
maybe presses the limits of what one can do with Python iterators
while staying sane.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Big time WTF with generators - bug?

2008-02-13 Thread James Stroud
Paul Rubin wrote:
> Peter Otten <[EMAIL PROTECTED]> writes:
>> You are trying to store a group for later consumption here. 
> 
> Good catch, the solution is to turn that loop into a generator,
> but then it has to be consumed very carefully.

Brilliant suggestion. Worked like a charm. Here is the final product:


def dekeyed(serialized, keyfunc):
   for name, series in serialized:
 grouped = groupby(series, keyfunc)
 regrouped = ((k, (v[1] for v in g)) for (k,g) in grouped)
 yield (name, regrouped)

def serialize(table, keyer=_keyer,
  selector=_selector,
  keyfunc=_keyfunc,
  series_keyfunc=_series_keyfunc):
   keyed = izip(imap(keyer, table), table)
   filtered = ifilter(selector, keyed)
   serialized = groupby(filtered, series_keyfunc)
   return dekeyed(serialized, keyfunc)


Thank you!

James



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

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


Re: No Module Named pstats

2008-02-13 Thread Juha S.
2008/2/13, Juha S. <[EMAIL PROTECTED] >:
>
> Hi,
>
> I'm trying to use the Python profilers to test my code, but I get the
> following output for cProfile.run() at the interpreter:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.5/cProfile.py", line 36, in run
> result = prof.print_stats(sort)
>   File "/usr/lib/python2.5/cProfile.py", line 80, in print_stats
> import pstats
> ImportError: No module named pstats
>
>
> I also tried to use the profile module but I get:
>
> >>> import profile
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named profile
>
>
> I'm on Ubuntu 7.10 with Python 2.5, and I can't seem to figure out
> what's missing.
>
>
> I think you have to install python-profiler.
>
> Regards,
> Ilias

Thanks! I apt-get installed the package and now cProfiler works correctly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python not finding modules

2008-02-13 Thread [EMAIL PROTECTED]
Hey!
I installed a few python modules through the freebsd ports, but
when I try to import them in the interpreter it says "module xxx not
found". This seems to happen for some modules and not for the others.
ex:- I installed psyco and parallel python which seem to be found but
then scipy, PIL aren't being imported. Below is my $PYTHONPATH

['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c7-
py2.5.egg', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-freebsd6', '/usr/local/lib/python2.5/
lib-tk', '/usr/local/lib/python2.5/lib-dynload', '/usr/local/lib/
python2.5/site-packages', '/usr/local/lib/python2.5/site-packages/
gtk-2.0', '/usr/local/lib/vtk/python', '/usr/local/lib/python2.5/site-
packages']

The scipy libs are located at "/usr/local/lib/python2.4/site-packages/
scipy"  so I manually added this path to the PYTHONPATH but it still
doesn't seem to find it.

Can someone please help me out here?:)

ps Also does including a directory in PYTHONPATH include all of it's
sub-directories too?


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


Re: No Module Named pstats

2008-02-13 Thread Chris
On Feb 13, 11:20 am, "Juha S." <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm trying to use the Python profilers to test my code, but I get the
> following output for cProfile.run() at the interpreter:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.5/cProfile.py", line 36, in run
> result = prof.print_stats(sort)
>   File "/usr/lib/python2.5/cProfile.py", line 80, in print_stats
> import pstats
> ImportError: No module named pstats
>
> I also tried to use the profile module but I get:
>
>  >>> import profile
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named profile
>
> I'm on Ubuntu 7.10 with Python 2.5, and I can't seem to figure out
> what's missing.

There is no module called 'profile', it's called 'cProfile'.  Both
'cProfile' and 'pstats' are part of the standard distro, have you
tried downloading a new binary and installing it ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Big time WTF with generators - bug?

2008-02-13 Thread Paul Rubin
James Stroud <[EMAIL PROTECTED]> writes:
> Brilliant suggestion. Worked like a charm. Here is the final product:

Cool, glad it worked out.  When writing this type of code I like to
use doctest to spell out some solid examples of what each function is
supposed to do, as part of the function.  It's the only way I can
remember the shapes of the sequences going in and out, and the
automatic testing doesn't hurt either.  Even with that though, at
least for me, Python starts feeling really scary when the iterators
get this complicated.  I start wishing for a static type system,
re-usable iterators, etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyinstall and matplotlib

2008-02-13 Thread John Henry
On Feb 9, 2:53 pm, John Henry <[EMAIL PROTECTED]> wrote:
> Has anybody been able to create an exe of their python applications
> involving matplotlib using pyinstall (ver 1.3)?  I am getting a:
>
>  RuntimeError: Could not find the matplotlib data files
>
> when I attempt to run the exe created.
>
> In searching the web, it appears this is an issue when others tried to
> use py2exe as well.  Unfortunately, the few hits I saw doesn't include
> enough details to inspire me as to what I should be doing in my
> pyinstall .spec file.
>
> Does anybody has an example or information about this?
>
> Thanks,

Well, looks like nobody has an answer to this question.

How'bout py2exe or other ways of creating exe files out of matplotlib
projects?  Has anybody been able to do that?  (I am cross-posting
these messages to the matploblib mailing list).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python not finding modules

2008-02-13 Thread Mani Chandra
Hey,
Thanks for replying. But what about the module whose path I included manually. 
That didn't work too!Is it like packages that are made for python2.4 do not 
work for 2.5?
Also are folders recursively included?
Thanks
Mani chandra


--- On Wed, 13/2/08, Guilherme Polo <[EMAIL PROTECTED]> wrote:

> From: Guilherme Polo <[EMAIL PROTECTED]>
> Subject: Re: Python not finding modules
> To: [EMAIL PROTECTED], python-list@python.org
> Date: Wednesday, 13 February, 2008, 3:56 PM
> 2008/2/13, Mani Chandra <[EMAIL PROTECTED]>:
> > Hey!
> > I installed a few python modules through the
> freebsd ports, but when I try to import them in the
> interpreter it says "module xxx not found". This
> seems to happen for some modules and not for the others.
> ex:- I installed psyco and parallel python which seem to be
> found but then scipy, PIL aren't being imported. Below
> is my $PYTHONPATH
> >
> >  ['',
> '/usr/local/lib/python2.5/site-packages/setuptools-0.6c7-py2.5.egg',
> '/usr/local/lib/python25.zip',
> '/usr/local/lib/python2.5',
> '/usr/local/lib/python2.5/plat-freebsd6',
> '/usr/local/lib/python2.5/lib-tk',
> '/usr/local/lib/python2.5/lib-dynload',
> '/usr/local/lib/python2.5/site-packages',
> '/usr/local/lib/python2.5/site-packages/gtk-2.0',
> '/usr/local/lib/vtk/python',
> '/usr/local/lib/python2.5/site-packages']
> >
> >  The scipy libs are located at
> "/usr/local/lib/python2.4/site-packages/scipy" 
> so I manually added this path to the PYTHONPATH but it
> still doesn't seem to find it.
> >
> 
> You need to install python modules for python2.5, you
> clearly installed for 2.4.
> 
> >  Can someone please help me out here?:)
> >
> >  ps Also does including a directory in PYTHONPATH
> include all of it's sub-directories too?
> >
> >
> >
> >   Download prohibited? No problem. CHAT from any
> browser, without download. Go to
> http://in.messenger.yahoo.com/webmessengerpromo.php/
> >
> > --
> >  http://mail.python.org/mailman/listinfo/python-list
> >
> 
> 
> -- 
> -- Guilherme H. Polo Goncalves


  Get your domain and website for less than Rs.100/month*. Go to 
http://in.business.yahoo.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Double underscore names

2008-02-13 Thread Steven D'Aprano
On Wed, 13 Feb 2008 09:55:39 +1100, Ben Finney wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> writes:
> 
>> having the ability to create a protocol is a Very Good Thing, and
>> double leading and trailing underscore names are the accepted Python
>> style for such special methods.
> 
> Is it? There are many protocols that use plain names. Even the built-in
> types support many "protocol" operations via plain-named attributes.
> 
> dict.get, dict.items, dict.keys, dict.values
> 
> list.insert, list.append, list.extend, list.remove

I don't believe any of those define a protocols. They are merely methods. 
An example of a protocol would be dict.__getitem__(): you can retrieve 
items from any object using the square bracket syntax if it has a 
__getitem__ method.

However, having said that, I find myself in the curious position of 
(reluctantly) agreeing with your conclusion to "Go ahead and implement 
your protocol using attributes with plain names" even though I disagree 
with virtually every part of your reasoning. In my mind, the two deciding 
factors are:

(1) Guido's original style guide essay allowed developers to use double-
underscore names under certain circumstances. It seems that this has been 
deliberately dropped when it became a PEP.

http://www.python.org/doc/essays/styleguide.html#names

(2) PEP 3114 "Renaming iterator.next() to iterator.__next__()" makes it 
explicit that names of the form __parrot__ are intended to be "a separate 
namespace for names that are part of the Python language definition".

Given that, I think that the special name __test__ in the doctest module 
is possibly an anomaly: it's not part of the language, but it seems to 
have the BDFL's blessing, or at least the BDFL didn't notice it. It's 
hardly the only anomaly in the standard library though, so one shouldn't 
draw too many conclusions from it. I think the intention is clear: names 
like __parrot__ are strictly verboten for user code.

If and when my modest little programming efforts are considered for 
inclusion in the standard library, I will rethink this issue. In the 
meantime, no more __parrots__.

You can stop reading now. But for those who care, I have a few final 
comments.



> file.read, file.write, file.close

I would accept that these three are part of the "file object protocol", 
However, they seem to be the odd one out: every other Python protocol 
that I can think of uses the __parrot__ form.

iterator.next() is the exception, but that's explicitly been slated for 
change to __next__() in Python 3.


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


Basic question

2008-02-13 Thread WILLIAM SCHMIDT
In several places in the Python documentation I have run across an extra "r" 
that I can not explain:


*
In sys.path after the open bracket:
   sys.path = [r'd:\temp']

In the on line help in the DATA section (towards the end):

>>> help('sys')
Help on built-in module sys:

  truncated 

DATA
exec_prefix = r'C:\Python25'
executable = r'C:\Python25\pythonw.exe'
path = [r'C:\Python25\Lib\idlelib', r'C:\Python25\python25.zip', r'C:\...
prefix = r'C:\Python25'
version = '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bi...
*

Can someone explain what that "r" is doing and where I would find it in the 
documentation?

Thank you in advance for your assistance.

William T. Schmidt



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


Re: Basic question

2008-02-13 Thread Chris
On Feb 13, 2:22 pm, "WILLIAM SCHMIDT" <[EMAIL PROTECTED]> wrote:
> In several places in the Python documentation I have run across an extra "r" 
> that I can not explain:
>
> *
> In sys.path after the open bracket:
>sys.path = [r'd:\temp']
>
> In the on line help in the DATA section (towards the end):
>
> >>> help('sys')
>
> Help on built-in module sys:
>
>   truncated 
>
> DATA
> exec_prefix = r'C:\Python25'
> executable = r'C:\Python25\pythonw.exe'
> path = [r'C:\Python25\Lib\idlelib', r'C:\Python25\python25.zip', r'C:\...
> prefix = r'C:\Python25'
> version = '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bi...
> *
>
> Can someone explain what that "r" is doing and where I would find it in the 
> documentation?
>
> Thank you in advance for your assistance.
>
> William T. Schmidt

It means it is a raw string, useful so you do not need to escape
special characters.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python not finding modules

2008-02-13 Thread Guilherme Polo
2008/2/13, Mani Chandra <[EMAIL PROTECTED]>:
> Hey,
>  Thanks for replying. But what about the module whose path I included 
> manually. That didn't work too!Is it like packages that are made for 
> python2.4 do not work for 2.5?

Depends on the module, if they are C extensions you need to compile
for correct python version.

>  Also are folders recursively included?

In the case you added this
"/usr/local/lib/python2.4/site-packages/scipy" path, but it looks like
wrong. The program will try to find a scipy package but won't find, to
this happen you would need to include
"/usr/local/lib/python2.4/site-packages/". Also, the path you add is a
"starting point" for finding packages and modules, so can consider it
recursive.

>  Thanks
>  Mani chandra
>
>
>  --- On Wed, 13/2/08, Guilherme Polo <[EMAIL PROTECTED]> wrote:
>
>  > From: Guilherme Polo <[EMAIL PROTECTED]>
>  > Subject: Re: Python not finding modules
>  > To: [EMAIL PROTECTED], python-list@python.org
>  > Date: Wednesday, 13 February, 2008, 3:56 PM
>
> > 2008/2/13, Mani Chandra <[EMAIL PROTECTED]>:
>  > > Hey!
>  > > I installed a few python modules through the
>  > freebsd ports, but when I try to import them in the
>  > interpreter it says "module xxx not found". This
>  > seems to happen for some modules and not for the others.
>  > ex:- I installed psyco and parallel python which seem to be
>  > found but then scipy, PIL aren't being imported. Below
>  > is my $PYTHONPATH
>  > >
>  > >  ['',
>  > '/usr/local/lib/python2.5/site-packages/setuptools-0.6c7-py2.5.egg',
>  > '/usr/local/lib/python25.zip',
>  > '/usr/local/lib/python2.5',
>  > '/usr/local/lib/python2.5/plat-freebsd6',
>  > '/usr/local/lib/python2.5/lib-tk',
>  > '/usr/local/lib/python2.5/lib-dynload',
>  > '/usr/local/lib/python2.5/site-packages',
>  > '/usr/local/lib/python2.5/site-packages/gtk-2.0',
>  > '/usr/local/lib/vtk/python',
>  > '/usr/local/lib/python2.5/site-packages']
>  > >
>  > >  The scipy libs are located at
>  > "/usr/local/lib/python2.4/site-packages/scipy"
>  > so I manually added this path to the PYTHONPATH but it
>  > still doesn't seem to find it.
>  > >
>  >
>  > You need to install python modules for python2.5, you
>  > clearly installed for 2.4.
>  >
>  > >  Can someone please help me out here?:)
>  > >
>  > >  ps Also does including a directory in PYTHONPATH
>  > include all of it's sub-directories too?
>  > >
>  > >
>  > >
>  > >   Download prohibited? No problem. CHAT from any
>  > browser, without download. Go to
>  > http://in.messenger.yahoo.com/webmessengerpromo.php/
>  > >
>  > > --
>  > >  http://mail.python.org/mailman/listinfo/python-list
>  > >
>  >
>  >
>  > --
>  > -- Guilherme H. Polo Goncalves
>
>
>
>   Get your domain and website for less than Rs.100/month*. Go to 
> http://in.business.yahoo.com/
>


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


regex question

2008-02-13 Thread mathieu
I do not understand what is wrong with the following regex expression.
I clearly mark that the separator in between group 3 and group 4
should contain at least 2 white space, but group 3 is actually reading
3 +4

Thanks
-Mathieu

import re

line = "  (0021,xx0A)   Siemens: Thorax/Multix FD Lab Settings
Auto Window Width  SL   1 "
patt = re.compile("^\s*\(([0-9A-Z]+),([0-9A-Zx]+)\)\s+([A-Za-z0-9./:_
-]+)\s\s+([A-Za-z0-9 ()._,/#>-]+)\s+([A-Z][A-Z]_?O?W?)\s+([0-9n-]+)\s*
$")
m = patt.match(line)
if m:
  print m.group(3)
  print m.group(4)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [2.4.2/Linux] Getting Python to fork?

2008-02-13 Thread Gilles Ganault
On Mon, 04 Feb 2008 16:40:01 +0100, Rolf van de Krol
<[EMAIL PROTECTED]> wrote:
>To create a deamon, you indeed need to fork two times.

Do I really need this much complication just to exit the script and
let a child handle the pop-up?

I've changed this line, and the parent still doesn't return, and the
script waits until the child ends before resuming to the next step:

if os.fork():
#BAD? sys.exit(0)   
os._exit(0)
else:

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


Re: Basic question

2008-02-13 Thread Guilherme Polo
2008/2/13, WILLIAM SCHMIDT <[EMAIL PROTECTED]>:
> In several places in the Python documentation I have run across an extra "r" 
> that I can not explain:
>
>
>  *
>  In sys.path after the open bracket:
>sys.path = [r'd:\temp']
>
>  In the on line help in the DATA section (towards the end):
>
>  >>> help('sys')
>  Help on built-in module sys:
>
>    truncated 
>
>  DATA
> exec_prefix = r'C:\Python25'
> executable = r'C:\Python25\pythonw.exe'
> path = [r'C:\Python25\Lib\idlelib', r'C:\Python25\python25.zip', r'C:\...
> prefix = r'C:\Python25'
> version = '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bi...
>  *
>
>  Can someone explain what that "r" is doing and where I would find it in the 
> documentation?
>
>  Thank you in advance for your assistance.
>
>  William T. Schmidt
>
>
>
>
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>

"r" is a string literal indicating that a raw string follows. You can
read about it and more here: http://docs.python.org/ref/strings.html

-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regex question

2008-02-13 Thread Wanja Chresta
Hey Mathieu

Due to word wrap I'm not sure what you want to do. What result do you
expect? I get:
>>> print m.groups()
('0021', 'xx0A', 'Siemens: Thorax/Multix FD Lab Settings Auto Window
Width  ', ' ', 'SL', '1')
But only when I insert a space in the 3rd char group (I'm not sure if
your original pattern has a space there or not). So the third group is:
([A-Za-z0-9./:_ -]+). If I do not insert the space, the pattern does not
match the line.

I also cant see how the format of your line is. If it is like this:
line = "...Siemens: Thorax/Multix FD Lab Settings  Auto Window Width..."
where "Auto Window Width" should be the 4th group, you have to mark the
+ in the 3rd group as non-greedy (it's done with a "?"):
http://docs.python.org/lib/re-syntax.html
([A-Za-z0-9./:_ -]+?)
With that I get:
>>> patt.match(line).groups()
('0021', 'xx0A', 'Siemens: Thorax/Multix FD Lab Settings', 'Auto Window
Width ', 'SL', '1')
Which probably is what you want. You can also add the non-greedy marker
in the fourth group, to get rid of the tailing spaces.

HTH
Wanja


mathieu wrote:
> I clearly mark that the separator in between group 3 and group 4
> should contain at least 2 white space, but group 3 is actually reading
> 3 +4

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


Word document accessing using python

2008-02-13 Thread Hari
Hello,
I want to fetch some data from the work document and to fill it inside
excel sheet. For this I want to perform opening word documents and do
some string manipulations for extracting data and to fill it inside
excel sheet.
Can any one help in this by saying how to do this or by giving some
link where I can find some hints.

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


Re: CGI with URL problem

2008-02-13 Thread Ralf Schönian

rodmc schrieb:
> -- sorry if this has shown up twice, but my browser crashed and ended
> up posting the message when I hit the space bar for some odd reason.
> Also it was not quite ready.
> 
> Hi,
> 
> I am writing a small CGI app which tests if another webpage exists,
> the pages are on a Wiki system. Anyway when I run the same function
> (see below) from within IDLE it is ok, however when it is run from
> within the CGI script I get a socket error::
> 
> "URLError:
>   reason = "
> 
> I am not quite sure what is causing this, is there a special way of
> dealing with such things from within CGI script? I have pasted the
> offending function below, along with only the import statement which
> relates to that function.
> 
> Thanks in advance for any help.
> 
> Kind regards,
> 
> rod
> 
> From the CGI version:
> 
> from urllib2 import urlopen as urlopen
> 
> def urlexists(url):
> path="http://x.y.z/wiki/index.php?title="+url
> sock = urlopen(path)
> page=sock.read()
> if "There is currently no text in this page" in page:
> return True
> else:
> return False
> 
> Ammended IDLE version:
> 
> from urllib2 import urlopen as urlopen
> import os,sys
> 
> def urlexists(url):
> path="http://x.y.z/wiki/index.php?title="+url
> sock = urlopen(path)
> page=sock.read()
> if "There is currently no text in this page" in page:
> print "found"
> return True
> else:
> print "not found"
> return False
> 
> if __name__=="__main__":
> urlexists("cheese_test")

Are you using the same user in your cgi script and within IDLE?

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


Re: regex question

2008-02-13 Thread grflanagan
On Feb 13, 1:53 pm, mathieu <[EMAIL PROTECTED]> wrote:
> I do not understand what is wrong with the following regex expression.
> I clearly mark that the separator in between group 3 and group 4
> should contain at least 2 white space, but group 3 is actually reading
> 3 +4
>
> Thanks
> -Mathieu
>
> import re
>
> line = "  (0021,xx0A)   Siemens: Thorax/Multix FD Lab Settings
> Auto Window Width  SL   1 "
> patt = re.compile("^\s*\(([0-9A-Z]+),([0-9A-Zx]+)\)\s+([A-Za-z0-9./:_
> -]+)\s\s+([A-Za-z0-9 ()._,/#>-]+)\s+([A-Z][A-Z]_?O?W?)\s+([0-9n-]+)\s*
> $")
> m = patt.match(line)
> if m:
>   print m.group(3)
>   print m.group(4)


I don't know if it solves your problem, but if you want to match a
dash (-), then it must be either escaped or be the first element in a
character class.

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


Write ooxml .ods (spreadsheat) from python?

2008-02-13 Thread Neal Becker
I'd like to output some data directly in .ods format.  This format appears
to be quite complex.  Is there any python software available to do this?  I
did look at pyuno briefly.  It looks pretty complicated also, and it looks
like it uses it's own private version of python, which would not help me.

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


Re: regex question

2008-02-13 Thread bearophileHUGS
mathieu, stop writing complex REs like obfuscated toys, use the
re.VERBOSE flag and split that RE into several commented and
*indented* lines (indented just like Python code), the indentation
level has to be used to denote nesting. With that you may be able to
solve the problem by yourself. If not, you can offer us a much more
readable thing to fix.

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


Answer: Re: Basic question

2008-02-13 Thread WILLIAM SCHMIDT
Thank you Guilherme 

Solution below:

>>> "Guilherme Polo" <[EMAIL PROTECTED]> 2008-02-13 06:48 >>>
2008/2/13, WILLIAM SCHMIDT <[EMAIL PROTECTED]>:
> In several places in the Python documentation I have run across an extra "r" 
> that I can not explain:
>  *
>  In sys.path after the open bracket:
>sys.path = [r'd:\temp']
>  In the on line help in the DATA section (towards the end):
>  >>> help('sys')
>  Help on built-in module sys:
>    truncated 
>  DATA
> exec_prefix = r'C:\Python25'
> executable = r'C:\Python25\pythonw.exe'
> path = [r'C:\Python25\Lib\idlelib', r'C:\Python25\python25.zip', r'C:\...
> prefix = r'C:\Python25'
> version = '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bi...
>  *
>
>  Can someone explain what that "r" is doing and where I would find it in the 
> documentation?
>  Thank you in advance for your assistance.
>  William T. Schmidt
>

"r" is a string literal indicating that a raw string follows. You can
read about it and more here: http://docs.python.org/ref/strings.html 

-- 
-- Guilherme H. Polo Goncalves

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


win32com.client question

2008-02-13 Thread Juan_Pablo
import  win32com.client
is posible in linux ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Word document accessing using python

2008-02-13 Thread Juan_Pablo
On 13 feb, 10:40, Hari <[EMAIL PROTECTED]> wrote:
> Hello,
> I want to fetch some data from the work document and to fill it inside
> excel sheet. For this I want to perform opening word documents and do
> some string manipulations for extracting data and to fill it inside
> excel sheet.
> Can any one help in this by saying how to do this or by giving some
> link where I can find some hints.
>
> Thanks in advance,
> Hari


I have a similar problem
look this
http://www.thescripts.com/forum/thread39591.html
http://www.velocityreviews.com/forums/t330073-opening-ms-word-files-via-python.html

I hope you can supplement with more information
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client question

2008-02-13 Thread juan pablo
On Feb 13, 2008 11:58 AM, James Matthews <[EMAIL PROTECTED]> wrote:

> What do you mean possible?
>

It is possible to use the library win32com.client in  linux?
I thought that was only for windows
?¿
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python equivt of __FILE__ and __LINE__

2008-02-13 Thread alain
On Feb 12, 7:44 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:

> It still would be nice to have syntax as clean as __FILE__ and __LINE__.

There exists an undocumented builtin called __file__, but
unfortunately no corresponding __line__

Alain

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


Re: Combinatorics

2008-02-13 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
 <[EMAIL PROTECTED]> wrote:
>Cameron Laird:
>> It does occur to me, though, that even more widely applicable
>> than the combinatorics module of Mathematica (if only because of
>> its licensing) might be such resources as
>
>What I was trying to say is that that Mathematica combinatorics module
>contains lots and lots and lots of things, so people that want to
>create a combinatorics module for the Python std lib may read that
>huge list of good ideas as a starting point.
.
.
.
Certainly; and I see that I neglected to make explicit that one
possible response to this thread would be to begin contributing
(pure-Python) combinatoric recipes to the Cookbook.
-- 
http://mail.python.org/mailman/listinfo/python-list


Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread cokofreedom
I was reading up on this site [http://www.noulakaz.net/weblog/
2007/03/18/a-regular-expression-to-check-for-prime-numbers/] of an
interesting way to work out prime numbers using Regular Expression.

However my attempts to use this in Python keep returning none
(obviously no match), however I don't see why, I was under the
impression Python used the same RE system as Perl/Ruby and I know the
convert is producing the correct display of 1's...Any thoughts?

def re_prime(n):
import re
convert = "".join("1" for i in xrange(n))
return re.match("^1?$|^(11+?)\1+$", convert)

print re_prime(2)

Also on a side note the quickest method I have come across as yet is
the following

def prime_numbers(n):
if n < 3: return [2] if n == 2 else []
nroot = int(n ** 0.5) + 1
sieve = range(n + 1)
sieve[1] = 0
for i in xrange(2, nroot):
if sieve[i]:
sieve[i * i: n + 1: i] = [0] * ((n / i - i) + 1)
return [x for x in sieve if x]

Damn clever whoever built this (note sieve will produce a list the
size of your 'n' which is unfortunate)
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Word document accessing using python

2008-02-13 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Hari
> Sent: Wednesday, February 13, 2008 8:40 AM
> To: python-list@python.org
> Subject: Word document accessing using python
> 
> Hello,
> I want to fetch some data from the work document and to fill it inside
> excel sheet. For this I want to perform opening word documents and do
> some string manipulations for extracting data and to fill it inside
> excel sheet.
> Can any one help in this by saying how to do this or by giving some
> link where I can find some hints.
> 


Google for sample scripts.  Check the python documentation about
"Quick-Starts to Python and COM' and makepy.py.


Word Object Model Reference:
http://msdn2.microsoft.com/en-us/library/bb244515.aspx

import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.Visible = True 
word.Documents.Open('c:\\some\\where\\foo.doc')

doc = word.Documents(1)
tables = doc.Tables
for table in tables:
for row in table.Rows:
for cell in row.Cells:
...


Excel reference:  http://msdn2.microsoft.com/en-us/library/bb149081.aspx

import win32com.client
import os
excel = win32com.client.Dispatch("Excel.Application", "Quit")
excel.Visible = 1

dir = os.getcwd()
book = excel.Workbooks.Open(dir + "/test.xls")
sheet = book.Worksheets(1)

for i in sheet.Range("A8:B9"):
print i
print("active chart = " + str(excel.ActiveChart))
print("active sheet= " + str(excel.ActiveSheet))
print("\t" + str(excel.ActiveSheet.Name))
print("active workbook = " + str(excel.ActiveWorkbook))
print("\t" + str(excel.ActiveWorkbook.Name))


new_sheet = excel.Sheets.Add(None, None, None,
win32com.client.constants.xlWorksheet)
new_sheet.Name = "foo"

## import from a csv file
query_results = new_sheet.QueryTables.Add("TEXT;" + dir + "\\data.csv",
new_sheet.Cells(1,1))
query_results.TextFileParseType = win32com.client.constants.xlDelimited;
query_results.TextFileCommaDelimiter = 1;
query_results.Refresh();



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


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


Re: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread Carsten Haese
On Wed, 2008-02-13 at 07:31 -0800, [EMAIL PROTECTED] wrote:
> return re.match("^1?$|^(11+?)\1+$", convert)

That needs to be either

return re.match(r"^1?$|^(11+?)\1+$", convert)

or

return re.match("^1?$|^(11+?)\\1+$", convert)

in order to prevent "\1" from being read as "\x01".

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Difficulty with "inconsistent use of tabs and spaces in indentation" in file called

2008-02-13 Thread Bruno Desthuilliers
Gabriel Genellina a écrit :
(snip)
> Note that all the clues were on the traceback. 
> When people here insist that all error reports should come with the 
> complete stack trace, it isn't because they want to be annoying, but 
> because it's really useful...

+1 QOTW
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: win32com.client question

2008-02-13 Thread James Matthews
What do you mean possible?

On Feb 13, 2008 3:05 PM, Juan_Pablo <[EMAIL PROTECTED]> wrote:

> import  win32com.client
> is posible in linux ?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
http://www.goldwatches.com
-- 
http://mail.python.org/mailman/listinfo/python-list

fromfunc functions

2008-02-13 Thread azrael
I came across the fromfunc() function in numpy where you pass as an
argument the name of a function as a string and also the atributes for
the desired function.

I find this extremly usefull and sexy. Can someone point me how write
a function of such capabilities
-- 
http://mail.python.org/mailman/listinfo/python-list


Fw: error in importing scipy

2008-02-13 Thread Mani Chandra



--- On Wed, 13/2/08, Mani Chandra <[EMAIL PROTECTED]> wrote:

> From: Mani Chandra <[EMAIL PROTECTED]>
> Subject: error in importing scipy
> To: [EMAIL PROTECTED]
> Date: Wednesday, 13 February, 2008, 9:30 PM
> Hi
> I get the following error while importing scipy. 
> /usr/local/lib/python2.4/site-packages/scipy_base/__init__.py:16:
> RuntimeWarning: Python C API version mismatch for module
> fastumath: This Python has API version 1013, module
> fastumath has version 1012. import fastumath # no need to
> use scipy_base.fastumath
> 
> Can someone please help me out?
> 
> Thanks,
> Mani chandra
> 
> 
>   Get the freedom to save as many mails as you wish. To
> know how, go to
> http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html


  Unlimited freedom, unlimited storage. Get it now, on 
http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unbuffered mode

2008-02-13 Thread Hamish Allan
Further to my query about trying to make Python run unbuffered, I have
discovered that a SyntaxError seems to cause Python to close its SSH
connection:

$ ssh localhost python -u
,
  File "", line 1
,
^
SyntaxError: invalid syntax
$

Whereas a different sort of error (e.g. NameError) does not:

$ ssh localhost python -u
pront
[^D]
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'pront' is not defined
$

Can anyone tell me why?!

Thanks,
Hamish

On Feb 13, 2008 1:12 AM, Hamish Allan <[EMAIL PROTECTED]> wrote:
> Hi,
>
> The man page for python says:
>
> "-u Force stdin, stdout and stderr to be totally unbuffered."
>
> However, when I try:
>
> $ ssh localhost python -u
> print 'hello, world'
> [^D]
> hello, world
> $
>
> Nothing happens until I send that EOF. I'm pretty sure it's not SSH
> that's buffering because when I try:
>
> $ ssh localhost bash
> echo 'hello, world'
> hello, world
> [^D]
> $
>
> The 'hello, world' comes back immediately (I don't need to send the EOF).
>
> I've also tried:
>
> $ ssh localhost python -u
> import sys
> sys.stdout.write('hello, world\n')
> sys.stdout.flush()
> [^D]
> hello, world
> $
>
> Again, nothing happens until I send the EOF. How can I get Python to
> run over SSH unbuffered?
>
> Thanks,
> Hamish
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread Dotan Cohen
On 13/02/2008, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]> wrote:
> -On [20080212 22:15], Dotan Cohen ([EMAIL PROTECTED]) wrote:
>  >Note that Google will give a calculator result for "1 kilogram in
>  >pounds", but not for "1 kilogram in inches". I wonder why not? After
>  >all, both are conversions of incompatible measurements, ie, they
>  >measure different things.
>
>
> Eh? Last I checked both pound and kilogram are units of mass, so where is
>  the incompatibility?
>

Pound is a unit of force. That's why people like to say that you will
weigh 1/6th on the moon. If here you are 75 kilo, 165 pound, on the
moon you should be 75 kilo, 28 pound.

Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: win32com.client question

2008-02-13 Thread Gerhard Häring
Juan_Pablo wrote:
> import  win32com.client
> is posible in linux ?

Not in any meaningful way.

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


noobie question regarding installing a package

2008-02-13 Thread A_H
HI, I'm trying to install NumPy and the instructions say:

python setup.py install


When I try that it says, unhelpfully:


"This is the wrong setup.py"



So what does this mean, and what is the right setup.py?


Thanks,



grg




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


Re: regex question

2008-02-13 Thread Paul McGuire
On Feb 13, 6:53 am, mathieu <[EMAIL PROTECTED]> wrote:
> I do not understand what is wrong with the following regex expression.
> I clearly mark that the separator in between group 3 and group 4
> should contain at least 2 white space, but group 3 is actually reading
> 3 +4
>
> Thanks
> -Mathieu
>
> import re
>
> line = "      (0021,xx0A)   Siemens: Thorax/Multix FD Lab Settings
> Auto Window Width          SL   1 "
> patt = re.compile("^\s*\(([0-9A-Z]+),([0-9A-Zx]+)\)\s+([A-Za-z0-9./:_
> -]+)\s\s+([A-Za-z0-9 ()._,/#>-]+)\s+([A-Z][A-Z]_?O?W?)\s+([0-9n-]+)\s*
> $")


I love the smell of regex'es in the morning!

For more legible posting (and general maintainability), try breaking
up your quoted strings like this:

line = \
"  (0021,xx0A)   Siemens: Thorax/Multix FD Lab Settings  " \
"Auto Window Width  SL   1 "

patt = re.compile(
"^\s*"
"\("
"([0-9A-Z]+),"
"([0-9A-Zx]+)"
"\)\s+"
"([A-Za-z0-9./:_ -]+)\s\s+"
"([A-Za-z0-9 ()._,/#>-]+)\s+"
"([A-Z][A-Z]_?O?W?)\s+"
"([0-9n-]+)\s*$")


Of course, the problem is that you have a greedy match in the part of
the regex that is supposed to stop between "Settings" and "Auto".
Change patt to:

patt = re.compile(
"^\s*"
"\("
"([0-9A-Z]+),"
"([0-9A-Zx]+)"
"\)\s+"
"([A-Za-z0-9./:_ -]+?)\s\s+"
"([A-Za-z0-9 ()._,/#>-]+)\s+"
"([A-Z][A-Z]_?O?W?)\s+"
"([0-9n-]+)\s*$")

or if you prefer:

patt = re.compile("^\s*\(([0-9A-Z]+),([0-9A-Zx]+)\)\s+([A-Za-z0-9./:_
-]+?)\s\s+([A-Za-z0-9 ()._,/#>-]+)\s+([A-Z][A-Z]_?O?W?)\s+([0-9n-]+)\s*
$")

It looks like you wrote this regex to process this specific input
string - it has a fragile feel to it, as if you will have to go back
and tweak it to handle other data that might come along, such as

  (xx42,xx0A)   Honeywell: Inverse Flitznoid (Kelvin)
80  SL   1


Just out of curiosity, I wondered what a pyparsing version of this
would look like.  See below:

from pyparsing import Word,hexnums,delimitedList,printables,\
White,Regex,nums

line = \
"  (0021,xx0A)   Siemens: Thorax/Multix FD Lab Settings  " \
"Auto Window Width  SL   1 "

# define fields
hexint = Word(hexnums+"x")
text = delimitedList(Word(printables),
delim=White(" ",exact=1), combine=True)
type_label = Regex("[A-Z][A-Z]_?O?W?")
int_label = Word(nums+"n-")

# define line structure - give each field a name
line_defn = "(" + hexint("x") + "," + hexint("y") + ")" + \
text("desc") + text("window") + type_label("type") + \
int_label("int")

line_parts = line_defn.parseString(line)
print line_parts.dump()
print line_parts.desc

Prints:
['(', '0021', ',', 'xx0A', ')', 'Siemens: Thorax/Multix FD Lab
Settings', 'Auto Window Width', 'SL', '1']
- desc: Siemens: Thorax/Multix FD Lab Settings
- int: 1
- type: SL
- window: Auto Window Width
- x: 0021
- y: xx0A
Siemens: Thorax/Multix FD Lab Settings

I was just guessing on the field names, but you can see where they are
defined and change them to the appropriate values.

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


boost.python Event object wrapped with bp::object()

2008-02-13 Thread Alexander Eisenhuth
Hello everybody,

I Use a C++ thread that is called from the python sides to provoke some 
activities. The calls set some booleans in the thread object and return. To 
synchrThreadClassonize the execution in the thread, the idea of me is, to give 
a 
Python Event() object as bp::object to the C++ thread, that calls the python 
"set" attribute after the related activity has finished. Maybe this code is 
clearer:

Python:
thread = wrapper.ThreadClass()
event = Event()
thread.methode(event)
event.wait()


C++:
ThreadClass::methode(bp::object event)
{
 this->myEvent = event
 ...
 methodeCalled = true
 ...
}

ThreadClass::threadLoop()
{
 ...
 if (methodeCalled) {
 ...
 this->myEvent.attr("set")();
 }

}

The application crashes. If I comment out event.wait() it doesn't crash.

Any suggestions or experiances?

Thanks a lot
Alexander
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client question

2008-02-13 Thread Mike Driscoll
On Feb 13, 8:05 am, Juan_Pablo <[EMAIL PROTECTED]> wrote:
> import  win32com.client
> is posible in linux ?

No. It's a Windows only Python extension.

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


Re: Can anyone help, please?

2008-02-13 Thread Douglas Wells
In article <[EMAIL PROTECTED]>,
  maehhheeyy <[EMAIL PROTECTED]> writes:
> Hi, right now I'm using Python and Multicast. I have the code for
> Multicast receiver on Python but I keep getting this error;

Hi,

In the future please use a Subject: line that is relevant to your
inquiry.  Many people only read articles with "interesting"
subjects.  This is particularly true in groups like this one with
200+ messages a day.

> File "", line 1, in bind
> error: (10049, "Can't assign requested address")
> 
> The error is coming from this line;
> sock.bind ((MCAST_ADDR, MCAST_PORT))

You didn't provide either the OS that you're running on, nor your
network interface configuration, both of which are relevant to use
of IP-multicast.  (Many/most languages, including Python, do not
have a separate networking model:  they simply provide access to
the one provided by the target platform.

> This is the code that I am using:
> 
> [ ... ]
> 
> ANY = "0.0.0.0"
> [ ... ]
> 
> status = sock.setsockopt(socket.IPPROTO_IP,
>  socket.IP_ADD_MEMBERSHIP,
>  socket.inet_aton(MCAST_ADDR) +
> socket.inet_aton(ANY));

If I had to guess based on facts available, I would guess that
your operating system requires you to select the appropriate
interface.  Try replacing the second argument (the "ANY" one) with
the address of the networking interface over which you wish to
communicate.  Note that the interface *must* be multicast-capable
(on many platforms), and "localhost" usually is not.  So, you want
an/the address on your Ethernet interface, for example.

I include below an example program that works on my system (FreeBSD)
and has been somewhat altered to be similar to your failing test case.

 - dmw

=
#! /usr/bin/env python

# Receiver:

##

import socket
import struct
import time

MULTICAST_ADDR = '225.0.0.1'
PORT = 1200
REPORT_LENGTH = 1024000
BUFFSIZE = 1024

ANY_IPADDR = struct.pack ("!L", socket.INADDR_ANY)
INTERFACE_ADDR = socket.gethostbyname (socket.gethostname ())

ip = socket.inet_aton (MULTICAST_ADDR) + socket.inet_aton (INTERFACE_ADDR)

sock = socket.socket (socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)

sock.setsockopt (socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, ip)

sock.bind ((socket.inet_ntoa (ANY_IPADDR), PORT))

start = time.time ()
total_data_length = 0
print 'Listening ...'

while 1:
try:
data, addr = sock.recvfrom (BUFFSIZE)
total_data_length += len (data)
if (total_data_length % REPORT_LENGTH) == 0:
elapsed = time.time () - start
print "%7.3f: %d octets from %s" % (elapsed, 
total_data_length, addr)
except socket.error, e:
print "Socket error" + e
break

##

=

-- 
.   Douglas Wells .  Connection Technologies  .
.   Internet:  -sp9804- -at - contek.com- .
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread Rafael Sachetto
with this works:

 return re.match(r"^1?$|^(11+?)\1+$", convert)

but it match the non-prime numbers. So re_prime(2) will return null
and  re_prime(4) will return a match

2008/2/13, Carsten Haese <[EMAIL PROTECTED]>:
> On Wed, 2008-02-13 at 07:31 -0800, [EMAIL PROTECTED] wrote:
> > return re.match("^1?$|^(11+?)\1+$", convert)
>
> That needs to be either
>
> return re.match(r"^1?$|^(11+?)\1+$", convert)
>
> or
>
> return re.match("^1?$|^(11+?)\\1+$", convert)
>
> in order to prevent "\1" from being read as "\x01".
>
> --
> Carsten Haese
> http://informixdb.sourceforge.net
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


--
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Combinatorics

2008-02-13 Thread Thorsten Kampe
* Michael Robertson (Mon, 11 Feb 2008 23:52:31 -0800)
> Where is the python equivalent of:
> 
> http://search.cpan.org/~fxn/Algorithm-Combinatorics-0.16/Combinatorics.pm
> 
> combinations (with and without repetition)
> variations (with and without repetition)
> permutations

Permutations are also with and without repetition...

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


ANN: Leo 4.4.7 beta 1 released

2008-02-13 Thread Edward K Ream
Leo 4.4.7 beta 1 is available at:
http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106

This version features the ipython plugin that provides a two-way bridge
between Leo and IPython.  See 
http://webpages.charter.net/edreamleo/IPythonBridge.html

Leo's main discussion is now at: http://groups.google.com/group/leo-editor

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.4.7:

- The ipython plugin creates a simple, powerful, effective bridge between 
IPython and Leo.
  See http://webpages.charter.net/edreamleo/IPythonBridge.html
- Improved handling of unicode encodings in @auto files.
- All import commands now support @path directives in ancestor nodes.
- Fixed several minor bugs.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Forum:http://groups.google.com/group/leo-editor
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
CVS:  http://leo.tigris.org/source/browse/leo/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html

Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


Re: fromfunc functions

2008-02-13 Thread Chris
On Feb 13, 5:51 pm, azrael <[EMAIL PROTECTED]> wrote:
> I came across the fromfunc() function in numpy where you pass as an
> argument the name of a function as a string and also the atributes for
> the desired function.
>
> I find this extremly usefull and sexy. Can someone point me how write
> a function of such capabilities

class test_class():
def test_func(self, string):
print string

test = test_class()
getattr(test, 'test_class'){'this is the test argument')

getattr raises an Attribute Error though if the function doesn't exist
so you'll need to catch that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Write ooxml .ods (spreadsheat) from python?

2008-02-13 Thread Rolf van de Krol
Neal Becker wrote:
> I'd like to output some data directly in .ods format.  This format appears
> to be quite complex.  Is there any python software available to do this?  I
> did look at pyuno briefly.  It looks pretty complicated also, and it looks
> like it uses it's own private version of python, which would not help me.
>   
Google is your friend. For example this: 
http://www.oooforum.org/forum/viewtopic.phtml?p=56037#56037
It seems like that guy found the way to go for your problem.

Rolf

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


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread Jeff Schwab
Jeroen Ruigrok van der Werven wrote:
> -On [20080212 22:15], Dotan Cohen ([EMAIL PROTECTED]) wrote:
>> Note that Google will give a calculator result for "1 kilogram in
>> pounds", but not for "1 kilogram in inches". I wonder why not? After
>> all, both are conversions of incompatible measurements, ie, they
>> measure different things.
> 
> Eh? Last I checked both pound and kilogram are units of mass, so where is
> the incompatibility?

I've never heard of "pound" as a unit of mass.  At least where I went to 
school (Boston, MA), "pound" is the English unit of force, "slug" is the 
(rarely used) English unit of mass, and "kilogram" is the SI unit of 
mass.  ("English" in this context does not refer to the charming isle at 
the Western edge of Europe, but to the system of non-metric units used 
by most Americans.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fw: error in importing scipy

2008-02-13 Thread Robert Kern
Mani Chandra wrote:
> 
> 
> --- On Wed, 13/2/08, Mani Chandra <[EMAIL PROTECTED]> wrote:
> 
>> From: Mani Chandra <[EMAIL PROTECTED]>
>> Subject: error in importing scipy
>> To: [EMAIL PROTECTED]
>> Date: Wednesday, 13 February, 2008, 9:30 PM
>> Hi
>> I get the following error while importing scipy. 
>> /usr/local/lib/python2.4/site-packages/scipy_base/__init__.py:16:
>> RuntimeWarning: Python C API version mismatch for module
>> fastumath: This Python has API version 1013, module
>> fastumath has version 1012. import fastumath # no need to
>> use scipy_base.fastumath
>>
>> Can someone please help me out?

Your scipy was built against an older version of Python than the one you are 
trying to run it with. Rebuild scipy with your current version of Python.

-- 
Robert Kern

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

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


Re: Python equivt of __FILE__ and __LINE__

2008-02-13 Thread Jeff Schwab
alain wrote:
> On Feb 12, 7:44 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> 
>> It still would be nice to have syntax as clean as __FILE__ and __LINE__.
> 
> There exists an undocumented builtin called __file__, but
> unfortunately no corresponding __line__

Drat!  So close!  Thanks for the info.  Oh well, I guess special cases 
aren't all that special, anyway.

Maybe a function called srcinfo.here() could return a tuple of the file 
name and line number, to allow syntax like:

 print("The program has reached %f:%d" % srcinfo.here())

Methods names like file_name() and line_no() aren't too hideous, either.
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: NUCULAR B3 Full text indexing (now on Win32 too)

2008-02-13 Thread Aaron Watters

ANNOUNCE: NUCULAR Fielded Full Text Indexing, BETA 3

Nucular is a system for creating full text
indices for fielded data. It can be accessed
via a Python API or via a suite of command line
interfaces.

NEWS

Nucular now supports WIN32. Current releases
of Nucular abstract the file system in order
to emulate file system feature missing
on NT file systems which prevented older
versions from running correctly on Windows NT
based systems.

Proximity search added: Current versions of
Nucular allow queries to search for a sequence
of words near eachother separated by
no more than a specified number of other words.

Faceted suggestions: Nucular queries now
support faceted suggestions for values for
fields which are related to a query.

Faster index builds: Current releases of
Nucular have completely revamped internal
data structures which build indices much faster
(and query a bit faster also). For example some
builds run more than 8 times faster than
previously.

Read more and download at:

   http://nucular.sourceforge.net

ONLINE DEMOS:

Python source search:
 http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=malodorous+parrot
Mondial geographic text search:
 http://www.xfeedme.com/nucular/mondial.py/go?attr_name=ono
Gutenberg book search:
 http://www.xfeedme.com/nucular/gut.py/go?attr_Comments=immoral+english

BACKGROUND:

Nucular is intended to help store and retrieve
searchable information in a manner somewhat similar
to the way that "www.hotjobs.com" stores and
retrieves job descriptions, for example.

Nucular archives fielded documents and retrieves
them based on field value, field prefix, field
word prefix, or full text word prefix,
word proximity or combinations of these.
Nucular also includes features for determining
values related to a query often called query facets.

FEATURES

Nucular is very light weight. Updates and accesses
do not require any server process or other system
support such as shared memory locking.

Nucular supports concurrency. Arbitrary concurrent
updates and accesses by multiple processes or threads
are supported, with no possible locking issues.

Nucular supports document threading in the
manner of USENET replies. Built in semantics allows
"follow ups" to messages to match patterns that
match the "original" messages.

Nucular indexes and retrieves data quickly.

I hope you like.
   -- Aaron Watters

===
It's humbling to think that when Mozart was my age
he'd been dead for 5 years.  -- Tom Lehrer
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fromfunc functions

2008-02-13 Thread Chris
On Feb 13, 5:51 pm, azrael <[EMAIL PROTECTED]> wrote:
> I came across the fromfunc() function in numpy where you pass as an
> argument the name of a function as a string and also the atributes for
> the desired function.
>
> I find this extremly usefull and sexy. Can someone point me how write
> a function of such capabilities

getattr(object, 'function name')(*args)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fromfunc functions

2008-02-13 Thread Marc 'BlackJack' Rintsch
On Wed, 13 Feb 2008 07:51:36 -0800, azrael wrote:

> I came across the fromfunc() function in numpy where you pass as an
> argument the name of a function as a string and also the atributes for
> the desired function.

If you mean `fromfunction()` then you don't give the name of the function
as string but the function itself as argument.  And what you call
attributes are arguments.

> I find this extremly usefull and sexy. Can someone point me how write
> a function of such capabilities

Functions are objects in Python, you can pass them around like any other
object/value.

In [18]: def f(func, arg):
   : return func(arg)
   :

In [19]: f(int, '42')
Out[19]: 42

In [20]: f(str.split, 'a b c')
Out[20]: ['a', 'b', 'c']

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unbuffered mode

2008-02-13 Thread Hamish Allan
Sorry to reply to myself again, but I think I now know the answer and
wish to post it for the archives.

Python run without '-i', if not sys.stdin.isatty(), expects to read a
whole script before doing anything else (presuming to be reading it
from a pipe). Therefore syntax errors are fatal, but otherwise nothing
is executed until EOF.

So the answer to my question is to run:

$ ssh localhost python -ui

Best wishes,
Hamish

On Feb 13, 2008 4:20 PM, Hamish Allan <[EMAIL PROTECTED]> wrote:
> Further to my query about trying to make Python run unbuffered, I have
> discovered that a SyntaxError seems to cause Python to close its SSH
> connection:
>
> $ ssh localhost python -u
> ,
>   File "", line 1
> ,
> ^
> SyntaxError: invalid syntax
> $
>
> Whereas a different sort of error (e.g. NameError) does not:
>
> $ ssh localhost python -u
> pront
> [^D]
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'pront' is not defined
> $
>
> Can anyone tell me why?!
>
> Thanks,
> Hamish
>
>
> On Feb 13, 2008 1:12 AM, Hamish Allan <[EMAIL PROTECTED]> wrote:
> > Hi,
> >
> > The man page for python says:
> >
> > "-u Force stdin, stdout and stderr to be totally unbuffered."
> >
> > However, when I try:
> >
> > $ ssh localhost python -u
> > print 'hello, world'
> > [^D]
> > hello, world
> > $
> >
> > Nothing happens until I send that EOF. I'm pretty sure it's not SSH
> > that's buffering because when I try:
> >
> > $ ssh localhost bash
> > echo 'hello, world'
> > hello, world
> > [^D]
> > $
> >
> > The 'hello, world' comes back immediately (I don't need to send the EOF).
> >
> > I've also tried:
> >
> > $ ssh localhost python -u
> > import sys
> > sys.stdout.write('hello, world\n')
> > sys.stdout.flush()
> > [^D]
> > hello, world
> > $
> >
> > Again, nothing happens until I send the EOF. How can I get Python to
> > run over SSH unbuffered?
> >
> > Thanks,
> > Hamish
> >
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Cannot understand error message

2008-02-13 Thread Bill Davy
The following code produces an error message (using Idle with Py 2.4 and 
2.5).  "There's an error in your program: EOL while scanning single-quoted 
string".  It comes just after "s = ''" (put there to try and isolate the 
broken string).

It would be good if the error message pointed me to the start of said single 
quoted string.

The colouring in IDLE does not indicate a bad string.

Puzzled.

Bill


#

# The traceback module is used to provide a stack trace to

# show the user where the error occured.  See Error().

#

import traceback

#

# The math module is used to convert numbers between the Python real format

# and the Keil real format.  See KeilToFloatingPoint() and FloatingToKeil().

#

import math



LOAD_LIT = 1

LOAD_REG = 1

STORE_REG = 1

ADD_LIT_FP = 2 + 8

ADD_LIT_INT = 2 + 16

ADD_REG_FP = 2 + 32

ADD_REG_INT = 9

SUB_LIT_FP = 11

SUB_LIT_INT = 12

SUB_REG_FP = 13

SUB_REG_INT =14

MUL_LIT_FP = 11

MUL_LIT_INT = 12

MUL_REG_FP = 13

MUL_REG_INT =14

DIV_LIT_FP = 11

DIV_LIT_INT = 12

DIV_REG_FP = 13

DIV_REG_INT =14

AND_LIT_INT = 12

AND_REG_INT =14

OR_LIT_INT = 12

OR_REG_INT =14

NEGATE_FP = 11

NEGATE_INT = 12

ABSOLUTE_FP = 13

ABSOLUTE_INT = 14

INVERT_INT = 15

JUMP_OPCODE = 15

JLT_OPCODE = 15

JGT_OPCODE = 15

JLE_OPCODE = 15

JGE_OPCODE = 15

JEQ_OPCODE = 15

JNE_OPCODE = 15



BinaryOps={

"LOAD":{float:{"L":LOAD_LIT,"R":LOAD_REG},int:{"L":LOAD_LIT,"R":LOAD_REG}},

"STORE":{float:{"R":STORE_REG},int:{"R":STORE_REG}},


"ADD":{float:{"L":ADD_LIT_FP,"R":ADD_REG_FP},int:{"L":ADD_LIT_INT,"R":ADD_REG_INT}},


"SUB":{float:{"L":SUB_LIT_FP,"R":SUB_REG_FP},int:{"L":SUB_LIT_INT,"R":SUB_REG_INT}},


"MUL":{float:{"L":MUL_LIT_FP,"R":MUL_REG_FP},int:{"L":MUL_LIT_INT,"R":MUL_REG_INT}},


"DIV":{float:{"L":DIV_LIT_FP,"R":DIV_REG_FP},int:{"L":DIV_LIT_INT,"R":DIV_REG_INT}},

"AND":{int:{"L":AND_LIT_INT,"R":AND_REG_INT}},

"OR":{int:{"L":OR_LIT_INT,"R":OR_REG_INT}}

}

UnaryOps={

"NEGATE":{float:NEGATE_FP, int:NEGATE_INT},

"ABSOLUTE":{float:ABSOLUTE_FP, int:ABSOLUTE_INT},

"INVERT":{int:INVERT_INT}

}



JumpOps={

"JUMP":JUMP_OPCODE,

"JLT":JLT_OPCODE,

"JGT":JGT_OPCODE,

"JLE":JLE_OPCODE,

"JGE":JGE_OPCODE,

"JEQ":JEQ_OPCODE,

"JNE":JNE_OPCODE

}

def IsOpCode(s):

if ( s in BinaryOps ): return True;

if ( s in UnaryOps ): return True;

if ( s in JumpOps ): return True;

return False

class Register:

"""

This class provides us with a register (say) 0..32

In addtion to a number, a register can be given a name.

It allows LOAD(arg) and other opcodes to distinguish between

references to a register and a literal value.

"""

def __init__(self,Id,Name=None):

self.Number = Id

if ( Name == None):

self.Name = "R%d" % Id

else:

self.Name = Name

def RegisterNumber(self):

return self.Number



def RegisterName(self):

return self.Name

R0=Register(0)

R1=Register(1)

R2=Register(2)

Now=Register(2,"Now")

def IsRegister(arg):

return hasattr( arg, "RegisterNumber")

assert not IsRegister(0)

assert not IsRegister(1.2)

assert IsRegister(R1)

assert IsRegister(Now)

#

# ErrorCount is global as it is shared by all slaves.

#

ErrorCount = 0

def Error(Message):

"""

work back through the traceback until you find a function whose name is 
in one of the

opcode dictionaries and trace back from there.  This will keep internal

implemenataion functions private but still allow the suer to define 
functions

that generate code.

"""

global ErrorCount

ErrorCount += 1



"""

[

('', 1, '?', None),

('C:\\Python24\\lib\\idlelib\\run.py', 90, 'main', 'ret = method(*args, 
**kwargs)'),

('C:\\Python24\\lib\\idlelib\\run.py', 283, 'runcode', 'exec code in 
self.locals'),

('H:\\Husky Experiments\\Viper1\\tmp.py', 434, '?', 'STORE(1)'),

('H:\\Husky Experiments\\Viper1\\tmp.py', 147, 'STORE', 
'self.BINOP("STORE",Arg,Msg)'),

('H:\\Husky Experiments\\Viper1\\tmp.py', 198, 'BINOP', 'return 
Error("Cannot perform %s on %s" % (Op,Arg))'),

('H:\\Husky Experiments\\Viper1\\tmp.py', 106, 'Error', 'tb = 
traceback.extract_stack()')

]

"""

tb = traceback.extract_stack()

BeforePrinting = True

IsPrinting = False

for i in range(len(tb)-1,0,-1):

frame = tb[i]

if ( BeforePrinting ):

# Looking to start

if IsOpCode(frame[2]): # start printing

IsPrinting = True

BeforePrinting = False

print "John: %s\nTrace back follows:" % Message

elif ( IsPrinting ):

print '\tFile "%s", line %u, %s' % (frame[0], frame[1], 
frame[3])

# Stop when we find the curious function "?"

if (frame[2] == "?"):

break

if BeforePrinting:

print "John: %s (no trace back)" % Messa

Re: Write ooxml .ods (spreadsheat) from python?

2008-02-13 Thread Neal Becker
Rolf van de Krol wrote:

> Neal Becker wrote:
>> I'd like to output some data directly in .ods format.  This format
>> appears
>> to be quite complex.  Is there any python software available to do this? 
>> I
>> did look at pyuno briefly.  It looks pretty complicated also, and it
>> looks like it uses it's own private version of python, which would not
>> help me.
>>   
> Google is your friend. For example this:
> http://www.oooforum.org/forum/viewtopic.phtml?p=56037#56037
> It seems like that guy found the way to go for your problem.
> 
> Rolf
> 

I don't think he's my friend today.  I looked at this lib, but it starts
with:
# OOo's libraries 
 import uno 
 

IIUC, this is the same problem.  This uno module is tied to an old python
(2.2?) that ships with OO.  Is it available standalone to build for python
2.5?

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


Re: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread Carsten Haese
On Wed, 2008-02-13 at 10:40 -0800, [EMAIL PROTECTED] wrote:
> But why doesn't it work when you make that change?

I can't answer that question, because it *does* work when you make that
change.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


RE: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED]
> Sent: Wednesday, February 13, 2008 1:41 PM
> To: python-list@python.org
> Subject: Re: Regular Expression for Prime Numbers (or How I came to
> fail at them, and love the bomb)
> 
> On Feb 13, 9:48 am, Carsten Haese <[EMAIL PROTECTED]> wrote:
> > On Wed, 2008-02-13 at 07:31 -0800, [EMAIL PROTECTED] wrote:
> > >     return re.match("^1?$|^(11+?)\1+$", convert)
> >
> > That needs to be either
> >
> > return re.match(r"^1?$|^(11+?)\1+$", convert)
> >
> > or
> >
> > return re.match("^1?$|^(11+?)\\1+$", convert)
> >
> > in order to prevent "\1" from being read as "\x01".
> 
> But why doesn't it work when you make that change?


It does work.  Read the referenced website.

If there is a match then 
the number isn't prime
else # no match
the number is prime.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA622


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


Re: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread [EMAIL PROTECTED]
On Feb 13, 9:48 am, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Wed, 2008-02-13 at 07:31 -0800, [EMAIL PROTECTED] wrote:
> >     return re.match("^1?$|^(11+?)\1+$", convert)
>
> That needs to be either
>
> return re.match(r"^1?$|^(11+?)\1+$", convert)
>
> or
>
> return re.match("^1?$|^(11+?)\\1+$", convert)
>
> in order to prevent "\1" from being read as "\x01".

But why doesn't it work when you make that change?

>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

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


Re: Big time WTF with generators - bug?

2008-02-13 Thread Steve Holden
James Stroud wrote:
> [...] I then append the growing list of series generator
> into the "serieses" list ("serieses" is plural for series if your 
> vocablulary isn't that big).
> 
Not as big as your ego, apparently ;-) And don't be coming back with any 
argumentses.

regardses
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: OT: Speed of light

2008-02-13 Thread Jeff Schwab
Hrvoje Niksic wrote:
> Jeff Schwab <[EMAIL PROTECTED]> writes:
> 
>> Jeroen Ruigrok van der Werven wrote:
>>> -On [20080212 22:15], Dotan Cohen ([EMAIL PROTECTED]) wrote:
 Note that Google will give a calculator result for "1 kilogram in
 pounds", but not for "1 kilogram in inches". I wonder why not? After
 all, both are conversions of incompatible measurements, ie, they
 measure different things.
>>> Eh? Last I checked both pound and kilogram are units of mass, so where is
>>> the incompatibility?
>> I've never heard of "pound" as a unit of mass.  At least where I went
>> to school (Boston, MA), "pound" is the English unit of force, "slug"
>> is the (rarely used) English unit of mass, and "kilogram" is the SI
>> unit of mass.
> 
> It would be possible for US pound to only refer to weight, but I
> cannot find references to corroborate it.  For example, taken from
> Wikipedia:
> 
> In 1958 the United States and countries of the Commonwealth of
> Nations agreed upon common definitions for the pound and the
> yard. The international avoirdupois pound was defined as exactly
> 453.59237 grams.
> 
> The "pound-force" wikipedia entry documents "pound" being used as a
> unit of force "in some contexts, such as structural engineering
> applications."

That's suprising (to me, anyway.  We (Americans) all measure our weight 
in pounds.  People talk about how much less they would weigh on the 
moon, in pounds, or even near the equator (where the Earth's radius is 
slightly higher).  I remember converting pounds to Newtons, and vice 
versa, in school.  Apparently, what everybody here calls a "pound," 
Wikipedia lists as a "pound-force."  But I've only ever heard it called 
a pound, if anybody ever used "pound" as a unit of mass at school, 
they'd have been laughed at.

http://en.wikipedia.org/wiki/Pound-force
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Word document accessing using python

2008-02-13 Thread Juan_Pablo

> import win32com.client

 but, window32com.client is only functional in  windows
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot understand error message

2008-02-13 Thread Chris
It doesn't like all that text in the previous one...

Just before s = '' you have 4 double quotes to close to doc-string
instead of 3.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyinstall and matplotlib

2008-02-13 Thread Russell E. Owen
In article 
<[EMAIL PROTECTED]>,
 John Henry <[EMAIL PROTECTED]> wrote:

> On Feb 9, 2:53 pm, John Henry <[EMAIL PROTECTED]> wrote:
> > Has anybody been able to create an exe of their python applications
> > involving matplotlib using pyinstall (ver 1.3)?  I am getting a:
> >
> >  RuntimeError: Could not find the matplotlib data files
> >
> > when I attempt to run the exe created.
> >
> > In searching the web, it appears this is an issue when others tried to
> > use py2exe as well.  Unfortunately, the few hits I saw doesn't include
> > enough details to inspire me as to what I should be doing in my
> > pyinstall .spec file.
> >
> > Does anybody has an example or information about this?
> >
> > Thanks,
> 
> Well, looks like nobody has an answer to this question.
> 
> How'bout py2exe or other ways of creating exe files out of matplotlib
> projects?  Has anybody been able to do that?  (I am cross-posting
> these messages to the matploblib mailing list).

For py2exe I have appended a setup script I use to bundle an application 
that includes matplotlib. I am no Windows expert and there are probably 
better ways to do it, but it does work. I have made no attempt to strip 
out extra stuff.

(As for pyinstaller:a year or so ago I tried to use it to make a bundled 
*unix* version of my app. If that had worked I'd have considered trying 
to use it for Windows as well. But after a lot of experimenting I was 
never able to get anything even close to functional. Maybe it's better 
now.)

-- Russell

from distutils.core import setup
import os
import sys
import matplotlib
import py2exe

# The following code is necessary for py2exe to find win32com.shell.
# Solution from 

import win32com
import py2exe.mf as modulefinder
for pth in win32com.__path__[1:]:
modulefinder.AddPackagePath("win32com", pth)
for extra in ["win32com.shell"]:
__import__(extra)
m = sys.modules[extra]
for pth in m.__path__[1:]:
modulefinder.AddPackagePath(extra, pth)

tuiRoot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
roRoot = os.path.join(tuiRoot, "ROPackage")
sys.path = [tuiRoot, roRoot] + sys.path
import TUI.Version
mainProg = os.path.join(tuiRoot, "runtui.py")

NDataFilesToPrint = 0 # number of data files to print, per directory

def addDataFiles(dataFiles, fromDir, toSubDir=None, 
inclHiddenDirs=False):
"""Find data files and format data for the data_files argument of 
setup.

In/Out:
- dataFiles: a list to which is appended zero or more of these 
elements:
[subDir, list of paths to resource files]

Inputs:
- fromDir: path to root directory of existing resource files
- toSubDir: relative path to resources in package;
if omitted then the final dir of fromDir is used
- inclHiddenDirs: if True, the contents of directories whose names
start with "." are included

Returns a list of the following elements:
"""
lenFromDir = len(fromDir)
if toSubDir == None:
toSubDir = os.path.split(fromDir)[1]
for (dirPath, dirNames, fileNames) in os.walk(fromDir):
if not inclHiddenDirs:
numNames = len(dirNames)
for ii in range(numNames-1, -1, -1):
if dirNames[ii].startswith("."):
del(dirNames[ii])
if not dirPath.startswith(fromDir):
raise RuntimeError("Cannot deal with %r files; %s does not 
start with %r" %\
(resBase, dirPath, fromDir))
toPath = os.path.join(toSubDir, dirPath[lenFromDir+1:])
filePaths = [os.path.join(dirPath, fileName) for fileName in 
fileNames]
dataFiles.append((toPath, filePaths))

# Add resources
dataFiles = []
# TUI resources
for resBase in ("Help", "Scripts", "Sounds"):
toSubDir = os.path.join("TUI", resBase)
fromDir = os.path.join(tuiRoot, toSubDir)
addDataFiles(dataFiles, fromDir, toSubDir)
# RO resources
for resBase in ("Bitmaps",):
toSubDir = os.path.join("RO", resBase)
fromDir = os.path.join(roRoot, toSubDir)
addDataFiles(dataFiles, fromDir, toSubDir)

# Add tcl snack libraries
pythonDir = os.path.dirname(sys.executable)
snackSubDir = "tcl\\snack2.2"
snackDir = os.path.join(pythonDir, snackSubDir)
addDataFiles(dataFiles, snackDir, snackSubDir)

# Add matplotlib's data files.
matplotlibDataPath = matplotlib.get_data_path()
addDataFiles(dataFiles, matplotlibDataPath, "matplotlibdata")

if NDataFilesToPrint > 0:
print "\nData files:"
for pathInfo in dataFiles:
print pathInfo[0]
nFiles = len(pathInfo[1])
for resPath in pathInfo[1][0:NDataFilesToPrint]:
print "  ", resPath
if nFiles > NDataFilesToPrint:
print "  ...and %d more" % (nFiles - NDataFilesToPrint)

versDate = TUI.Version.VersionStr
appVers = versDate.split()[0]
distDir = "TUI_%s_Windows" % (appVers,)

inclModules = [
#"email.Utils", # needed for Python 2.5.0
]
# packages

Re: OT: Speed of light

2008-02-13 Thread Hrvoje Niksic
Jeff Schwab <[EMAIL PROTECTED]> writes:

> Jeroen Ruigrok van der Werven wrote:
>> -On [20080212 22:15], Dotan Cohen ([EMAIL PROTECTED]) wrote:
>>> Note that Google will give a calculator result for "1 kilogram in
>>> pounds", but not for "1 kilogram in inches". I wonder why not? After
>>> all, both are conversions of incompatible measurements, ie, they
>>> measure different things.
>>
>> Eh? Last I checked both pound and kilogram are units of mass, so where is
>> the incompatibility?
>
> I've never heard of "pound" as a unit of mass.  At least where I went
> to school (Boston, MA), "pound" is the English unit of force, "slug"
> is the (rarely used) English unit of mass, and "kilogram" is the SI
> unit of mass.

It would be possible for US pound to only refer to weight, but I
cannot find references to corroborate it.  For example, taken from
Wikipedia:

In 1958 the United States and countries of the Commonwealth of
Nations agreed upon common definitions for the pound and the
yard. The international avoirdupois pound was defined as exactly
453.59237 grams.

The "pound-force" wikipedia entry documents "pound" being used as a
unit of force "in some contexts, such as structural engineering
applications."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Big time WTF with generators - bug?

2008-02-13 Thread Jeff Schwab
Steve Holden wrote:
> James Stroud wrote:
>> [...] I then append the growing list of series generator
>> into the "serieses" list ("serieses" is plural for series if your 
>> vocablulary isn't that big).
>>
> Not as big as your ego, apparently ;-) And don't be coming back with any 
> argumentses.

Nasty hobbitses...  We hates them!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot understand error message

2008-02-13 Thread Chris
On Feb 13, 7:29 pm, "Bill Davy" <[EMAIL PROTECTED]> wrote:
> The following code produces an error message (using Idle with Py 2.4 and
> 2.5).  "There's an error in your program: EOL while scanning single-quoted
> string".  It comes just after "s = ''" (put there to try and isolate the
> broken string).
>
> It would be good if the error message pointed me to the start of said single
> quoted string.
>
> The colouring in IDLE does not indicate a bad string.
>
> Puzzled.
>
> Bill
>
> #
>
> # The traceback module is used to provide a stack trace to
>
> # show the user where the error occured.  See Error().
>
> #
>
> import traceback
>
> #
>
> # The math module is used to convert numbers between the Python real format
>
> # and the Keil real format.  See KeilToFloatingPoint() and FloatingToKeil().
>
> #
>
> import math
>
> LOAD_LIT = 1
>
> LOAD_REG = 1
>
> STORE_REG = 1
>
> ADD_LIT_FP = 2 + 8
>
> ADD_LIT_INT = 2 + 16
>
> ADD_REG_FP = 2 + 32
>
> ADD_REG_INT = 9
>
> SUB_LIT_FP = 11
>
> SUB_LIT_INT = 12
>
> SUB_REG_FP = 13
>
> SUB_REG_INT =14
>
> MUL_LIT_FP = 11
>
> MUL_LIT_INT = 12
>
> MUL_REG_FP = 13
>
> MUL_REG_INT =14
>
> DIV_LIT_FP = 11
>
> DIV_LIT_INT = 12
>
> DIV_REG_FP = 13
>
> DIV_REG_INT =14
>
> AND_LIT_INT = 12
>
> AND_REG_INT =14
>
> OR_LIT_INT = 12
>
> OR_REG_INT =14
>
> NEGATE_FP = 11
>
> NEGATE_INT = 12
>
> ABSOLUTE_FP = 13
>
> ABSOLUTE_INT = 14
>
> INVERT_INT = 15
>
> JUMP_OPCODE = 15
>
> JLT_OPCODE = 15
>
> JGT_OPCODE = 15
>
> JLE_OPCODE = 15
>
> JGE_OPCODE = 15
>
> JEQ_OPCODE = 15
>
> JNE_OPCODE = 15
>
> BinaryOps={
>
> 
> "LOAD":{float:{"L":LOAD_LIT,"R":LOAD_REG},int:{"L":LOAD_LIT,"R":LOAD_REG}},
>
> "STORE":{float:{"R":STORE_REG},int:{"R":STORE_REG}},
>
> 
> "ADD":{float:{"L":ADD_LIT_FP,"R":ADD_REG_FP},int:{"L":ADD_LIT_INT,"R":ADD_REG_INT}},
>
> 
> "SUB":{float:{"L":SUB_LIT_FP,"R":SUB_REG_FP},int:{"L":SUB_LIT_INT,"R":SUB_REG_INT}},
>
> 
> "MUL":{float:{"L":MUL_LIT_FP,"R":MUL_REG_FP},int:{"L":MUL_LIT_INT,"R":MUL_REG_INT}},
>
> 
> "DIV":{float:{"L":DIV_LIT_FP,"R":DIV_REG_FP},int:{"L":DIV_LIT_INT,"R":DIV_REG_INT}},
>
> "AND":{int:{"L":AND_LIT_INT,"R":AND_REG_INT}},
>
> "OR":{int:{"L":OR_LIT_INT,"R":OR_REG_INT}}
>
> }
>
> UnaryOps={
>
> "NEGATE":{float:NEGATE_FP, int:NEGATE_INT},
>
> "ABSOLUTE":{float:ABSOLUTE_FP, int:ABSOLUTE_INT},
>
> "INVERT":{int:INVERT_INT}
>
> }
>
> JumpOps={
>
> "JUMP":JUMP_OPCODE,
>
> "JLT":JLT_OPCODE,
>
> "JGT":JGT_OPCODE,
>
> "JLE":JLE_OPCODE,
>
> "JGE":JGE_OPCODE,
>
> "JEQ":JEQ_OPCODE,
>
> "JNE":JNE_OPCODE
>
> }
>
> def IsOpCode(s):
>
> if ( s in BinaryOps ): return True;
>
> if ( s in UnaryOps ): return True;
>
> if ( s in JumpOps ): return True;
>
> return False
>
> class Register:
>
> """
>
> This class provides us with a register (say) 0..32
>
> In addtion to a number, a register can be given a name.
>
> It allows LOAD(arg) and other opcodes to distinguish between
>
> references to a register and a literal value.
>
> """
>
> def __init__(self,Id,Name=None):
>
> self.Number = Id
>
> if ( Name == None):
>
> self.Name = "R%d" % Id
>
> else:
>
> self.Name = Name
>
> def RegisterNumber(self):
>
> return self.Number
>
> def RegisterName(self):
>
> return self.Name
>
> R0=Register(0)
>
> R1=Register(1)
>
> R2=Register(2)
>
> Now=Register(2,"Now")
>
> def IsRegister(arg):
>
> return hasattr( arg, "RegisterNumber")
>
> assert not IsRegister(0)
>
> assert not IsRegister(1.2)
>
> assert IsRegister(R1)
>
> assert IsRegister(Now)
>
> #
>
> # ErrorCount is global as it is shared by all slaves.
>
> #
>
> ErrorCount = 0
>
> def Error(Message):
>
> """
>
> work back through the traceback until you find a function whose name is
> in one of the
>
> opcode dictionaries and trace back from there.  This will keep internal
>
> implemenataion functions private but still allow the suer to define
> functions
>
> that generate code.
>
> """
>
> global ErrorCount
>
> ErrorCount += 1
>
> """
>
> [
>
> ('', 1, '?', None),
>
> ('C:\\Python24\\lib\\idlelib\\run.py', 90, 'main', 'ret = method(*args,
> **kwargs)'),
>
> ('C:\\Python24\\lib\\idlelib\\run.py', 283, 'runcode', 'exec code in
> self.locals'),
>
> ('H:\\Husky Experiments\\Viper1\\tmp.py', 434, '?', 'STORE(1)'),
>
> ('H:\\Husky Experiments\\Viper1\\tmp.py', 147, 'STORE',
> 'self.BINOP("STORE",Arg,Msg)'),
>
> ('H:\\Husky Experiments\\Viper1\\tmp.py', 198, 'BINOP', 'return
> Error("Cannot perform %s on %s" % (Op,Arg))'),
>
> ('H:\\Husky Experiments\\Viper1\\tmp.py', 106, 'Error', 'tb =
> traceback.extract_stack()')
>
> ]
>
> """
>
> tb = traceback.extract_stack()
>
> BeforePrinting = True
>
> IsPrinting = False
>
> for i in range(len(tb)-1,0,-1):
>
> frame = tb[i]
>
> if ( BeforePrinting ):
>
> # Looking to start
>
> 

Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread Grant Edwards
On 2008-02-13, Jeff Schwab <[EMAIL PROTECTED]> wrote:

>> Eh? Last I checked both pound and kilogram are units of mass, so where is
>> the incompatibility?
>
> I've never heard of "pound" as a unit of mass.  At least where I went to 
> school (Boston, MA), "pound" is the English unit of force, "slug" is the 
> (rarely used) English unit of mass,

Back in the day, I was once working on a fire control system
for the Navy.  All the units in the calculations were purely
metric except for one: air density was in slugs/m3.  I always
suspected that was somebody's attempt at humor.

-- 
Grant Edwards   grante Yow!  Where does it go when
  at   you flush?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread Jeff Schwab
Grant Edwards wrote:
> On 2008-02-13, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> 
>>> Eh? Last I checked both pound and kilogram are units of mass, so where is
>>> the incompatibility?
>> I've never heard of "pound" as a unit of mass.  At least where I went to 
>> school (Boston, MA), "pound" is the English unit of force, "slug" is the 
>> (rarely used) English unit of mass,
> 
> Back in the day, I was once working on a fire control system
> for the Navy.  All the units in the calculations were purely
> metric except for one: air density was in slugs/m3.  I always
> suspected that was somebody's attempt at humor.

So what is the mass of a slug, anyway?  (I assume this is slug as in 
bullet, not slimy, creeping thing.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread [EMAIL PROTECTED]
On Feb 13, 12:53 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Wed, 2008-02-13 at 10:40 -0800, [EMAIL PROTECTED] wrote:
> > But why doesn't it work when you make that change?
>
> I can't answer that question, because it *does* work when you make that
> change.

Well, the OP said the function was returning None which meant
no match which implies None means composite for the given example 2.

If None was supposed to mean prime, then why would returing None
for 2 be a  problem?

But isn't this kind of silly?

##3 None
##4 <_sre.SRE_Match object at 0x011761A0>
##5 None
##6 <_sre.SRE_Match object at 0x011761A0>
##7 None
##8 <_sre.SRE_Match object at 0x011761A0>
##9 <_sre.SRE_Match object at 0x011761A0>
##10 <_sre.SRE_Match object at 0x011761A0>
##11 None
##12 <_sre.SRE_Match object at 0x011761A0>
##13 None
##14 <_sre.SRE_Match object at 0x011761A0>
##15 <_sre.SRE_Match object at 0x011761A0>
##16 <_sre.SRE_Match object at 0x011761A0>
##17 None
##18 <_sre.SRE_Match object at 0x011761A0>
##19 None



>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

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


Re: Combinatorics

2008-02-13 Thread Paul Hankin
On Feb 12, 7:52 am, Michael Robertson <[EMAIL PROTECTED]> wrote:
> Where is the python equivalent of:
>
> http://search.cpan.org/~fxn/Algorithm-Combinatorics-0.16/Combinatoric...
>
> combinations (with and without repetition)
> variations (with and without repetition)
> permutations
> partitions
> derangements
> etc
>
> I'm guessing sage has this, but shouldn't something like this be part of
> the standard library (perhaps in C)?  I'd understand if derangements and
> partitions were excluded, but the standard combinatorics (replacement
> on/off, repetition on/off) would be quite nice.  It would also be
> helpful to have a general cartesian product function which combined
> elements from an arbitrary number of lists.
>
> It seems that questions for these algorithms occur too frequently.

Here's a fairly efficient and short cartesian product:

def cart_lists(lists, upto, result):
if not upto:
yield result
else:
for _ in cart_lists(lists, upto - 1, result):
for a in lists[upto - 1]:
result[upto - 1] = a
yield result

def cartesian_product(*args):
"Generate the cartesian product of the sequences passed in."
for x in cart_lists(map(list, args), len(args), [None] *
len(args)):
yield tuple(x)

print list(cartesian_product('ab', 'cd', xrange(3)))

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


Re: Recursive generator

2008-02-13 Thread Ben C
On 2008-02-12, Paul Hankin <[EMAIL PROTECTED]> wrote:
> On Feb 12, 10:17 pm, Ben C <[EMAIL PROTECTED]> wrote:
>> On 2008-02-12, Paul Rubin <> wrote:
>>
>> > Paul Hankin <[EMAIL PROTECTED]> writes:
>> >> def genDescendants(self):
>> >>     return chain([self], *[child.genDescendants()
>> >>         for child in self.children])
>>
>> > That is scary.  It generates an in-memory list the size of the
>> > whole subtree, at every level.  Total memory consumption is maybe
>> > even quadratic, depending on the tree shape, but even if it's
>> > only linear, it's way ugly.
>>
>> This would probably be better (in terms of memory if not beauty):
>>
>>     def genDescendants(self):
>>         return chain([self], *(child.genDescendants()
>>             for child in self.children))
>
> No, it's the same I think.

Yes I think you're right. The problem is really the *. The generator
comprehension (child.genDescendants() ...) will have to be run to
completion to build the arguments to pass to chain. So no laziness
there.

> forgot that a generator using yield isn't the same as the same
> function that returns an equivalent generator, because one is lazy and
> the other isn't. To get the lazy behaviour back, you'd have to
> write
>
> def genDescendants(self):
> for g in chain([self], *(child.genDescendants()
> for child in self.children)):
> yield g

Is that lazy? It still seems like (child.genDescendants() ...) would
have to be run all the way to the end before chain could be called.

Unless * is lazy. I don't think it is, but I don't know for sure.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No Module Named pstats

2008-02-13 Thread Joshua Kugler
Chris wrote:

> On Feb 13, 11:20 am, "Juha S." <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I'm trying to use the Python profilers to test my code, but I get the
>> following output for cProfile.run() at the interpreter:
>>
>> Traceback (most recent call last):
>>   File "", line 1, in 
>>   File "/usr/lib/python2.5/cProfile.py", line 36, in run
>> result = prof.print_stats(sort)
>>   File "/usr/lib/python2.5/cProfile.py", line 80, in print_stats
>> import pstats
>> ImportError: No module named pstats
>>
>> I also tried to use the profile module but I get:
>>
>>  >>> import profile
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> ImportError: No module named profile
>>
>> I'm on Ubuntu 7.10 with Python 2.5, and I can't seem to figure out
>> what's missing.
> 
> There is no module called 'profile', it's called 'cProfile'.  Both
> 'cProfile' and 'pstats' are part of the standard distro, have you
> tried downloading a new binary and installing it ?

There is a module called profile, as well as cProfile.  And as Ilias said,
you probably do have to install python-profile (or whatever package your
system places the profiler in).

j


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


Re: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread subeen
hmm... interesting

here is another way you can find prime numbers
http://love-python.blogspot.com/2008/02/find-prime-number-upto-100-nums-range2.html



On Feb 13, 9:31 pm, [EMAIL PROTECTED] wrote:
> I was reading up on this site [http://www.noulakaz.net/weblog/
> 2007/03/18/a-regular-expression-to-check-for-prime-numbers/] of an
> interesting way to work out prime numbers using Regular Expression.
>
> However my attempts to use this in Python keep returning none
> (obviously no match), however I don't see why, I was under the
> impression Python used the same RE system as Perl/Ruby and I know the
> convert is producing the correct display of 1's...Any thoughts?
>
> def re_prime(n):
> import re
> convert = "".join("1" for i in xrange(n))
> return re.match("^1?$|^(11+?)\1+$", convert)
>
> print re_prime(2)
>
> Also on a side note the quickest method I have come across as yet is
> the following
>
> def prime_numbers(n):
> if n < 3: return [2] if n == 2 else []
> nroot = int(n ** 0.5) + 1
> sieve = range(n + 1)
> sieve[1] = 0
> for i in xrange(2, nroot):
> if sieve[i]:
> sieve[i * i: n + 1: i] = [0] * ((n / i - i) + 1)
> return [x for x in sieve if x]
>
> Damn clever whoever built this (note sieve will produce a list the
> size of your 'n' which is unfortunate)

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


Re: Big time WTF with generators - bug?

2008-02-13 Thread James Stroud
Steve Holden wrote:
> James Stroud wrote:
>> [...] I then append the growing list of series generator
>> into the "serieses" list ("serieses" is plural for series if your 
>> vocablulary isn't that big).
>>
> Not as big as your ego, apparently ;-) And don't be coming back with any 
> argumentses.

Where is this coming from? Please see posts by Otten and Rubin for 
proper human conduct.

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

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


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread Grant Edwards
On 2008-02-13, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
>> On 2008-02-13, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>> 
 Eh? Last I checked both pound and kilogram are units of mass, so where is
 the incompatibility?
>>> I've never heard of "pound" as a unit of mass.  At least where I went to 
>>> school (Boston, MA), "pound" is the English unit of force, "slug" is the 
>>> (rarely used) English unit of mass,
>> 
>> Back in the day, I was once working on a fire control system
>> for the Navy.  All the units in the calculations were purely
>> metric except for one: air density was in slugs/m3.  I always
>> suspected that was somebody's attempt at humor.
>
> So what is the mass of a slug, anyway?  (I assume this is slug as in 
> bullet, not slimy, creeping thing.)

A slug is 14.593903 kg according to the trysty old Unix "units"
program.  Hmm, I always thought a slug weighed exactly 32 lbs,
but I see it's 32.174049.  Learn something new every day...

-- 
Grant Edwards   grante Yow!  I feel better about
  at   world problems now!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fromfunc functions

2008-02-13 Thread azrael
Thaks guys. this helped
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ways to declare empty set variable

2008-02-13 Thread Nick Craig-Wood
Ben Finney <[EMAIL PROTECTED]> wrote:
>  [EMAIL PROTECTED] writes:
> 
> > Missing that, I think dict() and set() and tuple() and list()
> 
>  I often use these myself. They're slightly more explicit, which can
>  help when I want the reader not to have to think too much, and they're
>  not particularly verbose because the names are well-chosen and
>  short.

You can also do this with the dict() syntax

dict(a = 1, b = 2, c = 3)

which I find a lot more readable than

{ 'a' : 1, 'b' : 2, 'c' : 3 }

In a lot of circumstances.

The syntax isn't so great when you set things which aren't valid
keywords though...

eg

{ (1,2,3) : 'a', (4,5,6) : 'b' }

vs

dict([ ((1,2,3), 'a'), ((4,5,6), 'b') ])

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread Jeroen Ruigrok van der Werven
-On [20080213 20:16], Jeff Schwab ([EMAIL PROTECTED]) wrote:
>So what is the mass of a slug, anyway?  (I assume this is slug as in 
>bullet, not slimy, creeping thing.)

http://en.wikipedia.org/wiki/Slug_(mass) would be my guess.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
Cum angelis et pueris, fideles inveniamur. Quis est iste Rex gloriae..?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread Jeroen Ruigrok van der Werven
-On [20080213 18:46], Jeff Schwab ([EMAIL PROTECTED]) wrote:
>I've never heard of "pound" as a unit of mass.

Then please correct/fix:

http://en.wikipedia.org/wiki/Pound_(mass)

Me being mainland European I know not this silly system called imperial.

[Yes, partially in good jest...]

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
Sometimes I wonder why are we so blind to face...
-- 
http://mail.python.org/mailman/listinfo/python-list

Truncated postings

2008-02-13 Thread lloyd
Hello,

Over the past 24 hours or so, all of my Python-List e-mails have been truncated 
to subject list only. No posts. 

Are others experiencing this problem? Or is it just on my end?

Thanks,

Lloyd R. Prentice


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


Re: Big time WTF with generators - bug?

2008-02-13 Thread bearophileHUGS
Paul Rubin:
> Even with that though, at least for me, Python starts feeling really
> scary when the iterators get this complicated.  I start wishing for
> a static type system, re-usable iterators, etc.

This is an interesting topic. I agree with you, I too was scared in a
similar situation. The language features allow you to do some things
in a simple way, but if you pile too much of them, you end losing
track of what you are doing, etc.
The D language has static typing and its classes allow a standard
opApply method that allows lazy iteration, they are re-usable
iterators (but to scan two iterators in parallel you need a big trick,
it's a matter of stack). They require more syntax, and it gets in the
way, so in the end I am more able to write recursive generators in
Python because its less cluttered syntax allows my brain to manage
that extra part of algorithmic complexity necessary for that kind of
convoluted code.
The Haskall language is often uses by very intelligent programmers, it
often allows to use lazy computations and iterations, but it has the
advantage that its iterators behave better, and during the generation
of some items you can, when you want, refer and use the items already
generated. Those things make lazy Python code very different from lazy
Haskell code.

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


  1   2   >